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