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