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