summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: e37de58a8f53e5d00b49844f4944d451a641ac1b (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. if ($ENV{CONTENT_LENGTH} > $LedgerSMB::Sysconfig::max_post_size) {
  49. print "Status: 413\n Request entity too large\n\n";
  50. die "Error: Request entity too large\n";
  51. }
  52. read( STDIN, $_, $ENV{CONTENT_LENGTH} );
  53. if ($argstr) {
  54. $_ = $argstr;
  55. }
  56. elsif ( $ENV{QUERY_STRING} ) {
  57. $_ = $ENV{QUERY_STRING};
  58. }
  59. elsif ( $ARGV[0] ) {
  60. $_ = $ARGV[0];
  61. }
  62. my $self = {};
  63. %$self = split /[&=]/;
  64. for ( keys %$self ) { $self->{$_} = unescape( "", $self->{$_} ) }
  65. if ( substr( $self->{action}, 0, 1 ) !~ /( |\.)/ ) {
  66. $self->{action} = lc $self->{action};
  67. $self->{action} =~ s/( |-|,|\#|\/|\.$)/_/g;
  68. $self->{nextsub} = lc $self->{nextsub};
  69. $self->{nextsub} =~ s/( |-|,|\#|\/|\.$)/_/g;
  70. }
  71. $self->{login} =~ s/[^a-zA-Z0-9._+\@'-]//g;
  72. $self->{menubar} = 1 if $self->{path} =~ /lynx/i;
  73. #menubar will be deprecated, replaced with below
  74. $self->{lynx} = 1 if $self->{path} =~ /lynx/i;
  75. $self->{version} = "1.2.14";
  76. $self->{dbversion} = "1.2.0";
  77. bless $self, $type;
  78. if ( $self->{path} ne 'bin/lynx' ) { $self->{path} = 'bin/mozilla'; }
  79. if ( ( $self->{script} )
  80. and not List::Util::first { $_ eq $self->{script} }
  81. @{LedgerSMB::Sysconfig::scripts} )
  82. {
  83. $self->error( 'Access Denied', __LINE__, __FILE__ );
  84. }
  85. if ( ( $self->{action} =~ /(:|')/ ) || ( $self->{nextsub} =~ /(:|')/ ) ) {
  86. $self->error( "Access Denied", __LINE__, __FILE__ );
  87. }
  88. for ( keys %$self ) { $self->{$_} =~ s/\N{NULL}//g }
  89. if ( ($self->{action} eq 'redirect') || ($self->{nextsub} eq 'redirect') ) {
  90. $self->error( 'Access Denied', __LINE__, __FILE__ );
  91. }
  92. $self;
  93. }
  94. sub debug {
  95. my ( $self, $file ) = @_;
  96. if ($file) {
  97. open( FH, '>', "$file" ) or die $!;
  98. for ( sort keys %$self ) { print FH "$_ = $self->{$_}\n" }
  99. close(FH);
  100. }
  101. else {
  102. print "\n";
  103. for ( sort keys %$self ) { print "$_ = $self->{$_}\n" }
  104. }
  105. }
  106. sub encode_all {
  107. # TODO;
  108. }
  109. sub decode_all {
  110. # TODO
  111. }
  112. sub escape {
  113. my ( $self, $str, $beenthere ) = @_;
  114. # for Apache 2 we escape strings twice
  115. if ( ( $ENV{SERVER_SIGNATURE} =~ /Apache\/2\.(\d+)\.(\d+)/ )
  116. && !$beenthere )
  117. {
  118. $str = $self->escape( $str, 1 ) if $1 == 0 && $2 < 44;
  119. }
  120. utf8::encode($str);
  121. $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
  122. $str;
  123. }
  124. sub unescape {
  125. my ( $self, $str ) = @_;
  126. $str =~ tr/+/ /;
  127. $str =~ s/\\$//;
  128. utf8::encode($str) if utf8::is_utf8($str);
  129. $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
  130. utf8::decode($str);
  131. $str =~ s/\r?\n/\n/g;
  132. $str;
  133. }
  134. sub quote {
  135. my ( $self, $str ) = @_;
  136. if ( $str && !ref($str) ) {
  137. $str =~ s/"/&quot;/g;
  138. }
  139. $str;
  140. }
  141. sub unquote {
  142. my ( $self, $str ) = @_;
  143. if ( $str && !ref($str) ) {
  144. $str =~ s/&quot;/"/g;
  145. }
  146. $str;
  147. }
  148. sub hide_form {
  149. my $self = shift;
  150. if (@_) {
  151. for (@_) {
  152. print qq|<input type="hidden" name="$_" value="|
  153. . $self->quote( $self->{$_} )
  154. . qq|" />\n|;
  155. }
  156. }
  157. else {
  158. delete $self->{header};
  159. for ( sort keys %$self ) {
  160. print qq|<input type="hidden" name="$_" value="|
  161. . $self->quote( $self->{$_} )
  162. . qq|" />\n|;
  163. }
  164. }
  165. }
  166. sub error {
  167. my ( $self, $msg ) = @_;
  168. if ( $ENV{GATEWAY_INTERFACE} ) {
  169. $self->{msg} = $msg;
  170. $self->{format} = "html";
  171. $self->format_string('msg');
  172. delete $self->{pre};
  173. if ( !$self->{header} ) {
  174. $self->header;
  175. }
  176. print
  177. qq|<body><h2 class="error">Error!</h2> <p><b>$self->{msg}</b></body>|;
  178. exit;
  179. }
  180. else {
  181. if ( $ENV{error_function} ) {
  182. &{ $ENV{error_function} }($msg);
  183. }
  184. die "Error: $msg\n";
  185. }
  186. }
  187. sub info {
  188. my ( $self, $msg ) = @_;
  189. if ( $ENV{GATEWAY_INTERFACE} ) {
  190. $msg =~ s/\n/<br>/g;
  191. delete $self->{pre};
  192. if ( !$self->{header} ) {
  193. $self->header;
  194. print qq| <body>|;
  195. $self->{header} = 1;
  196. }
  197. print "<b>$msg</b>";
  198. }
  199. else {
  200. if ( $ENV{info_function} ) {
  201. &{ $ENV{info_function} }($msg);
  202. }
  203. else {
  204. print "$msg\n";
  205. }
  206. }
  207. }
  208. sub numtextrows {
  209. my ( $self, $str, $cols, $maxrows ) = @_;
  210. my $rows = 0;
  211. for ( split /\n/, $str ) {
  212. $rows += int( ( (length) - 2 ) / $cols ) + 1;
  213. }
  214. $maxrows = $rows unless defined $maxrows;
  215. return ( $rows > $maxrows ) ? $maxrows : $rows;
  216. }
  217. sub dberror {
  218. my ( $self, $msg ) = @_;
  219. $self->error( "$msg\n" . $DBI::errstr );
  220. }
  221. sub isblank {
  222. my ( $self, $name, $msg ) = @_;
  223. $self->error($msg) if $self->{$name} =~ /^\s*$/;
  224. }
  225. sub header {
  226. my ( $self, $init, $headeradd ) = @_;
  227. return if $self->{header};
  228. my ( $stylesheet, $favicon, $charset );
  229. if ( $ENV{GATEWAY_INTERFACE} ) {
  230. $self->{charset} ||= "utf-8";
  231. if ( $self->{stylesheet} && ( -f "css/$self->{stylesheet}" ) ) {
  232. $stylesheet =
  233. qq|<link rel="stylesheet" href="css/$self->{stylesheet}" type="text/css" title="LedgerSMB stylesheet" />\n|;
  234. }
  235. $charset =
  236. qq|<meta http-equiv="content-type" content="text/html; charset=$self->{charset}" />\n|;
  237. $self->{titlebar} =
  238. ( $self->{title} )
  239. ? "$self->{title} - $self->{titlebar}"
  240. : $self->{titlebar};
  241. print qq|Content-Type: text/html; charset=utf-8\n\n
  242. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  243. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  244. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  245. <head>
  246. <title>$self->{titlebar}</title>
  247. <meta http-equiv="Pragma" content="no-cache" />
  248. <meta http-equiv="Expires" content="-1" />
  249. <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  250. $stylesheet
  251. $charset
  252. <meta name="robots" content="noindex,nofollow" />
  253. $headeradd
  254. </head>
  255. $self->{pre} \n|;
  256. }
  257. $self->{header} = 1;
  258. }
  259. sub redirect {
  260. my ( $self, $msg ) = @_;
  261. if ( $self->{callback} || !$msg ) {
  262. main::redirect();
  263. }
  264. else {
  265. $self->info($msg);
  266. }
  267. }
  268. sub sort_columns {
  269. my ( $self, @columns ) = @_;
  270. if ( $self->{sort} ) {
  271. $self->{sort} =~ s/^"*(.*?)"*$/$1/;
  272. if (@columns) {
  273. @columns = grep !/^$self->{sort}$/, @columns;
  274. if ($self->{sort} !~ /^\w*$/){
  275. $self->{sort} = $self->{dbh}->quote_identifier($self->{sort});
  276. }
  277. splice @columns, 0, 0, $self->{sort};
  278. }
  279. }
  280. @columns;
  281. }
  282. sub sort_order {
  283. my ( $self, $columns, $ordinal ) = @_;
  284. # setup direction
  285. if ( $self->{direction} ) {
  286. if ( $self->{sort} eq $self->{oldsort} ) {
  287. if ( $self->{direction} eq 'ASC' ) {
  288. $self->{direction} = "DESC";
  289. }
  290. else {
  291. $self->{direction} = "ASC";
  292. }
  293. }
  294. }
  295. else {
  296. $self->{direction} = "ASC";
  297. }
  298. $self->{oldsort} = $self->{sort};
  299. my @a = $self->sort_columns( @{$columns} );
  300. if (%$ordinal) {
  301. $a[0] =
  302. ( $ordinal->{ $a[$_] } )
  303. ? "$ordinal->{$a[0]} $self->{direction}"
  304. : "$a[0] $self->{direction}";
  305. for ( 1 .. $#a ) {
  306. $a[$_] = $ordinal->{ $a[$_] } if $ordinal->{ $a[$_] };
  307. }
  308. }
  309. else {
  310. $a[0] .= " $self->{direction}";
  311. }
  312. $sortorder = join ',', @a;
  313. $sortorder;
  314. }
  315. sub format_amount {
  316. my ( $self, $myconfig, $amount, $places, $dash ) = @_;
  317. my $negative;
  318. if ($amount) {
  319. $amount = $self->parse_amount( $myconfig, $amount );
  320. $negative = ( $amount < 0 );
  321. $amount =~ s/-//;
  322. }
  323. if ( $places =~ /\d+/ ) {
  324. #$places = 4 if $places == 2;
  325. $amount = $self->round_amount( $amount, $places );
  326. }
  327. # is the amount negative
  328. # Parse $myconfig->{numberformat}
  329. my ( $ts, $ds ) = ( $1, $2 );
  330. if ($amount) {
  331. if ( $myconfig->{numberformat} ) {
  332. my ( $whole, $dec ) = split /\./, "$amount";
  333. $amount = join '', reverse split //, $whole;
  334. if ($places) {
  335. $dec .= "0" x $places;
  336. $dec = substr( $dec, 0, $places );
  337. }
  338. if ( $myconfig->{numberformat} eq '1,000.00' ) {
  339. $amount =~ s/\d{3,}?/$&,/g;
  340. $amount =~ s/,$//;
  341. $amount = join '', reverse split //, $amount;
  342. $amount .= "\.$dec" if ( $dec ne "" );
  343. }
  344. if ( $myconfig->{numberformat} eq '1 000.00' ) {
  345. $amount =~ s/\d{3,}?/$& /g;
  346. $amount =~ s/\s$//;
  347. $amount = join '', reverse split //, $amount;
  348. $amount .= "\.$dec" if ( $dec ne "" );
  349. }
  350. if ( $myconfig->{numberformat} eq "1'000.00" ) {
  351. $amount =~ s/\d{3,}?/$&'/g;
  352. $amount =~ s/'$//;
  353. $amount = join '', reverse split //, $amount;
  354. $amount .= "\.$dec" if ( $dec ne "" );
  355. }
  356. if ( $myconfig->{numberformat} eq '1.000,00' ) {
  357. $amount =~ s/\d{3,}?/$&./g;
  358. $amount =~ s/\.$//;
  359. $amount = join '', reverse split //, $amount;
  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 ( $myconfig->{numberformat} eq '1000.00' ) {
  367. $amount = "$whole";
  368. $amount .= ".$dec" if ( $dec ne "" );
  369. }
  370. if ( $dash =~ /-/ ) {
  371. $amount = ($negative) ? "($amount)" : "$amount";
  372. }
  373. elsif ( $dash =~ /DRCR/ ) {
  374. $amount = ($negative) ? "$amount DR" : "$amount CR";
  375. }
  376. else {
  377. $amount = ($negative) ? "-$amount" : "$amount";
  378. }
  379. }
  380. }
  381. else {
  382. if ( $dash eq "0" && $places ) {
  383. if ( $myconfig->{numberformat} =~ /0,00$/ ) {
  384. $amount = "0" . "," . "0" x $places;
  385. }
  386. else {
  387. $amount = "0" . "." . "0" x $places;
  388. }
  389. }
  390. else {
  391. $amount = ( $dash ne "" ) ? "$dash" : "";
  392. }
  393. }
  394. $amount;
  395. }
  396. sub parse_amount {
  397. my ( $self, $myconfig, $amount ) = @_;
  398. if ( ( $amount eq '' ) or ( ! defined $amount ) ) {
  399. $amount = 0;
  400. }
  401. if ( UNIVERSAL::isa( $amount, 'Math::BigFloat' ) )
  402. { # Amount may not be an object
  403. return $amount;
  404. }
  405. my $numberformat = $myconfig->{numberformat};
  406. if ( ( $numberformat eq '1.000,00' )
  407. || ( $numberformat eq '1000,00' ) )
  408. {
  409. $amount =~ s/\.//g;
  410. $amount =~ s/,/./;
  411. }
  412. if ( $numberformat eq '1 000.00' ) {
  413. $amount =~ s/\s//g;
  414. }
  415. if ( $numberformat eq "1'000.00" ) {
  416. $amount =~ s/'//g;
  417. }
  418. $amount =~ s/,//g;
  419. if ( $amount =~ s/\((\d*\.?\d*)\)/$1/ ) {
  420. $amount = $1 * -1;
  421. }
  422. if ( $amount =~ s/(\d*\.?\d*)\s?DR/$1/ ) {
  423. $amount = $1 * -1;
  424. }
  425. $amount =~ s/\s?CR//;
  426. $amount =~ /(\d*)\.(\d*)/;
  427. my $decimalplaces = length $1 + length $2;
  428. $amount = new Math::BigFloat($amount);
  429. return ($amount);
  430. }
  431. sub round_amount {
  432. my ( $self, $amount, $places ) = @_;
  433. # These rounding rules follow from the previous implementation.
  434. # They should be changed to allow different rules for different accounts.
  435. Math::BigFloat->round_mode('+inf') if $amount >= 0;
  436. Math::BigFloat->round_mode('-inf') if $amount < 0;
  437. $amount = Math::BigFloat->new($amount)->ffround( -$places ) if $places >= 0;
  438. $amount = Math::BigFloat->new($amount)->ffround( -( $places - 1 ) )
  439. if $places < 0;
  440. $amount->precision(undef);
  441. return $amount;
  442. }
  443. sub db_parse_numeric {
  444. my $self = shift;
  445. my %args = @_;
  446. my ($sth, $arrayref, $hashref) = ($args{sth}, $args{arrayref},
  447. $args{hashref});
  448. my @types = @{$sth->{'TYPE'}};
  449. my @names = @{$sth->{'NAME_lc'}};
  450. for (0 .. $#names) {
  451. # numeric real/float4
  452. if ($types[$_] == 3 or $types[$_] == 2){
  453. $arrayref->[$_] = Math::BigFloat->new($arrayref->[$_])
  454. if defined $arrayref;
  455. $hashref->{$names[$_]} = Math::BigFloat->new($hashref->{$names[$_]})
  456. if defined $hashref;
  457. }
  458. }
  459. return ($hashref || $arrayref);
  460. }
  461. sub callproc {
  462. my $procname = shift @_;
  463. my $argstr = "";
  464. my @results;
  465. for ( 1 .. $#_ ) {
  466. $argstr .= "?, ";
  467. }
  468. $argstr =~ s/\, $//;
  469. $query = "SELECT $procname";
  470. $query =~ s/\(\)/$argstr/;
  471. my $sth = $self->{dbh}->prepare($query);
  472. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  473. push @results, $ref;
  474. }
  475. @results;
  476. }
  477. sub get_my_emp_num {
  478. my ( $self, $myconfig, $form ) = @_;
  479. %myconfig = %{$myconfig};
  480. my $dbh = $form->{dbh};
  481. # we got a connection, check the version
  482. my $query = qq|
  483. SELECT employeenumber FROM employee
  484. WHERE login = ?|;
  485. my $sth = $dbh->prepare($query);
  486. $sth->execute( $form->{login} ) || $form->dberror($query);
  487. my ($id) = $sth->fetchrow_array;
  488. $sth->finish;
  489. $form->{'emp_num'} = $id;
  490. }
  491. sub parse_template {
  492. my ( $self, $myconfig ) = @_;
  493. $self->{cwd} = Cwd::getcwd();
  494. for (qw(IN OUT)) {
  495. if ( $self->{$_} =~ m#[:/\\]# and
  496. ($self->{$_} != $LedgerSMB::Sysconfig::sendmail and ($_ eq 'OUT')))
  497. {
  498. $self->error("Access denied");
  499. }
  500. }
  501. if ( $self->{language_code} =~ m#[:/\\.*]# ) {
  502. $self->error("Access Denied");
  503. }
  504. my ( $chars_per_line, $lines_on_first_page, $lines_on_second_page ) =
  505. ( 0, 0, 0 );
  506. my ( $current_page, $current_line ) = ( 1, 1 );
  507. my $pagebreak = "";
  508. my $sum = 0;
  509. my $subdir = "";
  510. my $err = "";
  511. my %include = ();
  512. my $ok;
  513. if ( $self->{language_code} ) {
  514. if ( $self->{language_code} =~ /(\.\.|\/|\*)/ ) {
  515. $self->error("Invalid Language Code");
  516. }
  517. if ( -f "$self->{templates}/$self->{language_code}/$self->{IN}" ) {
  518. open( IN, '<',
  519. "$self->{templates}/$self->{language_code}/$self->{IN}" )
  520. or $self->error("$self->{IN} : $!");
  521. }
  522. else {
  523. open( IN, '<', "$self->{templates}/$self->{IN}" )
  524. or $self->error("$self->{IN} : $!");
  525. }
  526. }
  527. else {
  528. open( IN, '<', "$self->{templates}/$self->{IN}" )
  529. or $self->error("$self->{IN} : $!");
  530. }
  531. @_ = <IN>;
  532. close(IN);
  533. $self->{copies} = 1 if ( ( $self->{copies} *= 1 ) <= 0 );
  534. # OUT is used for the media, screen, printer, email
  535. # for postscript we store a copy in a temporary file
  536. my $fileid = time;
  537. my $tmpfile = $self->{IN};
  538. $tmpfile =~ s/\./_$self->{fileid}./ if $self->{fileid};
  539. $self->{tmpfile} = "${LedgerSMB::Sysconfig::tempdir}/${fileid}_${tmpfile}";
  540. my $temphash;
  541. if ( $self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email' ) {
  542. $temphash{out} = $self->{OUT};
  543. $self->{OUT} = "$self->{tmpfile}";
  544. File::Copy::copy(
  545. "$self->{templates}/logo.png",
  546. "${LedgerSMB::Sysconfig::tempdir}/"
  547. );
  548. File::Copy::copy(
  549. "$self->{templates}/logo.eps",
  550. "${LedgerSMB::Sysconfig::tempdir}/"
  551. );
  552. $temphash{printmode} = $self->{printmode};
  553. $self->{printmode} = '>:utf8';
  554. }
  555. if ( $self->{OUT} ) {
  556. open( OUT, $self->{printmode}, "$self->{OUT}" )
  557. or $self->error("$self->{OUT} : $!");
  558. chmod( 0600, "$self->{OUT}" );
  559. }
  560. else {
  561. open( OUT, ">-" ) or $self->error("STDOUT : $!");
  562. $self->header;
  563. }
  564. # first we generate a tmpfile
  565. # read file and replace <?lsmb variable ?>
  566. while ( $_ = shift ) {
  567. $par = "";
  568. $var = $_;
  569. # detect pagebreak block and its parameters
  570. if (/<\?lsmb pagebreak ([0-9]+) ([0-9]+) ([0-9]+) \?>/) {
  571. $chars_per_line = $1;
  572. $lines_on_first_page = $2;
  573. $lines_on_second_page = $3;
  574. while ( $_ = shift ) {
  575. last if (/<\?lsmb end pagebreak \?>/);
  576. $pagebreak .= $_;
  577. }
  578. }
  579. if (/<\?lsmb foreach /) {
  580. # this one we need for the count
  581. chomp $var;
  582. $var =~ s/.*?<\?lsmb foreach (.+?) \?>/$1/;
  583. while ( $_ = shift ) {
  584. last if (/<\?lsmb end $var \?>/);
  585. # store line in $par
  586. $par .= $_;
  587. }
  588. # display contents of $self->{number}[] array
  589. for $i ( 0 .. $#{ $self->{$var} } ) {
  590. if ( $var =~ /^(part|service)$/ ) {
  591. next if $self->{$var}[$i] eq 'NULL';
  592. }
  593. # Try to detect whether a manual page break is necessary
  594. # but only if there was a <?lsmb pagebreak ... ?> block before
  595. if ( $var eq 'number' || $var eq 'part' || $var eq 'service' ) {
  596. if ( $chars_per_line && defined $self->{$var} ) {
  597. my $line;
  598. my $lines = 0;
  599. my @d = qw(description);
  600. push @d, "itemnotes" if $self->{countitemnotes};
  601. foreach my $item (@d) {
  602. if ( $self->{$item}[$i] ) {
  603. foreach $line ( split /\r?\n/,
  604. $self->{$item}[$i] )
  605. {
  606. $lines++;
  607. $lines +=
  608. int( length($line) / $chars_per_line );
  609. }
  610. }
  611. }
  612. my $lpp;
  613. if ( $current_page == 1 ) {
  614. $lpp = $lines_on_first_page;
  615. }
  616. else {
  617. $lpp = $lines_on_second_page;
  618. }
  619. # Yes we need a manual page break
  620. if ( ( $current_line + $lines ) > $lpp ) {
  621. my $pb = $pagebreak;
  622. # replace the special variables <?lsmb sumcarriedforward ?>
  623. # and <?lsmb lastpage ?>
  624. my $psum =
  625. $self->format_amount( $myconfig, $sum, 2 );
  626. $pb =~ s/<\?lsmb sumcarriedforward \?>/$psum/g;
  627. $pb =~ s/<\?lsmb lastpage \?>/$current_page/g;
  628. # only "normal" variables are supported here
  629. # (no <?lsmb if, no <?lsmb foreach, no <?lsmb include)
  630. $pb =~ s/<\?lsmb (.+?) \?>/$self->{$1}/g;
  631. # page break block is ready to rock
  632. print( OUT $pb );
  633. $current_page++;
  634. $current_line = 1;
  635. $lines = 0;
  636. }
  637. $current_line += $lines;
  638. }
  639. $sum +=
  640. $self->parse_amount( $myconfig, $self->{linetotal}[$i] );
  641. }
  642. # don't parse par, we need it for each line
  643. print OUT $self->format_line( $par, $i );
  644. }
  645. next;
  646. }
  647. # if not comes before if!
  648. if (/<\?lsmb if not /) {
  649. # check if it is not set and display
  650. chop;
  651. s/.*?<\?lsmb if not (.+?) \?>/$1/;
  652. if ( !$self->{$_} ) {
  653. while ( $_ = shift ) {
  654. last if (/<\?lsmb end /);
  655. # store line in $par
  656. $par .= $_;
  657. }
  658. $_ = $par;
  659. }
  660. else {
  661. while ( $_ = shift ) {
  662. last if (/<\?lsmb end /);
  663. }
  664. next;
  665. }
  666. }
  667. if (/<\?lsmb if /) {
  668. # check if it is set and display
  669. chop;
  670. s/.*?<\?lsmb if (.+?) \?>/$1/;
  671. # commenting this out for security reasons. If needed,
  672. # please uncomment. Functionality below will be in 1.3
  673. # Chris Travers
  674. #if (/\s/) {
  675. # @args = split;
  676. # if ($args[1] !~ /^(==|eq|>|gt|>|lt|>=|ge|le|<=|ne|!=)$/){
  677. # $self->error("Unknown/forbidden operator");
  678. # }
  679. # $ok = eval "$self->{$args[0]} $args[1] $args[2]";
  680. #} else {
  681. $ok = $self->{$_};
  682. #}
  683. if ($ok) {
  684. while ( $_ = shift ) {
  685. last if (/<\?lsmb end /);
  686. # store line in $par
  687. $par .= $_;
  688. }
  689. $_ = $par;
  690. }
  691. else {
  692. while ( $_ = shift ) {
  693. last if (/<\?lsmb end /);
  694. }
  695. next;
  696. }
  697. }
  698. # check for <?lsmb include filename ?>
  699. if (/<\?lsmb include /) {
  700. # get the filename
  701. chomp $var;
  702. $var =~ s/.*?<\?lsmb include (.+?) \?>/$1/;
  703. # remove / .. for security reasons
  704. $var =~ s/(\/|\.\.)//g;
  705. # assume loop after 10 includes of the same file
  706. next if ( $include{$var} > 10 );
  707. unless (
  708. open( INC, '<', "$self->{templates}/$self->{language_code}/$var"
  709. )
  710. )
  711. {
  712. $err = $!;
  713. $self->cleanup;
  714. $self->error(
  715. "$self->{templates}/$self->{language_code}/$var : $err");
  716. }
  717. unshift( @_, <INC> );
  718. close(INC);
  719. $include{$var}++;
  720. next;
  721. }
  722. print OUT $self->format_line($_);
  723. }
  724. close(OUT);
  725. delete $self->{countitemnotes};
  726. # Convert the tex file to postscript
  727. if ( $self->{format} =~ /(postscript|pdf)/ ) {
  728. $self->{tmpdir} = "${LedgerSMB::Sysconfig::tempdir}";
  729. unless ( chdir( $self->{tmpdir} ) ) {
  730. $err = $!;
  731. $self->cleanup;
  732. $self->error("chdir : $self->{tmpdir} : $err");
  733. }
  734. $self->{tmpfile} =~ s/$self->{tmpdir}\///g;
  735. $self->{errfile} = $self->{tmpfile};
  736. $self->{errfile} =~ s/tex$/err/;
  737. my $r = 1;
  738. if ( $self->{format} eq 'postscript' ) {
  739. system(
  740. "latex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}"
  741. );
  742. while ( $self->rerun_latex ) {
  743. system(
  744. "latex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}"
  745. );
  746. last if ++$r > 4;
  747. }
  748. $self->{tmpfile} =~ s/tex$/dvi/;
  749. $self->error( $self->cleanup ) if !( -f $self->{tmpfile} );
  750. system("dvips $self->{tmpfile} -o -q");
  751. $self->error( $self->cleanup . "dvips : $!" ) if ($?);
  752. $self->{tmpfile} =~ s/dvi$/ps/;
  753. }
  754. if ( $self->{format} eq 'pdf' ) {
  755. system(
  756. "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}"
  757. );
  758. while ( $self->rerun_latex ) {
  759. system(
  760. "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}"
  761. );
  762. last if ++$r > 4;
  763. }
  764. $self->{tmpfile} =~ s/tex$/pdf/;
  765. $self->error( $self->cleanup ) if !( -f $self->{tmpfile} );
  766. }
  767. }
  768. if ( $self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email' ) {
  769. if ( $self->{media} eq 'email' ) {
  770. my $mail = new Mailer;
  771. for (qw(cc bcc subject message version format charset)) {
  772. $mail->{$_} = $self->{$_};
  773. }
  774. $mail->{to} = qq|$self->{email}|;
  775. $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
  776. $mail->{notify} = $self->{notify};
  777. $mail->{fileid} = "$fileid.";
  778. # if we send html or plain text inline
  779. if ( ( $self->{format} =~ /(html|txt)/ )
  780. && ( $self->{sendmode} eq 'inline' ) )
  781. {
  782. my $br = "";
  783. $br = "<br>" if $self->{format} eq 'html';
  784. $mail->{contenttype} = "text/$self->{format}";
  785. $mail->{message} =~ s/\r?\n/$br\n/g;
  786. $myconfig->{signature} =~ s/\\n/$br\n/g;
  787. $mail->{message} .= "$br\n-- $br\n$myconfig->{signature}\n$br"
  788. if $myconfig->{signature};
  789. unless ( open( IN, '<', $self->{tmpfile} ) ) {
  790. $err = $!;
  791. $self->cleanup;
  792. $self->error("$self->{tmpfile} : $err");
  793. }
  794. while (<IN>) {
  795. $mail->{message} .= $_;
  796. }
  797. close(IN);
  798. }
  799. else {
  800. @{ $mail->{attachments} } = ( $self->{tmpfile} );
  801. $myconfig->{signature} =~ s/\\n/\n/g;
  802. $mail->{message} .= "\n-- \n$myconfig->{signature}"
  803. if $myconfig->{signature};
  804. }
  805. if ( $err = $mail->send ) {
  806. $self->cleanup;
  807. $self->error($err);
  808. }
  809. }
  810. else {
  811. $self->{OUT} = $temphash{out};
  812. $self->{printmode} = $temphash{printmode} if $temphash{printmode};
  813. unless ( open( IN, '<', $self->{tmpfile} ) ) {
  814. $err = $!;
  815. $self->cleanup;
  816. $self->error("$self->{tmpfile} : $err");
  817. }
  818. binmode(IN);
  819. $self->{copies} = 1 if $self->{media} =~ /(screen|email|queue)/;
  820. chdir("$self->{cwd}");
  821. for my $i ( 1 .. $self->{copies} ) {
  822. if ( $self->{OUT} ) {
  823. unless ( open( OUT, $self->{printmode}, $self->{OUT} ) ) {
  824. $err = $!;
  825. $self->cleanup;
  826. $self->error("$self->{OUT} : $err");
  827. }
  828. chmod( 0600, "$self->{OUT}" );
  829. }
  830. else {
  831. # launch application
  832. print qq|Content-Type: application/$self->{format}\n|
  833. . qq|Content-Disposition: attachment; filename="$self->{tmpfile}"\n\n|;
  834. unless ( open( OUT, ">-" ) ) {
  835. $err = $!;
  836. $self->cleanup;
  837. $self->error("STDOUT : $err");
  838. }
  839. }
  840. binmode(OUT);
  841. while (<IN>) {
  842. print OUT $_;
  843. }
  844. close(OUT);
  845. seek IN, 0, 0;
  846. }
  847. close(IN);
  848. }
  849. $self->cleanup;
  850. }
  851. }
  852. sub format_line {
  853. my $self = shift;
  854. $_ = shift;
  855. my $i = shift;
  856. my $str;
  857. my $newstr;
  858. my $pos;
  859. my $l;
  860. my $lf;
  861. my $line;
  862. my $var = "";
  863. my %a;
  864. my $offset;
  865. my $pad;
  866. my $item;
  867. TAG: while (/<\?lsmb (.+?) \?>/) {
  868. %a = ();
  869. foreach $item ( split / /, $1 ) {
  870. my ( $key, $value ) = split /=/, $item;
  871. if ( $value ne "" ) {
  872. $a{$key} = $value;
  873. }
  874. else {
  875. $var = $item;
  876. }
  877. }
  878. $str = ( defined $i ) ? $self->{$var}[$i] : $self->{$var};
  879. $newstr = $str;
  880. $self->{countitemnotes} = 1 if $var eq 'itemnotes';
  881. $var = $1;
  882. if ( $var =~ /^if\s+not\s+/ ) {
  883. if ($str) {
  884. $var =~ s/if\s+not\s+//;
  885. s/<\?lsmb if\s+not\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  886. } else {
  887. s/<\?lsmb $var \?>//;
  888. }
  889. next TAG;
  890. }
  891. if ( $var =~ /^if\s+/ ) {
  892. if ($str) {
  893. s/<\?lsmb $var \?>//;
  894. }
  895. else {
  896. $var =~ s/if\s+//;
  897. s/<\?lsmb if\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  898. }
  899. next TAG;
  900. }
  901. if ( $var =~ /^end\s+/ ) {
  902. s/<\?lsmb $var \?>//;
  903. next TAG;
  904. }
  905. if ( $a{align} || $a{width} || $a{offset} ) {
  906. $newstr = "";
  907. $offset = 0;
  908. $lf = "";
  909. foreach $str ( split /\n/, $str ) {
  910. $line = $str;
  911. $l = length $str;
  912. do {
  913. if ( ( $pos = length $str ) > $a{width} ) {
  914. if ( ( $pos = rindex $str, " ", $a{width} ) > 0 ) {
  915. $line = substr( $str, 0, $pos );
  916. }
  917. $pos = length $str if $pos == -1;
  918. }
  919. $l = length $line;
  920. # pad left, right or center
  921. $l = ( $a{width} - $l );
  922. $pad = " " x $l;
  923. if ( $a{align} =~ /right/i ) {
  924. $line = " " x $offset . $pad . $line;
  925. }
  926. if ( $a{align} =~ /left/i ) {
  927. $line = " " x $offset . $line . $pad;
  928. }
  929. if ( $a{align} =~ /center/i ) {
  930. $pad = " " x ( $l / 2 );
  931. $line = " " x $offset . $pad . $line;
  932. $pad = " " x ( $l / 2 );
  933. $line .= $pad;
  934. }
  935. $newstr .= "$lf$line";
  936. $str = substr( $str, $pos + 1 );
  937. $line = $str;
  938. $lf = "\n";
  939. $offset = $a{offset};
  940. } while ($str);
  941. }
  942. }
  943. s/<\?lsmb (.+?) \?>/$newstr/;
  944. }
  945. $_;
  946. }
  947. sub cleanup {
  948. return;
  949. my $self = shift;
  950. chdir("$self->{tmpdir}");
  951. my @err = ();
  952. if ( -f "$self->{errfile}" ) {
  953. open( FH, '<', "$self->{errfile}" );
  954. @err = <FH>;
  955. close(FH);
  956. }
  957. if ( $self->{tmpfile} ) {
  958. # strip extension
  959. $self->{tmpfile} =~ s/\.\w+$//g;
  960. my $tmpfile = $self->{tmpfile};
  961. unlink(<$tmpfile.*>);
  962. }
  963. chdir("$self->{cwd}");
  964. "@err";
  965. }
  966. sub rerun_latex {
  967. my $self = shift;
  968. my $a = 0;
  969. if ( -f "$self->{errfile}" ) {
  970. open( FH, '<', "$self->{errfile}" );
  971. $a = grep /(longtable Warning:|Warning:.*?LastPage)/, <FH>;
  972. close(FH);
  973. }
  974. $a;
  975. }
  976. sub format_string {
  977. my ( $self, @fields ) = @_;
  978. my $format = $self->{format};
  979. if ( $self->{format} =~ /(postscript|pdf)/ ) {
  980. $format = 'tex';
  981. }
  982. my %replace = (
  983. 'order' => {
  984. html => [ '<', '>', '\n', '\r', '&' ],
  985. txt => [ '\n', '\r' ],
  986. tex => [
  987. # quotemeta('\\'), '&', '\n', '\r',
  988. '&', '\n', '\r',
  989. quotemeta('$'), '%', '(?<!\\\\)_', '#',
  990. quotemeta('^'), '{', '}', '<',
  991. '>', '£',
  992. ]
  993. },
  994. html => {
  995. '<' => '&lt;',
  996. '>' => '&gt;',
  997. '&' => '&amp;',
  998. '\n' => '<br />',
  999. '\r' => '<br />'
  1000. },
  1001. txt => { '\n' => "\n", '\r' => "\r" },
  1002. tex => {
  1003. '&' => '\&',
  1004. quotemeta('$') => '\$',
  1005. '%' => '\%',
  1006. '#' => '\#',
  1007. quotemeta('^') => '\^\\',
  1008. '{' => '\{',
  1009. '}' => '\}',
  1010. '(?<!\\\\)_' => '\_', # SC: Double escaping is annoying
  1011. '<' => '$<$',
  1012. '>' => '$>$',
  1013. '\n' => '\newline ',
  1014. '\r' => '\newline ',
  1015. '£' => '\pounds ',
  1016. # quotemeta('\\') => '/'
  1017. }
  1018. );
  1019. my $key;
  1020. if ($format eq 'tex') {
  1021. FIELD: for (@fields) {
  1022. $self->{$_} =~ s{\\(?!pounds\b|newline\b|\$|%|#|&|\{|\}|\^\\|_)}{/}g;
  1023. }
  1024. }
  1025. CHAR: foreach $key ( @{ $replace{order}{$format} } ) {
  1026. FIELD: for (@fields) {
  1027. $self->{$_} =~ s/$key/$replace{$format}{$key}/g;
  1028. }
  1029. }
  1030. }
  1031. sub datetonum {
  1032. my ( $self, $myconfig, $date, $picture ) = @_;
  1033. if ( $date && $date =~ /\D/ ) {
  1034. if ( $date =~ /^\d{4}-\d\d-\d\d$/ ) {
  1035. # SC: Handle standard form of YYYY-MM-DD
  1036. ( $yy, $mm, $dd ) = split /\D/, $date;
  1037. } elsif ( $myconfig->{dateformat} =~ /^yy/ ) {
  1038. ( $yy, $mm, $dd ) = split /\D/, $date;
  1039. } elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  1040. ( $mm, $dd, $yy ) = split /\D/, $date;
  1041. } elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  1042. ( $dd, $mm, $yy ) = split /\D/, $date;
  1043. }
  1044. $dd *= 1;
  1045. $mm *= 1;
  1046. $yy += 2000 if length $yy == 2;
  1047. $dd = substr( "0$dd", -2 );
  1048. $mm = substr( "0$mm", -2 );
  1049. $date = "$yy$mm$dd";
  1050. }
  1051. $date;
  1052. }
  1053. sub add_date {
  1054. my ( $self, $myconfig, $date, $repeat, $unit ) = @_;
  1055. my $diff = 0;
  1056. my $spc = $myconfig->{dateformat};
  1057. my $yy;
  1058. my $mm;
  1059. my $dd;
  1060. $spc =~ s/\w//g;
  1061. $spc = substr( $spc, 0, 1 );
  1062. if ($date) {
  1063. if ( $date =~ /\D/ ) {
  1064. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1065. ( $yy, $mm, $dd ) = split /\D/, $date;
  1066. }
  1067. if ( $myconfig->{dateformat} =~ /^mm/ ) {
  1068. ( $mm, $dd, $yy ) = split /\D/, $date;
  1069. }
  1070. if ( $myconfig->{dateformat} =~ /^dd/ ) {
  1071. ( $dd, $mm, $yy ) = split /\D/, $date;
  1072. }
  1073. }
  1074. else {
  1075. # ISO
  1076. ( $yy, $mm, $dd ) = ($date =~ /(....)(..)(..)/);
  1077. }
  1078. if ( $unit eq 'days' ) {
  1079. $diff = $repeat * 86400;
  1080. }
  1081. if ( $unit eq 'weeks' ) {
  1082. $diff = $repeat * 604800;
  1083. }
  1084. if ( $unit eq 'months' ) {
  1085. $diff = $mm + $repeat;
  1086. my $whole = int( $diff / 12 );
  1087. $yy += $whole;
  1088. $mm = ( $diff % 12 );
  1089. $mm = '12' if $mm == 0;
  1090. $yy-- if $mm == 12;
  1091. $diff = 0;
  1092. }
  1093. if ( $unit eq 'years' ) {
  1094. $yy += $repeat;
  1095. }
  1096. $mm--;
  1097. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yy ) + $diff );
  1098. $t[4]++;
  1099. $mm = substr( "0$t[4]", -2 );
  1100. $dd = substr( "0$t[3]", -2 );
  1101. $yy = $t[5] + 1900;
  1102. if ( $date =~ /\D/ ) {
  1103. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1104. $date = "$yy$spc$mm$spc$dd";
  1105. }
  1106. if ( $myconfig->{dateformat} =~ /^mm/ ) {
  1107. $date = "$mm$spc$dd$spc$yy";
  1108. }
  1109. if ( $myconfig->{dateformat} =~ /^dd/ ) {
  1110. $date = "$dd$spc$mm$spc$yy";
  1111. }
  1112. }
  1113. else {
  1114. $date = "$yy$mm$dd";
  1115. }
  1116. }
  1117. $date;
  1118. }
  1119. sub print_button {
  1120. my ( $self, $button, $name ) = @_;
  1121. print
  1122. 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|;
  1123. }
  1124. # Database routines used throughout
  1125. sub db_init {
  1126. my ( $self, $myconfig ) = @_;
  1127. $self->{dbh} = $self->dbconnect_noauto($myconfig) || $self->dberror();
  1128. %date_query = (
  1129. 'mm/dd/yy' => 'set DateStyle to \'SQL, US\'',
  1130. 'mm-dd-yy' => 'set DateStyle to \'POSTGRES, US\'',
  1131. 'dd/mm/yy' => 'set DateStyle to \'SQL, EUROPEAN\'',
  1132. 'dd-mm-yy' => 'set DateStyle to \'POSTGRES, EUROPEAN\'',
  1133. 'dd.mm.yy' => 'set DateStyle to \'GERMAN\''
  1134. );
  1135. $self->{dbh}->do( $date_query{ $myconfig->{dateformat} } );
  1136. $self->{db_dateformat} = $myconfig->{dateformat}; #shim
  1137. #$self->{dbh}->do('set log_statement to \'all\'');
  1138. my $query = "SELECT t.extends,
  1139. coalesce (t.table_name, 'custom_' || extends)
  1140. || ':' || f.field_name as field_def
  1141. FROM custom_table_catalog t
  1142. JOIN custom_field_catalog f USING (table_id)";
  1143. my $sth = $self->{dbh}->prepare($query);
  1144. $sth->execute;
  1145. my $ref;
  1146. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1147. push @{ $self->{custom_db_fields}{ $ref->{extends} } },
  1148. $ref->{field_def};
  1149. }
  1150. }
  1151. sub run_custom_queries {
  1152. my ( $self, $tablename, $query_type, $linenum ) = @_;
  1153. my $dbh = $self->{dbh};
  1154. if ( $query_type !~ /^(select|insert|update)$/i ) {
  1155. $self->error(
  1156. $locale->text(
  1157. "Passed incorrect query type to run_custom_queries."
  1158. )
  1159. );
  1160. }
  1161. my @rc;
  1162. my %temphash;
  1163. my @templist;
  1164. my @elements;
  1165. my $query;
  1166. my $ins_values;
  1167. if ($linenum) {
  1168. $linenum = "_$linenum";
  1169. }
  1170. $query_type = uc($query_type);
  1171. for ( @{ $self->{custom_db_fields}{$tablename} } ) {
  1172. @elements = split( /:/, $_ );
  1173. push @{ $temphash{ $elements[0] } }, $elements[1];
  1174. }
  1175. for ( keys %temphash ) {
  1176. my @data;
  1177. my $ins_values;
  1178. $query = "$query_type ";
  1179. if ( $query_type eq 'UPDATE' ) {
  1180. $query = "DELETE FROM $_ WHERE row_id = ?";
  1181. my $sth = $dbh->prepare($query);
  1182. $sth->execute( $self->{ "id" . "$linenum" } )
  1183. || $self->dberror($query);
  1184. }
  1185. elsif ( $query_type eq 'INSERT' ) {
  1186. $query .= " INTO $_ (";
  1187. }
  1188. my $first = 1;
  1189. for ( @{ $temphash{$_} } ) {
  1190. $query .= "$_";
  1191. if ( $query_type eq 'UPDATE' ) {
  1192. $query .= '= ?';
  1193. }
  1194. $ins_values .= "?, ";
  1195. $query .= ", ";
  1196. $first = 0;
  1197. if ( $query_type eq 'UPDATE' or $query_type eq 'INSERT' ) {
  1198. push @data, $self->{"$_$linenum"};
  1199. }
  1200. }
  1201. if ( $query_type ne 'INSERT' ) {
  1202. $query =~ s/, $//;
  1203. }
  1204. if ( $query_type eq 'SELECT' ) {
  1205. $query .= " FROM $_";
  1206. }
  1207. if ( $query_type eq 'SELECT' or $query_type eq 'UPDATE' ) {
  1208. $query .= " WHERE row_id = ?";
  1209. }
  1210. if ( $query_type eq 'INSERT' ) {
  1211. $query .= " row_id) VALUES ($ins_values ?)";
  1212. }
  1213. if ( $query_type eq 'SELECT' ) {
  1214. push @rc, [$query];
  1215. }
  1216. else {
  1217. unshift( @data, $query );
  1218. push @rc, [@data];
  1219. }
  1220. }
  1221. if ( $query_type eq 'INSERT' ) {
  1222. for (@rc) {
  1223. $query = shift( @{$_} );
  1224. $sth = $dbh->prepare($query)
  1225. || $self->db_error($query);
  1226. $sth->execute( @{$_}, $self->{id} )
  1227. || $self->dberror($query);
  1228. $sth->finish;
  1229. $did_insert = 1;
  1230. }
  1231. }
  1232. elsif ( $query_type eq 'UPDATE' ) {
  1233. @rc = $self->run_custom_queries( $tablename, 'INSERT', $linenum );
  1234. }
  1235. elsif ( $query_type eq 'SELECT' ) {
  1236. for (@rc) {
  1237. $query = shift @{$_};
  1238. $sth = $self->{dbh}->prepare($query);
  1239. $sth->execute( $self->{id} );
  1240. $ref = $sth->fetchrow_hashref('NAME_lc');
  1241. for ( keys %{$ref} ) {
  1242. $self->{$_} = $ref->{$_};
  1243. }
  1244. }
  1245. }
  1246. @rc;
  1247. }
  1248. sub dbconnect {
  1249. my ( $self, $myconfig ) = @_;
  1250. # connect to database
  1251. my $dbh = DBI->connect( $myconfig->{dbconnect},
  1252. $myconfig->{dbuser}, $myconfig->{dbpasswd} )
  1253. or $self->dberror;
  1254. $dbh->{pg_enable_utf8} = 1;
  1255. # set db options
  1256. if ( $myconfig->{dboptions} ) {
  1257. $dbh->do( $myconfig->{dboptions} )
  1258. || $self->dberror( $myconfig->{dboptions} );
  1259. }
  1260. $dbh;
  1261. }
  1262. sub dbconnect_noauto {
  1263. my ( $self, $myconfig ) = @_;
  1264. # connect to database
  1265. $dbh = DBI->connect(
  1266. $myconfig->{dbconnect}, $myconfig->{dbuser},
  1267. $myconfig->{dbpasswd}, { AutoCommit => 0 }
  1268. ) or $self->dberror;
  1269. $dbh->{pg_enable_utf8} = 1;
  1270. # set db options
  1271. if ( $myconfig->{dboptions} ) {
  1272. $dbh->do( $myconfig->{dboptions} );
  1273. }
  1274. $dbh;
  1275. }
  1276. sub dbquote {
  1277. my ( $self, $var ) = @_;
  1278. if ( $var eq '' ) {
  1279. $_ = "NULL";
  1280. }
  1281. else {
  1282. $_ = $self->{dbh}->quote($var);
  1283. }
  1284. $_;
  1285. }
  1286. sub update_balance {
  1287. # This is a dangerous private function. All apps calling it must
  1288. # be careful to avoid SQL injection issues
  1289. my ( $self, $dbh, $table, $field, $where, $value ) = @_;
  1290. # if we have a value, go do it
  1291. if ($value) {
  1292. $table = $dbh->quote_identifier($table);
  1293. $field = $dbh->quote_identifier($field);
  1294. # retrieve balance from table
  1295. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  1296. my ($balance) = $dbh->selectrow_array($query);
  1297. $balance = $dbh->quote($balance + $value);
  1298. # update balance
  1299. $query = "UPDATE $table SET $field = $balance WHERE $where";
  1300. $dbh->do($query) || $self->dberror($query);
  1301. }
  1302. }
  1303. sub update_exchangerate {
  1304. my ( $self, $dbh, $curr, $transdate, $buy, $sell ) = @_;
  1305. # some sanity check for currency
  1306. return if ( $curr eq "" );
  1307. my $query = qq|
  1308. SELECT curr
  1309. FROM exchangerate
  1310. WHERE curr = ?
  1311. AND transdate = ?
  1312. FOR UPDATE|;
  1313. my $sth = $self->{dbh}->prepare($query);
  1314. $sth->execute( $curr, $transdate ) || $self->dberror($query);
  1315. my $set;
  1316. my @queryargs;
  1317. if ( $buy && $sell ) {
  1318. $set = "buy = ?, sell = ?";
  1319. @queryargs = ( $buy, $sell );
  1320. }
  1321. elsif ($buy) {
  1322. $set = "buy = ?";
  1323. @queryargs = ($buy);
  1324. }
  1325. elsif ($sell) {
  1326. $set = "sell = ?";
  1327. @queryargs = ($sell);
  1328. }
  1329. if ( !$set ) {
  1330. $self->error("Exchange rate missing!");
  1331. }
  1332. if ( $sth->fetchrow_array ) {
  1333. $query = qq|UPDATE exchangerate
  1334. SET $set
  1335. WHERE curr = ?
  1336. AND transdate = ?|;
  1337. push( @queryargs, $curr, $transdate );
  1338. }
  1339. else {
  1340. $query = qq|
  1341. INSERT INTO exchangerate (
  1342. curr, buy, sell, transdate)
  1343. VALUES (?, ?, ?, ?)|;
  1344. @queryargs = ( $curr, $buy, $sell, $transdate );
  1345. }
  1346. $sth->finish;
  1347. $sth = $self->{dbh}->prepare($query);
  1348. $sth->execute(@queryargs) || $self->dberror($query);
  1349. }
  1350. sub save_exchangerate {
  1351. my ( $self, $myconfig, $currency, $transdate, $rate, $fld ) = @_;
  1352. my ( $buy, $sell ) = ( 0, 0 );
  1353. $buy = $rate if $fld eq 'buy';
  1354. $sell = $rate if $fld eq 'sell';
  1355. $self->update_exchangerate( $self->{dbh}, $currency, $transdate, $buy,
  1356. $sell );
  1357. $dbh->commit;
  1358. }
  1359. sub get_exchangerate {
  1360. my ( $self, $dbh, $curr, $transdate, $fld ) = @_;
  1361. my $exchangerate = 1;
  1362. if ($transdate) {
  1363. my $query = qq|
  1364. SELECT $fld FROM exchangerate
  1365. WHERE curr = ? AND transdate = ?|;
  1366. my $sth = $self->{dbh}->prepare($query);
  1367. $sth->execute( $curr, $transdate );
  1368. ($exchangerate) = $sth->fetchrow_array;
  1369. $exchangerate = Math::BigFloat->new($exchangerate);
  1370. $sth->finish;
  1371. }
  1372. $self->{dbh}->commit;
  1373. $exchangerate;
  1374. }
  1375. sub check_exchangerate {
  1376. my ( $self, $myconfig, $currency, $transdate, $fld ) = @_;
  1377. return "" unless $transdate;
  1378. my $query = qq|
  1379. SELECT $fld
  1380. FROM exchangerate
  1381. WHERE curr = ? AND transdate = ?|;
  1382. my $sth = $self->{dbh}->prepare($query);
  1383. $sth->execute( $currency, $transdate );
  1384. my @array = $sth->fetchrow_array;
  1385. $self->db_parse_numeric(sth => $sth, arrayref => \@array);
  1386. my ($exchangerate) = @array;
  1387. $sth->finish;
  1388. $self->{dbh}->commit;
  1389. $exchangerate;
  1390. }
  1391. sub add_shipto {
  1392. my ( $self, $dbh, $id ) = @_;
  1393. my $shipto;
  1394. foreach my $item (
  1395. qw(name address1 address2 city state
  1396. zipcode country contact phone fax email)
  1397. )
  1398. {
  1399. if ( $self->{"shipto$item"} ne "" ) {
  1400. $shipto = 1 if ( $self->{$item} ne $self->{"shipto$item"} );
  1401. }
  1402. }
  1403. if ($shipto) {
  1404. my $query = qq|
  1405. INSERT INTO shipto
  1406. (trans_id, shiptoname, shiptoaddress1,
  1407. shiptoaddress2, shiptocity, shiptostate,
  1408. shiptozipcode, shiptocountry, shiptocontact,
  1409. shiptophone, shiptofax, shiptoemail)
  1410. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1411. |;
  1412. $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  1413. $sth->execute(
  1414. $id, $self->{shiptoname},
  1415. $self->{shiptoaddress1}, $self->{shiptoaddress2},
  1416. $self->{shiptocity}, $self->{shiptostate},
  1417. $self->{shiptozipcode}, $self->{shiptocountry},
  1418. $self->{shiptocontact}, $self->{shiptophone},
  1419. $self->{shiptofax}, $self->{shiptoemail}
  1420. ) || $self->dberror($query);
  1421. $sth->finish;
  1422. $self->{dbh}->commit;
  1423. }
  1424. }
  1425. sub get_employee {
  1426. my ( $self, $dbh ) = @_;
  1427. my $login = $self->{login};
  1428. $login =~ s/@.*//;
  1429. my $query = qq|SELECT name, id
  1430. FROM employee
  1431. WHERE login = ?|;
  1432. $sth = $self->{dbh}->prepare($query);
  1433. $sth->execute($login);
  1434. my (@a) = $sth->fetchrow_array();
  1435. $a[1] *= 1;
  1436. $sth->finish;
  1437. $self->{dbh}->commit;
  1438. @a;
  1439. }
  1440. # this sub gets the id and name from $table
  1441. sub get_name {
  1442. my ( $self, $myconfig, $table, $transdate ) = @_;
  1443. # connect to database
  1444. my @queryargs;
  1445. my $where;
  1446. if ($transdate) {
  1447. $where = qq|
  1448. AND (startdate IS NULL OR startdate <= ?)
  1449. AND (enddate IS NULL OR enddate >= ?)|;
  1450. @queryargs = ( $transdate, $transdate );
  1451. }
  1452. my $name = $self->like( lc $self->{$table} );
  1453. my $query = qq|
  1454. SELECT * FROM $table
  1455. WHERE (lower(name) LIKE ? OR ${table}number LIKE ?)
  1456. $where
  1457. ORDER BY name|;
  1458. unshift( @queryargs, $name, $name );
  1459. my $sth = $self->{dbh}->prepare($query);
  1460. $sth->execute(@queryargs) || $self->dberror($query);
  1461. my $i = 0;
  1462. @{ $self->{name_list} } = ();
  1463. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1464. push( @{ $self->{name_list} }, $ref );
  1465. $i++;
  1466. }
  1467. $sth->finish;
  1468. $self->{dbh}->commit;
  1469. $i;
  1470. }
  1471. sub all_vc {
  1472. my ( $self, $myconfig, $vc, $module, $dbh, $transdate, $job ) = @_;
  1473. my $ref;
  1474. my $disconnect = 0;
  1475. $dbh = $self->{dbh};
  1476. my $sth;
  1477. my $query = qq|SELECT count(*) FROM $vc|;
  1478. my $where;
  1479. my @queryargs = ();
  1480. if ($transdate) {
  1481. $query .= qq| WHERE (startdate IS NULL OR startdate <= ?)
  1482. AND (enddate IS NULL OR enddate >= ?)|;
  1483. @queryargs = ( $transdate, $transdate );
  1484. }
  1485. $sth = $dbh->prepare($query);
  1486. $sth->execute(@queryargs);
  1487. my ($count) = $sth->fetchrow_array;
  1488. $sth->finish;
  1489. @queryargs = ();
  1490. # build selection list
  1491. if ( $count < $myconfig->{vclimit} ) {
  1492. $self->{"${vc}_id"} *= 1;
  1493. $query = qq|SELECT id, name
  1494. FROM $vc
  1495. WHERE 1=1
  1496. $where
  1497. UNION
  1498. SELECT id,name
  1499. FROM $vc
  1500. WHERE id = ?
  1501. ORDER BY name|;
  1502. push( @queryargs, $self->{"${vc}_id"} );
  1503. $sth = $dbh->prepare($query);
  1504. $sth->execute(@queryargs) || $self->dberror($query);
  1505. @{ $self->{"all_$vc"} } = ();
  1506. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1507. push @{ $self->{"all_$vc"} }, $ref;
  1508. }
  1509. $sth->finish;
  1510. }
  1511. # get self
  1512. if ( !$self->{employee_id} ) {
  1513. ( $self->{employee}, $self->{employee_id} ) = split /--/,
  1514. $self->{employee};
  1515. ( $self->{employee}, $self->{employee_id} ) = $self->get_employee($dbh)
  1516. unless $self->{employee_id};
  1517. }
  1518. $self->all_employees( $myconfig, $dbh, $transdate, 1 );
  1519. $self->all_departments( $myconfig, $dbh, $vc );
  1520. $self->all_projects( $myconfig, $dbh, $transdate, $job );
  1521. # get language codes
  1522. $query = qq|SELECT *
  1523. FROM language
  1524. ORDER BY 2|;
  1525. $sth = $dbh->prepare($query);
  1526. $sth->execute || $self->dberror($query);
  1527. $self->{all_language} = ();
  1528. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1529. push @{ $self->{all_language} }, $ref;
  1530. }
  1531. $sth->finish;
  1532. $self->all_taxaccounts( $myconfig, $dbh, $transdate );
  1533. $self->{dbh}->commit;
  1534. }
  1535. sub all_taxaccounts {
  1536. my ( $self, $myconfig, $dbh2, $transdate ) = @_;
  1537. my $dbh = $self->{dbh};
  1538. my $sth;
  1539. my $query;
  1540. my $where;
  1541. my @queryargs = ();
  1542. if ($transdate) {
  1543. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1544. push( @queryargs, $transdate );
  1545. }
  1546. if ( $self->{taxaccounts} ) {
  1547. # rebuild tax rates
  1548. $query = qq|SELECT t.rate, t.taxnumber
  1549. FROM tax t
  1550. JOIN chart c ON (c.id = t.chart_id)
  1551. WHERE c.accno = ?
  1552. $where
  1553. ORDER BY accno, validto|;
  1554. $sth = $dbh->prepare($query) || $self->dberror($query);
  1555. foreach my $accno ( split / /, $self->{taxaccounts} ) {
  1556. $sth->execute( $accno, @queryargs );
  1557. ( $self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"} ) =
  1558. $sth->fetchrow_array;
  1559. $sth->finish;
  1560. }
  1561. }
  1562. $self->{dbh}->commit;
  1563. }
  1564. sub all_employees {
  1565. my ( $self, $myconfig, $dbh2, $transdate, $sales ) = @_;
  1566. my $dbh = $self->{dbh};
  1567. my @whereargs = ();
  1568. # setup employees/sales contacts
  1569. my $query = qq|SELECT id, name
  1570. FROM employee
  1571. WHERE 1 = 1|;
  1572. if ($transdate) {
  1573. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1574. AND (enddate IS NULL OR enddate >= ?)|;
  1575. @whereargs = ( $transdate, $transdate );
  1576. }
  1577. else {
  1578. $query .= qq| AND enddate IS NULL|;
  1579. }
  1580. if ($sales) {
  1581. $query .= qq| AND sales = '1'|;
  1582. }
  1583. $query .= qq| ORDER BY name|;
  1584. my $sth = $dbh->prepare($query);
  1585. $sth->execute(@whereargs) || $self->dberror($query);
  1586. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1587. push @{ $self->{all_employee} }, $ref;
  1588. }
  1589. $sth->finish;
  1590. $dbh->commit;
  1591. }
  1592. sub all_projects {
  1593. my ( $self, $myconfig, $dbh2, $transdate, $job ) = @_;
  1594. my $dbh = $self->{dbh};
  1595. my @queryargs = ();
  1596. my $where = "1 = 1";
  1597. $where = qq|id NOT IN (SELECT id
  1598. FROM parts
  1599. WHERE project_id > 0)| if !$job;
  1600. my $query = qq|SELECT *
  1601. FROM project
  1602. WHERE $where|;
  1603. if ( $self->{language_code} ) {
  1604. $query = qq|
  1605. SELECT pr.*, t.description AS translation
  1606. FROM project pr
  1607. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1608. WHERE t.language_code = ?|;
  1609. push( @queryargs, $self->{language_code} );
  1610. }
  1611. if ($transdate) {
  1612. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1613. AND (enddate IS NULL OR enddate >= ?)|;
  1614. push( @queryargs, $transdate, $transdate );
  1615. }
  1616. $query .= qq| ORDER BY projectnumber|;
  1617. $sth = $dbh->prepare($query);
  1618. $sth->execute(@queryargs) || $self->dberror($query);
  1619. @{ $self->{all_project} } = ();
  1620. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1621. push @{ $self->{all_project} }, $ref;
  1622. }
  1623. $sth->finish;
  1624. $dbh->commit;
  1625. }
  1626. sub all_departments {
  1627. my ( $self, $myconfig, $dbh2, $vc ) = @_;
  1628. $dbh = $self->{dbh};
  1629. my $where = "1 = 1";
  1630. if ($vc) {
  1631. if ( $vc eq 'customer' ) {
  1632. $where = " role = 'P'";
  1633. }
  1634. }
  1635. my $query = qq|SELECT id, description
  1636. FROM department
  1637. WHERE $where
  1638. ORDER BY 2|;
  1639. my $sth = $dbh->prepare($query);
  1640. $sth->execute || $self->dberror($query);
  1641. @{ $self->{all_department} } = ();
  1642. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1643. push @{ $self->{all_department} }, $ref;
  1644. }
  1645. $sth->finish;
  1646. $self->all_years($myconfig);
  1647. $dbh->commit;
  1648. }
  1649. sub all_years {
  1650. my ( $self, $myconfig, $dbh2 ) = @_;
  1651. $dbh = $self->{dbh};
  1652. $self->{all_years} = [];
  1653. # get years
  1654. my $query = qq|
  1655. SELECT extract('YEARS' FROM transdate) FROM acc_trans
  1656. GROUP BY extract('YEARS' FROM transdate) ORDER BY 1 DESC|;
  1657. #this should probably be changed to use locale
  1658. %{ $self->{all_month} } = (
  1659. '01' => 'January',
  1660. '02' => 'February',
  1661. '03' => 'March',
  1662. '04' => 'April',
  1663. '05' => 'May ',
  1664. '06' => 'June',
  1665. '07' => 'July',
  1666. '08' => 'August',
  1667. '09' => 'September',
  1668. '10' => 'October',
  1669. '11' => 'November',
  1670. '12' => 'December'
  1671. );
  1672. @{$self->{all_years}} = @{$dbh->selectcol_arrayref($query)};
  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. $param = quotemeta $param;
  2236. $var =~ s/$param/$str/;
  2237. }
  2238. if ( $param =~
  2239. /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i
  2240. )
  2241. {
  2242. my $fld = lc $&;
  2243. $fld =~ s/<\?lsmb //;
  2244. if ( $fld =~ /name/ ) {
  2245. if ( $self->{type} ) {
  2246. $fld = $self->{vc};
  2247. }
  2248. }
  2249. my $p = $param;
  2250. $p =~ s/(:<\?lsmb\s*|\s*\?>)//g;
  2251. my @p = split / /, $p;
  2252. my @n = split / /, uc $self->{$fld};
  2253. if ( $#p > 0 ) {
  2254. foreach my $i (1 .. $#p) {
  2255. $str .= substr( $n[ $i - 1 ], 0, $p[$i] );
  2256. }
  2257. } else {
  2258. ($str) = split /--/, $self->{$fld};
  2259. }
  2260. $param = quotemeta $param;
  2261. $var =~ s/$param/$str/;
  2262. $var =~ s/\W//g if $fld eq 'phone';
  2263. }
  2264. if ( $param =~ /<\?lsmb (yy|mm|dd)/i ) {
  2265. my $p = $param;
  2266. $p =~ s/(<\?lsmb\s*|\s*\?>)//g;
  2267. my $spc = $p;
  2268. $spc =~ s/\w//g;
  2269. $spc = substr( $spc, 0, 1 );
  2270. my %d = ( yy => 1, mm => 2, dd => 3 );
  2271. my @p = ();
  2272. my @date = $self->split_date( $myconfig->{dateformat},
  2273. $self->{transdate} );
  2274. for ( sort keys %d ) { push @p, $date[ $d{$_} ] if ( $p =~ /$_/i ) }
  2275. $str = join $spc, @p;
  2276. $param = quotemeta $param;
  2277. $var =~ s/$param/$str/;
  2278. }
  2279. if ( $param =~ /<\?lsmb curr/i ) {
  2280. $param = quotemeta $param;
  2281. $var =~ s/$param/$self->{currency}/;
  2282. }
  2283. }
  2284. }
  2285. $query = qq|
  2286. UPDATE defaults
  2287. SET value = ?
  2288. WHERE setting_key = ?|;
  2289. $sth = $dbh->prepare($query);
  2290. $sth->execute( $dbvar, $fld ) || $self->dberror($query);
  2291. $dbh->commit;
  2292. $var;
  2293. }
  2294. sub db_prepare_vars {
  2295. my $self = shift;
  2296. for (@_) {
  2297. if ( !$self->{$_} and $self->{$_} ne "0" ) {
  2298. undef $self->{$_};
  2299. }
  2300. }
  2301. }
  2302. sub split_date {
  2303. my ( $self, $dateformat, $date ) = @_;
  2304. my @d = localtime;
  2305. my $mm;
  2306. my $dd;
  2307. my $yy;
  2308. my $rv;
  2309. if ( !$date ) {
  2310. $dd = $d[3];
  2311. $mm = ++$d[4];
  2312. $yy = substr( $d[5], -2 );
  2313. $mm = substr( "0$mm", -2 );
  2314. $dd = substr( "0$dd", -2 );
  2315. }
  2316. if ( $dateformat =~ /^yy/ ) {
  2317. if ($date) {
  2318. if ( $date =~ /\D/ ) {
  2319. ( $yy, $mm, $dd ) = split /\D/, $date;
  2320. $mm *= 1;
  2321. $dd *= 1;
  2322. $mm = substr( "0$mm", -2 );
  2323. $dd = substr( "0$dd", -2 );
  2324. $yy = substr( $yy, -2 );
  2325. $rv = "$yy$mm$dd";
  2326. }
  2327. else {
  2328. $rv = $date;
  2329. }
  2330. }
  2331. else {
  2332. $rv = "$yy$mm$dd";
  2333. }
  2334. }
  2335. if ( $dateformat =~ /^mm/ ) {
  2336. if ($date) {
  2337. if ( $date =~ /\D/ ) {
  2338. ( $mm, $dd, $yy ) = split /\D/, $date;
  2339. $mm *= 1;
  2340. $dd *= 1;
  2341. $mm = substr( "0$mm", -2 );
  2342. $dd = substr( "0$dd", -2 );
  2343. $yy = substr( $yy, -2 );
  2344. $rv = "$mm$dd$yy";
  2345. }
  2346. else {
  2347. $rv = $date;
  2348. }
  2349. }
  2350. else {
  2351. $rv = "$mm$dd$yy";
  2352. }
  2353. }
  2354. if ( $dateformat =~ /^dd/ ) {
  2355. if ($date) {
  2356. if ( $date =~ /\D/ ) {
  2357. ( $dd, $mm, $yy ) = split /\D/, $date;
  2358. $mm *= 1;
  2359. $dd *= 1;
  2360. $mm = substr( "0$mm", -2 );
  2361. $dd = substr( "0$dd", -2 );
  2362. $yy = substr( $yy, -2 );
  2363. $rv = "$dd$mm$yy";
  2364. }
  2365. else {
  2366. $rv = $date;
  2367. }
  2368. }
  2369. else {
  2370. $rv = "$dd$mm$yy";
  2371. }
  2372. }
  2373. ( $rv, $yy, $mm, $dd );
  2374. }
  2375. sub format_date {
  2376. # takes an iso date in, and converts it to the date for printing
  2377. my ( $self, $date ) = @_;
  2378. my $datestring;
  2379. if ( $date =~ /^\d{4}\D/ ) { # is an ISO date
  2380. $datestring = $self->{db_dateformat};
  2381. my ( $yyyy, $mm, $dd ) = split( /\W/, $date );
  2382. $datestring =~ s/y+/$yyyy/;
  2383. $datestring =~ s/mm/$mm/;
  2384. $datestring =~ s/dd/$dd/;
  2385. }
  2386. else { # return date
  2387. $datestring = $date;
  2388. }
  2389. $datestring;
  2390. }
  2391. sub from_to {
  2392. my ( $self, $yyyy, $mm, $interval ) = @_;
  2393. my @t;
  2394. my $dd = 1;
  2395. my $fromdate = "$yyyy-${mm}-01";
  2396. my $bd = 1;
  2397. if ( defined $interval ) {
  2398. if ( $interval == 12 ) {
  2399. $yyyy++;
  2400. }
  2401. else {
  2402. if ( ( $mm += $interval ) > 12 ) {
  2403. $mm -= 12;
  2404. $yyyy++;
  2405. }
  2406. if ( $interval == 0 ) {
  2407. @t = localtime(time);
  2408. $dd = $t[3];
  2409. $mm = $t[4] + 1;
  2410. $yyyy = $t[5] + 1900;
  2411. $bd = 0;
  2412. }
  2413. }
  2414. }
  2415. else {
  2416. if ( ++$mm > 12 ) {
  2417. $mm -= 12;
  2418. $yyyy++;
  2419. }
  2420. }
  2421. $mm--;
  2422. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yyyy ) - $bd );
  2423. $t[4]++;
  2424. $t[4] = substr( "0$t[4]", -2 );
  2425. $t[3] = substr( "0$t[3]", -2 );
  2426. $t[5] += 1900;
  2427. ( $self->format_date($fromdate), $self->format_date("$t[5]-$t[4]-$t[3]") );
  2428. }
  2429. sub audittrail {
  2430. my ( $self, $dbh, $myconfig, $audittrail ) = @_;
  2431. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2432. my $query;
  2433. my $rv;
  2434. my $disconnect;
  2435. if ( !$dbh ) {
  2436. $dbh = $self->{dbh};
  2437. }
  2438. # if we have an id add audittrail, otherwise get a new timestamp
  2439. my @queryargs;
  2440. if ( $audittrail->{id} ) {
  2441. $query = qq|
  2442. SELECT value FROM defaults
  2443. WHERE setting_key = 'audittrail'|;
  2444. if ( $dbh->selectrow_array($query) ) {
  2445. my ( $null, $employee_id ) = $self->get_employee($dbh);
  2446. if ( $self->{audittrail} && !$myconfig ) {
  2447. chop $self->{audittrail};
  2448. my @a = split /\|/, $self->{audittrail};
  2449. my %newtrail = ();
  2450. my $key;
  2451. my $i;
  2452. my @flds = qw(tablename reference formname action transdate);
  2453. # put into hash and remove dups
  2454. while (@a) {
  2455. $key = "$a[2]$a[3]";
  2456. $i = 0;
  2457. $newtrail{$key} = { map { $_ => $a[ $i++ ] } @flds };
  2458. splice @a, 0, 5;
  2459. }
  2460. $query = qq|
  2461. INSERT INTO audittrail
  2462. (trans_id, tablename, reference,
  2463. formname, action, transdate,
  2464. employee_id)
  2465. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2466. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2467. foreach $key (
  2468. sort {
  2469. $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
  2470. } keys %newtrail
  2471. )
  2472. {
  2473. $i = 2;
  2474. $sth->bind_param( 1, $audittrail->{id} );
  2475. for (@flds) {
  2476. $sth->bind_param( $i++, $newtrail{$key}{$_} );
  2477. }
  2478. $sth->bind_param( $i++, $employee_id );
  2479. $sth->execute() || $self->dberror($query);
  2480. $sth->finish;
  2481. }
  2482. }
  2483. if ( $audittrail->{transdate} ) {
  2484. $query = qq|
  2485. INSERT INTO audittrail (
  2486. trans_id, tablename, reference,
  2487. formname, action, employee_id,
  2488. transdate)
  2489. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2490. @queryargs = (
  2491. $audittrail->{id}, $audittrail->{tablename},
  2492. $audittrail->{reference}, $audittrail->{formname},
  2493. $audittrail->{action}, $employee_id,
  2494. $audittrail->{transdate}
  2495. );
  2496. }
  2497. else {
  2498. $query = qq|
  2499. INSERT INTO audittrail
  2500. (trans_id, tablename, reference,
  2501. formname, action, employee_id)
  2502. VALUES (?, ?, ?, ?, ?, ?)|;
  2503. @queryargs = (
  2504. $audittrail->{id}, $audittrail->{tablename},
  2505. $audittrail->{reference}, $audittrail->{formname},
  2506. $audittrail->{action}, $employee_id,
  2507. );
  2508. }
  2509. $sth = $dbh->prepare($query);
  2510. $sth->execute(@queryargs) || $self->dberror($query);
  2511. }
  2512. }
  2513. else {
  2514. $query = qq|SELECT current_timestamp|;
  2515. my ($timestamp) = $dbh->selectrow_array($query);
  2516. $rv =
  2517. "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2518. }
  2519. $dbh->commit;
  2520. $rv;
  2521. }
  2522. 1;