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