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