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