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