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