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