summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: 26dbd40b028ffd844c431dc3a230c635ea671d51 (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. # 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. 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. }
  883. else {
  884. s/<\?lsmb $var \?>//;
  885. }
  886. next;
  887. }
  888. if ( $var =~ /^if\s+/ ) {
  889. if ($str) {
  890. s/<\?lsmb $var \?>//;
  891. }
  892. else {
  893. $var =~ s/if\s+//;
  894. s/<\?lsmb if\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  895. }
  896. next;
  897. }
  898. if ( $var =~ /^end\s+/ ) {
  899. s/<\?lsmb $var \?>//;
  900. next;
  901. }
  902. if ( $a{align} || $a{width} || $a{offset} ) {
  903. $newstr = "";
  904. $offset = 0;
  905. $lf = "";
  906. foreach $str ( split /\n/, $str ) {
  907. $line = $str;
  908. $l = length $str;
  909. do {
  910. if ( ( $pos = length $str ) > $a{width} ) {
  911. if ( ( $pos = rindex $str, " ", $a{width} ) > 0 ) {
  912. $line = substr( $str, 0, $pos );
  913. }
  914. $pos = length $str if $pos == -1;
  915. }
  916. $l = length $line;
  917. # pad left, right or center
  918. $l = ( $a{width} - $l );
  919. $pad = " " x $l;
  920. if ( $a{align} =~ /right/i ) {
  921. $line = " " x $offset . $pad . $line;
  922. }
  923. if ( $a{align} =~ /left/i ) {
  924. $line = " " x $offset . $line . $pad;
  925. }
  926. if ( $a{align} =~ /center/i ) {
  927. $pad = " " x ( $l / 2 );
  928. $line = " " x $offset . $pad . $line;
  929. $pad = " " x ( $l / 2 );
  930. $line .= $pad;
  931. }
  932. $newstr .= "$lf$line";
  933. $str = substr( $str, $pos + 1 );
  934. $line = $str;
  935. $lf = "\n";
  936. $offset = $a{offset};
  937. } while ($str);
  938. }
  939. }
  940. s/<\?lsmb (.+?) \?>/$newstr/;
  941. }
  942. $_;
  943. }
  944. sub cleanup {
  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. quotemeta('$'), '%', '_', '#',
  985. quotemeta('^'), '{', '}', '<',
  986. '>', '£'
  987. ]
  988. },
  989. html => {
  990. '<' => '&lt;',
  991. '>' => '&gt;',
  992. '&' => '&amp;',
  993. '\n' => '<br />',
  994. '\r' => '<br />'
  995. },
  996. txt => { '\n' => "\n", '\r' => "\r" },
  997. tex => {
  998. '&' => '\&',
  999. quotemeta('$') => '\$',
  1000. '%' => '\%',
  1001. '_' => '\_',
  1002. '#' => '\#',
  1003. quotemeta('^') => '\^\\',
  1004. '{' => '\{',
  1005. '}' => '\}',
  1006. '<' => '$<$',
  1007. '>' => '$>$',
  1008. '\n' => '\newline ',
  1009. '\r' => '\newline ',
  1010. '£' => '\pounds ',
  1011. quotemeta('\\') => '/'
  1012. }
  1013. );
  1014. my $key;
  1015. foreach $key ( @{ $replace{order}{$format} } ) {
  1016. for (@fields) { $self->{$_} =~ s/$key/$replace{$format}{$key}/g }
  1017. }
  1018. }
  1019. sub datetonum {
  1020. my ( $self, $myconfig, $date, $picture ) = @_;
  1021. if ( $date && $date =~ /\D/ ) {
  1022. if ( $date =~ /^\d{4}-\d\d-\d\d$/ ) {
  1023. # SC: Handle standard form of YYYY-MM-DD
  1024. ( $yy, $mm, $dd ) = split /\D/, $date;
  1025. } elsif ( $myconfig->{dateformat} =~ /^yy/ ) {
  1026. ( $yy, $mm, $dd ) = split /\D/, $date;
  1027. } elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  1028. ( $mm, $dd, $yy ) = split /\D/, $date;
  1029. } elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  1030. ( $dd, $mm, $yy ) = split /\D/, $date;
  1031. }
  1032. $dd *= 1;
  1033. $mm *= 1;
  1034. $yy += 2000 if length $yy == 2;
  1035. $dd = substr( "0$dd", -2 );
  1036. $mm = substr( "0$mm", -2 );
  1037. $date = "$yy$mm$dd";
  1038. }
  1039. $date;
  1040. }
  1041. sub add_date {
  1042. my ( $self, $myconfig, $date, $repeat, $unit ) = @_;
  1043. my $diff = 0;
  1044. my $spc = $myconfig->{dateformat};
  1045. my $yy;
  1046. my $mm;
  1047. my $dd;
  1048. $spc =~ s/\w//g;
  1049. $spc = substr( $spc, 0, 1 );
  1050. if ($date) {
  1051. if ( $date =~ /\D/ ) {
  1052. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1053. ( $yy, $mm, $dd ) = split /\D/, $date;
  1054. }
  1055. if ( $myconfig->{dateformat} =~ /^mm/ ) {
  1056. ( $mm, $dd, $yy ) = split /\D/, $date;
  1057. }
  1058. if ( $myconfig->{dateformat} =~ /^dd/ ) {
  1059. ( $dd, $mm, $yy ) = split /\D/, $date;
  1060. }
  1061. }
  1062. else {
  1063. # ISO
  1064. ( $yy, $mm, $dd ) = ($date =~ /(....)(..)(..)/);
  1065. }
  1066. if ( $unit eq 'days' ) {
  1067. $diff = $repeat * 86400;
  1068. }
  1069. if ( $unit eq 'weeks' ) {
  1070. $diff = $repeat * 604800;
  1071. }
  1072. if ( $unit eq 'months' ) {
  1073. $diff = $mm + $repeat;
  1074. my $whole = int( $diff / 12 );
  1075. $yy += $whole;
  1076. $mm = ( $diff % 12 );
  1077. $mm = '12' if $mm == 0;
  1078. $yy-- if $mm == 12;
  1079. $diff = 0;
  1080. }
  1081. if ( $unit eq 'years' ) {
  1082. $yy += $repeat;
  1083. }
  1084. $mm--;
  1085. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yy ) + $diff );
  1086. $t[4]++;
  1087. $mm = substr( "0$t[4]", -2 );
  1088. $dd = substr( "0$t[3]", -2 );
  1089. $yy = $t[5] + 1900;
  1090. if ( $date =~ /\D/ ) {
  1091. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1092. $date = "$yy$spc$mm$spc$dd";
  1093. }
  1094. if ( $myconfig->{dateformat} =~ /^mm/ ) {
  1095. $date = "$mm$spc$dd$spc$yy";
  1096. }
  1097. if ( $myconfig->{dateformat} =~ /^dd/ ) {
  1098. $date = "$dd$spc$mm$spc$yy";
  1099. }
  1100. }
  1101. else {
  1102. $date = "$yy$mm$dd";
  1103. }
  1104. }
  1105. $date;
  1106. }
  1107. sub print_button {
  1108. my ( $self, $button, $name ) = @_;
  1109. print
  1110. 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|;
  1111. }
  1112. # Database routines used throughout
  1113. sub db_init {
  1114. my ( $self, $myconfig ) = @_;
  1115. $self->{dbh} = $self->dbconnect_noauto($myconfig) || $self->dberror();
  1116. %date_query = (
  1117. 'mm/dd/yy' => 'set DateStyle to \'SQL, US\'',
  1118. 'mm-dd-yy' => 'set DateStyle to \'POSTGRES, US\'',
  1119. 'dd/mm/yy' => 'set DateStyle to \'SQL, EUROPEAN\'',
  1120. 'dd-mm-yy' => 'set DateStyle to \'POSTGRES, EUROPEAN\'',
  1121. 'dd.mm.yy' => 'set DateStyle to \'GERMAN\''
  1122. );
  1123. $self->{dbh}->do( $date_query{ $myconfig->{dateformat} } );
  1124. $self->{db_dateformat} = $myconfig->{dateformat}; #shim
  1125. #$self->{dbh}->do('set log_statement to \'all\'');
  1126. my $query = "SELECT t.extends,
  1127. coalesce (t.table_name, 'custom_' || extends)
  1128. || ':' || f.field_name as field_def
  1129. FROM custom_table_catalog t
  1130. JOIN custom_field_catalog f USING (table_id)";
  1131. my $sth = $self->{dbh}->prepare($query);
  1132. $sth->execute;
  1133. my $ref;
  1134. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1135. push @{ $self->{custom_db_fields}{ $ref->{extends} } },
  1136. $ref->{field_def};
  1137. }
  1138. }
  1139. sub run_custom_queries {
  1140. my ( $self, $tablename, $query_type, $linenum ) = @_;
  1141. my $dbh = $self->{dbh};
  1142. if ( $query_type !~ /^(select|insert|update)$/i ) {
  1143. $self->error(
  1144. $locale->text(
  1145. "Passed incorrect query type to run_custom_queries."
  1146. )
  1147. );
  1148. }
  1149. my @rc;
  1150. my %temphash;
  1151. my @templist;
  1152. my @elements;
  1153. my $query;
  1154. my $ins_values;
  1155. if ($linenum) {
  1156. $linenum = "_$linenum";
  1157. }
  1158. $query_type = uc($query_type);
  1159. for ( @{ $self->{custom_db_fields}{$tablename} } ) {
  1160. @elements = split( /:/, $_ );
  1161. push @{ $temphash{ $elements[0] } }, $elements[1];
  1162. }
  1163. for ( keys %temphash ) {
  1164. my @data;
  1165. my $ins_values;
  1166. $query = "$query_type ";
  1167. if ( $query_type eq 'UPDATE' ) {
  1168. $query = "DELETE FROM $_ WHERE row_id = ?";
  1169. my $sth = $dbh->prepare($query);
  1170. $sth->execute( $self->{ "id" . "$linenum" } )
  1171. || $self->dberror($query);
  1172. }
  1173. elsif ( $query_type eq 'INSERT' ) {
  1174. $query .= " INTO $_ (";
  1175. }
  1176. my $first = 1;
  1177. for ( @{ $temphash{$_} } ) {
  1178. $query .= "$_";
  1179. if ( $query_type eq 'UPDATE' ) {
  1180. $query .= '= ?';
  1181. }
  1182. $ins_values .= "?, ";
  1183. $query .= ", ";
  1184. $first = 0;
  1185. if ( $query_type eq 'UPDATE' or $query_type eq 'INSERT' ) {
  1186. push @data, $self->{"$_$linenum"};
  1187. }
  1188. }
  1189. if ( $query_type ne 'INSERT' ) {
  1190. $query =~ s/, $//;
  1191. }
  1192. if ( $query_type eq 'SELECT' ) {
  1193. $query .= " FROM $_";
  1194. }
  1195. if ( $query_type eq 'SELECT' or $query_type eq 'UPDATE' ) {
  1196. $query .= " WHERE row_id = ?";
  1197. }
  1198. if ( $query_type eq 'INSERT' ) {
  1199. $query .= " row_id) VALUES ($ins_values ?)";
  1200. }
  1201. if ( $query_type eq 'SELECT' ) {
  1202. push @rc, [$query];
  1203. }
  1204. else {
  1205. unshift( @data, $query );
  1206. push @rc, [@data];
  1207. }
  1208. }
  1209. if ( $query_type eq 'INSERT' ) {
  1210. for (@rc) {
  1211. $query = shift( @{$_} );
  1212. $sth = $dbh->prepare($query)
  1213. || $self->db_error($query);
  1214. $sth->execute( @{$_}, $self->{id} )
  1215. || $self->dberror($query);
  1216. $sth->finish;
  1217. $did_insert = 1;
  1218. }
  1219. }
  1220. elsif ( $query_type eq 'UPDATE' ) {
  1221. @rc = $self->run_custom_queries( $tablename, 'INSERT', $linenum );
  1222. }
  1223. elsif ( $query_type eq 'SELECT' ) {
  1224. for (@rc) {
  1225. $query = shift @{$_};
  1226. $sth = $self->{dbh}->prepare($query);
  1227. $sth->execute( $self->{id} );
  1228. $ref = $sth->fetchrow_hashref('NAME_lc');
  1229. for ( keys %{$ref} ) {
  1230. $self->{$_} = $ref->{$_};
  1231. }
  1232. }
  1233. }
  1234. @rc;
  1235. }
  1236. sub dbconnect {
  1237. my ( $self, $myconfig ) = @_;
  1238. # connect to database
  1239. my $dbh = DBI->connect( $myconfig->{dbconnect},
  1240. $myconfig->{dbuser}, $myconfig->{dbpasswd} )
  1241. or $self->dberror;
  1242. $dbh->{pg_enable_utf8} = 1;
  1243. # set db options
  1244. if ( $myconfig->{dboptions} ) {
  1245. $dbh->do( $myconfig->{dboptions} )
  1246. || $self->dberror( $myconfig->{dboptions} );
  1247. }
  1248. $dbh;
  1249. }
  1250. sub dbconnect_noauto {
  1251. my ( $self, $myconfig ) = @_;
  1252. # connect to database
  1253. $dbh = DBI->connect(
  1254. $myconfig->{dbconnect}, $myconfig->{dbuser},
  1255. $myconfig->{dbpasswd}, { AutoCommit => 0 }
  1256. ) or $self->dberror;
  1257. $dbh->{pg_enable_utf8} = 1;
  1258. # set db options
  1259. if ( $myconfig->{dboptions} ) {
  1260. $dbh->do( $myconfig->{dboptions} );
  1261. }
  1262. $dbh;
  1263. }
  1264. sub dbquote {
  1265. my ( $self, $var ) = @_;
  1266. if ( $var eq '' ) {
  1267. $_ = "NULL";
  1268. }
  1269. else {
  1270. $_ = $self->{dbh}->quote($var);
  1271. }
  1272. $_;
  1273. }
  1274. sub update_balance {
  1275. # This is a dangerous private function. All apps calling it must
  1276. # be careful to avoid SQL injection issues
  1277. my ( $self, $dbh, $table, $field, $where, $value ) = @_;
  1278. # if we have a value, go do it
  1279. if ($value) {
  1280. $table = $dbh->quote_identifier($table);
  1281. $field = $dbh->quote_identifier($field);
  1282. # retrieve balance from table
  1283. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  1284. my ($balance) = $dbh->selectrow_array($query);
  1285. $balance = $dbh->quote($balance + $value);
  1286. # update balance
  1287. $query = "UPDATE $table SET $field = $balance WHERE $where";
  1288. $dbh->do($query) || $self->dberror($query);
  1289. }
  1290. }
  1291. sub update_exchangerate {
  1292. my ( $self, $dbh, $curr, $transdate, $buy, $sell ) = @_;
  1293. # some sanity check for currency
  1294. return if ( $curr eq "" );
  1295. my $query = qq|
  1296. SELECT curr
  1297. FROM exchangerate
  1298. WHERE curr = ?
  1299. AND transdate = ?
  1300. FOR UPDATE|;
  1301. my $sth = $self->{dbh}->prepare($query);
  1302. $sth->execute( $curr, $transdate ) || $self->dberror($query);
  1303. my $set;
  1304. my @queryargs;
  1305. if ( $buy && $sell ) {
  1306. $set = "buy = ?, sell = ?";
  1307. @queryargs = ( $buy, $sell );
  1308. }
  1309. elsif ($buy) {
  1310. $set = "buy = ?";
  1311. @queryargs = ($buy);
  1312. }
  1313. elsif ($sell) {
  1314. $set = "sell = ?";
  1315. @queryargs = ($sell);
  1316. }
  1317. if ( !$set ) {
  1318. $self->error("Exchange rate missing!");
  1319. }
  1320. if ( $sth->fetchrow_array ) {
  1321. $query = qq|UPDATE exchangerate
  1322. SET $set
  1323. WHERE curr = ?
  1324. AND transdate = ?|;
  1325. push( @queryargs, $curr, $transdate );
  1326. }
  1327. else {
  1328. $query = qq|
  1329. INSERT INTO exchangerate (
  1330. curr, buy, sell, transdate)
  1331. VALUES (?, ?, ?, ?)|;
  1332. @queryargs = ( $curr, $buy, $sell, $transdate );
  1333. }
  1334. $sth->finish;
  1335. $sth = $self->{dbh}->prepare($query);
  1336. $sth->execute(@queryargs) || $self->dberror($query);
  1337. }
  1338. sub save_exchangerate {
  1339. my ( $self, $myconfig, $currency, $transdate, $rate, $fld ) = @_;
  1340. my ( $buy, $sell ) = ( 0, 0 );
  1341. $buy = $rate if $fld eq 'buy';
  1342. $sell = $rate if $fld eq 'sell';
  1343. $self->update_exchangerate( $self->{dbh}, $currency, $transdate, $buy,
  1344. $sell );
  1345. $dbh->commit;
  1346. }
  1347. sub get_exchangerate {
  1348. my ( $self, $dbh, $curr, $transdate, $fld ) = @_;
  1349. my $exchangerate = 1;
  1350. if ($transdate) {
  1351. my $query = qq|
  1352. SELECT $fld FROM exchangerate
  1353. WHERE curr = ? AND transdate = ?|;
  1354. my $sth = $self->{dbh}->prepare($query);
  1355. $sth->execute( $curr, $transdate );
  1356. ($exchangerate) = $sth->fetchrow_array;
  1357. $exchangerate = Math::BigFloat->new($exchangerate);
  1358. $sth->finish;
  1359. }
  1360. $self->{dbh}->commit;
  1361. $exchangerate;
  1362. }
  1363. sub check_exchangerate {
  1364. my ( $self, $myconfig, $currency, $transdate, $fld ) = @_;
  1365. return "" unless $transdate;
  1366. my $query = qq|
  1367. SELECT $fld
  1368. FROM exchangerate
  1369. WHERE curr = ? AND transdate = ?|;
  1370. my $sth = $self->{dbh}->prepare($query);
  1371. $sth->execute( $currency, $transdate );
  1372. my ($exchangerate) = $sth->fetchrow_array;
  1373. $sth->finish;
  1374. $self->{dbh}->commit;
  1375. $exchangerate;
  1376. }
  1377. sub add_shipto {
  1378. my ( $self, $dbh, $id ) = @_;
  1379. my $shipto;
  1380. foreach my $item (
  1381. qw(name address1 address2 city state
  1382. zipcode country contact phone fax email)
  1383. )
  1384. {
  1385. if ( $self->{"shipto$item"} ne "" ) {
  1386. $shipto = 1 if ( $self->{$item} ne $self->{"shipto$item"} );
  1387. }
  1388. }
  1389. if ($shipto) {
  1390. my $query = qq|
  1391. INSERT INTO shipto
  1392. (trans_id, shiptoname, shiptoaddress1,
  1393. shiptoaddress2, shiptocity, shiptostate,
  1394. shiptozipcode, shiptocountry, shiptocontact,
  1395. shiptophone, shiptofax, shiptoemail)
  1396. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1397. |;
  1398. $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  1399. $sth->execute(
  1400. $id, $self->{shiptoname},
  1401. $self->{shiptoaddress1}, $self->{shiptoaddress2},
  1402. $self->{shiptocity}, $self->{shiptostate},
  1403. $self->{shiptozipcode}, $self->{shiptocountry},
  1404. $self->{shiptocontact}, $self->{shiptophone},
  1405. $self->{shiptofax}, $self->{shiptoemail}
  1406. ) || $self->dberror($query);
  1407. $sth->finish;
  1408. $self->{dbh}->commit;
  1409. }
  1410. }
  1411. sub get_employee {
  1412. my ( $self, $dbh ) = @_;
  1413. my $login = $self->{login};
  1414. $login =~ s/@.*//;
  1415. my $query = qq|SELECT name, id
  1416. FROM employee
  1417. WHERE login = ?|;
  1418. $sth = $self->{dbh}->prepare($query);
  1419. $sth->execute($login);
  1420. my (@a) = $sth->fetchrow_array();
  1421. $a[1] *= 1;
  1422. $sth->finish;
  1423. $self->{dbh}->commit;
  1424. @a;
  1425. }
  1426. # this sub gets the id and name from $table
  1427. sub get_name {
  1428. my ( $self, $myconfig, $table, $transdate ) = @_;
  1429. # connect to database
  1430. my @queryargs;
  1431. my $where;
  1432. if ($transdate) {
  1433. $where = qq|
  1434. AND (startdate IS NULL OR startdate <= ?)
  1435. AND (enddate IS NULL OR enddate >= ?)|;
  1436. @queryargs = ( $transdate, $transdate );
  1437. }
  1438. my $name = $self->like( lc $self->{$table} );
  1439. my $query = qq|
  1440. SELECT * FROM $table
  1441. WHERE (lower(name) LIKE ? OR ${table}number LIKE ?)
  1442. $where
  1443. ORDER BY name|;
  1444. unshift( @queryargs, $name, $name );
  1445. my $sth = $self->{dbh}->prepare($query);
  1446. $sth->execute(@queryargs) || $self->dberror($query);
  1447. my $i = 0;
  1448. @{ $self->{name_list} } = ();
  1449. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1450. push( @{ $self->{name_list} }, $ref );
  1451. $i++;
  1452. }
  1453. $sth->finish;
  1454. $self->{dbh}->commit;
  1455. $i;
  1456. }
  1457. sub all_vc {
  1458. my ( $self, $myconfig, $vc, $module, $dbh, $transdate, $job ) = @_;
  1459. my $ref;
  1460. my $disconnect = 0;
  1461. $dbh = $self->{dbh};
  1462. my $sth;
  1463. my $query = qq|SELECT count(*) FROM $vc|;
  1464. my $where;
  1465. my @queryargs = ();
  1466. if ($transdate) {
  1467. $query .= qq| WHERE (startdate IS NULL OR startdate <= ?)
  1468. AND (enddate IS NULL OR enddate >= ?)|;
  1469. @queryargs = ( $transdate, $transdate );
  1470. }
  1471. $sth = $dbh->prepare($query);
  1472. $sth->execute(@queryargs);
  1473. my ($count) = $sth->fetchrow_array;
  1474. $sth->finish;
  1475. @queryargs = ();
  1476. # build selection list
  1477. if ( $count < $myconfig->{vclimit} ) {
  1478. $self->{"${vc}_id"} *= 1;
  1479. $query = qq|SELECT id, name
  1480. FROM $vc
  1481. WHERE 1=1
  1482. $where
  1483. UNION
  1484. SELECT id,name
  1485. FROM $vc
  1486. WHERE id = ?
  1487. ORDER BY name|;
  1488. push( @queryargs, $self->{"${vc}_id"} );
  1489. $sth = $dbh->prepare($query);
  1490. $sth->execute(@queryargs) || $self->dberror($query);
  1491. @{ $self->{"all_$vc"} } = ();
  1492. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1493. push @{ $self->{"all_$vc"} }, $ref;
  1494. }
  1495. $sth->finish;
  1496. }
  1497. # get self
  1498. if ( !$self->{employee_id} ) {
  1499. ( $self->{employee}, $self->{employee_id} ) = split /--/,
  1500. $self->{employee};
  1501. ( $self->{employee}, $self->{employee_id} ) = $self->get_employee($dbh)
  1502. unless $self->{employee_id};
  1503. }
  1504. $self->all_employees( $myconfig, $dbh, $transdate, 1 );
  1505. $self->all_departments( $myconfig, $dbh, $vc );
  1506. $self->all_projects( $myconfig, $dbh, $transdate, $job );
  1507. # get language codes
  1508. $query = qq|SELECT *
  1509. FROM language
  1510. ORDER BY 2|;
  1511. $sth = $dbh->prepare($query);
  1512. $sth->execute || $self->dberror($query);
  1513. $self->{all_language} = ();
  1514. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1515. push @{ $self->{all_language} }, $ref;
  1516. }
  1517. $sth->finish;
  1518. $self->all_taxaccounts( $myconfig, $dbh, $transdate );
  1519. $self->{dbh}->commit;
  1520. }
  1521. sub all_taxaccounts {
  1522. my ( $self, $myconfig, $dbh2, $transdate ) = @_;
  1523. my $dbh = $self->{dbh};
  1524. my $sth;
  1525. my $query;
  1526. my $where;
  1527. my @queryargs = ();
  1528. if ($transdate) {
  1529. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1530. push( @queryargs, $transdate );
  1531. }
  1532. if ( $self->{taxaccounts} ) {
  1533. # rebuild tax rates
  1534. $query = qq|SELECT t.rate, t.taxnumber
  1535. FROM tax t
  1536. JOIN chart c ON (c.id = t.chart_id)
  1537. WHERE c.accno = ?
  1538. $where
  1539. ORDER BY accno, validto|;
  1540. $sth = $dbh->prepare($query) || $self->dberror($query);
  1541. foreach my $accno ( split / /, $self->{taxaccounts} ) {
  1542. $sth->execute( $accno, @queryargs );
  1543. ( $self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"} ) =
  1544. $sth->fetchrow_array;
  1545. $sth->finish;
  1546. }
  1547. }
  1548. $self->{dbh}->commit;
  1549. }
  1550. sub all_employees {
  1551. my ( $self, $myconfig, $dbh2, $transdate, $sales ) = @_;
  1552. my $dbh = $self->{dbh};
  1553. my @whereargs = ();
  1554. # setup employees/sales contacts
  1555. my $query = qq|SELECT id, name
  1556. FROM employee
  1557. WHERE 1 = 1|;
  1558. if ($transdate) {
  1559. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1560. AND (enddate IS NULL OR enddate >= ?)|;
  1561. @whereargs = ( $transdate, $transdate );
  1562. }
  1563. else {
  1564. $query .= qq| AND enddate IS NULL|;
  1565. }
  1566. if ($sales) {
  1567. $query .= qq| AND sales = '1'|;
  1568. }
  1569. $query .= qq| ORDER BY name|;
  1570. my $sth = $dbh->prepare($query);
  1571. $sth->execute(@whereargs) || $self->dberror($query);
  1572. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1573. push @{ $self->{all_employee} }, $ref;
  1574. }
  1575. $sth->finish;
  1576. $dbh->commit;
  1577. }
  1578. sub all_projects {
  1579. my ( $self, $myconfig, $dbh2, $transdate, $job ) = @_;
  1580. my $dbh = $self->{dbh};
  1581. my @queryargs = ();
  1582. my $where = "1 = 1";
  1583. $where = qq|id NOT IN (SELECT id
  1584. FROM parts
  1585. WHERE project_id > 0)| if !$job;
  1586. my $query = qq|SELECT *
  1587. FROM project
  1588. WHERE $where|;
  1589. if ( $self->{language_code} ) {
  1590. $query = qq|
  1591. SELECT pr.*, t.description AS translation
  1592. FROM project pr
  1593. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1594. WHERE t.language_code = ?|;
  1595. push( @queryargs, $self->{language_code} );
  1596. }
  1597. if ($transdate) {
  1598. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1599. AND (enddate IS NULL OR enddate >= ?)|;
  1600. push( @queryargs, $transdate, $transdate );
  1601. }
  1602. $query .= qq| ORDER BY projectnumber|;
  1603. $sth = $dbh->prepare($query);
  1604. $sth->execute(@queryargs) || $self->dberror($query);
  1605. @{ $self->{all_project} } = ();
  1606. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1607. push @{ $self->{all_project} }, $ref;
  1608. }
  1609. $sth->finish;
  1610. $dbh->commit;
  1611. }
  1612. sub all_departments {
  1613. my ( $self, $myconfig, $dbh2, $vc ) = @_;
  1614. $dbh = $self->{dbh};
  1615. my $where = "1 = 1";
  1616. if ($vc) {
  1617. if ( $vc eq 'customer' ) {
  1618. $where = " role = 'P'";
  1619. }
  1620. }
  1621. my $query = qq|SELECT id, description
  1622. FROM department
  1623. WHERE $where
  1624. ORDER BY 2|;
  1625. my $sth = $dbh->prepare($query);
  1626. $sth->execute || $self->dberror($query);
  1627. @{ $self->{all_department} } = ();
  1628. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1629. push @{ $self->{all_department} }, $ref;
  1630. }
  1631. $sth->finish;
  1632. $self->all_years($myconfig);
  1633. $dbh->commit;
  1634. }
  1635. sub all_years {
  1636. my ( $self, $myconfig, $dbh2 ) = @_;
  1637. $dbh = $self->{dbh};
  1638. # get years
  1639. my $query = qq|
  1640. SELECT (SELECT transdate FROM acc_trans ORDER BY transdate asc
  1641. LIMIT 1),
  1642. (SELECT transdate FROM acc_trans ORDER BY transdate desc
  1643. LIMIT 1)|;
  1644. my ( $startdate, $enddate ) = $dbh->selectrow_array($query);
  1645. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1646. ($startdate) = split /\W/, $startdate;
  1647. ($enddate) = split /\W/, $enddate;
  1648. }
  1649. else {
  1650. (@_) = split /\W/, $startdate;
  1651. $startdate = $_[2];
  1652. (@_) = split /\W/, $enddate;
  1653. $enddate = $_[2];
  1654. }
  1655. $self->{all_years} = ();
  1656. $startdate = substr( $startdate, 0, 4 );
  1657. $enddate = substr( $enddate, 0, 4 );
  1658. while ( $enddate >= $startdate ) {
  1659. push @{ $self->{all_years} }, $enddate--;
  1660. }
  1661. #this should probably be changed to use locale
  1662. %{ $self->{all_month} } = (
  1663. '01' => 'January',
  1664. '02' => 'February',
  1665. '03' => 'March',
  1666. '04' => 'April',
  1667. '05' => 'May ',
  1668. '06' => 'June',
  1669. '07' => 'July',
  1670. '08' => 'August',
  1671. '09' => 'September',
  1672. '10' => 'October',
  1673. '11' => 'November',
  1674. '12' => 'December'
  1675. );
  1676. $dbh->commit;
  1677. }
  1678. sub create_links {
  1679. my ( $self, $module, $myconfig, $vc, $job ) = @_;
  1680. # get last customers or vendors
  1681. my ( $query, $sth );
  1682. if (!$self->{dbh}) {
  1683. $self->db_init($myconfig);
  1684. }
  1685. $dbh = $self->{dbh};
  1686. my %xkeyref = ();
  1687. # now get the account numbers
  1688. $query = qq|SELECT accno, description, link
  1689. FROM chart
  1690. WHERE link LIKE ?
  1691. ORDER BY accno|;
  1692. $sth = $dbh->prepare($query);
  1693. $sth->execute( "%" . "$module%" ) || $self->dberror($query);
  1694. $self->{accounts} = "";
  1695. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1696. foreach my $key ( split /:/, $ref->{link} ) {
  1697. if ( $key =~ /$module/ ) {
  1698. # cross reference for keys
  1699. $xkeyref{ $ref->{accno} } = $key;
  1700. push @{ $self->{"${module}_links"}{$key} },
  1701. {
  1702. accno => $ref->{accno},
  1703. description => $ref->{description}
  1704. };
  1705. $self->{accounts} .= "$ref->{accno} "
  1706. unless $key =~ /tax/;
  1707. }
  1708. }
  1709. }
  1710. $sth->finish;
  1711. my $arap = ( $vc eq 'customer' ) ? 'ar' : 'ap';
  1712. if ( $self->{id} ) {
  1713. $query = qq|
  1714. SELECT a.invnumber, a.transdate,
  1715. a.${vc}_id, a.datepaid, a.duedate, a.ordnumber,
  1716. a.taxincluded, a.curr AS currency, a.notes,
  1717. a.intnotes, c.name AS $vc, a.department_id,
  1718. d.description AS department,
  1719. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1720. a.employee_id, e.name AS employee,
  1721. c.language_code, a.ponumber
  1722. FROM $arap a
  1723. JOIN $vc c ON (a.${vc}_id = c.id)
  1724. LEFT JOIN employee e ON (e.id = a.employee_id)
  1725. LEFT JOIN department d ON (d.id = a.department_id)
  1726. WHERE a.id = ?|;
  1727. $sth = $dbh->prepare($query);
  1728. $sth->execute( $self->{id} ) || $self->dberror($query);
  1729. $ref = $sth->fetchrow_hashref('NAME_lc');
  1730. $self->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1731. foreach $key ( keys %$ref ) {
  1732. $self->{$key} = $ref->{$key};
  1733. }
  1734. $sth->finish;
  1735. # get printed, emailed
  1736. $query = qq|
  1737. SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1738. FROM status s WHERE s.trans_id = ?|;
  1739. $sth = $dbh->prepare($query);
  1740. $sth->execute( $self->{id} ) || $self->dberror($query);
  1741. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1742. $self->{printed} .= "$ref->{formname} "
  1743. if $ref->{printed};
  1744. $self->{emailed} .= "$ref->{formname} "
  1745. if $ref->{emailed};
  1746. $self->{queued} .= "$ref->{formname} " . "$ref->{spoolfile} "
  1747. if $ref->{spoolfile};
  1748. }
  1749. $sth->finish;
  1750. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1751. # get recurring
  1752. $self->get_recurring($dbh);
  1753. # get amounts from individual entries
  1754. $query = qq|
  1755. SELECT c.accno, c.description, a.source, a.amount,
  1756. a.memo, a.transdate, a.cleared, a.project_id,
  1757. p.projectnumber
  1758. FROM acc_trans a
  1759. JOIN chart c ON (c.id = a.chart_id)
  1760. LEFT JOIN project p ON (p.id = a.project_id)
  1761. WHERE a.trans_id = ?
  1762. AND a.fx_transaction = '0'
  1763. ORDER BY transdate|;
  1764. $sth = $dbh->prepare($query);
  1765. $sth->execute( $self->{id} ) || $self->dberror($query);
  1766. my $fld = ( $vc eq 'customer' ) ? 'buy' : 'sell';
  1767. $self->{exchangerate} =
  1768. $self->get_exchangerate( $dbh, $self->{currency}, $self->{transdate},
  1769. $fld );
  1770. # store amounts in {acc_trans}{$key} for multiple accounts
  1771. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1772. $self->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1773. $ref->{exchangerate} =
  1774. $self->get_exchangerate( $dbh, $self->{currency},
  1775. $ref->{transdate}, $fld );
  1776. push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
  1777. }
  1778. $sth->finish;
  1779. }
  1780. else {
  1781. if ( !$self->{"$self->{vc}_id"} ) {
  1782. $self->lastname_used( $myconfig, $dbh, $vc, $module );
  1783. }
  1784. }
  1785. for (qw(current_date curr closedto revtrans)) {
  1786. if ($_ eq 'current_date'){
  1787. $query = "SELECT $_";
  1788. } elsif ($_ eq 'closedto'){
  1789. $query = qq|
  1790. SELECT value::date FROM defaults
  1791. WHERE setting_key = '$_'|;
  1792. } else {
  1793. $query = qq|
  1794. SELECT value FROM defaults
  1795. WHERE setting_key = '$_'|;
  1796. }
  1797. $sth = $dbh->prepare($query);
  1798. $sth->execute || $self->dberror($query);
  1799. ($val) = $sth->fetchrow_array();
  1800. if ( $_ eq 'curr' ) {
  1801. $self->{currencies} = $val;
  1802. }
  1803. else {
  1804. $self->{$_} = $val;
  1805. }
  1806. $sth->finish;
  1807. }
  1808. $self->{transdate} = $self->{current_date} if (!$self->{id});
  1809. $self->all_vc( $myconfig, $vc, $module, $dbh, $self->{transdate}, $job );
  1810. $self->{dbh}->commit;
  1811. }
  1812. sub lastname_used {
  1813. my ( $self, $myconfig, $dbh2, $vc, $module ) = @_;
  1814. my $dbh = $self->{dbh};
  1815. $vc ||= $self->{vc}; # add default to correct for improper passing
  1816. my $arap = ( $vc eq 'customer' ) ? "ar" : "ap";
  1817. my $where = "1 = 1";
  1818. my $sth;
  1819. if ( $self->{type} =~ /_order/ ) {
  1820. $arap = 'oe';
  1821. $where = "quotation = '0'";
  1822. }
  1823. if ( $self->{type} =~ /_quotation/ ) {
  1824. $arap = 'oe';
  1825. $where = "quotation = '1'";
  1826. }
  1827. my $query = qq|
  1828. SELECT ct.name AS $vc, ct.curr AS currency, ct.id AS ${vc}_id,
  1829. current_date + ct.terms AS duedate,
  1830. ct.notes,
  1831. ct.curr AS currency
  1832. FROM $vc ct
  1833. WHERE ct.id = (select ${vc}_id from $arap where $where AND ${vc}_id IS NOT NULL order by id DESC limit 1)|;
  1834. $sth = $dbh->prepare($query);
  1835. $sth->execute() || $self->dberror($query);
  1836. my $ref = $sth->fetchrow_hashref('NAME_lc');
  1837. for ( keys %$ref ) { $self->{$_} = $ref->{$_} }
  1838. $sth->finish;
  1839. $dbh->commit;
  1840. }
  1841. sub current_date {
  1842. my ( $self, $myconfig, $thisdate, $days ) = @_;
  1843. my $dbh = $self->{dbh};
  1844. my $query;
  1845. $days *= 1;
  1846. if ($thisdate) {
  1847. my $dateformat = $myconfig->{dateformat};
  1848. if ( $myconfig->{dateformat} !~ /^y/ ) {
  1849. my @a = split /\D/, $thisdate;
  1850. $dateformat .= "yy" if ( length $a[2] > 2 );
  1851. }
  1852. if ( $thisdate !~ /\D/ ) {
  1853. $dateformat = 'yyyymmdd';
  1854. }
  1855. $query = qq|SELECT (to_date(?, ?)
  1856. + ?::interval)::date AS thisdate|;
  1857. @queryargs = ( $thisdate, $dateformat, sprintf('%d days', $days) );
  1858. }
  1859. else {
  1860. $query = qq|SELECT current_date AS thisdate|;
  1861. @queryargs = ();
  1862. }
  1863. $sth = $dbh->prepare($query);
  1864. $sth->execute(@queryargs);
  1865. ($thisdate) = $sth->fetchrow_array;
  1866. $dbh->commit;
  1867. $thisdate;
  1868. }
  1869. sub like {
  1870. my ( $self, $str ) = @_;
  1871. "%$str%";
  1872. }
  1873. sub redo_rows {
  1874. my ( $self, $flds, $new, $count, $numrows ) = @_;
  1875. my @ndx = ();
  1876. for ( 1 .. $count ) {
  1877. push @ndx, { num => $new->[ $_ - 1 ]->{runningnumber}, ndx => $_ };
  1878. }
  1879. my $i = 0;
  1880. # fill rows
  1881. foreach my $item ( sort { $a->{num} <=> $b->{num} } @ndx ) {
  1882. $i++;
  1883. $j = $item->{ndx} - 1;
  1884. for ( @{$flds} ) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1885. }
  1886. # delete empty rows
  1887. for $i ( $count + 1 .. $numrows ) {
  1888. for ( @{$flds} ) { delete $self->{"${_}_$i"} }
  1889. }
  1890. }
  1891. sub get_partsgroup {
  1892. my ( $self, $myconfig, $p ) = @_;
  1893. my $dbh = $self->{dbh};
  1894. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1895. FROM partsgroup pg
  1896. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1897. my $where;
  1898. my $sortorder = "partsgroup";
  1899. if ( $p->{searchitems} eq 'part' ) {
  1900. $where = qq| WHERE (p.inventory_accno_id > 0
  1901. AND p.income_accno_id > 0)|;
  1902. }
  1903. if ( $p->{searchitems} eq 'service' ) {
  1904. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1905. }
  1906. if ( $p->{searchitems} eq 'assembly' ) {
  1907. $where = qq| WHERE p.assembly = '1'|;
  1908. }
  1909. if ( $p->{searchitems} eq 'labor' ) {
  1910. $where =
  1911. qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1912. }
  1913. if ( $p->{searchitems} eq 'nolabor' ) {
  1914. $where = qq| WHERE p.income_accno_id > 0|;
  1915. }
  1916. if ( $p->{all} ) {
  1917. $query = qq|SELECT id, partsgroup
  1918. FROM partsgroup|;
  1919. }
  1920. my @queryargs = ();
  1921. if ( $p->{language_code} ) {
  1922. $sortorder = "translation";
  1923. $query = qq|
  1924. SELECT DISTINCT pg.id, pg.partsgroup,
  1925. t.description AS translation
  1926. FROM partsgroup pg
  1927. JOIN parts p ON (p.partsgroup_id = pg.id)
  1928. LEFT JOIN translation t ON (t.trans_id = pg.id
  1929. AND t.language_code = ?)|;
  1930. @queryargs = ( $p->{language_code} );
  1931. }
  1932. $query .= qq| $where ORDER BY $sortorder|;
  1933. my $sth = $dbh->prepare($query);
  1934. $sth->execute(@queryargs) || $self->dberror($query);
  1935. $self->{all_partsgroup} = ();
  1936. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1937. push @{ $self->{all_partsgroup} }, $ref;
  1938. }
  1939. $sth->finish;
  1940. $dbh->commit;
  1941. }
  1942. sub update_status {
  1943. my ( $self, $myconfig ) = @_;
  1944. # no id return
  1945. return unless $self->{id};
  1946. my $dbh = $self->{dbh};
  1947. my %queued = split / +/, $self->{queued};
  1948. my $spoolfile =
  1949. ( $queued{ $self->{formname} } )
  1950. ? "'$queued{$self->{formname}}'"
  1951. : 'NULL';
  1952. my $query = qq|DELETE FROM status
  1953. WHERE formname = ?
  1954. AND trans_id = ?|;
  1955. $sth = $dbh->prepare($query);
  1956. $sth->execute( $self->{formname}, $self->{id} ) || $self->dberror($query);
  1957. $sth->finish;
  1958. my $printed = ( $self->{printed} =~ /$self->{formname}/ ) ? "1" : "0";
  1959. my $emailed = ( $self->{emailed} =~ /$self->{formname}/ ) ? "1" : "0";
  1960. $query = qq|
  1961. INSERT INTO status
  1962. (trans_id, printed, emailed, spoolfile, formname)
  1963. VALUES (?, ?, ?, ?, ?)|;
  1964. $sth = $dbh->prepare($query);
  1965. $sth->execute( $self->{id}, $printed, $emailed, $spoolfile,
  1966. $self->{formname} );
  1967. $sth->finish;
  1968. $dbh->commit;
  1969. }
  1970. sub save_status {
  1971. my ($self) = @_;
  1972. $dbh = $self->{dbh};
  1973. my $formnames = $self->{printed};
  1974. my $emailforms = $self->{emailed};
  1975. my $query = qq|DELETE FROM status
  1976. WHERE trans_id = ?|;
  1977. my $sth = $dbh->prepare($query);
  1978. $sth->execute( $self->{id} );
  1979. $sth->finish;
  1980. my %queued;
  1981. my $formname;
  1982. if ( $self->{queued} ) {
  1983. %queued = split / +/, $self->{queued};
  1984. foreach $formname ( keys %queued ) {
  1985. $printed = ( $self->{printed} =~ /$formname/ ) ? "1" : "0";
  1986. $emailed = ( $self->{emailed} =~ /$formname/ ) ? "1" : "0";
  1987. if ( $queued{$formname} ) {
  1988. $query = qq|
  1989. INSERT INTO status
  1990. (trans_id, printed, emailed,
  1991. spoolfile, formname)
  1992. VALUES (?, ?, ?, ?, ?)|;
  1993. $sth = $dbh->prepare($query);
  1994. $sth->execute( $self->{id}, $printed, $emailed,
  1995. $queued{$formname}, $formname )
  1996. || $self->dberror($query);
  1997. $sth->finish;
  1998. }
  1999. $formnames =~ s/$formname//;
  2000. $emailforms =~ s/$formname//;
  2001. }
  2002. }
  2003. # save printed, emailed info
  2004. $formnames =~ s/^ +//g;
  2005. $emailforms =~ s/^ +//g;
  2006. my %status = ();
  2007. for ( split / +/, $formnames ) { $status{$_}{printed} = 1 }
  2008. for ( split / +/, $emailforms ) { $status{$_}{emailed} = 1 }
  2009. foreach my $formname ( keys %status ) {
  2010. $printed = ( $formnames =~ /$self->{formname}/ ) ? "1" : "0";
  2011. $emailed = ( $emailforms =~ /$self->{formname}/ ) ? "1" : "0";
  2012. $query = qq|
  2013. INSERT INTO status (trans_id, printed, emailed,
  2014. formname)
  2015. VALUES (?, ?, ?, ?)|;
  2016. $sth = $dbh->prepare($query);
  2017. $sth->execute( $self->{id}, $printed, $emailed, $formname );
  2018. $sth->finish;
  2019. }
  2020. $dbh->commit;
  2021. }
  2022. sub get_recurring {
  2023. my ($self) = @_;
  2024. $dbh = $self->{dbh};
  2025. my $query = qq/
  2026. SELECT s.*, se.formname || ':' || se.format AS emaila,
  2027. se.message, sp.formname || ':' ||
  2028. sp.format || ':' || sp.printer AS printa
  2029. FROM recurring s
  2030. LEFT JOIN recurringemail se ON (s.id = se.id)
  2031. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  2032. WHERE s.id = ?/;
  2033. my $sth = $dbh->prepare($query);
  2034. $sth->execute( $self->{id} ) || $self->dberror($query);
  2035. for (qw(email print)) { $self->{"recurring$_"} = "" }
  2036. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  2037. for ( keys %$ref ) { $self->{"recurring$_"} = $ref->{$_} }
  2038. $self->{recurringemail} .= "$ref->{emaila}:";
  2039. $self->{recurringprint} .= "$ref->{printa}:";
  2040. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  2041. }
  2042. $sth->finish;
  2043. chop $self->{recurringemail};
  2044. chop $self->{recurringprint};
  2045. if ( $self->{recurringstartdate} ) {
  2046. $self->{recurringreference} =
  2047. $self->escape( $self->{recurringreference}, 1 );
  2048. $self->{recurringmessage} =
  2049. $self->escape( $self->{recurringmessage}, 1 );
  2050. for (
  2051. qw(reference startdate repeat unit howmany
  2052. payment print email message)
  2053. )
  2054. {
  2055. $self->{recurring} .= qq|$self->{"recurring$_"},|;
  2056. }
  2057. chop $self->{recurring};
  2058. }
  2059. $dbh->commit;
  2060. }
  2061. sub save_recurring {
  2062. my ( $self, $dbh2, $myconfig ) = @_;
  2063. my $dbh = $self->{dbh};
  2064. my $query;
  2065. $query = qq|DELETE FROM recurring
  2066. WHERE id = ?|;
  2067. $sth = $dbh->prepare($query) || $self->dberror($query);
  2068. $sth->execute( $self->{id} ) || $self->dberror($query);
  2069. $query = qq|DELETE FROM recurringemail
  2070. WHERE id = ?|;
  2071. $sth = $dbh->prepare($query) || $self->dberror($query);
  2072. $sth->execute( $self->{id} ) || $self->dberror($query);
  2073. $query = qq|DELETE FROM recurringprint
  2074. WHERE id = ?|;
  2075. $sth = $dbh->prepare($query) || $self->dberror($query);
  2076. $sth->execute( $self->{id} ) || $self->dberror($query);
  2077. if ( $self->{recurring} ) {
  2078. my %s = ();
  2079. (
  2080. $s{reference}, $s{startdate}, $s{repeat},
  2081. $s{unit}, $s{howmany}, $s{payment},
  2082. $s{print}, $s{email}, $s{message}
  2083. ) = split /,/, $self->{recurring};
  2084. if ($s{howmany} == 0){
  2085. $self->error("Cannot set to recur 0 times");
  2086. }
  2087. for (qw(reference message)) { $s{$_} = $self->unescape( $s{$_} ) }
  2088. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  2089. # calculate enddate
  2090. my $advance = $s{repeat} * ( $s{howmany} - 1 );
  2091. my %interval;
  2092. $interval{'Pg'} =
  2093. "(date '$s{startdate}' + interval '$advance $s{unit}')";
  2094. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  2095. my ($enddate) = $dbh->selectrow_array($query);
  2096. # calculate nextdate
  2097. $query = qq|
  2098. SELECT current_date - ?::date AS a,
  2099. ?::date - current_date AS b|;
  2100. $sth = $dbh->prepare($query) || $self->dberror($query);
  2101. $sth->execute( $s{startdate}, $enddate );
  2102. my ( $a, $b ) = $sth->fetchrow_array;
  2103. if ( $a + $b ) {
  2104. $advance =
  2105. int( ( $a / ( $a + $b ) ) * ( $s{howmany} - 1 ) + 1 ) *
  2106. $s{repeat};
  2107. }
  2108. else {
  2109. $advance = 0;
  2110. }
  2111. my $nextdate = $enddate;
  2112. if ( $advance > 0 ) {
  2113. if ( $advance < ( $s{repeat} * $s{howmany} ) ) {
  2114. $query = qq|SELECT (date '$s{startdate}' + interval '$advance $s{unit}')|;
  2115. ($nextdate) = $dbh->selectrow_array($query);
  2116. }
  2117. }
  2118. else {
  2119. $nextdate = $s{startdate};
  2120. }
  2121. if ( $self->{recurringnextdate} ) {
  2122. $nextdate = $self->{recurringnextdate};
  2123. $query = qq|SELECT '$enddate' - date '$nextdate'|;
  2124. if ( $dbh->selectrow_array($query) < 0 ) {
  2125. undef $nextdate;
  2126. }
  2127. }
  2128. $self->{recurringpayment} *= 1;
  2129. $query = qq|
  2130. INSERT INTO recurring
  2131. (id, reference, startdate, enddate, nextdate,
  2132. repeat, unit, howmany, payment)
  2133. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  2134. $sth = $dbh->prepare($query);
  2135. $sth->execute(
  2136. $self->{id}, $s{reference}, $s{startdate},
  2137. $enddate, $nextdate, $s{repeat},
  2138. $s{unit}, $s{howmany}, $s{payment}
  2139. );
  2140. my @p;
  2141. my $p;
  2142. my $i;
  2143. my $sth;
  2144. if ( $s{email} ) {
  2145. # formname:format
  2146. @p = split /:/, $s{email};
  2147. $query =
  2148. qq|INSERT INTO recurringemail (id, formname, format, message)
  2149. VALUES (?, ?, ?, ?)|;
  2150. $sth = $dbh->prepare($query) || $self->dberror($query);
  2151. for ( $i = 0 ; $i <= $#p ; $i += 2 ) {
  2152. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $s{message} );
  2153. }
  2154. $sth->finish;
  2155. }
  2156. if ( $s{print} ) {
  2157. # formname:format:printer
  2158. @p = split /:/, $s{print};
  2159. $query =
  2160. qq|INSERT INTO recurringprint (id, formname, format, printer)
  2161. VALUES (?, ?, ?, ?)|;
  2162. $sth = $dbh->prepare($query) || $self->dberror($query);
  2163. for ( $i = 0 ; $i <= $#p ; $i += 3 ) {
  2164. $p = ( $p[ $i + 2 ] ) ? $p[ $i + 2 ] : "";
  2165. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $p );
  2166. }
  2167. $sth->finish;
  2168. }
  2169. }
  2170. $dbh->commit;
  2171. }
  2172. sub save_intnotes {
  2173. my ( $self, $myconfig, $vc ) = @_;
  2174. # no id return
  2175. return unless $self->{id};
  2176. my $dbh = $self->{dbh};
  2177. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  2178. $sth = $dbh->prepare($query);
  2179. $sth->execute( $self->{intnotes}, $self->{id} ) || $self->dberror($query);
  2180. $dbh->commit;
  2181. }
  2182. sub update_defaults {
  2183. my ( $self, $myconfig, $fld ) = @_;
  2184. if ( !$self->{dbh} && $self ) {
  2185. $self->db_init($myconfig);
  2186. }
  2187. my $dbh = $self->{dbh};
  2188. if ( !$self ) {
  2189. $dbh = $_[3];
  2190. }
  2191. my $query = qq|
  2192. SELECT value FROM defaults
  2193. WHERE setting_key = ? FOR UPDATE|;
  2194. $sth = $dbh->prepare($query);
  2195. $sth->execute($fld);
  2196. ($_) = $sth->fetchrow_array();
  2197. $_ = "0" unless $_;
  2198. # check for and replace
  2199. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  2200. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  2201. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  2202. # <?lsmb PHONE ?> for customer and vendors
  2203. my $num = $_;
  2204. ($num) = $num =~ /(\d+)/;
  2205. if ( defined $num ) {
  2206. my $incnum;
  2207. # if we have leading zeros check how long it is
  2208. if ( $num =~ /^0/ ) {
  2209. my $l = length $num;
  2210. $incnum = $num + 1;
  2211. $l -= length $incnum;
  2212. # pad it out with zeros
  2213. my $padzero = "0" x $l;
  2214. $incnum = ( "0" x $l ) . $incnum;
  2215. }
  2216. else {
  2217. $incnum = $num + 1;
  2218. }
  2219. s/$num/$incnum/;
  2220. }
  2221. my $dbvar = $_;
  2222. my $var = $_;
  2223. my $str;
  2224. my $param;
  2225. if (/<\?lsmb /) {
  2226. while (/<\?lsmb /) {
  2227. s/<\?lsmb .*? \?>//;
  2228. last unless $&;
  2229. $param = $&;
  2230. $str = "";
  2231. if ( $param =~ /<\?lsmb date \?>/i ) {
  2232. $str = (
  2233. $self->split_date(
  2234. $myconfig->{dateformat},
  2235. $self->{transdate}
  2236. )
  2237. )[0];
  2238. $var =~ s/$param/$str/;
  2239. }
  2240. if ( $param =~
  2241. /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i
  2242. )
  2243. {
  2244. my $fld = lc $&;
  2245. $fld =~ s/<\?lsmb //;
  2246. if ( $fld =~ /name/ ) {
  2247. if ( $self->{type} ) {
  2248. $fld = $self->{vc};
  2249. }
  2250. }
  2251. my $p = $param;
  2252. $p =~ s/(<|>|%)//g;
  2253. my @p = split / /, $p;
  2254. my @n = split / /, uc $self->{$fld};
  2255. if ( $#p > 0 ) {
  2256. for ( my $i = 1 ; $i <= $#p ; $i++ ) {
  2257. $str .= substr( $n[ $i - 1 ], 0, $p[$i] );
  2258. }
  2259. }
  2260. else {
  2261. ($str) = split /--/, $self->{$fld};
  2262. }
  2263. $var =~ s/$param/$str/;
  2264. $var =~ s/\W//g if $fld eq 'phone';
  2265. }
  2266. if ( $param =~ /<\?lsmb (yy|mm|dd)/i ) {
  2267. my $p = $param;
  2268. $p =~ s/(<|>|%)//g;
  2269. my $spc = $p;
  2270. $spc =~ s/\w//g;
  2271. $spc = substr( $spc, 0, 1 );
  2272. my %d = ( yy => 1, mm => 2, dd => 3 );
  2273. my @p = ();
  2274. my @a = $self->split_date( $myconfig->{dateformat},
  2275. $self->{transdate} );
  2276. for ( sort keys %d ) { push @p, $a[ $d{$_} ] if ( $p =~ /$_/ ) }
  2277. $str = join $spc, @p;
  2278. $var =~ s/$param/$str/;
  2279. }
  2280. if ( $param =~ /<\?lsmb curr/i ) {
  2281. $var =~ s/$param/$self->{currency}/;
  2282. }
  2283. }
  2284. }
  2285. $query = qq|
  2286. UPDATE defaults
  2287. SET value = ?
  2288. WHERE setting_key = ?|;
  2289. $sth = $dbh->prepare($query);
  2290. $sth->execute( $dbvar, $fld ) || $self->dberror($query);
  2291. $dbh->commit;
  2292. $var;
  2293. }
  2294. sub db_prepare_vars {
  2295. my $self = shift;
  2296. for (@_) {
  2297. if ( !$self->{$_} and $self->{$_} ne "0" ) {
  2298. undef $self->{$_};
  2299. }
  2300. }
  2301. }
  2302. sub split_date {
  2303. my ( $self, $dateformat, $date ) = @_;
  2304. my @d = localtime;
  2305. my $mm;
  2306. my $dd;
  2307. my $yy;
  2308. my $rv;
  2309. if ( !$date ) {
  2310. $dd = $d[3];
  2311. $mm = ++$d[4];
  2312. $yy = substr( $d[5], -2 );
  2313. $mm = substr( "0$mm", -2 );
  2314. $dd = substr( "0$dd", -2 );
  2315. }
  2316. if ( $dateformat =~ /^yy/ ) {
  2317. if ($date) {
  2318. if ( $date =~ /\D/ ) {
  2319. ( $yy, $mm, $dd ) = split /\D/, $date;
  2320. $mm *= 1;
  2321. $dd *= 1;
  2322. $mm = substr( "0$mm", -2 );
  2323. $dd = substr( "0$dd", -2 );
  2324. $yy = substr( $yy, -2 );
  2325. $rv = "$yy$mm$dd";
  2326. }
  2327. else {
  2328. $rv = $date;
  2329. }
  2330. }
  2331. else {
  2332. $rv = "$yy$mm$dd";
  2333. }
  2334. }
  2335. if ( $dateformat =~ /^mm/ ) {
  2336. if ($date) {
  2337. if ( $date =~ /\D/ ) {
  2338. ( $mm, $dd, $yy ) = split /\D/, $date;
  2339. $mm *= 1;
  2340. $dd *= 1;
  2341. $mm = substr( "0$mm", -2 );
  2342. $dd = substr( "0$dd", -2 );
  2343. $yy = substr( $yy, -2 );
  2344. $rv = "$mm$dd$yy";
  2345. }
  2346. else {
  2347. $rv = $date;
  2348. }
  2349. }
  2350. else {
  2351. $rv = "$mm$dd$yy";
  2352. }
  2353. }
  2354. if ( $dateformat =~ /^dd/ ) {
  2355. if ($date) {
  2356. if ( $date =~ /\D/ ) {
  2357. ( $dd, $mm, $yy ) = split /\D/, $date;
  2358. $mm *= 1;
  2359. $dd *= 1;
  2360. $mm = substr( "0$mm", -2 );
  2361. $dd = substr( "0$dd", -2 );
  2362. $yy = substr( $yy, -2 );
  2363. $rv = "$dd$mm$yy";
  2364. }
  2365. else {
  2366. $rv = $date;
  2367. }
  2368. }
  2369. else {
  2370. $rv = "$dd$mm$yy";
  2371. }
  2372. }
  2373. ( $rv, $yy, $mm, $dd );
  2374. }
  2375. sub format_date {
  2376. # takes an iso date in, and converts it to the date for printing
  2377. my ( $self, $date ) = @_;
  2378. my $datestring;
  2379. if ( $date =~ /^\d{4}\D/ ) { # is an ISO date
  2380. $datestring = $self->{db_dateformat};
  2381. my ( $yyyy, $mm, $dd ) = split( /\W/, $date );
  2382. $datestring =~ s/y+/$yyyy/;
  2383. $datestring =~ s/mm/$mm/;
  2384. $datestring =~ s/dd/$dd/;
  2385. }
  2386. else { # return date
  2387. $datestring = $date;
  2388. }
  2389. $datestring;
  2390. }
  2391. sub from_to {
  2392. my ( $self, $yyyy, $mm, $interval ) = @_;
  2393. my @t;
  2394. my $dd = 1;
  2395. my $fromdate = "$yyyy-${mm}-01";
  2396. my $bd = 1;
  2397. if ( defined $interval ) {
  2398. if ( $interval == 12 ) {
  2399. $yyyy++;
  2400. }
  2401. else {
  2402. if ( ( $mm += $interval ) > 12 ) {
  2403. $mm -= 12;
  2404. $yyyy++;
  2405. }
  2406. if ( $interval == 0 ) {
  2407. @t = localtime(time);
  2408. $dd = $t[3];
  2409. $mm = $t[4] + 1;
  2410. $yyyy = $t[5] + 1900;
  2411. $bd = 0;
  2412. }
  2413. }
  2414. }
  2415. else {
  2416. if ( ++$mm > 12 ) {
  2417. $mm -= 12;
  2418. $yyyy++;
  2419. }
  2420. }
  2421. $mm--;
  2422. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yyyy ) - $bd );
  2423. $t[4]++;
  2424. $t[4] = substr( "0$t[4]", -2 );
  2425. $t[3] = substr( "0$t[3]", -2 );
  2426. $t[5] += 1900;
  2427. ( $self->format_date($fromdate), $self->format_date("$t[5]-$t[4]-$t[3]") );
  2428. }
  2429. sub audittrail {
  2430. my ( $self, $dbh, $myconfig, $audittrail ) = @_;
  2431. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2432. my $query;
  2433. my $rv;
  2434. my $disconnect;
  2435. if ( !$dbh ) {
  2436. $dbh = $self->{dbh};
  2437. }
  2438. # if we have an id add audittrail, otherwise get a new timestamp
  2439. my @queryargs;
  2440. if ( $audittrail->{id} ) {
  2441. $query = qq|
  2442. SELECT value FROM defaults
  2443. WHERE setting_key = 'audittrail'|;
  2444. if ( $dbh->selectrow_array($query) ) {
  2445. my ( $null, $employee_id ) = $self->get_employee($dbh);
  2446. if ( $self->{audittrail} && !$myconfig ) {
  2447. chop $self->{audittrail};
  2448. my @a = split /\|/, $self->{audittrail};
  2449. my %newtrail = ();
  2450. my $key;
  2451. my $i;
  2452. my @flds = qw(tablename reference formname action transdate);
  2453. # put into hash and remove dups
  2454. while (@a) {
  2455. $key = "$a[2]$a[3]";
  2456. $i = 0;
  2457. $newtrail{$key} = { map { $_ => $a[ $i++ ] } @flds };
  2458. splice @a, 0, 5;
  2459. }
  2460. $query = qq|
  2461. INSERT INTO audittrail
  2462. (trans_id, tablename, reference,
  2463. formname, action, transdate,
  2464. employee_id)
  2465. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2466. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2467. foreach $key (
  2468. sort {
  2469. $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
  2470. } keys %newtrail
  2471. )
  2472. {
  2473. $i = 2;
  2474. $sth->bind_param( 1, $audittrail->{id} );
  2475. for (@flds) {
  2476. $sth->bind_param( $i++, $newtrail{$key}{$_} );
  2477. }
  2478. $sth->bind_param( $i++, $employee_id );
  2479. $sth->execute() || $self->dberror($query);
  2480. $sth->finish;
  2481. }
  2482. }
  2483. if ( $audittrail->{transdate} ) {
  2484. $query = qq|
  2485. INSERT INTO audittrail (
  2486. trans_id, tablename, reference,
  2487. formname, action, employee_id,
  2488. transdate)
  2489. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2490. @queryargs = (
  2491. $audittrail->{id}, $audittrail->{tablename},
  2492. $audittrail->{reference}, $audittrail->{formname},
  2493. $audittrail->{action}, $employee_id,
  2494. $audittrail->{transdate}
  2495. );
  2496. }
  2497. else {
  2498. $query = qq|
  2499. INSERT INTO audittrail
  2500. (trans_id, tablename, reference,
  2501. formname, action, employee_id)
  2502. VALUES (?, ?, ?, ?, ?, ?)|;
  2503. @queryargs = (
  2504. $audittrail->{id}, $audittrail->{tablename},
  2505. $audittrail->{reference}, $audittrail->{formname},
  2506. $audittrail->{action}, $employee_id,
  2507. );
  2508. }
  2509. $sth = $dbh->prepare($query);
  2510. $sth->execute(@queryargs) || $self->dberror($query);
  2511. }
  2512. }
  2513. else {
  2514. $query = qq|SELECT current_timestamp|;
  2515. my ($timestamp) = $dbh->selectrow_array($query);
  2516. $rv =
  2517. "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2518. }
  2519. $dbh->commit;
  2520. $rv;
  2521. }
  2522. 1;