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