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