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