summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: 6dcaec79fd4607a490875c6f0eec3aef7f58cbf5 (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\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}) {
  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. unless (chdir("${LedgerSMB::Sysconfig::userspath}")) {
  587. $err = $!;
  588. $self->cleanup;
  589. $self->error("chdir : $err");
  590. }
  591. $self->{tmpfile} =~ s/${LedgerSMB::Sysconfig::userspath}\///g;
  592. $self->{errfile} = $self->{tmpfile};
  593. $self->{errfile} =~ s/tex$/err/;
  594. my $r = 1;
  595. if ($self->{format} eq 'postscript') {
  596. system("latex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  597. while ($self->rerun_latex) {
  598. system("latex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  599. last if ++$r > 4;
  600. }
  601. $self->{tmpfile} =~ s/tex$/dvi/;
  602. $self->error($self->cleanup) if ! (-f $self->{tmpfile});
  603. system("dvips $self->{tmpfile} -o -q");
  604. $self->error($self->cleanup."dvips : $!") if ($?);
  605. $self->{tmpfile} =~ s/dvi$/ps/;
  606. }
  607. if ($self->{format} eq 'pdf') {
  608. system("pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  609. while ($self->rerun_latex) {
  610. system("pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  611. last if ++$r > 4;
  612. }
  613. $self->{tmpfile} =~ s/tex$/pdf/;
  614. $self->error($self->cleanup) if ! (-f $self->{tmpfile});
  615. }
  616. }
  617. if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
  618. if ($self->{media} eq 'email') {
  619. use LedgerSMB::Mailer;
  620. my $mail = new Mailer;
  621. for (qw(cc bcc subject message version format charset)) {
  622. $mail->{$_} = $self->{$_}
  623. }
  624. $mail->{to} = qq|$self->{email}|;
  625. $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
  626. $mail->{notify} = $self->{notify};
  627. $mail->{fileid} = "$fileid.";
  628. # if we send html or plain text inline
  629. if (($self->{format} =~ /(html|txt)/) &&
  630. ($self->{sendmode} eq 'inline')) {
  631. my $br = "";
  632. $br = "<br>" if $self->{format} eq 'html';
  633. $mail->{contenttype} = "text/$self->{format}";
  634. $mail->{message} =~ s/\r?\n/$br\n/g;
  635. $myconfig->{signature} =~ s/\\n/$br\n/g;
  636. $mail->{message} .= "$br\n-- $br\n$myconfig->{signature}\n$br" if $myconfig->{signature};
  637. unless (open(IN, $self->{tmpfile})) {
  638. $err = $!;
  639. $self->cleanup;
  640. $self->error("$self->{tmpfile} : $err");
  641. }
  642. while (<IN>) {
  643. $mail->{message} .= $_;
  644. }
  645. close(IN);
  646. } else {
  647. @{ $mail->{attachments} } = ($self->{tmpfile});
  648. $myconfig->{signature} =~ s/\\n/\n/g;
  649. $mail->{message} .= "\n-- \n$myconfig->{signature}" if $myconfig->{signature};
  650. }
  651. if ($err = $mail->send) {
  652. $self->cleanup;
  653. $self->error($err);
  654. }
  655. } else {
  656. $self->{OUT} = $out;
  657. unless (open(IN, $self->{tmpfile})) {
  658. $err = $!;
  659. $self->cleanup;
  660. $self->error("$self->{tmpfile} : $err");
  661. }
  662. binmode(IN);
  663. $self->{copies} = 1 if $self->{media} =~ /(screen|email|queue)/;
  664. chdir("$self->{cwd}");
  665. for my $i (1 .. $self->{copies}) {
  666. if ($self->{OUT}) {
  667. unless (open(OUT, $self->{OUT})) {
  668. $err = $!;
  669. $self->cleanup;
  670. $self->error("$self->{OUT} : $err");
  671. }
  672. } else {
  673. # launch application
  674. print qq|Content-Type: application/$self->{format}\n|.
  675. qq|Content-Disposition: attachment; filename="$self->{tmpfile}"\n\n|;
  676. unless (open(OUT, ">-")) {
  677. $err = $!;
  678. $self->cleanup;
  679. $self->error("STDOUT : $err");
  680. }
  681. }
  682. binmode(OUT);
  683. while (<IN>) {
  684. print OUT $_;
  685. }
  686. close(OUT);
  687. seek IN, 0, 0;
  688. }
  689. close(IN);
  690. }
  691. $self->cleanup;
  692. }
  693. }
  694. sub format_line {
  695. my $self = shift;
  696. $_ = shift;
  697. my $i = shift;
  698. my $str;
  699. my $newstr;
  700. my $pos;
  701. my $l;
  702. my $lf;
  703. my $line;
  704. my $var = "";
  705. my %a;
  706. my $offset;
  707. my $pad;
  708. my $item;
  709. while (/<\?lsmb (.+?) \?>/) {
  710. %a = ();
  711. foreach $item (split / /, $1) {
  712. my ($key, $value) = split /=/, $item;
  713. if ($value ne "") {
  714. $a{$key} = $value;
  715. } else {
  716. $var = $item;
  717. }
  718. }
  719. $str = (defined $i) ? $self->{$var}[$i] : $self->{$var};
  720. $newstr = $str;
  721. $self->{countitemnotes} = 1 if $var eq 'itemnotes';
  722. $var = $1;
  723. if ($var =~ /^if\s+not\s+/) {
  724. if ($str) {
  725. $var =~ s/if\s+not\s+//;
  726. s/<\?lsmb if\s+not\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  727. } else {
  728. s/<\?lsmb $var \?>//;
  729. }
  730. next;
  731. }
  732. if ($var =~ /^if\s+/) {
  733. if ($str) {
  734. s/<\?lsmb $var \?>//;
  735. } else {
  736. $var =~ s/if\s+//;
  737. s/<\?lsmb if\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  738. }
  739. next;
  740. }
  741. if ($var =~ /^end\s+/) {
  742. s/<\?lsmb $var \?>//;
  743. next;
  744. }
  745. if ($a{align} || $a{width} || $a{offset}) {
  746. $newstr = "";
  747. $offset = 0;
  748. $lf = "";
  749. foreach $str (split /\n/, $str) {
  750. $line = $str;
  751. $l = length $str;
  752. do {
  753. if (($pos = length $str) > $a{width}) {
  754. if (($pos = rindex $str, " ", $a{width}) > 0) {
  755. $line = substr($str, 0, $pos);
  756. }
  757. $pos = length $str if $pos == -1;
  758. }
  759. $l = length $line;
  760. # pad left, right or center
  761. $l = ($a{width} - $l);
  762. $pad = " " x $l;
  763. if ($a{align} =~ /right/i) {
  764. $line = " " x $offset . $pad . $line;
  765. }
  766. if ($a{align} =~ /left/i) {
  767. $line = " " x $offset . $line . $pad;
  768. }
  769. if ($a{align} =~ /center/i) {
  770. $pad = " " x ($l/2);
  771. $line = " " x $offset . $pad . $line;
  772. $pad = " " x ($l/2);
  773. $line .= $pad;
  774. }
  775. $newstr .= "$lf$line";
  776. $str = substr($str, $pos + 1);
  777. $line = $str;
  778. $lf = "\n";
  779. $offset = $a{offset};
  780. } while ($str);
  781. }
  782. }
  783. s/<\?lsmb (.+?) \?>/$newstr/;
  784. }
  785. $_;
  786. }
  787. sub cleanup {
  788. my $self = shift;
  789. chdir("$self->{tmpdir}");
  790. my @err = ();
  791. if (-f "$self->{errfile}") {
  792. open(FH, "$self->{errfile}");
  793. @err = <FH>;
  794. close(FH);
  795. }
  796. if ($self->{tmpfile}) {
  797. # strip extension
  798. $self->{tmpfile} =~ s/\.\w+$//g;
  799. my $tmpfile = $self->{tmpfile};
  800. unlink(<$tmpfile.*>);
  801. }
  802. chdir("$self->{cwd}");
  803. "@err";
  804. }
  805. sub rerun_latex {
  806. my $self = shift;
  807. my $a = 0;
  808. if (-f "$self->{errfile}") {
  809. open(FH, "$self->{errfile}");
  810. $a = grep /(longtable Warning:|Warning:.*?LastPage)/, <FH>;
  811. close(FH);
  812. }
  813. $a;
  814. }
  815. sub format_string {
  816. my ($self, @fields) = @_;
  817. my $format = $self->{format};
  818. if ($self->{format} =~ /(postscript|pdf)/) {
  819. $format = 'tex';
  820. }
  821. my %replace = (
  822. 'order' => {
  823. html => [ '<', '>', '\n', '\r' ],
  824. txt => [ '\n', '\r' ],
  825. tex => [ quotemeta('\\'), '&', '\n','\r',
  826. '\$', '%', '_', '#',
  827. quotemeta('^'), '{', '}', '<', '>', '£'
  828. ] },
  829. html => { '<' => '&lt;', '>' => '&gt;','\n' => '<br />',
  830. '\r' => '<br />' },
  831. txt => { '\n' => "\n", '\r' => "\r" },
  832. tex => {'&' => '\&', '$' => '\$', '%' => '\%', '_' => '\_',
  833. '#' => '\#', quotemeta('^') => '\^\\', '{' => '\{',
  834. '}' => '\}', '<' => '$<$', '>' => '$>$',
  835. '\n' => '\newline ', '\r' => '\newline ',
  836. '£' => '\pounds ', quotemeta('\\') => '/'}
  837. );
  838. my $key;
  839. foreach $key (@{ $replace{order}{$format} }) {
  840. for (@fields) { $self->{$_} =~ s/$key/$replace{$format}{$key}/g }
  841. }
  842. }
  843. sub datetonum {
  844. my ($self, $myconfig, $date, $picture) = @_;
  845. if ($date && $date =~ /\D/) {
  846. if ($myconfig->{dateformat} =~ /^yy/) {
  847. ($yy, $mm, $dd) = split /\D/, $date;
  848. }
  849. if ($myconfig->{dateformat} =~ /^mm/) {
  850. ($mm, $dd, $yy) = split /\D/, $date;
  851. }
  852. if ($myconfig->{dateformat} =~ /^dd/) {
  853. ($dd, $mm, $yy) = split /\D/, $date;
  854. }
  855. $dd *= 1;
  856. $mm *= 1;
  857. $yy += 2000 if length $yy == 2;
  858. $dd = substr("0$dd", -2);
  859. $mm = substr("0$mm", -2);
  860. $date = "$yy$mm$dd";
  861. }
  862. $date;
  863. }
  864. sub add_date {
  865. my ($self, $myconfig, $date, $repeat, $unit) = @_;
  866. use Time::Local;
  867. my $diff = 0;
  868. my $spc = $myconfig->{dateformat};
  869. $spc =~ s/\w//g;
  870. $spc = substr($spc, 0, 1);
  871. if ($date) {
  872. if ($date =~ /\D/) {
  873. if ($myconfig->{dateformat} =~ /^yy/) {
  874. ($yy, $mm, $dd) = split /\D/, $date;
  875. }
  876. if ($myconfig->{dateformat} =~ /^mm/) {
  877. ($mm, $dd, $yy) = split /\D/, $date;
  878. }
  879. if ($myconfig->{dateformat} =~ /^dd/) {
  880. ($dd, $mm, $yy) = split /\D/, $date;
  881. }
  882. } else {
  883. # ISO
  884. ($yy, $mm, $dd) =~ /(....)(..)(..)/;
  885. }
  886. if ($unit eq 'days') {
  887. $diff = $repeat * 86400;
  888. }
  889. if ($unit eq 'weeks') {
  890. $diff = $repeat * 604800;
  891. }
  892. if ($unit eq 'months') {
  893. $diff = $mm + $repeat;
  894. my $whole = int($diff / 12);
  895. $yy += $whole;
  896. $mm = ($diff % 12) + 1;
  897. $diff = 0;
  898. }
  899. if ($unit eq 'years') {
  900. $yy++;
  901. }
  902. $mm--;
  903. @t = localtime(timelocal(0,0,0,$dd,$mm,$yy) + $diff);
  904. $t[4]++;
  905. $mm = substr("0$t[4]",-2);
  906. $dd = substr("0$t[3]",-2);
  907. $yy = $t[5] + 1900;
  908. if ($date =~ /\D/) {
  909. if ($myconfig->{dateformat} =~ /^yy/) {
  910. $date = "$yy$spc$mm$spc$dd";
  911. }
  912. if ($myconfig->{dateformat} =~ /^mm/) {
  913. $date = "$mm$spc$dd$spc$yy";
  914. }
  915. if ($myconfig->{dateformat} =~ /^dd/) {
  916. $date = "$dd$spc$mm$spc$yy";
  917. }
  918. } else {
  919. $date = "$yy$mm$dd";
  920. }
  921. }
  922. $date;
  923. }
  924. sub print_button {
  925. my ($self, $button, $name) = @_;
  926. 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|;
  927. }
  928. # Database routines used throughout
  929. sub db_init {
  930. my ($self, $myconfig) = @_;
  931. $self->{dbh} = $self->dbconnect_noauto($myconfig) || $self->dberror();
  932. my $query =
  933. "SELECT t.extends,
  934. coalesce (t.table_name, 'custom_' || extends)
  935. || ':' || f.field_name as field_def
  936. FROM custom_table_catalog t
  937. JOIN custom_field_catalog f USING (table_id)";
  938. my $sth = $self->{dbh}->prepare($query);
  939. $sth->execute;
  940. my $ref;
  941. while ($ref = $sth->fetchrow_hashref(NAME_lc)){
  942. push @{$self->{custom_db_fields}{$ref->{extends}}},
  943. $ref->{field_def};
  944. }
  945. }
  946. sub run_custom_queries {
  947. my ($self, $tablename, $query_type, $linenum) = @_;
  948. my $dbh = $self->{dbh};
  949. if ($query_type !~ /^(select|insert|update)$/i){
  950. $self->error($locale->text(
  951. "Passed incorrect query type to get_cutstom_queries."
  952. ));
  953. }
  954. my @rc;
  955. my %temphash;
  956. my @templist;
  957. my @elements;
  958. my $query;
  959. my $ins_values;
  960. if ($linenum){
  961. $linenum = "_$linenum";
  962. }
  963. $query_type = uc($query_type);
  964. for (@{$self->{custom_db_fields}{$tablename}}){
  965. @elements = split (/:/, $_);
  966. push @{$temphash{$elements[0]}}, $elements[1];
  967. }
  968. for (keys %temphash){
  969. my @data;
  970. my $ins_values;
  971. $query = "$query_type ";
  972. if ($query_type eq 'UPDATE'){
  973. $query = "DELETE FROM $_ WHERE row_id = ?";
  974. my $sth = $dbh->prepare($query);
  975. $sth->execute->($self->{"id"."$linenum"})
  976. || $self->dberror($query);
  977. } elsif ($query_type eq 'INSERT'){
  978. $query .= " INTO $_ (";
  979. }
  980. my $first = 1;
  981. for (@{$temphash{$_}}){
  982. $query .= "$_";
  983. if ($query_type eq 'UPDATE'){
  984. $query .= '= ?';
  985. }
  986. $ins_values .= "?, ";
  987. $query .= ", ";
  988. $first = 0;
  989. if ($query_type eq 'UPDATE' or $query_type eq 'INSERT'){
  990. push @data, $self->{"$_$linenum"};
  991. }
  992. }
  993. if ($query_type ne 'INSERT'){
  994. $query =~ s/, $//;
  995. }
  996. if ($query_type eq 'SELECT'){
  997. $query .= " FROM $_";
  998. }
  999. if ($query_type eq 'SELECT' or $query_type eq 'UPDATE'){
  1000. $query .= " WHERE row_id = ?";
  1001. }
  1002. if ($query_type eq 'INSERT'){
  1003. $query .= " row_id) VALUES ($ins_values ?)";
  1004. }
  1005. if ($query_type eq 'SELECT'){
  1006. push @rc, [ $query ];
  1007. } else {
  1008. unshift (@data, $query);
  1009. push @rc, [ @data ];
  1010. }
  1011. }
  1012. if ($query_type eq 'INSERT'){
  1013. for (@rc){
  1014. $query = shift (@{$_});
  1015. $sth = $dbh->prepare($query)
  1016. || $self->db_error($query);
  1017. $sth->execute(@{$_}, $self->{id})
  1018. || $self->dberror($query);;
  1019. $sth->finish;
  1020. $did_insert = 1;
  1021. }
  1022. } elsif ($query_type eq 'UPDATE'){
  1023. @rc = $self->run_custom_queries(
  1024. $tablename, 'INSERT', $linenum);
  1025. } elsif ($query_type eq 'SELECT'){
  1026. for (@rc){
  1027. $query = shift @{$_};
  1028. $sth = $self->{dbh}->prepare($query);
  1029. $sth->execute($self->{id});
  1030. $ref = $sth->fetchrow_hashref(NAME_lc);
  1031. for (keys %{$ref}){
  1032. $self->{$_} = $ref->{$_};
  1033. }
  1034. }
  1035. }
  1036. @rc;
  1037. }
  1038. sub dbconnect {
  1039. my ($self, $myconfig) = @_;
  1040. # connect to database
  1041. my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}) or $self->dberror;
  1042. # set db options
  1043. if ($myconfig->{dboptions}) {
  1044. $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
  1045. }
  1046. $dbh;
  1047. }
  1048. sub dbconnect_noauto {
  1049. my ($self, $myconfig) = @_;
  1050. # connect to database
  1051. $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, {AutoCommit => 0}) or $self->dberror;
  1052. # set db options
  1053. if ($myconfig->{dboptions}) {
  1054. $dbh->do($myconfig->{dboptions});
  1055. }
  1056. $dbh;
  1057. }
  1058. sub dbquote {
  1059. my ($self, $var) = @_;
  1060. if ($var eq ''){
  1061. $_ = "NULL";
  1062. } else {
  1063. $_ = $self->{dbh}->quote($var);
  1064. }
  1065. $_;
  1066. }
  1067. sub update_balance {
  1068. # This is a dangerous private function. All apps calling it must
  1069. # be careful to avoid SQL injection issues
  1070. my ($self, $dbh, $table, $field, $where, $value) = @_;
  1071. # if we have a value, go do it
  1072. if ($value) {
  1073. # retrieve balance from table
  1074. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  1075. my ($balance) = $dbh->selectrow_array($query);
  1076. $balance += $value;
  1077. # update balance
  1078. $query = "UPDATE $table SET $field = $balance WHERE $where";
  1079. $dbh->do($query) || $self->dberror($query);
  1080. }
  1081. }
  1082. sub update_exchangerate {
  1083. my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
  1084. # some sanity check for currency
  1085. return if ($curr eq "");
  1086. my $query = qq|
  1087. SELECT curr
  1088. FROM exchangerate
  1089. WHERE curr = ?
  1090. AND transdate = ?
  1091. FOR UPDATE|;
  1092. my $sth = $self->{dbh}->prepare($query);
  1093. $sth->execute($curr, $transdate) || $self->dberror($query);
  1094. my $set;
  1095. my @queryargs;
  1096. if ($buy && $sell) {
  1097. $set = "buy = ?, sell = ?";
  1098. @queryargs = ($buy, $sell);
  1099. } elsif ($buy) {
  1100. $set = "buy = ?";
  1101. @queryargs = ($buy);
  1102. } elsif ($sell) {
  1103. $set = "sell = ?";
  1104. @queryargs = ($sell);
  1105. }
  1106. if ($sth->fetchrow_array) {
  1107. $query = qq|UPDATE exchangerate
  1108. SET $set
  1109. WHERE curr = ?
  1110. AND transdate = ?|;
  1111. push (@queryargs, $curr, $transdate);
  1112. } else {
  1113. $query = qq|
  1114. INSERT INTO exchangerate (
  1115. curr, buy, sell, transdate)
  1116. VALUES (?, ?, ?, ?)|;
  1117. @queryargs = ($curr, $buy, $sell, $transdate);
  1118. }
  1119. $sth->finish;
  1120. $sth = $self->{dbh}->prepare($query);
  1121. $sth->execute(@queryargs) || $self->dberror($query);
  1122. }
  1123. sub save_exchangerate {
  1124. my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
  1125. my ($buy, $sell) = (0, 0);
  1126. $buy = $rate if $fld eq 'buy';
  1127. $sell = $rate if $fld eq 'sell';
  1128. $self->update_exchangerate(
  1129. $self->{dbh},
  1130. $currency,
  1131. $transdate,
  1132. $buy,
  1133. $sell);
  1134. $dbh->commit;
  1135. }
  1136. sub get_exchangerate {
  1137. my ($self, $dbh, $curr, $transdate, $fld) = @_;
  1138. my $exchangerate = 1;
  1139. if ($transdate) {
  1140. my $query = qq|
  1141. SELECT $fld FROM exchangerate
  1142. WHERE curr = ? AND transdate = ?|;
  1143. $sth = $self->{dbh}->prepare($query);
  1144. $sth->execute($curr, $transdate);
  1145. ($exchangerate) = $sth->fetchrow_array;
  1146. }
  1147. $exchangerate;
  1148. $sth->finish;
  1149. $self->{dbh}->commit;
  1150. }
  1151. sub check_exchangerate {
  1152. my ($self, $myconfig, $currency, $transdate, $fld) = @_;
  1153. return "" unless $transdate;
  1154. my $query = qq|
  1155. SELECT $fld
  1156. FROM exchangerate
  1157. WHERE curr = ? AND transdate = ?|;
  1158. my $sth = $self->{dbh}->prepare($query);
  1159. $sth->execute($currenct, $transdate);
  1160. my ($exchangerate) = $sth->fetchrow_array;
  1161. $sth->finish;
  1162. $self->{dbh}->commit;
  1163. $exchangerate;
  1164. }
  1165. sub add_shipto {
  1166. my ($self, $dbh, $id) = @_;
  1167. my $shipto;
  1168. foreach my $item (qw(name address1 address2 city state
  1169. zipcode country contact phone fax email)) {
  1170. if ($self->{"shipto$item"} ne "") {
  1171. $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
  1172. }
  1173. }
  1174. if ($shipto) {
  1175. my $query = qq|
  1176. INSERT INTO shipto
  1177. (trans_id, shiptoname, shiptoaddress1,
  1178. shiptoaddress2, shiptocity, shiptostate,
  1179. shiptozipcode, shiptocountry, shiptocontact,
  1180. shiptophone, shiptofax, shiptoemail)
  1181. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1182. |;
  1183. $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  1184. $sth->execute(
  1185. $id, $self->{shiptoname}, $self->{shiptoaddress1},
  1186. $self->{shiptoaddress2}, $self->{shiptocity},
  1187. $self->{shiptostate}, $self->{shiptostate},
  1188. $self->{shiptozipcode}, $self->{shiptocountry},
  1189. $self->{shiptocontact}, $self->{shiptophone},
  1190. $self->{shiptofax}, $self->{shiptoemail}
  1191. ) || $self->dberror($query);
  1192. $sth->finish;
  1193. $self->{dbh}->commit;
  1194. }
  1195. }
  1196. sub get_employee {
  1197. my ($self, $dbh) = @_;
  1198. my $login = $self->{login};
  1199. $login =~ s/@.*//;
  1200. my $query = qq|SELECT name, id
  1201. FROM employee
  1202. WHERE login = ?|;
  1203. $sth = $self->{dbh}->prepare($query);
  1204. $sth->execute($login);
  1205. my (@a) = $sth->fetchrow_array();
  1206. $a[1] *= 1;
  1207. $sth->finish;
  1208. $self->{dbh}->commit;
  1209. @a;
  1210. }
  1211. # this sub gets the id and name from $table
  1212. sub get_name {
  1213. my ($self, $myconfig, $table, $transdate) = @_;
  1214. # connect to database
  1215. my @queryargs;
  1216. my $where;
  1217. if ($transdate) {
  1218. $where = qq|
  1219. AND (startdate IS NULL OR startdate <= ?)
  1220. AND (enddate IS NULL OR enddate >= ?)|;
  1221. @queryargs = ($transdate, $transdate);
  1222. }
  1223. my $name = $self->like(lc $self->{$table});
  1224. my $query = qq|
  1225. SELECT * FROM $table
  1226. WHERE (lower(name) LIKE ? OR ${table}number LIKE ?)
  1227. $where
  1228. ORDER BY name|;
  1229. unshift(@queryargs, $name, $name);
  1230. my $sth = $self->{dbh}->prepare($query);
  1231. $sth->execute(@queryargs) || $self->dberror($query);
  1232. my $i = 0;
  1233. @{ $self->{name_list} } = ();
  1234. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1235. push(@{ $self->{name_list} }, $ref);
  1236. $i++;
  1237. }
  1238. $sth->finish;
  1239. $self->{dbh}->commit;
  1240. $i;
  1241. }
  1242. sub all_vc {
  1243. my ($self, $myconfig, $vc, $module, $dbh, $transdate, $job) = @_;
  1244. my $ref;
  1245. my $disconnect = 0;
  1246. $dbh = $self->{dbh};
  1247. my $sth;
  1248. my $query = qq|SELECT count(*) FROM $vc|;
  1249. my $where;
  1250. my @queryargs = ();
  1251. if ($transdate) {
  1252. $query .= qq| WHERE (startdate IS NULL OR startdate <= ?)
  1253. AND (enddate IS NULL OR enddate >= ?)|;
  1254. @queryargs = ($transdate, $transdate);
  1255. }
  1256. $sth = $dbh->prepare($query);
  1257. $sth->execute(@queryargs);
  1258. my ($count) = $sth->fetchrow_array;
  1259. $sth->finish;
  1260. @queryargs = ();
  1261. # build selection list
  1262. if ($count < $myconfig->{vclimit}) {
  1263. $self->{"${vc}_id"} *= 1;
  1264. $query = qq|SELECT id, name
  1265. FROM $vc
  1266. WHERE 1=1
  1267. $where
  1268. UNION
  1269. SELECT id,name
  1270. FROM $vc
  1271. WHERE id = ?
  1272. ORDER BY name|;
  1273. push(@queryargs, $self->{"${vc}_id"});
  1274. $sth = $dbh->prepare($query);
  1275. $sth->execute(@queryargs) || $self->dberror($query);
  1276. @{ $self->{"all_$vc"} } = ();
  1277. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1278. push @{ $self->{"all_$vc"} }, $ref;
  1279. }
  1280. $sth->finish;
  1281. }
  1282. # get self
  1283. if (! $self->{employee_id}) {
  1284. ($self->{employee}, $self->{employee_id}) = split /--/, $self->{employee};
  1285. ($self->{employee}, $self->{employee_id}) = $self->get_employee($dbh) unless $self->{employee_id};
  1286. }
  1287. $self->all_employees($myconfig, $dbh, $transdate, 1);
  1288. $self->all_departments($myconfig, $dbh, $vc);
  1289. $self->all_projects($myconfig, $dbh, $transdate, $job);
  1290. # get language codes
  1291. $query = qq|SELECT *
  1292. FROM language
  1293. ORDER BY 2|;
  1294. $sth = $dbh->prepare($query);
  1295. $sth->execute || $self->dberror($query);
  1296. $self->{all_language} = ();
  1297. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1298. push @{ $self->{all_language} }, $ref;
  1299. }
  1300. $sth->finish;
  1301. $self->all_taxaccounts($myconfig, $dbh, $transdate);
  1302. $self->{dbh}->commit;
  1303. }
  1304. sub all_taxaccounts {
  1305. my ($self, $myconfig, $dbh2, $transdate) = @_;
  1306. my $dbh = $self->{dbh};
  1307. my $sth;
  1308. my $query;
  1309. my $where;
  1310. my @queryargs = ();
  1311. if ($transdate) {
  1312. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1313. push(@queryargs, $transdate);
  1314. }
  1315. if ($self->{taxaccounts}) {
  1316. # rebuild tax rates
  1317. $query = qq|SELECT t.rate, t.taxnumber
  1318. FROM tax t
  1319. JOIN chart c ON (c.id = t.chart_id)
  1320. WHERE c.accno = ?
  1321. $where
  1322. ORDER BY accno, validto|;
  1323. $sth = $dbh->prepare($query) || $self->dberror($query);
  1324. foreach my $accno (split / /, $self->{taxaccounts}) {
  1325. $sth->execute($accno, @queryargs);
  1326. ($self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"}) = $sth->fetchrow_array;
  1327. $sth->finish;
  1328. }
  1329. }
  1330. $self->{dbh}->commit;
  1331. }
  1332. sub all_employees {
  1333. my ($self, $myconfig, $dbh2, $transdate, $sales) = @_;
  1334. my $dbh = $self->{dbh};
  1335. my @whereargs = ();
  1336. # setup employees/sales contacts
  1337. my $query = qq|SELECT id, name
  1338. FROM employee
  1339. WHERE 1 = 1|;
  1340. if ($transdate) {
  1341. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1342. AND (enddate IS NULL OR enddate >= ?)|;
  1343. @whereargs = ($transdate, $transdate);
  1344. } else {
  1345. $query .= qq| AND enddate IS NULL|;
  1346. }
  1347. if ($sales) {
  1348. $query .= qq| AND sales = '1'|;
  1349. }
  1350. $query .= qq| ORDER BY name|;
  1351. my $sth = $dbh->prepare($query);
  1352. $sth->execute(@whereargs) || $self->dberror($query);
  1353. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1354. push @{ $self->{all_employee} }, $ref;
  1355. }
  1356. $sth->finish;
  1357. $dbh->commit;
  1358. }
  1359. sub all_projects {
  1360. my ($self, $myconfig, $dbh2, $transdate, $job) = @_;
  1361. my $dbh = $self->{dbh};
  1362. my @queryargs = ();
  1363. my $where = "1 = 1";
  1364. $where = qq|id NOT IN (SELECT id
  1365. FROM parts
  1366. WHERE project_id > 0)| if ! $job;
  1367. my $query = qq|SELECT *
  1368. FROM project
  1369. WHERE $where|;
  1370. if ($self->{language_code}) {
  1371. $query = qq|
  1372. SELECT pr.*, t.description AS translation
  1373. FROM project pr
  1374. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1375. WHERE t.language_code = ?|;
  1376. push(@queryargs, $self->{language_code});
  1377. }
  1378. if ($transdate) {
  1379. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1380. AND (enddate IS NULL OR enddate >= ?)|;
  1381. push(@queryargs, $transdate, $transdate);
  1382. }
  1383. $query .= qq| ORDER BY projectnumber|;
  1384. $sth = $dbh->prepare($query);
  1385. $sth->execute(@queryargs)|| $self->dberror($query);
  1386. @{ $self->{all_project} } = ();
  1387. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1388. push @{ $self->{all_project} }, $ref;
  1389. }
  1390. $sth->finish;
  1391. $dbh->commit;
  1392. }
  1393. sub all_departments {
  1394. my ($self, $myconfig, $dbh2, $vc) = @_;
  1395. $dbh = $self->{dbh};
  1396. my $where = "1 = 1";
  1397. if ($vc) {
  1398. if ($vc eq 'customer') {
  1399. $where = " role = 'P'";
  1400. }
  1401. }
  1402. my $query = qq|SELECT id, description
  1403. FROM department
  1404. WHERE $where
  1405. ORDER BY 2|;
  1406. my $sth = $dbh->prepare($query);
  1407. $sth->execute || $self->dberror($query);
  1408. @{ $self->{all_department} } = ();
  1409. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1410. push @{ $self->{all_department} }, $ref;
  1411. }
  1412. $sth->finish;
  1413. $self->all_years($myconfig);
  1414. $dbh->commit;
  1415. }
  1416. sub all_years {
  1417. my ($self, $myconfig, $dbh2) = @_;
  1418. $dbh = $self->{dbh};
  1419. # get years
  1420. my $query = qq|
  1421. SELECT (SELECT MIN(transdate) FROM acc_trans),
  1422. (SELECT MAX(transdate) FROM acc_trans)|;
  1423. my ($startdate, $enddate) = $dbh->selectrow_array($query);
  1424. if ($myconfig->{dateformat} =~ /^yy/) {
  1425. ($startdate) = split /\W/, $startdate;
  1426. ($enddate) = split /\W/, $enddate;
  1427. } else {
  1428. (@_) = split /\W/, $startdate;
  1429. $startdate = $_[2];
  1430. (@_) = split /\W/, $enddate;
  1431. $enddate = $_[2];
  1432. }
  1433. $self->{all_years} = ();
  1434. $startdate = substr($startdate,0,4);
  1435. $enddate = substr($enddate,0,4);
  1436. while ($enddate >= $startdate) {
  1437. push @{ $self->{all_years} }, $enddate--;
  1438. }
  1439. #this should probably be changed to use locale
  1440. %{ $self->{all_month} } = (
  1441. '01' => 'January',
  1442. '02' => 'February',
  1443. '03' => 'March',
  1444. '04' => 'April',
  1445. '05' => 'May ',
  1446. '06' => 'June',
  1447. '07' => 'July',
  1448. '08' => 'August',
  1449. '09' => 'September',
  1450. '10' => 'October',
  1451. '11' => 'November',
  1452. '12' => 'December' );
  1453. $dbh->commit;
  1454. }
  1455. sub create_links {
  1456. my ($self, $module, $myconfig, $vc, $job) = @_;
  1457. # get last customers or vendors
  1458. my ($query, $sth);
  1459. $dbh = $self->{dbh};
  1460. my %xkeyref = ();
  1461. # now get the account numbers
  1462. $query = qq|SELECT accno, description, link
  1463. FROM chart
  1464. WHERE link LIKE ?
  1465. ORDER BY accno|;
  1466. $sth = $dbh->prepare($query);
  1467. $sth->execute("%"."$module%") || $self->dberror($query);
  1468. $self->{accounts} = "";
  1469. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1470. foreach my $key (split /:/, $ref->{link}) {
  1471. if ($key =~ /$module/) {
  1472. # cross reference for keys
  1473. $xkeyref{$ref->{accno}} = $key;
  1474. push @{ $self->{"${module}_links"}{$key} },
  1475. { accno => $ref->{accno},
  1476. description => $ref->{description} };
  1477. $self->{accounts} .= "$ref->{accno} "
  1478. unless $key =~ /tax/;
  1479. }
  1480. }
  1481. }
  1482. $sth->finish;
  1483. my $arap = ($vc eq 'customer') ? 'ar' : 'ap';
  1484. if ($self->{id}) {
  1485. $query = qq|
  1486. SELECT a.invnumber, a.transdate,
  1487. a.${vc}_id, a.datepaid, a.duedate, a.ordnumber,
  1488. a.taxincluded, a.curr AS currency, a.notes,
  1489. a.intnotes, c.name AS $vc, a.department_id,
  1490. d.description AS department,
  1491. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1492. a.employee_id, e.name AS employee,
  1493. c.language_code, a.ponumber
  1494. FROM $arap a
  1495. JOIN $vc c ON (a.${vc}_id = c.id)
  1496. LEFT JOIN employee e ON (e.id = a.employee_id)
  1497. LEFT JOIN department d ON (d.id = a.department_id)
  1498. WHERE a.id = ?|;
  1499. $sth = $dbh->prepare($query);
  1500. $sth->execute($self->{id}) || $self->dberror($query);
  1501. $ref = $sth->fetchrow_hashref(NAME_lc);
  1502. foreach $key (keys %$ref) {
  1503. $self->{$key} = $ref->{$key};
  1504. }
  1505. $sth->finish;
  1506. # get printed, emailed
  1507. $query = qq|
  1508. SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1509. FROM status s WHERE s.trans_id = ?|;
  1510. $sth = $dbh->prepare($query);
  1511. $sth->execute($self->{id}) || $self->dberror($query);
  1512. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1513. $self->{printed} .= "$ref->{formname} "
  1514. if $ref->{printed};
  1515. $self->{emailed} .= "$ref->{formname} "
  1516. if $ref->{emailed};
  1517. $self->{queued} .= "$ref->{formname} ".
  1518. "$ref->{spoolfile} " if $ref->{spoolfile};
  1519. }
  1520. $sth->finish;
  1521. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1522. # get recurring
  1523. $self->get_recurring($dbh);
  1524. # get amounts from individual entries
  1525. $query = qq|
  1526. SELECT c.accno, c.description, a.source, a.amount,
  1527. a.memo, a.transdate, a.cleared, a.project_id,
  1528. p.projectnumber
  1529. FROM acc_trans a
  1530. JOIN chart c ON (c.id = a.chart_id)
  1531. LEFT JOIN project p ON (p.id = a.project_id)
  1532. WHERE a.trans_id = ?
  1533. AND a.fx_transaction = '0'
  1534. ORDER BY transdate|;
  1535. $sth = $dbh->prepare($query);
  1536. $sth->execute($self->{id}) || $self->dberror($query);
  1537. my $fld = ($vc eq 'customer') ? 'buy' : 'sell';
  1538. $self->{exchangerate} = $self->get_exchangerate($dbh,
  1539. $self->{currency}, $self->{transdate}, $fld);
  1540. # store amounts in {acc_trans}{$key} for multiple accounts
  1541. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1542. $ref->{exchangerate} = $self->get_exchangerate($dbh,
  1543. $self->{currency},
  1544. $ref->{transdate},
  1545. $fld);
  1546. push @{ $self->{acc_trans}{$xkeyref{$ref->{accno}}} },
  1547. $ref;
  1548. }
  1549. $sth->finish;
  1550. for (qw(curr closedto revtrans)){
  1551. $query = qq|
  1552. SELECT value FROM defaults
  1553. WHERE setting_key = '$_'|;
  1554. $sth = $dbh->prepare($query);
  1555. $sth->execute || $self->dberror($query);
  1556. (undef, $val) = $sth->fetchrow_array();
  1557. if ($_ eq 'curr'){
  1558. $self->{currencies} = $val;
  1559. } else {
  1560. $self->{$_} = $val;
  1561. }
  1562. $sth->finish;
  1563. }
  1564. } else {
  1565. for (qw(current_date curr closedto revtrans)){
  1566. $query = qq|
  1567. SELECT value FROM defaults
  1568. WHERE setting_key = '$_'|;
  1569. $sth = $dbh->prepare($query);
  1570. $sth->execute || $self->dberror($query);
  1571. ($val) = $sth->fetchrow_array();
  1572. if ($_ eq 'curr'){
  1573. $self->{currencies} = $val;
  1574. } elsif ($_ eq 'current_date'){
  1575. $self->{transdate} = $val;
  1576. } else {
  1577. $self->{$_} = $val;
  1578. }
  1579. $sth->finish;
  1580. }
  1581. if (! $self->{"$self->{vc}_id"}) {
  1582. $self->lastname_used($myconfig, $dbh, $vc, $module);
  1583. }
  1584. }
  1585. $self->all_vc($myconfig, $vc, $module, $dbh, $self->{transdate}, $job);
  1586. $self->{dbh}->commit;
  1587. }
  1588. sub lastname_used {
  1589. my ($self, $myconfig, $dbh2, $vc, $module) = @_;
  1590. my $dbh = $self->{dbh};
  1591. my $arap = ($vc eq 'customer') ? "ar" : "ap";
  1592. my $where = "1 = 1";
  1593. my $sth;
  1594. if ($self->{type} =~ /_order/) {
  1595. $arap = 'oe';
  1596. $where = "quotation = '0'";
  1597. }
  1598. if ($self->{type} =~ /_quotation/) {
  1599. $arap = 'oe';
  1600. $where = "quotation = '1'";
  1601. }
  1602. my $query = qq|
  1603. SELECT id
  1604. FROM $arap
  1605. WHERE id IN
  1606. (SELECT MAX(id)
  1607. FROM $arap
  1608. WHERE $where AND ${vc}_id > 0)|;
  1609. my ($trans_id) = $dbh->selectrow_array($query);
  1610. $trans_id *= 1;
  1611. my $DAYS = ($myconfig->{dbdriver} eq 'DB2') ? "DAYS" : "";
  1612. $query = qq|
  1613. SELECT ct.name AS $vc, a.curr AS currency, a.${vc}_id,
  1614. current_date + ct.terms $DAYS AS duedate,
  1615. a.department_id, d.description AS department, ct.notes,
  1616. ct.curr AS currency
  1617. FROM $arap a
  1618. JOIN $vc ct ON (a.${vc}_id = ct.id)
  1619. LEFT JOIN department d ON (a.department_id = d.id)
  1620. WHERE a.id = ?|;
  1621. $sth = $dbh->prepare($query);
  1622. $sth->execute($trans_id)|| $self->dberror($query);
  1623. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1624. for (keys %$ref) { $self->{$_} = $ref->{$_} }
  1625. $sth->finish;
  1626. $dbh->commit;
  1627. }
  1628. sub current_date {
  1629. my ($self, $myconfig, $thisdate, $days) = @_;
  1630. my $dbh = $self->{dbh};
  1631. my $query;
  1632. $days *= 1;
  1633. if ($thisdate) {
  1634. my $dateformat = $myconfig->{dateformat};
  1635. if ($myconfig->{dateformat} !~ /^y/) {
  1636. my @a = split /\D/, $thisdate;
  1637. $dateformat .= "yy" if (length $a[2] > 2);
  1638. }
  1639. if ($thisdate !~ /\D/) {
  1640. $dateformat = 'yyyymmdd';
  1641. }
  1642. $query = qq|SELECT to_date(?, ?)
  1643. + ?::interval AS thisdate|;
  1644. @queryargs = ($thisdate, $dateformat, $days);
  1645. } else {
  1646. $query = qq|SELECT current_date AS thisdate|;
  1647. @queryargs = ();
  1648. }
  1649. $sth = $dbh->prepare($query);
  1650. $sth->execute(@queryargs);
  1651. ($thisdate) = $sth->fetchrow_array;
  1652. $dbh->commit;
  1653. $thisdate;
  1654. }
  1655. sub like {
  1656. my ($self, $str) = @_;
  1657. if ($str !~ /(%|_)/) {
  1658. if ($str =~ /(^").*("$)/) {
  1659. $str =~ s/(^"|"$)//g;
  1660. } else {
  1661. $str = "%$str%";
  1662. }
  1663. }
  1664. $str =~ s/'/''/g;
  1665. $str;
  1666. }
  1667. sub redo_rows {
  1668. my ($self, $flds, $new, $count, $numrows) = @_;
  1669. my @ndx = ();
  1670. for (1 .. $count) {
  1671. push @ndx, { num => $new->[$_-1]->{runningnumber}, ndx => $_ }
  1672. }
  1673. my $i = 0;
  1674. # fill rows
  1675. foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
  1676. $i++;
  1677. $j = $item->{ndx} - 1;
  1678. for (@{$flds}) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1679. }
  1680. # delete empty rows
  1681. for $i ($count + 1 .. $numrows) {
  1682. for (@{$flds}) { delete $self->{"${_}_$i"} }
  1683. }
  1684. }
  1685. sub get_partsgroup {
  1686. my ($self, $myconfig, $p) = @_;
  1687. my $dbh = $self->{dbh};
  1688. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1689. FROM partsgroup pg
  1690. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1691. my $where;
  1692. my $sortorder = "partsgroup";
  1693. if ($p->{searchitems} eq 'part') {
  1694. $where = qq| WHERE (p.inventory_accno_id > 0
  1695. AND p.income_accno_id > 0)|;
  1696. }
  1697. if ($p->{searchitems} eq 'service') {
  1698. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1699. }
  1700. if ($p->{searchitems} eq 'assembly') {
  1701. $where = qq| WHERE p.assembly = '1'|;
  1702. }
  1703. if ($p->{searchitems} eq 'labor') {
  1704. $where = qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1705. }
  1706. if ($p->{searchitems} eq 'nolabor') {
  1707. $where = qq| WHERE p.income_accno_id > 0|;
  1708. }
  1709. if ($p->{all}) {
  1710. $query = qq|SELECT id, partsgroup
  1711. FROM partsgroup|;
  1712. }
  1713. my @queryargs = ();
  1714. if ($p->{language_code}) {
  1715. $sortorder = "translation";
  1716. $query = qq|
  1717. SELECT DISTINCT pg.id, pg.partsgroup,
  1718. t.description AS translation
  1719. FROM partsgroup pg
  1720. JOIN parts p ON (p.partsgroup_id = pg.id)
  1721. LEFT JOIN translation t ON (t.trans_id = pg.id
  1722. AND t.language_code = ?)|;
  1723. @queryargs = ($p->{language_code});
  1724. }
  1725. $query .= qq| $where ORDER BY $sortorder|;
  1726. my $sth = $dbh->prepare($query);
  1727. $sth->execute(@queryargs)|| $self->dberror($query);
  1728. $self->{all_partsgroup} = ();
  1729. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1730. push @{ $self->{all_partsgroup} }, $ref;
  1731. }
  1732. $sth->finish;
  1733. $dbh->commit;
  1734. }
  1735. sub update_status {
  1736. my ($self, $myconfig) = @_;
  1737. # no id return
  1738. return unless $self->{id};
  1739. my $dbh = $self->{dbh};
  1740. my %queued = split / +/, $self->{queued};
  1741. my $spoolfile = ($queued{$self->{formname}}) ? "'$queued{$self->{formname}}'" : 'NULL';
  1742. my $query = qq|DELETE FROM status
  1743. WHERE formname = ?
  1744. AND trans_id = ?|;
  1745. $sth=$dbh->prepare($query);
  1746. $sth->execute($self->{formname}, $self->{id}) || $self->dberror($query);
  1747. $sth->finish;
  1748. my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
  1749. my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
  1750. $query = qq|
  1751. INSERT INTO status
  1752. (trans_id, printed, emailed, spoolfile, formname)
  1753. VALUES (?, ?, ?, ?, ?)|;
  1754. $sth = $dbh->prepare($query);
  1755. $sth->execute($self->{id}, $printed, $emailed, $spoolfile,
  1756. $self->{formname});
  1757. $sth->finish;
  1758. $dbh->commit;
  1759. }
  1760. sub save_status {
  1761. my ($self) = @_;
  1762. $dbh = $self->{dbh};
  1763. my $formnames = $self->{printed};
  1764. my $emailforms = $self->{emailed};
  1765. my $query = qq|DELETE FROM status
  1766. WHERE trans_id = ?|;
  1767. my $sth = $dbh->prepare($query);
  1768. $sth->execute($self->{id});
  1769. $sth->finish;
  1770. my %queued;
  1771. my $formname;
  1772. if ($self->{queued}) {
  1773. %queued = split / +/, $self->{queued};
  1774. foreach $formname (keys %queued) {
  1775. $printed = ($self->{printed} =~ /$formname/) ? "1" : "0";
  1776. $emailed = ($self->{emailed} =~ /$formname/) ? "1" : "0";
  1777. if ($queued{$formname}) {
  1778. $query = qq|
  1779. INSERT INTO status
  1780. (trans_id, printed, emailed,
  1781. spoolfile, formname)
  1782. VALUES (?, ?, ?, ?, ?)|;
  1783. $sth = $dbh->prepare($query);
  1784. $sth->execute($self->{id}, $pinted, $emailed,
  1785. $queued{$formname}, $formname)
  1786. || $self->dberror($query);
  1787. $sth->finish;
  1788. }
  1789. $formnames =~ s/$formname//;
  1790. $emailforms =~ s/$formname//;
  1791. }
  1792. }
  1793. # save printed, emailed info
  1794. $formnames =~ s/^ +//g;
  1795. $emailforms =~ s/^ +//g;
  1796. my %status = ();
  1797. for (split / +/, $formnames) { $status{$_}{printed} = 1 }
  1798. for (split / +/, $emailforms) { $status{$_}{emailed} = 1 }
  1799. foreach my $formname (keys %status) {
  1800. $printed = ($formnames =~ /$self->{formname}/) ? "1" : "0";
  1801. $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
  1802. $query = qq|
  1803. INSERT INTO status (trans_id, printed, emailed,
  1804. formname)
  1805. VALUES (?, ?, ?, ?)|;
  1806. $sth = $dbh->prepare($query);
  1807. $sth->execute($self->{id}, $printed, $emailed, $formname);
  1808. $sth->finish;
  1809. }
  1810. $dbh->commit;
  1811. }
  1812. sub get_recurring {
  1813. my ($self) = @_;
  1814. $dbh = $self->{dbh};
  1815. my $query = qq/
  1816. SELECT s.*, se.formname || ':' || se.format AS emaila,
  1817. se.message, sp.formname || ':' ||
  1818. sp.format || ':' || sp.printer AS printa
  1819. FROM recurring s
  1820. LEFT JOIN recurringemail se ON (s.id = se.id)
  1821. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  1822. WHERE s.id = ?/;
  1823. my $sth = $dbh->prepare($query);
  1824. $sth->execute($self->{id}) || $self->dberror($query);
  1825. for (qw(email print)) { $self->{"recurring$_"} = "" }
  1826. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1827. for (keys %$ref) { $self->{"recurring$_"} = $ref->{$_} }
  1828. $self->{recurringemail} .= "$ref->{emaila}:";
  1829. $self->{recurringprint} .= "$ref->{printa}:";
  1830. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  1831. }
  1832. $sth->finish;
  1833. chop $self->{recurringemail};
  1834. chop $self->{recurringprint};
  1835. if ($self->{recurringstartdate}) {
  1836. $self->{recurringreference} = $self->escape($self->{recurringreference},1);
  1837. $self->{recurringmessage} = $self->escape($self->{recurringmessage},1);
  1838. for (qw(reference startdate repeat unit howmany
  1839. payment print email message)) {
  1840. $self->{recurring} .= qq|$self->{"recurring$_"},|
  1841. }
  1842. chop $self->{recurring};
  1843. }
  1844. $dbh->commit;
  1845. }
  1846. sub save_recurring {
  1847. my ($self, $dbh2, $myconfig) = @_;
  1848. my $dbh = $self->{dbh};
  1849. my $query;
  1850. $query = qq|DELETE FROM recurring
  1851. WHERE id = ?|;
  1852. $sth = $dbh->prepare($query);
  1853. $sth->execute($self->{id}) || $self->dberror($query);
  1854. $query = qq|DELETE FROM recurringemail
  1855. WHERE id = ?|;
  1856. $sth = $dbh->prepare($query);
  1857. $sth->execute($self->{id}) || $self->dberror($query);
  1858. $query = qq|DELETE FROM recurringprint
  1859. WHERE id = ?|;
  1860. $sth = $dbh->prepare($query);
  1861. $sth->execute($self->{id}) || $self->dberror($query);
  1862. if ($self->{recurring}) {
  1863. my %s = ();
  1864. ($s{reference}, $s{startdate}, $s{repeat}, $s{unit},
  1865. $s{howmany}, $s{payment}, $s{print}, $s{email},
  1866. $s{message})
  1867. = split /,/, $self->{recurring};
  1868. for (qw(reference message)) { $s{$_} = $self->unescape($s{$_}) }
  1869. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  1870. # calculate enddate
  1871. my $advance = $s{repeat} * ($s{howmany} - 1);
  1872. my %interval;
  1873. $interval{'Pg'} =
  1874. "(date '$s{startdate}' + interval '$advance $s{unit}')";
  1875. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  1876. my ($enddate) = $dbh->selectrow_array($query);
  1877. # calculate nextdate
  1878. $query = qq|
  1879. SELECT current_date - date ? AS a,
  1880. date ? - current_date AS b|;
  1881. $sth = $dbh->prepare($query);
  1882. $sth->execute($s{startdate}, $enddate);
  1883. my ($a, $b) = $sth->fetchrow_array;
  1884. if ($a + $b) {
  1885. $advance = int(($a / ($a + $b)) * ($s{howmany} - 1) + 1) * $s{repeat};
  1886. } else {
  1887. $advance = 0;
  1888. }
  1889. my $nextdate = $enddate;
  1890. if ($advance > 0) {
  1891. if ($advance < ($s{repeat} * $s{howmany})) {
  1892. %interval = ( 'Pg' => "(date '$s{startdate}' + interval '$advance $s{unit}')",
  1893. 'DB2' => qq|(date ('$s{startdate}') + "$advance $s{unit}")|,);
  1894. $interval{Oracle} = $interval{PgPP} = $interval{Pg};
  1895. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  1896. ($nextdate) = $dbh->selectrow_array($query);
  1897. }
  1898. } else {
  1899. $nextdate = $s{startdate};
  1900. }
  1901. if ($self->{recurringnextdate}) {
  1902. $nextdate = $self->{recurringnextdate};
  1903. $query = qq|SELECT '$enddate' - date '$nextdate'|;
  1904. if ($dbh->selectrow_array($query) < 0) {
  1905. undef $nextdate;
  1906. }
  1907. }
  1908. $self->{recurringpayment} *= 1;
  1909. $query = qq|
  1910. INSERT INTO recurring
  1911. (id, reference, startdate, enddate, nextdate,
  1912. repeat, unit, howmany, payment)
  1913. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  1914. $sth = $dbh->prepare($query);
  1915. $sth->execute($self->{id}, $s{reference}, $s{startdate},
  1916. $enddate, $nextdate, $s{repeat}, $s{unit}, $s{howmany},
  1917. $s{payment});
  1918. my @p;
  1919. my $p;
  1920. my $i;
  1921. my $sth;
  1922. if ($s{email}) {
  1923. # formname:format
  1924. @p = split /:/, $s{email};
  1925. $query = qq|INSERT INTO recurringemail (id, formname, format, message)
  1926. VALUES (?, ?, ?, ?)|;
  1927. $sth = $dbh->prepare($query) || $self->dberror($query);
  1928. for ($i = 0; $i <= $#p; $i += 2) {
  1929. $sth->execute($self->{id}, $p[$i], $p[$i+1],
  1930. $s{message});
  1931. }
  1932. $sth->finish;
  1933. }
  1934. if ($s{print}) {
  1935. # formname:format:printer
  1936. @p = split /:/, $s{print};
  1937. $query = qq|INSERT INTO recurringprint (id, formname, format, printer)
  1938. VALUES (?, ?, ?, ?)|;
  1939. $sth = $dbh->prepare($query) || $self->dberror($query);
  1940. for ($i = 0; $i <= $#p; $i += 3) {
  1941. $p = ($p[$i+2]) ? $p[$i+2] : "";
  1942. $sth->execute($self->{id}, $p[$i], $p[$i+1], $p);
  1943. }
  1944. $sth->finish;
  1945. }
  1946. }
  1947. $dbh->commit;
  1948. }
  1949. sub save_intnotes {
  1950. my ($self, $myconfig, $vc) = @_;
  1951. # no id return
  1952. return unless $self->{id};
  1953. my $dbh = $self->dbconnect($myconfig);
  1954. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  1955. $sth=$dbh->prepare($query);
  1956. $sth->execute($self->{intnotes}, $self->{id}) || $self->dberror($query);
  1957. $dbh->commit;
  1958. }
  1959. sub update_defaults {
  1960. my ($self, $myconfig, $fld) = @_;
  1961. if (!$self->{dbh} && $self){
  1962. $self->db_init($myconfig);
  1963. }
  1964. my $dbh = $self->{dbh};
  1965. if (!$self){
  1966. $dbh = $_[3];
  1967. }
  1968. my $query = qq|
  1969. SELECT value FROM defaults
  1970. WHERE setting_key = ? FOR UPDATE|;
  1971. $sth = $dbh->prepare($query);
  1972. $sth->execute($fld);
  1973. ($_) = $sth->fetchrow_array();
  1974. $_ = "0" unless $_;
  1975. # check for and replace
  1976. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  1977. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  1978. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  1979. # <?lsmb PHONE ?> for customer and vendors
  1980. my $num = $_;
  1981. ($num) = $num =~ /(\d+)/;
  1982. if (defined $num) {
  1983. my $incnum;
  1984. # if we have leading zeros check how long it is
  1985. if ($num =~ /^0/) {
  1986. my $l = length $num;
  1987. $incnum = $num + 1;
  1988. $l -= length $incnum;
  1989. # pad it out with zeros
  1990. my $padzero = "0" x $l;
  1991. $incnum = ("0" x $l) . $incnum;
  1992. } else {
  1993. $incnum = $num + 1;
  1994. }
  1995. s/$num/$incnum/;
  1996. }
  1997. my $dbvar = $_;
  1998. my $var = $_;
  1999. my $str;
  2000. my $param;
  2001. if (/<\?lsmb /) {
  2002. while (/<\?lsmb /) {
  2003. s/<\?lsmb .*? \?>//;
  2004. last unless $&;
  2005. $param = $&;
  2006. $str = "";
  2007. if ($param =~ /<\?lsmb date \?>/i) {
  2008. $str = ($self->split_date($myconfig->{dateformat}, $self->{transdate}))[0];
  2009. $var =~ s/$param/$str/;
  2010. }
  2011. if ($param =~ /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i) {
  2012. my $fld = lc $&;
  2013. $fld =~ s/<\?lsmb //;
  2014. if ($fld =~ /name/) {
  2015. if ($self->{type}) {
  2016. $fld = $self->{vc};
  2017. }
  2018. }
  2019. my $p = $param;
  2020. $p =~ s/(<|>|%)//g;
  2021. my @p = split / /, $p;
  2022. my @n = split / /, uc $self->{$fld};
  2023. if ($#p > 0) {
  2024. for (my $i = 1; $i <= $#p; $i++) {
  2025. $str .= substr($n[$i-1], 0, $p[$i]);
  2026. }
  2027. } else {
  2028. ($str) = split /--/, $self->{$fld};
  2029. }
  2030. $var =~ s/$param/$str/;
  2031. $var =~ s/\W//g if $fld eq 'phone';
  2032. }
  2033. if ($param =~ /<\?lsmb (yy|mm|dd)/i) {
  2034. my $p = $param;
  2035. $p =~ s/(<|>|%)//g;
  2036. my $spc = $p;
  2037. $spc =~ s/\w//g;
  2038. $spc = substr($spc, 0, 1);
  2039. my %d = ( yy => 1, mm => 2, dd => 3 );
  2040. my @p = ();
  2041. my @a = $self->split_date($myconfig->{dateformat}, $self->{transdate});
  2042. for (sort keys %d) { push @p, $a[$d{$_}] if ($p =~ /$_/) }
  2043. $str = join $spc, @p;
  2044. $var =~ s/$param/$str/;
  2045. }
  2046. if ($param =~ /<\?lsmb curr/i) {
  2047. $var =~ s/$param/$self->{currency}/;
  2048. }
  2049. }
  2050. }
  2051. $query = qq|
  2052. UPDATE defaults
  2053. SET value = ?
  2054. WHERE setting_key = ?|;
  2055. $sth = $dbh->prepare($query);
  2056. $sth->execute($dbvar, $fld) || $self->dberror($query);
  2057. $dbh->commit;
  2058. $var;
  2059. }
  2060. sub db_prepare_vars {
  2061. for (@_){
  2062. if (!$self->{$_} and $self->{$_} ne "0"){
  2063. undef $self->{$_};
  2064. }
  2065. }
  2066. }
  2067. sub split_date {
  2068. my ($self, $dateformat, $date) = @_;
  2069. my @d = localtime;
  2070. my $mm;
  2071. my $dd;
  2072. my $yy;
  2073. my $rv;
  2074. if (! $date) {
  2075. $dd = $d[3];
  2076. $mm = ++$d[4];
  2077. $yy = substr($d[5],-2);
  2078. $mm = substr("0$mm", -2);
  2079. $dd = substr("0$dd", -2);
  2080. }
  2081. if ($dateformat =~ /^yy/) {
  2082. if ($date) {
  2083. if ($date =~ /\D/) {
  2084. ($yy, $mm, $dd) = split /\D/, $date;
  2085. $mm *= 1;
  2086. $dd *= 1;
  2087. $mm = substr("0$mm", -2);
  2088. $dd = substr("0$dd", -2);
  2089. $yy = substr($yy, -2);
  2090. $rv = "$yy$mm$dd";
  2091. } else {
  2092. $rv = $date;
  2093. }
  2094. } else {
  2095. $rv = "$yy$mm$dd";
  2096. }
  2097. }
  2098. if ($dateformat =~ /^mm/) {
  2099. if ($date) {
  2100. if ($date =~ /\D/) {
  2101. ($mm, $dd, $yy) = 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 = "$mm$dd$yy";
  2108. } else {
  2109. $rv = $date;
  2110. }
  2111. } else {
  2112. $rv = "$mm$dd$yy";
  2113. }
  2114. }
  2115. if ($dateformat =~ /^dd/) {
  2116. if ($date) {
  2117. if ($date =~ /\D/) {
  2118. ($dd, $mm, $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 = "$dd$mm$yy";
  2125. } else {
  2126. $rv = $date;
  2127. }
  2128. } else {
  2129. $rv = "$dd$mm$yy";
  2130. }
  2131. }
  2132. ($rv, $yy, $mm, $dd);
  2133. }
  2134. sub from_to {
  2135. my ($self, $yy, $mm, $interval) = @_;
  2136. use Time::Local;
  2137. my @t;
  2138. my $dd = 1;
  2139. my $fromdate = "$yy${mm}01";
  2140. my $bd = 1;
  2141. if (defined $interval) {
  2142. if ($interval == 12) {
  2143. $yy++;
  2144. } else {
  2145. if (($mm += $interval) > 12) {
  2146. $mm -= 12;
  2147. $yy++;
  2148. }
  2149. if ($interval == 0) {
  2150. @t = localtime(time);
  2151. $dd = $t[3];
  2152. $mm = $t[4] + 1;
  2153. $yy = $t[5] + 1900;
  2154. $bd = 0;
  2155. }
  2156. }
  2157. } else {
  2158. if (++$mm > 12) {
  2159. $mm -= 12;
  2160. $yy++;
  2161. }
  2162. }
  2163. $mm--;
  2164. @t = localtime(timelocal(0,0,0,$dd,$mm,$yy) - $bd);
  2165. $t[4]++;
  2166. $t[4] = substr("0$t[4]",-2);
  2167. $t[3] = substr("0$t[3]",-2);
  2168. $t[5] += 1900;
  2169. ($fromdate, "$t[5]$t[4]$t[3]");
  2170. }
  2171. sub audittrail {
  2172. my ($self, $dbh, $myconfig, $audittrail) = @_;
  2173. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2174. my $query;
  2175. my $rv;
  2176. my $disconnect;
  2177. if (! $dbh) {
  2178. $dbh = $self->{dbh};
  2179. }
  2180. # if we have an id add audittrail, otherwise get a new timestamp
  2181. my @queryargs;
  2182. if ($audittrail->{id}) {
  2183. $query = qq|
  2184. SELECT value FROM defaults
  2185. WHERE setting_key = 'audittrail'|;
  2186. if ($dbh->selectrow_array($query)) {
  2187. my ($null, $employee_id) = $self->get_employee($dbh);
  2188. if ($self->{audittrail} && !$myconfig) {
  2189. chop $self->{audittrail};
  2190. my @a = split /\|/, $self->{audittrail};
  2191. my %newtrail = ();
  2192. my $key;
  2193. my $i;
  2194. my @flds = qw(tablename reference formname action transdate);
  2195. # put into hash and remove dups
  2196. while (@a) {
  2197. $key = "$a[2]$a[3]";
  2198. $i = 0;
  2199. $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
  2200. splice @a, 0, 5;
  2201. }
  2202. $query = qq|
  2203. INSERT INTO audittrail
  2204. (trans_id, tablename, reference,
  2205. formname, action, transdate,
  2206. employee_id)
  2207. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2208. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2209. foreach $key (sort { $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate} } keys %newtrail) {
  2210. $i = 2;
  2211. $sth->bind_param(1, $audittrail->{id});
  2212. for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
  2213. $sth->bind_param($i++, $employee_id);
  2214. $sth->execute || $self->dberror;
  2215. $sth->finish;
  2216. }
  2217. }
  2218. if ($audittrail->{transdate}) {
  2219. $query = qq|
  2220. INSERT INTO audittrail (
  2221. trans_id, tablename, reference,
  2222. formname, action, employee_id,
  2223. transdate)
  2224. VALUES (?, ?, ?, ?, ?, ?)|;
  2225. @queryargs = (
  2226. $audittrail->{id},
  2227. $audittrail->{tablename},
  2228. $audittrail->{reference},
  2229. $audittrail->{formname},
  2230. $audittrail->{action}.
  2231. $employee_id,
  2232. $audittrail->{transdate}
  2233. );
  2234. } else {
  2235. $query = qq|
  2236. INSERT INTO audittrail
  2237. (trans_id, tablename, reference,
  2238. formname, action, employee_id)
  2239. VALUES (?, ?, ?, ?, ?)|;
  2240. @queryargs = (
  2241. $audittrail->{id},
  2242. $audittrail->{tablename},
  2243. $audittrail->{reference},
  2244. $audittrail->{formname},
  2245. $audittrail->{action}.
  2246. $employee_id,
  2247. );
  2248. }
  2249. $sth = $dbh->prepare($query);
  2250. $sth->execute(@queryargs)||$self->dberror($query);
  2251. }
  2252. } else {
  2253. $query = qq|SELECT current_timestamp|;
  2254. my ($timestamp) = $dbh->selectrow_array($query);
  2255. $rv = "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2256. }
  2257. $dbh->commit;
  2258. $rv;
  2259. }
  2260. 1;