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