summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: bc693ea9879a91410de527e288f5a064f198158c (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. use Cwd;
  41. package Form;
  42. sub new {
  43. my $type = shift;
  44. my $argstr = shift;
  45. read(STDIN, $_, $ENV{CONTENT_LENGTH});
  46. if ($argstr){
  47. $_ = $argstr;
  48. }
  49. elsif ($ENV{QUERY_STRING}) {
  50. $_ = $ENV{QUERY_STRING};
  51. }
  52. elsif ($ARGV[0]) {
  53. $_ = $ARGV[0];
  54. }
  55. my $self = {};
  56. %$self = split /[&=]/;
  57. for (keys %$self) { $self->{$_} = unescape("", $self->{$_}) }
  58. if (substr($self->{action}, 0, 1) !~ /( |\.)/) {
  59. $self->{action} = lc $self->{action};
  60. $self->{action} =~ s/( |-|,|\#|\/|\.$)/_/g;
  61. $self->{nextsub} = lc $self->{nextsub};
  62. $self->{nextsub} =~ s/( |-|,|\#|\/|\.$)/_/g;
  63. }
  64. $self->{login} =~ s/[^a-zA-Z0-9._+@'-]//g;
  65. $self->{menubar} = 1 if $self->{path} =~ /lynx/i;
  66. #menubar will be deprecated, replaced with below
  67. $self->{lynx} = 1 if $self->{path} =~ /lynx/i;
  68. $self->{version} = "1.2.0 Release Candidate 4";
  69. $self->{dbversion} = "1.2.0";
  70. bless $self, $type;
  71. if ($self->{path} ne 'bin/lynx'){ $self->{path} = 'bin/mozilla';}
  72. if (($self->{script}) and not List::Util::first {$_ eq $self->{script}}
  73. @{LedgerSMB::Sysconfig::scripts}){
  74. $self->error('Access Denied', __line__, __file__);
  75. }
  76. if (($self->{action} =~ /:/) || ($self->{nextsub} =~ /:/)){
  77. $self->error("Access Denied", __line__, __file__);
  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. if ($self->{callback} || !$msg){
  231. main::redirect();
  232. } else {
  233. $self->info($msg);
  234. }
  235. }
  236. sub sort_columns {
  237. my ($self, @columns) = @_;
  238. if ($self->{sort}) {
  239. if (@columns) {
  240. @columns = grep !/^$self->{sort}$/, @columns;
  241. splice @columns, 0, 0, $self->{sort};
  242. }
  243. }
  244. @columns;
  245. }
  246. sub sort_order {
  247. my ($self, $columns, $ordinal) = @_;
  248. # setup direction
  249. if ($self->{direction}) {
  250. if ($self->{sort} eq $self->{oldsort}) {
  251. if ($self->{direction} eq 'ASC') {
  252. $self->{direction} = "DESC";
  253. } else {
  254. $self->{direction} = "ASC";
  255. }
  256. }
  257. } else {
  258. $self->{direction} = "ASC";
  259. }
  260. $self->{oldsort} = $self->{sort};
  261. my @a = $self->sort_columns(@{$columns});
  262. if (%$ordinal) {
  263. $a[0] = ($ordinal->{$a[$_]}) ? "$ordinal->{$a[0]} $self->{direction}" : "$a[0] $self->{direction}";
  264. for (1 .. $#a) {
  265. $a[$_] = $ordinal->{$a[$_]} if $ordinal->{$a[$_]}
  266. }
  267. } else {
  268. $a[0] .= " $self->{direction}";
  269. }
  270. $sortorder = join ',', @a;
  271. $sortorder;
  272. }
  273. sub format_amount {
  274. my ($self, $myconfig, $amount, $places, $dash) = @_;
  275. my $negative ;
  276. if ($amount){
  277. $amount = $self->parse_amount($myconfig, $amount);
  278. $negative = ($amount < 0);
  279. $amount =~ s/-//;
  280. }
  281. if ($places =~ /\d+/) {
  282. #$places = 4 if $places == 2;
  283. $amount = $self->round_amount($amount, $places);
  284. }
  285. # is the amount negative
  286. # Parse $myconfig->{numberformat}
  287. my ($ts, $ds) = ($1, $2);
  288. if ($amount) {
  289. if ($myconfig->{numberformat}) {
  290. my ($whole, $dec) = split /\./, "$amount";
  291. $amount = join '', reverse split //, $whole;
  292. if ($places) {
  293. $dec .= "0" x $places;
  294. $dec = substr($dec, 0, $places);
  295. }
  296. if ($myconfig->{numberformat} eq '1,000.00') {
  297. $amount =~ s/\d{3,}?/$&,/g;
  298. $amount =~ s/,$//;
  299. $amount = join '', reverse split //, $amount;
  300. $amount .= "\.$dec" if ($dec ne "");
  301. }
  302. if ($myconfig->{numberformat} eq '1 000.00') {
  303. $amount =~ s/\d{3,}?/$& /g;
  304. $amount =~ s/\s$//;
  305. $amount = join '', reverse split //, $amount;
  306. $amount .= "\.$dec" if ($dec ne "");
  307. }
  308. if ($myconfig->{numberformat} eq "1'000.00") {
  309. $amount =~ s/\d{3,}?/$&'/g;
  310. $amount =~ s/'$//;
  311. $amount = join '', reverse split //, $amount;
  312. $amount .= "\.$dec" if ($dec ne "");
  313. }
  314. if ($myconfig->{numberformat} eq '1.000,00') {
  315. $amount =~ s/\d{3,}?/$&./g;
  316. $amount =~ s/\.$//;
  317. $amount = join '', reverse split //, $amount;
  318. $amount .= ",$dec" if ($dec ne "");
  319. }
  320. if ($myconfig->{numberformat} eq '1000,00') {
  321. $amount = "$whole";
  322. $amount .= ",$dec" if ($dec ne "");
  323. }
  324. if ($myconfig->{numberformat} eq '1000.00') {
  325. $amount = "$whole";
  326. $amount .= ".$dec" if ($dec ne "");
  327. }
  328. if ($dash =~ /-/) {
  329. $amount = ($negative) ? "($amount)" : "$amount";
  330. } elsif ($dash =~ /DRCR/) {
  331. $amount = ($negative) ? "$amount DR" : "$amount CR";
  332. } else {
  333. $amount = ($negative) ? "-$amount" : "$amount";
  334. }
  335. }
  336. } else {
  337. if ($dash eq "0" && $places) {
  338. if ($myconfig->{numberformat} eq '1.000,00') {
  339. $amount = "0".","."0" x $places;
  340. } else {
  341. $amount = "0"."."."0" x $places;
  342. }
  343. } else {
  344. $amount = ($dash ne "") ? "$dash" : "";
  345. }
  346. }
  347. $amount;
  348. }
  349. sub parse_amount {
  350. my ($self, $myconfig, $amount) = @_;
  351. if (($amount eq '') or ($amount eq undef)) {
  352. $amount = 0;
  353. }
  354. if (UNIVERSAL::isa($amount, 'Math::BigFloat')){ # Amount may not be an object
  355. return $amount;
  356. }
  357. my $numberformat = $myconfig->{numberformat};
  358. if (($numberformat eq '1.000,00') ||
  359. ($numberformat eq '1000,00')) {
  360. $amount =~ s/\.//g;
  361. $amount =~ s/,/./;
  362. }
  363. if ($numberformat eq '1 000.00'){
  364. $amount =~ s/\s//g;
  365. }
  366. if ($numberformat eq "1'000.00") {
  367. $amount =~ s/'//g;
  368. }
  369. $amount =~ s/,//g;
  370. if ($amount =~ s/\((\d*\.?\d*)\)/$1/){
  371. $amount = $1 * -1;
  372. }
  373. if ($amount =~ s/(\d*\.?\d*)\s?DR/$1/){
  374. $amount = $1 * -1;
  375. }
  376. $amount =~ s/\s?CR//;
  377. $amount = new Math::BigFloat($amount);
  378. return ($amount * 1);
  379. }
  380. sub round_amount {
  381. my ($self, $amount, $places) = @_;
  382. # These rounding rules follow from the previous implementation.
  383. # They should be changed to allow different rules for different accounts.
  384. Math::BigFloat->round_mode('+inf') if $amount >= 0;
  385. Math::BigFloat->round_mode('-inf') if $amount < 0;
  386. $amount = Math::BigFloat->new($amount)->ffround(-$places) if $places >= 0;
  387. $amount = Math::BigFloat->new($amount)->ffround(-($places-1)) if $places < 0;
  388. return $amount;
  389. }
  390. sub callproc {
  391. my $procname = shift @_;
  392. my $argstr = "";
  393. my @results;
  394. for (1 .. $#_){
  395. $argstr .= "?, ";
  396. }
  397. $argstr =~ s/\, $//;
  398. $query = "SELECT $procname";
  399. $query =~ s/\(\)/$argstr/;
  400. my $sth = $self->{dbh}->prepare($query);
  401. while (my $ref = $sth->fetchrow_hashref(NAME_lc)){
  402. push @results, $ref;
  403. }
  404. @results;
  405. }
  406. sub get_my_emp_num {
  407. my ($self, $myconfig, $form) = @_;
  408. %myconfig = %{$myconfig};
  409. my $dbh = $form->{dbh};
  410. # we got a connection, check the version
  411. my $query = qq|
  412. SELECT employeenumber FROM employee
  413. WHERE login = ?|;
  414. my $sth = $dbh->prepare($query);
  415. $sth->execute($form->{login}) || $form->dberror($query);
  416. $sth->execute;
  417. my ($id) = $sth->fetchrow_array;
  418. $sth->finish;
  419. $form->{'emp_num'} = $id;
  420. }
  421. sub parse_template {
  422. my ($self, $myconfig) = @_;
  423. $self->{cwd} = Cwd::getcwd();
  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. chmod(0600, "$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. chmod (0600, "$self->{OUT}");
  707. } else {
  708. # launch application
  709. print qq|Content-Type: application/$self->{format}\n|.
  710. qq|Content-Disposition: attachment; filename="$self->{tmpfile}"\n\n|;
  711. unless (open(OUT, ">-")) {
  712. $err = $!;
  713. $self->cleanup;
  714. $self->error("STDOUT : $err");
  715. }
  716. }
  717. binmode(OUT);
  718. while (<IN>) {
  719. print OUT $_;
  720. }
  721. close(OUT);
  722. seek IN, 0, 0;
  723. }
  724. close(IN);
  725. }
  726. $self->cleanup;
  727. }
  728. }
  729. sub format_line {
  730. my $self = shift;
  731. $_ = shift;
  732. my $i = shift;
  733. my $str;
  734. my $newstr;
  735. my $pos;
  736. my $l;
  737. my $lf;
  738. my $line;
  739. my $var = "";
  740. my %a;
  741. my $offset;
  742. my $pad;
  743. my $item;
  744. while (/<\?lsmb (.+?) \?>/) {
  745. %a = ();
  746. foreach $item (split / /, $1) {
  747. my ($key, $value) = split /=/, $item;
  748. if ($value ne "") {
  749. $a{$key} = $value;
  750. } else {
  751. $var = $item;
  752. }
  753. }
  754. $str = (defined $i) ? $self->{$var}[$i] : $self->{$var};
  755. $newstr = $str;
  756. $self->{countitemnotes} = 1 if $var eq 'itemnotes';
  757. $var = $1;
  758. if ($var =~ /^if\s+not\s+/) {
  759. if ($str) {
  760. $var =~ s/if\s+not\s+//;
  761. s/<\?lsmb if\s+not\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  762. } else {
  763. s/<\?lsmb $var \?>//;
  764. }
  765. next;
  766. }
  767. if ($var =~ /^if\s+/) {
  768. if ($str) {
  769. s/<\?lsmb $var \?>//;
  770. } else {
  771. $var =~ s/if\s+//;
  772. s/<\?lsmb if\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  773. }
  774. next;
  775. }
  776. if ($var =~ /^end\s+/) {
  777. s/<\?lsmb $var \?>//;
  778. next;
  779. }
  780. if ($a{align} || $a{width} || $a{offset}) {
  781. $newstr = "";
  782. $offset = 0;
  783. $lf = "";
  784. foreach $str (split /\n/, $str) {
  785. $line = $str;
  786. $l = length $str;
  787. do {
  788. if (($pos = length $str) > $a{width}) {
  789. if (($pos = rindex $str, " ", $a{width}) > 0) {
  790. $line = substr($str, 0, $pos);
  791. }
  792. $pos = length $str if $pos == -1;
  793. }
  794. $l = length $line;
  795. # pad left, right or center
  796. $l = ($a{width} - $l);
  797. $pad = " " x $l;
  798. if ($a{align} =~ /right/i) {
  799. $line = " " x $offset . $pad . $line;
  800. }
  801. if ($a{align} =~ /left/i) {
  802. $line = " " x $offset . $line . $pad;
  803. }
  804. if ($a{align} =~ /center/i) {
  805. $pad = " " x ($l/2);
  806. $line = " " x $offset . $pad . $line;
  807. $pad = " " x ($l/2);
  808. $line .= $pad;
  809. }
  810. $newstr .= "$lf$line";
  811. $str = substr($str, $pos + 1);
  812. $line = $str;
  813. $lf = "\n";
  814. $offset = $a{offset};
  815. } while ($str);
  816. }
  817. }
  818. s/<\?lsmb (.+?) \?>/$newstr/;
  819. }
  820. $_;
  821. }
  822. sub cleanup {
  823. my $self = shift;
  824. chdir("$self->{tmpdir}");
  825. my @err = ();
  826. if (-f "$self->{errfile}") {
  827. open(FH, '<', "$self->{errfile}");
  828. @err = <FH>;
  829. close(FH);
  830. }
  831. if ($self->{tmpfile}) {
  832. # strip extension
  833. $self->{tmpfile} =~ s/\.\w+$//g;
  834. my $tmpfile = $self->{tmpfile};
  835. unlink(<$tmpfile.*>);
  836. }
  837. chdir("$self->{cwd}");
  838. "@err";
  839. }
  840. sub rerun_latex {
  841. my $self = shift;
  842. my $a = 0;
  843. if (-f "$self->{errfile}") {
  844. open(FH, '<', "$self->{errfile}");
  845. $a = grep /(longtable Warning:|Warning:.*?LastPage)/, <FH>;
  846. close(FH);
  847. }
  848. $a;
  849. }
  850. sub format_string {
  851. my ($self, @fields) = @_;
  852. my $format = $self->{format};
  853. if ($self->{format} =~ /(postscript|pdf)/) {
  854. $format = 'tex';
  855. }
  856. my %replace = (
  857. 'order' => {
  858. html => [ '<', '>', '\n', '\r' ],
  859. txt => [ '\n', '\r' ],
  860. tex => [ quotemeta('\\'), '&', '\n','\r',
  861. '\$', '%', '_', '#',
  862. quotemeta('^'), '{', '}', '<', '>', '£'
  863. ] },
  864. html => { '<' => '&lt;', '>' => '&gt;','\n' => '<br />',
  865. '\r' => '<br />' },
  866. txt => { '\n' => "\n", '\r' => "\r" },
  867. tex => {'&' => '\&', '$' => '\$', '%' => '\%', '_' => '\_',
  868. '#' => '\#', quotemeta('^') => '\^\\', '{' => '\{',
  869. '}' => '\}', '<' => '$<$', '>' => '$>$',
  870. '\n' => '\newline ', '\r' => '\newline ',
  871. '£' => '\pounds ', quotemeta('\\') => '/'}
  872. );
  873. my $key;
  874. foreach $key (@{ $replace{order}{$format} }) {
  875. for (@fields) { $self->{$_} =~ s/$key/$replace{$format}{$key}/g }
  876. }
  877. }
  878. sub datetonum {
  879. my ($self, $myconfig, $date, $picture) = @_;
  880. if ($date && $date =~ /\D/) {
  881. if ($myconfig->{dateformat} =~ /^yy/) {
  882. ($yy, $mm, $dd) = split /\D/, $date;
  883. }
  884. if ($myconfig->{dateformat} =~ /^mm/) {
  885. ($mm, $dd, $yy) = split /\D/, $date;
  886. }
  887. if ($myconfig->{dateformat} =~ /^dd/) {
  888. ($dd, $mm, $yy) = split /\D/, $date;
  889. }
  890. $dd *= 1;
  891. $mm *= 1;
  892. $yy += 2000 if length $yy == 2;
  893. $dd = substr("0$dd", -2);
  894. $mm = substr("0$mm", -2);
  895. $date = "$yy$mm$dd";
  896. }
  897. $date;
  898. }
  899. sub add_date {
  900. my ($self, $myconfig, $date, $repeat, $unit) = @_;
  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->{dbh};
  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. my @t;
  2164. my $dd = 1;
  2165. my $fromdate = "$yy${mm}01";
  2166. my $bd = 1;
  2167. if (defined $interval) {
  2168. if ($interval == 12) {
  2169. $yy++;
  2170. } else {
  2171. if (($mm += $interval) > 12) {
  2172. $mm -= 12;
  2173. $yy++;
  2174. }
  2175. if ($interval == 0) {
  2176. @t = localtime(time);
  2177. $dd = $t[3];
  2178. $mm = $t[4] + 1;
  2179. $yy = $t[5] + 1900;
  2180. $bd = 0;
  2181. }
  2182. }
  2183. } else {
  2184. if (++$mm > 12) {
  2185. $mm -= 12;
  2186. $yy++;
  2187. }
  2188. }
  2189. $mm--;
  2190. @t = localtime(timelocal(0,0,0,$dd,$mm,$yy) - $bd);
  2191. $t[4]++;
  2192. $t[4] = substr("0$t[4]",-2);
  2193. $t[3] = substr("0$t[3]",-2);
  2194. $t[5] += 1900;
  2195. ($fromdate, "$t[5]$t[4]$t[3]");
  2196. }
  2197. sub audittrail {
  2198. my ($self, $dbh, $myconfig, $audittrail) = @_;
  2199. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2200. my $query;
  2201. my $rv;
  2202. my $disconnect;
  2203. if (! $dbh) {
  2204. $dbh = $self->{dbh};
  2205. }
  2206. # if we have an id add audittrail, otherwise get a new timestamp
  2207. my @queryargs;
  2208. if ($audittrail->{id}) {
  2209. $query = qq|
  2210. SELECT value FROM defaults
  2211. WHERE setting_key = 'audittrail'|;
  2212. if ($dbh->selectrow_array($query)) {
  2213. my ($null, $employee_id) = $self->get_employee($dbh);
  2214. if ($self->{audittrail} && !$myconfig) {
  2215. chop $self->{audittrail};
  2216. my @a = split /\|/, $self->{audittrail};
  2217. my %newtrail = ();
  2218. my $key;
  2219. my $i;
  2220. my @flds = qw(tablename reference formname action transdate);
  2221. # put into hash and remove dups
  2222. while (@a) {
  2223. $key = "$a[2]$a[3]";
  2224. $i = 0;
  2225. $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
  2226. splice @a, 0, 5;
  2227. }
  2228. $query = qq|
  2229. INSERT INTO audittrail
  2230. (trans_id, tablename, reference,
  2231. formname, action, transdate,
  2232. employee_id)
  2233. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2234. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2235. foreach $key (sort { $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate} } keys %newtrail) {
  2236. $i = 2;
  2237. $sth->bind_param(1, $audittrail->{id});
  2238. for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
  2239. $sth->bind_param($i++, $employee_id);
  2240. $sth->execute || $self->dberror;
  2241. $sth->finish;
  2242. }
  2243. }
  2244. if ($audittrail->{transdate}) {
  2245. $query = qq|
  2246. INSERT INTO audittrail (
  2247. trans_id, tablename, reference,
  2248. formname, action, employee_id,
  2249. transdate)
  2250. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2251. @queryargs = (
  2252. $audittrail->{id},
  2253. $audittrail->{tablename},
  2254. $audittrail->{reference},
  2255. $audittrail->{formname},
  2256. $audittrail->{action},
  2257. $employee_id,
  2258. $audittrail->{transdate}
  2259. );
  2260. } else {
  2261. $query = qq|
  2262. INSERT INTO audittrail
  2263. (trans_id, tablename, reference,
  2264. formname, action, employee_id)
  2265. VALUES (?, ?, ?, ?, ?, ?)|;
  2266. @queryargs = (
  2267. $audittrail->{id},
  2268. $audittrail->{tablename},
  2269. $audittrail->{reference},
  2270. $audittrail->{formname},
  2271. $audittrail->{action},
  2272. $employee_id,
  2273. );
  2274. }
  2275. $sth = $dbh->prepare($query);
  2276. $sth->execute(@queryargs)||$self->dberror($query);
  2277. }
  2278. } else {
  2279. $query = qq|SELECT current_timestamp|;
  2280. my ($timestamp) = $dbh->selectrow_array($query);
  2281. $rv = "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2282. }
  2283. $dbh->commit;
  2284. $rv;
  2285. }
  2286. 1;