summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: d582601fd49a9ae54a90c48dea2776e1bdb0d504 (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} =~ /0,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. #$self->{dbh}->do('set log_statement to \'all\'');
  1118. my $query = "SELECT t.extends,
  1119. coalesce (t.table_name, 'custom_' || extends)
  1120. || ':' || f.field_name as field_def
  1121. FROM custom_table_catalog t
  1122. JOIN custom_field_catalog f USING (table_id)";
  1123. my $sth = $self->{dbh}->prepare($query);
  1124. $sth->execute;
  1125. my $ref;
  1126. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1127. push @{ $self->{custom_db_fields}{ $ref->{extends} } },
  1128. $ref->{field_def};
  1129. }
  1130. }
  1131. sub run_custom_queries {
  1132. my ( $self, $tablename, $query_type, $linenum ) = @_;
  1133. my $dbh = $self->{dbh};
  1134. if ( $query_type !~ /^(select|insert|update)$/i ) {
  1135. $self->error(
  1136. $locale->text(
  1137. "Passed incorrect query type to run_custom_queries."
  1138. )
  1139. );
  1140. }
  1141. my @rc;
  1142. my %temphash;
  1143. my @templist;
  1144. my @elements;
  1145. my $query;
  1146. my $ins_values;
  1147. if ($linenum) {
  1148. $linenum = "_$linenum";
  1149. }
  1150. $query_type = uc($query_type);
  1151. for ( @{ $self->{custom_db_fields}{$tablename} } ) {
  1152. @elements = split( /:/, $_ );
  1153. push @{ $temphash{ $elements[0] } }, $elements[1];
  1154. }
  1155. for ( keys %temphash ) {
  1156. my @data;
  1157. my $ins_values;
  1158. $query = "$query_type ";
  1159. if ( $query_type eq 'UPDATE' ) {
  1160. $query = "DELETE FROM $_ WHERE row_id = ?";
  1161. my $sth = $dbh->prepare($query);
  1162. $sth->execute->( $self->{ "id" . "$linenum" } )
  1163. || $self->dberror($query);
  1164. }
  1165. elsif ( $query_type eq 'INSERT' ) {
  1166. $query .= " INTO $_ (";
  1167. }
  1168. my $first = 1;
  1169. for ( @{ $temphash{$_} } ) {
  1170. $query .= "$_";
  1171. if ( $query_type eq 'UPDATE' ) {
  1172. $query .= '= ?';
  1173. }
  1174. $ins_values .= "?, ";
  1175. $query .= ", ";
  1176. $first = 0;
  1177. if ( $query_type eq 'UPDATE' or $query_type eq 'INSERT' ) {
  1178. push @data, $self->{"$_$linenum"};
  1179. }
  1180. }
  1181. if ( $query_type ne 'INSERT' ) {
  1182. $query =~ s/, $//;
  1183. }
  1184. if ( $query_type eq 'SELECT' ) {
  1185. $query .= " FROM $_";
  1186. }
  1187. if ( $query_type eq 'SELECT' or $query_type eq 'UPDATE' ) {
  1188. $query .= " WHERE row_id = ?";
  1189. }
  1190. if ( $query_type eq 'INSERT' ) {
  1191. $query .= " row_id) VALUES ($ins_values ?)";
  1192. }
  1193. if ( $query_type eq 'SELECT' ) {
  1194. push @rc, [$query];
  1195. }
  1196. else {
  1197. unshift( @data, $query );
  1198. push @rc, [@data];
  1199. }
  1200. }
  1201. if ( $query_type eq 'INSERT' ) {
  1202. for (@rc) {
  1203. $query = shift( @{$_} );
  1204. $sth = $dbh->prepare($query)
  1205. || $self->db_error($query);
  1206. $sth->execute( @{$_}, $self->{id} )
  1207. || $self->dberror($query);
  1208. $sth->finish;
  1209. $did_insert = 1;
  1210. }
  1211. }
  1212. elsif ( $query_type eq 'UPDATE' ) {
  1213. @rc = $self->run_custom_queries( $tablename, 'INSERT', $linenum );
  1214. }
  1215. elsif ( $query_type eq 'SELECT' ) {
  1216. for (@rc) {
  1217. $query = shift @{$_};
  1218. $sth = $self->{dbh}->prepare($query);
  1219. $sth->execute( $self->{id} );
  1220. $ref = $sth->fetchrow_hashref(NAME_lc);
  1221. for ( keys %{$ref} ) {
  1222. $self->{$_} = $ref->{$_};
  1223. }
  1224. }
  1225. }
  1226. @rc;
  1227. }
  1228. sub dbconnect {
  1229. my ( $self, $myconfig ) = @_;
  1230. # connect to database
  1231. my $dbh = DBI->connect( $myconfig->{dbconnect},
  1232. $myconfig->{dbuser}, $myconfig->{dbpasswd} )
  1233. or $self->dberror;
  1234. $dbh->{pg_enable_utf8} = 1;
  1235. # set db options
  1236. if ( $myconfig->{dboptions} ) {
  1237. $dbh->do( $myconfig->{dboptions} )
  1238. || $self->dberror( $myconfig->{dboptions} );
  1239. }
  1240. $dbh;
  1241. }
  1242. sub dbconnect_noauto {
  1243. my ( $self, $myconfig ) = @_;
  1244. # connect to database
  1245. $dbh = DBI->connect(
  1246. $myconfig->{dbconnect}, $myconfig->{dbuser},
  1247. $myconfig->{dbpasswd}, { AutoCommit => 0 }
  1248. ) or $self->dberror;
  1249. $dbh->{pg_enable_utf8} = 1;
  1250. # set db options
  1251. if ( $myconfig->{dboptions} ) {
  1252. $dbh->do( $myconfig->{dboptions} );
  1253. }
  1254. $dbh;
  1255. }
  1256. sub dbquote {
  1257. my ( $self, $var ) = @_;
  1258. if ( $var eq '' ) {
  1259. $_ = "NULL";
  1260. }
  1261. else {
  1262. $_ = $self->{dbh}->quote($var);
  1263. }
  1264. $_;
  1265. }
  1266. sub update_balance {
  1267. # This is a dangerous private function. All apps calling it must
  1268. # be careful to avoid SQL injection issues
  1269. my ( $self, $dbh, $table, $field, $where, $value ) = @_;
  1270. # if we have a value, go do it
  1271. if ($value) {
  1272. # retrieve balance from table
  1273. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  1274. my ($balance) = $dbh->selectrow_array($query);
  1275. $balance += $value;
  1276. # update balance
  1277. $query = "UPDATE $table SET $field = $balance WHERE $where";
  1278. $dbh->do($query) || $self->dberror($query);
  1279. }
  1280. }
  1281. sub update_exchangerate {
  1282. my ( $self, $dbh, $curr, $transdate, $buy, $sell ) = @_;
  1283. # some sanity check for currency
  1284. return if ( $curr eq "" );
  1285. my $query = qq|
  1286. SELECT curr
  1287. FROM exchangerate
  1288. WHERE curr = ?
  1289. AND transdate = ?
  1290. FOR UPDATE|;
  1291. my $sth = $self->{dbh}->prepare($query);
  1292. $sth->execute( $curr, $transdate ) || $self->dberror($query);
  1293. my $set;
  1294. my @queryargs;
  1295. if ( $buy && $sell ) {
  1296. $set = "buy = ?, sell = ?";
  1297. @queryargs = ( $buy, $sell );
  1298. }
  1299. elsif ($buy) {
  1300. $set = "buy = ?";
  1301. @queryargs = ($buy);
  1302. }
  1303. elsif ($sell) {
  1304. $set = "sell = ?";
  1305. @queryargs = ($sell);
  1306. }
  1307. if ( !$set ) {
  1308. $self->error("Exchange rate missing!");
  1309. }
  1310. if ( $sth->fetchrow_array ) {
  1311. $query = qq|UPDATE exchangerate
  1312. SET $set
  1313. WHERE curr = ?
  1314. AND transdate = ?|;
  1315. push( @queryargs, $curr, $transdate );
  1316. }
  1317. else {
  1318. $query = qq|
  1319. INSERT INTO exchangerate (
  1320. curr, buy, sell, transdate)
  1321. VALUES (?, ?, ?, ?)|;
  1322. @queryargs = ( $curr, $buy, $sell, $transdate );
  1323. }
  1324. $sth->finish;
  1325. $sth = $self->{dbh}->prepare($query);
  1326. $sth->execute(@queryargs) || $self->dberror($query);
  1327. }
  1328. sub save_exchangerate {
  1329. my ( $self, $myconfig, $currency, $transdate, $rate, $fld ) = @_;
  1330. my ( $buy, $sell ) = ( 0, 0 );
  1331. $buy = $rate if $fld eq 'buy';
  1332. $sell = $rate if $fld eq 'sell';
  1333. $self->update_exchangerate( $self->{dbh}, $currency, $transdate, $buy,
  1334. $sell );
  1335. $dbh->commit;
  1336. }
  1337. sub get_exchangerate {
  1338. my ( $self, $dbh, $curr, $transdate, $fld ) = @_;
  1339. my $exchangerate = 1;
  1340. if ($transdate) {
  1341. my $query = qq|
  1342. SELECT $fld FROM exchangerate
  1343. WHERE curr = ? AND transdate = ?|;
  1344. $sth = $self->{dbh}->prepare($query);
  1345. $sth->execute( $curr, $transdate );
  1346. ($exchangerate) = $sth->fetchrow_array;
  1347. $exchangerate = Math::BigFloat->new($exchangerate);
  1348. }
  1349. $sth->finish;
  1350. $self->{dbh}->commit;
  1351. $exchangerate;
  1352. }
  1353. sub check_exchangerate {
  1354. my ( $self, $myconfig, $currency, $transdate, $fld ) = @_;
  1355. return "" unless $transdate;
  1356. my $query = qq|
  1357. SELECT $fld
  1358. FROM exchangerate
  1359. WHERE curr = ? AND transdate = ?|;
  1360. my $sth = $self->{dbh}->prepare($query);
  1361. $sth->execute( $currenct, $transdate );
  1362. my ($exchangerate) = $sth->fetchrow_array;
  1363. $sth->finish;
  1364. $self->{dbh}->commit;
  1365. $exchangerate;
  1366. }
  1367. sub add_shipto {
  1368. my ( $self, $dbh, $id ) = @_;
  1369. my $shipto;
  1370. foreach my $item (
  1371. qw(name address1 address2 city state
  1372. zipcode country contact phone fax email)
  1373. )
  1374. {
  1375. if ( $self->{"shipto$item"} ne "" ) {
  1376. $shipto = 1 if ( $self->{$item} ne $self->{"shipto$item"} );
  1377. }
  1378. }
  1379. if ($shipto) {
  1380. my $query = qq|
  1381. INSERT INTO shipto
  1382. (trans_id, shiptoname, shiptoaddress1,
  1383. shiptoaddress2, shiptocity, shiptostate,
  1384. shiptozipcode, shiptocountry, shiptocontact,
  1385. shiptophone, shiptofax, shiptoemail)
  1386. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1387. |;
  1388. $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  1389. $sth->execute(
  1390. $id, $self->{shiptoname},
  1391. $self->{shiptoaddress1}, $self->{shiptoaddress2},
  1392. $self->{shiptocity}, $self->{shiptostate},
  1393. $self->{shiptozipcode}, $self->{shiptocountry},
  1394. $self->{shiptocontact}, $self->{shiptophone},
  1395. $self->{shiptofax}, $self->{shiptoemail}
  1396. ) || $self->dberror($query);
  1397. $sth->finish;
  1398. $self->{dbh}->commit;
  1399. }
  1400. }
  1401. sub get_employee {
  1402. my ( $self, $dbh ) = @_;
  1403. my $login = $self->{login};
  1404. $login =~ s/@.*//;
  1405. my $query = qq|SELECT name, id
  1406. FROM employee
  1407. WHERE login = ?|;
  1408. $sth = $self->{dbh}->prepare($query);
  1409. $sth->execute($login);
  1410. my (@a) = $sth->fetchrow_array();
  1411. $a[1] *= 1;
  1412. $sth->finish;
  1413. $self->{dbh}->commit;
  1414. @a;
  1415. }
  1416. # this sub gets the id and name from $table
  1417. sub get_name {
  1418. my ( $self, $myconfig, $table, $transdate ) = @_;
  1419. # connect to database
  1420. my @queryargs;
  1421. my $where;
  1422. if ($transdate) {
  1423. $where = qq|
  1424. AND (startdate IS NULL OR startdate <= ?)
  1425. AND (enddate IS NULL OR enddate >= ?)|;
  1426. @queryargs = ( $transdate, $transdate );
  1427. }
  1428. my $name = $self->like( lc $self->{$table} );
  1429. my $query = qq|
  1430. SELECT * FROM $table
  1431. WHERE (lower(name) LIKE ? OR ${table}number LIKE ?)
  1432. $where
  1433. ORDER BY name|;
  1434. unshift( @queryargs, $name, $name );
  1435. my $sth = $self->{dbh}->prepare($query);
  1436. $sth->execute(@queryargs) || $self->dberror($query);
  1437. my $i = 0;
  1438. @{ $self->{name_list} } = ();
  1439. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1440. push( @{ $self->{name_list} }, $ref );
  1441. $i++;
  1442. }
  1443. $sth->finish;
  1444. $self->{dbh}->commit;
  1445. $i;
  1446. }
  1447. sub all_vc {
  1448. my ( $self, $myconfig, $vc, $module, $dbh, $transdate, $job ) = @_;
  1449. my $ref;
  1450. my $disconnect = 0;
  1451. $dbh = $self->{dbh};
  1452. my $sth;
  1453. my $query = qq|SELECT count(*) FROM $vc|;
  1454. my $where;
  1455. my @queryargs = ();
  1456. if ($transdate) {
  1457. $query .= qq| WHERE (startdate IS NULL OR startdate <= ?)
  1458. AND (enddate IS NULL OR enddate >= ?)|;
  1459. @queryargs = ( $transdate, $transdate );
  1460. }
  1461. $sth = $dbh->prepare($query);
  1462. $sth->execute(@queryargs);
  1463. my ($count) = $sth->fetchrow_array;
  1464. $sth->finish;
  1465. @queryargs = ();
  1466. # build selection list
  1467. if ( $count < $myconfig->{vclimit} ) {
  1468. $self->{"${vc}_id"} *= 1;
  1469. $query = qq|SELECT id, name
  1470. FROM $vc
  1471. WHERE 1=1
  1472. $where
  1473. UNION
  1474. SELECT id,name
  1475. FROM $vc
  1476. WHERE id = ?
  1477. ORDER BY name|;
  1478. push( @queryargs, $self->{"${vc}_id"} );
  1479. $sth = $dbh->prepare($query);
  1480. $sth->execute(@queryargs) || $self->dberror($query);
  1481. @{ $self->{"all_$vc"} } = ();
  1482. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1483. push @{ $self->{"all_$vc"} }, $ref;
  1484. }
  1485. $sth->finish;
  1486. }
  1487. # get self
  1488. if ( !$self->{employee_id} ) {
  1489. ( $self->{employee}, $self->{employee_id} ) = split /--/,
  1490. $self->{employee};
  1491. ( $self->{employee}, $self->{employee_id} ) = $self->get_employee($dbh)
  1492. unless $self->{employee_id};
  1493. }
  1494. $self->all_employees( $myconfig, $dbh, $transdate, 1 );
  1495. $self->all_departments( $myconfig, $dbh, $vc );
  1496. $self->all_projects( $myconfig, $dbh, $transdate, $job );
  1497. # get language codes
  1498. $query = qq|SELECT *
  1499. FROM language
  1500. ORDER BY 2|;
  1501. $sth = $dbh->prepare($query);
  1502. $sth->execute || $self->dberror($query);
  1503. $self->{all_language} = ();
  1504. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1505. push @{ $self->{all_language} }, $ref;
  1506. }
  1507. $sth->finish;
  1508. $self->all_taxaccounts( $myconfig, $dbh, $transdate );
  1509. $self->{dbh}->commit;
  1510. }
  1511. sub all_taxaccounts {
  1512. my ( $self, $myconfig, $dbh2, $transdate ) = @_;
  1513. my $dbh = $self->{dbh};
  1514. my $sth;
  1515. my $query;
  1516. my $where;
  1517. my @queryargs = ();
  1518. if ($transdate) {
  1519. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1520. push( @queryargs, $transdate );
  1521. }
  1522. if ( $self->{taxaccounts} ) {
  1523. # rebuild tax rates
  1524. $query = qq|SELECT t.rate, t.taxnumber
  1525. FROM tax t
  1526. JOIN chart c ON (c.id = t.chart_id)
  1527. WHERE c.accno = ?
  1528. $where
  1529. ORDER BY accno, validto|;
  1530. $sth = $dbh->prepare($query) || $self->dberror($query);
  1531. foreach my $accno ( split / /, $self->{taxaccounts} ) {
  1532. $sth->execute( $accno, @queryargs );
  1533. ( $self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"} ) =
  1534. $sth->fetchrow_array;
  1535. $sth->finish;
  1536. }
  1537. }
  1538. $self->{dbh}->commit;
  1539. }
  1540. sub all_employees {
  1541. my ( $self, $myconfig, $dbh2, $transdate, $sales ) = @_;
  1542. my $dbh = $self->{dbh};
  1543. my @whereargs = ();
  1544. # setup employees/sales contacts
  1545. my $query = qq|SELECT id, name
  1546. FROM employee
  1547. WHERE 1 = 1|;
  1548. if ($transdate) {
  1549. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1550. AND (enddate IS NULL OR enddate >= ?)|;
  1551. @whereargs = ( $transdate, $transdate );
  1552. }
  1553. else {
  1554. $query .= qq| AND enddate IS NULL|;
  1555. }
  1556. if ($sales) {
  1557. $query .= qq| AND sales = '1'|;
  1558. }
  1559. $query .= qq| ORDER BY name|;
  1560. my $sth = $dbh->prepare($query);
  1561. $sth->execute(@whereargs) || $self->dberror($query);
  1562. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1563. push @{ $self->{all_employee} }, $ref;
  1564. }
  1565. $sth->finish;
  1566. $dbh->commit;
  1567. }
  1568. sub all_projects {
  1569. my ( $self, $myconfig, $dbh2, $transdate, $job ) = @_;
  1570. my $dbh = $self->{dbh};
  1571. my @queryargs = ();
  1572. my $where = "1 = 1";
  1573. $where = qq|id NOT IN (SELECT id
  1574. FROM parts
  1575. WHERE project_id > 0)| if !$job;
  1576. my $query = qq|SELECT *
  1577. FROM project
  1578. WHERE $where|;
  1579. if ( $self->{language_code} ) {
  1580. $query = qq|
  1581. SELECT pr.*, t.description AS translation
  1582. FROM project pr
  1583. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1584. WHERE t.language_code = ?|;
  1585. push( @queryargs, $self->{language_code} );
  1586. }
  1587. if ($transdate) {
  1588. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1589. AND (enddate IS NULL OR enddate >= ?)|;
  1590. push( @queryargs, $transdate, $transdate );
  1591. }
  1592. $query .= qq| ORDER BY projectnumber|;
  1593. $sth = $dbh->prepare($query);
  1594. $sth->execute(@queryargs) || $self->dberror($query);
  1595. @{ $self->{all_project} } = ();
  1596. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1597. push @{ $self->{all_project} }, $ref;
  1598. }
  1599. $sth->finish;
  1600. $dbh->commit;
  1601. }
  1602. sub all_departments {
  1603. my ( $self, $myconfig, $dbh2, $vc ) = @_;
  1604. $dbh = $self->{dbh};
  1605. my $where = "1 = 1";
  1606. if ($vc) {
  1607. if ( $vc eq 'customer' ) {
  1608. $where = " role = 'P'";
  1609. }
  1610. }
  1611. my $query = qq|SELECT id, description
  1612. FROM department
  1613. WHERE $where
  1614. ORDER BY 2|;
  1615. my $sth = $dbh->prepare($query);
  1616. $sth->execute || $self->dberror($query);
  1617. @{ $self->{all_department} } = ();
  1618. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1619. push @{ $self->{all_department} }, $ref;
  1620. }
  1621. $sth->finish;
  1622. $self->all_years($myconfig);
  1623. $dbh->commit;
  1624. }
  1625. sub all_years {
  1626. my ( $self, $myconfig, $dbh2 ) = @_;
  1627. $dbh = $self->{dbh};
  1628. # get years
  1629. my $query = qq|
  1630. SELECT (SELECT transdate FROM acc_trans ORDER BY transdate asc
  1631. LIMIT 1),
  1632. (SELECT transdate FROM acc_trans ORDER BY transdate desc
  1633. LIMIT 1)|;
  1634. my ( $startdate, $enddate ) = $dbh->selectrow_array($query);
  1635. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1636. ($startdate) = split /\W/, $startdate;
  1637. ($enddate) = split /\W/, $enddate;
  1638. }
  1639. else {
  1640. (@_) = split /\W/, $startdate;
  1641. $startdate = $_[2];
  1642. (@_) = split /\W/, $enddate;
  1643. $enddate = $_[2];
  1644. }
  1645. $self->{all_years} = ();
  1646. $startdate = substr( $startdate, 0, 4 );
  1647. $enddate = substr( $enddate, 0, 4 );
  1648. while ( $enddate >= $startdate ) {
  1649. push @{ $self->{all_years} }, $enddate--;
  1650. }
  1651. #this should probably be changed to use locale
  1652. %{ $self->{all_month} } = (
  1653. '01' => 'January',
  1654. '02' => 'February',
  1655. '03' => 'March',
  1656. '04' => 'April',
  1657. '05' => 'May ',
  1658. '06' => 'June',
  1659. '07' => 'July',
  1660. '08' => 'August',
  1661. '09' => 'September',
  1662. '10' => 'October',
  1663. '11' => 'November',
  1664. '12' => 'December'
  1665. );
  1666. $dbh->commit;
  1667. }
  1668. sub create_links {
  1669. my ( $self, $module, $myconfig, $vc, $job ) = @_;
  1670. # get last customers or vendors
  1671. my ( $query, $sth );
  1672. if (!$self->{dbh}) {
  1673. $self->db_init($myconfig);
  1674. }
  1675. $dbh = $self->{dbh};
  1676. my %xkeyref = ();
  1677. # now get the account numbers
  1678. $query = qq|SELECT accno, description, link
  1679. FROM chart
  1680. WHERE link LIKE ?
  1681. ORDER BY accno|;
  1682. $sth = $dbh->prepare($query);
  1683. $sth->execute( "%" . "$module%" ) || $self->dberror($query);
  1684. $self->{accounts} = "";
  1685. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1686. foreach my $key ( split /:/, $ref->{link} ) {
  1687. if ( $key =~ /$module/ ) {
  1688. # cross reference for keys
  1689. $xkeyref{ $ref->{accno} } = $key;
  1690. push @{ $self->{"${module}_links"}{$key} },
  1691. {
  1692. accno => $ref->{accno},
  1693. description => $ref->{description}
  1694. };
  1695. $self->{accounts} .= "$ref->{accno} "
  1696. unless $key =~ /tax/;
  1697. }
  1698. }
  1699. }
  1700. $sth->finish;
  1701. my $arap = ( $vc eq 'customer' ) ? 'ar' : 'ap';
  1702. if ( $self->{id} ) {
  1703. $query = qq|
  1704. SELECT a.invnumber, a.transdate,
  1705. a.${vc}_id, a.datepaid, a.duedate, a.ordnumber,
  1706. a.taxincluded, a.curr AS currency, a.notes,
  1707. a.intnotes, c.name AS $vc, a.department_id,
  1708. d.description AS department,
  1709. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1710. a.employee_id, e.name AS employee,
  1711. c.language_code, a.ponumber
  1712. FROM $arap a
  1713. JOIN $vc c ON (a.${vc}_id = c.id)
  1714. LEFT JOIN employee e ON (e.id = a.employee_id)
  1715. LEFT JOIN department d ON (d.id = a.department_id)
  1716. WHERE a.id = ?|;
  1717. $sth = $dbh->prepare($query);
  1718. $sth->execute( $self->{id} ) || $self->dberror($query);
  1719. $ref = $sth->fetchrow_hashref(NAME_lc);
  1720. $self->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1721. foreach $key ( keys %$ref ) {
  1722. $self->{$key} = $ref->{$key};
  1723. }
  1724. $sth->finish;
  1725. # get printed, emailed
  1726. $query = qq|
  1727. SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1728. FROM status s WHERE s.trans_id = ?|;
  1729. $sth = $dbh->prepare($query);
  1730. $sth->execute( $self->{id} ) || $self->dberror($query);
  1731. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1732. $self->{printed} .= "$ref->{formname} "
  1733. if $ref->{printed};
  1734. $self->{emailed} .= "$ref->{formname} "
  1735. if $ref->{emailed};
  1736. $self->{queued} .= "$ref->{formname} " . "$ref->{spoolfile} "
  1737. if $ref->{spoolfile};
  1738. }
  1739. $sth->finish;
  1740. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1741. # get recurring
  1742. $self->get_recurring($dbh);
  1743. # get amounts from individual entries
  1744. $query = qq|
  1745. SELECT c.accno, c.description, a.source, a.amount,
  1746. a.memo, a.transdate, a.cleared, a.project_id,
  1747. p.projectnumber
  1748. FROM acc_trans a
  1749. JOIN chart c ON (c.id = a.chart_id)
  1750. LEFT JOIN project p ON (p.id = a.project_id)
  1751. WHERE a.trans_id = ?
  1752. AND a.fx_transaction = '0'
  1753. ORDER BY transdate|;
  1754. $sth = $dbh->prepare($query);
  1755. $sth->execute( $self->{id} ) || $self->dberror($query);
  1756. my $fld = ( $vc eq 'customer' ) ? 'buy' : 'sell';
  1757. $self->{exchangerate} =
  1758. $self->get_exchangerate( $dbh, $self->{currency}, $self->{transdate},
  1759. $fld );
  1760. # store amounts in {acc_trans}{$key} for multiple accounts
  1761. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1762. $self->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1763. $ref->{exchangerate} =
  1764. $self->get_exchangerate( $dbh, $self->{currency},
  1765. $ref->{transdate}, $fld );
  1766. push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
  1767. }
  1768. $sth->finish;
  1769. for (qw(curr closedto revtrans)) {
  1770. $query = qq|
  1771. SELECT value FROM defaults
  1772. WHERE setting_key = '$_'|;
  1773. $sth = $dbh->prepare($query);
  1774. $sth->execute || $self->dberror($query);
  1775. ($val) = $sth->fetchrow_array();
  1776. if ( $_ eq 'curr' ) {
  1777. $self->{currencies} = $val;
  1778. }
  1779. else {
  1780. $self->{$_} = $val;
  1781. }
  1782. $sth->finish;
  1783. }
  1784. }
  1785. else {
  1786. for (qw(curr closedto revtrans)) {
  1787. $query = qq|
  1788. SELECT value FROM defaults
  1789. WHERE setting_key = '$_'|;
  1790. $sth = $dbh->prepare($query);
  1791. $sth->execute || $self->dberror($query);
  1792. ($val) = $sth->fetchrow_array();
  1793. if ( $_ eq 'curr' ) {
  1794. $self->{currencies} = $val;
  1795. }
  1796. else {
  1797. $self->{$_} = $val;
  1798. }
  1799. $sth->finish;
  1800. }
  1801. $self->{transdate} = $self->current_date;
  1802. if ( !$self->{"$self->{vc}_id"} ) {
  1803. $self->lastname_used( $myconfig, $dbh, $vc, $module );
  1804. }
  1805. }
  1806. $self->all_vc( $myconfig, $vc, $module, $dbh, $self->{transdate}, $job );
  1807. $self->{dbh}->commit;
  1808. }
  1809. sub lastname_used {
  1810. my ( $self, $myconfig, $dbh2, $vc, $module ) = @_;
  1811. my $dbh = $self->{dbh};
  1812. $vc ||= $self->{vc}; # add default to correct for improper passing
  1813. my $arap = ( $vc eq 'customer' ) ? "ar" : "ap";
  1814. my $where = "1 = 1";
  1815. my $sth;
  1816. if ( $self->{type} =~ /_order/ ) {
  1817. $arap = 'oe';
  1818. $where = "quotation = '0'";
  1819. }
  1820. if ( $self->{type} =~ /_quotation/ ) {
  1821. $arap = 'oe';
  1822. $where = "quotation = '1'";
  1823. }
  1824. my $query = qq|
  1825. SELECT ct.name AS $vc, ct.curr AS currency, ct.id AS ${vc}_id,
  1826. current_date + ct.terms AS duedate,
  1827. ct.notes,
  1828. ct.curr AS currency
  1829. FROM $vc ct
  1830. WHERE ct.id = (select ${vc}_id from $arap where $where AND ${vc}_id IS NOT NULL order by id DESC limit 1)|;
  1831. $sth = $dbh->prepare($query);
  1832. $sth->execute() || $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;