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