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