summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: 64590e487eb811d95f6f0292eaa55fbda83b2185 (plain)
  1. #=====================================================================
  2. # LedgerSMB
  3. # Small Medium Business Accounting software
  4. # http://sourceforge.net/projects/ledger-smb/
  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.0.0";
  54. $self->{dbversion} = "2.6.17";
  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}
  625. 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 dbconnect {
  883. my ($self, $myconfig) = @_;
  884. # connect to database
  885. my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}) or $self->dberror;
  886. # set db options
  887. if ($myconfig->{dboptions}) {
  888. $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
  889. }
  890. $dbh;
  891. }
  892. sub dbconnect_noauto {
  893. my ($self, $myconfig) = @_;
  894. # connect to database
  895. $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, {AutoCommit => 0}) or $self->dberror;
  896. # set db options
  897. if ($myconfig->{dboptions}) {
  898. $dbh->do($myconfig->{dboptions});
  899. }
  900. $dbh;
  901. }
  902. sub dbquote {
  903. my ($self, $var, $type) = @_;
  904. # DBI does not return NULL for SQL_DATE if the date is empty
  905. if ($type eq 'SQL_DATE') {
  906. $_ = ($var) ? "'$var'" : "NULL";
  907. }
  908. if ($type eq 'SQL_INT') {
  909. $_ = $var * 1;
  910. }
  911. $_;
  912. }
  913. sub update_balance {
  914. my ($self, $dbh, $table, $field, $where, $value) = @_;
  915. # if we have a value, go do it
  916. if ($value) {
  917. # retrieve balance from table
  918. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  919. my ($balance) = $dbh->selectrow_array($query);
  920. $balance += $value;
  921. # update balance
  922. $query = "UPDATE $table SET $field = $balance WHERE $where";
  923. $dbh->do($query) || $self->dberror($query);
  924. }
  925. }
  926. sub update_exchangerate {
  927. my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
  928. # some sanity check for currency
  929. return if ($curr eq "");
  930. my $query = qq|SELECT curr
  931. FROM exchangerate
  932. WHERE curr = '$curr'
  933. AND transdate = '$transdate'
  934. FOR UPDATE|;
  935. my $sth = $dbh->prepare($query);
  936. $sth->execute || $self->dberror($query);
  937. my $set;
  938. if ($buy && $sell) {
  939. $set = "buy = $buy, sell = $sell";
  940. } elsif ($buy) {
  941. $set = "buy = $buy";
  942. } elsif ($sell) {
  943. $set = "sell = $sell";
  944. }
  945. if ($sth->fetchrow_array) {
  946. $query = qq|UPDATE exchangerate
  947. SET $set
  948. WHERE curr = '$curr'
  949. AND transdate = '$transdate'|;
  950. } else {
  951. $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
  952. VALUES ('$curr', $buy, $sell, '$transdate')|;
  953. }
  954. $sth->finish;
  955. $dbh->do($query) || $self->dberror($query);
  956. }
  957. sub save_exchangerate {
  958. my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
  959. my $dbh = $self->dbconnect($myconfig);
  960. my ($buy, $sell) = (0, 0);
  961. $buy = $rate if $fld eq 'buy';
  962. $sell = $rate if $fld eq 'sell';
  963. $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
  964. $dbh->disconnect;
  965. }
  966. sub get_exchangerate {
  967. my ($self, $dbh, $curr, $transdate, $fld) = @_;
  968. my $exchangerate = 1;
  969. if ($transdate) {
  970. my $query = qq|SELECT $fld
  971. FROM exchangerate
  972. WHERE curr = '$curr'
  973. AND transdate = '$transdate'|;
  974. ($exchangerate) = $dbh->selectrow_array($query);
  975. }
  976. $exchangerate;
  977. }
  978. sub check_exchangerate {
  979. my ($self, $myconfig, $currency, $transdate, $fld) = @_;
  980. return "" unless $transdate;
  981. my $dbh = $self->dbconnect($myconfig);
  982. my $query = qq|SELECT $fld
  983. FROM exchangerate
  984. WHERE curr = '$currency'
  985. AND transdate = '$transdate'|;
  986. my ($exchangerate) = $dbh->selectrow_array($query);
  987. $dbh->disconnect;
  988. $exchangerate;
  989. }
  990. sub add_shipto {
  991. my ($self, $dbh, $id) = @_;
  992. my $shipto;
  993. foreach my $item (qw(name address1 address2 city state
  994. zipcode country contact phone fax email)) {
  995. if ($self->{"shipto$item"} ne "") {
  996. $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
  997. }
  998. }
  999. if ($shipto) {
  1000. my $query = qq|INSERT INTO shipto (trans_id, shiptoname, shiptoaddress1,
  1001. shiptoaddress2, shiptocity, shiptostate,
  1002. shiptozipcode, shiptocountry, shiptocontact,
  1003. shiptophone, shiptofax, shiptoemail)
  1004. VALUES ($id, |
  1005. .$dbh->quote($self->{shiptoname}).qq|, |
  1006. .$dbh->quote($self->{shiptoaddress1}).qq|, |
  1007. .$dbh->quote($self->{shiptoaddress2}).qq|, |
  1008. .$dbh->quote($self->{shiptocity}).qq|, |
  1009. .$dbh->quote($self->{shiptostate}).qq|, |
  1010. .$dbh->quote($self->{shiptozipcode}).qq|, |
  1011. .$dbh->quote($self->{shiptocountry}).qq|, |
  1012. .$dbh->quote($self->{shiptocontact}).qq|,
  1013. '$self->{shiptophone}', '$self->{shiptofax}',
  1014. '$self->{shiptoemail}')|;
  1015. $dbh->do($query) || $self->dberror($query);
  1016. }
  1017. }
  1018. sub get_employee {
  1019. my ($self, $dbh) = @_;
  1020. my $login = $self->{login};
  1021. $login =~ s/@.*//;
  1022. my $query = qq|SELECT name, id
  1023. FROM employee
  1024. WHERE login = '$login'|;
  1025. my (@a) = $dbh->selectrow_array($query);
  1026. $a[1] *= 1;
  1027. @a;
  1028. }
  1029. # this sub gets the id and name from $table
  1030. sub get_name {
  1031. my ($self, $myconfig, $table, $transdate) = @_;
  1032. # connect to database
  1033. my $dbh = $self->dbconnect($myconfig);
  1034. my $where;
  1035. if ($transdate) {
  1036. $where = qq|AND (startdate IS NULL OR startdate <= '$transdate')
  1037. AND (enddate IS NULL OR enddate >= '$transdate')|;
  1038. }
  1039. my $name = $self->like(lc $self->{$table});
  1040. my $query = qq|SELECT *
  1041. FROM $table
  1042. WHERE (lower(name) LIKE '$name'
  1043. OR ${table}number LIKE '$name')
  1044. $where
  1045. ORDER BY name|;
  1046. my $sth = $dbh->prepare($query);
  1047. $sth->execute || $self->dberror($query);
  1048. my $i = 0;
  1049. @{ $self->{name_list} } = ();
  1050. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1051. push(@{ $self->{name_list} }, $ref);
  1052. $i++;
  1053. }
  1054. $sth->finish;
  1055. $dbh->disconnect;
  1056. $i;
  1057. }
  1058. sub all_vc {
  1059. my ($self, $myconfig, $vc, $module, $dbh, $transdate, $job) = @_;
  1060. my $ref;
  1061. my $disconnect = 0;
  1062. if (! $dbh) {
  1063. $dbh = $self->dbconnect($myconfig);
  1064. $disconnect = 1;
  1065. }
  1066. my $sth;
  1067. my $query = qq|SELECT count(*) FROM $vc|;
  1068. my $where;
  1069. if ($transdate) {
  1070. $where = qq|AND (startdate IS NULL OR startdate <= '$transdate')
  1071. AND (enddate IS NULL OR enddate >= '$transdate')|;
  1072. $query .= qq| WHERE 1=1 $where|;
  1073. }
  1074. my ($count) = $dbh->selectrow_array($query);
  1075. # build selection list
  1076. if ($count < $myconfig->{vclimit}) {
  1077. $self->{"${vc}_id"} *= 1;
  1078. $query = qq|SELECT id, name
  1079. FROM $vc
  1080. WHERE 1=1
  1081. $where
  1082. UNION
  1083. SELECT id,name
  1084. FROM $vc
  1085. WHERE id = $self->{"${vc}_id"}
  1086. ORDER BY name|;
  1087. $sth = $dbh->prepare($query);
  1088. $sth->execute || $self->dberror($query);
  1089. @{ $self->{"all_$vc"} } = ();
  1090. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1091. push @{ $self->{"all_$vc"} }, $ref;
  1092. }
  1093. $sth->finish;
  1094. }
  1095. # get self
  1096. if (! $self->{employee_id}) {
  1097. ($self->{employee}, $self->{employee_id}) = split /--/, $self->{employee};
  1098. ($self->{employee}, $self->{employee_id}) = $self->get_employee($dbh) unless $self->{employee_id};
  1099. }
  1100. $self->all_employees($myconfig, $dbh, $transdate, 1);
  1101. $self->all_departments($myconfig, $dbh, $vc);
  1102. $self->all_projects($myconfig, $dbh, $transdate, $job);
  1103. # get language codes
  1104. $query = qq|SELECT *
  1105. FROM language
  1106. ORDER BY 2|;
  1107. $sth = $dbh->prepare($query);
  1108. $sth->execute || $self->dberror($query);
  1109. $self->{all_language} = ();
  1110. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1111. push @{ $self->{all_language} }, $ref;
  1112. }
  1113. $sth->finish;
  1114. $self->all_taxaccounts($myconfig, $dbh, $transdate);
  1115. $dbh->disconnect if $disconnect;
  1116. }
  1117. sub all_taxaccounts {
  1118. my ($self, $myconfig, $dbh, $transdate) = @_;
  1119. my $disconnect = ($dbh) ? 0 : 1;
  1120. if (! $dbh) {
  1121. $dbh = $self->dbconnect($myconfig);
  1122. }
  1123. my $sth;
  1124. my $query;
  1125. my $where;
  1126. if ($transdate) {
  1127. $where = qq| AND (t.validto >= '$transdate' OR t.validto IS NULL)|;
  1128. }
  1129. if ($self->{taxaccounts}) {
  1130. # rebuild tax rates
  1131. $query = qq|SELECT t.rate, t.taxnumber
  1132. FROM tax t
  1133. JOIN chart c ON (c.id = t.chart_id)
  1134. WHERE c.accno = ?
  1135. $where
  1136. ORDER BY accno, validto|;
  1137. $sth = $dbh->prepare($query) || $self->dberror($query);
  1138. foreach my $accno (split / /, $self->{taxaccounts}) {
  1139. $sth->execute($accno);
  1140. ($self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"}) = $sth->fetchrow_array;
  1141. $sth->finish;
  1142. }
  1143. }
  1144. $dbh->disconnect if $disconnect;
  1145. }
  1146. sub all_employees {
  1147. my ($self, $myconfig, $dbh, $transdate, $sales) = @_;
  1148. # setup employees/sales contacts
  1149. my $query = qq|SELECT id, name
  1150. FROM employee
  1151. WHERE 1 = 1|;
  1152. if ($transdate) {
  1153. $query .= qq| AND (startdate IS NULL OR startdate <= '$transdate')
  1154. AND (enddate IS NULL OR enddate >= '$transdate')|;
  1155. } else {
  1156. $query .= qq| AND enddate IS NULL|;
  1157. }
  1158. if ($sales) {
  1159. $query .= qq| AND sales = '1'|;
  1160. }
  1161. $query .= qq| ORDER BY name|;
  1162. my $sth = $dbh->prepare($query);
  1163. $sth->execute || $self->dberror($query);
  1164. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1165. push @{ $self->{all_employee} }, $ref;
  1166. }
  1167. $sth->finish;
  1168. }
  1169. sub all_projects {
  1170. my ($self, $myconfig, $dbh, $transdate, $job) = @_;
  1171. my $disconnect = 0;
  1172. if (! $dbh) {
  1173. $dbh = $self->dbconnect($myconfig);
  1174. $disconnect = 1;
  1175. }
  1176. my $where = "1 = 1";
  1177. $where = qq|id NOT IN (SELECT id
  1178. FROM parts
  1179. WHERE project_id > 0)| if ! $job;
  1180. my $query = qq|SELECT *
  1181. FROM project
  1182. WHERE $where|;
  1183. if ($form->{language_code}) {
  1184. $query = qq|SELECT pr.*, t.description AS translation
  1185. FROM project pr
  1186. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1187. WHERE t.language_code = '$form->{language_code}'|;
  1188. }
  1189. if ($transdate) {
  1190. $query .= qq| AND (startdate IS NULL OR startdate <= '$transdate')
  1191. AND (enddate IS NULL OR enddate >= '$transdate')|;
  1192. }
  1193. $query .= qq| ORDER BY projectnumber|;
  1194. $sth = $dbh->prepare($query);
  1195. $sth->execute || $self->dberror($query);
  1196. @{ $self->{all_project} } = ();
  1197. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1198. push @{ $self->{all_project} }, $ref;
  1199. }
  1200. $sth->finish;
  1201. $dbh->disconnect if $disconnect;
  1202. }
  1203. sub all_departments {
  1204. my ($self, $myconfig, $dbh, $vc) = @_;
  1205. my $disconnect = 0;
  1206. if (! $dbh) {
  1207. $dbh = $self->dbconnect($myconfig);
  1208. $disconnect = 1;
  1209. }
  1210. my $where = "1 = 1";
  1211. if ($vc) {
  1212. if ($vc eq 'customer') {
  1213. $where = " role = 'P'";
  1214. }
  1215. }
  1216. my $query = qq|SELECT id, description
  1217. FROM department
  1218. WHERE $where
  1219. ORDER BY 2|;
  1220. my $sth = $dbh->prepare($query);
  1221. $sth->execute || $self->dberror($query);
  1222. @{ $self->{all_department} } = ();
  1223. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1224. push @{ $self->{all_department} }, $ref;
  1225. }
  1226. $sth->finish;
  1227. $self->all_years($myconfig, $dbh);
  1228. $dbh->disconnect if $disconnect;
  1229. }
  1230. sub all_years {
  1231. my ($self, $myconfig, $dbh) = @_;
  1232. my $disconnect = 0;
  1233. if (! $dbh) {
  1234. $dbh = $self->dbconnect($myconfig);
  1235. $disconnect = 1;
  1236. }
  1237. # get years
  1238. my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
  1239. (SELECT MAX(transdate) FROM acc_trans)
  1240. FROM defaults|;
  1241. my ($startdate, $enddate) = $dbh->selectrow_array($query);
  1242. if ($myconfig->{dateformat} =~ /^yy/) {
  1243. ($startdate) = split /\W/, $startdate;
  1244. ($enddate) = split /\W/, $enddate;
  1245. } else {
  1246. (@_) = split /\W/, $startdate;
  1247. $startdate = $_[2];
  1248. (@_) = split /\W/, $enddate;
  1249. $enddate = $_[2];
  1250. }
  1251. $self->{all_years} = ();
  1252. $startdate = substr($startdate,0,4);
  1253. $enddate = substr($enddate,0,4);
  1254. while ($enddate >= $startdate) {
  1255. push @{ $self->{all_years} }, $enddate--;
  1256. }
  1257. #this should probably be changed to use locale
  1258. %{ $self->{all_month} } = ( '01' => 'January',
  1259. '02' => 'February',
  1260. '03' => 'March',
  1261. '04' => 'April',
  1262. '05' => 'May ',
  1263. '06' => 'June',
  1264. '07' => 'July',
  1265. '08' => 'August',
  1266. '09' => 'September',
  1267. '10' => 'October',
  1268. '11' => 'November',
  1269. '12' => 'December' );
  1270. $dbh->disconnect if $disconnect;
  1271. }
  1272. sub create_links {
  1273. my ($self, $module, $myconfig, $vc, $job) = @_;
  1274. # get last customers or vendors
  1275. my ($query, $sth);
  1276. my $dbh = $self->dbconnect($myconfig);
  1277. my %xkeyref = ();
  1278. # now get the account numbers
  1279. $query = qq|SELECT accno, description, link
  1280. FROM chart
  1281. WHERE link LIKE '%$module%'
  1282. ORDER BY accno|;
  1283. $sth = $dbh->prepare($query);
  1284. $sth->execute || $self->dberror($query);
  1285. $self->{accounts} = "";
  1286. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1287. foreach my $key (split /:/, $ref->{link}) {
  1288. if ($key =~ /$module/) {
  1289. # cross reference for keys
  1290. $xkeyref{$ref->{accno}} = $key;
  1291. push @{ $self->{"${module}_links"}{$key} }, { accno => $ref->{accno},
  1292. description => $ref->{description} };
  1293. $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
  1294. }
  1295. }
  1296. }
  1297. $sth->finish;
  1298. my $arap = ($vc eq 'customer') ? 'ar' : 'ap';
  1299. if ($self->{id}) {
  1300. $query = qq|SELECT a.invnumber, a.transdate,
  1301. a.${vc}_id, a.datepaid, a.duedate, a.ordnumber,
  1302. a.taxincluded, a.curr AS currency, a.notes, a.intnotes,
  1303. c.name AS $vc, a.department_id, d.description AS department,
  1304. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1305. a.employee_id, e.name AS employee, c.language_code,
  1306. a.ponumber
  1307. FROM $arap a
  1308. JOIN $vc c ON (a.${vc}_id = c.id)
  1309. LEFT JOIN employee e ON (e.id = a.employee_id)
  1310. LEFT JOIN department d ON (d.id = a.department_id)
  1311. WHERE a.id = $self->{id}|;
  1312. $sth = $dbh->prepare($query);
  1313. $sth->execute || $self->dberror($query);
  1314. $ref = $sth->fetchrow_hashref(NAME_lc);
  1315. foreach $key (keys %$ref) {
  1316. $self->{$key} = $ref->{$key};
  1317. }
  1318. $sth->finish;
  1319. # get printed, emailed
  1320. $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1321. FROM status s
  1322. WHERE s.trans_id = $self->{id}|;
  1323. $sth = $dbh->prepare($query);
  1324. $sth->execute || $form->dberror($query);
  1325. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1326. $self->{printed} .= "$ref->{formname} " if $ref->{printed};
  1327. $self->{emailed} .= "$ref->{formname} " if $ref->{emailed};
  1328. $self->{queued} .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
  1329. }
  1330. $sth->finish;
  1331. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1332. # get recurring
  1333. $self->get_recurring($dbh);
  1334. # get amounts from individual entries
  1335. $query = qq|SELECT c.accno, c.description, a.source, a.amount,
  1336. a.memo, a.transdate, a.cleared, a.project_id,
  1337. p.projectnumber
  1338. FROM acc_trans a
  1339. JOIN chart c ON (c.id = a.chart_id)
  1340. LEFT JOIN project p ON (p.id = a.project_id)
  1341. WHERE a.trans_id = $self->{id}
  1342. AND a.fx_transaction = '0'
  1343. ORDER BY transdate|;
  1344. $sth = $dbh->prepare($query);
  1345. $sth->execute || $self->dberror($query);
  1346. my $fld = ($vc eq 'customer') ? 'buy' : 'sell';
  1347. $self->{exchangerate} = $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
  1348. # store amounts in {acc_trans}{$key} for multiple accounts
  1349. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1350. $ref->{exchangerate} = $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
  1351. push @{ $self->{acc_trans}{$xkeyref{$ref->{accno}}} }, $ref;
  1352. }
  1353. $sth->finish;
  1354. $query = qq|SELECT d.curr AS currencies, d.closedto, d.revtrans
  1355. FROM defaults d|;
  1356. $sth = $dbh->prepare($query);
  1357. $sth->execute || $self->dberror($query);
  1358. $ref = $sth->fetchrow_hashref(NAME_lc);
  1359. for (keys %$ref) { $self->{$_} = $ref->{$_} }
  1360. $sth->finish;
  1361. } else {
  1362. # get date
  1363. $query = qq|SELECT current_date AS transdate,
  1364. d.curr AS currencies, d.closedto, d.revtrans
  1365. FROM defaults d|;
  1366. $sth = $dbh->prepare($query);
  1367. $sth->execute || $self->dberror($query);
  1368. $ref = $sth->fetchrow_hashref(NAME_lc);
  1369. for (keys %$ref) { $self->{$_} = $ref->{$_} }
  1370. $sth->finish;
  1371. if (! $self->{"$self->{vc}_id"}) {
  1372. $self->lastname_used($myconfig, $dbh, $vc, $module);
  1373. }
  1374. }
  1375. $self->all_vc($myconfig, $vc, $module, $dbh, $self->{transdate}, $job);
  1376. $dbh->disconnect;
  1377. }
  1378. sub lastname_used {
  1379. my ($self, $myconfig, $dbh, $vc, $module) = @_;
  1380. my $arap = ($vc eq 'customer') ? "ar" : "ap";
  1381. my $where = "1 = 1";
  1382. my $sth;
  1383. if ($self->{type} =~ /_order/) {
  1384. $arap = 'oe';
  1385. $where = "quotation = '0'";
  1386. }
  1387. if ($self->{type} =~ /_quotation/) {
  1388. $arap = 'oe';
  1389. $where = "quotation = '1'";
  1390. }
  1391. my $query = qq|SELECT id
  1392. FROM $arap
  1393. WHERE id IN (SELECT MAX(id)
  1394. FROM $arap
  1395. WHERE $where
  1396. AND ${vc}_id > 0)|;
  1397. my ($trans_id) = $dbh->selectrow_array($query);
  1398. $trans_id *= 1;
  1399. my $DAYS = ($myconfig->{dbdriver} eq 'DB2') ? "DAYS" : "";
  1400. $query = qq|SELECT ct.name AS $vc, a.curr AS currency, a.${vc}_id,
  1401. current_date + ct.terms $DAYS AS duedate, a.department_id,
  1402. d.description AS department, ct.notes, ct.curr AS currency
  1403. FROM $arap a
  1404. JOIN $vc ct ON (a.${vc}_id = ct.id)
  1405. LEFT JOIN department d ON (a.department_id = d.id)
  1406. WHERE a.id = $trans_id|;
  1407. $sth = $dbh->prepare($query);
  1408. $sth->execute || $self->dberror($query);
  1409. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1410. for (keys %$ref) { $self->{$_} = $ref->{$_} }
  1411. $sth->finish;
  1412. }
  1413. sub current_date {
  1414. my ($self, $myconfig, $thisdate, $days) = @_;
  1415. my $dbh = $self->dbconnect($myconfig);
  1416. my $query;
  1417. $days *= 1;
  1418. if ($thisdate) {
  1419. my $dateformat = $myconfig->{dateformat};
  1420. if ($myconfig->{dateformat} !~ /^y/) {
  1421. my @a = split /\D/, $thisdate;
  1422. $dateformat .= "yy" if (length $a[2] > 2);
  1423. }
  1424. if ($thisdate !~ /\D/) {
  1425. $dateformat = 'yyyymmdd';
  1426. }
  1427. if ($myconfig->{dbdriver} eq 'DB2') {
  1428. $query = qq|SELECT date('$thisdate') + $days DAYS AS thisdate
  1429. FROM defaults|;
  1430. } else {
  1431. $query = qq|SELECT to_date('$thisdate', '$dateformat') + $days AS thisdate
  1432. FROM defaults|;
  1433. }
  1434. } else {
  1435. $query = qq|SELECT current_date AS thisdate
  1436. FROM defaults|;
  1437. }
  1438. ($thisdate) = $dbh->selectrow_array($query);
  1439. $dbh->disconnect;
  1440. $thisdate;
  1441. }
  1442. sub like {
  1443. my ($self, $str) = @_;
  1444. if ($str !~ /(%|_)/) {
  1445. if ($str =~ /(^").*("$)/) {
  1446. $str =~ s/(^"|"$)//g;
  1447. } else {
  1448. $str = "%$str%";
  1449. }
  1450. }
  1451. $str =~ s/'/''/g;
  1452. $str;
  1453. }
  1454. sub redo_rows {
  1455. my ($self, $flds, $new, $count, $numrows) = @_;
  1456. my @ndx = ();
  1457. for (1 .. $count) {
  1458. push @ndx, { num => $new->[$_-1]->{runningnumber}, ndx => $_ }
  1459. }
  1460. my $i = 0;
  1461. # fill rows
  1462. foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
  1463. $i++;
  1464. $j = $item->{ndx} - 1;
  1465. for (@{$flds}) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1466. }
  1467. # delete empty rows
  1468. for $i ($count + 1 .. $numrows) {
  1469. for (@{$flds}) { delete $self->{"${_}_$i"} }
  1470. }
  1471. }
  1472. sub get_partsgroup {
  1473. my ($self, $myconfig, $p) = @_;
  1474. my $dbh = $self->dbconnect($myconfig);
  1475. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1476. FROM partsgroup pg
  1477. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1478. my $where;
  1479. my $sortorder = "partsgroup";
  1480. if ($p->{searchitems} eq 'part') {
  1481. $where = qq| WHERE (p.inventory_accno_id > 0
  1482. AND p.income_accno_id > 0)|;
  1483. }
  1484. if ($p->{searchitems} eq 'service') {
  1485. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1486. }
  1487. if ($p->{searchitems} eq 'assembly') {
  1488. $where = qq| WHERE p.assembly = '1'|;
  1489. }
  1490. if ($p->{searchitems} eq 'labor') {
  1491. $where = qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1492. }
  1493. if ($p->{searchitems} eq 'nolabor') {
  1494. $where = qq| WHERE p.income_accno_id > 0|;
  1495. }
  1496. if ($p->{all}) {
  1497. $query = qq|SELECT id, partsgroup
  1498. FROM partsgroup|;
  1499. }
  1500. if ($p->{language_code}) {
  1501. $sortorder = "translation";
  1502. $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
  1503. t.description AS translation
  1504. FROM partsgroup pg
  1505. JOIN parts p ON (p.partsgroup_id = pg.id)
  1506. LEFT JOIN translation t ON (t.trans_id = pg.id AND t.language_code = '$p->{language_code}')|;
  1507. }
  1508. $query .= qq| $where ORDER BY $sortorder|;
  1509. my $sth = $dbh->prepare($query);
  1510. $sth->execute || $self->dberror($query);
  1511. $self->{all_partsgroup} = ();
  1512. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1513. push @{ $self->{all_partsgroup} }, $ref;
  1514. }
  1515. $sth->finish;
  1516. $dbh->disconnect;
  1517. }
  1518. sub update_status {
  1519. my ($self, $myconfig) = @_;
  1520. # no id return
  1521. return unless $self->{id};
  1522. my $dbh = $self->dbconnect_noauto($myconfig);
  1523. my %queued = split / +/, $self->{queued};
  1524. my $spoolfile = ($queued{$self->{formname}}) ? "'$queued{$self->{formname}}'" : 'NULL';
  1525. my $query = qq|DELETE FROM status
  1526. WHERE formname = '$self->{formname}'
  1527. AND trans_id = $self->{id}|;
  1528. $dbh->do($query) || $self->dberror($query);
  1529. my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
  1530. my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
  1531. $query = qq|INSERT INTO status (trans_id, printed, emailed,
  1532. spoolfile, formname)
  1533. VALUES ($self->{id}, '$printed',
  1534. '$emailed', $spoolfile,
  1535. '$self->{formname}')|;
  1536. $dbh->do($query) || $self->dberror($query);
  1537. $dbh->commit;
  1538. $dbh->disconnect;
  1539. }
  1540. sub save_status {
  1541. my ($self, $dbh) = @_;
  1542. my $formnames = $self->{printed};
  1543. my $emailforms = $self->{emailed};
  1544. my $query = qq|DELETE FROM status
  1545. WHERE trans_id = $self->{id}|;
  1546. $dbh->do($query) || $self->dberror($query);
  1547. my %queued;
  1548. my $formname;
  1549. if ($self->{queued}) {
  1550. %queued = split / +/, $self->{queued};
  1551. foreach $formname (keys %queued) {
  1552. $printed = ($self->{printed} =~ /$formname/) ? "1" : "0";
  1553. $emailed = ($self->{emailed} =~ /$formname/) ? "1" : "0";
  1554. if ($queued{$formname}) {
  1555. $query = qq|INSERT INTO status (trans_id, printed, emailed,
  1556. spoolfile, formname)
  1557. VALUES ($self->{id}, '$printed', '$emailed',
  1558. '$queued{$formname}', '$formname')|;
  1559. $dbh->do($query) || $self->dberror($query);
  1560. }
  1561. $formnames =~ s/$formname//;
  1562. $emailforms =~ s/$formname//;
  1563. }
  1564. }
  1565. # save printed, emailed info
  1566. $formnames =~ s/^ +//g;
  1567. $emailforms =~ s/^ +//g;
  1568. my %status = ();
  1569. for (split / +/, $formnames) { $status{$_}{printed} = 1 }
  1570. for (split / +/, $emailforms) { $status{$_}{emailed} = 1 }
  1571. foreach my $formname (keys %status) {
  1572. $printed = ($formnames =~ /$self->{formname}/) ? "1" : "0";
  1573. $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
  1574. $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
  1575. VALUES ($self->{id}, '$printed', '$emailed', '$formname')|;
  1576. $dbh->do($query) || $self->dberror($query);
  1577. }
  1578. }
  1579. sub get_recurring {
  1580. my ($self, $dbh) = @_;
  1581. my $query = qq/SELECT s.*, se.formname || ':' || se.format AS emaila,
  1582. se.message,
  1583. sp.formname || ':' || sp.format || ':' || sp.printer AS printa
  1584. FROM recurring s
  1585. LEFT JOIN recurringemail se ON (s.id = se.id)
  1586. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  1587. WHERE s.id = $self->{id}/;
  1588. my $sth = $dbh->prepare($query);
  1589. $sth->execute || $form->dberror($query);
  1590. for (qw(email print)) { $self->{"recurring$_"} = "" }
  1591. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1592. for (keys %$ref) { $self->{"recurring$_"} = $ref->{$_} }
  1593. $self->{recurringemail} .= "$ref->{emaila}:";
  1594. $self->{recurringprint} .= "$ref->{printa}:";
  1595. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  1596. }
  1597. $sth->finish;
  1598. chop $self->{recurringemail};
  1599. chop $self->{recurringprint};
  1600. if ($self->{recurringstartdate}) {
  1601. $self->{recurringreference} = $self->escape($self->{recurringreference},1);
  1602. $self->{recurringmessage} = $self->escape($self->{recurringmessage},1);
  1603. for (qw(reference startdate repeat unit howmany
  1604. payment print email message)) {
  1605. $self->{recurring} .= qq|$self->{"recurring$_"},|
  1606. }
  1607. chop $self->{recurring};
  1608. }
  1609. }
  1610. sub save_recurring {
  1611. my ($self, $dbh, $myconfig) = @_;
  1612. my $disconnect = 0;
  1613. if (! $dbh) {
  1614. $dbh = $self->dbconnect_noauto($myconfig);
  1615. $disconnect = 1;
  1616. }
  1617. my $query;
  1618. $query = qq|DELETE FROM recurring
  1619. WHERE id = $self->{id}|;
  1620. $dbh->do($query) || $self->dberror($query);
  1621. $query = qq|DELETE FROM recurringemail
  1622. WHERE id = $self->{id}|;
  1623. $dbh->do($query) || $self->dberror($query);
  1624. $query = qq|DELETE FROM recurringprint
  1625. WHERE id = $self->{id}|;
  1626. $dbh->do($query) || $self->dberror($query);
  1627. if ($self->{recurring}) {
  1628. my %s = ();
  1629. ($s{reference}, $s{startdate}, $s{repeat}, $s{unit}, $s{howmany},
  1630. $s{payment}, $s{print}, $s{email}, $s{message}) = split /,/, $self->{recurring};
  1631. for (qw(reference message)) { $s{$_} = $self->unescape($s{$_}) }
  1632. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  1633. # calculate enddate
  1634. my $advance = $s{repeat} * ($s{howmany} - 1);
  1635. my %interval = ( 'Pg' => "(date '$s{startdate}' + interval '$advance $s{unit}')",
  1636. 'DB2' => qq|(date ('$s{startdate}') + "$advance $s{unit}")|, );
  1637. $interval{Oracle} = $interval{PgPP} = $interval{Pg};
  1638. $query = qq|SELECT $interval{$myconfig->{dbdriver}}
  1639. FROM defaults|;
  1640. my ($enddate) = $dbh->selectrow_array($query);
  1641. # calculate nextdate
  1642. $query = qq|SELECT current_date - date '$s{startdate}' AS a,
  1643. date '$enddate' - current_date AS b
  1644. FROM defaults|;
  1645. my ($a, $b) = $dbh->selectrow_array($query);
  1646. if ($a + $b) {
  1647. $advance = int(($a / ($a + $b)) * ($s{howmany} - 1) + 1) * $s{repeat};
  1648. } else {
  1649. $advance = 0;
  1650. }
  1651. my $nextdate = $enddate;
  1652. if ($advance > 0) {
  1653. if ($advance < ($s{repeat} * $s{howmany})) {
  1654. %interval = ( 'Pg' => "(date '$s{startdate}' + interval '$advance $s{unit}')",
  1655. 'DB2' => qq|(date ('$s{startdate}') + "$advance $s{unit}")|,);
  1656. $interval{Oracle} = $interval{PgPP} = $interval{Pg};
  1657. $query = qq|SELECT $interval{$myconfig->{dbdriver}}
  1658. FROM defaults|;
  1659. ($nextdate) = $dbh->selectrow_array($query);
  1660. }
  1661. } else {
  1662. $nextdate = $s{startdate};
  1663. }
  1664. if ($self->{recurringnextdate}) {
  1665. $nextdate = $self->{recurringnextdate};
  1666. $query = qq|SELECT '$enddate' - date '$nextdate'
  1667. FROM defaults|;
  1668. if ($dbh->selectrow_array($query) < 0) {
  1669. undef $nextdate;
  1670. }
  1671. }
  1672. $self->{recurringpayment} *= 1;
  1673. $query = qq|INSERT INTO recurring (id, reference, startdate, enddate,
  1674. nextdate, repeat, unit, howmany, payment)
  1675. VALUES ($self->{id}, |.$dbh->quote($s{reference}).qq|,
  1676. '$s{startdate}', '$enddate', |.
  1677. $self->dbquote($nextdate, SQL_DATE).
  1678. qq|, $s{repeat}, '$s{unit}', $s{howmany}, '$s{payment}')|;
  1679. $dbh->do($query) || $self->dberror($query);
  1680. my @p;
  1681. my $p;
  1682. my $i;
  1683. my $sth;
  1684. if ($s{email}) {
  1685. # formname:format
  1686. @p = split /:/, $s{email};
  1687. $query = qq|INSERT INTO recurringemail (id, formname, format, message)
  1688. VALUES ($self->{id}, ?, ?, ?)|;
  1689. $sth = $dbh->prepare($query) || $self->dberror($query);
  1690. for ($i = 0; $i <= $#p; $i += 2) {
  1691. $sth->execute($p[$i], $p[$i+1], $s{message});
  1692. }
  1693. $sth->finish;
  1694. }
  1695. if ($s{print}) {
  1696. # formname:format:printer
  1697. @p = split /:/, $s{print};
  1698. $query = qq|INSERT INTO recurringprint (id, formname, format, printer)
  1699. VALUES ($self->{id}, ?, ?, ?)|;
  1700. $sth = $dbh->prepare($query) || $self->dberror($query);
  1701. for ($i = 0; $i <= $#p; $i += 3) {
  1702. $p = ($p[$i+2]) ? $p[$i+2] : "";
  1703. $sth->execute($p[$i], $p[$i+1], $p);
  1704. }
  1705. $sth->finish;
  1706. }
  1707. }
  1708. if ($disconnect) {
  1709. $dbh->commit;
  1710. $dbh->disconnect;
  1711. }
  1712. }
  1713. sub save_intnotes {
  1714. my ($self, $myconfig, $vc) = @_;
  1715. # no id return
  1716. return unless $self->{id};
  1717. my $dbh = $self->dbconnect($myconfig);
  1718. my $query = qq|UPDATE $vc
  1719. SET intnotes = |.$dbh->quote($self->{intnotes}).qq|
  1720. WHERE id = $self->{id}|;
  1721. $dbh->do($query) || $self->dberror($query);
  1722. $dbh->disconnect;
  1723. }
  1724. sub update_defaults {
  1725. my ($self, $myconfig, $fld, $dbh) = @_;
  1726. my $closedb;
  1727. if (! $dbh) {
  1728. $dbh = $self->dbconnect_noauto($myconfig);
  1729. $closedb = 1;
  1730. }
  1731. my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
  1732. ($_) = $dbh->selectrow_array($query);
  1733. $_ = "0" unless $_;
  1734. # check for and replace
  1735. # <%DATE%>, <%YYMMDD%>, <%YEAR%>, <%MONTH%>, <%DAY%> or variations of
  1736. # <%NAME 1 1 3%>, <%BUSINESS%>, <%BUSINESS 10%>, <%CURR...%>
  1737. # <%DESCRIPTION 1 1 3%>, <%ITEM 1 1 3%>, <%PARTSGROUP 1 1 3%> only for parts
  1738. # <%PHONE%> for customer and vendors
  1739. my $num = $_;
  1740. $num =~ s/.*?<%.*?%>//g;
  1741. ($num) = $num =~ /(\d+)/;
  1742. if (defined $num) {
  1743. my $incnum;
  1744. # if we have leading zeros check how long it is
  1745. if ($num =~ /^0/) {
  1746. my $l = length $num;
  1747. $incnum = $num + 1;
  1748. $l -= length $incnum;
  1749. # pad it out with zeros
  1750. my $padzero = "0" x $l;
  1751. $incnum = ("0" x $l) . $incnum;
  1752. } else {
  1753. $incnum = $num + 1;
  1754. }
  1755. s/$num/$incnum/;
  1756. }
  1757. my $dbvar = $_;
  1758. my $var = $_;
  1759. my $str;
  1760. my $param;
  1761. if (/<%/) {
  1762. while (/<%/) {
  1763. s/<%.*?%>//;
  1764. last unless $&;
  1765. $param = $&;
  1766. $str = "";
  1767. if ($param =~ /<%date%>/i) {
  1768. $str = ($self->split_date($myconfig->{dateformat}, $self->{transdate}))[0];
  1769. $var =~ s/$param/$str/;
  1770. }
  1771. if ($param =~ /<%(name|business|description|item|partsgroup|phone|custom)/i) {
  1772. my $fld = lc $&;
  1773. $fld =~ s/<%//;
  1774. if ($fld =~ /name/) {
  1775. if ($self->{type}) {
  1776. $fld = $self->{vc};
  1777. }
  1778. }
  1779. my $p = $param;
  1780. $p =~ s/(<|>|%)//g;
  1781. my @p = split / /, $p;
  1782. my @n = split / /, uc $self->{$fld};
  1783. if ($#p > 0) {
  1784. for (my $i = 1; $i <= $#p; $i++) {
  1785. $str .= substr($n[$i-1], 0, $p[$i]);
  1786. }
  1787. } else {
  1788. ($str) = split /--/, $self->{$fld};
  1789. }
  1790. $var =~ s/$param/$str/;
  1791. $var =~ s/\W//g if $fld eq 'phone';
  1792. }
  1793. if ($param =~ /<%(yy|mm|dd)/i) {
  1794. my $p = $param;
  1795. $p =~ s/(<|>|%)//g;
  1796. my $spc = $p;
  1797. $spc =~ s/\w//g;
  1798. $spc = substr($spc, 0, 1);
  1799. my %d = ( yy => 1, mm => 2, dd => 3 );
  1800. my @p = ();
  1801. my @a = $self->split_date($myconfig->{dateformat}, $self->{transdate});
  1802. for (sort keys %d) { push @p, $a[$d{$_}] if ($p =~ /$_/) }
  1803. $str = join $spc, @p;
  1804. $var =~ s/$param/$str/;
  1805. }
  1806. if ($param =~ /<%curr/i) {
  1807. $var =~ s/$param/$self->{currency}/;
  1808. }
  1809. }
  1810. }
  1811. $query = qq|UPDATE defaults
  1812. SET $fld = '$dbvar'|;
  1813. $dbh->do($query) || $form->dberror($query);
  1814. if ($closedb) {
  1815. $dbh->commit;
  1816. $dbh->disconnect;
  1817. }
  1818. $var;
  1819. }
  1820. sub split_date {
  1821. my ($self, $dateformat, $date) = @_;
  1822. my @d = localtime;
  1823. my $mm;
  1824. my $dd;
  1825. my $yy;
  1826. my $rv;
  1827. if (! $date) {
  1828. $dd = $d[3];
  1829. $mm = ++$d[4];
  1830. $yy = substr($d[5],-2);
  1831. $mm = substr("0$mm", -2);
  1832. $dd = substr("0$dd", -2);
  1833. }
  1834. if ($dateformat =~ /^yy/) {
  1835. if ($date) {
  1836. if ($date =~ /\D/) {
  1837. ($yy, $mm, $dd) = split /\D/, $date;
  1838. $mm *= 1;
  1839. $dd *= 1;
  1840. $mm = substr("0$mm", -2);
  1841. $dd = substr("0$dd", -2);
  1842. $yy = substr($yy, -2);
  1843. $rv = "$yy$mm$dd";
  1844. } else {
  1845. $rv = $date;
  1846. }
  1847. } else {
  1848. $rv = "$yy$mm$dd";
  1849. }
  1850. }
  1851. if ($dateformat =~ /^mm/) {
  1852. if ($date) {
  1853. if ($date =~ /\D/) {
  1854. ($mm, $dd, $yy) = split /\D/, $date;
  1855. $mm *= 1;
  1856. $dd *= 1;
  1857. $mm = substr("0$mm", -2);
  1858. $dd = substr("0$dd", -2);
  1859. $yy = substr($yy, -2);
  1860. $rv = "$mm$dd$yy";
  1861. } else {
  1862. $rv = $date;
  1863. }
  1864. } else {
  1865. $rv = "$mm$dd$yy";
  1866. }
  1867. }
  1868. if ($dateformat =~ /^dd/) {
  1869. if ($date) {
  1870. if ($date =~ /\D/) {
  1871. ($dd, $mm, $yy) = split /\D/, $date;
  1872. $mm *= 1;
  1873. $dd *= 1;
  1874. $mm = substr("0$mm", -2);
  1875. $dd = substr("0$dd", -2);
  1876. $yy = substr($yy, -2);
  1877. $rv = "$dd$mm$yy";
  1878. } else {
  1879. $rv = $date;
  1880. }
  1881. } else {
  1882. $rv = "$dd$mm$yy";
  1883. }
  1884. }
  1885. ($rv, $yy, $mm, $dd);
  1886. }
  1887. sub from_to {
  1888. my ($self, $yy, $mm, $interval) = @_;
  1889. use Time::Local;
  1890. my @t;
  1891. my $dd = 1;
  1892. my $fromdate = "$yy${mm}01";
  1893. my $bd = 1;
  1894. if (defined $interval) {
  1895. if ($interval == 12) {
  1896. $yy++;
  1897. } else {
  1898. if (($mm += $interval) > 12) {
  1899. $mm -= 12;
  1900. $yy++;
  1901. }
  1902. if ($interval == 0) {
  1903. @t = localtime(time);
  1904. $dd = $t[3];
  1905. $mm = $t[4] + 1;
  1906. $yy = $t[5] + 1900;
  1907. $bd = 0;
  1908. }
  1909. }
  1910. } else {
  1911. if (++$mm > 12) {
  1912. $mm -= 12;
  1913. $yy++;
  1914. }
  1915. }
  1916. $mm--;
  1917. @t = localtime(timelocal(0,0,0,$dd,$mm,$yy) - $bd);
  1918. $t[4]++;
  1919. $t[4] = substr("0$t[4]",-2);
  1920. $t[3] = substr("0$t[3]",-2);
  1921. $t[5] += 1900;
  1922. ($fromdate, "$t[5]$t[4]$t[3]");
  1923. }
  1924. sub audittrail {
  1925. my ($self, $dbh, $myconfig, $audittrail) = @_;
  1926. # table, $reference, $formname, $action, $id, $transdate) = @_;
  1927. my $query;
  1928. my $rv;
  1929. my $disconnect;
  1930. if (! $dbh) {
  1931. $dbh = $self->dbconnect($myconfig);
  1932. $disconnect = 1;
  1933. }
  1934. # if we have an id add audittrail, otherwise get a new timestamp
  1935. if ($audittrail->{id}) {
  1936. $query = qq|SELECT audittrail FROM defaults|;
  1937. if ($dbh->selectrow_array($query)) {
  1938. my ($null, $employee_id) = $self->get_employee($dbh);
  1939. if ($self->{audittrail} && !$myconfig) {
  1940. chop $self->{audittrail};
  1941. my @a = split /\|/, $self->{audittrail};
  1942. my %newtrail = ();
  1943. my $key;
  1944. my $i;
  1945. my @flds = qw(tablename reference formname action transdate);
  1946. # put into hash and remove dups
  1947. while (@a) {
  1948. $key = "$a[2]$a[3]";
  1949. $i = 0;
  1950. $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
  1951. splice @a, 0, 5;
  1952. }
  1953. $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
  1954. formname, action, employee_id, transdate)
  1955. VALUES ($audittrail->{id}, ?, ?, ?, ?, $employee_id, ?)|;
  1956. my $sth = $dbh->prepare($query) || $self->dberror($query);
  1957. foreach $key (sort { $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate} } keys %newtrail) {
  1958. $i = 1;
  1959. for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
  1960. $sth->execute || $self->dberror;
  1961. $sth->finish;
  1962. }
  1963. }
  1964. if ($audittrail->{transdate}) {
  1965. $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
  1966. formname, action, employee_id, transdate)
  1967. VALUES ($audittrail->{id}, '$audittrail->{tablename}', |
  1968. .$dbh->quote($audittrail->{reference}).qq|',
  1969. '$audittrail->{formname}', '$audittrail->{action}',
  1970. $employee_id, '$audittrail->{transdate}')|;
  1971. } else {
  1972. $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
  1973. formname, action, employee_id)
  1974. VALUES ($audittrail->{id},
  1975. '$audittrail->{tablename}', |
  1976. .$dbh->quote($audittrail->{reference}).qq|,
  1977. '$audittrail->{formname}', '$audittrail->{action}',
  1978. $employee_id)|;
  1979. }
  1980. $dbh->do($query);
  1981. }
  1982. } else {
  1983. $query = qq|SELECT current_timestamp FROM defaults|;
  1984. my ($timestamp) = $dbh->selectrow_array($query);
  1985. $rv = "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  1986. }
  1987. $dbh->disconnect if $disconnect;
  1988. $rv;
  1989. }
  1990. package Locale;
  1991. sub new {
  1992. my ($type, $country, $NLS_file) = @_;
  1993. my $self = {};
  1994. %self = ();
  1995. if ($country && -d "locale/$country") {
  1996. $self->{countrycode} = $country;
  1997. eval { require "locale/$country/$NLS_file"; };
  1998. }
  1999. $self->{NLS_file} = $NLS_file;
  2000. $self->{charset} = $self{charset};
  2001. push @{ $self->{LONG_MONTH} }, ("January", "February", "March", "April", "May ", "June", "July", "August", "September", "October", "November", "December");
  2002. push @{ $self->{SHORT_MONTH} }, (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec));
  2003. bless $self, $type;
  2004. }
  2005. sub text {
  2006. my ($self, $text) = @_;
  2007. return (exists $self{texts}{$text}) ? $self{texts}{$text} : $text;
  2008. }
  2009. sub findsub {
  2010. my ($self, $text) = @_;
  2011. if (exists $self{subs}{$text}) {
  2012. $text = $self{subs}{$text};
  2013. } else {
  2014. if ($self->{countrycode} && $self->{NLS_file}) {
  2015. Form->error("$text not defined in locale/$self->{countrycode}/$self->{NLS_file}");
  2016. }
  2017. }
  2018. $text;
  2019. }
  2020. sub date {
  2021. my ($self, $myconfig, $date, $longformat) = @_;
  2022. my $longdate = "";
  2023. my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
  2024. if ($date) {
  2025. # get separator
  2026. $spc = $myconfig->{dateformat};
  2027. $spc =~ s/\w//g;
  2028. $spc = substr($spc, 0, 1);
  2029. if ($date =~ /\D/) {
  2030. if ($myconfig->{dateformat} =~ /^yy/) {
  2031. ($yy, $mm, $dd) = split /\D/, $date;
  2032. }
  2033. if ($myconfig->{dateformat} =~ /^mm/) {
  2034. ($mm, $dd, $yy) = split /\D/, $date;
  2035. }
  2036. if ($myconfig->{dateformat} =~ /^dd/) {
  2037. ($dd, $mm, $yy) = split /\D/, $date;
  2038. }
  2039. } else {
  2040. $date = substr($date, 2);
  2041. ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
  2042. }
  2043. $dd *= 1;
  2044. $mm--;
  2045. $yy += 2000 if length $yy == 2;
  2046. if ($myconfig->{dateformat} =~ /^dd/) {
  2047. $mm++;
  2048. $dd = substr("0$dd", -2);
  2049. $mm = substr("0$mm", -2);
  2050. $longdate = "$dd$spc$mm$spc$yy";
  2051. if (defined $longformat) {
  2052. $longdate = "$dd";
  2053. $longdate .= ($spc eq '.') ? ". " : " ";
  2054. $longdate .= &text($self, $self->{$longmonth}[--$mm])." $yy";
  2055. }
  2056. } elsif ($myconfig->{dateformat} =~ /^yy/) {
  2057. $mm++;
  2058. $dd = substr("0$dd", -2);
  2059. $mm = substr("0$mm", -2);
  2060. $longdate = "$yy$spc$mm$spc$dd";
  2061. if (defined $longformat) {
  2062. $longdate = &text($self, $self->{$longmonth}[--$mm])." $dd $yy";
  2063. }
  2064. } else {
  2065. $mm++;
  2066. $dd = substr("0$dd", -2);
  2067. $mm = substr("0$mm", -2);
  2068. $longdate = "$mm$spc$dd$spc$yy";
  2069. if (defined $longformat) {
  2070. $longdate = &text($self, $self->{$longmonth}[--$mm])." $dd $yy";
  2071. }
  2072. }
  2073. }
  2074. $longdate;
  2075. }
  2076. 1;