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