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