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