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