summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: dba2194d1e99b74ffd08f3d5b759f92566932f22 (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 employees
  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|SELECT name, id
  1398. FROM employees
  1399. WHERE login = ?|;
  1400. $sth = $self->{dbh}->prepare($query);
  1401. $sth->execute($login);
  1402. my (@a) = $sth->fetchrow_array();
  1403. $a[1] *= 1;
  1404. $sth->finish;
  1405. $self->{dbh}->commit;
  1406. @a;
  1407. }
  1408. # this sub gets the id and name from $table
  1409. sub get_name {
  1410. my ( $self, $myconfig, $table, $transdate ) = @_;
  1411. # connect to database
  1412. my @queryargs;
  1413. my $where;
  1414. if ($transdate) {
  1415. $where = qq|
  1416. AND (startdate IS NULL OR startdate <= ?)
  1417. AND (enddate IS NULL OR enddate >= ?)|;
  1418. @queryargs = ( $transdate, $transdate );
  1419. }
  1420. my $name = $self->like( lc $self->{$table} );
  1421. my $query = qq|
  1422. SELECT * FROM $table
  1423. WHERE (lower(name) LIKE ? OR ${table}number LIKE ?)
  1424. $where
  1425. ORDER BY name|;
  1426. unshift( @queryargs, $name, $name );
  1427. my $sth = $self->{dbh}->prepare($query);
  1428. $sth->execute(@queryargs) || $self->dberror($query);
  1429. my $i = 0;
  1430. @{ $self->{name_list} } = ();
  1431. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1432. push( @{ $self->{name_list} }, $ref );
  1433. $i++;
  1434. }
  1435. $sth->finish;
  1436. $self->{dbh}->commit;
  1437. $i;
  1438. }
  1439. sub all_vc {
  1440. my ( $self, $myconfig, $vc, $module, $dbh, $transdate, $job ) = @_;
  1441. my $ref;
  1442. my $disconnect = 0;
  1443. $dbh = $self->{dbh};
  1444. my $sth;
  1445. my $query = qq|SELECT count(*) FROM $vc|;
  1446. my $where;
  1447. my @queryargs = ();
  1448. if ($transdate) {
  1449. $query .= qq| WHERE (startdate IS NULL OR startdate <= ?)
  1450. AND (enddate IS NULL OR enddate >= ?)|;
  1451. @queryargs = ( $transdate, $transdate );
  1452. }
  1453. $sth = $dbh->prepare($query);
  1454. $sth->execute(@queryargs);
  1455. my ($count) = $sth->fetchrow_array;
  1456. $sth->finish;
  1457. @queryargs = ();
  1458. # build selection list
  1459. if ( $count < $myconfig->{vclimit} ) {
  1460. $self->{"${vc}_id"} *= 1;
  1461. $query = qq|SELECT id, name
  1462. FROM $vc
  1463. WHERE 1=1
  1464. $where
  1465. UNION
  1466. SELECT id,name
  1467. FROM $vc
  1468. WHERE id = ?
  1469. ORDER BY name|;
  1470. push( @queryargs, $self->{"${vc}_id"} );
  1471. $sth = $dbh->prepare($query);
  1472. $sth->execute(@queryargs) || $self->dberror($query);
  1473. @{ $self->{"all_$vc"} } = ();
  1474. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1475. push @{ $self->{"all_$vc"} }, $ref;
  1476. }
  1477. $sth->finish;
  1478. }
  1479. # get self
  1480. if ( !$self->{employee_id} ) {
  1481. ( $self->{employee}, $self->{employee_id} ) = split /--/,
  1482. $self->{employee};
  1483. ( $self->{employee}, $self->{employee_id} ) = $self->get_employee($dbh)
  1484. unless $self->{employee_id};
  1485. }
  1486. $self->all_employees( $myconfig, $dbh, $transdate, 1 );
  1487. $self->all_departments( $myconfig, $dbh, $vc );
  1488. $self->all_projects( $myconfig, $dbh, $transdate, $job );
  1489. # get language codes
  1490. $query = qq|SELECT *
  1491. FROM language
  1492. ORDER BY 2|;
  1493. $sth = $dbh->prepare($query);
  1494. $sth->execute || $self->dberror($query);
  1495. $self->{all_language} = ();
  1496. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1497. push @{ $self->{all_language} }, $ref;
  1498. }
  1499. $sth->finish;
  1500. $self->all_taxaccounts( $myconfig, $dbh, $transdate );
  1501. $self->{dbh}->commit;
  1502. }
  1503. sub all_taxaccounts {
  1504. my ( $self, $myconfig, $dbh2, $transdate ) = @_;
  1505. my $dbh = $self->{dbh};
  1506. my $sth;
  1507. my $query;
  1508. my $where;
  1509. my @queryargs = ();
  1510. if ($transdate) {
  1511. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1512. push( @queryargs, $transdate );
  1513. }
  1514. if ( $self->{taxaccounts} ) {
  1515. # rebuild tax rates
  1516. $query = qq|SELECT t.rate, t.taxnumber
  1517. FROM tax t
  1518. JOIN chart c ON (c.id = t.chart_id)
  1519. WHERE c.accno = ?
  1520. $where
  1521. ORDER BY accno, validto|;
  1522. $sth = $dbh->prepare($query) || $self->dberror($query);
  1523. foreach my $accno ( split / /, $self->{taxaccounts} ) {
  1524. $sth->execute( $accno, @queryargs );
  1525. ( $self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"} ) =
  1526. $sth->fetchrow_array;
  1527. $sth->finish;
  1528. }
  1529. }
  1530. $self->{dbh}->commit;
  1531. }
  1532. sub all_employees {
  1533. my ( $self, $myconfig, $dbh2, $transdate, $sales ) = @_;
  1534. my $dbh = $self->{dbh};
  1535. my @whereargs = ();
  1536. # setup employees/sales contacts
  1537. my $query = qq|SELECT id, name
  1538. FROM employees
  1539. WHERE 1 = 1|;
  1540. if ($transdate) {
  1541. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1542. AND (enddate IS NULL OR enddate >= ?)|;
  1543. @whereargs = ( $transdate, $transdate );
  1544. }
  1545. else {
  1546. $query .= qq| AND enddate IS NULL|;
  1547. }
  1548. if ($sales) {
  1549. $query .= qq| AND sales = '1'|;
  1550. }
  1551. $query .= qq| ORDER BY name|;
  1552. my $sth = $dbh->prepare($query);
  1553. $sth->execute(@whereargs) || $self->dberror($query);
  1554. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1555. push @{ $self->{all_employee} }, $ref;
  1556. }
  1557. $sth->finish;
  1558. $dbh->commit;
  1559. }
  1560. sub all_projects {
  1561. my ( $self, $myconfig, $dbh2, $transdate, $job ) = @_;
  1562. my $dbh = $self->{dbh};
  1563. my @queryargs = ();
  1564. my $where = "1 = 1";
  1565. $where = qq|id NOT IN (SELECT id
  1566. FROM parts
  1567. WHERE project_id > 0)| if !$job;
  1568. my $query = qq|SELECT *
  1569. FROM project
  1570. WHERE $where|;
  1571. if ( $self->{language_code} ) {
  1572. $query = qq|
  1573. SELECT pr.*, t.description AS translation
  1574. FROM project pr
  1575. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1576. WHERE t.language_code = ?|;
  1577. push( @queryargs, $self->{language_code} );
  1578. }
  1579. if ($transdate) {
  1580. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1581. AND (enddate IS NULL OR enddate >= ?)|;
  1582. push( @queryargs, $transdate, $transdate );
  1583. }
  1584. $query .= qq| ORDER BY projectnumber|;
  1585. $sth = $dbh->prepare($query);
  1586. $sth->execute(@queryargs) || $self->dberror($query);
  1587. @{ $self->{all_project} } = ();
  1588. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1589. push @{ $self->{all_project} }, $ref;
  1590. }
  1591. $sth->finish;
  1592. $dbh->commit;
  1593. }
  1594. sub all_departments {
  1595. my ( $self, $myconfig, $dbh2, $vc ) = @_;
  1596. $dbh = $self->{dbh};
  1597. my $where = "1 = 1";
  1598. if ($vc) {
  1599. if ( $vc eq 'customer' ) {
  1600. $where = " role = 'P'";
  1601. }
  1602. }
  1603. my $query = qq|SELECT id, description
  1604. FROM department
  1605. WHERE $where
  1606. ORDER BY 2|;
  1607. my $sth = $dbh->prepare($query);
  1608. $sth->execute || $self->dberror($query);
  1609. @{ $self->{all_department} } = ();
  1610. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1611. push @{ $self->{all_department} }, $ref;
  1612. }
  1613. $sth->finish;
  1614. $self->all_years($myconfig);
  1615. $dbh->commit;
  1616. }
  1617. sub all_years {
  1618. my ( $self, $myconfig, $dbh2 ) = @_;
  1619. $dbh = $self->{dbh};
  1620. # get years
  1621. my $query = qq|
  1622. SELECT (SELECT transdate FROM acc_trans ORDER BY transdate asc
  1623. LIMIT 1),
  1624. (SELECT transdate FROM acc_trans ORDER BY transdate desc
  1625. LIMIT 1)|;
  1626. my ( $startdate, $enddate ) = $dbh->selectrow_array($query);
  1627. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1628. ($startdate) = split /\W/, $startdate;
  1629. ($enddate) = split /\W/, $enddate;
  1630. }
  1631. else {
  1632. (@_) = split /\W/, $startdate;
  1633. $startdate = $_[2];
  1634. (@_) = split /\W/, $enddate;
  1635. $enddate = $_[2];
  1636. }
  1637. $self->{all_years} = ();
  1638. $startdate = substr( $startdate, 0, 4 );
  1639. $enddate = substr( $enddate, 0, 4 );
  1640. while ( $enddate >= $startdate ) {
  1641. push @{ $self->{all_years} }, $enddate--;
  1642. }
  1643. #this should probably be changed to use locale
  1644. %{ $self->{all_month} } = (
  1645. '01' => 'January',
  1646. '02' => 'February',
  1647. '03' => 'March',
  1648. '04' => 'April',
  1649. '05' => 'May ',
  1650. '06' => 'June',
  1651. '07' => 'July',
  1652. '08' => 'August',
  1653. '09' => 'September',
  1654. '10' => 'October',
  1655. '11' => 'November',
  1656. '12' => 'December'
  1657. );
  1658. $dbh->commit;
  1659. }
  1660. sub create_links {
  1661. my ( $self, $module, $myconfig, $vc, $job ) = @_;
  1662. # get last customers or vendors
  1663. my ( $query, $sth );
  1664. if (!$self->{dbh}) {
  1665. $self->db_init($myconfig);
  1666. }
  1667. $dbh = $self->{dbh};
  1668. my %xkeyref = ();
  1669. # now get the account numbers
  1670. $query = qq|SELECT accno, description, link
  1671. FROM chart
  1672. WHERE link LIKE ?
  1673. ORDER BY accno|;
  1674. $sth = $dbh->prepare($query);
  1675. $sth->execute( "%" . "$module%" ) || $self->dberror($query);
  1676. $self->{accounts} = "";
  1677. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1678. foreach my $key ( split /:/, $ref->{link} ) {
  1679. if ( $key =~ /$module/ ) {
  1680. # cross reference for keys
  1681. $xkeyref{ $ref->{accno} } = $key;
  1682. push @{ $self->{"${module}_links"}{$key} },
  1683. {
  1684. accno => $ref->{accno},
  1685. description => $ref->{description}
  1686. };
  1687. $self->{accounts} .= "$ref->{accno} "
  1688. unless $key =~ /tax/;
  1689. }
  1690. }
  1691. }
  1692. $sth->finish;
  1693. my $arap = ( $vc eq 'customer' ) ? 'ar' : 'ap';
  1694. if ( $self->{id} ) {
  1695. $query = qq|
  1696. SELECT a.invnumber, a.transdate,
  1697. a.${vc}_id, a.datepaid, a.duedate, a.ordnumber,
  1698. a.taxincluded, a.curr AS currency, a.notes,
  1699. a.intnotes, c.name AS $vc, a.department_id,
  1700. d.description AS department,
  1701. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1702. a.employee_id, e.name AS employee,
  1703. c.language_code, a.ponumber
  1704. FROM $arap a
  1705. JOIN $vc c ON (a.${vc}_id = c.id)
  1706. LEFT JOIN employees e ON (e.id = a.employee_id)
  1707. LEFT JOIN department d ON (d.id = a.department_id)
  1708. WHERE a.id = ?|;
  1709. $sth = $dbh->prepare($query);
  1710. $sth->execute( $self->{id} ) || $self->dberror($query);
  1711. $ref = $sth->fetchrow_hashref(NAME_lc);
  1712. $self->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1713. foreach $key ( keys %$ref ) {
  1714. $self->{$key} = $ref->{$key};
  1715. }
  1716. $sth->finish;
  1717. # get printed, emailed
  1718. $query = qq|
  1719. SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1720. FROM status s WHERE s.trans_id = ?|;
  1721. $sth = $dbh->prepare($query);
  1722. $sth->execute( $self->{id} ) || $self->dberror($query);
  1723. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1724. $self->{printed} .= "$ref->{formname} "
  1725. if $ref->{printed};
  1726. $self->{emailed} .= "$ref->{formname} "
  1727. if $ref->{emailed};
  1728. $self->{queued} .= "$ref->{formname} " . "$ref->{spoolfile} "
  1729. if $ref->{spoolfile};
  1730. }
  1731. $sth->finish;
  1732. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1733. # get recurring
  1734. $self->get_recurring($dbh);
  1735. # get amounts from individual entries
  1736. $query = qq|
  1737. SELECT c.accno, c.description, a.source, a.amount,
  1738. a.memo, a.transdate, a.cleared, a.project_id,
  1739. p.projectnumber
  1740. FROM acc_trans a
  1741. JOIN chart c ON (c.id = a.chart_id)
  1742. LEFT JOIN project p ON (p.id = a.project_id)
  1743. WHERE a.trans_id = ?
  1744. AND a.fx_transaction = '0'
  1745. ORDER BY transdate|;
  1746. $sth = $dbh->prepare($query);
  1747. $sth->execute( $self->{id} ) || $self->dberror($query);
  1748. my $fld = ( $vc eq 'customer' ) ? 'buy' : 'sell';
  1749. $self->{exchangerate} =
  1750. $self->get_exchangerate( $dbh, $self->{currency}, $self->{transdate},
  1751. $fld );
  1752. # store amounts in {acc_trans}{$key} for multiple accounts
  1753. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1754. $ref->{exchangerate} =
  1755. $self->get_exchangerate( $dbh, $self->{currency},
  1756. $ref->{transdate}, $fld );
  1757. push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
  1758. }
  1759. $sth->finish;
  1760. for (qw(curr closedto revtrans)) {
  1761. $query = qq|
  1762. SELECT value FROM defaults
  1763. WHERE setting_key = '$_'|;
  1764. $sth = $dbh->prepare($query);
  1765. $sth->execute || $self->dberror($query);
  1766. ($val) = $sth->fetchrow_array();
  1767. if ( $_ eq 'curr' ) {
  1768. $self->{currencies} = $val;
  1769. }
  1770. else {
  1771. $self->{$_} = $val;
  1772. }
  1773. $sth->finish;
  1774. }
  1775. $self->{transdate} = $self->current_date;
  1776. }
  1777. else {
  1778. for (qw(current_date curr closedto revtrans)) {
  1779. $query = qq|
  1780. SELECT value FROM defaults
  1781. WHERE setting_key = '$_'|;
  1782. $sth = $dbh->prepare($query);
  1783. $sth->execute || $self->dberror($query);
  1784. ($val) = $sth->fetchrow_array();
  1785. if ( $_ eq 'curr' ) {
  1786. $self->{currencies} = $val;
  1787. }
  1788. elsif ( $_ eq 'current_date' ) {
  1789. $self->{transdate} = $val;
  1790. }
  1791. else {
  1792. $self->{$_} = $val;
  1793. }
  1794. $sth->finish;
  1795. }
  1796. if ( !$self->{"$self->{vc}_id"} ) {
  1797. $self->lastname_used( $myconfig, $dbh, $vc, $module );
  1798. }
  1799. }
  1800. $self->all_vc( $myconfig, $vc, $module, $dbh, $self->{transdate}, $job );
  1801. $self->{dbh}->commit;
  1802. }
  1803. sub lastname_used {
  1804. my ( $self, $myconfig, $dbh2, $vc, $module ) = @_;
  1805. my $dbh = $self->{dbh};
  1806. $vc ||= $self->{vc}; # add default to correct for improper passing
  1807. my $arap = ( $vc eq 'customer' ) ? "ar" : "ap";
  1808. my $where = "1 = 1";
  1809. my $sth;
  1810. if ( $self->{type} =~ /_order/ ) {
  1811. $arap = 'oe';
  1812. $where = "quotation = '0'";
  1813. }
  1814. if ( $self->{type} =~ /_quotation/ ) {
  1815. $arap = 'oe';
  1816. $where = "quotation = '1'";
  1817. }
  1818. my $query = qq|
  1819. SELECT ct.name AS $vc, ct.curr AS currency, ct.id AS ${vc}_id,
  1820. current_date + ct.terms AS duedate,
  1821. ct.notes,
  1822. ct.curr AS currency
  1823. FROM $vc ct
  1824. WHERE ct.id = (select ${vc}_id from $arap where $where AND ${vc}_id IS NOT NULL order by id DESC limit 1)|;
  1825. $sth = $dbh->prepare($query);
  1826. $sth->execute() || $self->dberror($query);
  1827. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1828. for ( keys %$ref ) { $self->{$_} = $ref->{$_} }
  1829. $sth->finish;
  1830. $dbh->commit;
  1831. }
  1832. sub current_date {
  1833. my ( $self, $myconfig, $thisdate, $days ) = @_;
  1834. my $dbh = $self->{dbh};
  1835. my $query;
  1836. $days *= 1;
  1837. if ($thisdate) {
  1838. my $dateformat = $myconfig->{dateformat};
  1839. if ( $myconfig->{dateformat} !~ /^y/ ) {
  1840. my @a = split /\D/, $thisdate;
  1841. $dateformat .= "yy" if ( length $a[2] > 2 );
  1842. }
  1843. if ( $thisdate !~ /\D/ ) {
  1844. $dateformat = 'yyyymmdd';
  1845. }
  1846. $query = qq|SELECT (to_date(?, ?)
  1847. + ?::interval)::date AS thisdate|;
  1848. @queryargs = ( $thisdate, $dateformat, sprintf('%d days', $days) );
  1849. }
  1850. else {
  1851. $query = qq|SELECT current_date AS thisdate|;
  1852. @queryargs = ();
  1853. }
  1854. $sth = $dbh->prepare($query);
  1855. $sth->execute(@queryargs);
  1856. ($thisdate) = $sth->fetchrow_array;
  1857. $dbh->commit;
  1858. $thisdate;
  1859. }
  1860. sub like {
  1861. my ( $self, $str ) = @_;
  1862. "%$str%";
  1863. }
  1864. sub redo_rows {
  1865. my ( $self, $flds, $new, $count, $numrows ) = @_;
  1866. my @ndx = ();
  1867. for ( 1 .. $count ) {
  1868. push @ndx, { num => $new->[ $_ - 1 ]->{runningnumber}, ndx => $_ };
  1869. }
  1870. my $i = 0;
  1871. # fill rows
  1872. foreach my $item ( sort { $a->{num} <=> $b->{num} } @ndx ) {
  1873. $i++;
  1874. $j = $item->{ndx} - 1;
  1875. for ( @{$flds} ) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1876. }
  1877. # delete empty rows
  1878. for $i ( $count + 1 .. $numrows ) {
  1879. for ( @{$flds} ) { delete $self->{"${_}_$i"} }
  1880. }
  1881. }
  1882. sub get_partsgroup {
  1883. my ( $self, $myconfig, $p ) = @_;
  1884. my $dbh = $self->{dbh};
  1885. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1886. FROM partsgroup pg
  1887. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1888. my $where;
  1889. my $sortorder = "partsgroup";
  1890. if ( $p->{searchitems} eq 'part' ) {
  1891. $where = qq| WHERE (p.inventory_accno_id > 0
  1892. AND p.income_accno_id > 0)|;
  1893. }
  1894. if ( $p->{searchitems} eq 'service' ) {
  1895. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1896. }
  1897. if ( $p->{searchitems} eq 'assembly' ) {
  1898. $where = qq| WHERE p.assembly = '1'|;
  1899. }
  1900. if ( $p->{searchitems} eq 'labor' ) {
  1901. $where =
  1902. qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1903. }
  1904. if ( $p->{searchitems} eq 'nolabor' ) {
  1905. $where = qq| WHERE p.income_accno_id > 0|;
  1906. }
  1907. if ( $p->{all} ) {
  1908. $query = qq|SELECT id, partsgroup
  1909. FROM partsgroup|;
  1910. }
  1911. my @queryargs = ();
  1912. if ( $p->{language_code} ) {
  1913. $sortorder = "translation";
  1914. $query = qq|
  1915. SELECT DISTINCT pg.id, pg.partsgroup,
  1916. t.description AS translation
  1917. FROM partsgroup pg
  1918. JOIN parts p ON (p.partsgroup_id = pg.id)
  1919. LEFT JOIN translation t ON (t.trans_id = pg.id
  1920. AND t.language_code = ?)|;
  1921. @queryargs = ( $p->{language_code} );
  1922. }
  1923. $query .= qq| $where ORDER BY $sortorder|;
  1924. my $sth = $dbh->prepare($query);
  1925. $sth->execute(@queryargs) || $self->dberror($query);
  1926. $self->{all_partsgroup} = ();
  1927. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1928. push @{ $self->{all_partsgroup} }, $ref;
  1929. }
  1930. $sth->finish;
  1931. $dbh->commit;
  1932. }
  1933. sub update_status {
  1934. my ( $self, $myconfig ) = @_;
  1935. # no id return
  1936. return unless $self->{id};
  1937. my $dbh = $self->{dbh};
  1938. my %queued = split / +/, $self->{queued};
  1939. my $spoolfile =
  1940. ( $queued{ $self->{formname} } )
  1941. ? "'$queued{$self->{formname}}'"
  1942. : 'NULL';
  1943. my $query = qq|DELETE FROM status
  1944. WHERE formname = ?
  1945. AND trans_id = ?|;
  1946. $sth = $dbh->prepare($query);
  1947. $sth->execute( $self->{formname}, $self->{id} ) || $self->dberror($query);
  1948. $sth->finish;
  1949. my $printed = ( $self->{printed} =~ /$self->{formname}/ ) ? "1" : "0";
  1950. my $emailed = ( $self->{emailed} =~ /$self->{formname}/ ) ? "1" : "0";
  1951. $query = qq|
  1952. INSERT INTO status
  1953. (trans_id, printed, emailed, spoolfile, formname)
  1954. VALUES (?, ?, ?, ?, ?)|;
  1955. $sth = $dbh->prepare($query);
  1956. $sth->execute( $self->{id}, $printed, $emailed, $spoolfile,
  1957. $self->{formname} );
  1958. $sth->finish;
  1959. $dbh->commit;
  1960. }
  1961. sub save_status {
  1962. my ($self) = @_;
  1963. $dbh = $self->{dbh};
  1964. my $formnames = $self->{printed};
  1965. my $emailforms = $self->{emailed};
  1966. my $query = qq|DELETE FROM status
  1967. WHERE trans_id = ?|;
  1968. my $sth = $dbh->prepare($query);
  1969. $sth->execute( $self->{id} );
  1970. $sth->finish;
  1971. my %queued;
  1972. my $formname;
  1973. if ( $self->{queued} ) {
  1974. %queued = split / +/, $self->{queued};
  1975. foreach $formname ( keys %queued ) {
  1976. $printed = ( $self->{printed} =~ /$formname/ ) ? "1" : "0";
  1977. $emailed = ( $self->{emailed} =~ /$formname/ ) ? "1" : "0";
  1978. if ( $queued{$formname} ) {
  1979. $query = qq|
  1980. INSERT INTO status
  1981. (trans_id, printed, emailed,
  1982. spoolfile, formname)
  1983. VALUES (?, ?, ?, ?, ?)|;
  1984. $sth = $dbh->prepare($query);
  1985. $sth->execute( $self->{id}, $pinted, $emailed,
  1986. $queued{$formname}, $formname )
  1987. || $self->dberror($query);
  1988. $sth->finish;
  1989. }
  1990. $formnames =~ s/$formname//;
  1991. $emailforms =~ s/$formname//;
  1992. }
  1993. }
  1994. # save printed, emailed info
  1995. $formnames =~ s/^ +//g;
  1996. $emailforms =~ s/^ +//g;
  1997. my %status = ();
  1998. for ( split / +/, $formnames ) { $status{$_}{printed} = 1 }
  1999. for ( split / +/, $emailforms ) { $status{$_}{emailed} = 1 }
  2000. foreach my $formname ( keys %status ) {
  2001. $printed = ( $formnames =~ /$self->{formname}/ ) ? "1" : "0";
  2002. $emailed = ( $emailforms =~ /$self->{formname}/ ) ? "1" : "0";
  2003. $query = qq|
  2004. INSERT INTO status (trans_id, printed, emailed,
  2005. formname)
  2006. VALUES (?, ?, ?, ?)|;
  2007. $sth = $dbh->prepare($query);
  2008. $sth->execute( $self->{id}, $printed, $emailed, $formname );
  2009. $sth->finish;
  2010. }
  2011. $dbh->commit;
  2012. }
  2013. sub get_recurring {
  2014. my ($self) = @_;
  2015. $dbh = $self->{dbh};
  2016. my $query = qq/
  2017. SELECT s.*, se.formname || ':' || se.format AS emaila,
  2018. se.message, sp.formname || ':' ||
  2019. sp.format || ':' || sp.printer AS printa
  2020. FROM recurring s
  2021. LEFT JOIN recurringemail se ON (s.id = se.id)
  2022. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  2023. WHERE s.id = ?/;
  2024. my $sth = $dbh->prepare($query);
  2025. $sth->execute( $self->{id} ) || $self->dberror($query);
  2026. for (qw(email print)) { $self->{"recurring$_"} = "" }
  2027. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  2028. for ( keys %$ref ) { $self->{"recurring$_"} = $ref->{$_} }
  2029. $self->{recurringemail} .= "$ref->{emaila}:";
  2030. $self->{recurringprint} .= "$ref->{printa}:";
  2031. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  2032. }
  2033. $sth->finish;
  2034. chop $self->{recurringemail};
  2035. chop $self->{recurringprint};
  2036. if ( $self->{recurringstartdate} ) {
  2037. $self->{recurringreference} =
  2038. $self->escape( $self->{recurringreference}, 1 );
  2039. $self->{recurringmessage} =
  2040. $self->escape( $self->{recurringmessage}, 1 );
  2041. for (
  2042. qw(reference startdate repeat unit howmany
  2043. payment print email message)
  2044. )
  2045. {
  2046. $self->{recurring} .= qq|$self->{"recurring$_"},|;
  2047. }
  2048. chop $self->{recurring};
  2049. }
  2050. $dbh->commit;
  2051. }
  2052. sub save_recurring {
  2053. my ( $self, $dbh2, $myconfig ) = @_;
  2054. my $dbh = $self->{dbh};
  2055. my $query;
  2056. $query = qq|DELETE FROM recurring
  2057. WHERE id = ?|;
  2058. $sth = $dbh->prepare($query) || $self->dberror($query);
  2059. $sth->execute( $self->{id} ) || $self->dberror($query);
  2060. $query = qq|DELETE FROM recurringemail
  2061. WHERE id = ?|;
  2062. $sth = $dbh->prepare($query) || $self->dberror($query);
  2063. $sth->execute( $self->{id} ) || $self->dberror($query);
  2064. $query = qq|DELETE FROM recurringprint
  2065. WHERE id = ?|;
  2066. $sth = $dbh->prepare($query) || $self->dberror($query);
  2067. $sth->execute( $self->{id} ) || $self->dberror($query);
  2068. if ( $self->{recurring} ) {
  2069. my %s = ();
  2070. (
  2071. $s{reference}, $s{startdate}, $s{repeat},
  2072. $s{unit}, $s{howmany}, $s{payment},
  2073. $s{print}, $s{email}, $s{message}
  2074. ) = split /,/, $self->{recurring};
  2075. if ($s{howmany} == 0){
  2076. $self->error("Cannot set to recur 0 times");
  2077. }
  2078. for (qw(reference message)) { $s{$_} = $self->unescape( $s{$_} ) }
  2079. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  2080. # calculate enddate
  2081. my $advance = $s{repeat} * ( $s{howmany} - 1 );
  2082. my %interval;
  2083. $interval{'Pg'} =
  2084. "(date '$s{startdate}' + interval '$advance $s{unit}')";
  2085. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  2086. my ($enddate) = $dbh->selectrow_array($query);
  2087. # calculate nextdate
  2088. $query = qq|
  2089. SELECT current_date - ?::date AS a,
  2090. ?::date - current_date AS b|;
  2091. $sth = $dbh->prepare($query) || $self->dberror($query);
  2092. $sth->execute( $s{startdate}, $enddate );
  2093. my ( $a, $b ) = $sth->fetchrow_array;
  2094. if ( $a + $b ) {
  2095. $advance =
  2096. int( ( $a / ( $a + $b ) ) * ( $s{howmany} - 1 ) + 1 ) *
  2097. $s{repeat};
  2098. }
  2099. else {
  2100. $advance = 0;
  2101. }
  2102. my $nextdate = $enddate;
  2103. if ( $advance > 0 ) {
  2104. if ( $advance < ( $s{repeat} * $s{howmany} ) ) {
  2105. $query = qq|SELECT (date '$s{startdate}' + interval '$advance $s{unit}')|;
  2106. ($nextdate) = $dbh->selectrow_array($query);
  2107. }
  2108. }
  2109. else {
  2110. $nextdate = $s{startdate};
  2111. }
  2112. if ( $self->{recurringnextdate} ) {
  2113. $nextdate = $self->{recurringnextdate};
  2114. $query = qq|SELECT '$enddate' - date '$nextdate'|;
  2115. if ( $dbh->selectrow_array($query) < 0 ) {
  2116. undef $nextdate;
  2117. }
  2118. }
  2119. $self->{recurringpayment} *= 1;
  2120. $query = qq|
  2121. INSERT INTO recurring
  2122. (id, reference, startdate, enddate, nextdate,
  2123. repeat, unit, howmany, payment)
  2124. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  2125. $sth = $dbh->prepare($query);
  2126. $sth->execute(
  2127. $self->{id}, $s{reference}, $s{startdate},
  2128. $enddate, $nextdate, $s{repeat},
  2129. $s{unit}, $s{howmany}, $s{payment}
  2130. );
  2131. my @p;
  2132. my $p;
  2133. my $i;
  2134. my $sth;
  2135. if ( $s{email} ) {
  2136. # formname:format
  2137. @p = split /:/, $s{email};
  2138. $query =
  2139. qq|INSERT INTO recurringemail (id, formname, format, message)
  2140. VALUES (?, ?, ?, ?)|;
  2141. $sth = $dbh->prepare($query) || $self->dberror($query);
  2142. for ( $i = 0 ; $i <= $#p ; $i += 2 ) {
  2143. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $s{message} );
  2144. }
  2145. $sth->finish;
  2146. }
  2147. if ( $s{print} ) {
  2148. # formname:format:printer
  2149. @p = split /:/, $s{print};
  2150. $query =
  2151. qq|INSERT INTO recurringprint (id, formname, format, printer)
  2152. VALUES (?, ?, ?, ?)|;
  2153. $sth = $dbh->prepare($query) || $self->dberror($query);
  2154. for ( $i = 0 ; $i <= $#p ; $i += 3 ) {
  2155. $p = ( $p[ $i + 2 ] ) ? $p[ $i + 2 ] : "";
  2156. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $p );
  2157. }
  2158. $sth->finish;
  2159. }
  2160. }
  2161. $dbh->commit;
  2162. }
  2163. sub save_intnotes {
  2164. my ( $self, $myconfig, $vc ) = @_;
  2165. # no id return
  2166. return unless $self->{id};
  2167. my $dbh = $self->{dbh};
  2168. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  2169. $sth = $dbh->prepare($query);
  2170. $sth->execute( $self->{intnotes}, $self->{id} ) || $self->dberror($query);
  2171. $dbh->commit;
  2172. }
  2173. sub update_defaults {
  2174. my ( $self, $myconfig, $fld ) = @_;
  2175. if ( !$self->{dbh} && $self ) {
  2176. $self->db_init($myconfig);
  2177. }
  2178. my $dbh = $self->{dbh};
  2179. if ( !$self ) {
  2180. $dbh = $_[3];
  2181. }
  2182. my $query = qq|
  2183. SELECT value FROM defaults
  2184. WHERE setting_key = ? FOR UPDATE|;
  2185. $sth = $dbh->prepare($query);
  2186. $sth->execute($fld);
  2187. ($_) = $sth->fetchrow_array();
  2188. $_ = "0" unless $_;
  2189. # check for and replace
  2190. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  2191. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  2192. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  2193. # <?lsmb PHONE ?> for customer and vendors
  2194. my $num = $_;
  2195. ($num) = $num =~ /(\d+)/;
  2196. if ( defined $num ) {
  2197. my $incnum;
  2198. # if we have leading zeros check how long it is
  2199. if ( $num =~ /^0/ ) {
  2200. my $l = length $num;
  2201. $incnum = $num + 1;
  2202. $l -= length $incnum;
  2203. # pad it out with zeros
  2204. my $padzero = "0" x $l;
  2205. $incnum = ( "0" x $l ) . $incnum;
  2206. }
  2207. else {
  2208. $incnum = $num + 1;
  2209. }
  2210. s/$num/$incnum/;
  2211. }
  2212. my $dbvar = $_;
  2213. my $var = $_;
  2214. my $str;
  2215. my $param;
  2216. if (/<\?lsmb /) {
  2217. while (/<\?lsmb /) {
  2218. s/<\?lsmb .*? \?>//;
  2219. last unless $&;
  2220. $param = $&;
  2221. $str = "";
  2222. if ( $param =~ /<\?lsmb date \?>/i ) {
  2223. $str = (
  2224. $self->split_date(
  2225. $myconfig->{dateformat},
  2226. $self->{transdate}
  2227. )
  2228. )[0];
  2229. $var =~ s/$param/$str/;
  2230. }
  2231. if ( $param =~
  2232. /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i
  2233. )
  2234. {
  2235. my $fld = lc $&;
  2236. $fld =~ s/<\?lsmb //;
  2237. if ( $fld =~ /name/ ) {
  2238. if ( $self->{type} ) {
  2239. $fld = $self->{vc};
  2240. }
  2241. }
  2242. my $p = $param;
  2243. $p =~ s/(<|>|%)//g;
  2244. my @p = split / /, $p;
  2245. my @n = split / /, uc $self->{$fld};
  2246. if ( $#p > 0 ) {
  2247. for ( my $i = 1 ; $i <= $#p ; $i++ ) {
  2248. $str .= substr( $n[ $i - 1 ], 0, $p[$i] );
  2249. }
  2250. }
  2251. else {
  2252. ($str) = split /--/, $self->{$fld};
  2253. }
  2254. $var =~ s/$param/$str/;
  2255. $var =~ s/\W//g if $fld eq 'phone';
  2256. }
  2257. if ( $param =~ /<\?lsmb (yy|mm|dd)/i ) {
  2258. my $p = $param;
  2259. $p =~ s/(<|>|%)//g;
  2260. my $spc = $p;
  2261. $spc =~ s/\w//g;
  2262. $spc = substr( $spc, 0, 1 );
  2263. my %d = ( yy => 1, mm => 2, dd => 3 );
  2264. my @p = ();
  2265. my @a = $self->split_date( $myconfig->{dateformat},
  2266. $self->{transdate} );
  2267. for ( sort keys %d ) { push @p, $a[ $d{$_} ] if ( $p =~ /$_/ ) }
  2268. $str = join $spc, @p;
  2269. $var =~ s/$param/$str/;
  2270. }
  2271. if ( $param =~ /<\?lsmb curr/i ) {
  2272. $var =~ s/$param/$self->{currency}/;
  2273. }
  2274. }
  2275. }
  2276. $query = qq|
  2277. UPDATE defaults
  2278. SET value = ?
  2279. WHERE setting_key = ?|;
  2280. $sth = $dbh->prepare($query);
  2281. $sth->execute( $dbvar, $fld ) || $self->dberror($query);
  2282. $dbh->commit;
  2283. $var;
  2284. }
  2285. sub db_prepare_vars {
  2286. my $self = shift;
  2287. for (@_) {
  2288. if ( !$self->{$_} and $self->{$_} ne "0" ) {
  2289. undef $self->{$_};
  2290. }
  2291. }
  2292. }
  2293. sub split_date {
  2294. my ( $self, $dateformat, $date ) = @_;
  2295. my $mm;
  2296. my $dd;
  2297. my $yy;
  2298. my $rv;
  2299. if ( !$date ) {
  2300. my @d = localtime;
  2301. $dd = $d[3];
  2302. $mm = ++$d[4];
  2303. $yy = substr( $d[5], -2 );
  2304. $mm = substr( "0$mm", -2 );
  2305. $dd = substr( "0$dd", -2 );
  2306. }
  2307. if ( $dateformat =~ /^yy/ ) {
  2308. if ($date) {
  2309. if ( $date =~ /\D/ ) {
  2310. ( $yy, $mm, $dd ) = split /\D/, $date;
  2311. $mm *= 1;
  2312. $dd *= 1;
  2313. $mm = substr( "0$mm", -2 );
  2314. $dd = substr( "0$dd", -2 );
  2315. $yy = substr( $yy, -2 );
  2316. $rv = "$yy$mm$dd";
  2317. }
  2318. else {
  2319. $rv = $date;
  2320. }
  2321. }
  2322. else {
  2323. $rv = "$yy$mm$dd";
  2324. }
  2325. }
  2326. elsif ( $dateformat =~ /^mm/ ) {
  2327. if ($date) {
  2328. if ( $date =~ /\D/ ) {
  2329. ( $mm, $dd, $yy ) = split /\D/, $date;
  2330. $mm *= 1;
  2331. $dd *= 1;
  2332. $mm = substr( "0$mm", -2 );
  2333. $dd = substr( "0$dd", -2 );
  2334. $yy = substr( $yy, -2 );
  2335. $rv = "$mm$dd$yy";
  2336. }
  2337. else {
  2338. $rv = $date;
  2339. }
  2340. }
  2341. else {
  2342. $rv = "$mm$dd$yy";
  2343. }
  2344. }
  2345. elsif ( $dateformat =~ /^dd/ ) {
  2346. if ($date) {
  2347. if ( $date =~ /\D/ ) {
  2348. ( $dd, $mm, $yy ) = split /\D/, $date;
  2349. $mm *= 1;
  2350. $dd *= 1;
  2351. $mm = substr( "0$mm", -2 );
  2352. $dd = substr( "0$dd", -2 );
  2353. $yy = substr( $yy, -2 );
  2354. $rv = "$dd$mm$yy";
  2355. }
  2356. else {
  2357. $rv = $date;
  2358. }
  2359. }
  2360. else {
  2361. $rv = "$dd$mm$yy";
  2362. }
  2363. }
  2364. ( $rv, $yy, $mm, $dd );
  2365. }
  2366. sub format_date {
  2367. # takes an iso date in, and converts it to the date for printing
  2368. my ( $self, $date ) = @_;
  2369. my $datestring;
  2370. if ( $date =~ /^\d{4}\D/ ) { # is an ISO date
  2371. $datestring = $self->{db_dateformat};
  2372. my ( $yyyy, $mm, $dd ) = split( /\W/, $date );
  2373. $datestring =~ s/y+/$yyyy/;
  2374. $datestring =~ s/mm/$mm/;
  2375. $datestring =~ s/dd/$dd/;
  2376. }
  2377. else { # return date
  2378. $datestring = $date;
  2379. }
  2380. $datestring;
  2381. }
  2382. sub from_to {
  2383. my ( $self, $yyyy, $mm, $interval ) = @_;
  2384. my @t;
  2385. my $dd = 1;
  2386. my $fromdate = "$yyyy-${mm}-01";
  2387. my $bd = 1;
  2388. if ( defined $interval ) {
  2389. if ( $interval == 12 ) {
  2390. $yyyy++;
  2391. }
  2392. else {
  2393. if ( ( $mm += $interval ) > 12 ) {
  2394. $mm -= 12;
  2395. $yyyy++;
  2396. }
  2397. if ( $interval == 0 ) {
  2398. @t = localtime(time);
  2399. $dd = $t[3];
  2400. $mm = $t[4] + 1;
  2401. $yyyy = $t[5] + 1900;
  2402. $bd = 0;
  2403. }
  2404. }
  2405. }
  2406. else {
  2407. if ( ++$mm > 12 ) {
  2408. $mm -= 12;
  2409. $yyyy++;
  2410. }
  2411. }
  2412. $mm--;
  2413. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yyyy ) - $bd );
  2414. $t[4]++;
  2415. $t[4] = substr( "0$t[4]", -2 );
  2416. $t[3] = substr( "0$t[3]", -2 );
  2417. $t[5] += 1900;
  2418. ( $self->format_date($fromdate), $self->format_date("$t[5]-$t[4]-$t[3]") );
  2419. }
  2420. sub audittrail {
  2421. my ( $self, $dbh, $myconfig, $audittrail ) = @_;
  2422. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2423. my $query;
  2424. my $rv;
  2425. my $disconnect;
  2426. if ( !$dbh ) {
  2427. $dbh = $self->{dbh};
  2428. }
  2429. # if we have an id add audittrail, otherwise get a new timestamp
  2430. my @queryargs;
  2431. if ( $audittrail->{id} ) {
  2432. $query = qq|
  2433. SELECT value FROM defaults
  2434. WHERE setting_key = 'audittrail'|;
  2435. if ( $dbh->selectrow_array($query) ) {
  2436. my ( $null, $employee_id ) = $self->get_employee($dbh);
  2437. if ( $self->{audittrail} && !$myconfig ) {
  2438. chop $self->{audittrail};
  2439. my @a = split /\|/, $self->{audittrail};
  2440. my %newtrail = ();
  2441. my $key;
  2442. my $i;
  2443. my @flds = qw(tablename reference formname action transdate);
  2444. # put into hash and remove dups
  2445. while (@a) {
  2446. $key = "$a[2]$a[3]";
  2447. $i = 0;
  2448. $newtrail{$key} = { map { $_ => $a[ $i++ ] } @flds };
  2449. splice @a, 0, 5;
  2450. }
  2451. $query = qq|
  2452. INSERT INTO audittrail
  2453. (trans_id, tablename, reference,
  2454. formname, action, transdate,
  2455. employee_id)
  2456. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2457. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2458. foreach $key (
  2459. sort {
  2460. $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
  2461. } keys %newtrail
  2462. )
  2463. {
  2464. $i = 2;
  2465. $sth->bind_param( 1, $audittrail->{id} );
  2466. for (@flds) {
  2467. $sth->bind_param( $i++, $newtrail{$key}{$_} );
  2468. }
  2469. $sth->bind_param( $i++, $employee_id );
  2470. $sth->execute() || $self->dberror($query);
  2471. $sth->finish;
  2472. }
  2473. }
  2474. if ( $audittrail->{transdate} ) {
  2475. $query = qq|
  2476. INSERT INTO audittrail (
  2477. trans_id, tablename, reference,
  2478. formname, action, employee_id,
  2479. transdate)
  2480. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2481. @queryargs = (
  2482. $audittrail->{id}, $audittrail->{tablename},
  2483. $audittrail->{reference}, $audittrail->{formname},
  2484. $audittrail->{action}, $employee_id,
  2485. $audittrail->{transdate}
  2486. );
  2487. }
  2488. else {
  2489. $query = qq|
  2490. INSERT INTO audittrail
  2491. (trans_id, tablename, reference,
  2492. formname, action, employee_id)
  2493. VALUES (?, ?, ?, ?, ?, ?)|;
  2494. @queryargs = (
  2495. $audittrail->{id}, $audittrail->{tablename},
  2496. $audittrail->{reference}, $audittrail->{formname},
  2497. $audittrail->{action}, $employee_id,
  2498. );
  2499. }
  2500. $sth = $dbh->prepare($query);
  2501. $sth->execute(@queryargs) || $self->dberror($query);
  2502. }
  2503. }
  2504. else {
  2505. $query = qq|SELECT current_timestamp|;
  2506. my ($timestamp) = $dbh->selectrow_array($query);
  2507. $rv =
  2508. "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2509. }
  2510. $dbh->commit;
  2511. $rv;
  2512. }
  2513. 1;