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