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