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