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