summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: 6617edcd4b3e53aef61036ccd0a60e127e248235 (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. "%$str%";
  1658. }
  1659. sub redo_rows {
  1660. my ($self, $flds, $new, $count, $numrows) = @_;
  1661. my @ndx = ();
  1662. for (1 .. $count) {
  1663. push @ndx, { num => $new->[$_-1]->{runningnumber}, ndx => $_ }
  1664. }
  1665. my $i = 0;
  1666. # fill rows
  1667. foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
  1668. $i++;
  1669. $j = $item->{ndx} - 1;
  1670. for (@{$flds}) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1671. }
  1672. # delete empty rows
  1673. for $i ($count + 1 .. $numrows) {
  1674. for (@{$flds}) { delete $self->{"${_}_$i"} }
  1675. }
  1676. }
  1677. sub get_partsgroup {
  1678. my ($self, $myconfig, $p) = @_;
  1679. my $dbh = $self->{dbh};
  1680. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1681. FROM partsgroup pg
  1682. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1683. my $where;
  1684. my $sortorder = "partsgroup";
  1685. if ($p->{searchitems} eq 'part') {
  1686. $where = qq| WHERE (p.inventory_accno_id > 0
  1687. AND p.income_accno_id > 0)|;
  1688. }
  1689. if ($p->{searchitems} eq 'service') {
  1690. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1691. }
  1692. if ($p->{searchitems} eq 'assembly') {
  1693. $where = qq| WHERE p.assembly = '1'|;
  1694. }
  1695. if ($p->{searchitems} eq 'labor') {
  1696. $where = qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1697. }
  1698. if ($p->{searchitems} eq 'nolabor') {
  1699. $where = qq| WHERE p.income_accno_id > 0|;
  1700. }
  1701. if ($p->{all}) {
  1702. $query = qq|SELECT id, partsgroup
  1703. FROM partsgroup|;
  1704. }
  1705. my @queryargs = ();
  1706. if ($p->{language_code}) {
  1707. $sortorder = "translation";
  1708. $query = qq|
  1709. SELECT DISTINCT pg.id, pg.partsgroup,
  1710. t.description AS translation
  1711. FROM partsgroup pg
  1712. JOIN parts p ON (p.partsgroup_id = pg.id)
  1713. LEFT JOIN translation t ON (t.trans_id = pg.id
  1714. AND t.language_code = ?)|;
  1715. @queryargs = ($p->{language_code});
  1716. }
  1717. $query .= qq| $where ORDER BY $sortorder|;
  1718. my $sth = $dbh->prepare($query);
  1719. $sth->execute(@queryargs)|| $self->dberror($query);
  1720. $self->{all_partsgroup} = ();
  1721. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1722. push @{ $self->{all_partsgroup} }, $ref;
  1723. }
  1724. $sth->finish;
  1725. $dbh->commit;
  1726. }
  1727. sub update_status {
  1728. my ($self, $myconfig) = @_;
  1729. # no id return
  1730. return unless $self->{id};
  1731. my $dbh = $self->{dbh};
  1732. my %queued = split / +/, $self->{queued};
  1733. my $spoolfile = ($queued{$self->{formname}}) ? "'$queued{$self->{formname}}'" : 'NULL';
  1734. my $query = qq|DELETE FROM status
  1735. WHERE formname = ?
  1736. AND trans_id = ?|;
  1737. $sth=$dbh->prepare($query);
  1738. $sth->execute($self->{formname}, $self->{id}) || $self->dberror($query);
  1739. $sth->finish;
  1740. my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
  1741. my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
  1742. $query = qq|
  1743. INSERT INTO status
  1744. (trans_id, printed, emailed, spoolfile, formname)
  1745. VALUES (?, ?, ?, ?, ?)|;
  1746. $sth = $dbh->prepare($query);
  1747. $sth->execute($self->{id}, $printed, $emailed, $spoolfile,
  1748. $self->{formname});
  1749. $sth->finish;
  1750. $dbh->commit;
  1751. }
  1752. sub save_status {
  1753. my ($self) = @_;
  1754. $dbh = $self->{dbh};
  1755. my $formnames = $self->{printed};
  1756. my $emailforms = $self->{emailed};
  1757. my $query = qq|DELETE FROM status
  1758. WHERE trans_id = ?|;
  1759. my $sth = $dbh->prepare($query);
  1760. $sth->execute($self->{id});
  1761. $sth->finish;
  1762. my %queued;
  1763. my $formname;
  1764. if ($self->{queued}) {
  1765. %queued = split / +/, $self->{queued};
  1766. foreach $formname (keys %queued) {
  1767. $printed = ($self->{printed} =~ /$formname/) ? "1" : "0";
  1768. $emailed = ($self->{emailed} =~ /$formname/) ? "1" : "0";
  1769. if ($queued{$formname}) {
  1770. $query = qq|
  1771. INSERT INTO status
  1772. (trans_id, printed, emailed,
  1773. spoolfile, formname)
  1774. VALUES (?, ?, ?, ?, ?)|;
  1775. $sth = $dbh->prepare($query);
  1776. $sth->execute($self->{id}, $pinted, $emailed,
  1777. $queued{$formname}, $formname)
  1778. || $self->dberror($query);
  1779. $sth->finish;
  1780. }
  1781. $formnames =~ s/$formname//;
  1782. $emailforms =~ s/$formname//;
  1783. }
  1784. }
  1785. # save printed, emailed info
  1786. $formnames =~ s/^ +//g;
  1787. $emailforms =~ s/^ +//g;
  1788. my %status = ();
  1789. for (split / +/, $formnames) { $status{$_}{printed} = 1 }
  1790. for (split / +/, $emailforms) { $status{$_}{emailed} = 1 }
  1791. foreach my $formname (keys %status) {
  1792. $printed = ($formnames =~ /$self->{formname}/) ? "1" : "0";
  1793. $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
  1794. $query = qq|
  1795. INSERT INTO status (trans_id, printed, emailed,
  1796. formname)
  1797. VALUES (?, ?, ?, ?)|;
  1798. $sth = $dbh->prepare($query);
  1799. $sth->execute($self->{id}, $printed, $emailed, $formname);
  1800. $sth->finish;
  1801. }
  1802. $dbh->commit;
  1803. }
  1804. sub get_recurring {
  1805. my ($self) = @_;
  1806. $dbh = $self->{dbh};
  1807. my $query = qq/
  1808. SELECT s.*, se.formname || ':' || se.format AS emaila,
  1809. se.message, sp.formname || ':' ||
  1810. sp.format || ':' || sp.printer AS printa
  1811. FROM recurring s
  1812. LEFT JOIN recurringemail se ON (s.id = se.id)
  1813. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  1814. WHERE s.id = ?/;
  1815. my $sth = $dbh->prepare($query);
  1816. $sth->execute($self->{id}) || $self->dberror($query);
  1817. for (qw(email print)) { $self->{"recurring$_"} = "" }
  1818. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1819. for (keys %$ref) { $self->{"recurring$_"} = $ref->{$_} }
  1820. $self->{recurringemail} .= "$ref->{emaila}:";
  1821. $self->{recurringprint} .= "$ref->{printa}:";
  1822. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  1823. }
  1824. $sth->finish;
  1825. chop $self->{recurringemail};
  1826. chop $self->{recurringprint};
  1827. if ($self->{recurringstartdate}) {
  1828. $self->{recurringreference} = $self->escape($self->{recurringreference},1);
  1829. $self->{recurringmessage} = $self->escape($self->{recurringmessage},1);
  1830. for (qw(reference startdate repeat unit howmany
  1831. payment print email message)) {
  1832. $self->{recurring} .= qq|$self->{"recurring$_"},|
  1833. }
  1834. chop $self->{recurring};
  1835. }
  1836. $dbh->commit;
  1837. }
  1838. sub save_recurring {
  1839. my ($self, $dbh2, $myconfig) = @_;
  1840. my $dbh = $self->{dbh};
  1841. my $query;
  1842. $query = qq|DELETE FROM recurring
  1843. WHERE id = ?|;
  1844. $sth = $dbh->prepare($query);
  1845. $sth->execute($self->{id}) || $self->dberror($query);
  1846. $query = qq|DELETE FROM recurringemail
  1847. WHERE id = ?|;
  1848. $sth = $dbh->prepare($query);
  1849. $sth->execute($self->{id}) || $self->dberror($query);
  1850. $query = qq|DELETE FROM recurringprint
  1851. WHERE id = ?|;
  1852. $sth = $dbh->prepare($query);
  1853. $sth->execute($self->{id}) || $self->dberror($query);
  1854. if ($self->{recurring}) {
  1855. my %s = ();
  1856. ($s{reference}, $s{startdate}, $s{repeat}, $s{unit},
  1857. $s{howmany}, $s{payment}, $s{print}, $s{email},
  1858. $s{message})
  1859. = split /,/, $self->{recurring};
  1860. for (qw(reference message)) { $s{$_} = $self->unescape($s{$_}) }
  1861. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  1862. # calculate enddate
  1863. my $advance = $s{repeat} * ($s{howmany} - 1);
  1864. my %interval;
  1865. $interval{'Pg'} =
  1866. "(date '$s{startdate}' + interval '$advance $s{unit}')";
  1867. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  1868. my ($enddate) = $dbh->selectrow_array($query);
  1869. # calculate nextdate
  1870. $query = qq|
  1871. SELECT current_date - date ? AS a,
  1872. date ? - current_date AS b|;
  1873. $sth = $dbh->prepare($query);
  1874. $sth->execute($s{startdate}, $enddate);
  1875. my ($a, $b) = $sth->fetchrow_array;
  1876. if ($a + $b) {
  1877. $advance = int(($a / ($a + $b)) * ($s{howmany} - 1) + 1) * $s{repeat};
  1878. } else {
  1879. $advance = 0;
  1880. }
  1881. my $nextdate = $enddate;
  1882. if ($advance > 0) {
  1883. if ($advance < ($s{repeat} * $s{howmany})) {
  1884. %interval = ( 'Pg' => "(date '$s{startdate}' + interval '$advance $s{unit}')",
  1885. 'DB2' => qq|(date ('$s{startdate}') + "$advance $s{unit}")|,);
  1886. $interval{Oracle} = $interval{PgPP} = $interval{Pg};
  1887. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  1888. ($nextdate) = $dbh->selectrow_array($query);
  1889. }
  1890. } else {
  1891. $nextdate = $s{startdate};
  1892. }
  1893. if ($self->{recurringnextdate}) {
  1894. $nextdate = $self->{recurringnextdate};
  1895. $query = qq|SELECT '$enddate' - date '$nextdate'|;
  1896. if ($dbh->selectrow_array($query) < 0) {
  1897. undef $nextdate;
  1898. }
  1899. }
  1900. $self->{recurringpayment} *= 1;
  1901. $query = qq|
  1902. INSERT INTO recurring
  1903. (id, reference, startdate, enddate, nextdate,
  1904. repeat, unit, howmany, payment)
  1905. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  1906. $sth = $dbh->prepare($query);
  1907. $sth->execute($self->{id}, $s{reference}, $s{startdate},
  1908. $enddate, $nextdate, $s{repeat}, $s{unit}, $s{howmany},
  1909. $s{payment});
  1910. my @p;
  1911. my $p;
  1912. my $i;
  1913. my $sth;
  1914. if ($s{email}) {
  1915. # formname:format
  1916. @p = split /:/, $s{email};
  1917. $query = qq|INSERT INTO recurringemail (id, formname, format, message)
  1918. VALUES (?, ?, ?, ?)|;
  1919. $sth = $dbh->prepare($query) || $self->dberror($query);
  1920. for ($i = 0; $i <= $#p; $i += 2) {
  1921. $sth->execute($self->{id}, $p[$i], $p[$i+1],
  1922. $s{message});
  1923. }
  1924. $sth->finish;
  1925. }
  1926. if ($s{print}) {
  1927. # formname:format:printer
  1928. @p = split /:/, $s{print};
  1929. $query = qq|INSERT INTO recurringprint (id, formname, format, printer)
  1930. VALUES (?, ?, ?, ?)|;
  1931. $sth = $dbh->prepare($query) || $self->dberror($query);
  1932. for ($i = 0; $i <= $#p; $i += 3) {
  1933. $p = ($p[$i+2]) ? $p[$i+2] : "";
  1934. $sth->execute($self->{id}, $p[$i], $p[$i+1], $p);
  1935. }
  1936. $sth->finish;
  1937. }
  1938. }
  1939. $dbh->commit;
  1940. }
  1941. sub save_intnotes {
  1942. my ($self, $myconfig, $vc) = @_;
  1943. # no id return
  1944. return unless $self->{id};
  1945. my $dbh = $self->dbconnect($myconfig);
  1946. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  1947. $sth=$dbh->prepare($query);
  1948. $sth->execute($self->{intnotes}, $self->{id}) || $self->dberror($query);
  1949. $dbh->commit;
  1950. }
  1951. sub update_defaults {
  1952. my ($self, $myconfig, $fld) = @_;
  1953. if (!$self->{dbh} && $self){
  1954. $self->db_init($myconfig);
  1955. }
  1956. my $dbh = $self->{dbh};
  1957. if (!$self){
  1958. $dbh = $_[3];
  1959. }
  1960. my $query = qq|
  1961. SELECT value FROM defaults
  1962. WHERE setting_key = ? FOR UPDATE|;
  1963. $sth = $dbh->prepare($query);
  1964. $sth->execute($fld);
  1965. ($_) = $sth->fetchrow_array();
  1966. $_ = "0" unless $_;
  1967. # check for and replace
  1968. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  1969. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  1970. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  1971. # <?lsmb PHONE ?> for customer and vendors
  1972. my $num = $_;
  1973. ($num) = $num =~ /(\d+)/;
  1974. if (defined $num) {
  1975. my $incnum;
  1976. # if we have leading zeros check how long it is
  1977. if ($num =~ /^0/) {
  1978. my $l = length $num;
  1979. $incnum = $num + 1;
  1980. $l -= length $incnum;
  1981. # pad it out with zeros
  1982. my $padzero = "0" x $l;
  1983. $incnum = ("0" x $l) . $incnum;
  1984. } else {
  1985. $incnum = $num + 1;
  1986. }
  1987. s/$num/$incnum/;
  1988. }
  1989. my $dbvar = $_;
  1990. my $var = $_;
  1991. my $str;
  1992. my $param;
  1993. if (/<\?lsmb /) {
  1994. while (/<\?lsmb /) {
  1995. s/<\?lsmb .*? \?>//;
  1996. last unless $&;
  1997. $param = $&;
  1998. $str = "";
  1999. if ($param =~ /<\?lsmb date \?>/i) {
  2000. $str = ($self->split_date($myconfig->{dateformat}, $self->{transdate}))[0];
  2001. $var =~ s/$param/$str/;
  2002. }
  2003. if ($param =~ /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i) {
  2004. my $fld = lc $&;
  2005. $fld =~ s/<\?lsmb //;
  2006. if ($fld =~ /name/) {
  2007. if ($self->{type}) {
  2008. $fld = $self->{vc};
  2009. }
  2010. }
  2011. my $p = $param;
  2012. $p =~ s/(<|>|%)//g;
  2013. my @p = split / /, $p;
  2014. my @n = split / /, uc $self->{$fld};
  2015. if ($#p > 0) {
  2016. for (my $i = 1; $i <= $#p; $i++) {
  2017. $str .= substr($n[$i-1], 0, $p[$i]);
  2018. }
  2019. } else {
  2020. ($str) = split /--/, $self->{$fld};
  2021. }
  2022. $var =~ s/$param/$str/;
  2023. $var =~ s/\W//g if $fld eq 'phone';
  2024. }
  2025. if ($param =~ /<\?lsmb (yy|mm|dd)/i) {
  2026. my $p = $param;
  2027. $p =~ s/(<|>|%)//g;
  2028. my $spc = $p;
  2029. $spc =~ s/\w//g;
  2030. $spc = substr($spc, 0, 1);
  2031. my %d = ( yy => 1, mm => 2, dd => 3 );
  2032. my @p = ();
  2033. my @a = $self->split_date($myconfig->{dateformat}, $self->{transdate});
  2034. for (sort keys %d) { push @p, $a[$d{$_}] if ($p =~ /$_/) }
  2035. $str = join $spc, @p;
  2036. $var =~ s/$param/$str/;
  2037. }
  2038. if ($param =~ /<\?lsmb curr/i) {
  2039. $var =~ s/$param/$self->{currency}/;
  2040. }
  2041. }
  2042. }
  2043. $query = qq|
  2044. UPDATE defaults
  2045. SET value = ?
  2046. WHERE setting_key = ?|;
  2047. $sth = $dbh->prepare($query);
  2048. $sth->execute($dbvar, $fld) || $self->dberror($query);
  2049. $dbh->commit;
  2050. $var;
  2051. }
  2052. sub db_prepare_vars {
  2053. for (@_){
  2054. if (!$self->{$_} and $self->{$_} ne "0"){
  2055. undef $self->{$_};
  2056. }
  2057. }
  2058. }
  2059. sub split_date {
  2060. my ($self, $dateformat, $date) = @_;
  2061. my @d = localtime;
  2062. my $mm;
  2063. my $dd;
  2064. my $yy;
  2065. my $rv;
  2066. if (! $date) {
  2067. $dd = $d[3];
  2068. $mm = ++$d[4];
  2069. $yy = substr($d[5],-2);
  2070. $mm = substr("0$mm", -2);
  2071. $dd = substr("0$dd", -2);
  2072. }
  2073. if ($dateformat =~ /^yy/) {
  2074. if ($date) {
  2075. if ($date =~ /\D/) {
  2076. ($yy, $mm, $dd) = split /\D/, $date;
  2077. $mm *= 1;
  2078. $dd *= 1;
  2079. $mm = substr("0$mm", -2);
  2080. $dd = substr("0$dd", -2);
  2081. $yy = substr($yy, -2);
  2082. $rv = "$yy$mm$dd";
  2083. } else {
  2084. $rv = $date;
  2085. }
  2086. } else {
  2087. $rv = "$yy$mm$dd";
  2088. }
  2089. }
  2090. if ($dateformat =~ /^mm/) {
  2091. if ($date) {
  2092. if ($date =~ /\D/) {
  2093. ($mm, $dd, $yy) = split /\D/, $date;
  2094. $mm *= 1;
  2095. $dd *= 1;
  2096. $mm = substr("0$mm", -2);
  2097. $dd = substr("0$dd", -2);
  2098. $yy = substr($yy, -2);
  2099. $rv = "$mm$dd$yy";
  2100. } else {
  2101. $rv = $date;
  2102. }
  2103. } else {
  2104. $rv = "$mm$dd$yy";
  2105. }
  2106. }
  2107. if ($dateformat =~ /^dd/) {
  2108. if ($date) {
  2109. if ($date =~ /\D/) {
  2110. ($dd, $mm, $yy) = split /\D/, $date;
  2111. $mm *= 1;
  2112. $dd *= 1;
  2113. $mm = substr("0$mm", -2);
  2114. $dd = substr("0$dd", -2);
  2115. $yy = substr($yy, -2);
  2116. $rv = "$dd$mm$yy";
  2117. } else {
  2118. $rv = $date;
  2119. }
  2120. } else {
  2121. $rv = "$dd$mm$yy";
  2122. }
  2123. }
  2124. ($rv, $yy, $mm, $dd);
  2125. }
  2126. sub from_to {
  2127. my ($self, $yy, $mm, $interval) = @_;
  2128. use Time::Local;
  2129. my @t;
  2130. my $dd = 1;
  2131. my $fromdate = "$yy${mm}01";
  2132. my $bd = 1;
  2133. if (defined $interval) {
  2134. if ($interval == 12) {
  2135. $yy++;
  2136. } else {
  2137. if (($mm += $interval) > 12) {
  2138. $mm -= 12;
  2139. $yy++;
  2140. }
  2141. if ($interval == 0) {
  2142. @t = localtime(time);
  2143. $dd = $t[3];
  2144. $mm = $t[4] + 1;
  2145. $yy = $t[5] + 1900;
  2146. $bd = 0;
  2147. }
  2148. }
  2149. } else {
  2150. if (++$mm > 12) {
  2151. $mm -= 12;
  2152. $yy++;
  2153. }
  2154. }
  2155. $mm--;
  2156. @t = localtime(timelocal(0,0,0,$dd,$mm,$yy) - $bd);
  2157. $t[4]++;
  2158. $t[4] = substr("0$t[4]",-2);
  2159. $t[3] = substr("0$t[3]",-2);
  2160. $t[5] += 1900;
  2161. ($fromdate, "$t[5]$t[4]$t[3]");
  2162. }
  2163. sub audittrail {
  2164. my ($self, $dbh, $myconfig, $audittrail) = @_;
  2165. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2166. my $query;
  2167. my $rv;
  2168. my $disconnect;
  2169. if (! $dbh) {
  2170. $dbh = $self->{dbh};
  2171. }
  2172. # if we have an id add audittrail, otherwise get a new timestamp
  2173. my @queryargs;
  2174. if ($audittrail->{id}) {
  2175. $query = qq|
  2176. SELECT value FROM defaults
  2177. WHERE setting_key = 'audittrail'|;
  2178. if ($dbh->selectrow_array($query)) {
  2179. my ($null, $employee_id) = $self->get_employee($dbh);
  2180. if ($self->{audittrail} && !$myconfig) {
  2181. chop $self->{audittrail};
  2182. my @a = split /\|/, $self->{audittrail};
  2183. my %newtrail = ();
  2184. my $key;
  2185. my $i;
  2186. my @flds = qw(tablename reference formname action transdate);
  2187. # put into hash and remove dups
  2188. while (@a) {
  2189. $key = "$a[2]$a[3]";
  2190. $i = 0;
  2191. $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
  2192. splice @a, 0, 5;
  2193. }
  2194. $query = qq|
  2195. INSERT INTO audittrail
  2196. (trans_id, tablename, reference,
  2197. formname, action, transdate,
  2198. employee_id)
  2199. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2200. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2201. foreach $key (sort { $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate} } keys %newtrail) {
  2202. $i = 2;
  2203. $sth->bind_param(1, $audittrail->{id});
  2204. for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
  2205. $sth->bind_param($i++, $employee_id);
  2206. $sth->execute || $self->dberror;
  2207. $sth->finish;
  2208. }
  2209. }
  2210. if ($audittrail->{transdate}) {
  2211. $query = qq|
  2212. INSERT INTO audittrail (
  2213. trans_id, tablename, reference,
  2214. formname, action, employee_id,
  2215. transdate)
  2216. VALUES (?, ?, ?, ?, ?, ?)|;
  2217. @queryargs = (
  2218. $audittrail->{id},
  2219. $audittrail->{tablename},
  2220. $audittrail->{reference},
  2221. $audittrail->{formname},
  2222. $audittrail->{action}.
  2223. $employee_id,
  2224. $audittrail->{transdate}
  2225. );
  2226. } else {
  2227. $query = qq|
  2228. INSERT INTO audittrail
  2229. (trans_id, tablename, reference,
  2230. formname, action, employee_id)
  2231. VALUES (?, ?, ?, ?, ?)|;
  2232. @queryargs = (
  2233. $audittrail->{id},
  2234. $audittrail->{tablename},
  2235. $audittrail->{reference},
  2236. $audittrail->{formname},
  2237. $audittrail->{action}.
  2238. $employee_id,
  2239. );
  2240. }
  2241. $sth = $dbh->prepare($query);
  2242. $sth->execute(@queryargs)||$self->dberror($query);
  2243. }
  2244. } else {
  2245. $query = qq|SELECT current_timestamp|;
  2246. my ($timestamp) = $dbh->selectrow_array($query);
  2247. $rv = "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2248. }
  2249. $dbh->commit;
  2250. $rv;
  2251. }
  2252. 1;