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