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