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