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