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