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