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