summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: 5ea2271051b8be60a67a8ba19359c465341fe0f9 (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 ($self, $tablename, $query_type, $linenum) = @_;
  898. if ($query_type !~ /^(select|insert|update)$/i){
  899. $self->error($locale->text(
  900. "Passed incorrect query type to get_cutstom_queries."
  901. ));
  902. }
  903. my @rc;
  904. my %temphash;
  905. my @templist;
  906. my @elements;
  907. my $query;
  908. my $ins_values;
  909. if ($linenum){
  910. $linenum = "_$linenum";
  911. }
  912. $query_type = uc($query_type);
  913. for (@{$self->{custom_db_fields}{$tablename}}){
  914. @elements = split (/:/, $_);
  915. push @{$temphash{$elements[0]}}, $elements[1];
  916. }
  917. for (keys %temphash){
  918. my @data;
  919. my $ins_values;
  920. $query = "$query_type ";
  921. if ($query_type eq 'UPDATE'){
  922. $query .= " $_ SET ";
  923. } elsif ($query_type eq 'INSERT'){
  924. $query .= " INTO $_ (";
  925. }
  926. my $first = 1;
  927. for (@{$temphash{$_}}){
  928. $query .= "$_";
  929. if ($query_type eq 'UPDATE'){
  930. $query .= '= ?';
  931. }
  932. $ins_values .= "?, ";
  933. $query .= ", ";
  934. $first = 0;
  935. if ($query_type eq 'UPDATE' or $query_type eq 'INSERT'){
  936. push @data, $self->{"$_$linenum"};
  937. }
  938. }
  939. if ($query_type ne 'INSERT'){
  940. $query =~ s/, $//;
  941. }
  942. if ($query_type eq 'SELECT'){
  943. $query .= " FROM $_";
  944. }
  945. if ($query_type eq 'SELECT' or $query_type eq 'UPDATE'){
  946. $query .= " WHERE row_id = ?";
  947. }
  948. if ($query_type eq 'INSERT'){
  949. $query .= " row_id) VALUES ($ins_values ?)";
  950. }
  951. if ($query_type eq 'SELECT'){
  952. push @rc, [ $query ];
  953. } else {
  954. unshift (@data, $query);
  955. push @rc, [ @data ];
  956. }
  957. }
  958. @rc;
  959. }
  960. sub dbconnect {
  961. my ($self, $myconfig) = @_;
  962. # connect to database
  963. my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}) or $self->dberror;
  964. # set db options
  965. if ($myconfig->{dboptions}) {
  966. $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
  967. }
  968. $dbh;
  969. }
  970. sub dbconnect_noauto {
  971. my ($self, $myconfig) = @_;
  972. # connect to database
  973. $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, {AutoCommit => 0}) or $self->dberror;
  974. # set db options
  975. if ($myconfig->{dboptions}) {
  976. $dbh->do($myconfig->{dboptions});
  977. }
  978. $dbh;
  979. }
  980. sub dbquote {
  981. my ($self, $var) = @_;
  982. if ($var eq ''){
  983. $_ = "NULL";
  984. } else {
  985. $_ = $self->{dbh}->quote($var);
  986. }
  987. $_;
  988. }
  989. sub update_balance {
  990. my ($self, $dbh, $table, $field, $where, $value) = @_;
  991. # if we have a value, go do it
  992. if ($value) {
  993. # retrieve balance from table
  994. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  995. my ($balance) = $dbh->selectrow_array($query);
  996. $balance += $value;
  997. # update balance
  998. $query = "UPDATE $table SET $field = $balance WHERE $where";
  999. $dbh->do($query) || $self->dberror($query);
  1000. }
  1001. }
  1002. sub update_exchangerate {
  1003. my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
  1004. # some sanity check for currency
  1005. return if ($curr eq "");
  1006. my $query = qq|
  1007. SELECT curr
  1008. FROM exchangerate
  1009. WHERE curr = ?
  1010. AND transdate = ?
  1011. FOR UPDATE|;
  1012. my $sth = $self->{dbh}->prepare($query);
  1013. $sth->execute($curr, $transdate) || $self->dberror($query);
  1014. my $set;
  1015. my @queryargs;
  1016. if ($buy && $sell) {
  1017. $set = "buy = ?, sell = ?";
  1018. @queryargs = ($buy, $sell);
  1019. } elsif ($buy) {
  1020. $set = "buy = ?";
  1021. @queryargs = ($buy);
  1022. } elsif ($sell) {
  1023. $set = "sell = ?";
  1024. @queryargs = ($sell);
  1025. }
  1026. if ($sth->fetchrow_array) {
  1027. $query = qq|UPDATE exchangerate
  1028. SET $set
  1029. WHERE curr = ?
  1030. AND transdate = ?|;
  1031. push (@queryargs, $curr, $transdate);
  1032. } else {
  1033. $query = qq|
  1034. INSERT INTO exchangerate (
  1035. curr, buy, sell, transdate)
  1036. VALUES (?, ?, ?, ?)|;
  1037. @queryargs = ($curr, $buy, $sell, $transdate);
  1038. }
  1039. $sth->finish;
  1040. $sth = $self->{dbh}->prepare($query);
  1041. $sth->execute(@queryargs) || $self->dberror($query);
  1042. }
  1043. sub save_exchangerate {
  1044. my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
  1045. my ($buy, $sell) = (0, 0);
  1046. $buy = $rate if $fld eq 'buy';
  1047. $sell = $rate if $fld eq 'sell';
  1048. $self->update_exchangerate(
  1049. $self->{dbh},
  1050. $currency,
  1051. $transdate,
  1052. $buy,
  1053. $sell);
  1054. $dbh->commit;
  1055. }
  1056. sub get_exchangerate {
  1057. my ($self, $dbh, $curr, $transdate, $fld) = @_;
  1058. my $exchangerate = 1;
  1059. if ($transdate) {
  1060. my $query = qq|
  1061. SELECT $fld FROM exchangerate
  1062. WHERE curr = ? AND transdate = ?|;
  1063. $sth = $self->{dbh}->prepare($query);
  1064. $sth->execute($curr, $transdate);
  1065. ($exchangerate) = $sth->fetchrow_array;
  1066. }
  1067. $exchangerate;
  1068. $sth->finish;
  1069. $self->{dbh}->commit;
  1070. }
  1071. sub check_exchangerate {
  1072. my ($self, $myconfig, $currency, $transdate, $fld) = @_;
  1073. return "" unless $transdate;
  1074. my $query = qq|
  1075. SELECT $fld
  1076. FROM exchangerate
  1077. WHERE curr = ? AND transdate = ?|;
  1078. my $sth = $self->{dbh}->prepare($query);
  1079. $sth->execute($currenct, $transdate);
  1080. my ($exchangerate) = $sth->fetchrow_array($query);
  1081. $sth->finish;
  1082. $self->{dbh}->commit;
  1083. $exchangerate;
  1084. }
  1085. sub add_shipto {
  1086. my ($self, $dbh, $id) = @_;
  1087. my $shipto;
  1088. foreach my $item (qw(name address1 address2 city state
  1089. zipcode country contact phone fax email)) {
  1090. if ($self->{"shipto$item"} ne "") {
  1091. $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
  1092. }
  1093. }
  1094. if ($shipto) {
  1095. my $query = qq|
  1096. INSERT INTO shipto
  1097. (trans_id, shiptoname, shiptoaddress1,
  1098. shiptoaddress2, shiptocity, shiptostate,
  1099. shiptozipcode, shiptocountry, shiptocontact,
  1100. shiptophone, shiptofax, shiptoemail)
  1101. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1102. |;
  1103. $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  1104. $sth->execute(
  1105. $id, $self->{shiptoname}, $self->{shiptoaddress1},
  1106. $self->{shiptoaddress2}, $self->{shiptocity},
  1107. $self->{shiptostate}, $self->{shiptostate},
  1108. $self->{shiptozipcode}, $self->{shiptocountry},
  1109. $self->{shiptocontact}, $self->{shiptophone},
  1110. $self->{shiptofax}, $self->{shiptoemail}
  1111. ) || $self->dberror($query);
  1112. $sth->finish;
  1113. $self->{dbh}->commit;
  1114. }
  1115. }
  1116. sub get_employee {
  1117. my ($self, $dbh) = @_;
  1118. my $login = $self->{login};
  1119. $login =~ s/@.*//;
  1120. my $query = qq|SELECT name, id
  1121. FROM employee
  1122. WHERE login = ?|;
  1123. $sth = $self->{dbh}->prepare($query);
  1124. $sth->execute($login);
  1125. my (@a) = $sth->fetchrow_array();
  1126. $a[1] *= 1;
  1127. $sth->finish;
  1128. $self->{dbh}->commit;
  1129. @a;
  1130. }
  1131. # this sub gets the id and name from $table
  1132. sub get_name {
  1133. my ($self, $myconfig, $table, $transdate) = @_;
  1134. # connect to database
  1135. my @queryargs;
  1136. my $where;
  1137. if ($transdate) {
  1138. $where = qq|
  1139. AND (startdate IS NULL OR startdate <= ?)
  1140. AND (enddate IS NULL OR enddate >= ?)|;
  1141. @queryargs = ($transdate, $transdate);
  1142. }
  1143. my $name = $self->like(lc $self->{$table});
  1144. my $query = qq|
  1145. SELECT * FROM $table
  1146. WHERE (lower(name) LIKE ? OR ${table}number LIKE ?)
  1147. $where
  1148. ORDER BY name|;
  1149. unshift(@queryargs, $name, $name);
  1150. my $sth = $self->{dbh}->prepare($query);
  1151. $sth->execute(@queryargs) || $self->dberror($query);
  1152. my $i = 0;
  1153. @{ $self->{name_list} } = ();
  1154. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1155. push(@{ $self->{name_list} }, $ref);
  1156. $i++;
  1157. }
  1158. $sth->finish;
  1159. $self->{dbh}->commit;
  1160. $i;
  1161. }
  1162. sub all_vc {
  1163. my ($self, $myconfig, $vc, $module, $dbh, $transdate, $job) = @_;
  1164. my $ref;
  1165. my $disconnect = 0;
  1166. $dbh = $self->{dbh};
  1167. my $sth;
  1168. my $query = qq|SELECT count(*) FROM $vc|;
  1169. my $where;
  1170. my @ueryargs = ();
  1171. if ($transdate) {
  1172. $query .= qq| WHERE (startdate IS NULL OR startdate <= ?)
  1173. AND (enddate IS NULL OR enddate >= ?)|;
  1174. @queryargs = ($transdate, $transdate);
  1175. }
  1176. $sth = $dbh->prepare($query);
  1177. $sth->execute(@queryargs);
  1178. my ($count) = $sth->fetchrow_array;
  1179. $sth->finish;
  1180. @queryargs = ();
  1181. # build selection list
  1182. if ($count < $myconfig->{vclimit}) {
  1183. $self->{"${vc}_id"} *= 1;
  1184. $query = qq|SELECT id, name
  1185. FROM $vc
  1186. WHERE 1=1
  1187. $where
  1188. UNION
  1189. SELECT id,name
  1190. FROM $vc
  1191. WHERE id = ?
  1192. ORDER BY name|;
  1193. push(@queryargs, $self->{"${vc}_id"});
  1194. $sth = $dbh->prepare($query);
  1195. $sth->execute(@queryargs) || $self->dberror($query);
  1196. @{ $self->{"all_$vc"} } = ();
  1197. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1198. push @{ $self->{"all_$vc"} }, $ref;
  1199. }
  1200. $sth->finish;
  1201. }
  1202. # get self
  1203. if (! $self->{employee_id}) {
  1204. ($self->{employee}, $self->{employee_id}) = split /--/, $self->{employee};
  1205. ($self->{employee}, $self->{employee_id}) = $self->get_employee($dbh) unless $self->{employee_id};
  1206. }
  1207. $self->all_employees($myconfig, $dbh, $transdate, 1);
  1208. $self->all_departments($myconfig, $dbh, $vc);
  1209. $self->all_projects($myconfig, $dbh, $transdate, $job);
  1210. # get language codes
  1211. $query = qq|SELECT *
  1212. FROM language
  1213. ORDER BY 2|;
  1214. $sth = $dbh->prepare($query);
  1215. $sth->execute || $self->dberror($query);
  1216. $self->{all_language} = ();
  1217. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1218. push @{ $self->{all_language} }, $ref;
  1219. }
  1220. $sth->finish;
  1221. $self->all_taxaccounts($myconfig, $dbh, $transdate);
  1222. $self->{dbh}->commit;
  1223. }
  1224. sub all_taxaccounts {
  1225. my ($self, $myconfig, $dbh2, $transdate) = @_;
  1226. my $disconnect = ($dbh) ? 0 : 1;
  1227. my $dbh = $self->{dbh};
  1228. my $sth;
  1229. my $query;
  1230. my $where;
  1231. my @queryargs = ();
  1232. if ($transdate) {
  1233. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1234. push(@queryargs, $transdate);
  1235. }
  1236. if ($self->{taxaccounts}) {
  1237. # rebuild tax rates
  1238. $query = qq|SELECT t.rate, t.taxnumber
  1239. FROM tax t
  1240. JOIN chart c ON (c.id = t.chart_id)
  1241. WHERE c.accno = ?
  1242. $where
  1243. ORDER BY accno, validto|;
  1244. $sth = $dbh->prepare($query) || $self->dberror($query);
  1245. foreach my $accno (split / /, $self->{taxaccounts}) {
  1246. $sth->execute(@queryargs, $accno);
  1247. ($self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"}) = $sth->fetchrow_array;
  1248. $sth->finish;
  1249. }
  1250. }
  1251. $self->{dbh}->commit;
  1252. }
  1253. sub all_employees {
  1254. my ($self, $myconfig, $dbh2, $transdate, $sales) = @_;
  1255. my $dbh = $self->{dbh};
  1256. my @whereargs = ();
  1257. # setup employees/sales contacts
  1258. my $query = qq|SELECT id, name
  1259. FROM employee
  1260. WHERE 1 = 1|;
  1261. if ($transdate) {
  1262. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1263. AND (enddate IS NULL OR enddate >= ?)|;
  1264. @whereargs = ($transdate, $transdate);
  1265. } else {
  1266. $query .= qq| AND enddate IS NULL|;
  1267. }
  1268. if ($sales) {
  1269. $query .= qq| AND sales = '1'|;
  1270. }
  1271. $query .= qq| ORDER BY name|;
  1272. my $sth = $dbh->prepare($query);
  1273. $sth->execute(@whereargs) || $self->dberror($query);
  1274. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1275. push @{ $self->{all_employee} }, $ref;
  1276. }
  1277. $sth->finish;
  1278. $dbh->commit;
  1279. }
  1280. sub all_projects {
  1281. my ($self, $myconfig, $dbh2, $transdate, $job) = @_;
  1282. my $dbh = $self->{dbh};
  1283. my @queryargs = ();
  1284. my $where = "1 = 1";
  1285. $where = qq|id NOT IN (SELECT id
  1286. FROM parts
  1287. WHERE project_id > 0)| if ! $job;
  1288. my $query = qq|SELECT *
  1289. FROM project
  1290. WHERE $where|;
  1291. if ($form->{language_code}) {
  1292. $query = qq|
  1293. SELECT pr.*, t.description AS translation
  1294. FROM project pr
  1295. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1296. WHERE t.language_code = ?|;
  1297. push(@queryargs, $self->{language_code});
  1298. }
  1299. if ($transdate) {
  1300. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1301. AND (enddate IS NULL OR enddate >= ?)|;
  1302. push(@queryargs, $transdate, $transdate);
  1303. }
  1304. $query .= qq| ORDER BY projectnumber|;
  1305. $sth = $dbh->prepare($query);
  1306. $sth->execute(@queryargs)|| $self->dberror($query);
  1307. @{ $self->{all_project} } = ();
  1308. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1309. push @{ $self->{all_project} }, $ref;
  1310. }
  1311. $sth->finish;
  1312. $dbh->commit;
  1313. }
  1314. sub all_departments {
  1315. my ($self, $myconfig, $dbh2, $vc) = @_;
  1316. $dbh = $self->{dbh};
  1317. my $where = "1 = 1";
  1318. if ($vc) {
  1319. if ($vc eq 'customer') {
  1320. $where = " role = 'P'";
  1321. }
  1322. }
  1323. my $query = qq|SELECT id, description
  1324. FROM department
  1325. WHERE $where
  1326. ORDER BY 2|;
  1327. my $sth = $dbh->prepare($query);
  1328. $sth->execute || $self->dberror($query);
  1329. @{ $self->{all_department} } = ();
  1330. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1331. push @{ $self->{all_department} }, $ref;
  1332. }
  1333. $sth->finish;
  1334. $self->all_years($myconfig);
  1335. $dbh->commit;
  1336. }
  1337. sub all_years {
  1338. my ($self, $myconfig, $dbh2) = @_;
  1339. $dbh = $self->{dbh};
  1340. # get years
  1341. my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
  1342. (SELECT MAX(transdate) FROM acc_trans)
  1343. FROM defaults|;
  1344. my ($startdate, $enddate) = $dbh->selectrow_array($query);
  1345. if ($myconfig->{dateformat} =~ /^yy/) {
  1346. ($startdate) = split /\W/, $startdate;
  1347. ($enddate) = split /\W/, $enddate;
  1348. } else {
  1349. (@_) = split /\W/, $startdate;
  1350. $startdate = $_[2];
  1351. (@_) = split /\W/, $enddate;
  1352. $enddate = $_[2];
  1353. }
  1354. $self->{all_years} = ();
  1355. $startdate = substr($startdate,0,4);
  1356. $enddate = substr($enddate,0,4);
  1357. while ($enddate >= $startdate) {
  1358. push @{ $self->{all_years} }, $enddate--;
  1359. }
  1360. #this should probably be changed to use locale
  1361. %{ $self->{all_month} } = (
  1362. '01' => 'January',
  1363. '02' => 'February',
  1364. '03' => 'March',
  1365. '04' => 'April',
  1366. '05' => 'May ',
  1367. '06' => 'June',
  1368. '07' => 'July',
  1369. '08' => 'August',
  1370. '09' => 'September',
  1371. '10' => 'October',
  1372. '11' => 'November',
  1373. '12' => 'December' );
  1374. $dbh->commit;
  1375. }
  1376. sub create_links {
  1377. my ($self, $module, $myconfig, $vc, $job) = @_;
  1378. # get last customers or vendors
  1379. my ($query, $sth);
  1380. $dbh = $self->{dbh};
  1381. my %xkeyref = ();
  1382. # now get the account numbers
  1383. $query = qq|SELECT accno, description, link
  1384. FROM chart
  1385. WHERE link LIKE ?
  1386. ORDER BY accno|;
  1387. $sth = $dbh->prepare($query);
  1388. $sth->execute("%"."$module%") || $self->dberror($query);
  1389. $self->{accounts} = "";
  1390. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1391. foreach my $key (split /:/, $ref->{link}) {
  1392. if ($key =~ /$module/) {
  1393. # cross reference for keys
  1394. $xkeyref{$ref->{accno}} = $key;
  1395. push @{ $self->{"${module}_links"}{$key} },
  1396. { accno => $ref->{accno},
  1397. description => $ref->{description} };
  1398. $self->{accounts} .= "$ref->{accno} "
  1399. unless $key =~ /tax/;
  1400. }
  1401. }
  1402. }
  1403. $sth->finish;
  1404. my $arap = ($vc eq 'customer') ? 'ar' : 'ap';
  1405. if ($self->{id}) {
  1406. $query = qq|
  1407. SELECT a.invnumber, a.transdate,
  1408. a.${vc}_id, a.datepaid, a.duedate, a.ordnumber,
  1409. a.taxincluded, a.curr AS currency, a.notes,
  1410. a.intnotes, c.name AS $vc, a.department_id,
  1411. d.description AS department,
  1412. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1413. a.employee_id, e.name AS employee,
  1414. c.language_code, a.ponumber
  1415. FROM $arap a
  1416. JOIN $vc c ON (a.${vc}_id = c.id)
  1417. LEFT JOIN employee e ON (e.id = a.employee_id)
  1418. LEFT JOIN department d ON (d.id = a.department_id)
  1419. WHERE a.id = ?|;
  1420. $sth = $dbh->prepare($query);
  1421. $sth->execute($self->{id}) || $self->dberror($query);
  1422. $ref = $sth->fetchrow_hashref(NAME_lc);
  1423. foreach $key (keys %$ref) {
  1424. $self->{$key} = $ref->{$key};
  1425. }
  1426. $sth->finish;
  1427. # get printed, emailed
  1428. $query = qq|
  1429. SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1430. FROM status s WHERE s.trans_id = ?|;
  1431. $sth = $dbh->prepare($query);
  1432. $sth->execute($self->{id}) || $form->dberror($query);
  1433. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1434. $self->{printed} .= "$ref->{formname} "
  1435. if $ref->{printed};
  1436. $self->{emailed} .= "$ref->{formname} "
  1437. if $ref->{emailed};
  1438. $self->{queued} .= "$ref->{formname} ".
  1439. "$ref->{spoolfile} " if $ref->{spoolfile};
  1440. }
  1441. $sth->finish;
  1442. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1443. # get recurring
  1444. $self->get_recurring($dbh);
  1445. # get amounts from individual entries
  1446. $query = qq|
  1447. SELECT c.accno, c.description, a.source, a.amount,
  1448. a.memo, a.transdate, a.cleared, a.project_id,
  1449. p.projectnumber
  1450. FROM acc_trans a
  1451. JOIN chart c ON (c.id = a.chart_id)
  1452. LEFT JOIN project p ON (p.id = a.project_id)
  1453. WHERE a.trans_id = ?
  1454. AND a.fx_transaction = '0'
  1455. ORDER BY transdate|;
  1456. $sth = $dbh->prepare($query);
  1457. $sth->execute($self->{id}) || $self->dberror($query);
  1458. my $fld = ($vc eq 'customer') ? 'buy' : 'sell';
  1459. $self->{exchangerate} = $self->get_exchangerate($dbh,
  1460. $self->{currency}, $self->{transdate}, $fld);
  1461. # store amounts in {acc_trans}{$key} for multiple accounts
  1462. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1463. $ref->{exchangerate} = $self->get_exchangerate($dbh,
  1464. $self->{currency},
  1465. $ref->{transdate},
  1466. $fld);
  1467. push @{ $self->{acc_trans}{$xkeyref{$ref->{accno}}} },
  1468. $ref;
  1469. }
  1470. $sth->finish;
  1471. $query = qq|SELECT d.curr AS currencies, d.closedto, d.revtrans
  1472. FROM defaults d|;
  1473. $sth = $dbh->prepare($query);
  1474. $sth->execute || $self->dberror($query);
  1475. $ref = $sth->fetchrow_hashref(NAME_lc);
  1476. for (keys %$ref) { $self->{$_} = $ref->{$_} }
  1477. $sth->finish;
  1478. } else {
  1479. # get date
  1480. $query = qq|
  1481. SELECT current_date AS transdate,
  1482. d.curr AS currencies, d.closedto, d.revtrans
  1483. FROM defaults d|;
  1484. $sth = $dbh->prepare($query);
  1485. $sth->execute || $self->dberror($query);
  1486. $ref = $sth->fetchrow_hashref(NAME_lc);
  1487. for (keys %$ref) { $self->{$_} = $ref->{$_} }
  1488. $sth->finish;
  1489. if (! $self->{"$self->{vc}_id"}) {
  1490. $self->lastname_used($myconfig, $dbh, $vc, $module);
  1491. }
  1492. }
  1493. $self->all_vc($myconfig, $vc, $module, $dbh, $self->{transdate}, $job);
  1494. $self->{dbh}->commit;
  1495. }
  1496. sub lastname_used {
  1497. my ($self, $myconfig, $dbh2, $vc, $module) = @_;
  1498. my $dbh = $self->{dbh};
  1499. my $arap = ($vc eq 'customer') ? "ar" : "ap";
  1500. my $where = "1 = 1";
  1501. my $sth;
  1502. if ($self->{type} =~ /_order/) {
  1503. $arap = 'oe';
  1504. $where = "quotation = '0'";
  1505. }
  1506. if ($self->{type} =~ /_quotation/) {
  1507. $arap = 'oe';
  1508. $where = "quotation = '1'";
  1509. }
  1510. my $query = qq|
  1511. SELECT id
  1512. FROM $arap
  1513. WHERE id IN
  1514. (SELECT MAX(id)
  1515. FROM $arap
  1516. WHERE $where AND ${vc}_id > 0)|;
  1517. my ($trans_id) = $dbh->selectrow_array($query);
  1518. $trans_id *= 1;
  1519. my $DAYS = ($myconfig->{dbdriver} eq 'DB2') ? "DAYS" : "";
  1520. $query = qq|
  1521. SELECT ct.name AS $vc, a.curr AS currency, a.${vc}_id,
  1522. current_date + ct.terms $DAYS AS duedate,
  1523. a.department_id, d.description AS department, ct.notes,
  1524. ct.curr AS currency
  1525. FROM $arap a
  1526. JOIN $vc ct ON (a.${vc}_id = ct.id)
  1527. LEFT JOIN department d ON (a.department_id = d.id)
  1528. WHERE a.id = ?|;
  1529. $sth = $dbh->prepare($query);
  1530. $sth->execute($trans_id)|| $self->dberror($query);
  1531. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1532. for (keys %$ref) { $self->{$_} = $ref->{$_} }
  1533. $sth->finish;
  1534. $dbh->commit;
  1535. }
  1536. sub current_date {
  1537. my ($self, $myconfig, $thisdate, $days) = @_;
  1538. my $dbh = $self->{dbh};
  1539. my $query;
  1540. $days *= 1;
  1541. if ($thisdate) {
  1542. my $dateformat = $myconfig->{dateformat};
  1543. if ($myconfig->{dateformat} !~ /^y/) {
  1544. my @a = split /\D/, $thisdate;
  1545. $dateformat .= "yy" if (length $a[2] > 2);
  1546. }
  1547. if ($thisdate !~ /\D/) {
  1548. $dateformat = 'yyyymmdd';
  1549. }
  1550. $query = qq|SELECT to_date(?, ?)
  1551. + ? AS thisdate
  1552. FROM defaults|;
  1553. @queryargs = ($thisdate, $dateformat, $days);
  1554. } else {
  1555. $query = qq|SELECT current_date AS thisdate
  1556. FROM defaults|;
  1557. @queryargs = ();
  1558. }
  1559. $sth = $dbh->prepare($query);
  1560. $sth->execute(@queryargs);
  1561. ($thisdate) = $sth->fetchrow_array;
  1562. $dbh->commit;
  1563. $thisdate;
  1564. }
  1565. sub like {
  1566. my ($self, $str) = @_;
  1567. if ($str !~ /(%|_)/) {
  1568. if ($str =~ /(^").*("$)/) {
  1569. $str =~ s/(^"|"$)//g;
  1570. } else {
  1571. $str = "%$str%";
  1572. }
  1573. }
  1574. $str =~ s/'/''/g;
  1575. $str;
  1576. }
  1577. sub redo_rows {
  1578. my ($self, $flds, $new, $count, $numrows) = @_;
  1579. my @ndx = ();
  1580. for (1 .. $count) {
  1581. push @ndx, { num => $new->[$_-1]->{runningnumber}, ndx => $_ }
  1582. }
  1583. my $i = 0;
  1584. # fill rows
  1585. foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
  1586. $i++;
  1587. $j = $item->{ndx} - 1;
  1588. for (@{$flds}) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1589. }
  1590. # delete empty rows
  1591. for $i ($count + 1 .. $numrows) {
  1592. for (@{$flds}) { delete $self->{"${_}_$i"} }
  1593. }
  1594. }
  1595. sub get_partsgroup {
  1596. my ($self, $myconfig, $p) = @_;
  1597. my $dbh = $self->{dbh};
  1598. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1599. FROM partsgroup pg
  1600. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1601. my $where;
  1602. my $sortorder = "partsgroup";
  1603. if ($p->{searchitems} eq 'part') {
  1604. $where = qq| WHERE (p.inventory_accno_id > 0
  1605. AND p.income_accno_id > 0)|;
  1606. }
  1607. if ($p->{searchitems} eq 'service') {
  1608. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1609. }
  1610. if ($p->{searchitems} eq 'assembly') {
  1611. $where = qq| WHERE p.assembly = '1'|;
  1612. }
  1613. if ($p->{searchitems} eq 'labor') {
  1614. $where = qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1615. }
  1616. if ($p->{searchitems} eq 'nolabor') {
  1617. $where = qq| WHERE p.income_accno_id > 0|;
  1618. }
  1619. if ($p->{all}) {
  1620. $query = qq|SELECT id, partsgroup
  1621. FROM partsgroup|;
  1622. }
  1623. my @queryargs = ();
  1624. if ($p->{language_code}) {
  1625. $sortorder = "translation";
  1626. $query = qq|
  1627. SELECT DISTINCT pg.id, pg.partsgroup,
  1628. t.description AS translation
  1629. FROM partsgroup pg
  1630. JOIN parts p ON (p.partsgroup_id = pg.id)
  1631. LEFT JOIN translation t ON (t.trans_id = pg.id
  1632. AND t.language_code = ?)|;
  1633. @queryargs = ($p->{language_code});
  1634. }
  1635. $query .= qq| $where ORDER BY $sortorder|;
  1636. my $sth = $dbh->prepare($query);
  1637. $sth->execute(@queryargs)|| $self->dberror($query);
  1638. $self->{all_partsgroup} = ();
  1639. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1640. push @{ $self->{all_partsgroup} }, $ref;
  1641. }
  1642. $sth->finish;
  1643. $dbh->commit;
  1644. }
  1645. sub update_status {
  1646. my ($self, $myconfig) = @_;
  1647. # no id return
  1648. return unless $self->{id};
  1649. my $dbh = $self->{dbh};
  1650. my %queued = split / +/, $self->{queued};
  1651. my $spoolfile = ($queued{$self->{formname}}) ? "'$queued{$self->{formname}}'" : 'NULL';
  1652. my $query = qq|DELETE FROM status
  1653. WHERE formname = ?
  1654. AND trans_id = ?|;
  1655. $sth=$dbh->prepare($query);
  1656. $sth->execute($self->{formname}, $self->{id}) || $self->dberror($query);
  1657. $sth->finish;
  1658. my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
  1659. my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
  1660. $query = qq|
  1661. INSERT INTO status
  1662. (trans_id, printed, emailed, spoolfile, formname)
  1663. VALUES (?, ?, ?, ?, ?)|;
  1664. $sth = $dbh->prepare($query);
  1665. $sth->execute($self->{id}, $printed, $emailed, $spoolfile,
  1666. $self->{formname});
  1667. $sth->finish;
  1668. $dbh->commit;
  1669. }
  1670. sub save_status {
  1671. my ($self) = @_;
  1672. $dbh = $self->{dbh};
  1673. my $formnames = $self->{printed};
  1674. my $emailforms = $self->{emailed};
  1675. my $query = qq|DELETE FROM status
  1676. WHERE trans_id = ?|;
  1677. my $sth = $dbh->prepare($query);
  1678. $sth->execute($form->{id});
  1679. $sth->finish;
  1680. my %queued;
  1681. my $formname;
  1682. if ($self->{queued}) {
  1683. %queued = split / +/, $self->{queued};
  1684. foreach $formname (keys %queued) {
  1685. $printed = ($self->{printed} =~ /$formname/) ? "1" : "0";
  1686. $emailed = ($self->{emailed} =~ /$formname/) ? "1" : "0";
  1687. if ($queued{$formname}) {
  1688. $query = qq|
  1689. INSERT INTO status
  1690. (trans_id, printed, emailed,
  1691. spoolfile, formname)
  1692. VALUES (?, ?, ?, ?, ?)|;
  1693. $sth = $dbh->prepare($query);
  1694. $sth->execute($self->{id}, $pinted, $emailed,
  1695. $queued{$formname}, $formname)
  1696. || $self->dberror($query);
  1697. $sth->finish;
  1698. }
  1699. $formnames =~ s/$formname//;
  1700. $emailforms =~ s/$formname//;
  1701. }
  1702. }
  1703. # save printed, emailed info
  1704. $formnames =~ s/^ +//g;
  1705. $emailforms =~ s/^ +//g;
  1706. my %status = ();
  1707. for (split / +/, $formnames) { $status{$_}{printed} = 1 }
  1708. for (split / +/, $emailforms) { $status{$_}{emailed} = 1 }
  1709. foreach my $formname (keys %status) {
  1710. $printed = ($formnames =~ /$self->{formname}/) ? "1" : "0";
  1711. $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
  1712. $query = qq|
  1713. INSERT INTO status (trans_id, printed, emailed,
  1714. formname)
  1715. VALUES (?, ?, ?, ?)|;
  1716. $sth = $dbh->prepare($query);
  1717. $sth->execute($self->{id}, $printed, $emailed, $formname);
  1718. $sth->finish;
  1719. }
  1720. $dbh->commit;
  1721. }
  1722. sub get_recurring {
  1723. my ($self) = @_;
  1724. $dbh = $self->{dbh};
  1725. my $query = qq/
  1726. SELECT s.*, se.formname || ':' || se.format AS emaila,
  1727. se.message, sp.formname || ':' ||
  1728. sp.format || ':' || sp.printer AS printa
  1729. FROM recurring s
  1730. LEFT JOIN recurringemail se ON (s.id = se.id)
  1731. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  1732. WHERE s.id = ?/;
  1733. my $sth = $dbh->prepare($query);
  1734. $sth->execute($self->{id}) || $form->dberror($query);
  1735. for (qw(email print)) { $self->{"recurring$_"} = "" }
  1736. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1737. for (keys %$ref) { $self->{"recurring$_"} = $ref->{$_} }
  1738. $self->{recurringemail} .= "$ref->{emaila}:";
  1739. $self->{recurringprint} .= "$ref->{printa}:";
  1740. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  1741. }
  1742. $sth->finish;
  1743. chop $self->{recurringemail};
  1744. chop $self->{recurringprint};
  1745. if ($self->{recurringstartdate}) {
  1746. $self->{recurringreference} = $self->escape($self->{recurringreference},1);
  1747. $self->{recurringmessage} = $self->escape($self->{recurringmessage},1);
  1748. for (qw(reference startdate repeat unit howmany
  1749. payment print email message)) {
  1750. $self->{recurring} .= qq|$self->{"recurring$_"},|
  1751. }
  1752. chop $self->{recurring};
  1753. }
  1754. $dbh->commit;
  1755. }
  1756. sub save_recurring {
  1757. my ($self, $dbh2, $myconfig) = @_;
  1758. my $dbh = $self->{dbh};
  1759. my $query;
  1760. $query = qq|DELETE FROM recurring
  1761. WHERE id = ?|;
  1762. $sth = $dbh->prepare($query);
  1763. $sth->execute($self->{id}) || $self->dberror($query);
  1764. $query = qq|DELETE FROM recurringemail
  1765. WHERE id = ?|;
  1766. $sth = $dbh->prepare($query);
  1767. $sth->execute($self->{id}) || $self->dberror($query);
  1768. $query = qq|DELETE FROM recurringprint
  1769. WHERE id = ?|;
  1770. $sth = $dbh->prepare($query);
  1771. $sth->execute($self->{id}) || $self->dberror($query);
  1772. if ($self->{recurring}) {
  1773. my %s = ();
  1774. ($s{reference}, $s{startdate}, $s{repeat}, $s{unit},
  1775. $s{howmany}, $s{payment}, $s{print}, $s{email},
  1776. $s{message})
  1777. = split /,/, $self->{recurring};
  1778. for (qw(reference message)) { $s{$_} = $self->unescape($s{$_}) }
  1779. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  1780. # calculate enddate
  1781. my $advance = $s{repeat} * ($s{howmany} - 1);
  1782. my %interval;
  1783. $interval{'Pg'} =
  1784. "(date '$s{startdate}' + interval '$advance $s{unit}')";
  1785. $query = qq|SELECT $interval{$myconfig->{dbdriver}}
  1786. FROM defaults|;
  1787. my ($enddate) = $dbh->selectrow_array($query);
  1788. # calculate nextdate
  1789. $query = qq|
  1790. SELECT current_date - date ? AS a,
  1791. date ? - current_date AS b
  1792. FROM defaults|;
  1793. $sth = $dbh->prepare($query);
  1794. $sth->execute($s{startdate}, $enddate);
  1795. my ($a, $b) = $sth->fetchrow_array;
  1796. if ($a + $b) {
  1797. $advance = int(($a / ($a + $b)) * ($s{howmany} - 1) + 1) * $s{repeat};
  1798. } else {
  1799. $advance = 0;
  1800. }
  1801. my $nextdate = $enddate;
  1802. if ($advance > 0) {
  1803. if ($advance < ($s{repeat} * $s{howmany})) {
  1804. %interval = ( 'Pg' => "(date '$s{startdate}' + interval '$advance $s{unit}')",
  1805. 'DB2' => qq|(date ('$s{startdate}') + "$advance $s{unit}")|,);
  1806. $interval{Oracle} = $interval{PgPP} = $interval{Pg};
  1807. $query = qq|SELECT $interval{$myconfig->{dbdriver}}
  1808. FROM defaults|;
  1809. ($nextdate) = $dbh->selectrow_array($query);
  1810. }
  1811. } else {
  1812. $nextdate = $s{startdate};
  1813. }
  1814. if ($self->{recurringnextdate}) {
  1815. $nextdate = $self->{recurringnextdate};
  1816. $query = qq|SELECT '$enddate' - date '$nextdate'
  1817. FROM defaults|;
  1818. if ($dbh->selectrow_array($query) < 0) {
  1819. undef $nextdate;
  1820. }
  1821. }
  1822. $self->{recurringpayment} *= 1;
  1823. $query = qq|
  1824. INSERT INTO recurring
  1825. (id, reference, startdate, enddate, nextdate,
  1826. repeat, unit, howmany, payment)
  1827. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  1828. $sth = $dbh->prepare($query);
  1829. $sth->execute($self->{id}, $s{reference}, $s{startdate},
  1830. $enddate, $nextdate, $s{repeat}, $s{unit}, $s{howmany},
  1831. $s{payment});
  1832. my @p;
  1833. my $p;
  1834. my $i;
  1835. my $sth;
  1836. if ($s{email}) {
  1837. # formname:format
  1838. @p = split /:/, $s{email};
  1839. $query = qq|INSERT INTO recurringemail (id, formname, format, message)
  1840. VALUES (?, ?, ?, ?)|;
  1841. $sth = $dbh->prepare($query) || $self->dberror($query);
  1842. for ($i = 0; $i <= $#p; $i += 2) {
  1843. $sth->execute($self->{id}, $p[$i], $p[$i+1],
  1844. $s{message});
  1845. }
  1846. $sth->finish;
  1847. }
  1848. if ($s{print}) {
  1849. # formname:format:printer
  1850. @p = split /:/, $s{print};
  1851. $query = qq|INSERT INTO recurringprint (id, formname, format, printer)
  1852. VALUES (?, ?, ?, ?)|;
  1853. $sth = $dbh->prepare($query) || $self->dberror($query);
  1854. for ($i = 0; $i <= $#p; $i += 3) {
  1855. $p = ($p[$i+2]) ? $p[$i+2] : "";
  1856. $sth->execute($self->{id}, $p[$i], $p[$i+1], $p);
  1857. }
  1858. $sth->finish;
  1859. }
  1860. }
  1861. if ($disconnect) {
  1862. $dbh->commit;
  1863. $dbh->disconnect;
  1864. }
  1865. }
  1866. sub save_intnotes {
  1867. my ($self, $myconfig, $vc) = @_;
  1868. # no id return
  1869. return unless $self->{id};
  1870. my $dbh = $self->dbconnect($myconfig);
  1871. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  1872. $sth=$dbh->prepare($query);
  1873. $sth->execute($self->{intnotes}, $self->{id}) || $self->dberror($query);
  1874. $dbh->commit;
  1875. }
  1876. sub update_defaults {
  1877. my ($self, $myconfig, $fld) = @_;
  1878. my $dbh = $self->{dbh};
  1879. my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
  1880. ($_) = $dbh->selectrow_array($query);
  1881. $_ = "0" unless $_;
  1882. # check for and replace
  1883. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  1884. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  1885. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  1886. # <?lsmb PHONE ?> for customer and vendors
  1887. my $num = $_;
  1888. ($num) = $num =~ /(\d+)/;
  1889. if (defined $num) {
  1890. my $incnum;
  1891. # if we have leading zeros check how long it is
  1892. if ($num =~ /^0/) {
  1893. my $l = length $num;
  1894. $incnum = $num + 1;
  1895. $l -= length $incnum;
  1896. # pad it out with zeros
  1897. my $padzero = "0" x $l;
  1898. $incnum = ("0" x $l) . $incnum;
  1899. } else {
  1900. $incnum = $num + 1;
  1901. }
  1902. s/$num/$incnum/;
  1903. }
  1904. my $dbvar = $_;
  1905. my $var = $_;
  1906. my $str;
  1907. my $param;
  1908. if (/<\?lsmb /) {
  1909. while (/<\?lsmb /) {
  1910. s/<\?lsmb .*? \?>//;
  1911. last unless $&;
  1912. $param = $&;
  1913. $str = "";
  1914. if ($param =~ /<\?lsmb date \?>/i) {
  1915. $str = ($self->split_date($myconfig->{dateformat}, $self->{transdate}))[0];
  1916. $var =~ s/$param/$str/;
  1917. }
  1918. if ($param =~ /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i) {
  1919. my $fld = lc $&;
  1920. $fld =~ s/<\?lsmb //;
  1921. if ($fld =~ /name/) {
  1922. if ($self->{type}) {
  1923. $fld = $self->{vc};
  1924. }
  1925. }
  1926. my $p = $param;
  1927. $p =~ s/(<|>|%)//g;
  1928. my @p = split / /, $p;
  1929. my @n = split / /, uc $self->{$fld};
  1930. if ($#p > 0) {
  1931. for (my $i = 1; $i <= $#p; $i++) {
  1932. $str .= substr($n[$i-1], 0, $p[$i]);
  1933. }
  1934. } else {
  1935. ($str) = split /--/, $self->{$fld};
  1936. }
  1937. $var =~ s/$param/$str/;
  1938. $var =~ s/\W//g if $fld eq 'phone';
  1939. }
  1940. if ($param =~ /<\?lsmb (yy|mm|dd)/i) {
  1941. my $p = $param;
  1942. $p =~ s/(<|>|%)//g;
  1943. my $spc = $p;
  1944. $spc =~ s/\w//g;
  1945. $spc = substr($spc, 0, 1);
  1946. my %d = ( yy => 1, mm => 2, dd => 3 );
  1947. my @p = ();
  1948. my @a = $self->split_date($myconfig->{dateformat}, $self->{transdate});
  1949. for (sort keys %d) { push @p, $a[$d{$_}] if ($p =~ /$_/) }
  1950. $str = join $spc, @p;
  1951. $var =~ s/$param/$str/;
  1952. }
  1953. if ($param =~ /<\?lsmb curr/i) {
  1954. $var =~ s/$param/$self->{currency}/;
  1955. }
  1956. }
  1957. }
  1958. $query = qq|UPDATE defaults
  1959. SET $fld = ?|;
  1960. $sth = $dbh->prepare($query);
  1961. $sth->execute($dbvar) || $self->dberror($query);
  1962. $dbh->commit;
  1963. $var;
  1964. }
  1965. sub db_prepare_vars {
  1966. for (@_){
  1967. if (!$self->{$_} and $self->{$_} != 0){
  1968. $self->{$_} = undef;
  1969. }
  1970. }
  1971. }
  1972. sub split_date {
  1973. my ($self, $dateformat, $date) = @_;
  1974. my @d = localtime;
  1975. my $mm;
  1976. my $dd;
  1977. my $yy;
  1978. my $rv;
  1979. if (! $date) {
  1980. $dd = $d[3];
  1981. $mm = ++$d[4];
  1982. $yy = substr($d[5],-2);
  1983. $mm = substr("0$mm", -2);
  1984. $dd = substr("0$dd", -2);
  1985. }
  1986. if ($dateformat =~ /^yy/) {
  1987. if ($date) {
  1988. if ($date =~ /\D/) {
  1989. ($yy, $mm, $dd) = split /\D/, $date;
  1990. $mm *= 1;
  1991. $dd *= 1;
  1992. $mm = substr("0$mm", -2);
  1993. $dd = substr("0$dd", -2);
  1994. $yy = substr($yy, -2);
  1995. $rv = "$yy$mm$dd";
  1996. } else {
  1997. $rv = $date;
  1998. }
  1999. } else {
  2000. $rv = "$yy$mm$dd";
  2001. }
  2002. }
  2003. if ($dateformat =~ /^mm/) {
  2004. if ($date) {
  2005. if ($date =~ /\D/) {
  2006. ($mm, $dd, $yy) = split /\D/, $date;
  2007. $mm *= 1;
  2008. $dd *= 1;
  2009. $mm = substr("0$mm", -2);
  2010. $dd = substr("0$dd", -2);
  2011. $yy = substr($yy, -2);
  2012. $rv = "$mm$dd$yy";
  2013. } else {
  2014. $rv = $date;
  2015. }
  2016. } else {
  2017. $rv = "$mm$dd$yy";
  2018. }
  2019. }
  2020. if ($dateformat =~ /^dd/) {
  2021. if ($date) {
  2022. if ($date =~ /\D/) {
  2023. ($dd, $mm, $yy) = split /\D/, $date;
  2024. $mm *= 1;
  2025. $dd *= 1;
  2026. $mm = substr("0$mm", -2);
  2027. $dd = substr("0$dd", -2);
  2028. $yy = substr($yy, -2);
  2029. $rv = "$dd$mm$yy";
  2030. } else {
  2031. $rv = $date;
  2032. }
  2033. } else {
  2034. $rv = "$dd$mm$yy";
  2035. }
  2036. }
  2037. ($rv, $yy, $mm, $dd);
  2038. }
  2039. sub from_to {
  2040. my ($self, $yy, $mm, $interval) = @_;
  2041. use Time::Local;
  2042. my @t;
  2043. my $dd = 1;
  2044. my $fromdate = "$yy${mm}01";
  2045. my $bd = 1;
  2046. if (defined $interval) {
  2047. if ($interval == 12) {
  2048. $yy++;
  2049. } else {
  2050. if (($mm += $interval) > 12) {
  2051. $mm -= 12;
  2052. $yy++;
  2053. }
  2054. if ($interval == 0) {
  2055. @t = localtime(time);
  2056. $dd = $t[3];
  2057. $mm = $t[4] + 1;
  2058. $yy = $t[5] + 1900;
  2059. $bd = 0;
  2060. }
  2061. }
  2062. } else {
  2063. if (++$mm > 12) {
  2064. $mm -= 12;
  2065. $yy++;
  2066. }
  2067. }
  2068. $mm--;
  2069. @t = localtime(timelocal(0,0,0,$dd,$mm,$yy) - $bd);
  2070. $t[4]++;
  2071. $t[4] = substr("0$t[4]",-2);
  2072. $t[3] = substr("0$t[3]",-2);
  2073. $t[5] += 1900;
  2074. ($fromdate, "$t[5]$t[4]$t[3]");
  2075. }
  2076. sub audittrail {
  2077. my ($self, $dbh, $myconfig, $audittrail) = @_;
  2078. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2079. my $query;
  2080. my $rv;
  2081. my $disconnect;
  2082. if (! $dbh) {
  2083. $dbh = $self->dbconnect($myconfig);
  2084. $disconnect = 1;
  2085. }
  2086. # if we have an id add audittrail, otherwise get a new timestamp
  2087. my @queryargs;
  2088. if ($audittrail->{id}) {
  2089. $query = qq|SELECT audittrail FROM defaults|;
  2090. if ($dbh->selectrow_array($query)) {
  2091. my ($null, $employee_id) = $self->get_employee($dbh);
  2092. if ($self->{audittrail} && !$myconfig) {
  2093. chop $self->{audittrail};
  2094. my @a = split /\|/, $self->{audittrail};
  2095. my %newtrail = ();
  2096. my $key;
  2097. my $i;
  2098. my @flds = qw(tablename reference formname action transdate);
  2099. # put into hash and remove dups
  2100. while (@a) {
  2101. $key = "$a[2]$a[3]";
  2102. $i = 0;
  2103. $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
  2104. splice @a, 0, 5;
  2105. }
  2106. $query = qq|
  2107. INSERT INTO audittrail
  2108. (trans_id, tablename, reference,
  2109. formname, action, transdate,
  2110. employee_id)
  2111. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2112. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2113. foreach $key (sort { $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate} } keys %newtrail) {
  2114. $i = 2;
  2115. $sth->bind_param(1, $audittrail->{id});
  2116. for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
  2117. $sth->bind_param($i++, $employee_id);
  2118. $sth->execute || $self->dberror;
  2119. $sth->finish;
  2120. }
  2121. }
  2122. if ($audittrail->{transdate}) {
  2123. $query = qq|
  2124. INSERT INTO audittrail (
  2125. trans_id, tablename, reference,
  2126. formname, action, employee_id,
  2127. transdate)
  2128. VALUES (?, ?, ?, ?, ?, ?)|;
  2129. @queryargs = (
  2130. $audittrail->{id},
  2131. $audittrail->{tablename},
  2132. $audittrail->{reference},
  2133. $audittrail->{formname},
  2134. $audittrail->{action}.
  2135. $employee_id,
  2136. $audittrail->{transdate}
  2137. );
  2138. } else {
  2139. $query = qq|
  2140. INSERT INTO audittrail
  2141. (trans_id, tablename, reference,
  2142. formname, action, employee_id)
  2143. VALUES (?, ?, ?, ?, ?)|;
  2144. @queryargs = (
  2145. $audittrail->{id},
  2146. $audittrail->{tablename},
  2147. $audittrail->{reference},
  2148. $audittrail->{formname},
  2149. $audittrail->{action}.
  2150. $employee_id,
  2151. );
  2152. }
  2153. $sth = $dbh->prepare($query);
  2154. $sth->execute(@queryargs)||$self->dberror($query);
  2155. }
  2156. } else {
  2157. $query = qq|SELECT current_timestamp FROM defaults|;
  2158. my ($timestamp) = $dbh->selectrow_array($query);
  2159. $rv = "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2160. }
  2161. $dbh->commit;
  2162. $rv;
  2163. }
  2164. package Locale;
  2165. sub new {
  2166. my ($type, $country, $NLS_file) = @_;
  2167. my $self = {};
  2168. %self = ();
  2169. if ($country && -d "locale/$country") {
  2170. $self->{countrycode} = $country;
  2171. eval { require "locale/$country/$NLS_file"; };
  2172. }
  2173. $self->{NLS_file} = $NLS_file;
  2174. $self->{charset} = $self{charset};
  2175. push @{ $self->{LONG_MONTH} }, ("January", "February", "March", "April", "May ", "June", "July", "August", "September", "October", "November", "December");
  2176. push @{ $self->{SHORT_MONTH} }, (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec));
  2177. bless $self, $type;
  2178. }
  2179. sub text {
  2180. my ($self, $text) = @_;
  2181. return (exists $self{texts}{$text}) ? $self{texts}{$text} : $text;
  2182. }
  2183. sub findsub {
  2184. my ($self, $text) = @_;
  2185. if (exists $self{subs}{$text}) {
  2186. $text = $self{subs}{$text};
  2187. } else {
  2188. if ($self->{countrycode} && $self->{NLS_file}) {
  2189. Form->error("$text not defined in locale/$self->{countrycode}/$self->{NLS_file}");
  2190. }
  2191. }
  2192. $text;
  2193. }
  2194. sub date {
  2195. my ($self, $myconfig, $date, $longformat) = @_;
  2196. my $longdate = "";
  2197. my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
  2198. if ($date) {
  2199. # get separator
  2200. $spc = $myconfig->{dateformat};
  2201. $spc =~ s/\w//g;
  2202. $spc = substr($spc, 0, 1);
  2203. if ($date =~ /\D/) {
  2204. if ($myconfig->{dateformat} =~ /^yy/) {
  2205. ($yy, $mm, $dd) = split /\D/, $date;
  2206. }
  2207. if ($myconfig->{dateformat} =~ /^mm/) {
  2208. ($mm, $dd, $yy) = split /\D/, $date;
  2209. }
  2210. if ($myconfig->{dateformat} =~ /^dd/) {
  2211. ($dd, $mm, $yy) = split /\D/, $date;
  2212. }
  2213. } else {
  2214. $date = substr($date, 2);
  2215. ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
  2216. }
  2217. $dd *= 1;
  2218. $mm--;
  2219. $yy += 2000 if length $yy == 2;
  2220. if ($myconfig->{dateformat} =~ /^dd/) {
  2221. $mm++;
  2222. $dd = substr("0$dd", -2);
  2223. $mm = substr("0$mm", -2);
  2224. $longdate = "$dd$spc$mm$spc$yy";
  2225. if (defined $longformat) {
  2226. $longdate = "$dd";
  2227. $longdate .= ($spc eq '.') ? ". " : " ";
  2228. $longdate .= &text($self, $self->{$longmonth}[--$mm])." $yy";
  2229. }
  2230. } elsif ($myconfig->{dateformat} =~ /^yy/) {
  2231. $mm++;
  2232. $dd = substr("0$dd", -2);
  2233. $mm = substr("0$mm", -2);
  2234. $longdate = "$yy$spc$mm$spc$dd";
  2235. if (defined $longformat) {
  2236. $longdate = &text($self, $self->{$longmonth}[--$mm])." $dd $yy";
  2237. }
  2238. } else {
  2239. $mm++;
  2240. $dd = substr("0$dd", -2);
  2241. $mm = substr("0$mm", -2);
  2242. $longdate = "$mm$spc$dd$spc$yy";
  2243. if (defined $longformat) {
  2244. $longdate = &text($self, $self->{$longmonth}[--$mm])." $dd $yy";
  2245. }
  2246. }
  2247. }
  2248. $longdate;
  2249. }
  2250. 1;