summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: b8a23b011e7b7ab0841024b635bfab989c728575 (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. my $yy;
  1032. my $mm;
  1033. my $dd;
  1034. $spc =~ s/\w//g;
  1035. $spc = substr( $spc, 0, 1 );
  1036. if ($date) {
  1037. if ( $date =~ /\D/ ) {
  1038. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1039. ( $yy, $mm, $dd ) = split /\D/, $date;
  1040. }
  1041. if ( $myconfig->{dateformat} =~ /^mm/ ) {
  1042. ( $mm, $dd, $yy ) = split /\D/, $date;
  1043. }
  1044. if ( $myconfig->{dateformat} =~ /^dd/ ) {
  1045. ( $dd, $mm, $yy ) = split /\D/, $date;
  1046. }
  1047. }
  1048. else {
  1049. # ISO
  1050. ( $yy, $mm, $dd ) = ($date =~ /(....)(..)(..)/);
  1051. }
  1052. if ( $unit eq 'days' ) {
  1053. $diff = $repeat * 86400;
  1054. }
  1055. if ( $unit eq 'weeks' ) {
  1056. $diff = $repeat * 604800;
  1057. }
  1058. if ( $unit eq 'months' ) {
  1059. $diff = $mm + $repeat;
  1060. my $whole = int( $diff / 12 );
  1061. $yy += $whole;
  1062. $mm = ( $diff % 12 );
  1063. $mm = '12' if $mm == 0;
  1064. $yy-- if $mm == 12;
  1065. $diff = 0;
  1066. }
  1067. if ( $unit eq 'years' ) {
  1068. $yy += $repeat;
  1069. }
  1070. $mm--;
  1071. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yy ) + $diff );
  1072. $t[4]++;
  1073. $mm = substr( "0$t[4]", -2 );
  1074. $dd = substr( "0$t[3]", -2 );
  1075. $yy = $t[5] + 1900;
  1076. if ( $date =~ /\D/ ) {
  1077. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1078. $date = "$yy$spc$mm$spc$dd";
  1079. }
  1080. if ( $myconfig->{dateformat} =~ /^mm/ ) {
  1081. $date = "$mm$spc$dd$spc$yy";
  1082. }
  1083. if ( $myconfig->{dateformat} =~ /^dd/ ) {
  1084. $date = "$dd$spc$mm$spc$yy";
  1085. }
  1086. }
  1087. else {
  1088. $date = "$yy$mm$dd";
  1089. }
  1090. }
  1091. $date;
  1092. }
  1093. sub print_button {
  1094. my ( $self, $button, $name ) = @_;
  1095. print
  1096. 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|;
  1097. }
  1098. # Database routines used throughout
  1099. sub db_init {
  1100. my ( $self, $myconfig ) = @_;
  1101. $self->{dbh} = $self->dbconnect_noauto($myconfig) || $self->dberror();
  1102. %date_query = (
  1103. 'mm/dd/yy' => 'set DateStyle to \'SQL, US\'',
  1104. 'mm-dd-yy' => 'set DateStyle to \'POSTGRES, US\'',
  1105. 'dd/mm/yy' => 'set DateStyle to \'SQL, EUROPEAN\'',
  1106. 'dd-mm-yy' => 'set DateStyle to \'POSTGRES, EUROPEAN\'',
  1107. 'dd.mm.yy' => 'set DateStyle to \'GERMAN\''
  1108. );
  1109. $self->{dbh}->do( $date_query{ $myconfig->{dateformat} } );
  1110. $self->{db_dateformat} = $myconfig->{dateformat}; #shim
  1111. my $query = "SELECT t.extends,
  1112. coalesce (t.table_name, 'custom_' || extends)
  1113. || ':' || f.field_name as field_def
  1114. FROM custom_table_catalog t
  1115. JOIN custom_field_catalog f USING (table_id)";
  1116. my $sth = $self->{dbh}->prepare($query);
  1117. $sth->execute;
  1118. my $ref;
  1119. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1120. push @{ $self->{custom_db_fields}{ $ref->{extends} } },
  1121. $ref->{field_def};
  1122. }
  1123. }
  1124. sub run_custom_queries {
  1125. my ( $self, $tablename, $query_type, $linenum ) = @_;
  1126. my $dbh = $self->{dbh};
  1127. if ( $query_type !~ /^(select|insert|update)$/i ) {
  1128. $self->error(
  1129. $locale->text(
  1130. "Passed incorrect query type to run_custom_queries."
  1131. )
  1132. );
  1133. }
  1134. my @rc;
  1135. my %temphash;
  1136. my @templist;
  1137. my @elements;
  1138. my $query;
  1139. my $ins_values;
  1140. if ($linenum) {
  1141. $linenum = "_$linenum";
  1142. }
  1143. $query_type = uc($query_type);
  1144. for ( @{ $self->{custom_db_fields}{$tablename} } ) {
  1145. @elements = split( /:/, $_ );
  1146. push @{ $temphash{ $elements[0] } }, $elements[1];
  1147. }
  1148. for ( keys %temphash ) {
  1149. my @data;
  1150. my $ins_values;
  1151. $query = "$query_type ";
  1152. if ( $query_type eq 'UPDATE' ) {
  1153. $query = "DELETE FROM $_ WHERE row_id = ?";
  1154. my $sth = $dbh->prepare($query);
  1155. $sth->execute->( $self->{ "id" . "$linenum" } )
  1156. || $self->dberror($query);
  1157. }
  1158. elsif ( $query_type eq 'INSERT' ) {
  1159. $query .= " INTO $_ (";
  1160. }
  1161. my $first = 1;
  1162. for ( @{ $temphash{$_} } ) {
  1163. $query .= "$_";
  1164. if ( $query_type eq 'UPDATE' ) {
  1165. $query .= '= ?';
  1166. }
  1167. $ins_values .= "?, ";
  1168. $query .= ", ";
  1169. $first = 0;
  1170. if ( $query_type eq 'UPDATE' or $query_type eq 'INSERT' ) {
  1171. push @data, $self->{"$_$linenum"};
  1172. }
  1173. }
  1174. if ( $query_type ne 'INSERT' ) {
  1175. $query =~ s/, $//;
  1176. }
  1177. if ( $query_type eq 'SELECT' ) {
  1178. $query .= " FROM $_";
  1179. }
  1180. if ( $query_type eq 'SELECT' or $query_type eq 'UPDATE' ) {
  1181. $query .= " WHERE row_id = ?";
  1182. }
  1183. if ( $query_type eq 'INSERT' ) {
  1184. $query .= " row_id) VALUES ($ins_values ?)";
  1185. }
  1186. if ( $query_type eq 'SELECT' ) {
  1187. push @rc, [$query];
  1188. }
  1189. else {
  1190. unshift( @data, $query );
  1191. push @rc, [@data];
  1192. }
  1193. }
  1194. if ( $query_type eq 'INSERT' ) {
  1195. for (@rc) {
  1196. $query = shift( @{$_} );
  1197. $sth = $dbh->prepare($query)
  1198. || $self->db_error($query);
  1199. $sth->execute( @{$_}, $self->{id} )
  1200. || $self->dberror($query);
  1201. $sth->finish;
  1202. $did_insert = 1;
  1203. }
  1204. }
  1205. elsif ( $query_type eq 'UPDATE' ) {
  1206. @rc = $self->run_custom_queries( $tablename, 'INSERT', $linenum );
  1207. }
  1208. elsif ( $query_type eq 'SELECT' ) {
  1209. for (@rc) {
  1210. $query = shift @{$_};
  1211. $sth = $self->{dbh}->prepare($query);
  1212. $sth->execute( $self->{id} );
  1213. $ref = $sth->fetchrow_hashref(NAME_lc);
  1214. for ( keys %{$ref} ) {
  1215. $self->{$_} = $ref->{$_};
  1216. }
  1217. }
  1218. }
  1219. @rc;
  1220. }
  1221. sub dbconnect {
  1222. my ( $self, $myconfig ) = @_;
  1223. # connect to database
  1224. my $dbh = DBI->connect( $myconfig->{dbconnect},
  1225. $myconfig->{dbuser}, $myconfig->{dbpasswd} )
  1226. or $self->dberror;
  1227. $dbh->{pg_enable_utf8} = 1;
  1228. # set db options
  1229. if ( $myconfig->{dboptions} ) {
  1230. $dbh->do( $myconfig->{dboptions} )
  1231. || $self->dberror( $myconfig->{dboptions} );
  1232. }
  1233. $dbh;
  1234. }
  1235. sub dbconnect_noauto {
  1236. my ( $self, $myconfig ) = @_;
  1237. # connect to database
  1238. $dbh = DBI->connect(
  1239. $myconfig->{dbconnect}, $myconfig->{dbuser},
  1240. $myconfig->{dbpasswd}, { AutoCommit => 0 }
  1241. ) or $self->dberror;
  1242. $dbh->{pg_enable_utf8} = 1;
  1243. # set db options
  1244. if ( $myconfig->{dboptions} ) {
  1245. $dbh->do( $myconfig->{dboptions} );
  1246. }
  1247. $dbh;
  1248. }
  1249. sub dbquote {
  1250. my ( $self, $var ) = @_;
  1251. if ( $var eq '' ) {
  1252. $_ = "NULL";
  1253. }
  1254. else {
  1255. $_ = $self->{dbh}->quote($var);
  1256. }
  1257. $_;
  1258. }
  1259. sub update_balance {
  1260. # This is a dangerous private function. All apps calling it must
  1261. # be careful to avoid SQL injection issues
  1262. my ( $self, $dbh, $table, $field, $where, $value ) = @_;
  1263. # if we have a value, go do it
  1264. if ($value) {
  1265. # retrieve balance from table
  1266. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  1267. my ($balance) = $dbh->selectrow_array($query);
  1268. $balance += $value;
  1269. # update balance
  1270. $query = "UPDATE $table SET $field = $balance WHERE $where";
  1271. $dbh->do($query) || $self->dberror($query);
  1272. }
  1273. }
  1274. sub update_exchangerate {
  1275. my ( $self, $dbh, $curr, $transdate, $buy, $sell ) = @_;
  1276. # some sanity check for currency
  1277. return if ( $curr eq "" );
  1278. my $query = qq|
  1279. SELECT curr
  1280. FROM exchangerate
  1281. WHERE curr = ?
  1282. AND transdate = ?
  1283. FOR UPDATE|;
  1284. my $sth = $self->{dbh}->prepare($query);
  1285. $sth->execute( $curr, $transdate ) || $self->dberror($query);
  1286. my $set;
  1287. my @queryargs;
  1288. if ( $buy && $sell ) {
  1289. $set = "buy = ?, sell = ?";
  1290. @queryargs = ( $buy, $sell );
  1291. }
  1292. elsif ($buy) {
  1293. $set = "buy = ?";
  1294. @queryargs = ($buy);
  1295. }
  1296. elsif ($sell) {
  1297. $set = "sell = ?";
  1298. @queryargs = ($sell);
  1299. }
  1300. if ( !$set ) {
  1301. $self->error("Exchange rate missing!");
  1302. }
  1303. if ( $sth->fetchrow_array ) {
  1304. $query = qq|UPDATE exchangerate
  1305. SET $set
  1306. WHERE curr = ?
  1307. AND transdate = ?|;
  1308. push( @queryargs, $curr, $transdate );
  1309. }
  1310. else {
  1311. $query = qq|
  1312. INSERT INTO exchangerate (
  1313. curr, buy, sell, transdate)
  1314. VALUES (?, ?, ?, ?)|;
  1315. @queryargs = ( $curr, $buy, $sell, $transdate );
  1316. }
  1317. $sth->finish;
  1318. $sth = $self->{dbh}->prepare($query);
  1319. $sth->execute(@queryargs) || $self->dberror($query);
  1320. }
  1321. sub save_exchangerate {
  1322. my ( $self, $myconfig, $currency, $transdate, $rate, $fld ) = @_;
  1323. my ( $buy, $sell ) = ( 0, 0 );
  1324. $buy = $rate if $fld eq 'buy';
  1325. $sell = $rate if $fld eq 'sell';
  1326. $self->update_exchangerate( $self->{dbh}, $currency, $transdate, $buy,
  1327. $sell );
  1328. $dbh->commit;
  1329. }
  1330. sub get_exchangerate {
  1331. my ( $self, $dbh, $curr, $transdate, $fld ) = @_;
  1332. my $exchangerate = 1;
  1333. if ($transdate) {
  1334. my $query = qq|
  1335. SELECT $fld FROM exchangerate
  1336. WHERE curr = ? AND transdate = ?|;
  1337. $sth = $self->{dbh}->prepare($query);
  1338. $sth->execute( $curr, $transdate );
  1339. ($exchangerate) = $sth->fetchrow_array;
  1340. $exchangerate = Math::BigFloat->new($exchangerate);
  1341. }
  1342. $sth->finish;
  1343. $self->{dbh}->commit;
  1344. $exchangerate;
  1345. }
  1346. sub check_exchangerate {
  1347. my ( $self, $myconfig, $currency, $transdate, $fld ) = @_;
  1348. return "" unless $transdate;
  1349. my $query = qq|
  1350. SELECT $fld
  1351. FROM exchangerate
  1352. WHERE curr = ? AND transdate = ?|;
  1353. my $sth = $self->{dbh}->prepare($query);
  1354. $sth->execute( $currenct, $transdate );
  1355. my ($exchangerate) = $sth->fetchrow_array;
  1356. $sth->finish;
  1357. $self->{dbh}->commit;
  1358. $exchangerate;
  1359. }
  1360. sub add_shipto {
  1361. my ( $self, $dbh, $id ) = @_;
  1362. my $shipto;
  1363. foreach my $item (
  1364. qw(name address1 address2 city state
  1365. zipcode country contact phone fax email)
  1366. )
  1367. {
  1368. if ( $self->{"shipto$item"} ne "" ) {
  1369. $shipto = 1 if ( $self->{$item} ne $self->{"shipto$item"} );
  1370. }
  1371. }
  1372. if ($shipto) {
  1373. my $query = qq|
  1374. INSERT INTO shipto
  1375. (trans_id, shiptoname, shiptoaddress1,
  1376. shiptoaddress2, shiptocity, shiptostate,
  1377. shiptozipcode, shiptocountry, shiptocontact,
  1378. shiptophone, shiptofax, shiptoemail)
  1379. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1380. |;
  1381. $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  1382. $sth->execute(
  1383. $id, $self->{shiptoname},
  1384. $self->{shiptoaddress1}, $self->{shiptoaddress2},
  1385. $self->{shiptocity}, $self->{shiptostate},
  1386. $self->{shiptozipcode}, $self->{shiptocountry},
  1387. $self->{shiptocontact}, $self->{shiptophone},
  1388. $self->{shiptofax}, $self->{shiptoemail}
  1389. ) || $self->dberror($query);
  1390. $sth->finish;
  1391. $self->{dbh}->commit;
  1392. }
  1393. }
  1394. sub get_employee {
  1395. my ( $self, $dbh ) = @_;
  1396. my $login = $self->{login};
  1397. $login =~ s/@.*//;
  1398. my $query = qq|SELECT name, id
  1399. FROM employees
  1400. WHERE login = ?|;
  1401. $sth = $self->{dbh}->prepare($query);
  1402. $sth->execute($login);
  1403. my (@a) = $sth->fetchrow_array();
  1404. $a[1] *= 1;
  1405. $sth->finish;
  1406. $self->{dbh}->commit;
  1407. @a;
  1408. }
  1409. # this sub gets the id and name from $table
  1410. sub get_name {
  1411. my ( $self, $myconfig, $table, $transdate ) = @_;
  1412. # connect to database
  1413. my @queryargs;
  1414. my $where;
  1415. if ($transdate) {
  1416. $where = qq|
  1417. AND (startdate IS NULL OR startdate <= ?)
  1418. AND (enddate IS NULL OR enddate >= ?)|;
  1419. @queryargs = ( $transdate, $transdate );
  1420. }
  1421. my $name = $self->like( lc $self->{$table} );
  1422. my $query = qq|
  1423. SELECT * FROM $table
  1424. WHERE (lower(name) LIKE ? OR ${table}number LIKE ?)
  1425. $where
  1426. ORDER BY name|;
  1427. unshift( @queryargs, $name, $name );
  1428. my $sth = $self->{dbh}->prepare($query);
  1429. $sth->execute(@queryargs) || $self->dberror($query);
  1430. my $i = 0;
  1431. @{ $self->{name_list} } = ();
  1432. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1433. push( @{ $self->{name_list} }, $ref );
  1434. $i++;
  1435. }
  1436. $sth->finish;
  1437. $self->{dbh}->commit;
  1438. $i;
  1439. }
  1440. sub all_vc {
  1441. my ( $self, $myconfig, $vc, $module, $dbh, $transdate, $job ) = @_;
  1442. my $ref;
  1443. my $disconnect = 0;
  1444. $dbh = $self->{dbh};
  1445. my $sth;
  1446. my $query = qq|SELECT count(*) FROM $vc|;
  1447. my $where;
  1448. my @queryargs = ();
  1449. if ($transdate) {
  1450. $query .= qq| WHERE (startdate IS NULL OR startdate <= ?)
  1451. AND (enddate IS NULL OR enddate >= ?)|;
  1452. @queryargs = ( $transdate, $transdate );
  1453. }
  1454. $sth = $dbh->prepare($query);
  1455. $sth->execute(@queryargs);
  1456. my ($count) = $sth->fetchrow_array;
  1457. $sth->finish;
  1458. @queryargs = ();
  1459. # build selection list
  1460. if ( $count < $myconfig->{vclimit} ) {
  1461. $self->{"${vc}_id"} *= 1;
  1462. $query = qq|SELECT id, name
  1463. FROM $vc
  1464. WHERE 1=1
  1465. $where
  1466. UNION
  1467. SELECT id,name
  1468. FROM $vc
  1469. WHERE id = ?
  1470. ORDER BY name|;
  1471. push( @queryargs, $self->{"${vc}_id"} );
  1472. $sth = $dbh->prepare($query);
  1473. $sth->execute(@queryargs) || $self->dberror($query);
  1474. @{ $self->{"all_$vc"} } = ();
  1475. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1476. push @{ $self->{"all_$vc"} }, $ref;
  1477. }
  1478. $sth->finish;
  1479. }
  1480. # get self
  1481. if ( !$self->{employee_id} ) {
  1482. ( $self->{employee}, $self->{employee_id} ) = split /--/,
  1483. $self->{employee};
  1484. ( $self->{employee}, $self->{employee_id} ) = $self->get_employee($dbh)
  1485. unless $self->{employee_id};
  1486. }
  1487. $self->all_employees( $myconfig, $dbh, $transdate, 1 );
  1488. $self->all_departments( $myconfig, $dbh, $vc );
  1489. $self->all_projects( $myconfig, $dbh, $transdate, $job );
  1490. # get language codes
  1491. $query = qq|SELECT *
  1492. FROM language
  1493. ORDER BY 2|;
  1494. $sth = $dbh->prepare($query);
  1495. $sth->execute || $self->dberror($query);
  1496. $self->{all_language} = ();
  1497. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1498. push @{ $self->{all_language} }, $ref;
  1499. }
  1500. $sth->finish;
  1501. $self->all_taxaccounts( $myconfig, $dbh, $transdate );
  1502. $self->{dbh}->commit;
  1503. }
  1504. sub all_taxaccounts {
  1505. my ( $self, $myconfig, $dbh2, $transdate ) = @_;
  1506. my $dbh = $self->{dbh};
  1507. my $sth;
  1508. my $query;
  1509. my $where;
  1510. my @queryargs = ();
  1511. if ($transdate) {
  1512. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1513. push( @queryargs, $transdate );
  1514. }
  1515. if ( $self->{taxaccounts} ) {
  1516. # rebuild tax rates
  1517. $query = qq|SELECT t.rate, t.taxnumber
  1518. FROM tax t
  1519. JOIN chart c ON (c.id = t.chart_id)
  1520. WHERE c.accno = ?
  1521. $where
  1522. ORDER BY accno, validto|;
  1523. $sth = $dbh->prepare($query) || $self->dberror($query);
  1524. foreach my $accno ( split / /, $self->{taxaccounts} ) {
  1525. $sth->execute( $accno, @queryargs );
  1526. ( $self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"} ) =
  1527. $sth->fetchrow_array;
  1528. $sth->finish;
  1529. }
  1530. }
  1531. $self->{dbh}->commit;
  1532. }
  1533. sub all_employees {
  1534. my ( $self, $myconfig, $dbh2, $transdate, $sales ) = @_;
  1535. my $dbh = $self->{dbh};
  1536. my @whereargs = ();
  1537. # setup employees/sales contacts
  1538. my $query = qq|SELECT id, name
  1539. FROM employees
  1540. WHERE 1 = 1|;
  1541. if ($transdate) {
  1542. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1543. AND (enddate IS NULL OR enddate >= ?)|;
  1544. @whereargs = ( $transdate, $transdate );
  1545. }
  1546. else {
  1547. $query .= qq| AND enddate IS NULL|;
  1548. }
  1549. if ($sales) {
  1550. $query .= qq| AND sales = '1'|;
  1551. }
  1552. $query .= qq| ORDER BY name|;
  1553. my $sth = $dbh->prepare($query);
  1554. $sth->execute(@whereargs) || $self->dberror($query);
  1555. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1556. push @{ $self->{all_employee} }, $ref;
  1557. }
  1558. $sth->finish;
  1559. $dbh->commit;
  1560. }
  1561. sub all_projects {
  1562. my ( $self, $myconfig, $dbh2, $transdate, $job ) = @_;
  1563. my $dbh = $self->{dbh};
  1564. my @queryargs = ();
  1565. my $where = "1 = 1";
  1566. $where = qq|id NOT IN (SELECT id
  1567. FROM parts
  1568. WHERE project_id > 0)| if !$job;
  1569. my $query = qq|SELECT *
  1570. FROM project
  1571. WHERE $where|;
  1572. if ( $self->{language_code} ) {
  1573. $query = qq|
  1574. SELECT pr.*, t.description AS translation
  1575. FROM project pr
  1576. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1577. WHERE t.language_code = ?|;
  1578. push( @queryargs, $self->{language_code} );
  1579. }
  1580. if ($transdate) {
  1581. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1582. AND (enddate IS NULL OR enddate >= ?)|;
  1583. push( @queryargs, $transdate, $transdate );
  1584. }
  1585. $query .= qq| ORDER BY projectnumber|;
  1586. $sth = $dbh->prepare($query);
  1587. $sth->execute(@queryargs) || $self->dberror($query);
  1588. @{ $self->{all_project} } = ();
  1589. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1590. push @{ $self->{all_project} }, $ref;
  1591. }
  1592. $sth->finish;
  1593. $dbh->commit;
  1594. }
  1595. sub all_departments {
  1596. my ( $self, $myconfig, $dbh2, $vc ) = @_;
  1597. $dbh = $self->{dbh};
  1598. my $where = "1 = 1";
  1599. if ($vc) {
  1600. if ( $vc eq 'customer' ) {
  1601. $where = " role = 'P'";
  1602. }
  1603. }
  1604. my $query = qq|SELECT id, description
  1605. FROM department
  1606. WHERE $where
  1607. ORDER BY 2|;
  1608. my $sth = $dbh->prepare($query);
  1609. $sth->execute || $self->dberror($query);
  1610. @{ $self->{all_department} } = ();
  1611. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1612. push @{ $self->{all_department} }, $ref;
  1613. }
  1614. $sth->finish;
  1615. $self->all_years($myconfig);
  1616. $dbh->commit;
  1617. }
  1618. sub all_years {
  1619. my ( $self, $myconfig, $dbh2 ) = @_;
  1620. $dbh = $self->{dbh};
  1621. # get years
  1622. my $query = qq|
  1623. SELECT (SELECT MIN(transdate) FROM acc_trans),
  1624. (SELECT MAX(transdate) FROM acc_trans)|;
  1625. my ( $startdate, $enddate ) = $dbh->selectrow_array($query);
  1626. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1627. ($startdate) = split /\W/, $startdate;
  1628. ($enddate) = split /\W/, $enddate;
  1629. }
  1630. else {
  1631. (@_) = split /\W/, $startdate;
  1632. $startdate = $_[2];
  1633. (@_) = split /\W/, $enddate;
  1634. $enddate = $_[2];
  1635. }
  1636. $self->{all_years} = ();
  1637. $startdate = substr( $startdate, 0, 4 );
  1638. $enddate = substr( $enddate, 0, 4 );
  1639. while ( $enddate >= $startdate ) {
  1640. push @{ $self->{all_years} }, $enddate--;
  1641. }
  1642. #this should probably be changed to use locale
  1643. %{ $self->{all_month} } = (
  1644. '01' => 'January',
  1645. '02' => 'February',
  1646. '03' => 'March',
  1647. '04' => 'April',
  1648. '05' => 'May ',
  1649. '06' => 'June',
  1650. '07' => 'July',
  1651. '08' => 'August',
  1652. '09' => 'September',
  1653. '10' => 'October',
  1654. '11' => 'November',
  1655. '12' => 'December'
  1656. );
  1657. $dbh->commit;
  1658. }
  1659. sub create_links {
  1660. my ( $self, $module, $myconfig, $vc, $job ) = @_;
  1661. # get last customers or vendors
  1662. my ( $query, $sth );
  1663. if (!$self->{dbh}) {
  1664. $self->db_init($myconfig);
  1665. }
  1666. $dbh = $self->{dbh};
  1667. my %xkeyref = ();
  1668. # now get the account numbers
  1669. $query = qq|SELECT accno, description, link
  1670. FROM chart
  1671. WHERE link LIKE ?
  1672. ORDER BY accno|;
  1673. $sth = $dbh->prepare($query);
  1674. $sth->execute( "%" . "$module%" ) || $self->dberror($query);
  1675. $self->{accounts} = "";
  1676. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1677. foreach my $key ( split /:/, $ref->{link} ) {
  1678. if ( $key =~ /$module/ ) {
  1679. # cross reference for keys
  1680. $xkeyref{ $ref->{accno} } = $key;
  1681. push @{ $self->{"${module}_links"}{$key} },
  1682. {
  1683. accno => $ref->{accno},
  1684. description => $ref->{description}
  1685. };
  1686. $self->{accounts} .= "$ref->{accno} "
  1687. unless $key =~ /tax/;
  1688. }
  1689. }
  1690. }
  1691. $sth->finish;
  1692. my $arap = ( $vc eq 'customer' ) ? 'ar' : 'ap';
  1693. if ( $self->{id} ) {
  1694. $query = qq|
  1695. SELECT a.invnumber, a.transdate,
  1696. a.${vc}_id, a.datepaid, a.duedate, a.ordnumber,
  1697. a.taxincluded, a.curr AS currency, a.notes,
  1698. a.intnotes, c.name AS $vc, a.department_id,
  1699. d.description AS department,
  1700. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1701. a.employee_id, e.name AS employee,
  1702. c.language_code, a.ponumber
  1703. FROM $arap a
  1704. JOIN $vc c ON (a.${vc}_id = c.id)
  1705. LEFT JOIN employees e ON (e.id = a.employee_id)
  1706. LEFT JOIN department d ON (d.id = a.department_id)
  1707. WHERE a.id = ?|;
  1708. $sth = $dbh->prepare($query);
  1709. $sth->execute( $self->{id} ) || $self->dberror($query);
  1710. $ref = $sth->fetchrow_hashref(NAME_lc);
  1711. $self->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1712. foreach $key ( keys %$ref ) {
  1713. $self->{$key} = $ref->{$key};
  1714. }
  1715. $sth->finish;
  1716. # get printed, emailed
  1717. $query = qq|
  1718. SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1719. FROM status s WHERE s.trans_id = ?|;
  1720. $sth = $dbh->prepare($query);
  1721. $sth->execute( $self->{id} ) || $self->dberror($query);
  1722. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1723. $self->{printed} .= "$ref->{formname} "
  1724. if $ref->{printed};
  1725. $self->{emailed} .= "$ref->{formname} "
  1726. if $ref->{emailed};
  1727. $self->{queued} .= "$ref->{formname} " . "$ref->{spoolfile} "
  1728. if $ref->{spoolfile};
  1729. }
  1730. $sth->finish;
  1731. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1732. # get recurring
  1733. $self->get_recurring($dbh);
  1734. # get amounts from individual entries
  1735. $query = qq|
  1736. SELECT c.accno, c.description, a.source, a.amount,
  1737. a.memo, a.transdate, a.cleared, a.project_id,
  1738. p.projectnumber
  1739. FROM acc_trans a
  1740. JOIN chart c ON (c.id = a.chart_id)
  1741. LEFT JOIN project p ON (p.id = a.project_id)
  1742. WHERE a.trans_id = ?
  1743. AND a.fx_transaction = '0'
  1744. ORDER BY transdate|;
  1745. $sth = $dbh->prepare($query);
  1746. $sth->execute( $self->{id} ) || $self->dberror($query);
  1747. my $fld = ( $vc eq 'customer' ) ? 'buy' : 'sell';
  1748. $self->{exchangerate} =
  1749. $self->get_exchangerate( $dbh, $self->{currency}, $self->{transdate},
  1750. $fld );
  1751. # store amounts in {acc_trans}{$key} for multiple accounts
  1752. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1753. $ref->{exchangerate} =
  1754. $self->get_exchangerate( $dbh, $self->{currency},
  1755. $ref->{transdate}, $fld );
  1756. push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
  1757. }
  1758. $sth->finish;
  1759. for (qw(curr closedto revtrans)) {
  1760. $query = qq|
  1761. SELECT value FROM defaults
  1762. WHERE setting_key = '$_'|;
  1763. $sth = $dbh->prepare($query);
  1764. $sth->execute || $self->dberror($query);
  1765. ($val) = $sth->fetchrow_array();
  1766. if ( $_ eq 'curr' ) {
  1767. $self->{currencies} = $val;
  1768. }
  1769. else {
  1770. $self->{$_} = $val;
  1771. }
  1772. $sth->finish;
  1773. }
  1774. $self->{transdate} = $self->current_date;
  1775. }
  1776. else {
  1777. for (qw(current_date curr closedto revtrans)) {
  1778. $query = qq|
  1779. SELECT value FROM defaults
  1780. WHERE setting_key = '$_'|;
  1781. $sth = $dbh->prepare($query);
  1782. $sth->execute || $self->dberror($query);
  1783. ($val) = $sth->fetchrow_array();
  1784. if ( $_ eq 'curr' ) {
  1785. $self->{currencies} = $val;
  1786. }
  1787. elsif ( $_ eq 'current_date' ) {
  1788. $self->{transdate} = $val;
  1789. }
  1790. else {
  1791. $self->{$_} = $val;
  1792. }
  1793. $sth->finish;
  1794. }
  1795. if ( !$self->{"$self->{vc}_id"} ) {
  1796. $self->lastname_used( $myconfig, $dbh, $vc, $module );
  1797. }
  1798. }
  1799. $self->all_vc( $myconfig, $vc, $module, $dbh, $self->{transdate}, $job );
  1800. $self->{dbh}->commit;
  1801. }
  1802. sub lastname_used {
  1803. my ( $self, $myconfig, $dbh2, $vc, $module ) = @_;
  1804. my $dbh = $self->{dbh};
  1805. $vc ||= $self->{vc}; # add default to correct for improper passing
  1806. my $arap = ( $vc eq 'customer' ) ? "ar" : "ap";
  1807. my $where = "1 = 1";
  1808. my $sth;
  1809. if ( $self->{type} =~ /_order/ ) {
  1810. $arap = 'oe';
  1811. $where = "quotation = '0'";
  1812. }
  1813. if ( $self->{type} =~ /_quotation/ ) {
  1814. $arap = 'oe';
  1815. $where = "quotation = '1'";
  1816. }
  1817. my $query = qq|
  1818. SELECT id
  1819. FROM $arap
  1820. WHERE id IN
  1821. (SELECT MAX(id)
  1822. FROM $arap
  1823. WHERE $where AND ${vc}_id > 0)|;
  1824. my ($trans_id) = $dbh->selectrow_array($query);
  1825. $trans_id *= 1;
  1826. $query = qq|
  1827. SELECT ct.name AS $vc, a.curr AS currency, a.${vc}_id,
  1828. current_date + ct.terms AS duedate,
  1829. a.department_id, d.description AS department, ct.notes,
  1830. ct.curr AS currency
  1831. FROM $arap a
  1832. JOIN $vc ct ON (a.${vc}_id = ct.id)
  1833. LEFT JOIN department d ON (a.department_id = d.id)
  1834. WHERE a.id = ?|;
  1835. $sth = $dbh->prepare($query);
  1836. $sth->execute($trans_id) || $self->dberror($query);
  1837. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1838. for ( keys %$ref ) { $self->{$_} = $ref->{$_} }
  1839. $sth->finish;
  1840. $dbh->commit;
  1841. }
  1842. sub current_date {
  1843. my ( $self, $myconfig, $thisdate, $days ) = @_;
  1844. my $dbh = $self->{dbh};
  1845. my $query;
  1846. $days *= 1;
  1847. if ($thisdate) {
  1848. my $dateformat = $myconfig->{dateformat};
  1849. if ( $myconfig->{dateformat} !~ /^y/ ) {
  1850. my @a = split /\D/, $thisdate;
  1851. $dateformat .= "yy" if ( length $a[2] > 2 );
  1852. }
  1853. if ( $thisdate !~ /\D/ ) {
  1854. $dateformat = 'yyyymmdd';
  1855. }
  1856. $query = qq|SELECT (to_date(?, ?)
  1857. + ?::interval)::date AS thisdate|;
  1858. @queryargs = ( $thisdate, $dateformat, sprintf('%d days', $days) );
  1859. }
  1860. else {
  1861. $query = qq|SELECT current_date AS thisdate|;
  1862. @queryargs = ();
  1863. }
  1864. $sth = $dbh->prepare($query);
  1865. $sth->execute(@queryargs);
  1866. ($thisdate) = $sth->fetchrow_array;
  1867. $dbh->commit;
  1868. $thisdate;
  1869. }
  1870. sub like {
  1871. my ( $self, $str ) = @_;
  1872. "%$str%";
  1873. }
  1874. sub redo_rows {
  1875. my ( $self, $flds, $new, $count, $numrows ) = @_;
  1876. my @ndx = ();
  1877. for ( 1 .. $count ) {
  1878. push @ndx, { num => $new->[ $_ - 1 ]->{runningnumber}, ndx => $_ };
  1879. }
  1880. my $i = 0;
  1881. # fill rows
  1882. foreach my $item ( sort { $a->{num} <=> $b->{num} } @ndx ) {
  1883. $i++;
  1884. $j = $item->{ndx} - 1;
  1885. for ( @{$flds} ) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1886. }
  1887. # delete empty rows
  1888. for $i ( $count + 1 .. $numrows ) {
  1889. for ( @{$flds} ) { delete $self->{"${_}_$i"} }
  1890. }
  1891. }
  1892. sub get_partsgroup {
  1893. my ( $self, $myconfig, $p ) = @_;
  1894. my $dbh = $self->{dbh};
  1895. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1896. FROM partsgroup pg
  1897. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1898. my $where;
  1899. my $sortorder = "partsgroup";
  1900. if ( $p->{searchitems} eq 'part' ) {
  1901. $where = qq| WHERE (p.inventory_accno_id > 0
  1902. AND p.income_accno_id > 0)|;
  1903. }
  1904. if ( $p->{searchitems} eq 'service' ) {
  1905. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1906. }
  1907. if ( $p->{searchitems} eq 'assembly' ) {
  1908. $where = qq| WHERE p.assembly = '1'|;
  1909. }
  1910. if ( $p->{searchitems} eq 'labor' ) {
  1911. $where =
  1912. qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1913. }
  1914. if ( $p->{searchitems} eq 'nolabor' ) {
  1915. $where = qq| WHERE p.income_accno_id > 0|;
  1916. }
  1917. if ( $p->{all} ) {
  1918. $query = qq|SELECT id, partsgroup
  1919. FROM partsgroup|;
  1920. }
  1921. my @queryargs = ();
  1922. if ( $p->{language_code} ) {
  1923. $sortorder = "translation";
  1924. $query = qq|
  1925. SELECT DISTINCT pg.id, pg.partsgroup,
  1926. t.description AS translation
  1927. FROM partsgroup pg
  1928. JOIN parts p ON (p.partsgroup_id = pg.id)
  1929. LEFT JOIN translation t ON (t.trans_id = pg.id
  1930. AND t.language_code = ?)|;
  1931. @queryargs = ( $p->{language_code} );
  1932. }
  1933. $query .= qq| $where ORDER BY $sortorder|;
  1934. my $sth = $dbh->prepare($query);
  1935. $sth->execute(@queryargs) || $self->dberror($query);
  1936. $self->{all_partsgroup} = ();
  1937. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1938. push @{ $self->{all_partsgroup} }, $ref;
  1939. }
  1940. $sth->finish;
  1941. $dbh->commit;
  1942. }
  1943. sub update_status {
  1944. my ( $self, $myconfig ) = @_;
  1945. # no id return
  1946. return unless $self->{id};
  1947. my $dbh = $self->{dbh};
  1948. my %queued = split / +/, $self->{queued};
  1949. my $spoolfile =
  1950. ( $queued{ $self->{formname} } )
  1951. ? "'$queued{$self->{formname}}'"
  1952. : 'NULL';
  1953. my $query = qq|DELETE FROM status
  1954. WHERE formname = ?
  1955. AND trans_id = ?|;
  1956. $sth = $dbh->prepare($query);
  1957. $sth->execute( $self->{formname}, $self->{id} ) || $self->dberror($query);
  1958. $sth->finish;
  1959. my $printed = ( $self->{printed} =~ /$self->{formname}/ ) ? "1" : "0";
  1960. my $emailed = ( $self->{emailed} =~ /$self->{formname}/ ) ? "1" : "0";
  1961. $query = qq|
  1962. INSERT INTO status
  1963. (trans_id, printed, emailed, spoolfile, formname)
  1964. VALUES (?, ?, ?, ?, ?)|;
  1965. $sth = $dbh->prepare($query);
  1966. $sth->execute( $self->{id}, $printed, $emailed, $spoolfile,
  1967. $self->{formname} );
  1968. $sth->finish;
  1969. $dbh->commit;
  1970. }
  1971. sub save_status {
  1972. my ($self) = @_;
  1973. $dbh = $self->{dbh};
  1974. my $formnames = $self->{printed};
  1975. my $emailforms = $self->{emailed};
  1976. my $query = qq|DELETE FROM status
  1977. WHERE trans_id = ?|;
  1978. my $sth = $dbh->prepare($query);
  1979. $sth->execute( $self->{id} );
  1980. $sth->finish;
  1981. my %queued;
  1982. my $formname;
  1983. if ( $self->{queued} ) {
  1984. %queued = split / +/, $self->{queued};
  1985. foreach $formname ( keys %queued ) {
  1986. $printed = ( $self->{printed} =~ /$formname/ ) ? "1" : "0";
  1987. $emailed = ( $self->{emailed} =~ /$formname/ ) ? "1" : "0";
  1988. if ( $queued{$formname} ) {
  1989. $query = qq|
  1990. INSERT INTO status
  1991. (trans_id, printed, emailed,
  1992. spoolfile, formname)
  1993. VALUES (?, ?, ?, ?, ?)|;
  1994. $sth = $dbh->prepare($query);
  1995. $sth->execute( $self->{id}, $pinted, $emailed,
  1996. $queued{$formname}, $formname )
  1997. || $self->dberror($query);
  1998. $sth->finish;
  1999. }
  2000. $formnames =~ s/$formname//;
  2001. $emailforms =~ s/$formname//;
  2002. }
  2003. }
  2004. # save printed, emailed info
  2005. $formnames =~ s/^ +//g;
  2006. $emailforms =~ s/^ +//g;
  2007. my %status = ();
  2008. for ( split / +/, $formnames ) { $status{$_}{printed} = 1 }
  2009. for ( split / +/, $emailforms ) { $status{$_}{emailed} = 1 }
  2010. foreach my $formname ( keys %status ) {
  2011. $printed = ( $formnames =~ /$self->{formname}/ ) ? "1" : "0";
  2012. $emailed = ( $emailforms =~ /$self->{formname}/ ) ? "1" : "0";
  2013. $query = qq|
  2014. INSERT INTO status (trans_id, printed, emailed,
  2015. formname)
  2016. VALUES (?, ?, ?, ?)|;
  2017. $sth = $dbh->prepare($query);
  2018. $sth->execute( $self->{id}, $printed, $emailed, $formname );
  2019. $sth->finish;
  2020. }
  2021. $dbh->commit;
  2022. }
  2023. sub get_recurring {
  2024. my ($self) = @_;
  2025. $dbh = $self->{dbh};
  2026. my $query = qq/
  2027. SELECT s.*, se.formname || ':' || se.format AS emaila,
  2028. se.message, sp.formname || ':' ||
  2029. sp.format || ':' || sp.printer AS printa
  2030. FROM recurring s
  2031. LEFT JOIN recurringemail se ON (s.id = se.id)
  2032. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  2033. WHERE s.id = ?/;
  2034. my $sth = $dbh->prepare($query);
  2035. $sth->execute( $self->{id} ) || $self->dberror($query);
  2036. for (qw(email print)) { $self->{"recurring$_"} = "" }
  2037. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  2038. for ( keys %$ref ) { $self->{"recurring$_"} = $ref->{$_} }
  2039. $self->{recurringemail} .= "$ref->{emaila}:";
  2040. $self->{recurringprint} .= "$ref->{printa}:";
  2041. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  2042. }
  2043. $sth->finish;
  2044. chop $self->{recurringemail};
  2045. chop $self->{recurringprint};
  2046. if ( $self->{recurringstartdate} ) {
  2047. $self->{recurringreference} =
  2048. $self->escape( $self->{recurringreference}, 1 );
  2049. $self->{recurringmessage} =
  2050. $self->escape( $self->{recurringmessage}, 1 );
  2051. for (
  2052. qw(reference startdate repeat unit howmany
  2053. payment print email message)
  2054. )
  2055. {
  2056. $self->{recurring} .= qq|$self->{"recurring$_"},|;
  2057. }
  2058. chop $self->{recurring};
  2059. }
  2060. $dbh->commit;
  2061. }
  2062. sub save_recurring {
  2063. my ( $self, $dbh2, $myconfig ) = @_;
  2064. my $dbh = $self->{dbh};
  2065. my $query;
  2066. $query = qq|DELETE FROM recurring
  2067. WHERE id = ?|;
  2068. $sth = $dbh->prepare($query) || $self->dberror($query);
  2069. $sth->execute( $self->{id} ) || $self->dberror($query);
  2070. $query = qq|DELETE FROM recurringemail
  2071. WHERE id = ?|;
  2072. $sth = $dbh->prepare($query) || $self->dberror($query);
  2073. $sth->execute( $self->{id} ) || $self->dberror($query);
  2074. $query = qq|DELETE FROM recurringprint
  2075. WHERE id = ?|;
  2076. $sth = $dbh->prepare($query) || $self->dberror($query);
  2077. $sth->execute( $self->{id} ) || $self->dberror($query);
  2078. if ( $self->{recurring} ) {
  2079. my %s = ();
  2080. (
  2081. $s{reference}, $s{startdate}, $s{repeat},
  2082. $s{unit}, $s{howmany}, $s{payment},
  2083. $s{print}, $s{email}, $s{message}
  2084. ) = split /,/, $self->{recurring};
  2085. if ($s{howmany} == 0){
  2086. $self->error("Cannot set to recur 0 times");
  2087. }
  2088. for (qw(reference message)) { $s{$_} = $self->unescape( $s{$_} ) }
  2089. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  2090. # calculate enddate
  2091. my $advance = $s{repeat} * ( $s{howmany} - 1 );
  2092. my %interval;
  2093. $interval{'Pg'} =
  2094. "(date '$s{startdate}' + interval '$advance $s{unit}')";
  2095. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  2096. my ($enddate) = $dbh->selectrow_array($query);
  2097. # calculate nextdate
  2098. $query = qq|
  2099. SELECT current_date - ?::date AS a,
  2100. ?::date - current_date AS b|;
  2101. $sth = $dbh->prepare($query) || $self->dberror($query);
  2102. $sth->execute( $s{startdate}, $enddate );
  2103. my ( $a, $b ) = $sth->fetchrow_array;
  2104. if ( $a + $b ) {
  2105. $advance =
  2106. int( ( $a / ( $a + $b ) ) * ( $s{howmany} - 1 ) + 1 ) *
  2107. $s{repeat};
  2108. }
  2109. else {
  2110. $advance = 0;
  2111. }
  2112. my $nextdate = $enddate;
  2113. if ( $advance > 0 ) {
  2114. if ( $advance < ( $s{repeat} * $s{howmany} ) ) {
  2115. $query = qq|SELECT (date '$s{startdate}' + interval '$advance $s{unit}')|;
  2116. ($nextdate) = $dbh->selectrow_array($query);
  2117. }
  2118. }
  2119. else {
  2120. $nextdate = $s{startdate};
  2121. }
  2122. if ( $self->{recurringnextdate} ) {
  2123. $nextdate = $self->{recurringnextdate};
  2124. $query = qq|SELECT '$enddate' - date '$nextdate'|;
  2125. if ( $dbh->selectrow_array($query) < 0 ) {
  2126. undef $nextdate;
  2127. }
  2128. }
  2129. $self->{recurringpayment} *= 1;
  2130. $query = qq|
  2131. INSERT INTO recurring
  2132. (id, reference, startdate, enddate, nextdate,
  2133. repeat, unit, howmany, payment)
  2134. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  2135. $sth = $dbh->prepare($query);
  2136. $sth->execute(
  2137. $self->{id}, $s{reference}, $s{startdate},
  2138. $enddate, $nextdate, $s{repeat},
  2139. $s{unit}, $s{howmany}, $s{payment}
  2140. );
  2141. my @p;
  2142. my $p;
  2143. my $i;
  2144. my $sth;
  2145. if ( $s{email} ) {
  2146. # formname:format
  2147. @p = split /:/, $s{email};
  2148. $query =
  2149. qq|INSERT INTO recurringemail (id, formname, format, message)
  2150. VALUES (?, ?, ?, ?)|;
  2151. $sth = $dbh->prepare($query) || $self->dberror($query);
  2152. for ( $i = 0 ; $i <= $#p ; $i += 2 ) {
  2153. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $s{message} );
  2154. }
  2155. $sth->finish;
  2156. }
  2157. if ( $s{print} ) {
  2158. # formname:format:printer
  2159. @p = split /:/, $s{print};
  2160. $query =
  2161. qq|INSERT INTO recurringprint (id, formname, format, printer)
  2162. VALUES (?, ?, ?, ?)|;
  2163. $sth = $dbh->prepare($query) || $self->dberror($query);
  2164. for ( $i = 0 ; $i <= $#p ; $i += 3 ) {
  2165. $p = ( $p[ $i + 2 ] ) ? $p[ $i + 2 ] : "";
  2166. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $p );
  2167. }
  2168. $sth->finish;
  2169. }
  2170. }
  2171. $dbh->commit;
  2172. }
  2173. sub save_intnotes {
  2174. my ( $self, $myconfig, $vc ) = @_;
  2175. # no id return
  2176. return unless $self->{id};
  2177. my $dbh = $self->{dbh};
  2178. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  2179. $sth = $dbh->prepare($query);
  2180. $sth->execute( $self->{intnotes}, $self->{id} ) || $self->dberror($query);
  2181. $dbh->commit;
  2182. }
  2183. sub update_defaults {
  2184. my ( $self, $myconfig, $fld ) = @_;
  2185. if ( !$self->{dbh} && $self ) {
  2186. $self->db_init($myconfig);
  2187. }
  2188. my $dbh = $self->{dbh};
  2189. if ( !$self ) {
  2190. $dbh = $_[3];
  2191. }
  2192. my $query = qq|
  2193. SELECT value FROM defaults
  2194. WHERE setting_key = ? FOR UPDATE|;
  2195. $sth = $dbh->prepare($query);
  2196. $sth->execute($fld);
  2197. ($_) = $sth->fetchrow_array();
  2198. $_ = "0" unless $_;
  2199. # check for and replace
  2200. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  2201. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  2202. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  2203. # <?lsmb PHONE ?> for customer and vendors
  2204. my $num = $_;
  2205. ($num) = $num =~ /(\d+)/;
  2206. if ( defined $num ) {
  2207. my $incnum;
  2208. # if we have leading zeros check how long it is
  2209. if ( $num =~ /^0/ ) {
  2210. my $l = length $num;
  2211. $incnum = $num + 1;
  2212. $l -= length $incnum;
  2213. # pad it out with zeros
  2214. my $padzero = "0" x $l;
  2215. $incnum = ( "0" x $l ) . $incnum;
  2216. }
  2217. else {
  2218. $incnum = $num + 1;
  2219. }
  2220. s/$num/$incnum/;
  2221. }
  2222. my $dbvar = $_;
  2223. my $var = $_;
  2224. my $str;
  2225. my $param;
  2226. if (/<\?lsmb /) {
  2227. while (/<\?lsmb /) {
  2228. s/<\?lsmb .*? \?>//;
  2229. last unless $&;
  2230. $param = $&;
  2231. $str = "";
  2232. if ( $param =~ /<\?lsmb date \?>/i ) {
  2233. $str = (
  2234. $self->split_date(
  2235. $myconfig->{dateformat},
  2236. $self->{transdate}
  2237. )
  2238. )[0];
  2239. $var =~ s/$param/$str/;
  2240. }
  2241. if ( $param =~
  2242. /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i
  2243. )
  2244. {
  2245. my $fld = lc $&;
  2246. $fld =~ s/<\?lsmb //;
  2247. if ( $fld =~ /name/ ) {
  2248. if ( $self->{type} ) {
  2249. $fld = $self->{vc};
  2250. }
  2251. }
  2252. my $p = $param;
  2253. $p =~ s/(<|>|%)//g;
  2254. my @p = split / /, $p;
  2255. my @n = split / /, uc $self->{$fld};
  2256. if ( $#p > 0 ) {
  2257. for ( my $i = 1 ; $i <= $#p ; $i++ ) {
  2258. $str .= substr( $n[ $i - 1 ], 0, $p[$i] );
  2259. }
  2260. }
  2261. else {
  2262. ($str) = split /--/, $self->{$fld};
  2263. }
  2264. $var =~ s/$param/$str/;
  2265. $var =~ s/\W//g if $fld eq 'phone';
  2266. }
  2267. if ( $param =~ /<\?lsmb (yy|mm|dd)/i ) {
  2268. my $p = $param;
  2269. $p =~ s/(<|>|%)//g;
  2270. my $spc = $p;
  2271. $spc =~ s/\w//g;
  2272. $spc = substr( $spc, 0, 1 );
  2273. my %d = ( yy => 1, mm => 2, dd => 3 );
  2274. my @p = ();
  2275. my @a = $self->split_date( $myconfig->{dateformat},
  2276. $self->{transdate} );
  2277. for ( sort keys %d ) { push @p, $a[ $d{$_} ] if ( $p =~ /$_/ ) }
  2278. $str = join $spc, @p;
  2279. $var =~ s/$param/$str/;
  2280. }
  2281. if ( $param =~ /<\?lsmb curr/i ) {
  2282. $var =~ s/$param/$self->{currency}/;
  2283. }
  2284. }
  2285. }
  2286. $query = qq|
  2287. UPDATE defaults
  2288. SET value = ?
  2289. WHERE setting_key = ?|;
  2290. $sth = $dbh->prepare($query);
  2291. $sth->execute( $dbvar, $fld ) || $self->dberror($query);
  2292. $dbh->commit;
  2293. $var;
  2294. }
  2295. sub db_prepare_vars {
  2296. my $self = shift;
  2297. for (@_) {
  2298. if ( !$self->{$_} and $self->{$_} ne "0" ) {
  2299. undef $self->{$_};
  2300. }
  2301. }
  2302. }
  2303. sub split_date {
  2304. my ( $self, $dateformat, $date ) = @_;
  2305. my @d = localtime;
  2306. my $mm;
  2307. my $dd;
  2308. my $yy;
  2309. my $rv;
  2310. if ( !$date ) {
  2311. $dd = $d[3];
  2312. $mm = ++$d[4];
  2313. $yy = substr( $d[5], -2 );
  2314. $mm = substr( "0$mm", -2 );
  2315. $dd = substr( "0$dd", -2 );
  2316. }
  2317. if ( $dateformat =~ /^yy/ ) {
  2318. if ($date) {
  2319. if ( $date =~ /\D/ ) {
  2320. ( $yy, $mm, $dd ) = split /\D/, $date;
  2321. $mm *= 1;
  2322. $dd *= 1;
  2323. $mm = substr( "0$mm", -2 );
  2324. $dd = substr( "0$dd", -2 );
  2325. $yy = substr( $yy, -2 );
  2326. $rv = "$yy$mm$dd";
  2327. }
  2328. else {
  2329. $rv = $date;
  2330. }
  2331. }
  2332. else {
  2333. $rv = "$yy$mm$dd";
  2334. }
  2335. }
  2336. if ( $dateformat =~ /^mm/ ) {
  2337. if ($date) {
  2338. if ( $date =~ /\D/ ) {
  2339. ( $mm, $dd, $yy ) = split /\D/, $date;
  2340. $mm *= 1;
  2341. $dd *= 1;
  2342. $mm = substr( "0$mm", -2 );
  2343. $dd = substr( "0$dd", -2 );
  2344. $yy = substr( $yy, -2 );
  2345. $rv = "$mm$dd$yy";
  2346. }
  2347. else {
  2348. $rv = $date;
  2349. }
  2350. }
  2351. else {
  2352. $rv = "$mm$dd$yy";
  2353. }
  2354. }
  2355. if ( $dateformat =~ /^dd/ ) {
  2356. if ($date) {
  2357. if ( $date =~ /\D/ ) {
  2358. ( $dd, $mm, $yy ) = split /\D/, $date;
  2359. $mm *= 1;
  2360. $dd *= 1;
  2361. $mm = substr( "0$mm", -2 );
  2362. $dd = substr( "0$dd", -2 );
  2363. $yy = substr( $yy, -2 );
  2364. $rv = "$dd$mm$yy";
  2365. }
  2366. else {
  2367. $rv = $date;
  2368. }
  2369. }
  2370. else {
  2371. $rv = "$dd$mm$yy";
  2372. }
  2373. }
  2374. ( $rv, $yy, $mm, $dd );
  2375. }
  2376. sub format_date {
  2377. # takes an iso date in, and converts it to the date for printing
  2378. my ( $self, $date ) = @_;
  2379. my $datestring;
  2380. if ( $date =~ /^\d{4}\D/ ) { # is an ISO date
  2381. $datestring = $self->{db_dateformat};
  2382. my ( $yyyy, $mm, $dd ) = split( /\W/, $date );
  2383. $datestring =~ s/y+/$yyyy/;
  2384. $datestring =~ s/mm/$mm/;
  2385. $datestring =~ s/dd/$dd/;
  2386. }
  2387. else { # return date
  2388. $datestring = $date;
  2389. }
  2390. $datestring;
  2391. }
  2392. sub from_to {
  2393. my ( $self, $yyyy, $mm, $interval ) = @_;
  2394. my @t;
  2395. my $dd = 1;
  2396. my $fromdate = "$yyyy-${mm}-01";
  2397. my $bd = 1;
  2398. if ( defined $interval ) {
  2399. if ( $interval == 12 ) {
  2400. $yyyy++;
  2401. }
  2402. else {
  2403. if ( ( $mm += $interval ) > 12 ) {
  2404. $mm -= 12;
  2405. $yyyy++;
  2406. }
  2407. if ( $interval == 0 ) {
  2408. @t = localtime(time);
  2409. $dd = $t[3];
  2410. $mm = $t[4] + 1;
  2411. $yyyy = $t[5] + 1900;
  2412. $bd = 0;
  2413. }
  2414. }
  2415. }
  2416. else {
  2417. if ( ++$mm > 12 ) {
  2418. $mm -= 12;
  2419. $yyyy++;
  2420. }
  2421. }
  2422. $mm--;
  2423. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yyyy ) - $bd );
  2424. $t[4]++;
  2425. $t[4] = substr( "0$t[4]", -2 );
  2426. $t[3] = substr( "0$t[3]", -2 );
  2427. $t[5] += 1900;
  2428. ( $self->format_date($fromdate), $self->format_date("$t[5]-$t[4]-$t[3]") );
  2429. }
  2430. sub audittrail {
  2431. my ( $self, $dbh, $myconfig, $audittrail ) = @_;
  2432. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2433. my $query;
  2434. my $rv;
  2435. my $disconnect;
  2436. if ( !$dbh ) {
  2437. $dbh = $self->{dbh};
  2438. }
  2439. # if we have an id add audittrail, otherwise get a new timestamp
  2440. my @queryargs;
  2441. if ( $audittrail->{id} ) {
  2442. $query = qq|
  2443. SELECT value FROM defaults
  2444. WHERE setting_key = 'audittrail'|;
  2445. if ( $dbh->selectrow_array($query) ) {
  2446. my ( $null, $employee_id ) = $self->get_employee($dbh);
  2447. if ( $self->{audittrail} && !$myconfig ) {
  2448. chop $self->{audittrail};
  2449. my @a = split /\|/, $self->{audittrail};
  2450. my %newtrail = ();
  2451. my $key;
  2452. my $i;
  2453. my @flds = qw(tablename reference formname action transdate);
  2454. # put into hash and remove dups
  2455. while (@a) {
  2456. $key = "$a[2]$a[3]";
  2457. $i = 0;
  2458. $newtrail{$key} = { map { $_ => $a[ $i++ ] } @flds };
  2459. splice @a, 0, 5;
  2460. }
  2461. $query = qq|
  2462. INSERT INTO audittrail
  2463. (trans_id, tablename, reference,
  2464. formname, action, transdate,
  2465. employee_id)
  2466. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2467. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2468. foreach $key (
  2469. sort {
  2470. $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
  2471. } keys %newtrail
  2472. )
  2473. {
  2474. $i = 2;
  2475. $sth->bind_param( 1, $audittrail->{id} );
  2476. for (@flds) {
  2477. $sth->bind_param( $i++, $newtrail{$key}{$_} );
  2478. }
  2479. $sth->bind_param( $i++, $employee_id );
  2480. $sth->execute() || $self->dberror($query);
  2481. $sth->finish;
  2482. }
  2483. }
  2484. if ( $audittrail->{transdate} ) {
  2485. $query = qq|
  2486. INSERT INTO audittrail (
  2487. trans_id, tablename, reference,
  2488. formname, action, employee_id,
  2489. transdate)
  2490. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2491. @queryargs = (
  2492. $audittrail->{id}, $audittrail->{tablename},
  2493. $audittrail->{reference}, $audittrail->{formname},
  2494. $audittrail->{action}, $employee_id,
  2495. $audittrail->{transdate}
  2496. );
  2497. }
  2498. else {
  2499. $query = qq|
  2500. INSERT INTO audittrail
  2501. (trans_id, tablename, reference,
  2502. formname, action, employee_id)
  2503. VALUES (?, ?, ?, ?, ?, ?)|;
  2504. @queryargs = (
  2505. $audittrail->{id}, $audittrail->{tablename},
  2506. $audittrail->{reference}, $audittrail->{formname},
  2507. $audittrail->{action}, $employee_id,
  2508. );
  2509. }
  2510. $sth = $dbh->prepare($query);
  2511. $sth->execute(@queryargs) || $self->dberror($query);
  2512. }
  2513. }
  2514. else {
  2515. $query = qq|SELECT current_timestamp|;
  2516. my ($timestamp) = $dbh->selectrow_array($query);
  2517. $rv =
  2518. "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2519. }
  2520. $dbh->commit;
  2521. $rv;
  2522. }
  2523. 1;