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