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