summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: 94a96dc0792a7cea75c9b95a6940e1c4a258ffad (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. package Form;
  37. sub new {
  38. my $type = shift;
  39. my $self = {};
  40. read(STDIN, $_, $ENV{CONTENT_LENGTH});
  41. if ($ENV{QUERY_STRING}) {
  42. $_ = $ENV{QUERY_STRING};
  43. }
  44. if ($ARGV[0]) {
  45. $_ = $ARGV[0];
  46. }
  47. %$self = split /[&=]/;
  48. for (keys %$self) { $self->{$_} = unescape("", $self->{$_}) }
  49. if (substr($self->{action}, 0, 1) !~ /( |\.)/) {
  50. $self->{action} = lc $self->{action};
  51. $self->{action} =~ s/( |-|,|\#|\/|\.$)/_/g;
  52. }
  53. $self->{menubar} = 1 if $self->{path} =~ /lynx/i;
  54. #menubar will be deprecated, replaced with below
  55. $self->{lynx} = 1 if $self->{path} =~ /lynx/i;
  56. $self->{version} = "1.1.1";
  57. $self->{dbversion} = "2.6.18";
  58. bless $self, $type;
  59. }
  60. sub debug {
  61. my ($self, $file) = @_;
  62. if ($file) {
  63. open(FH, "> $file") or die $!;
  64. for (sort keys %$self) { print FH "$_ = $self->{$_}\n" }
  65. close(FH);
  66. } else {
  67. print "\n";
  68. for (sort keys %$self) { print "$_ = $self->{$_}\n" }
  69. }
  70. }
  71. sub escape {
  72. my ($self, $str, $beenthere) = @_;
  73. # for Apache 2 we escape strings twice
  74. if (($ENV{SERVER_SIGNATURE} =~ /Apache\/2\.(\d+)\.(\d+)/) && !$beenthere) {
  75. $str = $self->escape($str, 1) if $1 == 0 && $2 < 44;
  76. }
  77. $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
  78. $str;
  79. }
  80. sub unescape {
  81. my ($self, $str) = @_;
  82. $str =~ tr/+/ /;
  83. $str =~ s/\\$//;
  84. $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
  85. $str =~ s/\r?\n/\n/g;
  86. $str;
  87. }
  88. sub quote {
  89. my ($self, $str) = @_;
  90. if ($str && ! ref($str)) {
  91. $str =~ s/"/&quot;/g;
  92. }
  93. $str;
  94. }
  95. sub unquote {
  96. my ($self, $str) = @_;
  97. if ($str && ! ref($str)) {
  98. $str =~ s/&quot;/"/g;
  99. }
  100. $str;
  101. }
  102. sub hide_form {
  103. my $self = shift;
  104. if (@_) {
  105. for (@_) {
  106. print qq|<input type="hidden" name="$_" value="|.$self->quote($self->{$_}).qq|" />\n|
  107. }
  108. } else {
  109. delete $self->{header};
  110. for (sort keys %$self) {
  111. print qq|<input type="hidden" name="$_" value="|.$self->quote($self->{$_}).qq|" />\n|
  112. }
  113. }
  114. }
  115. sub error {
  116. my ($self, $msg) = @_;
  117. if ($ENV{HTTP_USER_AGENT}) {
  118. $self->{msg} = $msg;
  119. $self->{format} = "html";
  120. $self->format_string(msg);
  121. delete $self->{pre};
  122. if (!$self->{header}) {
  123. $self->header;
  124. }
  125. print qq|<body><h2 class="error">Error!</h2> <p><b>$self->{msg}</b></body>|;
  126. exit;
  127. } else {
  128. if ($self->{error_function}) {
  129. &{ $self->{error_function} }($msg);
  130. } else {
  131. die "Error: $msg\n";
  132. }
  133. }
  134. }
  135. sub info {
  136. my ($self, $msg) = @_;
  137. if ($ENV{HTTP_USER_AGENT}) {
  138. $msg =~ s/\n/<br>/g;
  139. delete $self->{pre};
  140. if (!$self->{header}) {
  141. $self->header;
  142. print qq| <body>|;
  143. $self->{header} = 1;
  144. }
  145. print "<b>$msg</b>";
  146. } else {
  147. if ($self->{info_function}) {
  148. &{ $self->{info_function} }($msg);
  149. } else {
  150. print "$msg\n";
  151. }
  152. }
  153. }
  154. sub numtextrows {
  155. my ($self, $str, $cols, $maxrows) = @_;
  156. my $rows = 0;
  157. for (split /\n/, $str) {
  158. $rows += int (((length) - 2)/$cols) + 1
  159. }
  160. $maxrows = $rows unless defined $maxrows;
  161. return ($rows > $maxrows) ? $maxrows : $rows;
  162. }
  163. sub dberror {
  164. my ($self, $msg) = @_;
  165. $self->error("$msg\n".$DBI::errstr);
  166. }
  167. sub isblank {
  168. my ($self, $name, $msg) = @_;
  169. $self->error($msg) if $self->{$name} =~ /^\s*$/;
  170. }
  171. sub header {
  172. my ($self, $init, $headeradd) = @_;
  173. return if $self->{header};
  174. my ($stylesheet, $favicon, $charset);
  175. if ($ENV{HTTP_USER_AGENT}) {
  176. if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
  177. $stylesheet = qq|<link rel="stylesheet" href="css/$self->{stylesheet}" type="text/css" title="LedgerSMB stylesheet" />\n|;
  178. }
  179. if ($self->{charset}) {
  180. $charset = qq|<meta http-equiv="content-type" content="text/html; charset=$self->{charset}" />\n|;
  181. }
  182. $self->{titlebar} = ($self->{title}) ? "$self->{title} - $self->{titlebar}" : $self->{titlebar};
  183. $self->set_cookie($init);
  184. print qq|Content-Type: text/html\n\n
  185. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  186. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  187. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  188. <head>
  189. <title>$self->{titlebar}</title>
  190. <meta http-equiv="Pragma" content="no-cache" />
  191. <meta http-equiv="Expires" content="-1" />
  192. <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  193. $stylesheet
  194. $charset
  195. <meta name="robots" content="noindex,nofollow" />
  196. $headeradd
  197. </head>
  198. $self->{pre} \n|;
  199. }
  200. $self->{header} = 1;
  201. }
  202. sub set_cookie {
  203. my ($self, $init) = @_;
  204. $self->{timeout} = ($self->{timeout} > 0) ? $self->{timeout} : 3600;
  205. my $t = ($self->{endsession}) ? time : time + $self->{timeout};
  206. if ($ENV{HTTP_USER_AGENT}) {
  207. my @d = split / +/, scalar gmtime($t);
  208. my $today = "$d[0], $d[2]-$d[1]-$d[4] $d[3] GMT";
  209. if ($init) {
  210. $self->{sessionid} = time;
  211. }
  212. print qq|Set-Cookie: LedgerSMB-$self->{login}=$self->{sessionid}; expires=$today; path=/;\n| if $self->{login};
  213. }
  214. }
  215. sub redirect {
  216. my ($self, $msg) = @_;
  217. if ($self->{callback}) {
  218. my ($script, $argv) = split(/\?/, $self->{callback});
  219. exec ("perl", $script, $argv);
  220. } else {
  221. $self->info($msg);
  222. }
  223. }
  224. sub sort_columns {
  225. my ($self, @columns) = @_;
  226. if ($self->{sort}) {
  227. if (@columns) {
  228. @columns = grep !/^$self->{sort}$/, @columns;
  229. splice @columns, 0, 0, $self->{sort};
  230. }
  231. }
  232. @columns;
  233. }
  234. sub sort_order {
  235. my ($self, $columns, $ordinal) = @_;
  236. # setup direction
  237. if ($self->{direction}) {
  238. if ($self->{sort} eq $self->{oldsort}) {
  239. if ($self->{direction} eq 'ASC') {
  240. $self->{direction} = "DESC";
  241. } else {
  242. $self->{direction} = "ASC";
  243. }
  244. }
  245. } else {
  246. $self->{direction} = "ASC";
  247. }
  248. $self->{oldsort} = $self->{sort};
  249. my @a = $self->sort_columns(@{$columns});
  250. if (%$ordinal) {
  251. $a[0] = ($ordinal->{$a[$_]}) ? "$ordinal->{$a[0]} $self->{direction}" : "$a[0] $self->{direction}";
  252. for (1 .. $#a) {
  253. $a[$_] = $ordinal->{$a[$_]} if $ordinal->{$a[$_]}
  254. }
  255. } else {
  256. $a[0] .= " $self->{direction}";
  257. }
  258. $sortorder = join ',', @a;
  259. $sortorder;
  260. }
  261. sub format_amount {
  262. my ($self, $myconfig, $amount, $places, $dash) = @_;
  263. my $negative = ($amount < 0);
  264. if ($amount){
  265. $amount = $self->parse_amount($myconfig, $amount);
  266. $amount =~ s/-//;
  267. }
  268. if ($places =~ /\d+/) {
  269. #$places = 4 if $places == 2;
  270. $amount = $self->round_amount($amount, $places);
  271. }
  272. # is the amount negative
  273. # Parse $myconfig->{numberformat}
  274. my ($ts, $ds) = ($1, $2);
  275. if ($amount) {
  276. if ($myconfig->{numberformat}) {
  277. my ($whole, $dec) = split /\./, "$amount";
  278. $amount = join '', reverse split //, $whole;
  279. if ($places) {
  280. $dec .= "0" x $places;
  281. $dec = substr($dec, 0, $places);
  282. }
  283. if ($myconfig->{numberformat} eq '1,000.00') {
  284. $amount =~ s/\d{3,}?/$&,/g;
  285. $amount =~ s/,$//;
  286. $amount = join '', reverse split //, $amount;
  287. $amount .= "\.$dec" if ($dec ne "");
  288. }
  289. if ($myconfig->{numberformat} eq '1 000.00') {
  290. $amount =~ s/\d{3,}?/$& /g;
  291. $amount =~ s/\s$//;
  292. $amount = join '', reverse split //, $amount;
  293. $amount .= "\.$dec" if ($dec ne "");
  294. }
  295. if ($myconfig->{numberformat} eq "1'000.00") {
  296. $amount =~ s/\d{3,}?/$&'/g;
  297. $amount =~ s/'$//;
  298. $amount = join '', reverse split //, $amount;
  299. $amount .= "\.$dec" if ($dec ne "");
  300. }
  301. if ($myconfig->{numberformat} eq '1.000,00') {
  302. $amount =~ s/\d{3,}?/$&./g;
  303. $amount =~ s/\.$//;
  304. $amount = join '', reverse split //, $amount;
  305. $amount .= ",$dec" if ($dec ne "");
  306. }
  307. if ($myconfig->{numberformat} eq '1000,00') {
  308. $amount = "$whole";
  309. $amount .= ",$dec" if ($dec ne "");
  310. }
  311. if ($myconfig->{numberformat} eq '1000.00') {
  312. $amount = "$whole";
  313. $amount .= ".$dec" if ($dec ne "");
  314. }
  315. if ($dash =~ /-/) {
  316. $amount = ($negative) ? "($amount)" : "$amount";
  317. } elsif ($dash =~ /DRCR/) {
  318. $amount = ($negative) ? "$amount DR" : "$amount CR";
  319. } else {
  320. $amount = ($negative) ? "-$amount" : "$amount";
  321. }
  322. }
  323. } else {
  324. if ($dash eq "0" && $places) {
  325. if ($myconfig->{numberformat} eq '1.000,00') {
  326. $amount = "0".","."0" x $places;
  327. } else {
  328. $amount = "0"."."."0" x $places;
  329. }
  330. } else {
  331. $amount = ($dash ne "") ? "$dash" : "";
  332. }
  333. }
  334. $amount;
  335. }
  336. sub parse_amount {
  337. my ($self, $myconfig, $amount) = @_;
  338. if (UNIVERSAL::isa($amount, 'Math::BigFloat')){ # Amount may not be an object
  339. return $amount;
  340. }
  341. my $numberformat = $myconfig->{numberformat};
  342. if (($numberformat eq '1.000,00') ||
  343. ($numberformat eq '1000,00')) {
  344. $amount =~ s/\.//g;
  345. $amount =~ s/,/./;
  346. }
  347. if ($numberformat eq '1 000.00'){
  348. $amount =~ s/\s//g;
  349. }
  350. if ($numberformat eq "1'000.00") {
  351. $amount =~ s/'//g;
  352. }
  353. $amount =~ s/,//g;
  354. $amount = new Math::BigFloat($amount);
  355. return ($amount * 1);
  356. }
  357. sub round_amount {
  358. my ($self, $amount, $places) = @_;
  359. # These rounding rules follow from the previous implementation.
  360. # They should be changed to allow different rules for different accounts.
  361. Math::BigFloat->round_mode('+inf') if $amount >= 0;
  362. Math::BigFloat->round_mode('-inf') if $amount < 0;
  363. $amount = Math::BigFloat->new($amount)->ffround(-$places) if $places >= 0;
  364. $amount = Math::BigFloat->new($amount)->ffround(-($places-1)) if $places < 0;
  365. return $amount;
  366. }
  367. sub callproc {
  368. my $procname = shift @_;
  369. my $argstr = "";
  370. my @results;
  371. for (1 .. $#_){
  372. $argstr .= "?, ";
  373. }
  374. $argstr =~ s/\, $//;
  375. $query = "SELECT $procname";
  376. $query =~ s/\(\)/$argstr/;
  377. my $sth = $form->{dbh}->prepare($query);
  378. while (my $ref = $sth->fetchrow_hashref(NAME_lc)){
  379. push @results, $ref;
  380. }
  381. @results;
  382. }
  383. sub get_my_emp_num {
  384. my ($self, $myconfig, $form) = @_;
  385. %myconfig = %{$myconfig};
  386. my $dbh = $form->{dbh};
  387. # we got a connection, check the version
  388. my $query = qq|
  389. SELECT employeenumber FROM employee
  390. WHERE login = ?|;
  391. my $sth = $dbh->prepare($query);
  392. $sth->execute($form->{login}) || $form->dberror($query);
  393. $sth->execute;
  394. my ($id) = $sth->fetchrow_array;
  395. $sth->finish;
  396. $form->{'emp_num'} = $id;
  397. }
  398. sub parse_template {
  399. my ($self, $myconfig, $userspath) = @_;
  400. my ($chars_per_line, $lines_on_first_page, $lines_on_second_page) = (0, 0, 0);
  401. my ($current_page, $current_line) = (1, 1);
  402. my $pagebreak = "";
  403. my $sum = 0;
  404. my $subdir = "";
  405. my $err = "";
  406. my %include = ();
  407. my $ok;
  408. if ($self->{language_code}) {
  409. if (-f "$self->{templates}/$self->{language_code}/$self->{IN}") {
  410. open(IN, "$self->{templates}/$self->{language_code}/$self->{IN}") or $self->error("$self->{IN} : $!");
  411. } else {
  412. open(IN, "$self->{templates}/$self->{IN}") or $self->error("$self->{IN} : $!");
  413. }
  414. } else {
  415. open(IN, "$self->{templates}/$self->{IN}") or $self->error("$self->{IN} : $!");
  416. }
  417. @_ = <IN>;
  418. close(IN);
  419. $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
  420. # OUT is used for the media, screen, printer, email
  421. # for postscript we store a copy in a temporary file
  422. my $fileid = time;
  423. my $tmpfile = $self->{IN};
  424. $tmpfile =~ s/\./_$self->{fileid}./ if $self->{fileid};
  425. $self->{tmpfile} = "$userspath/${fileid}_${tmpfile}";
  426. if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
  427. $out = $self->{OUT};
  428. $self->{OUT} = ">$self->{tmpfile}";
  429. }
  430. if ($self->{OUT}) {
  431. open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
  432. } else {
  433. open(OUT, ">-") or $self->error("STDOUT : $!");
  434. $self->header;
  435. }
  436. # first we generate a tmpfile
  437. # read file and replace <?lsmb variable ?>
  438. while ($_ = shift) {
  439. $par = "";
  440. $var = $_;
  441. # detect pagebreak block and its parameters
  442. if (/<\?lsmb pagebreak ([0-9]+) ([0-9]+) ([0-9]+) \?>/) {
  443. $chars_per_line = $1;
  444. $lines_on_first_page = $2;
  445. $lines_on_second_page = $3;
  446. while ($_ = shift) {
  447. last if (/<\?lsmb end pagebreak \?>/);
  448. $pagebreak .= $_;
  449. }
  450. }
  451. if (/<\?lsmb foreach /) {
  452. # this one we need for the count
  453. chomp $var;
  454. $var =~ s/.*?<\?lsmb foreach (.+?) \?>/$1/;
  455. while ($_ = shift) {
  456. last if (/<\?lsmb end $var \?>/);
  457. # store line in $par
  458. $par .= $_;
  459. }
  460. # display contents of $self->{number}[] array
  461. for $i (0 .. $#{ $self->{$var} }) {
  462. if ($var =~ /^(part|service)$/) {
  463. next if $self->{$var}[$i] eq 'NULL';
  464. }
  465. # Try to detect whether a manual page break is necessary
  466. # but only if there was a <?lsmb pagebreak ... ?> block before
  467. if ($var eq 'number' || $var eq 'part' || $var eq 'service') {
  468. if ($chars_per_line && defined $self->{$var}) {
  469. my $line;
  470. my $lines = 0;
  471. my @d = (description);
  472. push @d, "itemnotes" if $self->{countitemnotes};
  473. foreach my $item (@d) {
  474. if ($self->{$item}[$i]) {
  475. foreach $line (split /\r?\n/, $self->{$item}[$i]) {
  476. $lines++;
  477. $lines += int(length($line) / $chars_per_line);
  478. }
  479. }
  480. }
  481. my $lpp;
  482. if ($current_page == 1) {
  483. $lpp = $lines_on_first_page;
  484. } else {
  485. $lpp = $lines_on_second_page;
  486. }
  487. # Yes we need a manual page break
  488. if (($current_line + $lines) > $lpp) {
  489. my $pb = $pagebreak;
  490. # replace the special variables <?lsmb sumcarriedforward ?>
  491. # and <?lsmb lastpage ?>
  492. my $psum = $self->format_amount($myconfig, $sum, 2);
  493. $pb =~ s/<\?lsmb sumcarriedforward \?>/$psum/g;
  494. $pb =~ s/<\?lsmb lastpage \?>/$current_page/g;
  495. # only "normal" variables are supported here
  496. # (no <?lsmb if, no <?lsmb foreach, no <?lsmb include)
  497. $pb =~ s/<\?lsmb (.+?) \?>/$self->{$1}/g;
  498. # page break block is ready to rock
  499. print(OUT $pb);
  500. $current_page++;
  501. $current_line = 1;
  502. $lines = 0;
  503. }
  504. $current_line += $lines;
  505. }
  506. $sum += $self->parse_amount($myconfig, $self->{linetotal}[$i]);
  507. }
  508. # don't parse par, we need it for each line
  509. print OUT $self->format_line($par, $i);
  510. }
  511. next;
  512. }
  513. # if not comes before if!
  514. if (/<\?lsmb if not /) {
  515. # check if it is not set and display
  516. chop;
  517. s/.*?<\?lsmb if not (.+?) \?>/$1/;
  518. if (! $self->{$_}) {
  519. while ($_ = shift) {
  520. last if (/<\?lsmb end /);
  521. # store line in $par
  522. $par .= $_;
  523. }
  524. $_ = $par;
  525. } else {
  526. while ($_ = shift) {
  527. last if (/<\?lsmb end /);
  528. }
  529. next;
  530. }
  531. }
  532. if (/<\? lsmb if /) {
  533. # check if it is set and display
  534. chop;
  535. s/.*?<\?lsmb if (.+?) \?>/$1/;
  536. if (/\s/) {
  537. @a = split;
  538. $ok = eval "$self->{$a[0]} $a[1] $a[2]";
  539. } else {
  540. $ok = $self->{$_};
  541. }
  542. if ($ok) {
  543. while ($_ = shift) {
  544. last if (/<\?lsmb end /);
  545. # store line in $par
  546. $par .= $_;
  547. }
  548. $_ = $par;
  549. } else {
  550. while ($_ = shift) {
  551. last if (/<\?lsmb end /);
  552. }
  553. next;
  554. }
  555. }
  556. # check for <?lsmb include filename ?>
  557. if (/<\?lsmb include /) {
  558. # get the filename
  559. chomp $var;
  560. $var =~ s/.*?<\?lsmb include (.+?) \?>/$1/;
  561. # remove / .. for security reasons
  562. $var =~ s/(\/|\.\.)//g;
  563. # assume loop after 10 includes of the same file
  564. next if ($include{$var} > 10);
  565. unless (open(INC, "$self->{templates}/$self->{language_code}/$var")) {
  566. $err = $!;
  567. $self->cleanup;
  568. $self->error("$self->{templates}/$self->{language_code}/$var : $err");
  569. }
  570. unshift(@_, <INC>);
  571. close(INC);
  572. $include{$var}++;
  573. next;
  574. }
  575. print OUT $self->format_line($_);
  576. }
  577. close(OUT);
  578. delete $self->{countitemnotes};
  579. # Convert the tex file to postscript
  580. if ($self->{format} =~ /(postscript|pdf)/) {
  581. use Cwd;
  582. $self->{cwd} = cwd();
  583. $self->{tmpdir} = "$self->{cwd}/$userspath";
  584. unless (chdir("$userspath")) {
  585. $err = $!;
  586. $self->cleanup;
  587. $self->error("chdir : $err");
  588. }
  589. $self->{tmpfile} =~ s/$userspath\///g;
  590. $self->{errfile} = $self->{tmpfile};
  591. $self->{errfile} =~ s/tex$/err/;
  592. my $r = 1;
  593. if ($self->{format} eq 'postscript') {
  594. system("latex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  595. while ($self->rerun_latex) {
  596. system("latex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  597. last if ++$r > 4;
  598. }
  599. $self->{tmpfile} =~ s/tex$/dvi/;
  600. $self->error($self->cleanup) if ! (-f $self->{tmpfile});
  601. system("dvips $self->{tmpfile} -o -q");
  602. $self->error($self->cleanup."dvips : $!") if ($?);
  603. $self->{tmpfile} =~ s/dvi$/ps/;
  604. }
  605. if ($self->{format} eq 'pdf') {
  606. system("pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  607. while ($self->rerun_latex) {
  608. system("pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  609. last if ++$r > 4;
  610. }
  611. $self->{tmpfile} =~ s/tex$/pdf/;
  612. $self->error($self->cleanup) if ! (-f $self->{tmpfile});
  613. }
  614. }
  615. if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
  616. if ($self->{media} eq 'email') {
  617. use LedgerSMB::Mailer;
  618. my $mail = new Mailer;
  619. for (qw(cc bcc subject message version format charset)) {
  620. $mail->{$_} = $self->{$_}
  621. }
  622. $mail->{to} = qq|$self->{email}|;
  623. $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
  624. $mail->{fileid} = "$fileid.";
  625. # if we send html or plain text inline
  626. if (($self->{format} =~ /(html|txt)/) &&
  627. ($self->{sendmode} eq 'inline')) {
  628. my $br = "";
  629. $br = "<br>" if $self->{format} eq 'html';
  630. $mail->{contenttype} = "text/$self->{format}";
  631. $mail->{message} =~ s/\r?\n/$br\n/g;
  632. $myconfig->{signature} =~ s/\\n/$br\n/g;
  633. $mail->{message} .= "$br\n-- $br\n$myconfig->{signature}\n$br" if $myconfig->{signature};
  634. unless (open(IN, $self->{tmpfile})) {
  635. $err = $!;
  636. $self->cleanup;
  637. $self->error("$self->{tmpfile} : $err");
  638. }
  639. while (<IN>) {
  640. $mail->{message} .= $_;
  641. }
  642. close(IN);
  643. } else {
  644. @{ $mail->{attachments} } = ($self->{tmpfile});
  645. $myconfig->{signature} =~ s/\\n/\n/g;
  646. $mail->{message} .= "\n-- \n$myconfig->{signature}" if $myconfig->{signature};
  647. }
  648. if ($err = $mail->send($out)) {
  649. $self->cleanup;
  650. $self->error($err);
  651. }
  652. } else {
  653. $self->{OUT} = $out;
  654. unless (open(IN, $self->{tmpfile})) {
  655. $err = $!;
  656. $self->cleanup;
  657. $self->error("$self->{tmpfile} : $err");
  658. }
  659. binmode(IN);
  660. $self->{copies} = 1 if $self->{media} =~ /(screen|email|queue)/;
  661. chdir("$self->{cwd}");
  662. for my $i (1 .. $self->{copies}) {
  663. if ($self->{OUT}) {
  664. unless (open(OUT, $self->{OUT})) {
  665. $err = $!;
  666. $self->cleanup;
  667. $self->error("$self->{OUT} : $err");
  668. }
  669. } else {
  670. # launch application
  671. print qq|Content-Type: application/$self->{format}\n|.
  672. qq|Content-Disposition: attachment; filename="$self->{tmpfile}"\n\n|;
  673. unless (open(OUT, ">-")) {
  674. $err = $!;
  675. $self->cleanup;
  676. $self->error("STDOUT : $err");
  677. }
  678. }
  679. binmode(OUT);
  680. while (<IN>) {
  681. print OUT $_;
  682. }
  683. close(OUT);
  684. seek IN, 0, 0;
  685. }
  686. close(IN);
  687. }
  688. $self->cleanup;
  689. }
  690. }
  691. sub format_line {
  692. my $self = shift;
  693. $_ = shift;
  694. my $i = shift;
  695. my $str;
  696. my $newstr;
  697. my $pos;
  698. my $l;
  699. my $lf;
  700. my $line;
  701. my $var = "";
  702. my %a;
  703. my $offset;
  704. my $pad;
  705. my $item;
  706. while (/<\?lsmb (.+?) \?>/) {
  707. %a = ();
  708. foreach $item (split / /, $1) {
  709. my ($key, $value) = split /=/, $item;
  710. if ($value ne "") {
  711. $a{$key} = $value;
  712. } else {
  713. $var = $item;
  714. }
  715. }
  716. $str = (defined $i) ? $self->{$var}[$i] : $self->{$var};
  717. $newstr = $str;
  718. $self->{countitemnotes} = 1 if $var eq 'itemnotes';
  719. $var = $1;
  720. if ($var =~ /^if\s+not\s+/) {
  721. if ($str) {
  722. $var =~ s/if\s+not\s+//;
  723. s/<\?lsmb if\s+not\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  724. } else {
  725. s/<\?lsmb $var \?>//;
  726. }
  727. next;
  728. }
  729. if ($var =~ /^if\s+/) {
  730. if ($str) {
  731. s/<\?lsmb $var \?>//;
  732. } else {
  733. $var =~ s/if\s+//;
  734. s/<\?lsmb if\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  735. }
  736. next;
  737. }
  738. if ($var =~ /^end\s+/) {
  739. s/<\?lsmb $var \?>//;
  740. next;
  741. }
  742. if ($a{align} || $a{width} || $a{offset}) {
  743. $newstr = "";
  744. $offset = 0;
  745. $lf = "";
  746. foreach $str (split /\n/, $str) {
  747. $line = $str;
  748. $l = length $str;
  749. do {
  750. if (($pos = length $str) > $a{width}) {
  751. if (($pos = rindex $str, " ", $a{width}) > 0) {
  752. $line = substr($str, 0, $pos);
  753. }
  754. $pos = length $str if $pos == -1;
  755. }
  756. $l = length $line;
  757. # pad left, right or center
  758. $l = ($a{width} - $l);
  759. $pad = " " x $l;
  760. if ($a{align} =~ /right/i) {
  761. $line = " " x $offset . $pad . $line;
  762. }
  763. if ($a{align} =~ /left/i) {
  764. $line = " " x $offset . $line . $pad;
  765. }
  766. if ($a{align} =~ /center/i) {
  767. $pad = " " x ($l/2);
  768. $line = " " x $offset . $pad . $line;
  769. $pad = " " x ($l/2);
  770. $line .= $pad;
  771. }
  772. $newstr .= "$lf$line";
  773. $str = substr($str, $pos + 1);
  774. $line = $str;
  775. $lf = "\n";
  776. $offset = $a{offset};
  777. } while ($str);
  778. }
  779. }
  780. s/<\?lsmb (.+?) \?>/$newstr/;
  781. }
  782. $_;
  783. }
  784. sub cleanup {
  785. my $self = shift;
  786. chdir("$self->{tmpdir}");
  787. my @err = ();
  788. if (-f "$self->{errfile}") {
  789. open(FH, "$self->{errfile}");
  790. @err = <FH>;
  791. close(FH);
  792. }
  793. if ($self->{tmpfile}) {
  794. # strip extension
  795. $self->{tmpfile} =~ s/\.\w+$//g;
  796. my $tmpfile = $self->{tmpfile};
  797. unlink(<$tmpfile.*>);
  798. }
  799. chdir("$self->{cwd}");
  800. "@err";
  801. }
  802. sub rerun_latex {
  803. my $self = shift;
  804. my $a = 0;
  805. if (-f "$self->{errfile}") {
  806. open(FH, "$self->{errfile}");
  807. $a = grep /(longtable Warning:|Warning:.*?LastPage)/, <FH>;
  808. close(FH);
  809. }
  810. $a;
  811. }
  812. sub format_string {
  813. my ($self, @fields) = @_;
  814. my $format = $self->{format};
  815. if ($self->{format} =~ /(postscript|pdf)/) {
  816. $format = 'tex';
  817. }
  818. my %replace = (
  819. 'order' => {
  820. html => [ '<', '>', '\n', '\r' ],
  821. txt => [ '\n', '\r' ],
  822. tex => [ quotemeta('\\'), '&', '\n','\r',
  823. '\$', '%', '_', '#',
  824. quotemeta('^'), '{', '}', '<', '>', '£'
  825. ] },
  826. html => { '<' => '&lt;', '>' => '&gt;','\n' => '<br />',
  827. '\r' => '<br />' },
  828. txt => { '\n' => "\n", '\r' => "\r" },
  829. tex => {'&' => '\&', '$' => '\$', '%' => '\%', '_' => '\_',
  830. '#' => '\#', quotemeta('^') => '\^\\', '{' => '\{',
  831. '}' => '\}', '<' => '$<$', '>' => '$>$',
  832. '\n' => '\newline ', '\r' => '\newline ',
  833. '£' => '\pounds ', quotemeta('\\') => '/'}
  834. );
  835. my $key;
  836. foreach $key (@{ $replace{order}{$format} }) {
  837. for (@fields) { $self->{$_} =~ s/$key/$replace{$format}{$key}/g }
  838. }
  839. }
  840. sub datetonum {
  841. my ($self, $myconfig, $date, $picture) = @_;
  842. if ($date && $date =~ /\D/) {
  843. if ($myconfig->{dateformat} =~ /^yy/) {
  844. ($yy, $mm, $dd) = split /\D/, $date;
  845. }
  846. if ($myconfig->{dateformat} =~ /^mm/) {
  847. ($mm, $dd, $yy) = split /\D/, $date;
  848. }
  849. if ($myconfig->{dateformat} =~ /^dd/) {
  850. ($dd, $mm, $yy) = split /\D/, $date;
  851. }
  852. $dd *= 1;
  853. $mm *= 1;
  854. $yy += 2000 if length $yy == 2;
  855. $dd = substr("0$dd", -2);
  856. $mm = substr("0$mm", -2);
  857. $date = "$yy$mm$dd";
  858. }
  859. $date;
  860. }
  861. sub add_date {
  862. my ($self, $myconfig, $date, $repeat, $unit) = @_;
  863. use Time::Local;
  864. my $diff = 0;
  865. my $spc = $myconfig->{dateformat};
  866. $spc =~ s/\w//g;
  867. $spc = substr($spc, 0, 1);
  868. if ($date) {
  869. if ($date =~ /\D/) {
  870. if ($myconfig->{dateformat} =~ /^yy/) {
  871. ($yy, $mm, $dd) = split /\D/, $date;
  872. }
  873. if ($myconfig->{dateformat} =~ /^mm/) {
  874. ($mm, $dd, $yy) = split /\D/, $date;
  875. }
  876. if ($myconfig->{dateformat} =~ /^dd/) {
  877. ($dd, $mm, $yy) = split /\D/, $date;
  878. }
  879. } else {
  880. # ISO
  881. ($yy, $mm, $dd) =~ /(....)(..)(..)/;
  882. }
  883. if ($unit eq 'days') {
  884. $diff = $repeat * 86400;
  885. }
  886. if ($unit eq 'weeks') {
  887. $diff = $repeat * 604800;
  888. }
  889. if ($unit eq 'months') {
  890. $diff = $mm + $repeat;
  891. my $whole = int($diff / 12);
  892. $yy += $whole;
  893. $mm = ($diff % 12) + 1;
  894. $diff = 0;
  895. }
  896. if ($unit eq 'years') {
  897. $yy++;
  898. }
  899. $mm--;
  900. @t = localtime(timelocal(0,0,0,$dd,$mm,$yy) + $diff);
  901. $t[4]++;
  902. $mm = substr("0$t[4]",-2);
  903. $dd = substr("0$t[3]",-2);
  904. $yy = $t[5] + 1900;
  905. if ($date =~ /\D/) {
  906. if ($myconfig->{dateformat} =~ /^yy/) {
  907. $date = "$yy$spc$mm$spc$dd";
  908. }
  909. if ($myconfig->{dateformat} =~ /^mm/) {
  910. $date = "$mm$spc$dd$spc$yy";
  911. }
  912. if ($myconfig->{dateformat} =~ /^dd/) {
  913. $date = "$dd$spc$mm$spc$yy";
  914. }
  915. } else {
  916. $date = "$yy$mm$dd";
  917. }
  918. }
  919. $date;
  920. }
  921. sub print_button {
  922. my ($self, $button, $name) = @_;
  923. print qq|<input class="submit" type="submit" name="action" value="$button->{$name}{value}" accesskey="$button->{$name}{key}" title="$button->{$name}{value} [Alt-$button->{$name}{key}]" />\n|;
  924. }
  925. # Database routines used throughout
  926. sub db_init {
  927. my ($self, $myconfig) = @_;
  928. $self->{dbh} = $self->dbconnect_noauto($myconfig) || $self->dberror();
  929. my $query =
  930. "SELECT t.extends,
  931. coalesce (t.table_name, 'custom_' || extends)
  932. || ':' || f.field_name as field_def
  933. FROM custom_table_catalog t
  934. JOIN custom_field_catalog f USING (table_id)";
  935. my $sth = $self->{dbh}->prepare($query);
  936. $sth->execute;
  937. my $ref;
  938. while ($ref = $sth->fetchrow_hashref(NAME_lc)){
  939. push @{$self->{custom_db_fields}{$ref->{extends}}},
  940. $ref->{field_def};
  941. }
  942. }
  943. sub run_custom_queries {
  944. my ($self, $tablename, $query_type, $linenum) = @_;
  945. my $dbh = $self->{dbh};
  946. if ($query_type !~ /^(select|insert|update)$/i){
  947. $self->error($locale->text(
  948. "Passed incorrect query type to get_cutstom_queries."
  949. ));
  950. }
  951. my @rc;
  952. my %temphash;
  953. my @templist;
  954. my @elements;
  955. my $query;
  956. my $ins_values;
  957. if ($linenum){
  958. $linenum = "_$linenum";
  959. }
  960. $query_type = uc($query_type);
  961. for (@{$self->{custom_db_fields}{$tablename}}){
  962. @elements = split (/:/, $_);
  963. push @{$temphash{$elements[0]}}, $elements[1];
  964. }
  965. for (keys %temphash){
  966. my @data;
  967. my $ins_values;
  968. $query = "$query_type ";
  969. if ($query_type eq 'UPDATE'){
  970. $query = "DELETE FROM $_ WHERE row_id = ?";
  971. my $sth = $dbh->prepare($query);
  972. $sth->execute->($form->{"id"."$linenum"})
  973. || $self->dberror($query);
  974. } elsif ($query_type eq 'INSERT'){
  975. $query .= " INTO $_ (";
  976. }
  977. my $first = 1;
  978. for (@{$temphash{$_}}){
  979. $query .= "$_";
  980. if ($query_type eq 'UPDATE'){
  981. $query .= '= ?';
  982. }
  983. $ins_values .= "?, ";
  984. $query .= ", ";
  985. $first = 0;
  986. if ($query_type eq 'UPDATE' or $query_type eq 'INSERT'){
  987. push @data, $self->{"$_$linenum"};
  988. }
  989. }
  990. if ($query_type ne 'INSERT'){
  991. $query =~ s/, $//;
  992. }
  993. if ($query_type eq 'SELECT'){
  994. $query .= " FROM $_";
  995. }
  996. if ($query_type eq 'SELECT' or $query_type eq 'UPDATE'){
  997. $query .= " WHERE row_id = ?";
  998. }
  999. if ($query_type eq 'INSERT'){
  1000. $query .= " row_id) VALUES ($ins_values ?)";
  1001. }
  1002. if ($query_type eq 'SELECT'){
  1003. push @rc, [ $query ];
  1004. } else {
  1005. unshift (@data, $query);
  1006. push @rc, [ @data ];
  1007. }
  1008. }
  1009. if ($query_type eq 'INSERT'){
  1010. for (@rc){
  1011. $query = shift (@{$_});
  1012. $sth = $dbh->prepare($query)
  1013. || $form->db_error($query);
  1014. $sth->execute(@{$_}, $form->{id})
  1015. || $form->dberror($query);;
  1016. $sth->finish;
  1017. $did_insert = 1;
  1018. }
  1019. } elsif ($query_type eq 'UPDATE'){
  1020. @rc = $self->run_custom_queries(
  1021. $tablename, 'INSERT', $linenum);
  1022. } elsif ($query_type eq 'SELECT'){
  1023. for (@rc){
  1024. $query = shift @{$_};
  1025. $sth = $self->{dbh}->prepare($query);
  1026. $sth->execute($form->{id});
  1027. $ref = $sth->fetchrow_hashref(NAME_lc);
  1028. for (keys %{$ref}){
  1029. $form->{$_} = $ref->{$_};
  1030. }
  1031. }
  1032. }
  1033. @rc;
  1034. }
  1035. sub dbconnect {
  1036. my ($self, $myconfig) = @_;
  1037. # connect to database
  1038. my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}) or $self->dberror;
  1039. # set db options
  1040. if ($myconfig->{dboptions}) {
  1041. $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
  1042. }
  1043. $dbh;
  1044. }
  1045. sub dbconnect_noauto {
  1046. my ($self, $myconfig) = @_;
  1047. # connect to database
  1048. $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, {AutoCommit => 0}) or $self->dberror;
  1049. # set db options
  1050. if ($myconfig->{dboptions}) {
  1051. $dbh->do($myconfig->{dboptions});
  1052. }
  1053. $dbh;
  1054. }
  1055. sub dbquote {
  1056. my ($self, $var) = @_;
  1057. if ($var eq ''){
  1058. $_ = "NULL";
  1059. } else {
  1060. $_ = $self->{dbh}->quote($var);
  1061. }
  1062. $_;
  1063. }
  1064. sub update_balance {
  1065. my ($self, $dbh, $table, $field, $where, $value) = @_;
  1066. # if we have a value, go do it
  1067. if ($value) {
  1068. # retrieve balance from table
  1069. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  1070. my ($balance) = $dbh->selectrow_array($query);
  1071. $balance += $value;
  1072. # update balance
  1073. $query = "UPDATE $table SET $field = $balance WHERE $where";
  1074. $dbh->do($query) || $self->dberror($query);
  1075. }
  1076. }
  1077. sub update_exchangerate {
  1078. my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
  1079. # some sanity check for currency
  1080. return if ($curr eq "");
  1081. my $query = qq|
  1082. SELECT curr
  1083. FROM exchangerate
  1084. WHERE curr = ?
  1085. AND transdate = ?
  1086. FOR UPDATE|;
  1087. my $sth = $self->{dbh}->prepare($query);
  1088. $sth->execute($curr, $transdate) || $self->dberror($query);
  1089. my $set;
  1090. my @queryargs;
  1091. if ($buy && $sell) {
  1092. $set = "buy = ?, sell = ?";
  1093. @queryargs = ($buy, $sell);
  1094. } elsif ($buy) {
  1095. $set = "buy = ?";
  1096. @queryargs = ($buy);
  1097. } elsif ($sell) {
  1098. $set = "sell = ?";
  1099. @queryargs = ($sell);
  1100. }
  1101. if ($sth->fetchrow_array) {
  1102. $query = qq|UPDATE exchangerate
  1103. SET $set
  1104. WHERE curr = ?
  1105. AND transdate = ?|;
  1106. push (@queryargs, $curr, $transdate);
  1107. } else {
  1108. $query = qq|
  1109. INSERT INTO exchangerate (
  1110. curr, buy, sell, transdate)
  1111. VALUES (?, ?, ?, ?)|;
  1112. @queryargs = ($curr, $buy, $sell, $transdate);
  1113. }
  1114. $sth->finish;
  1115. $sth = $self->{dbh}->prepare($query);
  1116. $sth->execute(@queryargs) || $self->dberror($query);
  1117. }
  1118. sub save_exchangerate {
  1119. my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
  1120. my ($buy, $sell) = (0, 0);
  1121. $buy = $rate if $fld eq 'buy';
  1122. $sell = $rate if $fld eq 'sell';
  1123. $self->update_exchangerate(
  1124. $self->{dbh},
  1125. $currency,
  1126. $transdate,
  1127. $buy,
  1128. $sell);
  1129. $dbh->commit;
  1130. }
  1131. sub get_exchangerate {
  1132. my ($self, $dbh, $curr, $transdate, $fld) = @_;
  1133. my $exchangerate = 1;
  1134. if ($transdate) {
  1135. my $query = qq|
  1136. SELECT $fld FROM exchangerate
  1137. WHERE curr = ? AND transdate = ?|;
  1138. $sth = $self->{dbh}->prepare($query);
  1139. $sth->execute($curr, $transdate);
  1140. ($exchangerate) = $sth->fetchrow_array;
  1141. }
  1142. $exchangerate;
  1143. $sth->finish;
  1144. $self->{dbh}->commit;
  1145. }
  1146. sub check_exchangerate {
  1147. my ($self, $myconfig, $currency, $transdate, $fld) = @_;
  1148. return "" unless $transdate;
  1149. my $query = qq|
  1150. SELECT $fld
  1151. FROM exchangerate
  1152. WHERE curr = ? AND transdate = ?|;
  1153. my $sth = $self->{dbh}->prepare($query);
  1154. $sth->execute($currenct, $transdate);
  1155. my ($exchangerate) = $sth->fetchrow_array;
  1156. $sth->finish;
  1157. $self->{dbh}->commit;
  1158. $exchangerate;
  1159. }
  1160. sub add_shipto {
  1161. my ($self, $dbh, $id) = @_;
  1162. my $shipto;
  1163. foreach my $item (qw(name address1 address2 city state
  1164. zipcode country contact phone fax email)) {
  1165. if ($self->{"shipto$item"} ne "") {
  1166. $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
  1167. }
  1168. }
  1169. if ($shipto) {
  1170. my $query = qq|
  1171. INSERT INTO shipto
  1172. (trans_id, shiptoname, shiptoaddress1,
  1173. shiptoaddress2, shiptocity, shiptostate,
  1174. shiptozipcode, shiptocountry, shiptocontact,
  1175. shiptophone, shiptofax, shiptoemail)
  1176. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1177. |;
  1178. $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  1179. $sth->execute(
  1180. $id, $self->{shiptoname}, $self->{shiptoaddress1},
  1181. $self->{shiptoaddress2}, $self->{shiptocity},
  1182. $self->{shiptostate}, $self->{shiptostate},
  1183. $self->{shiptozipcode}, $self->{shiptocountry},
  1184. $self->{shiptocontact}, $self->{shiptophone},
  1185. $self->{shiptofax}, $self->{shiptoemail}
  1186. ) || $self->dberror($query);
  1187. $sth->finish;
  1188. $self->{dbh}->commit;
  1189. }
  1190. }
  1191. sub get_employee {
  1192. my ($self, $dbh) = @_;
  1193. my $login = $self->{login};
  1194. $login =~ s/@.*//;
  1195. my $query = qq|SELECT name, id
  1196. FROM employee
  1197. WHERE login = ?|;
  1198. $sth = $self->{dbh}->prepare($query);
  1199. $sth->execute($login);
  1200. my (@a) = $sth->fetchrow_array();
  1201. $a[1] *= 1;
  1202. $sth->finish;
  1203. $self->{dbh}->commit;
  1204. @a;
  1205. }
  1206. # this sub gets the id and name from $table
  1207. sub get_name {
  1208. my ($self, $myconfig, $table, $transdate) = @_;
  1209. # connect to database
  1210. my @queryargs;
  1211. my $where;
  1212. if ($transdate) {
  1213. $where = qq|
  1214. AND (startdate IS NULL OR startdate <= ?)
  1215. AND (enddate IS NULL OR enddate >= ?)|;
  1216. @queryargs = ($transdate, $transdate);
  1217. }
  1218. my $name = $self->like(lc $self->{$table});
  1219. my $query = qq|
  1220. SELECT * FROM $table
  1221. WHERE (lower(name) LIKE ? OR ${table}number LIKE ?)
  1222. $where
  1223. ORDER BY name|;
  1224. unshift(@queryargs, $name, $name);
  1225. my $sth = $self->{dbh}->prepare($query);
  1226. $sth->execute(@queryargs) || $self->dberror($query);
  1227. my $i = 0;
  1228. @{ $self->{name_list} } = ();
  1229. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1230. push(@{ $self->{name_list} }, $ref);
  1231. $i++;
  1232. }
  1233. $sth->finish;
  1234. $self->{dbh}->commit;
  1235. $i;
  1236. }
  1237. sub all_vc {
  1238. my ($self, $myconfig, $vc, $module, $dbh, $transdate, $job) = @_;
  1239. my $ref;
  1240. my $disconnect = 0;
  1241. $dbh = $self->{dbh};
  1242. my $sth;
  1243. my $query = qq|SELECT count(*) FROM $vc|;
  1244. my $where;
  1245. my @ueryargs = ();
  1246. if ($transdate) {
  1247. $query .= qq| WHERE (startdate IS NULL OR startdate <= ?)
  1248. AND (enddate IS NULL OR enddate >= ?)|;
  1249. @queryargs = ($transdate, $transdate);
  1250. }
  1251. $sth = $dbh->prepare($query);
  1252. $sth->execute(@queryargs);
  1253. my ($count) = $sth->fetchrow_array;
  1254. $sth->finish;
  1255. @queryargs = ();
  1256. # build selection list
  1257. if ($count < $myconfig->{vclimit}) {
  1258. $self->{"${vc}_id"} *= 1;
  1259. $query = qq|SELECT id, name
  1260. FROM $vc
  1261. WHERE 1=1
  1262. $where
  1263. UNION
  1264. SELECT id,name
  1265. FROM $vc
  1266. WHERE id = ?
  1267. ORDER BY name|;
  1268. push(@queryargs, $self->{"${vc}_id"});
  1269. $sth = $dbh->prepare($query);
  1270. $sth->execute(@queryargs) || $self->dberror($query);
  1271. @{ $self->{"all_$vc"} } = ();
  1272. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1273. push @{ $self->{"all_$vc"} }, $ref;
  1274. }
  1275. $sth->finish;
  1276. }
  1277. # get self
  1278. if (! $self->{employee_id}) {
  1279. ($self->{employee}, $self->{employee_id}) = split /--/, $self->{employee};
  1280. ($self->{employee}, $self->{employee_id}) = $self->get_employee($dbh) unless $self->{employee_id};
  1281. }
  1282. $self->all_employees($myconfig, $dbh, $transdate, 1);
  1283. $self->all_departments($myconfig, $dbh, $vc);
  1284. $self->all_projects($myconfig, $dbh, $transdate, $job);
  1285. # get language codes
  1286. $query = qq|SELECT *
  1287. FROM language
  1288. ORDER BY 2|;
  1289. $sth = $dbh->prepare($query);
  1290. $sth->execute || $self->dberror($query);
  1291. $self->{all_language} = ();
  1292. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1293. push @{ $self->{all_language} }, $ref;
  1294. }
  1295. $sth->finish;
  1296. $self->all_taxaccounts($myconfig, $dbh, $transdate);
  1297. $self->{dbh}->commit;
  1298. }
  1299. sub all_taxaccounts {
  1300. my ($self, $myconfig, $dbh2, $transdate) = @_;
  1301. my $disconnect = ($dbh) ? 0 : 1;
  1302. my $dbh = $self->{dbh};
  1303. my $sth;
  1304. my $query;
  1305. my $where;
  1306. my @queryargs = ();
  1307. if ($transdate) {
  1308. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1309. push(@queryargs, $transdate);
  1310. }
  1311. if ($self->{taxaccounts}) {
  1312. # rebuild tax rates
  1313. $query = qq|SELECT t.rate, t.taxnumber
  1314. FROM tax t
  1315. JOIN chart c ON (c.id = t.chart_id)
  1316. WHERE c.accno = ?
  1317. $where
  1318. ORDER BY accno, validto|;
  1319. $sth = $dbh->prepare($query) || $self->dberror($query);
  1320. foreach my $accno (split / /, $self->{taxaccounts}) {
  1321. $sth->execute(@queryargs, $accno);
  1322. ($self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"}) = $sth->fetchrow_array;
  1323. $sth->finish;
  1324. }
  1325. }
  1326. $self->{dbh}->commit;
  1327. }
  1328. sub all_employees {
  1329. my ($self, $myconfig, $dbh2, $transdate, $sales) = @_;
  1330. my $dbh = $self->{dbh};
  1331. my @whereargs = ();
  1332. # setup employees/sales contacts
  1333. my $query = qq|SELECT id, name
  1334. FROM employee
  1335. WHERE 1 = 1|;
  1336. if ($transdate) {
  1337. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1338. AND (enddate IS NULL OR enddate >= ?)|;
  1339. @whereargs = ($transdate, $transdate);
  1340. } else {
  1341. $query .= qq| AND enddate IS NULL|;
  1342. }
  1343. if ($sales) {
  1344. $query .= qq| AND sales = '1'|;
  1345. }
  1346. $query .= qq| ORDER BY name|;
  1347. my $sth = $dbh->prepare($query);
  1348. $sth->execute(@whereargs) || $self->dberror($query);
  1349. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1350. push @{ $self->{all_employee} }, $ref;
  1351. }
  1352. $sth->finish;
  1353. $dbh->commit;
  1354. }
  1355. sub all_projects {
  1356. my ($self, $myconfig, $dbh2, $transdate, $job) = @_;
  1357. my $dbh = $self->{dbh};
  1358. my @queryargs = ();
  1359. my $where = "1 = 1";
  1360. $where = qq|id NOT IN (SELECT id
  1361. FROM parts
  1362. WHERE project_id > 0)| if ! $job;
  1363. my $query = qq|SELECT *
  1364. FROM project
  1365. WHERE $where|;
  1366. if ($form->{language_code}) {
  1367. $query = qq|
  1368. SELECT pr.*, t.description AS translation
  1369. FROM project pr
  1370. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1371. WHERE t.language_code = ?|;
  1372. push(@queryargs, $self->{language_code});
  1373. }
  1374. if ($transdate) {
  1375. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1376. AND (enddate IS NULL OR enddate >= ?)|;
  1377. push(@queryargs, $transdate, $transdate);
  1378. }
  1379. $query .= qq| ORDER BY projectnumber|;
  1380. $sth = $dbh->prepare($query);
  1381. $sth->execute(@queryargs)|| $self->dberror($query);
  1382. @{ $self->{all_project} } = ();
  1383. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1384. push @{ $self->{all_project} }, $ref;
  1385. }
  1386. $sth->finish;
  1387. $dbh->commit;
  1388. }
  1389. sub all_departments {
  1390. my ($self, $myconfig, $dbh2, $vc) = @_;
  1391. $dbh = $self->{dbh};
  1392. my $where = "1 = 1";
  1393. if ($vc) {
  1394. if ($vc eq 'customer') {
  1395. $where = " role = 'P'";
  1396. }
  1397. }
  1398. my $query = qq|SELECT id, description
  1399. FROM department
  1400. WHERE $where
  1401. ORDER BY 2|;
  1402. my $sth = $dbh->prepare($query);
  1403. $sth->execute || $self->dberror($query);
  1404. @{ $self->{all_department} } = ();
  1405. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1406. push @{ $self->{all_department} }, $ref;
  1407. }
  1408. $sth->finish;
  1409. $self->all_years($myconfig);
  1410. $dbh->commit;
  1411. }
  1412. sub all_years {
  1413. my ($self, $myconfig, $dbh2) = @_;
  1414. $dbh = $self->{dbh};
  1415. # get years
  1416. my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
  1417. (SELECT MAX(transdate) FROM acc_trans)
  1418. FROM defaults|;
  1419. my ($startdate, $enddate) = $dbh->selectrow_array($query);
  1420. if ($myconfig->{dateformat} =~ /^yy/) {
  1421. ($startdate) = split /\W/, $startdate;
  1422. ($enddate) = split /\W/, $enddate;
  1423. } else {
  1424. (@_) = split /\W/, $startdate;
  1425. $startdate = $_[2];
  1426. (@_) = split /\W/, $enddate;
  1427. $enddate = $_[2];
  1428. }
  1429. $self->{all_years} = ();
  1430. $startdate = substr($startdate,0,4);
  1431. $enddate = substr($enddate,0,4);
  1432. while ($enddate >= $startdate) {
  1433. push @{ $self->{all_years} }, $enddate--;
  1434. }
  1435. #this should probably be changed to use locale
  1436. %{ $self->{all_month} } = (
  1437. '01' => 'January',
  1438. '02' => 'February',
  1439. '03' => 'March',
  1440. '04' => 'April',
  1441. '05' => 'May ',
  1442. '06' => 'June',
  1443. '07' => 'July',
  1444. '08' => 'August',
  1445. '09' => 'September',
  1446. '10' => 'October',
  1447. '11' => 'November',
  1448. '12' => 'December' );
  1449. $dbh->commit;
  1450. }
  1451. sub create_links {
  1452. my ($self, $module, $myconfig, $vc, $job) = @_;
  1453. # get last customers or vendors
  1454. my ($query, $sth);
  1455. $dbh = $self->{dbh};
  1456. my %xkeyref = ();
  1457. # now get the account numbers
  1458. $query = qq|SELECT accno, description, link
  1459. FROM chart
  1460. WHERE link LIKE ?
  1461. ORDER BY accno|;
  1462. $sth = $dbh->prepare($query);
  1463. $sth->execute("%"."$module%") || $self->dberror($query);
  1464. $self->{accounts} = "";
  1465. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1466. foreach my $key (split /:/, $ref->{link}) {
  1467. if ($key =~ /$module/) {
  1468. # cross reference for keys
  1469. $xkeyref{$ref->{accno}} = $key;
  1470. push @{ $self->{"${module}_links"}{$key} },
  1471. { accno => $ref->{accno},
  1472. description => $ref->{description} };
  1473. $self->{accounts} .= "$ref->{accno} "
  1474. unless $key =~ /tax/;
  1475. }
  1476. }
  1477. }
  1478. $sth->finish;
  1479. my $arap = ($vc eq 'customer') ? 'ar' : 'ap';
  1480. if ($self->{id}) {
  1481. $query = qq|
  1482. SELECT a.invnumber, a.transdate,
  1483. a.${vc}_id, a.datepaid, a.duedate, a.ordnumber,
  1484. a.taxincluded, a.curr AS currency, a.notes,
  1485. a.intnotes, c.name AS $vc, a.department_id,
  1486. d.description AS department,
  1487. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1488. a.employee_id, e.name AS employee,
  1489. c.language_code, a.ponumber
  1490. FROM $arap a
  1491. JOIN $vc c ON (a.${vc}_id = c.id)
  1492. LEFT JOIN employee e ON (e.id = a.employee_id)
  1493. LEFT JOIN department d ON (d.id = a.department_id)
  1494. WHERE a.id = ?|;
  1495. $sth = $dbh->prepare($query);
  1496. $sth->execute($self->{id}) || $self->dberror($query);
  1497. $ref = $sth->fetchrow_hashref(NAME_lc);
  1498. foreach $key (keys %$ref) {
  1499. $self->{$key} = $ref->{$key};
  1500. }
  1501. $sth->finish;
  1502. # get printed, emailed
  1503. $query = qq|
  1504. SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1505. FROM status s WHERE s.trans_id = ?|;
  1506. $sth = $dbh->prepare($query);
  1507. $sth->execute($self->{id}) || $form->dberror($query);
  1508. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1509. $self->{printed} .= "$ref->{formname} "
  1510. if $ref->{printed};
  1511. $self->{emailed} .= "$ref->{formname} "
  1512. if $ref->{emailed};
  1513. $self->{queued} .= "$ref->{formname} ".
  1514. "$ref->{spoolfile} " if $ref->{spoolfile};
  1515. }
  1516. $sth->finish;
  1517. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1518. # get recurring
  1519. $self->get_recurring($dbh);
  1520. # get amounts from individual entries
  1521. $query = qq|
  1522. SELECT c.accno, c.description, a.source, a.amount,
  1523. a.memo, a.transdate, a.cleared, a.project_id,
  1524. p.projectnumber
  1525. FROM acc_trans a
  1526. JOIN chart c ON (c.id = a.chart_id)
  1527. LEFT JOIN project p ON (p.id = a.project_id)
  1528. WHERE a.trans_id = ?
  1529. AND a.fx_transaction = '0'
  1530. ORDER BY transdate|;
  1531. $sth = $dbh->prepare($query);
  1532. $sth->execute($self->{id}) || $self->dberror($query);
  1533. my $fld = ($vc eq 'customer') ? 'buy' : 'sell';
  1534. $self->{exchangerate} = $self->get_exchangerate($dbh,
  1535. $self->{currency}, $self->{transdate}, $fld);
  1536. # store amounts in {acc_trans}{$key} for multiple accounts
  1537. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1538. $ref->{exchangerate} = $self->get_exchangerate($dbh,
  1539. $self->{currency},
  1540. $ref->{transdate},
  1541. $fld);
  1542. push @{ $self->{acc_trans}{$xkeyref{$ref->{accno}}} },
  1543. $ref;
  1544. }
  1545. $sth->finish;
  1546. $query = qq|SELECT d.curr AS currencies, d.closedto, d.revtrans
  1547. FROM defaults d|;
  1548. $sth = $dbh->prepare($query);
  1549. $sth->execute || $self->dberror($query);
  1550. $ref = $sth->fetchrow_hashref(NAME_lc);
  1551. for (keys %$ref) { $self->{$_} = $ref->{$_} }
  1552. $sth->finish;
  1553. } else {
  1554. # get date
  1555. $query = qq|
  1556. SELECT current_date AS transdate,
  1557. d.curr AS currencies, d.closedto, d.revtrans
  1558. FROM defaults d|;
  1559. $sth = $dbh->prepare($query);
  1560. $sth->execute || $self->dberror($query);
  1561. $ref = $sth->fetchrow_hashref(NAME_lc);
  1562. for (keys %$ref) { $self->{$_} = $ref->{$_} }
  1563. $sth->finish;
  1564. if (! $self->{"$self->{vc}_id"}) {
  1565. $self->lastname_used($myconfig, $dbh, $vc, $module);
  1566. }
  1567. }
  1568. $self->all_vc($myconfig, $vc, $module, $dbh, $self->{transdate}, $job);
  1569. $self->{dbh}->commit;
  1570. }
  1571. sub lastname_used {
  1572. my ($self, $myconfig, $dbh2, $vc, $module) = @_;
  1573. my $dbh = $self->{dbh};
  1574. my $arap = ($vc eq 'customer') ? "ar" : "ap";
  1575. my $where = "1 = 1";
  1576. my $sth;
  1577. if ($self->{type} =~ /_order/) {
  1578. $arap = 'oe';
  1579. $where = "quotation = '0'";
  1580. }
  1581. if ($self->{type} =~ /_quotation/) {
  1582. $arap = 'oe';
  1583. $where = "quotation = '1'";
  1584. }
  1585. my $query = qq|
  1586. SELECT id
  1587. FROM $arap
  1588. WHERE id IN
  1589. (SELECT MAX(id)
  1590. FROM $arap
  1591. WHERE $where AND ${vc}_id > 0)|;
  1592. my ($trans_id) = $dbh->selectrow_array($query);
  1593. $trans_id *= 1;
  1594. my $DAYS = ($myconfig->{dbdriver} eq 'DB2') ? "DAYS" : "";
  1595. $query = qq|
  1596. SELECT ct.name AS $vc, a.curr AS currency, a.${vc}_id,
  1597. current_date + ct.terms $DAYS AS duedate,
  1598. a.department_id, d.description AS department, ct.notes,
  1599. ct.curr AS currency
  1600. FROM $arap a
  1601. JOIN $vc ct ON (a.${vc}_id = ct.id)
  1602. LEFT JOIN department d ON (a.department_id = d.id)
  1603. WHERE a.id = ?|;
  1604. $sth = $dbh->prepare($query);
  1605. $sth->execute($trans_id)|| $self->dberror($query);
  1606. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1607. for (keys %$ref) { $self->{$_} = $ref->{$_} }
  1608. $sth->finish;
  1609. $dbh->commit;
  1610. }
  1611. sub current_date {
  1612. my ($self, $myconfig, $thisdate, $days) = @_;
  1613. my $dbh = $self->{dbh};
  1614. my $query;
  1615. $days *= 1;
  1616. if ($thisdate) {
  1617. my $dateformat = $myconfig->{dateformat};
  1618. if ($myconfig->{dateformat} !~ /^y/) {
  1619. my @a = split /\D/, $thisdate;
  1620. $dateformat .= "yy" if (length $a[2] > 2);
  1621. }
  1622. if ($thisdate !~ /\D/) {
  1623. $dateformat = 'yyyymmdd';
  1624. }
  1625. $query = qq|SELECT to_date(?, ?)
  1626. + ? AS thisdate
  1627. FROM defaults|;
  1628. @queryargs = ($thisdate, $dateformat, $days);
  1629. } else {
  1630. $query = qq|SELECT current_date AS thisdate
  1631. FROM defaults|;
  1632. @queryargs = ();
  1633. }
  1634. $sth = $dbh->prepare($query);
  1635. $sth->execute(@queryargs);
  1636. ($thisdate) = $sth->fetchrow_array;
  1637. $dbh->commit;
  1638. $thisdate;
  1639. }
  1640. sub like {
  1641. my ($self, $str) = @_;
  1642. if ($str !~ /(%|_)/) {
  1643. if ($str =~ /(^").*("$)/) {
  1644. $str =~ s/(^"|"$)//g;
  1645. } else {
  1646. $str = "%$str%";
  1647. }
  1648. }
  1649. $str =~ s/'/''/g;
  1650. $str;
  1651. }
  1652. sub redo_rows {
  1653. my ($self, $flds, $new, $count, $numrows) = @_;
  1654. my @ndx = ();
  1655. for (1 .. $count) {
  1656. push @ndx, { num => $new->[$_-1]->{runningnumber}, ndx => $_ }
  1657. }
  1658. my $i = 0;
  1659. # fill rows
  1660. foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
  1661. $i++;
  1662. $j = $item->{ndx} - 1;
  1663. for (@{$flds}) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1664. }
  1665. # delete empty rows
  1666. for $i ($count + 1 .. $numrows) {
  1667. for (@{$flds}) { delete $self->{"${_}_$i"} }
  1668. }
  1669. }
  1670. sub get_partsgroup {
  1671. my ($self, $myconfig, $p) = @_;
  1672. my $dbh = $self->{dbh};
  1673. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1674. FROM partsgroup pg
  1675. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1676. my $where;
  1677. my $sortorder = "partsgroup";
  1678. if ($p->{searchitems} eq 'part') {
  1679. $where = qq| WHERE (p.inventory_accno_id > 0
  1680. AND p.income_accno_id > 0)|;
  1681. }
  1682. if ($p->{searchitems} eq 'service') {
  1683. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1684. }
  1685. if ($p->{searchitems} eq 'assembly') {
  1686. $where = qq| WHERE p.assembly = '1'|;
  1687. }
  1688. if ($p->{searchitems} eq 'labor') {
  1689. $where = qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1690. }
  1691. if ($p->{searchitems} eq 'nolabor') {
  1692. $where = qq| WHERE p.income_accno_id > 0|;
  1693. }
  1694. if ($p->{all}) {
  1695. $query = qq|SELECT id, partsgroup
  1696. FROM partsgroup|;
  1697. }
  1698. my @queryargs = ();
  1699. if ($p->{language_code}) {
  1700. $sortorder = "translation";
  1701. $query = qq|
  1702. SELECT DISTINCT pg.id, pg.partsgroup,
  1703. t.description AS translation
  1704. FROM partsgroup pg
  1705. JOIN parts p ON (p.partsgroup_id = pg.id)
  1706. LEFT JOIN translation t ON (t.trans_id = pg.id
  1707. AND t.language_code = ?)|;
  1708. @queryargs = ($p->{language_code});
  1709. }
  1710. $query .= qq| $where ORDER BY $sortorder|;
  1711. my $sth = $dbh->prepare($query);
  1712. $sth->execute(@queryargs)|| $self->dberror($query);
  1713. $self->{all_partsgroup} = ();
  1714. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1715. push @{ $self->{all_partsgroup} }, $ref;
  1716. }
  1717. $sth->finish;
  1718. $dbh->commit;
  1719. }
  1720. sub update_status {
  1721. my ($self, $myconfig) = @_;
  1722. # no id return
  1723. return unless $self->{id};
  1724. my $dbh = $self->{dbh};
  1725. my %queued = split / +/, $self->{queued};
  1726. my $spoolfile = ($queued{$self->{formname}}) ? "'$queued{$self->{formname}}'" : 'NULL';
  1727. my $query = qq|DELETE FROM status
  1728. WHERE formname = ?
  1729. AND trans_id = ?|;
  1730. $sth=$dbh->prepare($query);
  1731. $sth->execute($self->{formname}, $self->{id}) || $self->dberror($query);
  1732. $sth->finish;
  1733. my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
  1734. my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
  1735. $query = qq|
  1736. INSERT INTO status
  1737. (trans_id, printed, emailed, spoolfile, formname)
  1738. VALUES (?, ?, ?, ?, ?)|;
  1739. $sth = $dbh->prepare($query);
  1740. $sth->execute($self->{id}, $printed, $emailed, $spoolfile,
  1741. $self->{formname});
  1742. $sth->finish;
  1743. $dbh->commit;
  1744. }
  1745. sub save_status {
  1746. my ($self) = @_;
  1747. $dbh = $self->{dbh};
  1748. my $formnames = $self->{printed};
  1749. my $emailforms = $self->{emailed};
  1750. my $query = qq|DELETE FROM status
  1751. WHERE trans_id = ?|;
  1752. my $sth = $dbh->prepare($query);
  1753. $sth->execute($form->{id});
  1754. $sth->finish;
  1755. my %queued;
  1756. my $formname;
  1757. if ($self->{queued}) {
  1758. %queued = split / +/, $self->{queued};
  1759. foreach $formname (keys %queued) {
  1760. $printed = ($self->{printed} =~ /$formname/) ? "1" : "0";
  1761. $emailed = ($self->{emailed} =~ /$formname/) ? "1" : "0";
  1762. if ($queued{$formname}) {
  1763. $query = qq|
  1764. INSERT INTO status
  1765. (trans_id, printed, emailed,
  1766. spoolfile, formname)
  1767. VALUES (?, ?, ?, ?, ?)|;
  1768. $sth = $dbh->prepare($query);
  1769. $sth->execute($self->{id}, $pinted, $emailed,
  1770. $queued{$formname}, $formname)
  1771. || $self->dberror($query);
  1772. $sth->finish;
  1773. }
  1774. $formnames =~ s/$formname//;
  1775. $emailforms =~ s/$formname//;
  1776. }
  1777. }
  1778. # save printed, emailed info
  1779. $formnames =~ s/^ +//g;
  1780. $emailforms =~ s/^ +//g;
  1781. my %status = ();
  1782. for (split / +/, $formnames) { $status{$_}{printed} = 1 }
  1783. for (split / +/, $emailforms) { $status{$_}{emailed} = 1 }
  1784. foreach my $formname (keys %status) {
  1785. $printed = ($formnames =~ /$self->{formname}/) ? "1" : "0";
  1786. $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
  1787. $query = qq|
  1788. INSERT INTO status (trans_id, printed, emailed,
  1789. formname)
  1790. VALUES (?, ?, ?, ?)|;
  1791. $sth = $dbh->prepare($query);
  1792. $sth->execute($self->{id}, $printed, $emailed, $formname);
  1793. $sth->finish;
  1794. }
  1795. $dbh->commit;
  1796. }
  1797. sub get_recurring {
  1798. my ($self) = @_;
  1799. $dbh = $self->{dbh};
  1800. my $query = qq/
  1801. SELECT s.*, se.formname || ':' || se.format AS emaila,
  1802. se.message, sp.formname || ':' ||
  1803. sp.format || ':' || sp.printer AS printa
  1804. FROM recurring s
  1805. LEFT JOIN recurringemail se ON (s.id = se.id)
  1806. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  1807. WHERE s.id = ?/;
  1808. my $sth = $dbh->prepare($query);
  1809. $sth->execute($self->{id}) || $form->dberror($query);
  1810. for (qw(email print)) { $self->{"recurring$_"} = "" }
  1811. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1812. for (keys %$ref) { $self->{"recurring$_"} = $ref->{$_} }
  1813. $self->{recurringemail} .= "$ref->{emaila}:";
  1814. $self->{recurringprint} .= "$ref->{printa}:";
  1815. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  1816. }
  1817. $sth->finish;
  1818. chop $self->{recurringemail};
  1819. chop $self->{recurringprint};
  1820. if ($self->{recurringstartdate}) {
  1821. $self->{recurringreference} = $self->escape($self->{recurringreference},1);
  1822. $self->{recurringmessage} = $self->escape($self->{recurringmessage},1);
  1823. for (qw(reference startdate repeat unit howmany
  1824. payment print email message)) {
  1825. $self->{recurring} .= qq|$self->{"recurring$_"},|
  1826. }
  1827. chop $self->{recurring};
  1828. }
  1829. $dbh->commit;
  1830. }
  1831. sub save_recurring {
  1832. my ($self, $dbh2, $myconfig) = @_;
  1833. my $dbh = $self->{dbh};
  1834. my $query;
  1835. $query = qq|DELETE FROM recurring
  1836. WHERE id = ?|;
  1837. $sth = $dbh->prepare($query);
  1838. $sth->execute($self->{id}) || $self->dberror($query);
  1839. $query = qq|DELETE FROM recurringemail
  1840. WHERE id = ?|;
  1841. $sth = $dbh->prepare($query);
  1842. $sth->execute($self->{id}) || $self->dberror($query);
  1843. $query = qq|DELETE FROM recurringprint
  1844. WHERE id = ?|;
  1845. $sth = $dbh->prepare($query);
  1846. $sth->execute($self->{id}) || $self->dberror($query);
  1847. if ($self->{recurring}) {
  1848. my %s = ();
  1849. ($s{reference}, $s{startdate}, $s{repeat}, $s{unit},
  1850. $s{howmany}, $s{payment}, $s{print}, $s{email},
  1851. $s{message})
  1852. = split /,/, $self->{recurring};
  1853. for (qw(reference message)) { $s{$_} = $self->unescape($s{$_}) }
  1854. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  1855. # calculate enddate
  1856. my $advance = $s{repeat} * ($s{howmany} - 1);
  1857. my %interval;
  1858. $interval{'Pg'} =
  1859. "(date '$s{startdate}' + interval '$advance $s{unit}')";
  1860. $query = qq|SELECT $interval{$myconfig->{dbdriver}}
  1861. FROM defaults|;
  1862. my ($enddate) = $dbh->selectrow_array($query);
  1863. # calculate nextdate
  1864. $query = qq|
  1865. SELECT current_date - date ? AS a,
  1866. date ? - current_date AS b
  1867. FROM defaults|;
  1868. $sth = $dbh->prepare($query);
  1869. $sth->execute($s{startdate}, $enddate);
  1870. my ($a, $b) = $sth->fetchrow_array;
  1871. if ($a + $b) {
  1872. $advance = int(($a / ($a + $b)) * ($s{howmany} - 1) + 1) * $s{repeat};
  1873. } else {
  1874. $advance = 0;
  1875. }
  1876. my $nextdate = $enddate;
  1877. if ($advance > 0) {
  1878. if ($advance < ($s{repeat} * $s{howmany})) {
  1879. %interval = ( 'Pg' => "(date '$s{startdate}' + interval '$advance $s{unit}')",
  1880. 'DB2' => qq|(date ('$s{startdate}') + "$advance $s{unit}")|,);
  1881. $interval{Oracle} = $interval{PgPP} = $interval{Pg};
  1882. $query = qq|SELECT $interval{$myconfig->{dbdriver}}
  1883. FROM defaults|;
  1884. ($nextdate) = $dbh->selectrow_array($query);
  1885. }
  1886. } else {
  1887. $nextdate = $s{startdate};
  1888. }
  1889. if ($self->{recurringnextdate}) {
  1890. $nextdate = $self->{recurringnextdate};
  1891. $query = qq|SELECT '$enddate' - date '$nextdate'
  1892. FROM defaults|;
  1893. if ($dbh->selectrow_array($query) < 0) {
  1894. undef $nextdate;
  1895. }
  1896. }
  1897. $self->{recurringpayment} *= 1;
  1898. $query = qq|
  1899. INSERT INTO recurring
  1900. (id, reference, startdate, enddate, nextdate,
  1901. repeat, unit, howmany, payment)
  1902. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  1903. $sth = $dbh->prepare($query);
  1904. $sth->execute($self->{id}, $s{reference}, $s{startdate},
  1905. $enddate, $nextdate, $s{repeat}, $s{unit}, $s{howmany},
  1906. $s{payment});
  1907. my @p;
  1908. my $p;
  1909. my $i;
  1910. my $sth;
  1911. if ($s{email}) {
  1912. # formname:format
  1913. @p = split /:/, $s{email};
  1914. $query = qq|INSERT INTO recurringemail (id, formname, format, message)
  1915. VALUES (?, ?, ?, ?)|;
  1916. $sth = $dbh->prepare($query) || $self->dberror($query);
  1917. for ($i = 0; $i <= $#p; $i += 2) {
  1918. $sth->execute($self->{id}, $p[$i], $p[$i+1],
  1919. $s{message});
  1920. }
  1921. $sth->finish;
  1922. }
  1923. if ($s{print}) {
  1924. # formname:format:printer
  1925. @p = split /:/, $s{print};
  1926. $query = qq|INSERT INTO recurringprint (id, formname, format, printer)
  1927. VALUES (?, ?, ?, ?)|;
  1928. $sth = $dbh->prepare($query) || $self->dberror($query);
  1929. for ($i = 0; $i <= $#p; $i += 3) {
  1930. $p = ($p[$i+2]) ? $p[$i+2] : "";
  1931. $sth->execute($self->{id}, $p[$i], $p[$i+1], $p);
  1932. }
  1933. $sth->finish;
  1934. }
  1935. }
  1936. if ($disconnect) {
  1937. $dbh->commit;
  1938. $dbh->disconnect;
  1939. }
  1940. }
  1941. sub save_intnotes {
  1942. my ($self, $myconfig, $vc) = @_;
  1943. # no id return
  1944. return unless $self->{id};
  1945. my $dbh = $self->dbconnect($myconfig);
  1946. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  1947. $sth=$dbh->prepare($query);
  1948. $sth->execute($self->{intnotes}, $self->{id}) || $self->dberror($query);
  1949. $dbh->commit;
  1950. }
  1951. sub update_defaults {
  1952. my ($self, $myconfig, $fld) = @_;
  1953. if (!$self->{dbh} && $self){
  1954. $self->db_init($myconfig);
  1955. }
  1956. my $dbh = $self->{dbh};
  1957. if (!$self){
  1958. $dbh = $_[3];
  1959. }
  1960. my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
  1961. ($_) = $dbh->selectrow_array($query);
  1962. $_ = "0" unless $_;
  1963. # check for and replace
  1964. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  1965. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  1966. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  1967. # <?lsmb PHONE ?> for customer and vendors
  1968. my $num = $_;
  1969. ($num) = $num =~ /(\d+)/;
  1970. if (defined $num) {
  1971. my $incnum;
  1972. # if we have leading zeros check how long it is
  1973. if ($num =~ /^0/) {
  1974. my $l = length $num;
  1975. $incnum = $num + 1;
  1976. $l -= length $incnum;
  1977. # pad it out with zeros
  1978. my $padzero = "0" x $l;
  1979. $incnum = ("0" x $l) . $incnum;
  1980. } else {
  1981. $incnum = $num + 1;
  1982. }
  1983. s/$num/$incnum/;
  1984. }
  1985. my $dbvar = $_;
  1986. my $var = $_;
  1987. my $str;
  1988. my $param;
  1989. if (/<\?lsmb /) {
  1990. while (/<\?lsmb /) {
  1991. s/<\?lsmb .*? \?>//;
  1992. last unless $&;
  1993. $param = $&;
  1994. $str = "";
  1995. if ($param =~ /<\?lsmb date \?>/i) {
  1996. $str = ($self->split_date($myconfig->{dateformat}, $self->{transdate}))[0];
  1997. $var =~ s/$param/$str/;
  1998. }
  1999. if ($param =~ /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i) {
  2000. my $fld = lc $&;
  2001. $fld =~ s/<\?lsmb //;
  2002. if ($fld =~ /name/) {
  2003. if ($self->{type}) {
  2004. $fld = $self->{vc};
  2005. }
  2006. }
  2007. my $p = $param;
  2008. $p =~ s/(<|>|%)//g;
  2009. my @p = split / /, $p;
  2010. my @n = split / /, uc $self->{$fld};
  2011. if ($#p > 0) {
  2012. for (my $i = 1; $i <= $#p; $i++) {
  2013. $str .= substr($n[$i-1], 0, $p[$i]);
  2014. }
  2015. } else {
  2016. ($str) = split /--/, $self->{$fld};
  2017. }
  2018. $var =~ s/$param/$str/;
  2019. $var =~ s/\W//g if $fld eq 'phone';
  2020. }
  2021. if ($param =~ /<\?lsmb (yy|mm|dd)/i) {
  2022. my $p = $param;
  2023. $p =~ s/(<|>|%)//g;
  2024. my $spc = $p;
  2025. $spc =~ s/\w//g;
  2026. $spc = substr($spc, 0, 1);
  2027. my %d = ( yy => 1, mm => 2, dd => 3 );
  2028. my @p = ();
  2029. my @a = $self->split_date($myconfig->{dateformat}, $self->{transdate});
  2030. for (sort keys %d) { push @p, $a[$d{$_}] if ($p =~ /$_/) }
  2031. $str = join $spc, @p;
  2032. $var =~ s/$param/$str/;
  2033. }
  2034. if ($param =~ /<\?lsmb curr/i) {
  2035. $var =~ s/$param/$self->{currency}/;
  2036. }
  2037. }
  2038. }
  2039. $query = qq|UPDATE defaults
  2040. SET $fld = ?|;
  2041. $sth = $dbh->prepare($query);
  2042. $sth->execute($dbvar) || $self->dberror($query);
  2043. $dbh->commit;
  2044. $var;
  2045. }
  2046. sub db_prepare_vars {
  2047. for (@_){
  2048. if (!$self->{$_} and $self->{$_} != 0){
  2049. $self->{$_} = undef;
  2050. }
  2051. }
  2052. }
  2053. sub split_date {
  2054. my ($self, $dateformat, $date) = @_;
  2055. my @d = localtime;
  2056. my $mm;
  2057. my $dd;
  2058. my $yy;
  2059. my $rv;
  2060. if (! $date) {
  2061. $dd = $d[3];
  2062. $mm = ++$d[4];
  2063. $yy = substr($d[5],-2);
  2064. $mm = substr("0$mm", -2);
  2065. $dd = substr("0$dd", -2);
  2066. }
  2067. if ($dateformat =~ /^yy/) {
  2068. if ($date) {
  2069. if ($date =~ /\D/) {
  2070. ($yy, $mm, $dd) = split /\D/, $date;
  2071. $mm *= 1;
  2072. $dd *= 1;
  2073. $mm = substr("0$mm", -2);
  2074. $dd = substr("0$dd", -2);
  2075. $yy = substr($yy, -2);
  2076. $rv = "$yy$mm$dd";
  2077. } else {
  2078. $rv = $date;
  2079. }
  2080. } else {
  2081. $rv = "$yy$mm$dd";
  2082. }
  2083. }
  2084. if ($dateformat =~ /^mm/) {
  2085. if ($date) {
  2086. if ($date =~ /\D/) {
  2087. ($mm, $dd, $yy) = split /\D/, $date;
  2088. $mm *= 1;
  2089. $dd *= 1;
  2090. $mm = substr("0$mm", -2);
  2091. $dd = substr("0$dd", -2);
  2092. $yy = substr($yy, -2);
  2093. $rv = "$mm$dd$yy";
  2094. } else {
  2095. $rv = $date;
  2096. }
  2097. } else {
  2098. $rv = "$mm$dd$yy";
  2099. }
  2100. }
  2101. if ($dateformat =~ /^dd/) {
  2102. if ($date) {
  2103. if ($date =~ /\D/) {
  2104. ($dd, $mm, $yy) = split /\D/, $date;
  2105. $mm *= 1;
  2106. $dd *= 1;
  2107. $mm = substr("0$mm", -2);
  2108. $dd = substr("0$dd", -2);
  2109. $yy = substr($yy, -2);
  2110. $rv = "$dd$mm$yy";
  2111. } else {
  2112. $rv = $date;
  2113. }
  2114. } else {
  2115. $rv = "$dd$mm$yy";
  2116. }
  2117. }
  2118. ($rv, $yy, $mm, $dd);
  2119. }
  2120. sub from_to {
  2121. my ($self, $yy, $mm, $interval) = @_;
  2122. use Time::Local;
  2123. my @t;
  2124. my $dd = 1;
  2125. my $fromdate = "$yy${mm}01";
  2126. my $bd = 1;
  2127. if (defined $interval) {
  2128. if ($interval == 12) {
  2129. $yy++;
  2130. } else {
  2131. if (($mm += $interval) > 12) {
  2132. $mm -= 12;
  2133. $yy++;
  2134. }
  2135. if ($interval == 0) {
  2136. @t = localtime(time);
  2137. $dd = $t[3];
  2138. $mm = $t[4] + 1;
  2139. $yy = $t[5] + 1900;
  2140. $bd = 0;
  2141. }
  2142. }
  2143. } else {
  2144. if (++$mm > 12) {
  2145. $mm -= 12;
  2146. $yy++;
  2147. }
  2148. }
  2149. $mm--;
  2150. @t = localtime(timelocal(0,0,0,$dd,$mm,$yy) - $bd);
  2151. $t[4]++;
  2152. $t[4] = substr("0$t[4]",-2);
  2153. $t[3] = substr("0$t[3]",-2);
  2154. $t[5] += 1900;
  2155. ($fromdate, "$t[5]$t[4]$t[3]");
  2156. }
  2157. sub audittrail {
  2158. my ($self, $dbh, $myconfig, $audittrail) = @_;
  2159. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2160. my $query;
  2161. my $rv;
  2162. my $disconnect;
  2163. if (! $dbh) {
  2164. $dbh = $self->dbconnect($myconfig);
  2165. $disconnect = 1;
  2166. }
  2167. # if we have an id add audittrail, otherwise get a new timestamp
  2168. my @queryargs;
  2169. if ($audittrail->{id}) {
  2170. $query = qq|SELECT audittrail FROM defaults|;
  2171. if ($dbh->selectrow_array($query)) {
  2172. my ($null, $employee_id) = $self->get_employee($dbh);
  2173. if ($self->{audittrail} && !$myconfig) {
  2174. chop $self->{audittrail};
  2175. my @a = split /\|/, $self->{audittrail};
  2176. my %newtrail = ();
  2177. my $key;
  2178. my $i;
  2179. my @flds = qw(tablename reference formname action transdate);
  2180. # put into hash and remove dups
  2181. while (@a) {
  2182. $key = "$a[2]$a[3]";
  2183. $i = 0;
  2184. $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
  2185. splice @a, 0, 5;
  2186. }
  2187. $query = qq|
  2188. INSERT INTO audittrail
  2189. (trans_id, tablename, reference,
  2190. formname, action, transdate,
  2191. employee_id)
  2192. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2193. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2194. foreach $key (sort { $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate} } keys %newtrail) {
  2195. $i = 2;
  2196. $sth->bind_param(1, $audittrail->{id});
  2197. for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
  2198. $sth->bind_param($i++, $employee_id);
  2199. $sth->execute || $self->dberror;
  2200. $sth->finish;
  2201. }
  2202. }
  2203. if ($audittrail->{transdate}) {
  2204. $query = qq|
  2205. INSERT INTO audittrail (
  2206. trans_id, tablename, reference,
  2207. formname, action, employee_id,
  2208. transdate)
  2209. VALUES (?, ?, ?, ?, ?, ?)|;
  2210. @queryargs = (
  2211. $audittrail->{id},
  2212. $audittrail->{tablename},
  2213. $audittrail->{reference},
  2214. $audittrail->{formname},
  2215. $audittrail->{action}.
  2216. $employee_id,
  2217. $audittrail->{transdate}
  2218. );
  2219. } else {
  2220. $query = qq|
  2221. INSERT INTO audittrail
  2222. (trans_id, tablename, reference,
  2223. formname, action, employee_id)
  2224. VALUES (?, ?, ?, ?, ?)|;
  2225. @queryargs = (
  2226. $audittrail->{id},
  2227. $audittrail->{tablename},
  2228. $audittrail->{reference},
  2229. $audittrail->{formname},
  2230. $audittrail->{action}.
  2231. $employee_id,
  2232. );
  2233. }
  2234. $sth = $dbh->prepare($query);
  2235. $sth->execute(@queryargs)||$self->dberror($query);
  2236. }
  2237. } else {
  2238. $query = qq|SELECT current_timestamp FROM defaults|;
  2239. my ($timestamp) = $dbh->selectrow_array($query);
  2240. $rv = "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2241. }
  2242. $dbh->commit;
  2243. $rv;
  2244. }
  2245. package Locale;
  2246. sub new {
  2247. my ($type, $country, $NLS_file) = @_;
  2248. my $self = {};
  2249. %self = ();
  2250. if ($country && -d "locale/$country") {
  2251. $self->{countrycode} = $country;
  2252. eval { require "locale/$country/$NLS_file"; };
  2253. }
  2254. $self->{NLS_file} = $NLS_file;
  2255. $self->{charset} = $self{charset};
  2256. push @{ $self->{LONG_MONTH} }, ("January", "February", "March", "April", "May ", "June", "July", "August", "September", "October", "November", "December");
  2257. push @{ $self->{SHORT_MONTH} }, (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec));
  2258. bless $self, $type;
  2259. }
  2260. sub text {
  2261. my ($self, $text) = @_;
  2262. return (exists $self{texts}{$text}) ? $self{texts}{$text} : $text;
  2263. }
  2264. sub findsub {
  2265. my ($self, $text) = @_;
  2266. if (exists $self{subs}{$text}) {
  2267. $text = $self{subs}{$text};
  2268. } else {
  2269. if ($self->{countrycode} && $self->{NLS_file}) {
  2270. Form->error("$text not defined in locale/$self->{countrycode}/$self->{NLS_file}");
  2271. }
  2272. }
  2273. $text;
  2274. }
  2275. sub date {
  2276. my ($self, $myconfig, $date, $longformat) = @_;
  2277. my $longdate = "";
  2278. my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
  2279. if ($date) {
  2280. # get separator
  2281. $spc = $myconfig->{dateformat};
  2282. $spc =~ s/\w//g;
  2283. $spc = substr($spc, 0, 1);
  2284. if ($date =~ /\D/) {
  2285. if ($myconfig->{dateformat} =~ /^yy/) {
  2286. ($yy, $mm, $dd) = split /\D/, $date;
  2287. }
  2288. if ($myconfig->{dateformat} =~ /^mm/) {
  2289. ($mm, $dd, $yy) = split /\D/, $date;
  2290. }
  2291. if ($myconfig->{dateformat} =~ /^dd/) {
  2292. ($dd, $mm, $yy) = split /\D/, $date;
  2293. }
  2294. } else {
  2295. $date = substr($date, 2);
  2296. ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
  2297. }
  2298. $dd *= 1;
  2299. $mm--;
  2300. $yy += 2000 if length $yy == 2;
  2301. if ($myconfig->{dateformat} =~ /^dd/) {
  2302. $mm++;
  2303. $dd = substr("0$dd", -2);
  2304. $mm = substr("0$mm", -2);
  2305. $longdate = "$dd$spc$mm$spc$yy";
  2306. if (defined $longformat) {
  2307. $longdate = "$dd";
  2308. $longdate .= ($spc eq '.') ? ". " : " ";
  2309. $longdate .= &text($self, $self->{$longmonth}[--$mm])." $yy";
  2310. }
  2311. } elsif ($myconfig->{dateformat} =~ /^yy/) {
  2312. $mm++;
  2313. $dd = substr("0$dd", -2);
  2314. $mm = substr("0$mm", -2);
  2315. $longdate = "$yy$spc$mm$spc$dd";
  2316. if (defined $longformat) {
  2317. $longdate = &text($self, $self->{$longmonth}[--$mm])." $dd $yy";
  2318. }
  2319. } else {
  2320. $mm++;
  2321. $dd = substr("0$dd", -2);
  2322. $mm = substr("0$mm", -2);
  2323. $longdate = "$mm$spc$dd$spc$yy";
  2324. if (defined $longformat) {
  2325. $longdate = &text($self, $self->{$longmonth}[--$mm])." $dd $yy";
  2326. }
  2327. }
  2328. }
  2329. $longdate;
  2330. }
  2331. 1;