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