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