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