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