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