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