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