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