summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: 9f4f526725ba3fc3fa9ca72568b6f7b935f1f306 (plain)
  1. #=====================================================================
  2. # LedgerSMB
  3. # Small Medium Business Accounting software
  4. #
  5. # Copyright (C) 2006
  6. # This work contains copyrighted information from a number of sources all used
  7. # with permission.
  8. #
  9. # This file contains source code included with or based on SQL-Ledger which
  10. # is Copyright Dieter Simader and DWS Systems Inc. 2000-2005 and licensed
  11. # under the GNU General Public License version 2 or, at your option, any later
  12. # version. For a full list including contact information of contributors,
  13. # maintainers, and copyright holders, see the CONTRIBUTORS file.
  14. #
  15. # Original Copyright Notice from SQL-Ledger 2.6.17 (before the fork):
  16. # Copyright (C) 2000
  17. #
  18. # Author: DWS Systems Inc.
  19. # Web: http://www.sql-ledger.org
  20. #
  21. # Contributors: Thomas Bayen <bayen@gmx.de>
  22. # Antti Kaihola <akaihola@siba.fi>
  23. # Moritz Bunkus (tex)
  24. # Jim Rawlings <jim@your-dba.com> (DB2)
  25. #======================================================================
  26. #
  27. # This file has undergone whitespace cleanup.
  28. #
  29. #======================================================================
  30. #
  31. # main package
  32. #
  33. #======================================================================
  34. package Form;
  35. sub new {
  36. my $type = shift;
  37. my $self = {};
  38. read(STDIN, $_, $ENV{CONTENT_LENGTH});
  39. if ($ENV{QUERY_STRING}) {
  40. $_ = $ENV{QUERY_STRING};
  41. }
  42. if ($ARGV[0]) {
  43. $_ = $ARGV[0];
  44. }
  45. %$self = split /[&=]/;
  46. for (keys %$self) { $self->{$_} = unescape("", $self->{$_}) }
  47. if (substr($self->{action}, 0, 1) !~ /( |\.)/) {
  48. $self->{action} = lc $self->{action};
  49. $self->{action} =~ s/( |-|,|\#|\/|\.$)/_/g;
  50. }
  51. $self->{menubar} = 1 if $self->{path} =~ /lynx/i;
  52. $self->{version} = "1.0.0";
  53. $self->{dbversion} = "2.6.17";
  54. bless $self, $type;
  55. }
  56. sub debug {
  57. my ($self, $file) = @_;
  58. if ($file) {
  59. open(FH, "> $file") or die $!;
  60. for (sort keys %$self) { print FH "$_ = $self->{$_}\n" }
  61. close(FH);
  62. } else {
  63. print "\n";
  64. for (sort keys %$self) { print "$_ = $self->{$_}\n" }
  65. }
  66. }
  67. sub escape {
  68. my ($self, $str, $beenthere) = @_;
  69. # for Apache 2 we escape strings twice
  70. if (($ENV{SERVER_SIGNATURE} =~ /Apache\/2\.(\d+)\.(\d+)/) && !$beenthere) {
  71. $str = $self->escape($str, 1) if $1 == 0 && $2 < 44;
  72. }
  73. $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
  74. $str;
  75. }
  76. sub unescape {
  77. my ($self, $str) = @_;
  78. $str =~ tr/+/ /;
  79. $str =~ s/\\$//;
  80. $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
  81. $str =~ s/\r?\n/\n/g;
  82. $str;
  83. }
  84. sub quote {
  85. my ($self, $str) = @_;
  86. if ($str && ! ref($str)) {
  87. $str =~ s/"/&quot;/g;
  88. }
  89. $str;
  90. }
  91. sub unquote {
  92. my ($self, $str) = @_;
  93. if ($str && ! ref($str)) {
  94. $str =~ s/&quot;/"/g;
  95. }
  96. $str;
  97. }
  98. sub hide_form {
  99. my $self = shift;
  100. if (@_) {
  101. for (@_) {
  102. print qq|<input type="hidden" name="$_" value="|.$self->quote($self->{$_}).qq|" />\n|
  103. }
  104. } else {
  105. delete $self->{header};
  106. for (sort keys %$self) {
  107. print qq|<input type="hidden" name="$_" value="|.$self->quote($self->{$_}).qq|" />\n|
  108. }
  109. }
  110. }
  111. sub error {
  112. my ($self, $msg) = @_;
  113. if ($ENV{HTTP_USER_AGENT}) {
  114. $self->{msg} = $msg;
  115. $self->{format} = "html";
  116. $self->format_string(msg);
  117. delete $self->{pre};
  118. if (!$self->{header}) {
  119. $self->header;
  120. }
  121. print qq|<body><h2 class="error">Error!</h2> <p><b>$self->{msg}</b></body>|;
  122. exit;
  123. } else {
  124. if ($self->{error_function}) {
  125. &{ $self->{error_function} }($msg);
  126. } else {
  127. die "Error: $msg\n";
  128. }
  129. }
  130. }
  131. sub info {
  132. my ($self, $msg) = @_;
  133. if ($ENV{HTTP_USER_AGENT}) {
  134. $msg =~ s/\n/<br>/g;
  135. delete $self->{pre};
  136. if (!$self->{header}) {
  137. $self->header;
  138. print qq| <body>|;
  139. $self->{header} = 1;
  140. }
  141. print "<b>$msg</b>";
  142. } else {
  143. if ($self->{info_function}) {
  144. &{ $self->{info_function} }($msg);
  145. } else {
  146. print "$msg\n";
  147. }
  148. }
  149. }
  150. sub numtextrows {
  151. my ($self, $str, $cols, $maxrows) = @_;
  152. my $rows = 0;
  153. for (split /\n/, $str) {
  154. $rows += int (((length) - 2)/$cols) + 1
  155. }
  156. $maxrows = $rows unless defined $maxrows;
  157. return ($rows > $maxrows) ? $maxrows : $rows;
  158. }
  159. sub dberror {
  160. my ($self, $msg) = @_;
  161. $self->error("$msg\n".$DBI::errstr);
  162. }
  163. sub isblank {
  164. my ($self, $name, $msg) = @_;
  165. $self->error($msg) if $self->{$name} =~ /^\s*$/;
  166. }
  167. sub header {
  168. my ($self, $init, $headeradd) = @_;
  169. return if $self->{header};
  170. my ($stylesheet, $favicon, $charset);
  171. if ($ENV{HTTP_USER_AGENT}) {
  172. if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
  173. $stylesheet = qq|<link rel="stylesheet" href="css/$self->{stylesheet}" type="text/css" title="LedgerSMB stylesheet" />\n|;
  174. }
  175. if ($self->{charset}) {
  176. $charset = qq|<meta http-equiv="content-type" content="text/html; charset=$self->{charset}" />\n|;
  177. }
  178. $self->{titlebar} = ($self->{title}) ? "$self->{title} - $self->{titlebar}" : $self->{titlebar};
  179. $self->set_cookie($init);
  180. print qq|Content-Type: text/html\n\n
  181. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  182. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  183. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  184. <head>
  185. <title>$self->{titlebar}</title>
  186. <meta http-equiv="Pragma" content="no-cache" />
  187. <meta http-equiv="Expires" content="-1" />
  188. <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  189. $stylesheet
  190. $charset
  191. <meta name="robots" content="noindex,nofollow" />
  192. $headeradd
  193. </head>
  194. $self->{pre} \n|;
  195. }
  196. $self->{header} = 1;
  197. }
  198. sub set_cookie {
  199. my ($self, $init) = @_;
  200. $self->{timeout} = ($self->{timeout} > 0) ? $self->{timeout} : 3600;
  201. my $t = ($self->{endsession}) ? time : time + $self->{timeout};
  202. if ($ENV{HTTP_USER_AGENT}) {
  203. my @d = split / +/, scalar gmtime($t);
  204. my $today = "$d[0], $d[2]-$d[1]-$d[4] $d[3] GMT";
  205. if ($init) {
  206. $self->{sessionid} = time;
  207. }
  208. print qq|Set-Cookie: LedgerSMB-$self->{login}=$self->{sessionid}; expires=$today; path=/;\n| if $self->{login};
  209. }
  210. }
  211. sub redirect {
  212. my ($self, $msg) = @_;
  213. if ($self->{callback}) {
  214. my ($script, $argv) = split(/\?/, $self->{callback});
  215. exec ("perl", $script, $argv);
  216. } else {
  217. $self->info($msg);
  218. }
  219. }
  220. sub sort_columns {
  221. my ($self, @columns) = @_;
  222. if ($self->{sort}) {
  223. if (@columns) {
  224. @columns = grep !/^$self->{sort}$/, @columns;
  225. splice @columns, 0, 0, $self->{sort};
  226. }
  227. }
  228. @columns;
  229. }
  230. sub sort_order {
  231. my ($self, $columns, $ordinal) = @_;
  232. # setup direction
  233. if ($self->{direction}) {
  234. if ($self->{sort} eq $self->{oldsort}) {
  235. if ($self->{direction} eq 'ASC') {
  236. $self->{direction} = "DESC";
  237. } else {
  238. $self->{direction} = "ASC";
  239. }
  240. }
  241. } else {
  242. $self->{direction} = "ASC";
  243. }
  244. $self->{oldsort} = $self->{sort};
  245. my @a = $self->sort_columns(@{$columns});
  246. if (%$ordinal) {
  247. $a[0] = ($ordinal->{$a[$_]}) ? "$ordinal->{$a[0]} $self->{direction}" : "$a[0] $self->{direction}";
  248. for (1 .. $#a) {
  249. $a[$_] = $ordinal->{$a[$_]} if $ordinal->{$a[$_]}
  250. }
  251. } else {
  252. $a[0] .= " $self->{direction}";
  253. }
  254. $sortorder = join ',', @a;
  255. $sortorder;
  256. }
  257. sub format_amount {
  258. my ($self, $myconfig, $amount, $places, $dash) = @_;
  259. if ($places =~ /\d+/) {
  260. #$places = 4 if $places == 2;
  261. $amount = $self->round_amount($amount, $places);
  262. }
  263. # is the amount negative
  264. my $negative = ($amount < 0);
  265. if ($amount) {
  266. if ($myconfig->{numberformat}) {
  267. my ($whole, $dec) = split /\./, "$amount";
  268. $whole =~ s/-//;
  269. $amount = join '', reverse split //, $whole;
  270. if ($places) {
  271. $dec .= "0" x $places;
  272. $dec = substr($dec, 0, $places);
  273. }
  274. if ($myconfig->{numberformat} eq '1,000.00') {
  275. $amount =~ s/\d{3,}?/$&,/g;
  276. $amount =~ s/,$//;
  277. $amount = join '', reverse split //, $amount;
  278. $amount .= "\.$dec" if ($dec ne "");
  279. }
  280. if ($myconfig->{numberformat} eq "1'000.00") {
  281. $amount =~ s/\d{3,}?/$&'/g;
  282. $amount =~ s/'$//;
  283. $amount = join '', reverse split //, $amount;
  284. $amount .= "\.$dec" if ($dec ne "");
  285. }
  286. if ($myconfig->{numberformat} eq '1.000,00') {
  287. $amount =~ s/\d{3,}?/$&./g;
  288. $amount =~ s/\.$//;
  289. $amount = join '', reverse split //, $amount;
  290. $amount .= ",$dec" if ($dec ne "");
  291. }
  292. if ($myconfig->{numberformat} eq '1000,00') {
  293. $amount = "$whole";
  294. $amount .= ",$dec" if ($dec ne "");
  295. }
  296. if ($myconfig->{numberformat} eq '1000.00') {
  297. $amount = "$whole";
  298. $amount .= ".$dec" if ($dec ne "");
  299. }
  300. if ($dash =~ /-/) {
  301. $amount = ($negative) ? "($amount)" : "$amount";
  302. } elsif ($dash =~ /DRCR/) {
  303. $amount = ($negative) ? "$amount DR" : "$amount CR";
  304. } else {
  305. $amount = ($negative) ? "-$amount" : "$amount";
  306. }
  307. }
  308. } else {
  309. if ($dash eq "0" && $places) {
  310. if ($myconfig->{numberformat} eq '1.000,00') {
  311. $amount = "0".","."0" x $places;
  312. } else {
  313. $amount = "0"."."."0" x $places;
  314. }
  315. } else {
  316. $amount = ($dash ne "") ? "$dash" : "";
  317. }
  318. }
  319. $amount;
  320. }
  321. sub parse_amount {
  322. my ($self, $myconfig, $amount) = @_;
  323. if (($myconfig->{numberformat} eq '1.000,00') ||
  324. ($myconfig->{numberformat} eq '1000,00')) {
  325. $amount =~ s/\.//g;
  326. $amount =~ s/,/\./;
  327. }
  328. if ($myconfig->{numberformat} eq "1'000.00") {
  329. $amount =~ s/'//g;
  330. }
  331. $amount =~ s/,//g;
  332. return ($amount * 1);
  333. }
  334. sub round_amount {
  335. my ($self, $amount, $places) = @_;
  336. # $places = 4 if $places == 2;
  337. my ($null, $dec) = split /\./, $amount;
  338. $dec = length $dec;
  339. $dec = ($dec > $places) ? $dec : $places;
  340. my $adj = ($amount < 0) ? (1/10**($dec+2)) * -1 : (1/10**($dec+2));
  341. if (($places * 1) >= 0) {
  342. $amount = sprintf("%.${places}f", $amount + $adj) * 1;
  343. } else {
  344. $places *= -1;
  345. $amount = sprintf("%.0f", $amount);
  346. $amount = sprintf("%.f", $amount / (10 ** $places)) * (10 ** $places);
  347. }
  348. $amount;
  349. }
  350. sub parse_template {
  351. my ($self, $myconfig, $userspath) = @_;
  352. my ($chars_per_line, $lines_on_first_page, $lines_on_second_page) = (0, 0, 0);
  353. my ($current_page, $current_line) = (1, 1);
  354. my $pagebreak = "";
  355. my $sum = 0;
  356. my $subdir = "";
  357. my $err = "";
  358. my %include = ();
  359. my $ok;
  360. if ($self->{language_code}) {
  361. if (-f "$self->{templates}/$self->{language_code}/$self->{IN}") {
  362. open(IN, "$self->{templates}/$self->{language_code}/$self->{IN}") or $self->error("$self->{IN} : $!");
  363. } else {
  364. open(IN, "$self->{templates}/$self->{IN}") or $self->error("$self->{IN} : $!");
  365. }
  366. } else {
  367. open(IN, "$self->{templates}/$self->{IN}") or $self->error("$self->{IN} : $!");
  368. }
  369. @_ = <IN>;
  370. close(IN);
  371. $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
  372. # OUT is used for the media, screen, printer, email
  373. # for postscript we store a copy in a temporary file
  374. my $fileid = time;
  375. my $tmpfile = $self->{IN};
  376. $tmpfile =~ s/\./_$self->{fileid}./ if $self->{fileid};
  377. $self->{tmpfile} = "$userspath/${fileid}_${tmpfile}";
  378. if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
  379. $out = $self->{OUT};
  380. $self->{OUT} = ">$self->{tmpfile}";
  381. }
  382. if ($self->{OUT}) {
  383. open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
  384. } else {
  385. open(OUT, ">-") or $self->error("STDOUT : $!");
  386. $self->header;
  387. }
  388. # first we generate a tmpfile
  389. # read file and replace <%variable%>
  390. while ($_ = shift) {
  391. $par = "";
  392. $var = $_;
  393. # detect pagebreak block and its parameters
  394. if (/<%pagebreak ([0-9]+) ([0-9]+) ([0-9]+)%>/) {
  395. $chars_per_line = $1;
  396. $lines_on_first_page = $2;
  397. $lines_on_second_page = $3;
  398. while ($_ = shift) {
  399. last if (/<%end pagebreak%>/);
  400. $pagebreak .= $_;
  401. }
  402. }
  403. if (/<%foreach /) {
  404. # this one we need for the count
  405. chomp $var;
  406. $var =~ s/.*?<%foreach (.+?)%>/$1/;
  407. while ($_ = shift) {
  408. last if (/<%end $var%>/);
  409. # store line in $par
  410. $par .= $_;
  411. }
  412. # display contents of $self->{number}[] array
  413. for $i (0 .. $#{ $self->{$var} }) {
  414. if ($var =~ /^(part|service)$/) {
  415. next if $self->{$var}[$i] eq 'NULL';
  416. }
  417. # Try to detect whether a manual page break is necessary
  418. # but only if there was a <%pagebreak ...%> block before
  419. if ($var eq 'number' || $var eq 'part' || $var eq 'service') {
  420. if ($chars_per_line && defined $self->{$var}) {
  421. my $line;
  422. my $lines = 0;
  423. my @d = (description);
  424. push @d, "itemnotes" if $self->{countitemnotes};
  425. foreach my $item (@d) {
  426. if ($self->{$item}[$i]) {
  427. foreach $line (split /\r?\n/, $self->{$item}[$i]) {
  428. $lines++;
  429. $lines += int(length($line) / $chars_per_line);
  430. }
  431. }
  432. }
  433. my $lpp;
  434. if ($current_page == 1) {
  435. $lpp = $lines_on_first_page;
  436. } else {
  437. $lpp = $lines_on_second_page;
  438. }
  439. # Yes we need a manual page break
  440. if (($current_line + $lines) > $lpp) {
  441. my $pb = $pagebreak;
  442. # replace the special variables <%sumcarriedforward%>
  443. # and <%lastpage%>
  444. my $psum = $self->format_amount($myconfig, $sum, 2);
  445. $pb =~ s/<%sumcarriedforward%>/$psum/g;
  446. $pb =~ s/<%lastpage%>/$current_page/g;
  447. # only "normal" variables are supported here
  448. # (no <%if, no <%foreach, no <%include)
  449. $pb =~ s/<%(.+?)%>/$self->{$1}/g;
  450. # page break block is ready to rock
  451. print(OUT $pb);
  452. $current_page++;
  453. $current_line = 1;
  454. $lines = 0;
  455. }
  456. $current_line += $lines;
  457. }
  458. $sum += $self->parse_amount($myconfig, $self->{linetotal}[$i]);
  459. }
  460. # don't parse par, we need it for each line
  461. print OUT $self->format_line($par, $i);
  462. }
  463. next;
  464. }
  465. # if not comes before if!
  466. if (/<%if not /) {
  467. # check if it is not set and display
  468. chop;
  469. s/.*?<%if not (.+?)%>/$1/;
  470. if (! $self->{$_}) {
  471. while ($_ = shift) {
  472. last if (/<%end /);
  473. # store line in $par
  474. $par .= $_;
  475. }
  476. $_ = $par;
  477. } else {
  478. while ($_ = shift) {
  479. last if (/<%end /);
  480. }
  481. next;
  482. }
  483. }
  484. if (/<%if /) {
  485. # check if it is set and display
  486. chop;
  487. s/.*?<%if (.+?)%>/$1/;
  488. if (/\s/) {
  489. @a = split;
  490. $ok = eval "$self->{$a[0]} $a[1] $a[2]";
  491. } else {
  492. $ok = $self->{$_};
  493. }
  494. if ($ok) {
  495. while ($_ = shift) {
  496. last if (/<%end /);
  497. # store line in $par
  498. $par .= $_;
  499. }
  500. $_ = $par;
  501. } else {
  502. while ($_ = shift) {
  503. last if (/<%end /);
  504. }
  505. next;
  506. }
  507. }
  508. # check for <%include filename%>
  509. if (/<%include /) {
  510. # get the filename
  511. chomp $var;
  512. $var =~ s/.*?<%include (.+?)%>/$1/;
  513. # remove / .. for security reasons
  514. $var =~ s/(\/|\.\.)//g;
  515. # assume loop after 10 includes of the same file
  516. next if ($include{$var} > 10);
  517. unless (open(INC, "$self->{templates}/$self->{language_code}/$var")) {
  518. $err = $!;
  519. $self->cleanup;
  520. $self->error("$self->{templates}/$self->{language_code}/$var : $err");
  521. }
  522. unshift(@_, <INC>);
  523. close(INC);
  524. $include{$var}++;
  525. next;
  526. }
  527. print OUT $self->format_line($_);
  528. }
  529. close(OUT);
  530. delete $self->{countitemnotes};
  531. # Convert the tex file to postscript
  532. if ($self->{format} =~ /(postscript|pdf)/) {
  533. use Cwd;
  534. $self->{cwd} = cwd();
  535. $self->{tmpdir} = "$self->{cwd}/$userspath";
  536. unless (chdir("$userspath")) {
  537. $err = $!;
  538. $self->cleanup;
  539. $self->error("chdir : $err");
  540. }
  541. $self->{tmpfile} =~ s/$userspath\///g;
  542. $self->{errfile} = $self->{tmpfile};
  543. $self->{errfile} =~ s/tex$/err/;
  544. my $r = 1;
  545. if ($self->{format} eq 'postscript') {
  546. system("latex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  547. while ($self->rerun_latex) {
  548. system("latex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  549. last if ++$r > 4;
  550. }
  551. $self->{tmpfile} =~ s/tex$/dvi/;
  552. $self->error($self->cleanup) if ! (-f $self->{tmpfile});
  553. system("dvips $self->{tmpfile} -o -q");
  554. $self->error($self->cleanup."dvips : $!") if ($?);
  555. $self->{tmpfile} =~ s/dvi$/ps/;
  556. }
  557. if ($self->{format} eq 'pdf') {
  558. system("pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  559. while ($self->rerun_latex) {
  560. system("pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  561. last if ++$r > 4;
  562. }
  563. $self->{tmpfile} =~ s/tex$/pdf/;
  564. $self->error($self->cleanup) if ! (-f $self->{tmpfile});
  565. }
  566. }
  567. if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
  568. if ($self->{media} eq 'email') {
  569. use LedgerSMB::Mailer;
  570. my $mail = new Mailer;
  571. for (qw(cc bcc subject message version format charset)) {
  572. $mail->{$_} = $self->{$_}
  573. }
  574. $mail->{to} = qq|$self->{email}|;
  575. $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
  576. $mail->{fileid} = "$fileid.";
  577. # if we send html or plain text inline
  578. if (($self->{format} =~ /(html|txt)/) &&
  579. ($self->{sendmode} eq 'inline')) {
  580. my $br = "";
  581. $br = "<br>" if $self->{format} eq 'html';
  582. $mail->{contenttype} = "text/$self->{format}";
  583. $mail->{message} =~ s/\r?\n/$br\n/g;
  584. $myconfig->{signature} =~ s/\\n/$br\n/g;
  585. $mail->{message} .= "$br\n-- $br\n$myconfig->{signature}\n$br" if $myconfig->{signature};
  586. unless (open(IN, $self->{tmpfile})) {
  587. $err = $!;
  588. $self->cleanup;
  589. $self->error("$self->{tmpfile} : $err");
  590. }
  591. while (<IN>) {
  592. $mail->{message} .= $_;
  593. }
  594. close(IN);
  595. } else {
  596. @{ $mail->{attachments} } = ($self->{tmpfile});
  597. $myconfig->{signature} =~ s/\\n/\n/g;
  598. $mail->{message} .= "\n-- \n$myconfig->{signature}" if $myconfig->{signature};
  599. }
  600. if ($err = $mail->send($out)) {
  601. $self->cleanup;
  602. $self->error($err);
  603. }
  604. } else {
  605. $self->{OUT} = $out;
  606. unless (open(IN, $self->{tmpfile})) {
  607. $err = $!;
  608. $self->cleanup;
  609. $self->error("$self->{tmpfile} : $err");
  610. }
  611. binmode(IN);
  612. $self->{copies} = 1 if $self->{media} =~ /(screen|email|queue)/;
  613. chdir("$self->{cwd}");
  614. for my $i (1 .. $self->{copies}) {
  615. if ($self->{OUT}) {
  616. unless (open(OUT, $self->{OUT})) {
  617. $err = $!;
  618. $self->cleanup;
  619. $self->error("$self->{OUT} : $err");
  620. }
  621. } else {
  622. # launch application
  623. print qq|Content-Type: application/$self->{format}
  624. Content-Disposition: attachment; filename="$self->{tmpfile}"\n\n|;
  625. unless (open(OUT, ">-")) {
  626. $err = $!;
  627. $self->cleanup;
  628. $self->error("STDOUT : $err");
  629. }
  630. }
  631. binmode(OUT);
  632. while (<IN>) {
  633. print OUT $_;
  634. }
  635. close(OUT);
  636. seek IN, 0, 0;
  637. }
  638. close(IN);
  639. }
  640. $self->cleanup;
  641. }
  642. }
  643. sub format_line {
  644. my $self = shift;
  645. $_ = shift;
  646. my $i = shift;
  647. my $str;
  648. my $newstr;
  649. my $pos;
  650. my $l;
  651. my $lf;
  652. my $line;
  653. my $var = "";
  654. my %a;
  655. my $offset;
  656. my $pad;
  657. my $item;
  658. while (/<%(.+?)%>/) {
  659. %a = ();
  660. foreach $item (split / /, $1) {
  661. my ($key, $value) = split /=/, $item;
  662. if ($value ne "") {
  663. $a{$key} = $value;
  664. } else {
  665. $var = $item;
  666. }
  667. }
  668. $str = (defined $i) ? $self->{$var}[$i] : $self->{$var};
  669. $newstr = $str;
  670. $self->{countitemnotes} = 1 if $var eq 'itemnotes';
  671. $var = $1;
  672. if ($var =~ /^if\s+not\s+/) {
  673. if ($str) {
  674. $var =~ s/if\s+not\s+//;
  675. s/<%if\s+not\s+$var%>.*?(<%end\s+$var%>|$)//s;
  676. } else {
  677. s/<%$var%>//;
  678. }
  679. next;
  680. }
  681. if ($var =~ /^if\s+/) {
  682. if ($str) {
  683. s/<%$var%>//;
  684. } else {
  685. $var =~ s/if\s+//;
  686. s/<%if\s+$var%>.*?(<%end\s+$var%>|$)//s;
  687. }
  688. next;
  689. }
  690. if ($var =~ /^end\s+/) {
  691. s/<%$var%>//;
  692. next;
  693. }
  694. if ($a{align} || $a{width} || $a{offset}) {
  695. $newstr = "";
  696. $offset = 0;
  697. $lf = "";
  698. foreach $str (split /\n/, $str) {
  699. $line = $str;
  700. $l = length $str;
  701. do {
  702. if (($pos = length $str) > $a{width}) {
  703. if (($pos = rindex $str, " ", $a{width}) > 0) {
  704. $line = substr($str, 0, $pos);
  705. }
  706. $pos = length $str if $pos == -1;
  707. }
  708. $l = length $line;
  709. # pad left, right or center
  710. $l = ($a{width} - $l);
  711. $pad = " " x $l;
  712. if ($a{align} =~ /right/i) {
  713. $line = " " x $offset . $pad . $line;
  714. }
  715. if ($a{align} =~ /left/i) {
  716. $line = " " x $offset . $line . $pad;
  717. }
  718. if ($a{align} =~ /center/i) {
  719. $pad = " " x ($l/2);
  720. $line = " " x $offset . $pad . $line;
  721. $pad = " " x ($l/2);
  722. $line .= $pad;
  723. }
  724. $newstr .= "$lf$line";
  725. $str = substr($str, $pos + 1);
  726. $line = $str;
  727. $lf = "\n";
  728. $offset = $a{offset};
  729. } while ($str);
  730. }
  731. }
  732. s/<%(.+?)%>/$newstr/;
  733. }
  734. $_;
  735. }
  736. sub cleanup {
  737. my $self = shift;
  738. chdir("$self->{tmpdir}");
  739. my @err = ();
  740. if (-f "$self->{errfile}") {
  741. open(FH, "$self->{errfile}");
  742. @err = <FH>;
  743. close(FH);
  744. }
  745. if ($self->{tmpfile}) {
  746. # strip extension
  747. $self->{tmpfile} =~ s/\.\w+$//g;
  748. my $tmpfile = $self->{tmpfile};
  749. unlink(<$tmpfile.*>);
  750. }
  751. chdir("$self->{cwd}");
  752. "@err";
  753. }
  754. sub rerun_latex {
  755. my $self = shift;
  756. my $a = 0;
  757. if (-f "$self->{errfile}") {
  758. open(FH, "$self->{errfile}");
  759. $a = grep /(longtable Warning:|Warning:.*?LastPage)/, <FH>;
  760. close(FH);
  761. }
  762. $a;
  763. }
  764. sub format_string {
  765. my ($self, @fields) = @_;
  766. my $format = $self->{format};
  767. if ($self->{format} =~ /(postscript|pdf)/) {
  768. $format = 'tex';
  769. }
  770. my %replace = (
  771. 'order' => {
  772. html => [ '<', '>', '\n', '\r' ],
  773. txt => [ '\n', '\r' ],
  774. tex => [ quotemeta('\\'), '&', '\n','\r',
  775. '\$', '%', '_', '#',
  776. quotemeta('^'), '{', '}', '<', '>', '£'
  777. ],
  778. utf => [ quotemeta('\\'), '&', quotemeta('\n'),
  779. '\r', '\$', '%', '_', '#', quotemeta('^'),
  780. '{', '}', '<', '>' ] },
  781. html => { '<' => '&lt;', '>' => '&gt;','\n' => '<br />',
  782. '\r' => '<br />' },
  783. txt => { '\n' => "\n", '\r' => "\r" },
  784. tex => {'&' => '\&', '\$' => '\$', '%' => '\%', '_' => '\_',
  785. '#' => '\#', quotemeta('^') => '\^\\', '{' => '\{',
  786. '}' => '\}', '<' => '$<$', '>' => '$>$',
  787. '\n' => '\newline ', '\r' => '\newline ',
  788. '£' => '\pounds ', quotemeta('\\') => '/'}
  789. );
  790. my $key;
  791. foreach $key (@{ $replace{order}{$format} }) {
  792. for (@fields) { $self->{$_} =~ s/$key/$replace{$format}{$key}/g }
  793. }
  794. }
  795. sub datetonum {
  796. my ($self, $myconfig, $date, $picture) = @_;
  797. if ($date && $date =~ /\D/) {
  798. if ($myconfig->{dateformat} =~ /^yy/) {
  799. ($yy, $mm, $dd) = split /\D/, $date;
  800. }
  801. if ($myconfig->{dateformat} =~ /^mm/) {
  802. ($mm, $dd, $yy) = split /\D/, $date;
  803. }
  804. if ($myconfig->{dateformat} =~ /^dd/) {
  805. ($dd, $mm, $yy) = split /\D/, $date;
  806. }
  807. $dd *= 1;
  808. $mm *= 1;
  809. $yy += 2000 if length $yy == 2;
  810. $dd = substr("0$dd", -2);
  811. $mm = substr("0$mm", -2);
  812. $date = "$yy$mm$dd";
  813. }
  814. $date;
  815. }
  816. sub add_date {
  817. my ($self, $myconfig, $date, $repeat, $unit) = @_;
  818. use Time::Local;
  819. my $diff = 0;
  820. my $spc = $myconfig->{dateformat};
  821. $spc =~ s/\w//g;
  822. $spc = substr($spc, 0, 1);
  823. if ($date) {
  824. if ($date =~ /\D/) {
  825. if ($myconfig->{dateformat} =~ /^yy/) {
  826. ($yy, $mm, $dd) = split /\D/, $date;
  827. }
  828. if ($myconfig->{dateformat} =~ /^mm/) {
  829. ($mm, $dd, $yy) = split /\D/, $date;
  830. }
  831. if ($myconfig->{dateformat} =~ /^dd/) {
  832. ($dd, $mm, $yy) = split /\D/, $date;
  833. }
  834. } else {
  835. # ISO
  836. ($yy, $mm, $dd) =~ /(....)(..)(..)/;
  837. }
  838. if ($unit eq 'days') {
  839. $diff = $repeat * 86400;
  840. }
  841. if ($unit eq 'weeks') {
  842. $diff = $repeat * 604800;
  843. }
  844. if ($unit eq 'months') {
  845. $diff = $mm + $repeat;
  846. my $whole = int($diff / 12);
  847. $yy += $whole;
  848. $mm = ($diff % 12) + 1;
  849. $diff = 0;
  850. }
  851. if ($unit eq 'years') {
  852. $yy++;
  853. }
  854. $mm--;
  855. @t = localtime(timelocal(0,0,0,$dd,$mm,$yy) + $diff);
  856. $t[4]++;
  857. $mm = substr("0$t[4]",-2);
  858. $dd = substr("0$t[3]",-2);
  859. $yy = $t[5] + 1900;
  860. if ($date =~ /\D/) {
  861. if ($myconfig->{dateformat} =~ /^yy/) {
  862. $date = "$yy$spc$mm$spc$dd";
  863. }
  864. if ($myconfig->{dateformat} =~ /^mm/) {
  865. $date = "$mm$spc$dd$spc$yy";
  866. }
  867. if ($myconfig->{dateformat} =~ /^dd/) {
  868. $date = "$dd$spc$mm$spc$yy";
  869. }
  870. } else {
  871. $date = "$yy$mm$dd";
  872. }
  873. }
  874. $date;
  875. }
  876. sub print_button {
  877. my ($self, $button, $name) = @_;
  878. print qq|<input class="submit" type="submit" name="action" value="$button->{$name}{value}" accesskey="$button->{$name}{key}" title="$button->{$name}{value} [Alt-$button->{$name}{key}]" />\n|;
  879. }
  880. # Database routines used throughout
  881. sub dbconnect {
  882. my ($self, $myconfig) = @_;
  883. # connect to database
  884. my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}) or $self->dberror;
  885. # set db options
  886. if ($myconfig->{dboptions}) {
  887. $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
  888. }
  889. $dbh;
  890. }
  891. sub dbconnect_noauto {
  892. my ($self, $myconfig) = @_;
  893. # connect to database
  894. $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, {AutoCommit => 0}) or $self->dberror;
  895. # set db options
  896. if ($myconfig->{dboptions}) {
  897. $dbh->do($myconfig->{dboptions});
  898. }
  899. $dbh;
  900. }
  901. sub dbquote {
  902. my ($self, $var, $type) = @_;
  903. # DBI does not return NULL for SQL_DATE if the date is empty
  904. if ($type eq 'SQL_DATE') {
  905. $_ = ($var) ? "'$var'" : "NULL";
  906. }
  907. if ($type eq 'SQL_INT') {
  908. $_ = $var * 1;
  909. }
  910. $_;
  911. }
  912. sub update_balance {
  913. my ($self, $dbh, $table, $field, $where, $value) = @_;
  914. # if we have a value, go do it
  915. if ($value) {
  916. # retrieve balance from table
  917. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  918. my ($balance) = $dbh->selectrow_array($query);
  919. $balance += $value;
  920. # update balance
  921. $query = "UPDATE $table SET $field = $balance WHERE $where";
  922. $dbh->do($query) || $self->dberror($query);
  923. }
  924. }
  925. sub update_exchangerate {
  926. my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
  927. # some sanity check for currency
  928. return if ($curr eq "");
  929. my $query = qq|SELECT curr
  930. FROM exchangerate
  931. WHERE curr = '$curr'
  932. AND transdate = '$transdate'
  933. FOR UPDATE|;
  934. my $sth = $dbh->prepare($query);
  935. $sth->execute || $self->dberror($query);
  936. my $set;
  937. if ($buy && $sell) {
  938. $set = "buy = $buy, sell = $sell";
  939. } elsif ($buy) {
  940. $set = "buy = $buy";
  941. } elsif ($sell) {
  942. $set = "sell = $sell";
  943. }
  944. if ($sth->fetchrow_array) {
  945. $query = qq|UPDATE exchangerate
  946. SET $set
  947. WHERE curr = '$curr'
  948. AND transdate = '$transdate'|;
  949. } else {
  950. $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
  951. VALUES ('$curr', $buy, $sell, '$transdate')|;
  952. }
  953. $sth->finish;
  954. $dbh->do($query) || $self->dberror($query);
  955. }
  956. sub save_exchangerate {
  957. my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
  958. my $dbh = $self->dbconnect($myconfig);
  959. my ($buy, $sell) = (0, 0);
  960. $buy = $rate if $fld eq 'buy';
  961. $sell = $rate if $fld eq 'sell';
  962. $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
  963. $dbh->disconnect;
  964. }
  965. sub get_exchangerate {
  966. my ($self, $dbh, $curr, $transdate, $fld) = @_;
  967. my $exchangerate = 1;
  968. if ($transdate) {
  969. my $query = qq|SELECT $fld
  970. FROM exchangerate
  971. WHERE curr = '$curr'
  972. AND transdate = '$transdate'|;
  973. ($exchangerate) = $dbh->selectrow_array($query);
  974. }
  975. $exchangerate;
  976. }
  977. sub check_exchangerate {
  978. my ($self, $myconfig, $currency, $transdate, $fld) = @_;
  979. return "" unless $transdate;
  980. my $dbh = $self->dbconnect($myconfig);
  981. my $query = qq|SELECT $fld
  982. FROM exchangerate
  983. WHERE curr = '$currency'
  984. AND transdate = '$transdate'|;
  985. my ($exchangerate) = $dbh->selectrow_array($query);
  986. $dbh->disconnect;
  987. $exchangerate;
  988. }
  989. sub add_shipto {
  990. my ($self, $dbh, $id) = @_;
  991. my $shipto;
  992. foreach my $item (qw(name address1 address2 city state
  993. zipcode country contact phone fax email)) {
  994. if ($self->{"shipto$item"} ne "") {
  995. $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
  996. }
  997. }
  998. if ($shipto) {
  999. my $query = qq|INSERT INTO shipto (trans_id, shiptoname, shiptoaddress1,
  1000. shiptoaddress2, shiptocity, shiptostate,
  1001. shiptozipcode, shiptocountry, shiptocontact,
  1002. shiptophone, shiptofax, shiptoemail)
  1003. VALUES ($id, |
  1004. .$dbh->quote($self->{shiptoname}).qq|, |
  1005. .$dbh->quote($self->{shiptoaddress1}).qq|, |
  1006. .$dbh->quote($self->{shiptoaddress2}).qq|, |
  1007. .$dbh->quote($self->{shiptocity}).qq|, |
  1008. .$dbh->quote($self->{shiptostate}).qq|, |
  1009. .$dbh->quote($self->{shiptozipcode}).qq|, |
  1010. .$dbh->quote($self->{shiptocountry}).qq|, |
  1011. .$dbh->quote($self->{shiptocontact}).qq|,
  1012. '$self->{shiptophone}', '$self->{shiptofax}',
  1013. '$self->{shiptoemail}')|;
  1014. $dbh->do($query) || $self->dberror($query);
  1015. }
  1016. }
  1017. sub get_employee {
  1018. my ($self, $dbh) = @_;
  1019. my $login = $self->{login};
  1020. $login =~ s/@.*//;
  1021. my $query = qq|SELECT name, id
  1022. FROM employee
  1023. WHERE login = '$login'|;
  1024. my (@a) = $dbh->selectrow_array($query);
  1025. $a[1] *= 1;
  1026. @a;
  1027. }
  1028. # this sub gets the id and name from $table
  1029. sub get_name {
  1030. my ($self, $myconfig, $table, $transdate) = @_;
  1031. # connect to database
  1032. my $dbh = $self->dbconnect($myconfig);
  1033. my $where;
  1034. if ($transdate) {
  1035. $where = qq|AND (startdate IS NULL OR startdate <= '$transdate')
  1036. AND (enddate IS NULL OR enddate >= '$transdate')|;
  1037. }
  1038. my $name = $self->like(lc $self->{$table});
  1039. my $query = qq|SELECT *
  1040. FROM $table
  1041. WHERE (lower(name) LIKE '$name'
  1042. OR ${table}number LIKE '$name')
  1043. $where
  1044. ORDER BY name|;
  1045. my $sth = $dbh->prepare($query);
  1046. $sth->execute || $self->dberror($query);
  1047. my $i = 0;
  1048. @{ $self->{name_list} } = ();
  1049. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1050. push(@{ $self->{name_list} }, $ref);
  1051. $i++;
  1052. }
  1053. $sth->finish;
  1054. $dbh->disconnect;
  1055. $i;
  1056. }
  1057. sub all_vc {
  1058. my ($self, $myconfig, $vc, $module, $dbh, $transdate, $job) = @_;
  1059. my $ref;
  1060. my $disconnect = 0;
  1061. if (! $dbh) {
  1062. $dbh = $self->dbconnect($myconfig);
  1063. $disconnect = 1;
  1064. }
  1065. my $sth;
  1066. my $query = qq|SELECT count(*) FROM $vc|;
  1067. my $where;
  1068. if ($transdate) {
  1069. $where = qq|AND (startdate IS NULL OR startdate <= '$transdate')
  1070. AND (enddate IS NULL OR enddate >= '$transdate')|;
  1071. $query .= qq| WHERE 1=1 $where|;
  1072. }
  1073. my ($count) = $dbh->selectrow_array($query);
  1074. # build selection list
  1075. if ($count < $myconfig->{vclimit}) {
  1076. $self->{"${vc}_id"} *= 1;
  1077. $query = qq|SELECT id, name
  1078. FROM $vc
  1079. WHERE 1=1
  1080. $where
  1081. UNION
  1082. SELECT id,name
  1083. FROM $vc
  1084. WHERE id = $self->{"${vc}_id"}
  1085. ORDER BY name|;
  1086. $sth = $dbh->prepare($query);
  1087. $sth->execute || $self->dberror($query);
  1088. @{ $self->{"all_$vc"} } = ();
  1089. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1090. push @{ $self->{"all_$vc"} }, $ref;
  1091. }
  1092. $sth->finish;
  1093. }
  1094. # get self
  1095. if (! $self->{employee_id}) {
  1096. ($self->{employee}, $self->{employee_id}) = split /--/, $self->{employee};
  1097. ($self->{employee}, $self->{employee_id}) = $self->get_employee($dbh) unless $self->{employee_id};
  1098. }
  1099. $self->all_employees($myconfig, $dbh, $transdate, 1);
  1100. $self->all_departments($myconfig, $dbh, $vc);
  1101. $self->all_projects($myconfig, $dbh, $transdate, $job);
  1102. # get language codes
  1103. $query = qq|SELECT *
  1104. FROM language
  1105. ORDER BY 2|;
  1106. $sth = $dbh->prepare($query);
  1107. $sth->execute || $self->dberror($query);
  1108. $self->{all_language} = ();
  1109. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1110. push @{ $self->{all_language} }, $ref;
  1111. }
  1112. $sth->finish;
  1113. $self->all_taxaccounts($myconfig, $dbh, $transdate);
  1114. $dbh->disconnect if $disconnect;
  1115. }
  1116. sub all_taxaccounts {
  1117. my ($self, $myconfig, $dbh, $transdate) = @_;
  1118. my $disconnect = ($dbh) ? 0 : 1;
  1119. if (! $dbh) {
  1120. $dbh = $self->dbconnect($myconfig);
  1121. }
  1122. my $sth;
  1123. my $query;
  1124. my $where;
  1125. if ($transdate) {
  1126. $where = qq| AND (t.validto >= '$transdate' OR t.validto IS NULL)|;
  1127. }
  1128. if ($self->{taxaccounts}) {
  1129. # rebuild tax rates
  1130. $query = qq|SELECT t.rate, t.taxnumber
  1131. FROM tax t
  1132. JOIN chart c ON (c.id = t.chart_id)
  1133. WHERE c.accno = ?
  1134. $where
  1135. ORDER BY accno, validto|;
  1136. $sth = $dbh->prepare($query) || $self->dberror($query);
  1137. foreach my $accno (split / /, $self->{taxaccounts}) {
  1138. $sth->execute($accno);
  1139. ($self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"}) = $sth->fetchrow_array;
  1140. $sth->finish;
  1141. }
  1142. }
  1143. $dbh->disconnect if $disconnect;
  1144. }
  1145. sub all_employees {
  1146. my ($self, $myconfig, $dbh, $transdate, $sales) = @_;
  1147. # setup employees/sales contacts
  1148. my $query = qq|SELECT id, name
  1149. FROM employee
  1150. WHERE 1 = 1|;
  1151. if ($transdate) {
  1152. $query .= qq| AND (startdate IS NULL OR startdate <= '$transdate')
  1153. AND (enddate IS NULL OR enddate >= '$transdate')|;
  1154. } else {
  1155. $query .= qq| AND enddate IS NULL|;
  1156. }
  1157. if ($sales) {
  1158. $query .= qq| AND sales = '1'|;
  1159. }
  1160. $query .= qq| ORDER BY name|;
  1161. my $sth = $dbh->prepare($query);
  1162. $sth->execute || $self->dberror($query);
  1163. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1164. push @{ $self->{all_employee} }, $ref;
  1165. }
  1166. $sth->finish;
  1167. }
  1168. sub all_projects {
  1169. my ($self, $myconfig, $dbh, $transdate, $job) = @_;
  1170. my $disconnect = 0;
  1171. if (! $dbh) {
  1172. $dbh = $self->dbconnect($myconfig);
  1173. $disconnect = 1;
  1174. }
  1175. my $where = "1 = 1";
  1176. $where = qq|id NOT IN (SELECT id
  1177. FROM parts
  1178. WHERE project_id > 0)| if ! $job;
  1179. my $query = qq|SELECT *
  1180. FROM project
  1181. WHERE $where|;
  1182. if ($form->{language_code}) {
  1183. $query = qq|SELECT pr.*, t.description AS translation
  1184. FROM project pr
  1185. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1186. WHERE t.language_code = '$form->{language_code}'|;
  1187. }
  1188. if ($transdate) {
  1189. $query .= qq| AND (startdate IS NULL OR startdate <= '$transdate')
  1190. AND (enddate IS NULL OR enddate >= '$transdate')|;
  1191. }
  1192. $query .= qq| ORDER BY projectnumber|;
  1193. $sth = $dbh->prepare($query);
  1194. $sth->execute || $self->dberror($query);
  1195. @{ $self->{all_project} } = ();
  1196. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1197. push @{ $self->{all_project} }, $ref;
  1198. }
  1199. $sth->finish;
  1200. $dbh->disconnect if $disconnect;
  1201. }
  1202. sub all_departments {
  1203. my ($self, $myconfig, $dbh, $vc) = @_;
  1204. my $disconnect = 0;
  1205. if (! $dbh) {
  1206. $dbh = $self->dbconnect($myconfig);
  1207. $disconnect = 1;
  1208. }
  1209. my $where = "1 = 1";
  1210. if ($vc) {
  1211. if ($vc eq 'customer') {
  1212. $where = " role = 'P'";
  1213. }
  1214. }
  1215. my $query = qq|SELECT id, description
  1216. FROM department
  1217. WHERE $where
  1218. ORDER BY 2|;
  1219. my $sth = $dbh->prepare($query);
  1220. $sth->execute || $self->dberror($query);
  1221. @{ $self->{all_department} } = ();
  1222. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1223. push @{ $self->{all_department} }, $ref;
  1224. }
  1225. $sth->finish;
  1226. $self->all_years($myconfig, $dbh);
  1227. $dbh->disconnect if $disconnect;
  1228. }
  1229. sub all_years {
  1230. my ($self, $myconfig, $dbh) = @_;
  1231. my $disconnect = 0;
  1232. if (! $dbh) {
  1233. $dbh = $self->dbconnect($myconfig);
  1234. $disconnect = 1;
  1235. }
  1236. # get years
  1237. my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
  1238. (SELECT MAX(transdate) FROM acc_trans)
  1239. FROM defaults|;
  1240. my ($startdate, $enddate) = $dbh->selectrow_array($query);
  1241. if ($myconfig->{dateformat} =~ /^yy/) {
  1242. ($startdate) = split /\W/, $startdate;
  1243. ($enddate) = split /\W/, $enddate;
  1244. } else {
  1245. (@_) = split /\W/, $startdate;
  1246. $startdate = $_[2];
  1247. (@_) = split /\W/, $enddate;
  1248. $enddate = $_[2];
  1249. }
  1250. $self->{all_years} = ();
  1251. $startdate = substr($startdate,0,4);
  1252. $enddate = substr($enddate,0,4);
  1253. while ($enddate >= $startdate) {
  1254. push @{ $self->{all_years} }, $enddate--;
  1255. }
  1256. #this should probably be changed to use locale
  1257. %{ $self->{all_month} } = ( '01' => 'January',
  1258. '02' => 'February',
  1259. '03' => 'March',
  1260. '04' => 'April',
  1261. '05' => 'May ',
  1262. '06' => 'June',
  1263. '07' => 'July',
  1264. '08' => 'August',
  1265. '09' => 'September',
  1266. '10' => 'October',
  1267. '11' => 'November',
  1268. '12' => 'December' );
  1269. $dbh->disconnect if $disconnect;
  1270. }
  1271. sub create_links {
  1272. my ($self, $module, $myconfig, $vc, $job) = @_;
  1273. # get last customers or vendors
  1274. my ($query, $sth);
  1275. my $dbh = $self->dbconnect($myconfig);
  1276. my %xkeyref = ();
  1277. # now get the account numbers
  1278. $query = qq|SELECT accno, description, link
  1279. FROM chart
  1280. WHERE link LIKE '%$module%'
  1281. ORDER BY accno|;
  1282. $sth = $dbh->prepare($query);
  1283. $sth->execute || $self->dberror($query);
  1284. $self->{accounts} = "";
  1285. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1286. foreach my $key (split /:/, $ref->{link}) {
  1287. if ($key =~ /$module/) {
  1288. # cross reference for keys
  1289. $xkeyref{$ref->{accno}} = $key;
  1290. push @{ $self->{"${module}_links"}{$key} }, { accno => $ref->{accno},
  1291. description => $ref->{description} };
  1292. $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
  1293. }
  1294. }
  1295. }
  1296. $sth->finish;
  1297. my $arap = ($vc eq 'customer') ? 'ar' : 'ap';
  1298. if ($self->{id}) {
  1299. $query = qq|SELECT a.invnumber, a.transdate,
  1300. a.${vc}_id, a.datepaid, a.duedate, a.ordnumber,
  1301. a.taxincluded, a.curr AS currency, a.notes, a.intnotes,
  1302. c.name AS $vc, a.department_id, d.description AS department,
  1303. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1304. a.employee_id, e.name AS employee, c.language_code,
  1305. a.ponumber
  1306. FROM $arap a
  1307. JOIN $vc c ON (a.${vc}_id = c.id)
  1308. LEFT JOIN employee e ON (e.id = a.employee_id)
  1309. LEFT JOIN department d ON (d.id = a.department_id)
  1310. WHERE a.id = $self->{id}|;
  1311. $sth = $dbh->prepare($query);
  1312. $sth->execute || $self->dberror($query);
  1313. $ref = $sth->fetchrow_hashref(NAME_lc);
  1314. foreach $key (keys %$ref) {
  1315. $self->{$key} = $ref->{$key};
  1316. }
  1317. $sth->finish;
  1318. # get printed, emailed
  1319. $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1320. FROM status s
  1321. WHERE s.trans_id = $self->{id}|;
  1322. $sth = $dbh->prepare($query);
  1323. $sth->execute || $form->dberror($query);
  1324. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1325. $self->{printed} .= "$ref->{formname} " if $ref->{printed};
  1326. $self->{emailed} .= "$ref->{formname} " if $ref->{emailed};
  1327. $self->{queued} .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
  1328. }
  1329. $sth->finish;
  1330. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1331. # get recurring
  1332. $self->get_recurring($dbh);
  1333. # get amounts from individual entries
  1334. $query = qq|SELECT c.accno, c.description, a.source, a.amount,
  1335. a.memo, a.transdate, a.cleared, a.project_id,
  1336. p.projectnumber
  1337. FROM acc_trans a
  1338. JOIN chart c ON (c.id = a.chart_id)
  1339. LEFT JOIN project p ON (p.id = a.project_id)
  1340. WHERE a.trans_id = $self->{id}
  1341. AND a.fx_transaction = '0'
  1342. ORDER BY transdate|;
  1343. $sth = $dbh->prepare($query);
  1344. $sth->execute || $self->dberror($query);
  1345. my $fld = ($vc eq 'customer') ? 'buy' : 'sell';
  1346. $self->{exchangerate} = $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
  1347. # store amounts in {acc_trans}{$key} for multiple accounts
  1348. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1349. $ref->{exchangerate} = $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
  1350. push @{ $self->{acc_trans}{$xkeyref{$ref->{accno}}} }, $ref;
  1351. }
  1352. $sth->finish;
  1353. $query = qq|SELECT d.curr AS currencies, d.closedto, d.revtrans
  1354. FROM defaults d|;
  1355. $sth = $dbh->prepare($query);
  1356. $sth->execute || $self->dberror($query);
  1357. $ref = $sth->fetchrow_hashref(NAME_lc);
  1358. for (keys %$ref) { $self->{$_} = $ref->{$_} }
  1359. $sth->finish;
  1360. } else {
  1361. # get date
  1362. $query = qq|SELECT current_date AS transdate,
  1363. d.curr AS currencies, d.closedto, d.revtrans
  1364. FROM defaults d|;
  1365. $sth = $dbh->prepare($query);
  1366. $sth->execute || $self->dberror($query);
  1367. $ref = $sth->fetchrow_hashref(NAME_lc);
  1368. for (keys %$ref) { $self->{$_} = $ref->{$_} }
  1369. $sth->finish;
  1370. if (! $self->{"$self->{vc}_id"}) {
  1371. $self->lastname_used($myconfig, $dbh, $vc, $module);
  1372. }
  1373. }
  1374. $self->all_vc($myconfig, $vc, $module, $dbh, $self->{transdate}, $job);
  1375. $dbh->disconnect;
  1376. }
  1377. sub lastname_used {
  1378. my ($self, $myconfig, $dbh, $vc, $module) = @_;
  1379. my $arap = ($vc eq 'customer') ? "ar" : "ap";
  1380. my $where = "1 = 1";
  1381. my $sth;
  1382. if ($self->{type} =~ /_order/) {
  1383. $arap = 'oe';
  1384. $where = "quotation = '0'";
  1385. }
  1386. if ($self->{type} =~ /_quotation/) {
  1387. $arap = 'oe';
  1388. $where = "quotation = '1'";
  1389. }
  1390. my $query = qq|SELECT id
  1391. FROM $arap
  1392. WHERE id IN (SELECT MAX(id)
  1393. FROM $arap
  1394. WHERE $where
  1395. AND ${vc}_id > 0)|;
  1396. my ($trans_id) = $dbh->selectrow_array($query);
  1397. $trans_id *= 1;
  1398. my $DAYS = ($myconfig->{dbdriver} eq 'DB2') ? "DAYS" : "";
  1399. $query = qq|SELECT ct.name AS $vc, a.curr AS currency, a.${vc}_id,
  1400. current_date + ct.terms $DAYS AS duedate, a.department_id,
  1401. d.description AS department, ct.notes, ct.curr AS currency
  1402. FROM $arap a
  1403. JOIN $vc ct ON (a.${vc}_id = ct.id)
  1404. LEFT JOIN department d ON (a.department_id = d.id)
  1405. WHERE a.id = $trans_id|;
  1406. $sth = $dbh->prepare($query);
  1407. $sth->execute || $self->dberror($query);
  1408. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1409. for (keys %$ref) { $self->{$_} = $ref->{$_} }
  1410. $sth->finish;
  1411. }
  1412. sub current_date {
  1413. my ($self, $myconfig, $thisdate, $days) = @_;
  1414. my $dbh = $self->dbconnect($myconfig);
  1415. my $query;
  1416. $days *= 1;
  1417. if ($thisdate) {
  1418. my $dateformat = $myconfig->{dateformat};
  1419. if ($myconfig->{dateformat} !~ /^y/) {
  1420. my @a = split /\D/, $thisdate;
  1421. $dateformat .= "yy" if (length $a[2] > 2);
  1422. }
  1423. if ($thisdate !~ /\D/) {
  1424. $dateformat = 'yyyymmdd';
  1425. }
  1426. if ($myconfig->{dbdriver} eq 'DB2') {
  1427. $query = qq|SELECT date('$thisdate') + $days DAYS AS thisdate
  1428. FROM defaults|;
  1429. } else {
  1430. $query = qq|SELECT to_date('$thisdate', '$dateformat') + $days AS thisdate
  1431. FROM defaults|;
  1432. }
  1433. } else {
  1434. $query = qq|SELECT current_date AS thisdate
  1435. FROM defaults|;
  1436. }
  1437. ($thisdate) = $dbh->selectrow_array($query);
  1438. $dbh->disconnect;
  1439. $thisdate;
  1440. }
  1441. sub like {
  1442. my ($self, $str) = @_;
  1443. if ($str !~ /(%|_)/) {
  1444. if ($str =~ /(^").*("$)/) {
  1445. $str =~ s/(^"|"$)//g;
  1446. } else {
  1447. $str = "%$str%";
  1448. }
  1449. }
  1450. $str =~ s/'/''/g;
  1451. $str;
  1452. }
  1453. sub redo_rows {
  1454. my ($self, $flds, $new, $count, $numrows) = @_;
  1455. my @ndx = ();
  1456. for (1 .. $count) {
  1457. push @ndx, { num => $new->[$_-1]->{runningnumber}, ndx => $_ }
  1458. }
  1459. my $i = 0;
  1460. # fill rows
  1461. foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
  1462. $i++;
  1463. $j = $item->{ndx} - 1;
  1464. for (@{$flds}) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1465. }
  1466. # delete empty rows
  1467. for $i ($count + 1 .. $numrows) {
  1468. for (@{$flds}) { delete $self->{"${_}_$i"} }
  1469. }
  1470. }
  1471. sub get_partsgroup {
  1472. my ($self, $myconfig, $p) = @_;
  1473. my $dbh = $self->dbconnect($myconfig);
  1474. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1475. FROM partsgroup pg
  1476. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1477. my $where;
  1478. my $sortorder = "partsgroup";
  1479. if ($p->{searchitems} eq 'part') {
  1480. $where = qq| WHERE (p.inventory_accno_id > 0
  1481. AND p.income_accno_id > 0)|;
  1482. }
  1483. if ($p->{searchitems} eq 'service') {
  1484. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1485. }
  1486. if ($p->{searchitems} eq 'assembly') {
  1487. $where = qq| WHERE p.assembly = '1'|;
  1488. }
  1489. if ($p->{searchitems} eq 'labor') {
  1490. $where = qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1491. }
  1492. if ($p->{searchitems} eq 'nolabor') {
  1493. $where = qq| WHERE p.income_accno_id > 0|;
  1494. }
  1495. if ($p->{all}) {
  1496. $query = qq|SELECT id, partsgroup
  1497. FROM partsgroup|;
  1498. }
  1499. if ($p->{language_code}) {
  1500. $sortorder = "translation";
  1501. $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
  1502. t.description AS translation
  1503. FROM partsgroup pg
  1504. JOIN parts p ON (p.partsgroup_id = pg.id)
  1505. LEFT JOIN translation t ON (t.trans_id = pg.id AND t.language_code = '$p->{language_code}')|;
  1506. }
  1507. $query .= qq| $where ORDER BY $sortorder|;
  1508. my $sth = $dbh->prepare($query);
  1509. $sth->execute || $self->dberror($query);
  1510. $self->{all_partsgroup} = ();
  1511. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1512. push @{ $self->{all_partsgroup} }, $ref;
  1513. }
  1514. $sth->finish;
  1515. $dbh->disconnect;
  1516. }
  1517. sub update_status {
  1518. my ($self, $myconfig) = @_;
  1519. # no id return
  1520. return unless $self->{id};
  1521. my $dbh = $self->dbconnect_noauto($myconfig);
  1522. my %queued = split / +/, $self->{queued};
  1523. my $spoolfile = ($queued{$self->{formname}}) ? "'$queued{$self->{formname}}'" : 'NULL';
  1524. my $query = qq|DELETE FROM status
  1525. WHERE formname = '$self->{formname}'
  1526. AND trans_id = $self->{id}|;
  1527. $dbh->do($query) || $self->dberror($query);
  1528. my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
  1529. my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
  1530. $query = qq|INSERT INTO status (trans_id, printed, emailed,
  1531. spoolfile, formname)
  1532. VALUES ($self->{id}, '$printed',
  1533. '$emailed', $spoolfile,
  1534. '$self->{formname}')|;
  1535. $dbh->do($query) || $self->dberror($query);
  1536. $dbh->commit;
  1537. $dbh->disconnect;
  1538. }
  1539. sub save_status {
  1540. my ($self, $dbh) = @_;
  1541. my $formnames = $self->{printed};
  1542. my $emailforms = $self->{emailed};
  1543. my $query = qq|DELETE FROM status
  1544. WHERE trans_id = $self->{id}|;
  1545. $dbh->do($query) || $self->dberror($query);
  1546. my %queued;
  1547. my $formname;
  1548. if ($self->{queued}) {
  1549. %queued = split / +/, $self->{queued};
  1550. foreach $formname (keys %queued) {
  1551. $printed = ($self->{printed} =~ /$formname/) ? "1" : "0";
  1552. $emailed = ($self->{emailed} =~ /$formname/) ? "1" : "0";
  1553. if ($queued{$formname}) {
  1554. $query = qq|INSERT INTO status (trans_id, printed, emailed,
  1555. spoolfile, formname)
  1556. VALUES ($self->{id}, '$printed', '$emailed',
  1557. '$queued{$formname}', '$formname')|;
  1558. $dbh->do($query) || $self->dberror($query);
  1559. }
  1560. $formnames =~ s/$formname//;
  1561. $emailforms =~ s/$formname//;
  1562. }
  1563. }
  1564. # save printed, emailed info
  1565. $formnames =~ s/^ +//g;
  1566. $emailforms =~ s/^ +//g;
  1567. my %status = ();
  1568. for (split / +/, $formnames) { $status{$_}{printed} = 1 }
  1569. for (split / +/, $emailforms) { $status{$_}{emailed} = 1 }
  1570. foreach my $formname (keys %status) {
  1571. $printed = ($formnames =~ /$self->{formname}/) ? "1" : "0";
  1572. $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
  1573. $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
  1574. VALUES ($self->{id}, '$printed', '$emailed', '$formname')|;
  1575. $dbh->do($query) || $self->dberror($query);
  1576. }
  1577. }
  1578. sub get_recurring {
  1579. my ($self, $dbh) = @_;
  1580. my $query = qq/SELECT s.*, se.formname || ':' || se.format AS emaila,
  1581. se.message,
  1582. sp.formname || ':' || sp.format || ':' || sp.printer AS printa
  1583. FROM recurring s
  1584. LEFT JOIN recurringemail se ON (s.id = se.id)
  1585. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  1586. WHERE s.id = $self->{id}/;
  1587. my $sth = $dbh->prepare($query);
  1588. $sth->execute || $form->dberror($query);
  1589. for (qw(email print)) { $self->{"recurring$_"} = "" }
  1590. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1591. for (keys %$ref) { $self->{"recurring$_"} = $ref->{$_} }
  1592. $self->{recurringemail} .= "$ref->{emaila}:";
  1593. $self->{recurringprint} .= "$ref->{printa}:";
  1594. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  1595. }
  1596. $sth->finish;
  1597. chop $self->{recurringemail};
  1598. chop $self->{recurringprint};
  1599. if ($self->{recurringstartdate}) {
  1600. $self->{recurringreference} = $self->escape($self->{recurringreference},1);
  1601. $self->{recurringmessage} = $self->escape($self->{recurringmessage},1);
  1602. for (qw(reference startdate repeat unit howmany
  1603. payment print email message)) {
  1604. $self->{recurring} .= qq|$self->{"recurring$_"},|
  1605. }
  1606. chop $self->{recurring};
  1607. }
  1608. }
  1609. sub save_recurring {
  1610. my ($self, $dbh, $myconfig) = @_;
  1611. my $disconnect = 0;
  1612. if (! $dbh) {
  1613. $dbh = $self->dbconnect_noauto($myconfig);
  1614. $disconnect = 1;
  1615. }
  1616. my $query;
  1617. $query = qq|DELETE FROM recurring
  1618. WHERE id = $self->{id}|;
  1619. $dbh->do($query) || $self->dberror($query);
  1620. $query = qq|DELETE FROM recurringemail
  1621. WHERE id = $self->{id}|;
  1622. $dbh->do($query) || $self->dberror($query);
  1623. $query = qq|DELETE FROM recurringprint
  1624. WHERE id = $self->{id}|;
  1625. $dbh->do($query) || $self->dberror($query);
  1626. if ($self->{recurring}) {
  1627. my %s = ();
  1628. ($s{reference}, $s{startdate}, $s{repeat}, $s{unit}, $s{howmany},
  1629. $s{payment}, $s{print}, $s{email}, $s{message}) = split /,/, $self->{recurring};
  1630. for (qw(reference message)) { $s{$_} = $self->unescape($s{$_}) }
  1631. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  1632. # calculate enddate
  1633. my $advance = $s{repeat} * ($s{howmany} - 1);
  1634. my %interval = ( 'Pg' => "(date '$s{startdate}' + interval '$advance $s{unit}')",
  1635. 'DB2' => qq|(date ('$s{startdate}') + "$advance $s{unit}")|, );
  1636. $interval{Oracle} = $interval{PgPP} = $interval{Pg};
  1637. $query = qq|SELECT $interval{$myconfig->{dbdriver}}
  1638. FROM defaults|;
  1639. my ($enddate) = $dbh->selectrow_array($query);
  1640. # calculate nextdate
  1641. $query = qq|SELECT current_date - date '$s{startdate}' AS a,
  1642. date '$enddate' - current_date AS b
  1643. FROM defaults|;
  1644. my ($a, $b) = $dbh->selectrow_array($query);
  1645. if ($a + $b) {
  1646. $advance = int(($a / ($a + $b)) * ($s{howmany} - 1) + 1) * $s{repeat};
  1647. } else {
  1648. $advance = 0;
  1649. }
  1650. my $nextdate = $enddate;
  1651. if ($advance > 0) {
  1652. if ($advance < ($s{repeat} * $s{howmany})) {
  1653. %interval = ( 'Pg' => "(date '$s{startdate}' + interval '$advance $s{unit}')",
  1654. 'DB2' => qq|(date ('$s{startdate}') + "$advance $s{unit}")|,);
  1655. $interval{Oracle} = $interval{PgPP} = $interval{Pg};
  1656. $query = qq|SELECT $interval{$myconfig->{dbdriver}}
  1657. FROM defaults|;
  1658. ($nextdate) = $dbh->selectrow_array($query);
  1659. }
  1660. } else {
  1661. $nextdate = $s{startdate};
  1662. }
  1663. if ($self->{recurringnextdate}) {
  1664. $nextdate = $self->{recurringnextdate};
  1665. $query = qq|SELECT '$enddate' - date '$nextdate'
  1666. FROM defaults|;
  1667. if ($dbh->selectrow_array($query) < 0) {
  1668. undef $nextdate;
  1669. }
  1670. }
  1671. $self->{recurringpayment} *= 1;
  1672. $query = qq|INSERT INTO recurring (id, reference, startdate, enddate,
  1673. nextdate, repeat, unit, howmany, payment)
  1674. VALUES ($self->{id}, |.$dbh->quote($s{reference}).qq|,
  1675. '$s{startdate}', '$enddate', |.
  1676. $self->dbquote($nextdate, SQL_DATE).
  1677. qq|, $s{repeat}, '$s{unit}', $s{howmany}, '$s{payment}')|;
  1678. $dbh->do($query) || $self->dberror($query);
  1679. my @p;
  1680. my $p;
  1681. my $i;
  1682. my $sth;
  1683. if ($s{email}) {
  1684. # formname:format
  1685. @p = split /:/, $s{email};
  1686. $query = qq|INSERT INTO recurringemail (id, formname, format, message)
  1687. VALUES ($self->{id}, ?, ?, ?)|;
  1688. $sth = $dbh->prepare($query) || $self->dberror($query);
  1689. for ($i = 0; $i <= $#p; $i += 2) {
  1690. $sth->execute($p[$i], $p[$i+1], $s{message});
  1691. }
  1692. $sth->finish;
  1693. }
  1694. if ($s{print}) {
  1695. # formname:format:printer
  1696. @p = split /:/, $s{print};
  1697. $query = qq|INSERT INTO recurringprint (id, formname, format, printer)
  1698. VALUES ($self->{id}, ?, ?, ?)|;
  1699. $sth = $dbh->prepare($query) || $self->dberror($query);
  1700. for ($i = 0; $i <= $#p; $i += 3) {
  1701. $p = ($p[$i+2]) ? $p[$i+2] : "";
  1702. $sth->execute($p[$i], $p[$i+1], $p);
  1703. }
  1704. $sth->finish;
  1705. }
  1706. }
  1707. if ($disconnect) {
  1708. $dbh->commit;
  1709. $dbh->disconnect;
  1710. }
  1711. }
  1712. sub save_intnotes {
  1713. my ($self, $myconfig, $vc) = @_;
  1714. # no id return
  1715. return unless $self->{id};
  1716. my $dbh = $self->dbconnect($myconfig);
  1717. my $query = qq|UPDATE $vc
  1718. SET intnotes = |.$dbh->quote($self->{intnotes}).qq|
  1719. WHERE id = $self->{id}|;
  1720. $dbh->do($query) || $self->dberror($query);
  1721. $dbh->disconnect;
  1722. }
  1723. sub update_defaults {
  1724. my ($self, $myconfig, $fld, $dbh) = @_;
  1725. my $closedb;
  1726. if (! $dbh) {
  1727. $dbh = $self->dbconnect_noauto($myconfig);
  1728. $closedb = 1;
  1729. }
  1730. my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
  1731. ($_) = $dbh->selectrow_array($query);
  1732. $_ = "0" unless $_;
  1733. # check for and replace
  1734. # <%DATE%>, <%YYMMDD%>, <%YEAR%>, <%MONTH%>, <%DAY%> or variations of
  1735. # <%NAME 1 1 3%>, <%BUSINESS%>, <%BUSINESS 10%>, <%CURR...%>
  1736. # <%DESCRIPTION 1 1 3%>, <%ITEM 1 1 3%>, <%PARTSGROUP 1 1 3%> only for parts
  1737. # <%PHONE%> for customer and vendors
  1738. my $num = $_;
  1739. $num =~ s/.*?<%.*?%>//g;
  1740. ($num) = $num =~ /(\d+)/;
  1741. if (defined $num) {
  1742. my $incnum;
  1743. # if we have leading zeros check how long it is
  1744. if ($num =~ /^0/) {
  1745. my $l = length $num;
  1746. $incnum = $num + 1;
  1747. $l -= length $incnum;
  1748. # pad it out with zeros
  1749. my $padzero = "0" x $l;
  1750. $incnum = ("0" x $l) . $incnum;
  1751. } else {
  1752. $incnum = $num + 1;
  1753. }
  1754. s/$num/$incnum/;
  1755. }
  1756. my $dbvar = $_;
  1757. my $var = $_;
  1758. my $str;
  1759. my $param;
  1760. if (/<%/) {
  1761. while (/<%/) {
  1762. s/<%.*?%>//;
  1763. last unless $&;
  1764. $param = $&;
  1765. $str = "";
  1766. if ($param =~ /<%date%>/i) {
  1767. $str = ($self->split_date($myconfig->{dateformat}, $self->{transdate}))[0];
  1768. $var =~ s/$param/$str/;
  1769. }
  1770. if ($param =~ /<%(name|business|description|item|partsgroup|phone|custom)/i) {
  1771. my $fld = lc $&;
  1772. $fld =~ s/<%//;
  1773. if ($fld =~ /name/) {
  1774. if ($self->{type}) {
  1775. $fld = $self->{vc};
  1776. }
  1777. }
  1778. my $p = $param;
  1779. $p =~ s/(<|>|%)//g;
  1780. my @p = split / /, $p;
  1781. my @n = split / /, uc $self->{$fld};
  1782. if ($#p > 0) {
  1783. for (my $i = 1; $i <= $#p; $i++) {
  1784. $str .= substr($n[$i-1], 0, $p[$i]);
  1785. }
  1786. } else {
  1787. ($str) = split /--/, $self->{$fld};
  1788. }
  1789. $var =~ s/$param/$str/;
  1790. $var =~ s/\W//g if $fld eq 'phone';
  1791. }
  1792. if ($param =~ /<%(yy|mm|dd)/i) {
  1793. my $p = $param;
  1794. $p =~ s/(<|>|%)//g;
  1795. my $spc = $p;
  1796. $spc =~ s/\w//g;
  1797. $spc = substr($spc, 0, 1);
  1798. my %d = ( yy => 1, mm => 2, dd => 3 );
  1799. my @p = ();
  1800. my @a = $self->split_date($myconfig->{dateformat}, $self->{transdate});
  1801. for (sort keys %d) { push @p, $a[$d{$_}] if ($p =~ /$_/) }
  1802. $str = join $spc, @p;
  1803. $var =~ s/$param/$str/;
  1804. }
  1805. if ($param =~ /<%curr/i) {
  1806. $var =~ s/$param/$self->{currency}/;
  1807. }
  1808. }
  1809. }
  1810. $query = qq|UPDATE defaults
  1811. SET $fld = '$dbvar'|;
  1812. $dbh->do($query) || $form->dberror($query);
  1813. if ($closedb) {
  1814. $dbh->commit;
  1815. $dbh->disconnect;
  1816. }
  1817. $var;
  1818. }
  1819. sub split_date {
  1820. my ($self, $dateformat, $date) = @_;
  1821. my @d = localtime;
  1822. my $mm;
  1823. my $dd;
  1824. my $yy;
  1825. my $rv;
  1826. if (! $date) {
  1827. $dd = $d[3];
  1828. $mm = ++$d[4];
  1829. $yy = substr($d[5],-2);
  1830. $mm = substr("0$mm", -2);
  1831. $dd = substr("0$dd", -2);
  1832. }
  1833. if ($dateformat =~ /^yy/) {
  1834. if ($date) {
  1835. if ($date =~ /\D/) {
  1836. ($yy, $mm, $dd) = split /\D/, $date;
  1837. $mm *= 1;
  1838. $dd *= 1;
  1839. $mm = substr("0$mm", -2);
  1840. $dd = substr("0$dd", -2);
  1841. $yy = substr($yy, -2);
  1842. $rv = "$yy$mm$dd";
  1843. } else {
  1844. $rv = $date;
  1845. }
  1846. } else {
  1847. $rv = "$yy$mm$dd";
  1848. }
  1849. }
  1850. if ($dateformat =~ /^mm/) {
  1851. if ($date) {
  1852. if ($date =~ /\D/) {
  1853. ($mm, $dd, $yy) = split /\D/, $date;
  1854. $mm *= 1;
  1855. $dd *= 1;
  1856. $mm = substr("0$mm", -2);
  1857. $dd = substr("0$dd", -2);
  1858. $yy = substr($yy, -2);
  1859. $rv = "$mm$dd$yy";
  1860. } else {
  1861. $rv = $date;
  1862. }
  1863. } else {
  1864. $rv = "$mm$dd$yy";
  1865. }
  1866. }
  1867. if ($dateformat =~ /^dd/) {
  1868. if ($date) {
  1869. if ($date =~ /\D/) {
  1870. ($dd, $mm, $yy) = split /\D/, $date;
  1871. $mm *= 1;
  1872. $dd *= 1;
  1873. $mm = substr("0$mm", -2);
  1874. $dd = substr("0$dd", -2);
  1875. $yy = substr($yy, -2);
  1876. $rv = "$dd$mm$yy";
  1877. } else {
  1878. $rv = $date;
  1879. }
  1880. } else {
  1881. $rv = "$dd$mm$yy";
  1882. }
  1883. }
  1884. ($rv, $yy, $mm, $dd);
  1885. }
  1886. sub from_to {
  1887. my ($self, $yy, $mm, $interval) = @_;
  1888. use Time::Local;
  1889. my @t;
  1890. my $dd = 1;
  1891. my $fromdate = "$yy${mm}01";
  1892. my $bd = 1;
  1893. if (defined $interval) {
  1894. if ($interval == 12) {
  1895. $yy++;
  1896. } else {
  1897. if (($mm += $interval) > 12) {
  1898. $mm -= 12;
  1899. $yy++;
  1900. }
  1901. if ($interval == 0) {
  1902. @t = localtime(time);
  1903. $dd = $t[3];
  1904. $mm = $t[4] + 1;
  1905. $yy = $t[5] + 1900;
  1906. $bd = 0;
  1907. }
  1908. }
  1909. } else {
  1910. if (++$mm > 12) {
  1911. $mm -= 12;
  1912. $yy++;
  1913. }
  1914. }
  1915. $mm--;
  1916. @t = localtime(timelocal(0,0,0,$dd,$mm,$yy) - $bd);
  1917. $t[4]++;
  1918. $t[4] = substr("0$t[4]",-2);
  1919. $t[3] = substr("0$t[3]",-2);
  1920. $t[5] += 1900;
  1921. ($fromdate, "$t[5]$t[4]$t[3]");
  1922. }
  1923. sub audittrail {
  1924. my ($self, $dbh, $myconfig, $audittrail) = @_;
  1925. # table, $reference, $formname, $action, $id, $transdate) = @_;
  1926. my $query;
  1927. my $rv;
  1928. my $disconnect;
  1929. if (! $dbh) {
  1930. $dbh = $self->dbconnect($myconfig);
  1931. $disconnect = 1;
  1932. }
  1933. # if we have an id add audittrail, otherwise get a new timestamp
  1934. if ($audittrail->{id}) {
  1935. $query = qq|SELECT audittrail FROM defaults|;
  1936. if ($dbh->selectrow_array($query)) {
  1937. my ($null, $employee_id) = $self->get_employee($dbh);
  1938. if ($self->{audittrail} && !$myconfig) {
  1939. chop $self->{audittrail};
  1940. my @a = split /\|/, $self->{audittrail};
  1941. my %newtrail = ();
  1942. my $key;
  1943. my $i;
  1944. my @flds = qw(tablename reference formname action transdate);
  1945. # put into hash and remove dups
  1946. while (@a) {
  1947. $key = "$a[2]$a[3]";
  1948. $i = 0;
  1949. $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
  1950. splice @a, 0, 5;
  1951. }
  1952. $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
  1953. formname, action, employee_id, transdate)
  1954. VALUES ($audittrail->{id}, ?, ?, ?, ?, $employee_id, ?)|;
  1955. my $sth = $dbh->prepare($query) || $self->dberror($query);
  1956. foreach $key (sort { $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate} } keys %newtrail) {
  1957. $i = 1;
  1958. for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
  1959. $sth->execute || $self->dberror;
  1960. $sth->finish;
  1961. }
  1962. }
  1963. if ($audittrail->{transdate}) {
  1964. $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
  1965. formname, action, employee_id, transdate)
  1966. VALUES ($audittrail->{id}, '$audittrail->{tablename}', |
  1967. .$dbh->quote($audittrail->{reference}).qq|',
  1968. '$audittrail->{formname}', '$audittrail->{action}',
  1969. $employee_id, '$audittrail->{transdate}')|;
  1970. } else {
  1971. $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
  1972. formname, action, employee_id)
  1973. VALUES ($audittrail->{id},
  1974. '$audittrail->{tablename}', |
  1975. .$dbh->quote($audittrail->{reference}).qq|,
  1976. '$audittrail->{formname}', '$audittrail->{action}',
  1977. $employee_id)|;
  1978. }
  1979. $dbh->do($query);
  1980. }
  1981. } else {
  1982. $query = qq|SELECT current_timestamp FROM defaults|;
  1983. my ($timestamp) = $dbh->selectrow_array($query);
  1984. $rv = "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  1985. }
  1986. $dbh->disconnect if $disconnect;
  1987. $rv;
  1988. }
  1989. package Locale;
  1990. sub new {
  1991. my ($type, $country, $NLS_file) = @_;
  1992. my $self = {};
  1993. %self = ();
  1994. if ($country && -d "locale/$country") {
  1995. $self->{countrycode} = $country;
  1996. eval { require "locale/$country/$NLS_file"; };
  1997. }
  1998. $self->{NLS_file} = $NLS_file;
  1999. $self->{charset} = $self{charset};
  2000. push @{ $self->{LONG_MONTH} }, ("January", "February", "March", "April", "May ", "June", "July", "August", "September", "October", "November", "December");
  2001. push @{ $self->{SHORT_MONTH} }, (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec));
  2002. bless $self, $type;
  2003. }
  2004. sub text {
  2005. my ($self, $text) = @_;
  2006. return (exists $self{texts}{$text}) ? $self{texts}{$text} : $text;
  2007. }
  2008. sub findsub {
  2009. my ($self, $text) = @_;
  2010. if (exists $self{subs}{$text}) {
  2011. $text = $self{subs}{$text};
  2012. } else {
  2013. if ($self->{countrycode} && $self->{NLS_file}) {
  2014. Form->error("$text not defined in locale/$self->{countrycode}/$self->{NLS_file}");
  2015. }
  2016. }
  2017. $text;
  2018. }
  2019. sub date {
  2020. my ($self, $myconfig, $date, $longformat) = @_;
  2021. my $longdate = "";
  2022. my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
  2023. if ($date) {
  2024. # get separator
  2025. $spc = $myconfig->{dateformat};
  2026. $spc =~ s/\w//g;
  2027. $spc = substr($spc, 0, 1);
  2028. if ($date =~ /\D/) {
  2029. if ($myconfig->{dateformat} =~ /^yy/) {
  2030. ($yy, $mm, $dd) = split /\D/, $date;
  2031. }
  2032. if ($myconfig->{dateformat} =~ /^mm/) {
  2033. ($mm, $dd, $yy) = split /\D/, $date;
  2034. }
  2035. if ($myconfig->{dateformat} =~ /^dd/) {
  2036. ($dd, $mm, $yy) = split /\D/, $date;
  2037. }
  2038. } else {
  2039. $date = substr($date, 2);
  2040. ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
  2041. }
  2042. $dd *= 1;
  2043. $mm--;
  2044. $yy += 2000 if length $yy == 2;
  2045. if ($myconfig->{dateformat} =~ /^dd/) {
  2046. $mm++;
  2047. $dd = substr("0$dd", -2);
  2048. $mm = substr("0$mm", -2);
  2049. $longdate = "$dd$spc$mm$spc$yy";
  2050. if (defined $longformat) {
  2051. $longdate = "$dd";
  2052. $longdate .= ($spc eq '.') ? ". " : " ";
  2053. $longdate .= &text($self, $self->{$longmonth}[--$mm])." $yy";
  2054. }
  2055. } elsif ($myconfig->{dateformat} =~ /^yy/) {
  2056. $mm++;
  2057. $dd = substr("0$dd", -2);
  2058. $mm = substr("0$mm", -2);
  2059. $longdate = "$yy$spc$mm$spc$dd";
  2060. if (defined $longformat) {
  2061. $longdate = &text($self, $self->{$longmonth}[--$mm])." $dd $yy";
  2062. }
  2063. } else {
  2064. $mm++;
  2065. $dd = substr("0$dd", -2);
  2066. $mm = substr("0$mm", -2);
  2067. $longdate = "$mm$spc$dd$spc$yy";
  2068. if (defined $longformat) {
  2069. $longdate = &text($self, $self->{$longmonth}[--$mm])." $dd $yy";
  2070. }
  2071. }
  2072. }
  2073. $longdate;
  2074. }
  2075. 1;