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