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