summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: e69834dfdc850886050113cc96fbcb7ee764adf6 (plain)
  1. #=====================================================================
  2. # LedgerSMB
  3. # Small Medium Business Accounting software
  4. # http://www.ledgersmb.org/
  5. #
  6. # Copyright (C) 2006
  7. # This work contains copyrighted information from a number of sources all used
  8. # with permission.
  9. #
  10. # This file contains source code included with or based on SQL-Ledger which
  11. # is Copyright Dieter Simader and DWS Systems Inc. 2000-2005 and licensed
  12. # under the GNU General Public License version 2 or, at your option, any later
  13. # version. For a full list including contact information of contributors,
  14. # maintainers, and copyright holders, see the CONTRIBUTORS file.
  15. #
  16. # Original Copyright Notice from SQL-Ledger 2.6.17 (before the fork):
  17. # Copyright (C) 2000
  18. #
  19. # Author: DWS Systems Inc.
  20. # Web: http://www.sql-ledger.org
  21. #
  22. # Contributors: Thomas Bayen <bayen@gmx.de>
  23. # Antti Kaihola <akaihola@siba.fi>
  24. # Moritz Bunkus (tex)
  25. # Jim Rawlings <jim@your-dba.com> (DB2)
  26. #======================================================================
  27. #
  28. # This file has undergone whitespace cleanup.
  29. #
  30. #======================================================================
  31. #
  32. # main package
  33. #
  34. #======================================================================
  35. use Math::BigFloat lib=>'GMP';
  36. use LedgerSMB::Sysconfig;
  37. package Form;
  38. sub new {
  39. my $type = shift;
  40. my $argstr = shift;
  41. read(STDIN, $_, $ENV{CONTENT_LENGTH});
  42. if ($argstr){
  43. $_ = $argstr;
  44. }
  45. elsif ($ENV{QUERY_STRING}) {
  46. $_ = $ENV{QUERY_STRING};
  47. }
  48. elsif ($ARGV[0]) {
  49. $_ = $ARGV[0];
  50. }
  51. %$self = split /[&=]/;
  52. for (keys %$self) { $self->{$_} = unescape("", $self->{$_}) }
  53. if (substr($self->{action}, 0, 1) !~ /( |\.)/) {
  54. $self->{action} = lc $self->{action};
  55. $self->{action} =~ s/( |-|,|\#|\/|\.$)/_/g;
  56. }
  57. $self->{menubar} = 1 if $self->{path} =~ /lynx/i;
  58. #menubar will be deprecated, replaced with below
  59. $self->{lynx} = 1 if $self->{path} =~ /lynx/i;
  60. $self->{version} = "1.2.0 Beta 1";
  61. $self->{dbversion} = "1.2.0";
  62. bless $self, $type;
  63. }
  64. sub debug {
  65. my ($self, $file) = @_;
  66. if ($file) {
  67. open(FH, "> $file") or die $!;
  68. for (sort keys %$self) { print FH "$_ = $self->{$_}\n" }
  69. close(FH);
  70. } else {
  71. print "\n";
  72. for (sort keys %$self) { print "$_ = $self->{$_}\n" }
  73. }
  74. }
  75. sub escape {
  76. my ($self, $str, $beenthere) = @_;
  77. # for Apache 2 we escape strings twice
  78. if (($ENV{SERVER_SIGNATURE} =~ /Apache\/2\.(\d+)\.(\d+)/) && !$beenthere) {
  79. $str = $self->escape($str, 1) if $1 == 0 && $2 < 44;
  80. }
  81. $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
  82. $str;
  83. }
  84. sub unescape {
  85. my ($self, $str) = @_;
  86. $str =~ tr/+/ /;
  87. $str =~ s/\\$//;
  88. $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
  89. $str =~ s/\r?\n/\n/g;
  90. $str;
  91. }
  92. sub quote {
  93. my ($self, $str) = @_;
  94. if ($str && ! ref($str)) {
  95. $str =~ s/"/&quot;/g;
  96. }
  97. $str;
  98. }
  99. sub unquote {
  100. my ($self, $str) = @_;
  101. if ($str && ! ref($str)) {
  102. $str =~ s/&quot;/"/g;
  103. }
  104. $str;
  105. }
  106. sub hide_form {
  107. my $self = shift;
  108. if (@_) {
  109. for (@_) {
  110. print qq|<input type="hidden" name="$_" value="|.$self->quote($self->{$_}).qq|" />\n|
  111. }
  112. } else {
  113. delete $self->{header};
  114. for (sort keys %$self) {
  115. print qq|<input type="hidden" name="$_" value="|.$self->quote($self->{$_}).qq|" />\n|
  116. }
  117. }
  118. }
  119. sub error {
  120. my ($self, $msg) = @_;
  121. if ($ENV{HTTP_USER_AGENT}) {
  122. $self->{msg} = $msg;
  123. $self->{format} = "html";
  124. $self->format_string('msg');
  125. delete $self->{pre};
  126. if (!$self->{header}) {
  127. $self->header;
  128. }
  129. print qq|<body><h2 class="error">Error!</h2> <p><b>$self->{msg}</b></body>|;
  130. exit;
  131. } else {
  132. if ($self->{error_function}) {
  133. &{ $self->{error_function} }($msg);
  134. } else {
  135. die "Error: $msg\n";
  136. }
  137. }
  138. }
  139. sub info {
  140. my ($self, $msg) = @_;
  141. if ($ENV{HTTP_USER_AGENT}) {
  142. $msg =~ s/\n/<br>/g;
  143. delete $self->{pre};
  144. if (!$self->{header}) {
  145. $self->header;
  146. print qq| <body>|;
  147. $self->{header} = 1;
  148. }
  149. print "<b>$msg</b>";
  150. } else {
  151. if ($self->{info_function}) {
  152. &{ $self->{info_function} }($msg);
  153. } else {
  154. print "$msg\n";
  155. }
  156. }
  157. }
  158. sub numtextrows {
  159. my ($self, $str, $cols, $maxrows) = @_;
  160. my $rows = 0;
  161. for (split /\n/, $str) {
  162. $rows += int (((length) - 2)/$cols) + 1
  163. }
  164. $maxrows = $rows unless defined $maxrows;
  165. return ($rows > $maxrows) ? $maxrows : $rows;
  166. }
  167. sub dberror {
  168. my ($self, $msg) = @_;
  169. $self->error("$msg\n".$DBI::errstr);
  170. }
  171. sub isblank {
  172. my ($self, $name, $msg) = @_;
  173. $self->error($msg) if $self->{$name} =~ /^\s*$/;
  174. }
  175. sub header {
  176. my ($self, $init, $headeradd) = @_;
  177. return if $self->{header};
  178. my ($stylesheet, $favicon, $charset);
  179. if ($ENV{HTTP_USER_AGENT}) {
  180. if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
  181. $stylesheet = qq|<link rel="stylesheet" href="css/$self->{stylesheet}" type="text/css" title="LedgerSMB stylesheet" />\n|;
  182. }
  183. if ($self->{charset}) {
  184. $charset = qq|<meta http-equiv="content-type" content="text/html; charset=$self->{charset}" />\n|;
  185. }
  186. $self->{titlebar} = ($self->{title}) ? "$self->{title} - $self->{titlebar}" : $self->{titlebar};
  187. print qq|Content-Type: text/html\n\n
  188. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  189. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  190. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  191. <head>
  192. <title>$self->{titlebar}</title>
  193. <meta http-equiv="Pragma" content="no-cache" />
  194. <meta http-equiv="Expires" content="-1" />
  195. <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  196. $stylesheet
  197. $charset
  198. <meta name="robots" content="noindex,nofollow" />
  199. $headeradd
  200. </head>
  201. $self->{pre} \n|;
  202. }
  203. $self->{header} = 1;
  204. }
  205. sub redirect {
  206. my ($self, $msg) = @_;
  207. use List::Util qw(first);
  208. if ($self->{callback}) {
  209. main::redirect();
  210. } else {
  211. $self->info($msg);
  212. }
  213. }
  214. sub sort_columns {
  215. my ($self, @columns) = @_;
  216. if ($self->{sort}) {
  217. if (@columns) {
  218. @columns = grep !/^$self->{sort}$/, @columns;
  219. splice @columns, 0, 0, $self->{sort};
  220. }
  221. }
  222. @columns;
  223. }
  224. sub sort_order {
  225. my ($self, $columns, $ordinal) = @_;
  226. # setup direction
  227. if ($self->{direction}) {
  228. if ($self->{sort} eq $self->{oldsort}) {
  229. if ($self->{direction} eq 'ASC') {
  230. $self->{direction} = "DESC";
  231. } else {
  232. $self->{direction} = "ASC";
  233. }
  234. }
  235. } else {
  236. $self->{direction} = "ASC";
  237. }
  238. $self->{oldsort} = $self->{sort};
  239. my @a = $self->sort_columns(@{$columns});
  240. if (%$ordinal) {
  241. $a[0] = ($ordinal->{$a[$_]}) ? "$ordinal->{$a[0]} $self->{direction}" : "$a[0] $self->{direction}";
  242. for (1 .. $#a) {
  243. $a[$_] = $ordinal->{$a[$_]} if $ordinal->{$a[$_]}
  244. }
  245. } else {
  246. $a[0] .= " $self->{direction}";
  247. }
  248. $sortorder = join ',', @a;
  249. $sortorder;
  250. }
  251. sub format_amount {
  252. my ($self, $myconfig, $amount, $places, $dash) = @_;
  253. my $negative ;
  254. if ($amount){
  255. $amount = $self->parse_amount($myconfig, $amount);
  256. $negative = ($amount < 0);
  257. $amount =~ s/-//;
  258. }
  259. if ($places =~ /\d+/) {
  260. #$places = 4 if $places == 2;
  261. $amount = $self->round_amount($amount, $places);
  262. }
  263. # is the amount negative
  264. # Parse $myconfig->{numberformat}
  265. my ($ts, $ds) = ($1, $2);
  266. if ($amount) {
  267. if ($myconfig->{numberformat}) {
  268. my ($whole, $dec) = split /\./, "$amount";
  269. $amount = join '', reverse split //, $whole;
  270. if ($places) {
  271. $dec .= "0" x $places;
  272. $dec = substr($dec, 0, $places);
  273. }
  274. if ($myconfig->{numberformat} eq '1,000.00') {
  275. $amount =~ s/\d{3,}?/$&,/g;
  276. $amount =~ s/,$//;
  277. $amount = join '', reverse split //, $amount;
  278. $amount .= "\.$dec" if ($dec ne "");
  279. }
  280. if ($myconfig->{numberformat} eq '1 000.00') {
  281. $amount =~ s/\d{3,}?/$& /g;
  282. $amount =~ s/\s$//;
  283. $amount = join '', reverse split //, $amount;
  284. $amount .= "\.$dec" if ($dec ne "");
  285. }
  286. if ($myconfig->{numberformat} eq "1'000.00") {
  287. $amount =~ s/\d{3,}?/$&'/g;
  288. $amount =~ s/'$//;
  289. $amount = join '', reverse split //, $amount;
  290. $amount .= "\.$dec" if ($dec ne "");
  291. }
  292. if ($myconfig->{numberformat} eq '1.000,00') {
  293. $amount =~ s/\d{3,}?/$&./g;
  294. $amount =~ s/\.$//;
  295. $amount = join '', reverse split //, $amount;
  296. $amount .= ",$dec" if ($dec ne "");
  297. }
  298. if ($myconfig->{numberformat} eq '1000,00') {
  299. $amount = "$whole";
  300. $amount .= ",$dec" if ($dec ne "");
  301. }
  302. if ($myconfig->{numberformat} eq '1000.00') {
  303. $amount = "$whole";
  304. $amount .= ".$dec" if ($dec ne "");
  305. }
  306. if ($dash =~ /-/) {
  307. $amount = ($negative) ? "($amount)" : "$amount";
  308. } elsif ($dash =~ /DRCR/) {
  309. $amount = ($negative) ? "$amount DR" : "$amount CR";
  310. } else {
  311. $amount = ($negative) ? "-$amount" : "$amount";
  312. }
  313. }
  314. } else {
  315. if ($dash eq "0" && $places) {
  316. if ($myconfig->{numberformat} eq '1.000,00') {
  317. $amount = "0".","."0" x $places;
  318. } else {
  319. $amount = "0"."."."0" x $places;
  320. }
  321. } else {
  322. $amount = ($dash ne "") ? "$dash" : "";
  323. }
  324. }
  325. $amount;
  326. }
  327. sub parse_amount {
  328. my ($self, $myconfig, $amount) = @_;
  329. if ($amount eq '') {
  330. return undef;
  331. }
  332. if (UNIVERSAL::isa($amount, 'Math::BigFloat')){ # Amount may not be an object
  333. return $amount;
  334. }
  335. my $numberformat = $myconfig->{numberformat};
  336. if (($numberformat eq '1.000,00') ||
  337. ($numberformat eq '1000,00')) {
  338. $amount =~ s/\.//g;
  339. $amount =~ s/,/./;
  340. }
  341. if ($numberformat eq '1 000.00'){
  342. $amount =~ s/\s//g;
  343. }
  344. if ($numberformat eq "1'000.00") {
  345. $amount =~ s/'//g;
  346. }
  347. $amount =~ s/,//g;
  348. if ($amount =~ s/\((\d*\.?\d*)\)/$1/){
  349. $amount = $1 * -1;
  350. }
  351. if ($amount =~ s/(\d*\.?\d*)\s?DR/$1/){
  352. $amount = $1 * -1;
  353. }
  354. $amount =~ s/\s?CR//;
  355. $amount = new Math::BigFloat($amount);
  356. return ($amount * 1);
  357. }
  358. sub round_amount {
  359. my ($self, $amount, $places) = @_;
  360. # These rounding rules follow from the previous implementation.
  361. # They should be changed to allow different rules for different accounts.
  362. Math::BigFloat->round_mode('+inf') if $amount >= 0;
  363. Math::BigFloat->round_mode('-inf') if $amount < 0;
  364. $amount = Math::BigFloat->new($amount)->ffround(-$places) if $places >= 0;
  365. $amount = Math::BigFloat->new($amount)->ffround(-($places-1)) if $places < 0;
  366. return $amount;
  367. }
  368. sub callproc {
  369. my $procname = shift @_;
  370. my $argstr = "";
  371. my @results;
  372. for (1 .. $#_){
  373. $argstr .= "?, ";
  374. }
  375. $argstr =~ s/\, $//;
  376. $query = "SELECT $procname";
  377. $query =~ s/\(\)/$argstr/;
  378. my $sth = $self->{dbh}->prepare($query);
  379. while (my $ref = $sth->fetchrow_hashref(NAME_lc)){
  380. push @results, $ref;
  381. }
  382. @results;
  383. }
  384. sub get_my_emp_num {
  385. my ($self, $myconfig, $form) = @_;
  386. %myconfig = %{$myconfig};
  387. my $dbh = $form->{dbh};
  388. # we got a connection, check the version
  389. my $query = qq|
  390. SELECT employeenumber FROM employee
  391. WHERE login = ?|;
  392. my $sth = $dbh->prepare($query);
  393. $sth->execute($form->{login}) || $form->dberror($query);
  394. $sth->execute;
  395. my ($id) = $sth->fetchrow_array;
  396. $sth->finish;
  397. $form->{'emp_num'} = $id;
  398. }
  399. sub parse_template {
  400. my ($self, $myconfig) = @_;
  401. my ($chars_per_line, $lines_on_first_page, $lines_on_second_page) = (0, 0, 0);
  402. my ($current_page, $current_line) = (1, 1);
  403. my $pagebreak = "";
  404. my $sum = 0;
  405. my $subdir = "";
  406. my $err = "";
  407. my %include = ();
  408. my $ok;
  409. if ($self->{language_code}) {
  410. if (-f "$self->{templates}/$self->{language_code}/$self->{IN}") {
  411. open(IN, "$self->{templates}/$self->{language_code}/$self->{IN}") or $self->error("$self->{IN} : $!");
  412. } else {
  413. open(IN, "$self->{templates}/$self->{IN}") or $self->error("$self->{IN} : $!");
  414. }
  415. } else {
  416. open(IN, "$self->{templates}/$self->{IN}") or $self->error("$self->{IN} : $!");
  417. }
  418. @_ = <IN>;
  419. close(IN);
  420. $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
  421. # OUT is used for the media, screen, printer, email
  422. # for postscript we store a copy in a temporary file
  423. my $fileid = time;
  424. my $tmpfile = $self->{IN};
  425. $tmpfile =~ s/\./_$self->{fileid}./ if $self->{fileid};
  426. $self->{tmpfile} = "${LedgerSMB::Sysconfig::userspath}/${fileid}_${tmpfile}";
  427. if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
  428. my $out = $self->{OUT};
  429. $self->{OUT} = ">$self->{tmpfile}";
  430. }
  431. if ($self->{OUT}) {
  432. open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
  433. } else {
  434. open(OUT, ">-") or $self->error("STDOUT : $!");
  435. $self->header;
  436. }
  437. # first we generate a tmpfile
  438. # read file and replace <?lsmb variable ?>
  439. while ($_ = shift) {
  440. $par = "";
  441. $var = $_;
  442. # detect pagebreak block and its parameters
  443. if (/<\?lsmb pagebreak ([0-9]+) ([0-9]+) ([0-9]+) \?>/) {
  444. $chars_per_line = $1;
  445. $lines_on_first_page = $2;
  446. $lines_on_second_page = $3;
  447. while ($_ = shift) {
  448. last if (/<\?lsmb end pagebreak \?>/);
  449. $pagebreak .= $_;
  450. }
  451. }
  452. if (/<\?lsmb foreach /) {
  453. # this one we need for the count
  454. chomp $var;
  455. $var =~ s/.*?<\?lsmb foreach (.+?) \?>/$1/;
  456. while ($_ = shift) {
  457. last if (/<\?lsmb end $var \?>/);
  458. # store line in $par
  459. $par .= $_;
  460. }
  461. # display contents of $self->{number}[] array
  462. for $i (0 .. $#{ $self->{$var} }) {
  463. if ($var =~ /^(part|service)$/) {
  464. next if $self->{$var}[$i] eq 'NULL';
  465. }
  466. # Try to detect whether a manual page break is necessary
  467. # but only if there was a <?lsmb pagebreak ... ?> block before
  468. if ($var eq 'number' || $var eq 'part' || $var eq 'service') {
  469. if ($chars_per_line && defined $self->{$var}) {
  470. my $line;
  471. my $lines = 0;
  472. my @d = qw(description);
  473. push @d, "itemnotes" if $self->{countitemnotes};
  474. foreach my $item (@d) {
  475. if ($self->{$item}[$i]) {
  476. foreach $line (split /\r?\n/, $self->{$item}[$i]) {
  477. $lines++;
  478. $lines += int(length($line) / $chars_per_line);
  479. }
  480. }
  481. }
  482. my $lpp;
  483. if ($current_page == 1) {
  484. $lpp = $lines_on_first_page;
  485. } else {
  486. $lpp = $lines_on_second_page;
  487. }
  488. # Yes we need a manual page break
  489. if (($current_line + $lines) > $lpp) {
  490. my $pb = $pagebreak;
  491. # replace the special variables <?lsmb sumcarriedforward ?>
  492. # and <?lsmb lastpage ?>
  493. my $psum = $self->format_amount($myconfig, $sum, 2);
  494. $pb =~ s/<\?lsmb sumcarriedforward \?>/$psum/g;
  495. $pb =~ s/<\?lsmb lastpage \?>/$current_page/g;
  496. # only "normal" variables are supported here
  497. # (no <?lsmb if, no <?lsmb foreach, no <?lsmb include)
  498. $pb =~ s/<\?lsmb (.+?) \?>/$self->{$1}/g;
  499. # page break block is ready to rock
  500. print(OUT $pb);
  501. $current_page++;
  502. $current_line = 1;
  503. $lines = 0;
  504. }
  505. $current_line += $lines;
  506. }
  507. $sum += $self->parse_amount($myconfig, $self->{linetotal}[$i]);
  508. }
  509. # don't parse par, we need it for each line
  510. print OUT $self->format_line($par, $i);
  511. }
  512. next;
  513. }
  514. # if not comes before if!
  515. if (/<\?lsmb if not /) {
  516. # check if it is not set and display
  517. chop;
  518. s/.*?<\?lsmb if not (.+?) \?>/$1/;
  519. if (! $self->{$_}) {
  520. while ($_ = shift) {
  521. last if (/<\?lsmb end /);
  522. # store line in $par
  523. $par .= $_;
  524. }
  525. $_ = $par;
  526. } else {
  527. while ($_ = shift) {
  528. last if (/<\?lsmb end /);
  529. }
  530. next;
  531. }
  532. }
  533. if (/<\? lsmb if /) {
  534. # check if it is set and display
  535. chop;
  536. s/.*?<\?lsmb if (.+?) \?>/$1/;
  537. if (/\s/) {
  538. @a = split;
  539. $ok = eval "$self->{$a[0]} $a[1] $a[2]";
  540. } else {
  541. $ok = $self->{$_};
  542. }
  543. if ($ok) {
  544. while ($_ = shift) {
  545. last if (/<\?lsmb end /);
  546. # store line in $par
  547. $par .= $_;
  548. }
  549. $_ = $par;
  550. } else {
  551. while ($_ = shift) {
  552. last if (/<\?lsmb end /);
  553. }
  554. next;
  555. }
  556. }
  557. # check for <?lsmb include filename ?>
  558. if (/<\?lsmb include /) {
  559. # get the filename
  560. chomp $var;
  561. $var =~ s/.*?<\?lsmb include (.+?) \?>/$1/;
  562. # remove / .. for security reasons
  563. $var =~ s/(\/|\.\.)//g;
  564. # assume loop after 10 includes of the same file
  565. next if ($include{$var} > 10);
  566. unless (open(INC, "$self->{templates}/$self->{language_code}/$var")) {
  567. $err = $!;
  568. $self->cleanup;
  569. $self->error("$self->{templates}/$self->{language_code}/$var : $err");
  570. }
  571. unshift(@_, <INC>);
  572. close(INC);
  573. $include{$var}++;
  574. next;
  575. }
  576. print OUT $self->format_line($_);
  577. }
  578. close(OUT);
  579. delete $self->{countitemnotes};
  580. # Convert the tex file to postscript
  581. if ($self->{format} =~ /(postscript|pdf)/) {
  582. use Cwd;
  583. $self->{cwd} = cwd();
  584. $self->{tmpdir} = "$self->{cwd}/${LedgerSMB::Sysconfig::userspath}";
  585. unless (chdir("${LedgerSMB::Sysconfig::userspath}")) {
  586. $err = $!;
  587. $self->cleanup;
  588. $self->error("chdir : $err");
  589. }
  590. $self->{tmpfile} =~ s/${LedgerSMB::Sysconfig::userspath}\///g;
  591. $self->{errfile} = $self->{tmpfile};
  592. $self->{errfile} =~ s/tex$/err/;
  593. my $r = 1;
  594. if ($self->{format} eq 'postscript') {
  595. system("latex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  596. while ($self->rerun_latex) {
  597. system("latex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  598. last if ++$r > 4;
  599. }
  600. $self->{tmpfile} =~ s/tex$/dvi/;
  601. $self->error($self->cleanup) if ! (-f $self->{tmpfile});
  602. system("dvips $self->{tmpfile} -o -q");
  603. $self->error($self->cleanup."dvips : $!") if ($?);
  604. $self->{tmpfile} =~ s/dvi$/ps/;
  605. }
  606. if ($self->{format} eq 'pdf') {
  607. system("pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  608. while ($self->rerun_latex) {
  609. system("pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  610. last if ++$r > 4;
  611. }
  612. $self->{tmpfile} =~ s/tex$/pdf/;
  613. $self->error($self->cleanup) if ! (-f $self->{tmpfile});
  614. }
  615. }
  616. if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
  617. if ($self->{media} eq 'email') {
  618. use LedgerSMB::Mailer;
  619. my $mail = new Mailer;
  620. for (qw(cc bcc subject message version format charset)) {
  621. $mail->{$_} = $self->{$_}
  622. }
  623. $mail->{to} = qq|$self->{email}|;
  624. $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
  625. $mail->{notify} = $self->{notify};
  626. $mail->{fileid} = "$fileid.";
  627. # if we send html or plain text inline
  628. if (($self->{format} =~ /(html|txt)/) &&
  629. ($self->{sendmode} eq 'inline')) {
  630. my $br = "";
  631. $br = "<br>" if $self->{format} eq 'html';
  632. $mail->{contenttype} = "text/$self->{format}";
  633. $mail->{message} =~ s/\r?\n/$br\n/g;
  634. $myconfig->{signature} =~ s/\\n/$br\n/g;
  635. $mail->{message} .= "$br\n-- $br\n$myconfig->{signature}\n$br" if $myconfig->{signature};
  636. unless (open(IN, $self->{tmpfile})) {
  637. $err = $!;
  638. $self->cleanup;
  639. $self->error("$self->{tmpfile} : $err");
  640. }
  641. while (<IN>) {
  642. $mail->{message} .= $_;
  643. }
  644. close(IN);
  645. } else {
  646. @{ $mail->{attachments} } = ($self->{tmpfile});
  647. $myconfig->{signature} =~ s/\\n/\n/g;
  648. $mail->{message} .= "\n-- \n$myconfig->{signature}" if $myconfig->{signature};
  649. }
  650. if ($err = $mail->send) {
  651. $self->cleanup;
  652. $self->error($err);
  653. }
  654. } else {
  655. $self->{OUT} = $out;
  656. unless (open(IN, $self->{tmpfile})) {
  657. $err = $!;
  658. $self->cleanup;
  659. $self->error("$self->{tmpfile} : $err");
  660. }
  661. binmode(IN);
  662. $self->{copies} = 1 if $self->{media} =~ /(screen|email|queue)/;
  663. chdir("$self->{cwd}");
  664. for my $i (1 .. $self->{copies}) {
  665. if ($self->{OUT}) {
  666. unless (open(OUT, $self->{OUT})) {
  667. $err = $!;
  668. $self->cleanup;
  669. $self->error("$self->{OUT} : $err");
  670. }
  671. } else {
  672. # launch application
  673. print qq|Content-Type: application/$self->{format}\n|.
  674. qq|Content-Disposition: attachment; filename="$self->{tmpfile}"\n\n|;
  675. unless (open(OUT, ">-")) {
  676. $err = $!;
  677. $self->cleanup;
  678. $self->error("STDOUT : $err");
  679. }
  680. }
  681. binmode(OUT);
  682. while (<IN>) {
  683. print OUT $_;
  684. }
  685. close(OUT);
  686. seek IN, 0, 0;
  687. }
  688. close(IN);
  689. }
  690. $self->cleanup;
  691. }
  692. }
  693. sub format_line {
  694. my $self = shift;
  695. $_ = shift;
  696. my $i = shift;
  697. my $str;
  698. my $newstr;
  699. my $pos;
  700. my $l;
  701. my $lf;
  702. my $line;
  703. my $var = "";
  704. my %a;
  705. my $offset;
  706. my $pad;
  707. my $item;
  708. while (/<\?lsmb (.+?) \?>/) {
  709. %a = ();
  710. foreach $item (split / /, $1) {
  711. my ($key, $value) = split /=/, $item;
  712. if ($value ne "") {
  713. $a{$key} = $value;
  714. } else {
  715. $var = $item;
  716. }
  717. }
  718. $str = (defined $i) ? $self->{$var}[$i] : $self->{$var};
  719. $newstr = $str;
  720. $self->{countitemnotes} = 1 if $var eq 'itemnotes';
  721. $var = $1;
  722. if ($var =~ /^if\s+not\s+/) {
  723. if ($str) {
  724. $var =~ s/if\s+not\s+//;
  725. s/<\?lsmb if\s+not\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  726. } else {
  727. s/<\?lsmb $var \?>//;
  728. }
  729. next;
  730. }
  731. if ($var =~ /^if\s+/) {
  732. if ($str) {
  733. s/<\?lsmb $var \?>//;
  734. } else {
  735. $var =~ s/if\s+//;
  736. s/<\?lsmb if\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  737. }
  738. next;
  739. }
  740. if ($var =~ /^end\s+/) {
  741. s/<\?lsmb $var \?>//;
  742. next;
  743. }
  744. if ($a{align} || $a{width} || $a{offset}) {
  745. $newstr = "";
  746. $offset = 0;
  747. $lf = "";
  748. foreach $str (split /\n/, $str) {
  749. $line = $str;
  750. $l = length $str;
  751. do {
  752. if (($pos = length $str) > $a{width}) {
  753. if (($pos = rindex $str, " ", $a{width}) > 0) {
  754. $line = substr($str, 0, $pos);
  755. }
  756. $pos = length $str if $pos == -1;
  757. }
  758. $l = length $line;
  759. # pad left, right or center
  760. $l = ($a{width} - $l);
  761. $pad = " " x $l;
  762. if ($a{align} =~ /right/i) {
  763. $line = " " x $offset . $pad . $line;
  764. }
  765. if ($a{align} =~ /left/i) {
  766. $line = " " x $offset . $line . $pad;
  767. }
  768. if ($a{align} =~ /center/i) {
  769. $pad = " " x ($l/2);
  770. $line = " " x $offset . $pad . $line;
  771. $pad = " " x ($l/2);
  772. $line .= $pad;
  773. }
  774. $newstr .= "$lf$line";
  775. $str = substr($str, $pos + 1);
  776. $line = $str;
  777. $lf = "\n";
  778. $offset = $a{offset};
  779. } while ($str);
  780. }
  781. }
  782. s/<\?lsmb (.+?) \?>/$newstr/;
  783. }
  784. $_;
  785. }
  786. sub cleanup {
  787. my $self = shift;
  788. chdir("$self->{tmpdir}");
  789. my @err = ();
  790. if (-f "$self->{errfile}") {
  791. open(FH, "$self->{errfile}");
  792. @err = <FH>;
  793. close(FH);
  794. }
  795. if ($self->{tmpfile}) {
  796. # strip extension
  797. $self->{tmpfile} =~ s/\.\w+$//g;
  798. my $tmpfile = $self->{tmpfile};
  799. unlink(<$tmpfile.*>);
  800. }
  801. chdir("$self->{cwd}");
  802. "@err";
  803. }
  804. sub rerun_latex {
  805. my $self = shift;
  806. my $a = 0;
  807. if (-f "$self->{errfile}") {
  808. open(FH, "$self->{errfile}");
  809. $a = grep /(longtable Warning:|Warning:.*?LastPage)/, <FH>;
  810. close(FH);
  811. }
  812. $a;
  813. }
  814. sub format_string {
  815. my ($self, @fields) = @_;
  816. my $format = $self->{format};
  817. if ($self->{format} =~ /(postscript|pdf)/) {
  818. $format = 'tex';
  819. }
  820. my %replace = (
  821. 'order' => {
  822. html => [ '<', '>', '\n', '\r' ],
  823. txt => [ '\n', '\r' ],
  824. tex => [ quotemeta('\\'), '&', '\n','\r',
  825. '\$', '%', '_', '#',
  826. quotemeta('^'), '{', '}', '<', '>', '£'
  827. ] },
  828. html => { '<' => '&lt;', '>' => '&gt;','\n' => '<br />',
  829. '\r' => '<br />' },
  830. txt => { '\n' => "\n", '\r' => "\r" },
  831. tex => {'&' => '\&', '$' => '\$', '%' => '\%', '_' => '\_',
  832. '#' => '\#', quotemeta('^') => '\^\\', '{' => '\{',
  833. '}' => '\}', '<' => '$<$', '>' => '$>$',
  834. '\n' => '\newline ', '\r' => '\newline ',
  835. '£' => '\pounds ', quotemeta('\\') => '/'}
  836. );
  837. my $key;
  838. foreach $key (@{ $replace{order}{$format} }) {
  839. for (@fields) { $self->{$_} =~ s/$key/$replace{$format}{$key}/g }
  840. }
  841. }
  842. sub datetonum {
  843. my ($self, $myconfig, $date, $picture) = @_;
  844. if ($date && $date =~ /\D/) {
  845. if ($myconfig->{dateformat} =~ /^yy/) {
  846. ($yy, $mm, $dd) = split /\D/, $date;
  847. }
  848. if ($myconfig->{dateformat} =~ /^mm/) {
  849. ($mm, $dd, $yy) = split /\D/, $date;
  850. }
  851. if ($myconfig->{dateformat} =~ /^dd/) {
  852. ($dd, $mm, $yy) = split /\D/, $date;
  853. }
  854. $dd *= 1;
  855. $mm *= 1;
  856. $yy += 2000 if length $yy == 2;
  857. $dd = substr("0$dd", -2);
  858. $mm = substr("0$mm", -2);
  859. $date = "$yy$mm$dd";
  860. }
  861. $date;
  862. }
  863. sub add_date {
  864. my ($self, $myconfig, $date, $repeat, $unit) = @_;
  865. use Time::Local;
  866. my $diff = 0;
  867. my $spc = $myconfig->{dateformat};
  868. $spc =~ s/\w//g;
  869. $spc = substr($spc, 0, 1);
  870. if ($date) {
  871. if ($date =~ /\D/) {
  872. if ($myconfig->{dateformat} =~ /^yy/) {
  873. ($yy, $mm, $dd) = split /\D/, $date;
  874. }
  875. if ($myconfig->{dateformat} =~ /^mm/) {
  876. ($mm, $dd, $yy) = split /\D/, $date;
  877. }
  878. if ($myconfig->{dateformat} =~ /^dd/) {
  879. ($dd, $mm, $yy) = split /\D/, $date;
  880. }
  881. } else {
  882. # ISO
  883. ($yy, $mm, $dd) =~ /(....)(..)(..)/;
  884. }
  885. if ($unit eq 'days') {
  886. $diff = $repeat * 86400;
  887. }
  888. if ($unit eq 'weeks') {
  889. $diff = $repeat * 604800;
  890. }
  891. if ($unit eq 'months') {
  892. $diff = $mm + $repeat;
  893. my $whole = int($diff / 12);
  894. $yy += $whole;
  895. $mm = ($diff % 12) + 1;
  896. $diff = 0;
  897. }
  898. if ($unit eq 'years') {
  899. $yy++;
  900. }
  901. $mm--;
  902. @t = localtime(timelocal(0,0,0,$dd,$mm,$yy) + $diff);
  903. $t[4]++;
  904. $mm = substr("0$t[4]",-2);
  905. $dd = substr("0$t[3]",-2);
  906. $yy = $t[5] + 1900;
  907. if ($date =~ /\D/) {
  908. if ($myconfig->{dateformat} =~ /^yy/) {
  909. $date = "$yy$spc$mm$spc$dd";
  910. }
  911. if ($myconfig->{dateformat} =~ /^mm/) {
  912. $date = "$mm$spc$dd$spc$yy";
  913. }
  914. if ($myconfig->{dateformat} =~ /^dd/) {
  915. $date = "$dd$spc$mm$spc$yy";
  916. }
  917. } else {
  918. $date = "$yy$mm$dd";
  919. }
  920. }
  921. $date;
  922. }
  923. sub print_button {
  924. my ($self, $button, $name) = @_;
  925. 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|;
  926. }
  927. # Database routines used throughout
  928. sub db_init {
  929. my ($self, $myconfig) = @_;
  930. $self->{dbh} = $self->dbconnect_noauto($myconfig) || $self->dberror();
  931. my $query =
  932. "SELECT t.extends,
  933. coalesce (t.table_name, 'custom_' || extends)
  934. || ':' || f.field_name as field_def
  935. FROM custom_table_catalog t
  936. JOIN custom_field_catalog f USING (table_id)";
  937. my $sth = $self->{dbh}->prepare($query);
  938. $sth->execute;
  939. my $ref;
  940. while ($ref = $sth->fetchrow_hashref(NAME_lc)){
  941. push @{$self->{custom_db_fields}{$ref->{extends}}},
  942. $ref->{field_def};
  943. }
  944. }
  945. sub run_custom_queries {
  946. my ($self, $tablename, $query_type, $linenum) = @_;
  947. my $dbh = $self->{dbh};
  948. if ($query_type !~ /^(select|insert|update)$/i){
  949. $self->error($locale->text(
  950. "Passed incorrect query type to get_cutstom_queries."
  951. ));
  952. }
  953. my @rc;
  954. my %temphash;
  955. my @templist;
  956. my @elements;
  957. my $query;
  958. my $ins_values;
  959. if ($linenum){
  960. $linenum = "_$linenum";
  961. }
  962. $query_type = uc($query_type);
  963. for (@{$self->{custom_db_fields}{$tablename}}){
  964. @elements = split (/:/, $_);
  965. push @{$temphash{$elements[0]}}, $elements[1];
  966. }
  967. for (keys %temphash){
  968. my @data;
  969. my $ins_values;
  970. $query = "$query_type ";
  971. if ($query_type eq 'UPDATE'){
  972. $query = "DELETE FROM $_ WHERE row_id = ?";
  973. my $sth = $dbh->prepare($query);
  974. $sth->execute->($self->{"id"."$linenum"})
  975. || $self->dberror($query);
  976. } elsif ($query_type eq 'INSERT'){
  977. $query .= " INTO $_ (";
  978. }
  979. my $first = 1;
  980. for (@{$temphash{$_}}){
  981. $query .= "$_";
  982. if ($query_type eq 'UPDATE'){
  983. $query .= '= ?';
  984. }
  985. $ins_values .= "?, ";
  986. $query .= ", ";
  987. $first = 0;
  988. if ($query_type eq 'UPDATE' or $query_type eq 'INSERT'){
  989. push @data, $self->{"$_$linenum"};
  990. }
  991. }
  992. if ($query_type ne 'INSERT'){
  993. $query =~ s/, $//;
  994. }
  995. if ($query_type eq 'SELECT'){
  996. $query .= " FROM $_";
  997. }
  998. if ($query_type eq 'SELECT' or $query_type eq 'UPDATE'){
  999. $query .= " WHERE row_id = ?";
  1000. }
  1001. if ($query_type eq 'INSERT'){
  1002. $query .= " row_id) VALUES ($ins_values ?)";
  1003. }
  1004. if ($query_type eq 'SELECT'){
  1005. push @rc, [ $query ];
  1006. } else {
  1007. unshift (@data, $query);
  1008. push @rc, [ @data ];
  1009. }
  1010. }
  1011. if ($query_type eq 'INSERT'){
  1012. for (@rc){
  1013. $query = shift (@{$_});
  1014. $sth = $dbh->prepare($query)
  1015. || $self->db_error($query);
  1016. $sth->execute(@{$_}, $self->{id})
  1017. || $self->dberror($query);;
  1018. $sth->finish;
  1019. $did_insert = 1;
  1020. }
  1021. } elsif ($query_type eq 'UPDATE'){
  1022. @rc = $self->run_custom_queries(
  1023. $tablename, 'INSERT', $linenum);
  1024. } elsif ($query_type eq 'SELECT'){
  1025. for (@rc){
  1026. $query = shift @{$_};
  1027. $sth = $self->{dbh}->prepare($query);
  1028. $sth->execute($self->{id});
  1029. $ref = $sth->fetchrow_hashref(NAME_lc);
  1030. for (keys %{$ref}){
  1031. $self->{$_} = $ref->{$_};
  1032. }
  1033. }
  1034. }
  1035. @rc;
  1036. }
  1037. sub dbconnect {
  1038. my ($self, $myconfig) = @_;
  1039. # connect to database
  1040. my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}) or $self->dberror;
  1041. # set db options
  1042. if ($myconfig->{dboptions}) {
  1043. $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
  1044. }
  1045. $dbh;
  1046. }
  1047. sub dbconnect_noauto {
  1048. my ($self, $myconfig) = @_;
  1049. # connect to database
  1050. $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, {AutoCommit => 0}) or $self->dberror;
  1051. # set db options
  1052. if ($myconfig->{dboptions}) {
  1053. $dbh->do($myconfig->{dboptions});
  1054. }
  1055. $dbh;
  1056. }
  1057. sub dbquote {
  1058. my ($self, $var) = @_;
  1059. if ($var eq ''){
  1060. $_ = "NULL";
  1061. } else {
  1062. $_ = $self->{dbh}->quote($var);
  1063. }
  1064. $_;
  1065. }
  1066. sub update_balance {
  1067. # This is a dangerous private function. All apps calling it must
  1068. # be careful to avoid SQL injection issues
  1069. my ($self, $dbh, $table, $field, $where, $value) = @_;
  1070. # if we have a value, go do it
  1071. if ($value) {
  1072. # retrieve balance from table
  1073. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  1074. my ($balance) = $dbh->selectrow_array($query);
  1075. $balance += $value;
  1076. # update balance
  1077. $query = "UPDATE $table SET $field = $balance WHERE $where";
  1078. $dbh->do($query) || $self->dberror($query);
  1079. }
  1080. }
  1081. sub update_exchangerate {
  1082. my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
  1083. # some sanity check for currency
  1084. return if ($curr eq "");
  1085. my $query = qq|
  1086. SELECT curr
  1087. FROM exchangerate
  1088. WHERE curr = ?
  1089. AND transdate = ?
  1090. FOR UPDATE|;
  1091. my $sth = $self->{dbh}->prepare($query);
  1092. $sth->execute($curr, $transdate) || $self->dberror($query);
  1093. my $set;
  1094. my @queryargs;
  1095. if ($buy && $sell) {
  1096. $set = "buy = ?, sell = ?";
  1097. @queryargs = ($buy, $sell);
  1098. } elsif ($buy) {
  1099. $set = "buy = ?";
  1100. @queryargs = ($buy);
  1101. } elsif ($sell) {
  1102. $set = "sell = ?";
  1103. @queryargs = ($sell);
  1104. }
  1105. if ($sth->fetchrow_array) {
  1106. $query = qq|UPDATE exchangerate
  1107. SET $set
  1108. WHERE curr = ?
  1109. AND transdate = ?|;
  1110. push (@queryargs, $curr, $transdate);
  1111. } else {
  1112. $query = qq|
  1113. INSERT INTO exchangerate (
  1114. curr, buy, sell, transdate)
  1115. VALUES (?, ?, ?, ?)|;
  1116. @queryargs = ($curr, $buy, $sell, $transdate);
  1117. }
  1118. $sth->finish;
  1119. $sth = $self->{dbh}->prepare($query);
  1120. $sth->execute(@queryargs) || $self->dberror($query);
  1121. }
  1122. sub save_exchangerate {
  1123. my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
  1124. my ($buy, $sell) = (0, 0);
  1125. $buy = $rate if $fld eq 'buy';
  1126. $sell = $rate if $fld eq 'sell';
  1127. $self->update_exchangerate(
  1128. $self->{dbh},
  1129. $currency,
  1130. $transdate,
  1131. $buy,
  1132. $sell);
  1133. $dbh->commit;
  1134. }
  1135. sub get_exchangerate {
  1136. my ($self, $dbh, $curr, $transdate, $fld) = @_;
  1137. my $exchangerate = 1;
  1138. if ($transdate) {
  1139. my $query = qq|
  1140. SELECT $fld FROM exchangerate
  1141. WHERE curr = ? AND transdate = ?|;
  1142. $sth = $self->{dbh}->prepare($query);
  1143. $sth->execute($curr, $transdate);
  1144. ($exchangerate) = $sth->fetchrow_array;
  1145. }
  1146. $exchangerate;
  1147. $sth->finish;
  1148. $self->{dbh}->commit;
  1149. }
  1150. sub check_exchangerate {
  1151. my ($self, $myconfig, $currency, $transdate, $fld) = @_;
  1152. return "" unless $transdate;
  1153. my $query = qq|
  1154. SELECT $fld
  1155. FROM exchangerate
  1156. WHERE curr = ? AND transdate = ?|;
  1157. my $sth = $self->{dbh}->prepare($query);
  1158. $sth->execute($currenct, $transdate);
  1159. my ($exchangerate) = $sth->fetchrow_array;
  1160. $sth->finish;
  1161. $self->{dbh}->commit;
  1162. $exchangerate;
  1163. }
  1164. sub add_shipto {
  1165. my ($self, $dbh, $id) = @_;
  1166. my $shipto;
  1167. foreach my $item (qw(name address1 address2 city state
  1168. zipcode country contact phone fax email)) {
  1169. if ($self->{"shipto$item"} ne "") {
  1170. $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
  1171. }
  1172. }
  1173. if ($shipto) {
  1174. my $query = qq|
  1175. INSERT INTO shipto
  1176. (trans_id, shiptoname, shiptoaddress1,
  1177. shiptoaddress2, shiptocity, shiptostate,
  1178. shiptozipcode, shiptocountry, shiptocontact,
  1179. shiptophone, shiptofax, shiptoemail)
  1180. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1181. |;
  1182. $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  1183. $sth->execute(
  1184. $id, $self->{shiptoname}, $self->{shiptoaddress1},
  1185. $self->{shiptoaddress2}, $self->{shiptocity},
  1186. $self->{shiptostate}, $self->{shiptostate},
  1187. $self->{shiptozipcode}, $self->{shiptocountry},
  1188. $self->{shiptocontact}, $self->{shiptophone},
  1189. $self->{shiptofax}, $self->{shiptoemail}
  1190. ) || $self->dberror($query);
  1191. $sth->finish;
  1192. $self->{dbh}->commit;
  1193. }
  1194. }
  1195. sub get_employee {
  1196. my ($self, $dbh) = @_;
  1197. my $login = $self->{login};
  1198. $login =~ s/@.*//;
  1199. my $query = qq|SELECT name, id
  1200. FROM employee
  1201. WHERE login = ?|;
  1202. $sth = $self->{dbh}->prepare($query);
  1203. $sth->execute($login);
  1204. my (@a) = $sth->fetchrow_array();
  1205. $a[1] *= 1;
  1206. $sth->finish;
  1207. $self->{dbh}->commit;
  1208. @a;
  1209. }
  1210. # this sub gets the id and name from $table
  1211. sub get_name {
  1212. my ($self, $myconfig, $table, $transdate) = @_;
  1213. # connect to database
  1214. my @queryargs;
  1215. my $where;
  1216. if ($transdate) {
  1217. $where = qq|
  1218. AND (startdate IS NULL OR startdate <= ?)
  1219. AND (enddate IS NULL OR enddate >= ?)|;
  1220. @queryargs = ($transdate, $transdate);
  1221. }
  1222. my $name = $self->like(lc $self->{$table});
  1223. my $query = qq|
  1224. SELECT * FROM $table
  1225. WHERE (lower(name) LIKE ? OR ${table}number LIKE ?)
  1226. $where
  1227. ORDER BY name|;
  1228. unshift(@queryargs, $name, $name);
  1229. my $sth = $self->{dbh}->prepare($query);
  1230. $sth->execute(@queryargs) || $self->dberror($query);
  1231. my $i = 0;
  1232. @{ $self->{name_list} } = ();
  1233. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1234. push(@{ $self->{name_list} }, $ref);
  1235. $i++;
  1236. }
  1237. $sth->finish;
  1238. $self->{dbh}->commit;
  1239. $i;
  1240. }
  1241. sub all_vc {
  1242. my ($self, $myconfig, $vc, $module, $dbh, $transdate, $job) = @_;
  1243. my $ref;
  1244. my $disconnect = 0;
  1245. $dbh = $self->{dbh};
  1246. my $sth;
  1247. my $query = qq|SELECT count(*) FROM $vc|;
  1248. my $where;
  1249. my @ueryargs = ();
  1250. if ($transdate) {
  1251. $query .= qq| WHERE (startdate IS NULL OR startdate <= ?)
  1252. AND (enddate IS NULL OR enddate >= ?)|;
  1253. @queryargs = ($transdate, $transdate);
  1254. }
  1255. $sth = $dbh->prepare($query);
  1256. $sth->execute(@queryargs);
  1257. my ($count) = $sth->fetchrow_array;
  1258. $sth->finish;
  1259. @queryargs = ();
  1260. # build selection list
  1261. if ($count < $myconfig->{vclimit}) {
  1262. $self->{"${vc}_id"} *= 1;
  1263. $query = qq|SELECT id, name
  1264. FROM $vc
  1265. WHERE 1=1
  1266. $where
  1267. UNION
  1268. SELECT id,name
  1269. FROM $vc
  1270. WHERE id = ?
  1271. ORDER BY name|;
  1272. push(@queryargs, $self->{"${vc}_id"});
  1273. $sth = $dbh->prepare($query);
  1274. $sth->execute(@queryargs) || $self->dberror($query);
  1275. @{ $self->{"all_$vc"} } = ();
  1276. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1277. push @{ $self->{"all_$vc"} }, $ref;
  1278. }
  1279. $sth->finish;
  1280. }
  1281. # get self
  1282. if (! $self->{employee_id}) {
  1283. ($self->{employee}, $self->{employee_id}) = split /--/, $self->{employee};
  1284. ($self->{employee}, $self->{employee_id}) = $self->get_employee($dbh) unless $self->{employee_id};
  1285. }
  1286. $self->all_employees($myconfig, $dbh, $transdate, 1);
  1287. $self->all_departments($myconfig, $dbh, $vc);
  1288. $self->all_projects($myconfig, $dbh, $transdate, $job);
  1289. # get language codes
  1290. $query = qq|SELECT *
  1291. FROM language
  1292. ORDER BY 2|;
  1293. $sth = $dbh->prepare($query);
  1294. $sth->execute || $self->dberror($query);
  1295. $self->{all_language} = ();
  1296. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1297. push @{ $self->{all_language} }, $ref;
  1298. }
  1299. $sth->finish;
  1300. $self->all_taxaccounts($myconfig, $dbh, $transdate);
  1301. $self->{dbh}->commit;
  1302. }
  1303. sub all_taxaccounts {
  1304. my ($self, $myconfig, $dbh2, $transdate) = @_;
  1305. my $disconnect = ($dbh) ? 0 : 1;
  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. (undef, $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. + ? 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. if ($disconnect) {
  1948. $dbh->commit;
  1949. $dbh->disconnect;
  1950. }
  1951. }
  1952. sub save_intnotes {
  1953. my ($self, $myconfig, $vc) = @_;
  1954. # no id return
  1955. return unless $self->{id};
  1956. my $dbh = $self->dbconnect($myconfig);
  1957. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  1958. $sth=$dbh->prepare($query);
  1959. $sth->execute($self->{intnotes}, $self->{id}) || $self->dberror($query);
  1960. $dbh->commit;
  1961. }
  1962. sub update_defaults {
  1963. my ($self, $myconfig, $fld) = @_;
  1964. if (!$self->{dbh} && $self){
  1965. $self->db_init($myconfig);
  1966. }
  1967. my $dbh = $self->{dbh};
  1968. if (!$self){
  1969. $dbh = $_[3];
  1970. }
  1971. my $query = qq|
  1972. SELECT value FROM defaults
  1973. WHERE setting_key = ? FOR UPDATE|;
  1974. $sth = $dbh->prepare($query);
  1975. $sth->execute($fld);
  1976. ($_) = $sth->fetchrow_array();
  1977. $_ = "0" unless $_;
  1978. # check for and replace
  1979. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  1980. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  1981. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  1982. # <?lsmb PHONE ?> for customer and vendors
  1983. my $num = $_;
  1984. ($num) = $num =~ /(\d+)/;
  1985. if (defined $num) {
  1986. my $incnum;
  1987. # if we have leading zeros check how long it is
  1988. if ($num =~ /^0/) {
  1989. my $l = length $num;
  1990. $incnum = $num + 1;
  1991. $l -= length $incnum;
  1992. # pad it out with zeros
  1993. my $padzero = "0" x $l;
  1994. $incnum = ("0" x $l) . $incnum;
  1995. } else {
  1996. $incnum = $num + 1;
  1997. }
  1998. s/$num/$incnum/;
  1999. }
  2000. my $dbvar = $_;
  2001. my $var = $_;
  2002. my $str;
  2003. my $param;
  2004. if (/<\?lsmb /) {
  2005. while (/<\?lsmb /) {
  2006. s/<\?lsmb .*? \?>//;
  2007. last unless $&;
  2008. $param = $&;
  2009. $str = "";
  2010. if ($param =~ /<\?lsmb date \?>/i) {
  2011. $str = ($self->split_date($myconfig->{dateformat}, $self->{transdate}))[0];
  2012. $var =~ s/$param/$str/;
  2013. }
  2014. if ($param =~ /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i) {
  2015. my $fld = lc $&;
  2016. $fld =~ s/<\?lsmb //;
  2017. if ($fld =~ /name/) {
  2018. if ($self->{type}) {
  2019. $fld = $self->{vc};
  2020. }
  2021. }
  2022. my $p = $param;
  2023. $p =~ s/(<|>|%)//g;
  2024. my @p = split / /, $p;
  2025. my @n = split / /, uc $self->{$fld};
  2026. if ($#p > 0) {
  2027. for (my $i = 1; $i <= $#p; $i++) {
  2028. $str .= substr($n[$i-1], 0, $p[$i]);
  2029. }
  2030. } else {
  2031. ($str) = split /--/, $self->{$fld};
  2032. }
  2033. $var =~ s/$param/$str/;
  2034. $var =~ s/\W//g if $fld eq 'phone';
  2035. }
  2036. if ($param =~ /<\?lsmb (yy|mm|dd)/i) {
  2037. my $p = $param;
  2038. $p =~ s/(<|>|%)//g;
  2039. my $spc = $p;
  2040. $spc =~ s/\w//g;
  2041. $spc = substr($spc, 0, 1);
  2042. my %d = ( yy => 1, mm => 2, dd => 3 );
  2043. my @p = ();
  2044. my @a = $self->split_date($myconfig->{dateformat}, $self->{transdate});
  2045. for (sort keys %d) { push @p, $a[$d{$_}] if ($p =~ /$_/) }
  2046. $str = join $spc, @p;
  2047. $var =~ s/$param/$str/;
  2048. }
  2049. if ($param =~ /<\?lsmb curr/i) {
  2050. $var =~ s/$param/$self->{currency}/;
  2051. }
  2052. }
  2053. }
  2054. $query = qq|
  2055. UPDATE defaults
  2056. SET value = ?
  2057. WHERE setting_key = ?|;
  2058. $sth = $dbh->prepare($query);
  2059. $sth->execute($dbvar, $fld) || $self->dberror($query);
  2060. $dbh->commit;
  2061. $var;
  2062. }
  2063. sub db_prepare_vars {
  2064. for (@_){
  2065. if (!$self->{$_} and $self->{$_} ne "0"){
  2066. undef $self->{$_};
  2067. }
  2068. }
  2069. }
  2070. sub split_date {
  2071. my ($self, $dateformat, $date) = @_;
  2072. my @d = localtime;
  2073. my $mm;
  2074. my $dd;
  2075. my $yy;
  2076. my $rv;
  2077. if (! $date) {
  2078. $dd = $d[3];
  2079. $mm = ++$d[4];
  2080. $yy = substr($d[5],-2);
  2081. $mm = substr("0$mm", -2);
  2082. $dd = substr("0$dd", -2);
  2083. }
  2084. if ($dateformat =~ /^yy/) {
  2085. if ($date) {
  2086. if ($date =~ /\D/) {
  2087. ($yy, $mm, $dd) = split /\D/, $date;
  2088. $mm *= 1;
  2089. $dd *= 1;
  2090. $mm = substr("0$mm", -2);
  2091. $dd = substr("0$dd", -2);
  2092. $yy = substr($yy, -2);
  2093. $rv = "$yy$mm$dd";
  2094. } else {
  2095. $rv = $date;
  2096. }
  2097. } else {
  2098. $rv = "$yy$mm$dd";
  2099. }
  2100. }
  2101. if ($dateformat =~ /^mm/) {
  2102. if ($date) {
  2103. if ($date =~ /\D/) {
  2104. ($mm, $dd, $yy) = split /\D/, $date;
  2105. $mm *= 1;
  2106. $dd *= 1;
  2107. $mm = substr("0$mm", -2);
  2108. $dd = substr("0$dd", -2);
  2109. $yy = substr($yy, -2);
  2110. $rv = "$mm$dd$yy";
  2111. } else {
  2112. $rv = $date;
  2113. }
  2114. } else {
  2115. $rv = "$mm$dd$yy";
  2116. }
  2117. }
  2118. if ($dateformat =~ /^dd/) {
  2119. if ($date) {
  2120. if ($date =~ /\D/) {
  2121. ($dd, $mm, $yy) = split /\D/, $date;
  2122. $mm *= 1;
  2123. $dd *= 1;
  2124. $mm = substr("0$mm", -2);
  2125. $dd = substr("0$dd", -2);
  2126. $yy = substr($yy, -2);
  2127. $rv = "$dd$mm$yy";
  2128. } else {
  2129. $rv = $date;
  2130. }
  2131. } else {
  2132. $rv = "$dd$mm$yy";
  2133. }
  2134. }
  2135. ($rv, $yy, $mm, $dd);
  2136. }
  2137. sub from_to {
  2138. my ($self, $yy, $mm, $interval) = @_;
  2139. use Time::Local;
  2140. my @t;
  2141. my $dd = 1;
  2142. my $fromdate = "$yy${mm}01";
  2143. my $bd = 1;
  2144. if (defined $interval) {
  2145. if ($interval == 12) {
  2146. $yy++;
  2147. } else {
  2148. if (($mm += $interval) > 12) {
  2149. $mm -= 12;
  2150. $yy++;
  2151. }
  2152. if ($interval == 0) {
  2153. @t = localtime(time);
  2154. $dd = $t[3];
  2155. $mm = $t[4] + 1;
  2156. $yy = $t[5] + 1900;
  2157. $bd = 0;
  2158. }
  2159. }
  2160. } else {
  2161. if (++$mm > 12) {
  2162. $mm -= 12;
  2163. $yy++;
  2164. }
  2165. }
  2166. $mm--;
  2167. @t = localtime(timelocal(0,0,0,$dd,$mm,$yy) - $bd);
  2168. $t[4]++;
  2169. $t[4] = substr("0$t[4]",-2);
  2170. $t[3] = substr("0$t[3]",-2);
  2171. $t[5] += 1900;
  2172. ($fromdate, "$t[5]$t[4]$t[3]");
  2173. }
  2174. sub audittrail {
  2175. my ($self, $dbh, $myconfig, $audittrail) = @_;
  2176. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2177. my $query;
  2178. my $rv;
  2179. my $disconnect;
  2180. if (! $dbh) {
  2181. $dbh = $self->dbconnect($myconfig);
  2182. $disconnect = 1;
  2183. }
  2184. # if we have an id add audittrail, otherwise get a new timestamp
  2185. my @queryargs;
  2186. if ($audittrail->{id}) {
  2187. $query = qq|
  2188. SELECT value FROM defaults
  2189. WHERE setting_key = 'audittrail'|;
  2190. if ($dbh->selectrow_array($query)) {
  2191. my ($null, $employee_id) = $self->get_employee($dbh);
  2192. if ($self->{audittrail} && !$myconfig) {
  2193. chop $self->{audittrail};
  2194. my @a = split /\|/, $self->{audittrail};
  2195. my %newtrail = ();
  2196. my $key;
  2197. my $i;
  2198. my @flds = qw(tablename reference formname action transdate);
  2199. # put into hash and remove dups
  2200. while (@a) {
  2201. $key = "$a[2]$a[3]";
  2202. $i = 0;
  2203. $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
  2204. splice @a, 0, 5;
  2205. }
  2206. $query = qq|
  2207. INSERT INTO audittrail
  2208. (trans_id, tablename, reference,
  2209. formname, action, transdate,
  2210. employee_id)
  2211. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2212. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2213. foreach $key (sort { $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate} } keys %newtrail) {
  2214. $i = 2;
  2215. $sth->bind_param(1, $audittrail->{id});
  2216. for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
  2217. $sth->bind_param($i++, $employee_id);
  2218. $sth->execute || $self->dberror;
  2219. $sth->finish;
  2220. }
  2221. }
  2222. if ($audittrail->{transdate}) {
  2223. $query = qq|
  2224. INSERT INTO audittrail (
  2225. trans_id, tablename, reference,
  2226. formname, action, employee_id,
  2227. transdate)
  2228. VALUES (?, ?, ?, ?, ?, ?)|;
  2229. @queryargs = (
  2230. $audittrail->{id},
  2231. $audittrail->{tablename},
  2232. $audittrail->{reference},
  2233. $audittrail->{formname},
  2234. $audittrail->{action}.
  2235. $employee_id,
  2236. $audittrail->{transdate}
  2237. );
  2238. } else {
  2239. $query = qq|
  2240. INSERT INTO audittrail
  2241. (trans_id, tablename, reference,
  2242. formname, action, employee_id)
  2243. VALUES (?, ?, ?, ?, ?)|;
  2244. @queryargs = (
  2245. $audittrail->{id},
  2246. $audittrail->{tablename},
  2247. $audittrail->{reference},
  2248. $audittrail->{formname},
  2249. $audittrail->{action}.
  2250. $employee_id,
  2251. );
  2252. }
  2253. $sth = $dbh->prepare($query);
  2254. $sth->execute(@queryargs)||$self->dberror($query);
  2255. }
  2256. } else {
  2257. $query = qq|SELECT current_timestamp|;
  2258. my ($timestamp) = $dbh->selectrow_array($query);
  2259. $rv = "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2260. }
  2261. $dbh->commit;
  2262. $rv;
  2263. }
  2264. 1;