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