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