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