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