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