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