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