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