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