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