summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: ac3121aeeef4207a7d3816dba8861a92a0e40fab (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. use List::Util qw(first);
  38. use LedgerSMB::Mailer;
  39. use Time::Local;
  40. use Cwd;
  41. package Form;
  42. sub new {
  43. my $type = shift;
  44. my $argstr = shift;
  45. read(STDIN, $_, $ENV{CONTENT_LENGTH});
  46. if ($argstr){
  47. $_ = $argstr;
  48. }
  49. elsif ($ENV{QUERY_STRING}) {
  50. $_ = $ENV{QUERY_STRING};
  51. }
  52. elsif ($ARGV[0]) {
  53. $_ = $ARGV[0];
  54. }
  55. my $self = {};
  56. %$self = split /[&=]/;
  57. for (keys %$self) { $self->{$_} = unescape("", $self->{$_}) }
  58. if (substr($self->{action}, 0, 1) !~ /( |\.)/) {
  59. $self->{action} = lc $self->{action};
  60. $self->{action} =~ s/( |-|,|\#|\/|\.$)/_/g;
  61. $self->{nextsub} = lc $self->{nextsub};
  62. $self->{nextsub} =~ s/( |-|,|\#|\/|\.$)/_/g;
  63. }
  64. $self->{login} =~ s/[^a-zA-Z0-9._+@'-]//g;
  65. $self->{menubar} = 1 if $self->{path} =~ /lynx/i;
  66. #menubar will be deprecated, replaced with below
  67. $self->{lynx} = 1 if $self->{path} =~ /lynx/i;
  68. $self->{version} = "1.2.0 Release Candidate 4";
  69. $self->{dbversion} = "1.2.0";
  70. bless $self, $type;
  71. if ($self->{path} ne 'bin/lynx'){ $self->{path} = 'bin/mozilla';}
  72. if (($self->{script}) and not List::Util::first {$_ eq $self->{script}}
  73. @{LedgerSMB::Sysconfig::scripts}){
  74. $self->error('Access Denied', __line__, __file__);
  75. }
  76. if (($self->{action} =~ /:/) || ($self->{nextsub} =~ /:/)){
  77. $self->error("Access Denied", __line__, __file__);
  78. }
  79. for (keys %$self){ $self->{$_} =~ s/\000//g }
  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 encode_all {
  94. # TODO;
  95. }
  96. sub decode_all {
  97. # TODO
  98. }
  99. sub escape {
  100. my ($self, $str, $beenthere) = @_;
  101. # for Apache 2 we escape strings twice
  102. if (($ENV{SERVER_SIGNATURE} =~ /Apache\/2\.(\d+)\.(\d+)/) && !$beenthere) {
  103. $str = $self->escape($str, 1) if $1 == 0 && $2 < 44;
  104. }
  105. $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
  106. $str;
  107. }
  108. sub unescape {
  109. my ($self, $str) = @_;
  110. $str =~ tr/+/ /;
  111. $str =~ s/\\$//;
  112. $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
  113. $str =~ s/\r?\n/\n/g;
  114. $str;
  115. }
  116. sub quote {
  117. my ($self, $str) = @_;
  118. if ($str && ! ref($str)) {
  119. $str =~ s/"/&quot;/g;
  120. }
  121. $str;
  122. }
  123. sub unquote {
  124. my ($self, $str) = @_;
  125. if ($str && ! ref($str)) {
  126. $str =~ s/&quot;/"/g;
  127. }
  128. $str;
  129. }
  130. sub hide_form {
  131. my $self = shift;
  132. if (@_) {
  133. for (@_) {
  134. print qq|<input type="hidden" name="$_" value="|.$self->quote($self->{$_}).qq|" />\n|
  135. }
  136. } else {
  137. delete $self->{header};
  138. for (sort keys %$self) {
  139. print qq|<input type="hidden" name="$_" value="|.$self->quote($self->{$_}).qq|" />\n|
  140. }
  141. }
  142. }
  143. sub error {
  144. my ($self, $msg) = @_;
  145. if ($ENV{GATEWAY_INTERFACE}) {
  146. $self->{msg} = $msg;
  147. $self->{format} = "html";
  148. $self->format_string('msg');
  149. delete $self->{pre};
  150. if (!$self->{header}) {
  151. $self->header;
  152. }
  153. print qq|<body><h2 class="error">Error!</h2> <p><b>$self->{msg}</b></body>|;
  154. exit;
  155. } else {
  156. if ($ENV{error_function}) {
  157. &{ $ENV{error_function} }($msg);
  158. }
  159. die "Error: $msg\n";
  160. }
  161. }
  162. sub info {
  163. my ($self, $msg) = @_;
  164. if ($ENV{GATEWAY_INTERFACE}) {
  165. $msg =~ s/\n/<br>/g;
  166. delete $self->{pre};
  167. if (!$self->{header}) {
  168. $self->header;
  169. print qq| <body>|;
  170. $self->{header} = 1;
  171. }
  172. print "<b>$msg</b>";
  173. } else {
  174. if ($ENV{info_function}) {
  175. &{ $ENV{info_function} }($msg);
  176. } else {
  177. print "$msg\n";
  178. }
  179. }
  180. }
  181. sub numtextrows {
  182. my ($self, $str, $cols, $maxrows) = @_;
  183. my $rows = 0;
  184. for (split /\n/, $str) {
  185. $rows += int (((length) - 2)/$cols) + 1
  186. }
  187. $maxrows = $rows unless defined $maxrows;
  188. return ($rows > $maxrows) ? $maxrows : $rows;
  189. }
  190. sub dberror {
  191. my ($self, $msg) = @_;
  192. $self->error("$msg\n".$DBI::errstr);
  193. }
  194. sub isblank {
  195. my ($self, $name, $msg) = @_;
  196. $self->error($msg) if $self->{$name} =~ /^\s*$/;
  197. }
  198. sub header {
  199. my ($self, $init, $headeradd) = @_;
  200. return if $self->{header};
  201. my ($stylesheet, $favicon, $charset);
  202. if ($ENV{GATEWAY_INTERFACE}) {
  203. if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
  204. $stylesheet = qq|<link rel="stylesheet" href="css/$self->{stylesheet}" type="text/css" title="LedgerSMB stylesheet" />\n|;
  205. }
  206. if ($self->{charset}) {
  207. $charset = qq|<meta http-equiv="content-type" content="text/html; charset=$self->{charset}" />\n|;
  208. }
  209. $self->{titlebar} = ($self->{title}) ? "$self->{title} - $self->{titlebar}" : $self->{titlebar};
  210. print qq|Content-Type: text/html\n\n
  211. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  212. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  213. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  214. <head>
  215. <title>$self->{titlebar}</title>
  216. <meta http-equiv="Pragma" content="no-cache" />
  217. <meta http-equiv="Expires" content="-1" />
  218. <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  219. $stylesheet
  220. $charset
  221. <meta name="robots" content="noindex,nofollow" />
  222. $headeradd
  223. </head>
  224. $self->{pre} \n|;
  225. }
  226. $self->{header} = 1;
  227. }
  228. sub redirect {
  229. my ($self, $msg) = @_;
  230. if ($self->{callback} || !$msg){
  231. main::redirect();
  232. } else {
  233. $self->info($msg);
  234. }
  235. }
  236. sub sort_columns {
  237. my ($self, @columns) = @_;
  238. if ($self->{sort}) {
  239. if (@columns) {
  240. @columns = grep !/^$self->{sort}$/, @columns;
  241. splice @columns, 0, 0, $self->{sort};
  242. }
  243. }
  244. @columns;
  245. }
  246. sub sort_order {
  247. my ($self, $columns, $ordinal) = @_;
  248. # setup direction
  249. if ($self->{direction}) {
  250. if ($self->{sort} eq $self->{oldsort}) {
  251. if ($self->{direction} eq 'ASC') {
  252. $self->{direction} = "DESC";
  253. } else {
  254. $self->{direction} = "ASC";
  255. }
  256. }
  257. } else {
  258. $self->{direction} = "ASC";
  259. }
  260. $self->{oldsort} = $self->{sort};
  261. my @a = $self->sort_columns(@{$columns});
  262. if (%$ordinal) {
  263. $a[0] = ($ordinal->{$a[$_]}) ? "$ordinal->{$a[0]} $self->{direction}" : "$a[0] $self->{direction}";
  264. for (1 .. $#a) {
  265. $a[$_] = $ordinal->{$a[$_]} if $ordinal->{$a[$_]}
  266. }
  267. } else {
  268. $a[0] .= " $self->{direction}";
  269. }
  270. $sortorder = join ',', @a;
  271. $sortorder;
  272. }
  273. sub format_amount {
  274. my ($self, $myconfig, $amount, $places, $dash) = @_;
  275. my $negative ;
  276. if ($amount){
  277. $amount = $self->parse_amount($myconfig, $amount);
  278. $negative = ($amount < 0);
  279. $amount =~ s/-//;
  280. }
  281. if ($places =~ /\d+/) {
  282. #$places = 4 if $places == 2;
  283. $amount = $self->round_amount($amount, $places);
  284. }
  285. # is the amount negative
  286. # Parse $myconfig->{numberformat}
  287. my ($ts, $ds) = ($1, $2);
  288. if ($amount) {
  289. if ($myconfig->{numberformat}) {
  290. my ($whole, $dec) = split /\./, "$amount";
  291. $amount = join '', reverse split //, $whole;
  292. if ($places) {
  293. $dec .= "0" x $places;
  294. $dec = substr($dec, 0, $places);
  295. }
  296. if ($myconfig->{numberformat} eq '1,000.00') {
  297. $amount =~ s/\d{3,}?/$&,/g;
  298. $amount =~ s/,$//;
  299. $amount = join '', reverse split //, $amount;
  300. $amount .= "\.$dec" if ($dec ne "");
  301. }
  302. if ($myconfig->{numberformat} eq '1 000.00') {
  303. $amount =~ s/\d{3,}?/$& /g;
  304. $amount =~ s/\s$//;
  305. $amount = join '', reverse split //, $amount;
  306. $amount .= "\.$dec" if ($dec ne "");
  307. }
  308. if ($myconfig->{numberformat} eq "1'000.00") {
  309. $amount =~ s/\d{3,}?/$&'/g;
  310. $amount =~ s/'$//;
  311. $amount = join '', reverse split //, $amount;
  312. $amount .= "\.$dec" if ($dec ne "");
  313. }
  314. if ($myconfig->{numberformat} eq '1.000,00') {
  315. $amount =~ s/\d{3,}?/$&./g;
  316. $amount =~ s/\.$//;
  317. $amount = join '', reverse split //, $amount;
  318. $amount .= ",$dec" if ($dec ne "");
  319. }
  320. if ($myconfig->{numberformat} eq '1000,00') {
  321. $amount = "$whole";
  322. $amount .= ",$dec" if ($dec ne "");
  323. }
  324. if ($myconfig->{numberformat} eq '1000.00') {
  325. $amount = "$whole";
  326. $amount .= ".$dec" if ($dec ne "");
  327. }
  328. if ($dash =~ /-/) {
  329. $amount = ($negative) ? "($amount)" : "$amount";
  330. } elsif ($dash =~ /DRCR/) {
  331. $amount = ($negative) ? "$amount DR" : "$amount CR";
  332. } else {
  333. $amount = ($negative) ? "-$amount" : "$amount";
  334. }
  335. }
  336. } else {
  337. if ($dash eq "0" && $places) {
  338. if ($myconfig->{numberformat} eq '1.000,00') {
  339. $amount = "0".","."0" x $places;
  340. } else {
  341. $amount = "0"."."."0" x $places;
  342. }
  343. } else {
  344. $amount = ($dash ne "") ? "$dash" : "";
  345. }
  346. }
  347. $amount;
  348. }
  349. sub parse_amount {
  350. my ($self, $myconfig, $amount) = @_;
  351. if (($amount eq '') or ($amount eq undef)) {
  352. $amount = 0;
  353. }
  354. if (UNIVERSAL::isa($amount, 'Math::BigFloat')){ # Amount may not be an object
  355. return $amount;
  356. }
  357. my $numberformat = $myconfig->{numberformat};
  358. if (($numberformat eq '1.000,00') ||
  359. ($numberformat eq '1000,00')) {
  360. $amount =~ s/\.//g;
  361. $amount =~ s/,/./;
  362. }
  363. if ($numberformat eq '1 000.00'){
  364. $amount =~ s/\s//g;
  365. }
  366. if ($numberformat eq "1'000.00") {
  367. $amount =~ s/'//g;
  368. }
  369. $amount =~ s/,//g;
  370. if ($amount =~ s/\((\d*\.?\d*)\)/$1/){
  371. $amount = $1 * -1;
  372. }
  373. if ($amount =~ s/(\d*\.?\d*)\s?DR/$1/){
  374. $amount = $1 * -1;
  375. }
  376. $amount =~ s/\s?CR//;
  377. $amount = new Math::BigFloat($amount);
  378. return ($amount * 1);
  379. }
  380. sub round_amount {
  381. my ($self, $amount, $places) = @_;
  382. # These rounding rules follow from the previous implementation.
  383. # They should be changed to allow different rules for different accounts.
  384. Math::BigFloat->round_mode('+inf') if $amount >= 0;
  385. Math::BigFloat->round_mode('-inf') if $amount < 0;
  386. $amount = Math::BigFloat->new($amount)->ffround(-$places) if $places >= 0;
  387. $amount = Math::BigFloat->new($amount)->ffround(-($places-1)) if $places < 0;
  388. return $amount;
  389. }
  390. sub callproc {
  391. my $procname = shift @_;
  392. my $argstr = "";
  393. my @results;
  394. for (1 .. $#_){
  395. $argstr .= "?, ";
  396. }
  397. $argstr =~ s/\, $//;
  398. $query = "SELECT $procname";
  399. $query =~ s/\(\)/$argstr/;
  400. my $sth = $self->{dbh}->prepare($query);
  401. while (my $ref = $sth->fetchrow_hashref(NAME_lc)){
  402. push @results, $ref;
  403. }
  404. @results;
  405. }
  406. sub get_my_emp_num {
  407. my ($self, $myconfig, $form) = @_;
  408. %myconfig = %{$myconfig};
  409. my $dbh = $form->{dbh};
  410. # we got a connection, check the version
  411. my $query = qq|
  412. SELECT employeenumber FROM employee
  413. WHERE login = ?|;
  414. my $sth = $dbh->prepare($query);
  415. $sth->execute($form->{login}) || $form->dberror($query);
  416. $sth->execute;
  417. my ($id) = $sth->fetchrow_array;
  418. $sth->finish;
  419. $form->{'emp_num'} = $id;
  420. }
  421. sub parse_template {
  422. my ($self, $myconfig) = @_;
  423. $self->{cwd} = Cwd::getcwd();
  424. for (qw(IN OUT)){
  425. if ($self->{$_} =~ m#[:/\\]#){
  426. $self->error("Access denied");
  427. }
  428. }
  429. if ($self->{language_code} =~ m#[:/\\.*]#){
  430. $self->error("Access Denied");
  431. }
  432. my ($chars_per_line, $lines_on_first_page, $lines_on_second_page) = (0, 0, 0);
  433. my ($current_page, $current_line) = (1, 1);
  434. my $pagebreak = "";
  435. my $sum = 0;
  436. my $subdir = "";
  437. my $err = "";
  438. my %include = ();
  439. my $ok;
  440. if ($self->{language_code}) {
  441. if ($self->{language_code} =~ /(\.\.|\/|\*)/){
  442. $self->error("Invalid Language Code");
  443. }
  444. if (-f "$self->{templates}/$self->{language_code}/$self->{IN}") {
  445. open(IN, '<', "$self->{templates}/$self->{language_code}/$self->{IN}") or $self->error("$self->{IN} : $!");
  446. } else {
  447. open(IN, '<', "$self->{templates}/$self->{IN}") or $self->error("$self->{IN} : $!");
  448. }
  449. } else {
  450. open(IN, "$self->{templates}/$self->{IN}") or $self->error("$self->{IN} : $!");
  451. }
  452. @_ = <IN>;
  453. close(IN);
  454. $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
  455. # OUT is used for the media, screen, printer, email
  456. # for postscript we store a copy in a temporary file
  457. my $fileid = time;
  458. my $tmpfile = $self->{IN};
  459. $tmpfile =~ s/\./_$self->{fileid}./ if $self->{fileid};
  460. $self->{tmpfile} = "${LedgerSMB::Sysconfig::tempdir}/${fileid}_${tmpfile}";
  461. my $temphash;
  462. if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
  463. $temphash{out} = $self->{OUT};
  464. $self->{OUT} = "$self->{tmpfile}";
  465. $temphash{printmode} = $self->{printmode};
  466. $self->{printmode} = '>';
  467. }
  468. if ($self->{OUT}) {
  469. open(OUT, $self->{printmode}, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
  470. chmod(0600, "$self->{OUT}");
  471. } else {
  472. open(OUT, ">-") or $self->error("STDOUT : $!");
  473. $self->header;
  474. }
  475. # first we generate a tmpfile
  476. # read file and replace <?lsmb variable ?>
  477. while ($_ = shift) {
  478. $par = "";
  479. $var = $_;
  480. # detect pagebreak block and its parameters
  481. if (/<\?lsmb pagebreak ([0-9]+) ([0-9]+) ([0-9]+) \?>/) {
  482. $chars_per_line = $1;
  483. $lines_on_first_page = $2;
  484. $lines_on_second_page = $3;
  485. while ($_ = shift) {
  486. last if (/<\?lsmb end pagebreak \?>/);
  487. $pagebreak .= $_;
  488. }
  489. }
  490. if (/<\?lsmb foreach /) {
  491. # this one we need for the count
  492. chomp $var;
  493. $var =~ s/.*?<\?lsmb foreach (.+?) \?>/$1/;
  494. while ($_ = shift) {
  495. last if (/<\?lsmb end $var \?>/);
  496. # store line in $par
  497. $par .= $_;
  498. }
  499. # display contents of $self->{number}[] array
  500. for $i (0 .. $#{ $self->{$var} }) {
  501. if ($var =~ /^(part|service)$/) {
  502. next if $self->{$var}[$i] eq 'NULL';
  503. }
  504. # Try to detect whether a manual page break is necessary
  505. # but only if there was a <?lsmb pagebreak ... ?> block before
  506. if ($var eq 'number' || $var eq 'part' || $var eq 'service') {
  507. if ($chars_per_line && defined $self->{$var}) {
  508. my $line;
  509. my $lines = 0;
  510. my @d = qw(description);
  511. push @d, "itemnotes" if $self->{countitemnotes};
  512. foreach my $item (@d) {
  513. if ($self->{$item}[$i]) {
  514. foreach $line (split /\r?\n/, $self->{$item}[$i]) {
  515. $lines++;
  516. $lines += int(length($line) / $chars_per_line);
  517. }
  518. }
  519. }
  520. my $lpp;
  521. if ($current_page == 1) {
  522. $lpp = $lines_on_first_page;
  523. } else {
  524. $lpp = $lines_on_second_page;
  525. }
  526. # Yes we need a manual page break
  527. if (($current_line + $lines) > $lpp) {
  528. my $pb = $pagebreak;
  529. # replace the special variables <?lsmb sumcarriedforward ?>
  530. # and <?lsmb lastpage ?>
  531. my $psum = $self->format_amount($myconfig, $sum, 2);
  532. $pb =~ s/<\?lsmb sumcarriedforward \?>/$psum/g;
  533. $pb =~ s/<\?lsmb lastpage \?>/$current_page/g;
  534. # only "normal" variables are supported here
  535. # (no <?lsmb if, no <?lsmb foreach, no <?lsmb include)
  536. $pb =~ s/<\?lsmb (.+?) \?>/$self->{$1}/g;
  537. # page break block is ready to rock
  538. print(OUT $pb);
  539. $current_page++;
  540. $current_line = 1;
  541. $lines = 0;
  542. }
  543. $current_line += $lines;
  544. }
  545. $sum += $self->parse_amount($myconfig, $self->{linetotal}[$i]);
  546. }
  547. # don't parse par, we need it for each line
  548. print OUT $self->format_line($par, $i);
  549. }
  550. next;
  551. }
  552. # if not comes before if!
  553. if (/<\?lsmb if not /) {
  554. # check if it is not set and display
  555. chop;
  556. s/.*?<\?lsmb if not (.+?) \?>/$1/;
  557. if (! $self->{$_}) {
  558. while ($_ = shift) {
  559. last if (/<\?lsmb end /);
  560. # store line in $par
  561. $par .= $_;
  562. }
  563. $_ = $par;
  564. } else {
  565. while ($_ = shift) {
  566. last if (/<\?lsmb end /);
  567. }
  568. next;
  569. }
  570. }
  571. if (/<\?lsmb if /) {
  572. # check if it is set and display
  573. chop;
  574. s/.*?<\?lsmb if (.+?) \?>/$1/;
  575. # commenting this out for security reasons. If needed,
  576. # please uncomment. Functionality below will be in 1.3
  577. # Chris Travers
  578. #if (/\s/) {
  579. # @args = split;
  580. # if ($args[1] !~ /^(==|eq|>|gt|>|lt|>=|ge|le|<=|ne|!=)$/){
  581. # $self->error("Unknown/forbidden operator");
  582. # }
  583. # $ok = eval "$self->{$args[0]} $args[1] $args[2]";
  584. #} else {
  585. $ok = $self->{$_};
  586. #}
  587. if ($ok) {
  588. while ($_ = shift) {
  589. last if (/<\?lsmb end /);
  590. # store line in $par
  591. $par .= $_;
  592. }
  593. $_ = $par;
  594. } else {
  595. while ($_ = shift) {
  596. last if (/<\?lsmb end /);
  597. }
  598. next;
  599. }
  600. }
  601. # check for <?lsmb include filename ?>
  602. if (/<\?lsmb include /) {
  603. # get the filename
  604. chomp $var;
  605. $var =~ s/.*?<\?lsmb include (.+?) \?>/$1/;
  606. # remove / .. for security reasons
  607. $var =~ s/(\/|\.\.)//g;
  608. # assume loop after 10 includes of the same file
  609. next if ($include{$var} > 10);
  610. unless (open(INC, '<', "$self->{templates}/$self->{language_code}/$var")) {
  611. $err = $!;
  612. $self->cleanup;
  613. $self->error("$self->{templates}/$self->{language_code}/$var : $err");
  614. }
  615. unshift(@_, <INC>);
  616. close(INC);
  617. $include{$var}++;
  618. next;
  619. }
  620. print OUT $self->format_line($_);
  621. }
  622. close(OUT);
  623. delete $self->{countitemnotes};
  624. # Convert the tex file to postscript
  625. if ($self->{format} =~ /(postscript|pdf)/) {
  626. $self->{tmpdir} = "${LedgerSMB::Sysconfig::tempdir}";
  627. unless (chdir($self->{tmpdir})) {
  628. $err = $!;
  629. $self->cleanup;
  630. $self->debug;
  631. $self->error("chdir : $self->{tmpdir} : $err");
  632. }
  633. $self->{tmpfile} =~ s/$self->{tmpdir}\///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. 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} if $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. chmod (0600, "$self->{OUT}");
  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. 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 employee
  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 employee
  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 employee 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. my $dbh = $self->{dbh};
  1633. $vc ||= $self->{vc}; # add default to correct for improper passing
  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}}'" : 'NULL';
  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->{dbh};
  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, $yy, $mm, $interval) = @_;
  2171. my @t;
  2172. my $dd = 1;
  2173. my $fromdate = "$yy${mm}01";
  2174. my $bd = 1;
  2175. if (defined $interval) {
  2176. if ($interval == 12) {
  2177. $yy++;
  2178. } else {
  2179. if (($mm += $interval) > 12) {
  2180. $mm -= 12;
  2181. $yy++;
  2182. }
  2183. if ($interval == 0) {
  2184. @t = localtime(time);
  2185. $dd = $t[3];
  2186. $mm = $t[4] + 1;
  2187. $yy = $t[5] + 1900;
  2188. $bd = 0;
  2189. }
  2190. }
  2191. } else {
  2192. if (++$mm > 12) {
  2193. $mm -= 12;
  2194. $yy++;
  2195. }
  2196. }
  2197. $mm--;
  2198. @t = localtime(timelocal(0,0,0,$dd,$mm,$yy) - $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. ($fromdate, "$t[5]$t[4]$t[3]");
  2204. }
  2205. sub audittrail {
  2206. my ($self, $dbh, $myconfig, $audittrail) = @_;
  2207. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2208. my $query;
  2209. my $rv;
  2210. my $disconnect;
  2211. if (! $dbh) {
  2212. $dbh = $self->{dbh};
  2213. }
  2214. # if we have an id add audittrail, otherwise get a new timestamp
  2215. my @queryargs;
  2216. if ($audittrail->{id}) {
  2217. $query = qq|
  2218. SELECT value FROM defaults
  2219. WHERE setting_key = 'audittrail'|;
  2220. if ($dbh->selectrow_array($query)) {
  2221. my ($null, $employee_id) = $self->get_employee($dbh);
  2222. if ($self->{audittrail} && !$myconfig) {
  2223. chop $self->{audittrail};
  2224. my @a = split /\|/, $self->{audittrail};
  2225. my %newtrail = ();
  2226. my $key;
  2227. my $i;
  2228. my @flds = qw(tablename reference formname action transdate);
  2229. # put into hash and remove dups
  2230. while (@a) {
  2231. $key = "$a[2]$a[3]";
  2232. $i = 0;
  2233. $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
  2234. splice @a, 0, 5;
  2235. }
  2236. $query = qq|
  2237. INSERT INTO audittrail
  2238. (trans_id, tablename, reference,
  2239. formname, action, transdate,
  2240. employee_id)
  2241. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2242. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2243. foreach $key (sort { $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate} } keys %newtrail) {
  2244. $i = 2;
  2245. $sth->bind_param(1, $audittrail->{id});
  2246. for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
  2247. $sth->bind_param($i++, $employee_id);
  2248. $sth->execute || $self->dberror;
  2249. $sth->finish;
  2250. }
  2251. }
  2252. if ($audittrail->{transdate}) {
  2253. $query = qq|
  2254. INSERT INTO audittrail (
  2255. trans_id, tablename, reference,
  2256. formname, action, employee_id,
  2257. transdate)
  2258. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2259. @queryargs = (
  2260. $audittrail->{id},
  2261. $audittrail->{tablename},
  2262. $audittrail->{reference},
  2263. $audittrail->{formname},
  2264. $audittrail->{action},
  2265. $employee_id,
  2266. $audittrail->{transdate}
  2267. );
  2268. } else {
  2269. $query = qq|
  2270. INSERT INTO audittrail
  2271. (trans_id, tablename, reference,
  2272. formname, action, employee_id)
  2273. VALUES (?, ?, ?, ?, ?, ?)|;
  2274. @queryargs = (
  2275. $audittrail->{id},
  2276. $audittrail->{tablename},
  2277. $audittrail->{reference},
  2278. $audittrail->{formname},
  2279. $audittrail->{action},
  2280. $employee_id,
  2281. );
  2282. }
  2283. $sth = $dbh->prepare($query);
  2284. $sth->execute(@queryargs)||$self->dberror($query);
  2285. }
  2286. } else {
  2287. $query = qq|SELECT current_timestamp|;
  2288. my ($timestamp) = $dbh->selectrow_array($query);
  2289. $rv = "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2290. }
  2291. $dbh->commit;
  2292. $rv;
  2293. }
  2294. 1;