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