summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: 206669c6640d844d26e9a1b675a85ec9198a9c56 (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. for (qw(curr closedto revtrans)) {
  1768. $query = qq|
  1769. SELECT value FROM defaults
  1770. WHERE setting_key = '$_'|;
  1771. $sth = $dbh->prepare($query);
  1772. $sth->execute || $self->dberror($query);
  1773. ($val) = $sth->fetchrow_array();
  1774. if ( $_ eq 'curr' ) {
  1775. $self->{currencies} = $val;
  1776. }
  1777. else {
  1778. $self->{$_} = $val;
  1779. }
  1780. $sth->finish;
  1781. }
  1782. $self->{transdate} = $self->current_date;
  1783. }
  1784. else {
  1785. for (qw(current_date curr closedto revtrans)) {
  1786. $query = qq|
  1787. SELECT value FROM defaults
  1788. WHERE setting_key = '$_'|;
  1789. $sth = $dbh->prepare($query);
  1790. $sth->execute || $self->dberror($query);
  1791. ($val) = $sth->fetchrow_array();
  1792. if ( $_ eq 'curr' ) {
  1793. $self->{currencies} = $val;
  1794. }
  1795. elsif ( $_ eq 'current_date' ) {
  1796. $self->{transdate} = $val;
  1797. }
  1798. else {
  1799. $self->{$_} = $val;
  1800. }
  1801. $sth->finish;
  1802. }
  1803. if ( !$self->{"$self->{vc}_id"} ) {
  1804. $self->lastname_used( $myconfig, $dbh, $vc, $module );
  1805. }
  1806. }
  1807. $self->all_vc( $myconfig, $vc, $module, $dbh, $self->{transdate}, $job );
  1808. $self->{dbh}->commit;
  1809. }
  1810. sub lastname_used {
  1811. my ( $self, $myconfig, $dbh2, $vc, $module ) = @_;
  1812. my $dbh = $self->{dbh};
  1813. $vc ||= $self->{vc}; # add default to correct for improper passing
  1814. my $arap = ( $vc eq 'customer' ) ? "ar" : "ap";
  1815. my $sth;
  1816. if ( $self->{type} =~ /_order/ ) {
  1817. $arap = 'oe';
  1818. $where = "quotation = '0'";
  1819. }
  1820. if ( $self->{type} =~ /_quotation/ ) {
  1821. $arap = 'oe';
  1822. $where = "quotation = '1'";
  1823. }
  1824. $where = "AND $where " if $where;
  1825. $inv_notes = "ct.invoice_notes," if $vc eq 'customer';
  1826. my $query = qq|
  1827. SELECT entity.name, ct.curr AS currency, ct.id AS ${vc}_id,
  1828. current_date + ct.terms AS duedate,
  1829. $inv_notes
  1830. ct.curr AS currency
  1831. FROM $vc ct
  1832. JOIN entity ON (ct.entity_id = entity.id)
  1833. WHERE entity.id = (select entity_id from $arap
  1834. where entity_id IS NOT NULL $where
  1835. order by id DESC limit 1)|;
  1836. $sth = $dbh->prepare($query);
  1837. $sth->execute() || $self->dberror($query);
  1838. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1839. for ( keys %$ref ) { $self->{$_} = $ref->{$_} }
  1840. $sth->finish;
  1841. $dbh->commit;
  1842. }
  1843. sub current_date {
  1844. my ( $self, $myconfig, $thisdate, $days ) = @_;
  1845. my $dbh = $self->{dbh};
  1846. my $query;
  1847. $days *= 1;
  1848. if ($thisdate) {
  1849. my $dateformat = $myconfig->{dateformat};
  1850. if ( $myconfig->{dateformat} !~ /^y/ ) {
  1851. my @a = split /\D/, $thisdate;
  1852. $dateformat .= "yy" if ( length $a[2] > 2 );
  1853. }
  1854. if ( $thisdate !~ /\D/ ) {
  1855. $dateformat = 'yyyymmdd';
  1856. }
  1857. $query = qq|SELECT (to_date(?, ?)
  1858. + ?::interval)::date AS thisdate|;
  1859. @queryargs = ( $thisdate, $dateformat, sprintf('%d days', $days) );
  1860. }
  1861. else {
  1862. $query = qq|SELECT current_date AS thisdate|;
  1863. @queryargs = ();
  1864. }
  1865. $sth = $dbh->prepare($query);
  1866. $sth->execute(@queryargs);
  1867. ($thisdate) = $sth->fetchrow_array;
  1868. $dbh->commit;
  1869. $thisdate;
  1870. }
  1871. sub like {
  1872. my ( $self, $str ) = @_;
  1873. "%$str%";
  1874. }
  1875. sub redo_rows {
  1876. my ( $self, $flds, $new, $count, $numrows ) = @_;
  1877. my @ndx = ();
  1878. for ( 1 .. $count ) {
  1879. push @ndx, { num => $new->[ $_ - 1 ]->{runningnumber}, ndx => $_ };
  1880. }
  1881. my $i = 0;
  1882. # fill rows
  1883. foreach my $item ( sort { $a->{num} <=> $b->{num} } @ndx ) {
  1884. $i++;
  1885. $j = $item->{ndx} - 1;
  1886. for ( @{$flds} ) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1887. }
  1888. # delete empty rows
  1889. for $i ( $count + 1 .. $numrows ) {
  1890. for ( @{$flds} ) { delete $self->{"${_}_$i"} }
  1891. }
  1892. }
  1893. sub get_partsgroup {
  1894. my ( $self, $myconfig, $p ) = @_;
  1895. my $dbh = $self->{dbh};
  1896. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1897. FROM partsgroup pg
  1898. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1899. my $where;
  1900. my $sortorder = "partsgroup";
  1901. if ( $p->{searchitems} eq 'part' ) {
  1902. $where = qq| WHERE (p.inventory_accno_id > 0
  1903. AND p.income_accno_id > 0)|;
  1904. }
  1905. if ( $p->{searchitems} eq 'service' ) {
  1906. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1907. }
  1908. if ( $p->{searchitems} eq 'assembly' ) {
  1909. $where = qq| WHERE p.assembly = '1'|;
  1910. }
  1911. if ( $p->{searchitems} eq 'labor' ) {
  1912. $where =
  1913. qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1914. }
  1915. if ( $p->{searchitems} eq 'nolabor' ) {
  1916. $where = qq| WHERE p.income_accno_id > 0|;
  1917. }
  1918. if ( $p->{all} ) {
  1919. $query = qq|SELECT id, partsgroup
  1920. FROM partsgroup|;
  1921. }
  1922. my @queryargs = ();
  1923. if ( $p->{language_code} ) {
  1924. $sortorder = "translation";
  1925. $query = qq|
  1926. SELECT DISTINCT pg.id, pg.partsgroup,
  1927. t.description AS translation
  1928. FROM partsgroup pg
  1929. JOIN parts p ON (p.partsgroup_id = pg.id)
  1930. LEFT JOIN translation t ON (t.trans_id = pg.id
  1931. AND t.language_code = ?)|;
  1932. @queryargs = ( $p->{language_code} );
  1933. }
  1934. $query .= qq| $where ORDER BY $sortorder|;
  1935. my $sth = $dbh->prepare($query);
  1936. $sth->execute(@queryargs) || $self->dberror($query);
  1937. $self->{all_partsgroup} = ();
  1938. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1939. push @{ $self->{all_partsgroup} }, $ref;
  1940. }
  1941. $sth->finish;
  1942. $dbh->commit;
  1943. }
  1944. sub update_status {
  1945. my ( $self, $myconfig ) = @_;
  1946. # no id return
  1947. return unless $self->{id};
  1948. my $dbh = $self->{dbh};
  1949. my %queued = split / +/, $self->{queued};
  1950. my $spoolfile =
  1951. ( $queued{ $self->{formname} } )
  1952. ? "'$queued{$self->{formname}}'"
  1953. : 'NULL';
  1954. my $query = qq|DELETE FROM status
  1955. WHERE formname = ?
  1956. AND trans_id = ?|;
  1957. $sth = $dbh->prepare($query);
  1958. $sth->execute( $self->{formname}, $self->{id} ) || $self->dberror($query);
  1959. $sth->finish;
  1960. my $printed = ( $self->{printed} =~ /$self->{formname}/ ) ? "1" : "0";
  1961. my $emailed = ( $self->{emailed} =~ /$self->{formname}/ ) ? "1" : "0";
  1962. $query = qq|
  1963. INSERT INTO status
  1964. (trans_id, printed, emailed, spoolfile, formname)
  1965. VALUES (?, ?, ?, ?, ?)|;
  1966. $sth = $dbh->prepare($query);
  1967. $sth->execute( $self->{id}, $printed, $emailed, $spoolfile,
  1968. $self->{formname} );
  1969. $sth->finish;
  1970. $dbh->commit;
  1971. }
  1972. sub save_status {
  1973. my ($self) = @_;
  1974. $dbh = $self->{dbh};
  1975. my $formnames = $self->{printed};
  1976. my $emailforms = $self->{emailed};
  1977. my $query = qq|DELETE FROM status
  1978. WHERE trans_id = ?|;
  1979. my $sth = $dbh->prepare($query);
  1980. $sth->execute( $self->{id} );
  1981. $sth->finish;
  1982. my %queued;
  1983. my $formname;
  1984. if ( $self->{queued} ) {
  1985. %queued = split / +/, $self->{queued};
  1986. foreach $formname ( keys %queued ) {
  1987. $printed = ( $self->{printed} =~ /$formname/ ) ? "1" : "0";
  1988. $emailed = ( $self->{emailed} =~ /$formname/ ) ? "1" : "0";
  1989. if ( $queued{$formname} ) {
  1990. $query = qq|
  1991. INSERT INTO status
  1992. (trans_id, printed, emailed,
  1993. spoolfile, formname)
  1994. VALUES (?, ?, ?, ?, ?)|;
  1995. $sth = $dbh->prepare($query);
  1996. $sth->execute( $self->{id}, $pinted, $emailed,
  1997. $queued{$formname}, $formname )
  1998. || $self->dberror($query);
  1999. $sth->finish;
  2000. }
  2001. $formnames =~ s/$formname//;
  2002. $emailforms =~ s/$formname//;
  2003. }
  2004. }
  2005. # save printed, emailed info
  2006. $formnames =~ s/^ +//g;
  2007. $emailforms =~ s/^ +//g;
  2008. my %status = ();
  2009. for ( split / +/, $formnames ) { $status{$_}{printed} = 1 }
  2010. for ( split / +/, $emailforms ) { $status{$_}{emailed} = 1 }
  2011. foreach my $formname ( keys %status ) {
  2012. $printed = ( $formnames =~ /$self->{formname}/ ) ? "1" : "0";
  2013. $emailed = ( $emailforms =~ /$self->{formname}/ ) ? "1" : "0";
  2014. $query = qq|
  2015. INSERT INTO status (trans_id, printed, emailed,
  2016. formname)
  2017. VALUES (?, ?, ?, ?)|;
  2018. $sth = $dbh->prepare($query);
  2019. $sth->execute( $self->{id}, $printed, $emailed, $formname );
  2020. $sth->finish;
  2021. }
  2022. $dbh->commit;
  2023. }
  2024. sub get_recurring {
  2025. my ($self) = @_;
  2026. $dbh = $self->{dbh};
  2027. my $query = qq/
  2028. SELECT s.*, se.formname || ':' || se.format AS emaila,
  2029. se.message, sp.formname || ':' ||
  2030. sp.format || ':' || sp.printer AS printa
  2031. FROM recurring s
  2032. LEFT JOIN recurringemail se ON (s.id = se.id)
  2033. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  2034. WHERE s.id = ?/;
  2035. my $sth = $dbh->prepare($query);
  2036. $sth->execute( $self->{id} ) || $self->dberror($query);
  2037. for (qw(email print)) { $self->{"recurring$_"} = "" }
  2038. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  2039. for ( keys %$ref ) { $self->{"recurring$_"} = $ref->{$_} }
  2040. $self->{recurringemail} .= "$ref->{emaila}:";
  2041. $self->{recurringprint} .= "$ref->{printa}:";
  2042. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  2043. }
  2044. $sth->finish;
  2045. chop $self->{recurringemail};
  2046. chop $self->{recurringprint};
  2047. if ( $self->{recurringstartdate} ) {
  2048. $self->{recurringreference} =
  2049. $self->escape( $self->{recurringreference}, 1 );
  2050. $self->{recurringmessage} =
  2051. $self->escape( $self->{recurringmessage}, 1 );
  2052. for (
  2053. qw(reference startdate repeat unit howmany
  2054. payment print email message)
  2055. )
  2056. {
  2057. $self->{recurring} .= qq|$self->{"recurring$_"},|;
  2058. }
  2059. chop $self->{recurring};
  2060. }
  2061. $dbh->commit;
  2062. }
  2063. sub save_recurring {
  2064. my ( $self, $dbh2, $myconfig ) = @_;
  2065. my $dbh = $self->{dbh};
  2066. my $query;
  2067. $query = qq|DELETE FROM recurring
  2068. WHERE id = ?|;
  2069. $sth = $dbh->prepare($query) || $self->dberror($query);
  2070. $sth->execute( $self->{id} ) || $self->dberror($query);
  2071. $query = qq|DELETE FROM recurringemail
  2072. WHERE id = ?|;
  2073. $sth = $dbh->prepare($query) || $self->dberror($query);
  2074. $sth->execute( $self->{id} ) || $self->dberror($query);
  2075. $query = qq|DELETE FROM recurringprint
  2076. WHERE id = ?|;
  2077. $sth = $dbh->prepare($query) || $self->dberror($query);
  2078. $sth->execute( $self->{id} ) || $self->dberror($query);
  2079. if ( $self->{recurring} ) {
  2080. my %s = ();
  2081. (
  2082. $s{reference}, $s{startdate}, $s{repeat},
  2083. $s{unit}, $s{howmany}, $s{payment},
  2084. $s{print}, $s{email}, $s{message}
  2085. ) = split /,/, $self->{recurring};
  2086. if ($s{howmany} == 0){
  2087. $self->error("Cannot set to recur 0 times");
  2088. }
  2089. for (qw(reference message)) { $s{$_} = $self->unescape( $s{$_} ) }
  2090. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  2091. # calculate enddate
  2092. my $advance = $s{repeat} * ( $s{howmany} - 1 );
  2093. my %interval;
  2094. $interval{'Pg'} =
  2095. "(date '$s{startdate}' + interval '$advance $s{unit}')";
  2096. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  2097. my ($enddate) = $dbh->selectrow_array($query);
  2098. # calculate nextdate
  2099. $query = qq|
  2100. SELECT current_date - ?::date AS a,
  2101. ?::date - current_date AS b|;
  2102. $sth = $dbh->prepare($query) || $self->dberror($query);
  2103. $sth->execute( $s{startdate}, $enddate );
  2104. my ( $a, $b ) = $sth->fetchrow_array;
  2105. if ( $a + $b ) {
  2106. $advance =
  2107. int( ( $a / ( $a + $b ) ) * ( $s{howmany} - 1 ) + 1 ) *
  2108. $s{repeat};
  2109. }
  2110. else {
  2111. $advance = 0;
  2112. }
  2113. my $nextdate = $enddate;
  2114. if ( $advance > 0 ) {
  2115. if ( $advance < ( $s{repeat} * $s{howmany} ) ) {
  2116. $query = qq|SELECT (date '$s{startdate}' + interval '$advance $s{unit}')|;
  2117. ($nextdate) = $dbh->selectrow_array($query);
  2118. }
  2119. }
  2120. else {
  2121. $nextdate = $s{startdate};
  2122. }
  2123. if ( $self->{recurringnextdate} ) {
  2124. $nextdate = $self->{recurringnextdate};
  2125. $query = qq|SELECT '$enddate' - date '$nextdate'|;
  2126. if ( $dbh->selectrow_array($query) < 0 ) {
  2127. undef $nextdate;
  2128. }
  2129. }
  2130. $self->{recurringpayment} *= 1;
  2131. $query = qq|
  2132. INSERT INTO recurring
  2133. (id, reference, startdate, enddate, nextdate,
  2134. repeat, unit, howmany, payment)
  2135. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  2136. $sth = $dbh->prepare($query);
  2137. $sth->execute(
  2138. $self->{id}, $s{reference}, $s{startdate},
  2139. $enddate, $nextdate, $s{repeat},
  2140. $s{unit}, $s{howmany}, $s{payment}
  2141. );
  2142. my @p;
  2143. my $p;
  2144. my $i;
  2145. my $sth;
  2146. if ( $s{email} ) {
  2147. # formname:format
  2148. @p = split /:/, $s{email};
  2149. $query =
  2150. qq|INSERT INTO recurringemail (id, formname, format, message)
  2151. VALUES (?, ?, ?, ?)|;
  2152. $sth = $dbh->prepare($query) || $self->dberror($query);
  2153. for ( $i = 0 ; $i <= $#p ; $i += 2 ) {
  2154. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $s{message} );
  2155. }
  2156. $sth->finish;
  2157. }
  2158. if ( $s{print} ) {
  2159. # formname:format:printer
  2160. @p = split /:/, $s{print};
  2161. $query =
  2162. qq|INSERT INTO recurringprint (id, formname, format, printer)
  2163. VALUES (?, ?, ?, ?)|;
  2164. $sth = $dbh->prepare($query) || $self->dberror($query);
  2165. for ( $i = 0 ; $i <= $#p ; $i += 3 ) {
  2166. $p = ( $p[ $i + 2 ] ) ? $p[ $i + 2 ] : "";
  2167. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $p );
  2168. }
  2169. $sth->finish;
  2170. }
  2171. }
  2172. $dbh->commit;
  2173. }
  2174. sub save_intnotes {
  2175. my ( $self, $myconfig, $vc ) = @_;
  2176. # no id return
  2177. return unless $self->{id};
  2178. my $dbh = $self->{dbh};
  2179. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  2180. $sth = $dbh->prepare($query);
  2181. $sth->execute( $self->{intnotes}, $self->{id} ) || $self->dberror($query);
  2182. $dbh->commit;
  2183. }
  2184. sub update_defaults {
  2185. my ( $self, $myconfig, $fld ) = @_;
  2186. if ( !$self->{dbh} && $self ) {
  2187. $self->db_init($myconfig);
  2188. }
  2189. my $dbh = $self->{dbh};
  2190. if ( !$self ) {
  2191. $dbh = $_[3];
  2192. }
  2193. my $query = qq|
  2194. SELECT value FROM defaults
  2195. WHERE setting_key = ? FOR UPDATE|;
  2196. $sth = $dbh->prepare($query);
  2197. $sth->execute($fld);
  2198. ($_) = $sth->fetchrow_array();
  2199. $_ = "0" unless $_;
  2200. # check for and replace
  2201. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  2202. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  2203. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  2204. # <?lsmb PHONE ?> for customer and vendors
  2205. my $num = $_;
  2206. ($num) = $num =~ /(\d+)/;
  2207. if ( defined $num ) {
  2208. my $incnum;
  2209. # if we have leading zeros check how long it is
  2210. if ( $num =~ /^0/ ) {
  2211. my $l = length $num;
  2212. $incnum = $num + 1;
  2213. $l -= length $incnum;
  2214. # pad it out with zeros
  2215. my $padzero = "0" x $l;
  2216. $incnum = ( "0" x $l ) . $incnum;
  2217. }
  2218. else {
  2219. $incnum = $num + 1;
  2220. }
  2221. s/$num/$incnum/;
  2222. }
  2223. my $dbvar = $_;
  2224. my $var = $_;
  2225. my $str;
  2226. my $param;
  2227. if (/<\?lsmb /) {
  2228. while (/<\?lsmb /) {
  2229. s/<\?lsmb .*? \?>//;
  2230. last unless $&;
  2231. $param = $&;
  2232. $str = "";
  2233. if ( $param =~ /<\?lsmb date \?>/i ) {
  2234. $str = (
  2235. $self->split_date(
  2236. $myconfig->{dateformat},
  2237. $self->{transdate}
  2238. )
  2239. )[0];
  2240. $var =~ s/$param/$str/;
  2241. }
  2242. if ( $param =~
  2243. /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i
  2244. )
  2245. {
  2246. my $fld = lc $&;
  2247. $fld =~ s/<\?lsmb //;
  2248. if ( $fld =~ /name/ ) {
  2249. if ( $self->{type} ) {
  2250. $fld = $self->{vc};
  2251. }
  2252. }
  2253. my $p = $param;
  2254. $p =~ s/(<|>|%)//g;
  2255. my @p = split / /, $p;
  2256. my @n = split / /, uc $self->{$fld};
  2257. if ( $#p > 0 ) {
  2258. for ( my $i = 1 ; $i <= $#p ; $i++ ) {
  2259. $str .= substr( $n[ $i - 1 ], 0, $p[$i] );
  2260. }
  2261. }
  2262. else {
  2263. ($str) = split /--/, $self->{$fld};
  2264. }
  2265. $var =~ s/$param/$str/;
  2266. $var =~ s/\W//g if $fld eq 'phone';
  2267. }
  2268. if ( $param =~ /<\?lsmb (yy|mm|dd)/i ) {
  2269. my $p = $param;
  2270. $p =~ s/(<|>|%)//g;
  2271. my $spc = $p;
  2272. $spc =~ s/\w//g;
  2273. $spc = substr( $spc, 0, 1 );
  2274. my %d = ( yy => 1, mm => 2, dd => 3 );
  2275. my @p = ();
  2276. my @a = $self->split_date( $myconfig->{dateformat},
  2277. $self->{transdate} );
  2278. for ( sort keys %d ) { push @p, $a[ $d{$_} ] if ( $p =~ /$_/ ) }
  2279. $str = join $spc, @p;
  2280. $var =~ s/$param/$str/;
  2281. }
  2282. if ( $param =~ /<\?lsmb curr/i ) {
  2283. $var =~ s/$param/$self->{currency}/;
  2284. }
  2285. }
  2286. }
  2287. $query = qq|
  2288. UPDATE defaults
  2289. SET value = ?
  2290. WHERE setting_key = ?|;
  2291. $sth = $dbh->prepare($query);
  2292. $sth->execute( $dbvar, $fld ) || $self->dberror($query);
  2293. $dbh->commit;
  2294. $var;
  2295. }
  2296. sub db_prepare_vars {
  2297. my $self = shift;
  2298. for (@_) {
  2299. if ( !$self->{$_} and $self->{$_} ne "0" ) {
  2300. undef $self->{$_};
  2301. }
  2302. }
  2303. }
  2304. sub split_date {
  2305. my ( $self, $dateformat, $date ) = @_;
  2306. my $mm;
  2307. my $dd;
  2308. my $yy;
  2309. my $rv;
  2310. if ( !$date ) {
  2311. my @d = localtime;
  2312. $dd = $d[3];
  2313. $mm = ++$d[4];
  2314. $yy = substr( $d[5], -2 );
  2315. $mm = substr( "0$mm", -2 );
  2316. $dd = substr( "0$dd", -2 );
  2317. }
  2318. if ( $dateformat =~ /^yy/ ) {
  2319. if ($date) {
  2320. if ( $date =~ /\D/ ) {
  2321. ( $yy, $mm, $dd ) = split /\D/, $date;
  2322. $mm *= 1;
  2323. $dd *= 1;
  2324. $mm = substr( "0$mm", -2 );
  2325. $dd = substr( "0$dd", -2 );
  2326. $yy = substr( $yy, -2 );
  2327. $rv = "$yy$mm$dd";
  2328. }
  2329. else {
  2330. $rv = $date;
  2331. }
  2332. }
  2333. else {
  2334. $rv = "$yy$mm$dd";
  2335. }
  2336. }
  2337. elsif ( $dateformat =~ /^mm/ ) {
  2338. if ($date) {
  2339. if ( $date =~ /\D/ ) {
  2340. ( $mm, $dd, $yy ) = split /\D/, $date;
  2341. $mm *= 1;
  2342. $dd *= 1;
  2343. $mm = substr( "0$mm", -2 );
  2344. $dd = substr( "0$dd", -2 );
  2345. $yy = substr( $yy, -2 );
  2346. $rv = "$mm$dd$yy";
  2347. }
  2348. else {
  2349. $rv = $date;
  2350. }
  2351. }
  2352. else {
  2353. $rv = "$mm$dd$yy";
  2354. }
  2355. }
  2356. elsif ( $dateformat =~ /^dd/ ) {
  2357. if ($date) {
  2358. if ( $date =~ /\D/ ) {
  2359. ( $dd, $mm, $yy ) = split /\D/, $date;
  2360. $mm *= 1;
  2361. $dd *= 1;
  2362. $mm = substr( "0$mm", -2 );
  2363. $dd = substr( "0$dd", -2 );
  2364. $yy = substr( $yy, -2 );
  2365. $rv = "$dd$mm$yy";
  2366. }
  2367. else {
  2368. $rv = $date;
  2369. }
  2370. }
  2371. else {
  2372. $rv = "$dd$mm$yy";
  2373. }
  2374. }
  2375. ( $rv, $yy, $mm, $dd );
  2376. }
  2377. sub format_date {
  2378. # takes an iso date in, and converts it to the date for printing
  2379. my ( $self, $date ) = @_;
  2380. my $datestring;
  2381. if ( $date =~ /^\d{4}\D/ ) { # is an ISO date
  2382. $datestring = $self->{db_dateformat};
  2383. my ( $yyyy, $mm, $dd ) = split( /\W/, $date );
  2384. $datestring =~ s/y+/$yyyy/;
  2385. $datestring =~ s/mm/$mm/;
  2386. $datestring =~ s/dd/$dd/;
  2387. }
  2388. else { # return date
  2389. $datestring = $date;
  2390. }
  2391. $datestring;
  2392. }
  2393. sub from_to {
  2394. my ( $self, $yyyy, $mm, $interval ) = @_;
  2395. my @t;
  2396. my $dd = 1;
  2397. my $fromdate = "$yyyy-${mm}-01";
  2398. my $bd = 1;
  2399. if ( defined $interval ) {
  2400. if ( $interval == 12 ) {
  2401. $yyyy++;
  2402. }
  2403. else {
  2404. if ( ( $mm += $interval ) > 12 ) {
  2405. $mm -= 12;
  2406. $yyyy++;
  2407. }
  2408. if ( $interval == 0 ) {
  2409. @t = localtime(time);
  2410. $dd = $t[3];
  2411. $mm = $t[4] + 1;
  2412. $yyyy = $t[5] + 1900;
  2413. $bd = 0;
  2414. }
  2415. }
  2416. }
  2417. else {
  2418. if ( ++$mm > 12 ) {
  2419. $mm -= 12;
  2420. $yyyy++;
  2421. }
  2422. }
  2423. $mm--;
  2424. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yyyy ) - $bd );
  2425. $t[4]++;
  2426. $t[4] = substr( "0$t[4]", -2 );
  2427. $t[3] = substr( "0$t[3]", -2 );
  2428. $t[5] += 1900;
  2429. ( $self->format_date($fromdate), $self->format_date("$t[5]-$t[4]-$t[3]") );
  2430. }
  2431. sub audittrail {
  2432. my ( $self, $dbh, $myconfig, $audittrail ) = @_;
  2433. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2434. my $query;
  2435. my $rv;
  2436. my $disconnect;
  2437. if ( !$dbh ) {
  2438. $dbh = $self->{dbh};
  2439. }
  2440. # if we have an id add audittrail, otherwise get a new timestamp
  2441. my @queryargs;
  2442. if ( $audittrail->{id} ) {
  2443. $query = qq|
  2444. SELECT value FROM defaults
  2445. WHERE setting_key = 'audittrail'|;
  2446. if ( $dbh->selectrow_array($query) ) {
  2447. my ( $null, $employee_id ) = $self->get_employee($dbh);
  2448. if ( $self->{audittrail} && !$myconfig ) {
  2449. chop $self->{audittrail};
  2450. my @a = split /\|/, $self->{audittrail};
  2451. my %newtrail = ();
  2452. my $key;
  2453. my $i;
  2454. my @flds = qw(tablename reference formname action transdate);
  2455. # put into hash and remove dups
  2456. while (@a) {
  2457. $key = "$a[2]$a[3]";
  2458. $i = 0;
  2459. $newtrail{$key} = { map { $_ => $a[ $i++ ] } @flds };
  2460. splice @a, 0, 5;
  2461. }
  2462. $query = qq|
  2463. INSERT INTO audittrail
  2464. (trans_id, tablename, reference,
  2465. formname, action, transdate,
  2466. employee_id)
  2467. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2468. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2469. foreach $key (
  2470. sort {
  2471. $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
  2472. } keys %newtrail
  2473. )
  2474. {
  2475. $i = 2;
  2476. $sth->bind_param( 1, $audittrail->{id} );
  2477. for (@flds) {
  2478. $sth->bind_param( $i++, $newtrail{$key}{$_} );
  2479. }
  2480. $sth->bind_param( $i++, $employee_id );
  2481. $sth->execute() || $self->dberror($query);
  2482. $sth->finish;
  2483. }
  2484. }
  2485. if ( $audittrail->{transdate} ) {
  2486. $query = qq|
  2487. INSERT INTO audittrail (
  2488. trans_id, tablename, reference,
  2489. formname, action, employee_id,
  2490. transdate)
  2491. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2492. @queryargs = (
  2493. $audittrail->{id}, $audittrail->{tablename},
  2494. $audittrail->{reference}, $audittrail->{formname},
  2495. $audittrail->{action}, $employee_id,
  2496. $audittrail->{transdate}
  2497. );
  2498. }
  2499. else {
  2500. $query = qq|
  2501. INSERT INTO audittrail
  2502. (trans_id, tablename, reference,
  2503. formname, action, employee_id)
  2504. VALUES (?, ?, ?, ?, ?, ?)|;
  2505. @queryargs = (
  2506. $audittrail->{id}, $audittrail->{tablename},
  2507. $audittrail->{reference}, $audittrail->{formname},
  2508. $audittrail->{action}, $employee_id,
  2509. );
  2510. }
  2511. $sth = $dbh->prepare($query);
  2512. $sth->execute(@queryargs) || $self->dberror($query);
  2513. }
  2514. }
  2515. else {
  2516. $query = qq|SELECT current_timestamp|;
  2517. my ($timestamp) = $dbh->selectrow_array($query);
  2518. $rv =
  2519. "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2520. }
  2521. $dbh->commit;
  2522. $rv;
  2523. }
  2524. 1;