summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: 352b0ba0e8cb6d4a180024ecfda822425707e315 (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 (!$set){
  1157. $self->error("Exchange rate missing!");
  1158. }
  1159. if ($sth->fetchrow_array) {
  1160. $query = qq|UPDATE exchangerate
  1161. SET $set
  1162. WHERE curr = ?
  1163. AND transdate = ?|;
  1164. push (@queryargs, $curr, $transdate);
  1165. } else {
  1166. $query = qq|
  1167. INSERT INTO exchangerate (
  1168. curr, buy, sell, transdate)
  1169. VALUES (?, ?, ?, ?)|;
  1170. @queryargs = ($curr, $buy, $sell, $transdate);
  1171. }
  1172. $sth->finish;
  1173. $sth = $self->{dbh}->prepare($query);
  1174. $sth->execute(@queryargs) || $self->dberror($query);
  1175. }
  1176. sub save_exchangerate {
  1177. my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
  1178. my ($buy, $sell) = (0, 0);
  1179. $buy = $rate if $fld eq 'buy';
  1180. $sell = $rate if $fld eq 'sell';
  1181. $self->update_exchangerate(
  1182. $self->{dbh},
  1183. $currency,
  1184. $transdate,
  1185. $buy,
  1186. $sell);
  1187. $dbh->commit;
  1188. }
  1189. sub get_exchangerate {
  1190. my ($self, $dbh, $curr, $transdate, $fld) = @_;
  1191. my $exchangerate = 1;
  1192. if ($transdate) {
  1193. my $query = qq|
  1194. SELECT $fld FROM exchangerate
  1195. WHERE curr = ? AND transdate = ?|;
  1196. $sth = $self->{dbh}->prepare($query);
  1197. $sth->execute($curr, $transdate);
  1198. ($exchangerate) = $sth->fetchrow_array;
  1199. }
  1200. $exchangerate;
  1201. $sth->finish;
  1202. $self->{dbh}->commit;
  1203. }
  1204. sub check_exchangerate {
  1205. my ($self, $myconfig, $currency, $transdate, $fld) = @_;
  1206. return "" unless $transdate;
  1207. my $query = qq|
  1208. SELECT $fld
  1209. FROM exchangerate
  1210. WHERE curr = ? AND transdate = ?|;
  1211. my $sth = $self->{dbh}->prepare($query);
  1212. $sth->execute($currenct, $transdate);
  1213. my ($exchangerate) = $sth->fetchrow_array;
  1214. $sth->finish;
  1215. $self->{dbh}->commit;
  1216. $exchangerate;
  1217. }
  1218. sub add_shipto {
  1219. my ($self, $dbh, $id) = @_;
  1220. my $shipto;
  1221. foreach my $item (qw(name address1 address2 city state
  1222. zipcode country contact phone fax email)) {
  1223. if ($self->{"shipto$item"} ne "") {
  1224. $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
  1225. }
  1226. }
  1227. if ($shipto) {
  1228. my $query = qq|
  1229. INSERT INTO shipto
  1230. (trans_id, shiptoname, shiptoaddress1,
  1231. shiptoaddress2, shiptocity, shiptostate,
  1232. shiptozipcode, shiptocountry, shiptocontact,
  1233. shiptophone, shiptofax, shiptoemail)
  1234. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1235. |;
  1236. $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  1237. $sth->execute(
  1238. $id, $self->{shiptoname}, $self->{shiptoaddress1},
  1239. $self->{shiptoaddress2}, $self->{shiptocity},
  1240. $self->{shiptostate},
  1241. $self->{shiptozipcode}, $self->{shiptocountry},
  1242. $self->{shiptocontact}, $self->{shiptophone},
  1243. $self->{shiptofax}, $self->{shiptoemail}
  1244. ) || $self->dberror($query);
  1245. $sth->finish;
  1246. $self->{dbh}->commit;
  1247. }
  1248. }
  1249. sub get_employee {
  1250. my ($self, $dbh) = @_;
  1251. my $login = $self->{login};
  1252. $login =~ s/@.*//;
  1253. my $query = qq|SELECT name, id
  1254. FROM employee
  1255. WHERE login = ?|;
  1256. $sth = $self->{dbh}->prepare($query);
  1257. $sth->execute($login);
  1258. my (@a) = $sth->fetchrow_array();
  1259. $a[1] *= 1;
  1260. $sth->finish;
  1261. $self->{dbh}->commit;
  1262. @a;
  1263. }
  1264. # this sub gets the id and name from $table
  1265. sub get_name {
  1266. my ($self, $myconfig, $table, $transdate) = @_;
  1267. # connect to database
  1268. my @queryargs;
  1269. my $where;
  1270. if ($transdate) {
  1271. $where = qq|
  1272. AND (startdate IS NULL OR startdate <= ?)
  1273. AND (enddate IS NULL OR enddate >= ?)|;
  1274. @queryargs = ($transdate, $transdate);
  1275. }
  1276. my $name = $self->like(lc $self->{$table});
  1277. my $query = qq|
  1278. SELECT * FROM $table
  1279. WHERE (lower(name) LIKE ? OR ${table}number LIKE ?)
  1280. $where
  1281. ORDER BY name|;
  1282. unshift(@queryargs, $name, $name);
  1283. my $sth = $self->{dbh}->prepare($query);
  1284. $sth->execute(@queryargs) || $self->dberror($query);
  1285. my $i = 0;
  1286. @{ $self->{name_list} } = ();
  1287. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1288. push(@{ $self->{name_list} }, $ref);
  1289. $i++;
  1290. }
  1291. $sth->finish;
  1292. $self->{dbh}->commit;
  1293. $i;
  1294. }
  1295. sub all_vc {
  1296. my ($self, $myconfig, $vc, $module, $dbh, $transdate, $job) = @_;
  1297. my $ref;
  1298. my $disconnect = 0;
  1299. $dbh = $self->{dbh};
  1300. my $sth;
  1301. my $query = qq|SELECT count(*) FROM $vc|;
  1302. my $where;
  1303. my @queryargs = ();
  1304. if ($transdate) {
  1305. $query .= qq| WHERE (startdate IS NULL OR startdate <= ?)
  1306. AND (enddate IS NULL OR enddate >= ?)|;
  1307. @queryargs = ($transdate, $transdate);
  1308. }
  1309. $sth = $dbh->prepare($query);
  1310. $sth->execute(@queryargs);
  1311. my ($count) = $sth->fetchrow_array;
  1312. $sth->finish;
  1313. @queryargs = ();
  1314. # build selection list
  1315. if ($count < $myconfig->{vclimit}) {
  1316. $self->{"${vc}_id"} *= 1;
  1317. $query = qq|SELECT id, name
  1318. FROM $vc
  1319. WHERE 1=1
  1320. $where
  1321. UNION
  1322. SELECT id,name
  1323. FROM $vc
  1324. WHERE id = ?
  1325. ORDER BY name|;
  1326. push(@queryargs, $self->{"${vc}_id"});
  1327. $sth = $dbh->prepare($query);
  1328. $sth->execute(@queryargs) || $self->dberror($query);
  1329. @{ $self->{"all_$vc"} } = ();
  1330. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1331. push @{ $self->{"all_$vc"} }, $ref;
  1332. }
  1333. $sth->finish;
  1334. }
  1335. # get self
  1336. if (! $self->{employee_id}) {
  1337. ($self->{employee}, $self->{employee_id}) = split /--/, $self->{employee};
  1338. ($self->{employee}, $self->{employee_id}) = $self->get_employee($dbh) unless $self->{employee_id};
  1339. }
  1340. $self->all_employees($myconfig, $dbh, $transdate, 1);
  1341. $self->all_departments($myconfig, $dbh, $vc);
  1342. $self->all_projects($myconfig, $dbh, $transdate, $job);
  1343. # get language codes
  1344. $query = qq|SELECT *
  1345. FROM language
  1346. ORDER BY 2|;
  1347. $sth = $dbh->prepare($query);
  1348. $sth->execute || $self->dberror($query);
  1349. $self->{all_language} = ();
  1350. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1351. push @{ $self->{all_language} }, $ref;
  1352. }
  1353. $sth->finish;
  1354. $self->all_taxaccounts($myconfig, $dbh, $transdate);
  1355. $self->{dbh}->commit;
  1356. }
  1357. sub all_taxaccounts {
  1358. my ($self, $myconfig, $dbh2, $transdate) = @_;
  1359. my $dbh = $self->{dbh};
  1360. my $sth;
  1361. my $query;
  1362. my $where;
  1363. my @queryargs = ();
  1364. if ($transdate) {
  1365. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1366. push(@queryargs, $transdate);
  1367. }
  1368. if ($self->{taxaccounts}) {
  1369. # rebuild tax rates
  1370. $query = qq|SELECT t.rate, t.taxnumber
  1371. FROM tax t
  1372. JOIN chart c ON (c.id = t.chart_id)
  1373. WHERE c.accno = ?
  1374. $where
  1375. ORDER BY accno, validto|;
  1376. $sth = $dbh->prepare($query) || $self->dberror($query);
  1377. foreach my $accno (split / /, $self->{taxaccounts}) {
  1378. $sth->execute($accno, @queryargs);
  1379. ($self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"}) = $sth->fetchrow_array;
  1380. $sth->finish;
  1381. }
  1382. }
  1383. $self->{dbh}->commit;
  1384. }
  1385. sub all_employees {
  1386. my ($self, $myconfig, $dbh2, $transdate, $sales) = @_;
  1387. my $dbh = $self->{dbh};
  1388. my @whereargs = ();
  1389. # setup employees/sales contacts
  1390. my $query = qq|SELECT id, name
  1391. FROM employee
  1392. WHERE 1 = 1|;
  1393. if ($transdate) {
  1394. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1395. AND (enddate IS NULL OR enddate >= ?)|;
  1396. @whereargs = ($transdate, $transdate);
  1397. } else {
  1398. $query .= qq| AND enddate IS NULL|;
  1399. }
  1400. if ($sales) {
  1401. $query .= qq| AND sales = '1'|;
  1402. }
  1403. $query .= qq| ORDER BY name|;
  1404. my $sth = $dbh->prepare($query);
  1405. $sth->execute(@whereargs) || $self->dberror($query);
  1406. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1407. push @{ $self->{all_employee} }, $ref;
  1408. }
  1409. $sth->finish;
  1410. $dbh->commit;
  1411. }
  1412. sub all_projects {
  1413. my ($self, $myconfig, $dbh2, $transdate, $job) = @_;
  1414. my $dbh = $self->{dbh};
  1415. my @queryargs = ();
  1416. my $where = "1 = 1";
  1417. $where = qq|id NOT IN (SELECT id
  1418. FROM parts
  1419. WHERE project_id > 0)| if ! $job;
  1420. my $query = qq|SELECT *
  1421. FROM project
  1422. WHERE $where|;
  1423. if ($self->{language_code}) {
  1424. $query = qq|
  1425. SELECT pr.*, t.description AS translation
  1426. FROM project pr
  1427. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1428. WHERE t.language_code = ?|;
  1429. push(@queryargs, $self->{language_code});
  1430. }
  1431. if ($transdate) {
  1432. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1433. AND (enddate IS NULL OR enddate >= ?)|;
  1434. push(@queryargs, $transdate, $transdate);
  1435. }
  1436. $query .= qq| ORDER BY projectnumber|;
  1437. $sth = $dbh->prepare($query);
  1438. $sth->execute(@queryargs)|| $self->dberror($query);
  1439. @{ $self->{all_project} } = ();
  1440. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1441. push @{ $self->{all_project} }, $ref;
  1442. }
  1443. $sth->finish;
  1444. $dbh->commit;
  1445. }
  1446. sub all_departments {
  1447. my ($self, $myconfig, $dbh2, $vc) = @_;
  1448. $dbh = $self->{dbh};
  1449. my $where = "1 = 1";
  1450. if ($vc) {
  1451. if ($vc eq 'customer') {
  1452. $where = " role = 'P'";
  1453. }
  1454. }
  1455. my $query = qq|SELECT id, description
  1456. FROM department
  1457. WHERE $where
  1458. ORDER BY 2|;
  1459. my $sth = $dbh->prepare($query);
  1460. $sth->execute || $self->dberror($query);
  1461. @{ $self->{all_department} } = ();
  1462. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1463. push @{ $self->{all_department} }, $ref;
  1464. }
  1465. $sth->finish;
  1466. $self->all_years($myconfig);
  1467. $dbh->commit;
  1468. }
  1469. sub all_years {
  1470. my ($self, $myconfig, $dbh2) = @_;
  1471. $dbh = $self->{dbh};
  1472. # get years
  1473. my $query = qq|
  1474. SELECT (SELECT MIN(transdate) FROM acc_trans),
  1475. (SELECT MAX(transdate) FROM acc_trans)|;
  1476. my ($startdate, $enddate) = $dbh->selectrow_array($query);
  1477. if ($myconfig->{dateformat} =~ /^yy/) {
  1478. ($startdate) = split /\W/, $startdate;
  1479. ($enddate) = split /\W/, $enddate;
  1480. } else {
  1481. (@_) = split /\W/, $startdate;
  1482. $startdate = $_[2];
  1483. (@_) = split /\W/, $enddate;
  1484. $enddate = $_[2];
  1485. }
  1486. $self->{all_years} = ();
  1487. $startdate = substr($startdate,0,4);
  1488. $enddate = substr($enddate,0,4);
  1489. while ($enddate >= $startdate) {
  1490. push @{ $self->{all_years} }, $enddate--;
  1491. }
  1492. #this should probably be changed to use locale
  1493. %{ $self->{all_month} } = (
  1494. '01' => 'January',
  1495. '02' => 'February',
  1496. '03' => 'March',
  1497. '04' => 'April',
  1498. '05' => 'May ',
  1499. '06' => 'June',
  1500. '07' => 'July',
  1501. '08' => 'August',
  1502. '09' => 'September',
  1503. '10' => 'October',
  1504. '11' => 'November',
  1505. '12' => 'December' );
  1506. $dbh->commit;
  1507. }
  1508. sub create_links {
  1509. my ($self, $module, $myconfig, $vc, $job) = @_;
  1510. # get last customers or vendors
  1511. my ($query, $sth);
  1512. $dbh = $self->{dbh};
  1513. my %xkeyref = ();
  1514. # now get the account numbers
  1515. $query = qq|SELECT accno, description, link
  1516. FROM chart
  1517. WHERE link LIKE ?
  1518. ORDER BY accno|;
  1519. $sth = $dbh->prepare($query);
  1520. $sth->execute("%"."$module%") || $self->dberror($query);
  1521. $self->{accounts} = "";
  1522. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1523. foreach my $key (split /:/, $ref->{link}) {
  1524. if ($key =~ /$module/) {
  1525. # cross reference for keys
  1526. $xkeyref{$ref->{accno}} = $key;
  1527. push @{ $self->{"${module}_links"}{$key} },
  1528. { accno => $ref->{accno},
  1529. description => $ref->{description} };
  1530. $self->{accounts} .= "$ref->{accno} "
  1531. unless $key =~ /tax/;
  1532. }
  1533. }
  1534. }
  1535. $sth->finish;
  1536. my $arap = ($vc eq 'customer') ? 'ar' : 'ap';
  1537. if ($self->{id}) {
  1538. $query = qq|
  1539. SELECT a.invnumber, a.transdate,
  1540. a.${vc}_id, a.datepaid, a.duedate, a.ordnumber,
  1541. a.taxincluded, a.curr AS currency, a.notes,
  1542. a.intnotes, c.name AS $vc, a.department_id,
  1543. d.description AS department,
  1544. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1545. a.employee_id, e.name AS employee,
  1546. c.language_code, a.ponumber
  1547. FROM $arap a
  1548. JOIN $vc c ON (a.${vc}_id = c.id)
  1549. LEFT JOIN employee e ON (e.id = a.employee_id)
  1550. LEFT JOIN department d ON (d.id = a.department_id)
  1551. WHERE a.id = ?|;
  1552. $sth = $dbh->prepare($query);
  1553. $sth->execute($self->{id}) || $self->dberror($query);
  1554. $ref = $sth->fetchrow_hashref(NAME_lc);
  1555. foreach $key (keys %$ref) {
  1556. $self->{$key} = $ref->{$key};
  1557. }
  1558. $sth->finish;
  1559. # get printed, emailed
  1560. $query = qq|
  1561. SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1562. FROM status s WHERE s.trans_id = ?|;
  1563. $sth = $dbh->prepare($query);
  1564. $sth->execute($self->{id}) || $self->dberror($query);
  1565. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1566. $self->{printed} .= "$ref->{formname} "
  1567. if $ref->{printed};
  1568. $self->{emailed} .= "$ref->{formname} "
  1569. if $ref->{emailed};
  1570. $self->{queued} .= "$ref->{formname} ".
  1571. "$ref->{spoolfile} " if $ref->{spoolfile};
  1572. }
  1573. $sth->finish;
  1574. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1575. # get recurring
  1576. $self->get_recurring($dbh);
  1577. # get amounts from individual entries
  1578. $query = qq|
  1579. SELECT c.accno, c.description, a.source, a.amount,
  1580. a.memo, a.transdate, a.cleared, a.project_id,
  1581. p.projectnumber
  1582. FROM acc_trans a
  1583. JOIN chart c ON (c.id = a.chart_id)
  1584. LEFT JOIN project p ON (p.id = a.project_id)
  1585. WHERE a.trans_id = ?
  1586. AND a.fx_transaction = '0'
  1587. ORDER BY transdate|;
  1588. $sth = $dbh->prepare($query);
  1589. $sth->execute($self->{id}) || $self->dberror($query);
  1590. my $fld = ($vc eq 'customer') ? 'buy' : 'sell';
  1591. $self->{exchangerate} = $self->get_exchangerate($dbh,
  1592. $self->{currency}, $self->{transdate}, $fld);
  1593. # store amounts in {acc_trans}{$key} for multiple accounts
  1594. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1595. $ref->{exchangerate} = $self->get_exchangerate($dbh,
  1596. $self->{currency},
  1597. $ref->{transdate},
  1598. $fld);
  1599. push @{ $self->{acc_trans}{$xkeyref{$ref->{accno}}} },
  1600. $ref;
  1601. }
  1602. $sth->finish;
  1603. for (qw(curr closedto revtrans)){
  1604. $query = qq|
  1605. SELECT value FROM defaults
  1606. WHERE setting_key = '$_'|;
  1607. $sth = $dbh->prepare($query);
  1608. $sth->execute || $self->dberror($query);
  1609. ($val) = $sth->fetchrow_array();
  1610. if ($_ eq 'curr'){
  1611. $self->{currencies} = $val;
  1612. } else {
  1613. $self->{$_} = $val;
  1614. }
  1615. $sth->finish;
  1616. }
  1617. } else {
  1618. for (qw(current_date curr closedto revtrans)){
  1619. $query = qq|
  1620. SELECT value FROM defaults
  1621. WHERE setting_key = '$_'|;
  1622. $sth = $dbh->prepare($query);
  1623. $sth->execute || $self->dberror($query);
  1624. ($val) = $sth->fetchrow_array();
  1625. if ($_ eq 'curr'){
  1626. $self->{currencies} = $val;
  1627. } elsif ($_ eq 'current_date'){
  1628. $self->{transdate} = $val;
  1629. } else {
  1630. $self->{$_} = $val;
  1631. }
  1632. $sth->finish;
  1633. }
  1634. if (! $self->{"$self->{vc}_id"}) {
  1635. $self->lastname_used($myconfig, $dbh, $vc, $module);
  1636. }
  1637. }
  1638. $self->all_vc($myconfig, $vc, $module, $dbh, $self->{transdate}, $job);
  1639. $self->{dbh}->commit;
  1640. }
  1641. sub lastname_used {
  1642. my ($self, $myconfig, $dbh2, $vc, $module) = @_;
  1643. my $dbh = $self->{dbh};
  1644. $vc ||= $self->{vc}; # add default to correct for improper passing
  1645. my $arap = ($vc eq 'customer') ? "ar" : "ap";
  1646. my $where = "1 = 1";
  1647. my $sth;
  1648. if ($self->{type} =~ /_order/) {
  1649. $arap = 'oe';
  1650. $where = "quotation = '0'";
  1651. }
  1652. if ($self->{type} =~ /_quotation/) {
  1653. $arap = 'oe';
  1654. $where = "quotation = '1'";
  1655. }
  1656. my $query = qq|
  1657. SELECT id
  1658. FROM $arap
  1659. WHERE id IN
  1660. (SELECT MAX(id)
  1661. FROM $arap
  1662. WHERE $where AND ${vc}_id > 0)|;
  1663. my ($trans_id) = $dbh->selectrow_array($query);
  1664. $trans_id *= 1;
  1665. $query = qq|
  1666. SELECT ct.name AS $vc, a.curr AS currency, a.${vc}_id,
  1667. current_date + ct.terms AS duedate,
  1668. a.department_id, d.description AS department, ct.notes,
  1669. ct.curr AS currency
  1670. FROM $arap a
  1671. JOIN $vc ct ON (a.${vc}_id = ct.id)
  1672. LEFT JOIN department d ON (a.department_id = d.id)
  1673. WHERE a.id = ?|;
  1674. $sth = $dbh->prepare($query);
  1675. $sth->execute($trans_id)|| $self->dberror($query);
  1676. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1677. for (keys %$ref) { $self->{$_} = $ref->{$_} }
  1678. $sth->finish;
  1679. $dbh->commit;
  1680. }
  1681. sub current_date {
  1682. my ($self, $myconfig, $thisdate, $days) = @_;
  1683. my $dbh = $self->{dbh};
  1684. my $query;
  1685. $days *= 1;
  1686. if ($thisdate) {
  1687. my $dateformat = $myconfig->{dateformat};
  1688. if ($myconfig->{dateformat} !~ /^y/) {
  1689. my @a = split /\D/, $thisdate;
  1690. $dateformat .= "yy" if (length $a[2] > 2);
  1691. }
  1692. if ($thisdate !~ /\D/) {
  1693. $dateformat = 'yyyymmdd';
  1694. }
  1695. $query = qq|SELECT (to_date(?, ?)
  1696. + ?::interval)::date AS thisdate|;
  1697. @queryargs = ($thisdate, $dateformat, $days);
  1698. } else {
  1699. $query = qq|SELECT current_date AS thisdate|;
  1700. @queryargs = ();
  1701. }
  1702. $sth = $dbh->prepare($query);
  1703. $sth->execute(@queryargs);
  1704. ($thisdate) = $sth->fetchrow_array;
  1705. $dbh->commit;
  1706. $thisdate;
  1707. }
  1708. sub like {
  1709. my ($self, $str) = @_;
  1710. "%$str%";
  1711. }
  1712. sub redo_rows {
  1713. my ($self, $flds, $new, $count, $numrows) = @_;
  1714. my @ndx = ();
  1715. for (1 .. $count) {
  1716. push @ndx, { num => $new->[$_-1]->{runningnumber}, ndx => $_ }
  1717. }
  1718. my $i = 0;
  1719. # fill rows
  1720. foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
  1721. $i++;
  1722. $j = $item->{ndx} - 1;
  1723. for (@{$flds}) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1724. }
  1725. # delete empty rows
  1726. for $i ($count + 1 .. $numrows) {
  1727. for (@{$flds}) { delete $self->{"${_}_$i"} }
  1728. }
  1729. }
  1730. sub get_partsgroup {
  1731. my ($self, $myconfig, $p) = @_;
  1732. my $dbh = $self->{dbh};
  1733. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1734. FROM partsgroup pg
  1735. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1736. my $where;
  1737. my $sortorder = "partsgroup";
  1738. if ($p->{searchitems} eq 'part') {
  1739. $where = qq| WHERE (p.inventory_accno_id > 0
  1740. AND p.income_accno_id > 0)|;
  1741. }
  1742. if ($p->{searchitems} eq 'service') {
  1743. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1744. }
  1745. if ($p->{searchitems} eq 'assembly') {
  1746. $where = qq| WHERE p.assembly = '1'|;
  1747. }
  1748. if ($p->{searchitems} eq 'labor') {
  1749. $where = qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1750. }
  1751. if ($p->{searchitems} eq 'nolabor') {
  1752. $where = qq| WHERE p.income_accno_id > 0|;
  1753. }
  1754. if ($p->{all}) {
  1755. $query = qq|SELECT id, partsgroup
  1756. FROM partsgroup|;
  1757. }
  1758. my @queryargs = ();
  1759. if ($p->{language_code}) {
  1760. $sortorder = "translation";
  1761. $query = qq|
  1762. SELECT DISTINCT pg.id, pg.partsgroup,
  1763. t.description AS translation
  1764. FROM partsgroup pg
  1765. JOIN parts p ON (p.partsgroup_id = pg.id)
  1766. LEFT JOIN translation t ON (t.trans_id = pg.id
  1767. AND t.language_code = ?)|;
  1768. @queryargs = ($p->{language_code});
  1769. }
  1770. $query .= qq| $where ORDER BY $sortorder|;
  1771. my $sth = $dbh->prepare($query);
  1772. $sth->execute(@queryargs)|| $self->dberror($query);
  1773. $self->{all_partsgroup} = ();
  1774. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1775. push @{ $self->{all_partsgroup} }, $ref;
  1776. }
  1777. $sth->finish;
  1778. $dbh->commit;
  1779. }
  1780. sub update_status {
  1781. my ($self, $myconfig) = @_;
  1782. # no id return
  1783. return unless $self->{id};
  1784. my $dbh = $self->{dbh};
  1785. my %queued = split / +/, $self->{queued};
  1786. my $spoolfile = ($queued{$self->{formname}}) ? "'$queued{$self->{formname}}'" : 'NULL';
  1787. my $query = qq|DELETE FROM status
  1788. WHERE formname = ?
  1789. AND trans_id = ?|;
  1790. $sth=$dbh->prepare($query);
  1791. $sth->execute($self->{formname}, $self->{id}) || $self->dberror($query);
  1792. $sth->finish;
  1793. my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
  1794. my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
  1795. $query = qq|
  1796. INSERT INTO status
  1797. (trans_id, printed, emailed, spoolfile, formname)
  1798. VALUES (?, ?, ?, ?, ?)|;
  1799. $sth = $dbh->prepare($query);
  1800. $sth->execute($self->{id}, $printed, $emailed, $spoolfile,
  1801. $self->{formname});
  1802. $sth->finish;
  1803. $dbh->commit;
  1804. }
  1805. sub save_status {
  1806. my ($self) = @_;
  1807. $dbh = $self->{dbh};
  1808. my $formnames = $self->{printed};
  1809. my $emailforms = $self->{emailed};
  1810. my $query = qq|DELETE FROM status
  1811. WHERE trans_id = ?|;
  1812. my $sth = $dbh->prepare($query);
  1813. $sth->execute($self->{id});
  1814. $sth->finish;
  1815. my %queued;
  1816. my $formname;
  1817. if ($self->{queued}) {
  1818. %queued = split / +/, $self->{queued};
  1819. foreach $formname (keys %queued) {
  1820. $printed = ($self->{printed} =~ /$formname/) ? "1" : "0";
  1821. $emailed = ($self->{emailed} =~ /$formname/) ? "1" : "0";
  1822. if ($queued{$formname}) {
  1823. $query = qq|
  1824. INSERT INTO status
  1825. (trans_id, printed, emailed,
  1826. spoolfile, formname)
  1827. VALUES (?, ?, ?, ?, ?)|;
  1828. $sth = $dbh->prepare($query);
  1829. $sth->execute($self->{id}, $pinted, $emailed,
  1830. $queued{$formname}, $formname)
  1831. || $self->dberror($query);
  1832. $sth->finish;
  1833. }
  1834. $formnames =~ s/$formname//;
  1835. $emailforms =~ s/$formname//;
  1836. }
  1837. }
  1838. # save printed, emailed info
  1839. $formnames =~ s/^ +//g;
  1840. $emailforms =~ s/^ +//g;
  1841. my %status = ();
  1842. for (split / +/, $formnames) { $status{$_}{printed} = 1 }
  1843. for (split / +/, $emailforms) { $status{$_}{emailed} = 1 }
  1844. foreach my $formname (keys %status) {
  1845. $printed = ($formnames =~ /$self->{formname}/) ? "1" : "0";
  1846. $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
  1847. $query = qq|
  1848. INSERT INTO status (trans_id, printed, emailed,
  1849. formname)
  1850. VALUES (?, ?, ?, ?)|;
  1851. $sth = $dbh->prepare($query);
  1852. $sth->execute($self->{id}, $printed, $emailed, $formname);
  1853. $sth->finish;
  1854. }
  1855. $dbh->commit;
  1856. }
  1857. sub get_recurring {
  1858. my ($self) = @_;
  1859. $dbh = $self->{dbh};
  1860. my $query = qq/
  1861. SELECT s.*, se.formname || ':' || se.format AS emaila,
  1862. se.message, sp.formname || ':' ||
  1863. sp.format || ':' || sp.printer AS printa
  1864. FROM recurring s
  1865. LEFT JOIN recurringemail se ON (s.id = se.id)
  1866. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  1867. WHERE s.id = ?/;
  1868. my $sth = $dbh->prepare($query);
  1869. $sth->execute($self->{id}) || $self->dberror($query);
  1870. for (qw(email print)) { $self->{"recurring$_"} = "" }
  1871. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1872. for (keys %$ref) { $self->{"recurring$_"} = $ref->{$_} }
  1873. $self->{recurringemail} .= "$ref->{emaila}:";
  1874. $self->{recurringprint} .= "$ref->{printa}:";
  1875. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  1876. }
  1877. $sth->finish;
  1878. chop $self->{recurringemail};
  1879. chop $self->{recurringprint};
  1880. if ($self->{recurringstartdate}) {
  1881. $self->{recurringreference} = $self->escape($self->{recurringreference},1);
  1882. $self->{recurringmessage} = $self->escape($self->{recurringmessage},1);
  1883. for (qw(reference startdate repeat unit howmany
  1884. payment print email message)) {
  1885. $self->{recurring} .= qq|$self->{"recurring$_"},|
  1886. }
  1887. chop $self->{recurring};
  1888. }
  1889. $dbh->commit;
  1890. }
  1891. sub save_recurring {
  1892. my ($self, $dbh2, $myconfig) = @_;
  1893. my $dbh = $self->{dbh};
  1894. my $query;
  1895. $query = qq|DELETE FROM recurring
  1896. WHERE id = ?|;
  1897. $sth = $dbh->prepare($query);
  1898. $sth->execute($self->{id}) || $self->dberror($query);
  1899. $query = qq|DELETE FROM recurringemail
  1900. WHERE id = ?|;
  1901. $sth = $dbh->prepare($query);
  1902. $sth->execute($self->{id}) || $self->dberror($query);
  1903. $query = qq|DELETE FROM recurringprint
  1904. WHERE id = ?|;
  1905. $sth = $dbh->prepare($query);
  1906. $sth->execute($self->{id}) || $self->dberror($query);
  1907. if ($self->{recurring}) {
  1908. my %s = ();
  1909. ($s{reference}, $s{startdate}, $s{repeat}, $s{unit},
  1910. $s{howmany}, $s{payment}, $s{print}, $s{email},
  1911. $s{message})
  1912. = split /,/, $self->{recurring};
  1913. for (qw(reference message)) { $s{$_} = $self->unescape($s{$_}) }
  1914. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  1915. # calculate enddate
  1916. my $advance = $s{repeat} * ($s{howmany} - 1);
  1917. my %interval;
  1918. $interval{'Pg'} =
  1919. "(date '$s{startdate}' + interval '$advance $s{unit}')";
  1920. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  1921. my ($enddate) = $dbh->selectrow_array($query);
  1922. # calculate nextdate
  1923. $query = qq|
  1924. SELECT current_date - date ? AS a,
  1925. date ? - current_date AS b|;
  1926. $sth = $dbh->prepare($query);
  1927. $sth->execute($s{startdate}, $enddate);
  1928. my ($a, $b) = $sth->fetchrow_array;
  1929. if ($a + $b) {
  1930. $advance = int(($a / ($a + $b)) * ($s{howmany} - 1) + 1) * $s{repeat};
  1931. } else {
  1932. $advance = 0;
  1933. }
  1934. my $nextdate = $enddate;
  1935. if ($advance > 0) {
  1936. if ($advance < ($s{repeat} * $s{howmany})) {
  1937. %interval = ( 'Pg' => "(date '$s{startdate}' + interval '$advance $s{unit}')",
  1938. 'DB2' => qq|(date ('$s{startdate}') + "$advance $s{unit}")|,);
  1939. $interval{Oracle} = $interval{PgPP} = $interval{Pg};
  1940. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  1941. ($nextdate) = $dbh->selectrow_array($query);
  1942. }
  1943. } else {
  1944. $nextdate = $s{startdate};
  1945. }
  1946. if ($self->{recurringnextdate}) {
  1947. $nextdate = $self->{recurringnextdate};
  1948. $query = qq|SELECT '$enddate' - date '$nextdate'|;
  1949. if ($dbh->selectrow_array($query) < 0) {
  1950. undef $nextdate;
  1951. }
  1952. }
  1953. $self->{recurringpayment} *= 1;
  1954. $query = qq|
  1955. INSERT INTO recurring
  1956. (id, reference, startdate, enddate, nextdate,
  1957. repeat, unit, howmany, payment)
  1958. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  1959. $sth = $dbh->prepare($query);
  1960. $sth->execute($self->{id}, $s{reference}, $s{startdate},
  1961. $enddate, $nextdate, $s{repeat}, $s{unit}, $s{howmany},
  1962. $s{payment});
  1963. my @p;
  1964. my $p;
  1965. my $i;
  1966. my $sth;
  1967. if ($s{email}) {
  1968. # formname:format
  1969. @p = split /:/, $s{email};
  1970. $query = qq|INSERT INTO recurringemail (id, formname, format, message)
  1971. VALUES (?, ?, ?, ?)|;
  1972. $sth = $dbh->prepare($query) || $self->dberror($query);
  1973. for ($i = 0; $i <= $#p; $i += 2) {
  1974. $sth->execute($self->{id}, $p[$i], $p[$i+1],
  1975. $s{message});
  1976. }
  1977. $sth->finish;
  1978. }
  1979. if ($s{print}) {
  1980. # formname:format:printer
  1981. @p = split /:/, $s{print};
  1982. $query = qq|INSERT INTO recurringprint (id, formname, format, printer)
  1983. VALUES (?, ?, ?, ?)|;
  1984. $sth = $dbh->prepare($query) || $self->dberror($query);
  1985. for ($i = 0; $i <= $#p; $i += 3) {
  1986. $p = ($p[$i+2]) ? $p[$i+2] : "";
  1987. $sth->execute($self->{id}, $p[$i], $p[$i+1], $p);
  1988. }
  1989. $sth->finish;
  1990. }
  1991. }
  1992. $dbh->commit;
  1993. }
  1994. sub save_intnotes {
  1995. my ($self, $myconfig, $vc) = @_;
  1996. # no id return
  1997. return unless $self->{id};
  1998. my $dbh = $self->{dbh};
  1999. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  2000. $sth=$dbh->prepare($query);
  2001. $sth->execute($self->{intnotes}, $self->{id}) || $self->dberror($query);
  2002. $dbh->commit;
  2003. }
  2004. sub update_defaults {
  2005. my ($self, $myconfig, $fld) = @_;
  2006. if (!$self->{dbh} && $self){
  2007. $self->db_init($myconfig);
  2008. }
  2009. my $dbh = $self->{dbh};
  2010. if (!$self){
  2011. $dbh = $_[3];
  2012. }
  2013. my $query = qq|
  2014. SELECT value FROM defaults
  2015. WHERE setting_key = ? FOR UPDATE|;
  2016. $sth = $dbh->prepare($query);
  2017. $sth->execute($fld);
  2018. ($_) = $sth->fetchrow_array();
  2019. $_ = "0" unless $_;
  2020. # check for and replace
  2021. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  2022. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  2023. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  2024. # <?lsmb PHONE ?> for customer and vendors
  2025. my $num = $_;
  2026. ($num) = $num =~ /(\d+)/;
  2027. if (defined $num) {
  2028. my $incnum;
  2029. # if we have leading zeros check how long it is
  2030. if ($num =~ /^0/) {
  2031. my $l = length $num;
  2032. $incnum = $num + 1;
  2033. $l -= length $incnum;
  2034. # pad it out with zeros
  2035. my $padzero = "0" x $l;
  2036. $incnum = ("0" x $l) . $incnum;
  2037. } else {
  2038. $incnum = $num + 1;
  2039. }
  2040. s/$num/$incnum/;
  2041. }
  2042. my $dbvar = $_;
  2043. my $var = $_;
  2044. my $str;
  2045. my $param;
  2046. if (/<\?lsmb /) {
  2047. while (/<\?lsmb /) {
  2048. s/<\?lsmb .*? \?>//;
  2049. last unless $&;
  2050. $param = $&;
  2051. $str = "";
  2052. if ($param =~ /<\?lsmb date \?>/i) {
  2053. $str = ($self->split_date($myconfig->{dateformat}, $self->{transdate}))[0];
  2054. $var =~ s/$param/$str/;
  2055. }
  2056. if ($param =~ /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i) {
  2057. my $fld = lc $&;
  2058. $fld =~ s/<\?lsmb //;
  2059. if ($fld =~ /name/) {
  2060. if ($self->{type}) {
  2061. $fld = $self->{vc};
  2062. }
  2063. }
  2064. my $p = $param;
  2065. $p =~ s/(<|>|%)//g;
  2066. my @p = split / /, $p;
  2067. my @n = split / /, uc $self->{$fld};
  2068. if ($#p > 0) {
  2069. for (my $i = 1; $i <= $#p; $i++) {
  2070. $str .= substr($n[$i-1], 0, $p[$i]);
  2071. }
  2072. } else {
  2073. ($str) = split /--/, $self->{$fld};
  2074. }
  2075. $var =~ s/$param/$str/;
  2076. $var =~ s/\W//g if $fld eq 'phone';
  2077. }
  2078. if ($param =~ /<\?lsmb (yy|mm|dd)/i) {
  2079. my $p = $param;
  2080. $p =~ s/(<|>|%)//g;
  2081. my $spc = $p;
  2082. $spc =~ s/\w//g;
  2083. $spc = substr($spc, 0, 1);
  2084. my %d = ( yy => 1, mm => 2, dd => 3 );
  2085. my @p = ();
  2086. my @a = $self->split_date($myconfig->{dateformat}, $self->{transdate});
  2087. for (sort keys %d) { push @p, $a[$d{$_}] if ($p =~ /$_/) }
  2088. $str = join $spc, @p;
  2089. $var =~ s/$param/$str/;
  2090. }
  2091. if ($param =~ /<\?lsmb curr/i) {
  2092. $var =~ s/$param/$self->{currency}/;
  2093. }
  2094. }
  2095. }
  2096. $query = qq|
  2097. UPDATE defaults
  2098. SET value = ?
  2099. WHERE setting_key = ?|;
  2100. $sth = $dbh->prepare($query);
  2101. $sth->execute($dbvar, $fld) || $self->dberror($query);
  2102. $dbh->commit;
  2103. $var;
  2104. }
  2105. sub db_prepare_vars {
  2106. my $self = shift;
  2107. for (@_){
  2108. if (!$self->{$_} and $self->{$_} ne "0"){
  2109. undef $self->{$_};
  2110. }
  2111. }
  2112. }
  2113. sub split_date {
  2114. my ($self, $dateformat, $date) = @_;
  2115. my @d = localtime;
  2116. my $mm;
  2117. my $dd;
  2118. my $yy;
  2119. my $rv;
  2120. if (! $date) {
  2121. $dd = $d[3];
  2122. $mm = ++$d[4];
  2123. $yy = substr($d[5],-2);
  2124. $mm = substr("0$mm", -2);
  2125. $dd = substr("0$dd", -2);
  2126. }
  2127. if ($dateformat =~ /^yy/) {
  2128. if ($date) {
  2129. if ($date =~ /\D/) {
  2130. ($yy, $mm, $dd) = split /\D/, $date;
  2131. $mm *= 1;
  2132. $dd *= 1;
  2133. $mm = substr("0$mm", -2);
  2134. $dd = substr("0$dd", -2);
  2135. $yy = substr($yy, -2);
  2136. $rv = "$yy$mm$dd";
  2137. } else {
  2138. $rv = $date;
  2139. }
  2140. } else {
  2141. $rv = "$yy$mm$dd";
  2142. }
  2143. }
  2144. if ($dateformat =~ /^mm/) {
  2145. if ($date) {
  2146. if ($date =~ /\D/) {
  2147. ($mm, $dd, $yy) = split /\D/, $date;
  2148. $mm *= 1;
  2149. $dd *= 1;
  2150. $mm = substr("0$mm", -2);
  2151. $dd = substr("0$dd", -2);
  2152. $yy = substr($yy, -2);
  2153. $rv = "$mm$dd$yy";
  2154. } else {
  2155. $rv = $date;
  2156. }
  2157. } else {
  2158. $rv = "$mm$dd$yy";
  2159. }
  2160. }
  2161. if ($dateformat =~ /^dd/) {
  2162. if ($date) {
  2163. if ($date =~ /\D/) {
  2164. ($dd, $mm, $yy) = split /\D/, $date;
  2165. $mm *= 1;
  2166. $dd *= 1;
  2167. $mm = substr("0$mm", -2);
  2168. $dd = substr("0$dd", -2);
  2169. $yy = substr($yy, -2);
  2170. $rv = "$dd$mm$yy";
  2171. } else {
  2172. $rv = $date;
  2173. }
  2174. } else {
  2175. $rv = "$dd$mm$yy";
  2176. }
  2177. }
  2178. ($rv, $yy, $mm, $dd);
  2179. }
  2180. sub format_date {
  2181. # takes an iso date in, and converts it to the date for printing
  2182. my ($self, $date) = @_;
  2183. my $datestring;
  2184. if ($date =~ /^\d{4}\D/){ # is an ISO date
  2185. $datestring = $self->{db_dateformat};
  2186. my ($yyyy, $mm, $dd) = split(/\W/, $date);
  2187. $datestring =~ s/y+/$yyyy/;
  2188. $datestring =~ s/mm/$mm/;
  2189. $datestring =~ s/dd/$dd/;
  2190. } else { # return date
  2191. $datestring = $date;
  2192. }
  2193. $datestring;
  2194. }
  2195. sub from_to {
  2196. my ($self, $yyyy, $mm, $interval) = @_;
  2197. my @t;
  2198. my $dd = 1;
  2199. my $fromdate = "$yyyy-${mm}-01";
  2200. my $bd = 1;
  2201. if (defined $interval) {
  2202. if ($interval == 12) {
  2203. $yyyy++;
  2204. } else {
  2205. if (($mm += $interval) > 12) {
  2206. $mm -= 12;
  2207. $yyyy++;
  2208. }
  2209. if ($interval == 0) {
  2210. @t = localtime(time);
  2211. $dd = $t[3];
  2212. $mm = $t[4] + 1;
  2213. $yyyy = $t[5] + 1900;
  2214. $bd = 0;
  2215. }
  2216. }
  2217. } else {
  2218. if (++$mm > 12) {
  2219. $mm -= 12;
  2220. $yyyy++;
  2221. }
  2222. }
  2223. $mm--;
  2224. @t = localtime(Time::Local::timelocal(0,0,0,$dd,$mm,$yyyy) - $bd);
  2225. $t[4]++;
  2226. $t[4] = substr("0$t[4]",-2);
  2227. $t[3] = substr("0$t[3]",-2);
  2228. $t[5] += 1900;
  2229. ($self->format_date($fromdate),
  2230. $self->format_date("$t[5]-$t[4]-$t[3]"));
  2231. }
  2232. sub audittrail {
  2233. my ($self, $dbh, $myconfig, $audittrail) = @_;
  2234. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2235. my $query;
  2236. my $rv;
  2237. my $disconnect;
  2238. if (! $dbh) {
  2239. $dbh = $self->{dbh};
  2240. }
  2241. # if we have an id add audittrail, otherwise get a new timestamp
  2242. my @queryargs;
  2243. if ($audittrail->{id}) {
  2244. $query = qq|
  2245. SELECT value FROM defaults
  2246. WHERE setting_key = 'audittrail'|;
  2247. if ($dbh->selectrow_array($query)) {
  2248. my ($null, $employee_id) = $self->get_employee($dbh);
  2249. if ($self->{audittrail} && !$myconfig) {
  2250. chop $self->{audittrail};
  2251. my @a = split /\|/, $self->{audittrail};
  2252. my %newtrail = ();
  2253. my $key;
  2254. my $i;
  2255. my @flds = qw(tablename reference formname action transdate);
  2256. # put into hash and remove dups
  2257. while (@a) {
  2258. $key = "$a[2]$a[3]";
  2259. $i = 0;
  2260. $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
  2261. splice @a, 0, 5;
  2262. }
  2263. $query = qq|
  2264. INSERT INTO audittrail
  2265. (trans_id, tablename, reference,
  2266. formname, action, transdate,
  2267. employee_id)
  2268. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2269. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2270. foreach $key (sort { $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate} } keys %newtrail) {
  2271. $i = 2;
  2272. $sth->bind_param(1, $audittrail->{id});
  2273. for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
  2274. $sth->bind_param($i++, $employee_id);
  2275. $sth->execute || $self->dberror;
  2276. $sth->finish;
  2277. }
  2278. }
  2279. if ($audittrail->{transdate}) {
  2280. $query = qq|
  2281. INSERT INTO audittrail (
  2282. trans_id, tablename, reference,
  2283. formname, action, employee_id,
  2284. transdate)
  2285. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2286. @queryargs = (
  2287. $audittrail->{id},
  2288. $audittrail->{tablename},
  2289. $audittrail->{reference},
  2290. $audittrail->{formname},
  2291. $audittrail->{action},
  2292. $employee_id,
  2293. $audittrail->{transdate}
  2294. );
  2295. } else {
  2296. $query = qq|
  2297. INSERT INTO audittrail
  2298. (trans_id, tablename, reference,
  2299. formname, action, employee_id)
  2300. VALUES (?, ?, ?, ?, ?, ?)|;
  2301. @queryargs = (
  2302. $audittrail->{id},
  2303. $audittrail->{tablename},
  2304. $audittrail->{reference},
  2305. $audittrail->{formname},
  2306. $audittrail->{action},
  2307. $employee_id,
  2308. );
  2309. }
  2310. $sth = $dbh->prepare($query);
  2311. $sth->execute(@queryargs)||$self->dberror($query);
  2312. }
  2313. } else {
  2314. $query = qq|SELECT current_timestamp|;
  2315. my ($timestamp) = $dbh->selectrow_array($query);
  2316. $rv = "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2317. }
  2318. $dbh->commit;
  2319. $rv;
  2320. }
  2321. 1;