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