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