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