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