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