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