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