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