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