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