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