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