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