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