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