summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: 4a2d0a65966e3c3bc1c7acd01c12a8e3a161c609 (plain)
  1. #=====================================================================
  2. # LedgerSMB
  3. # Small Medium Business Accounting software
  4. # http://www.ledgersmb.org/
  5. #
  6. # Copyright (C) 2006
  7. # This work contains copyrighted information from a number of sources all used
  8. # with permission.
  9. #
  10. # This file contains source code included with or based on SQL-Ledger which
  11. # is Copyright Dieter Simader and DWS Systems Inc. 2000-2005 and licensed
  12. # under the GNU General Public License version 2 or, at your option, any later
  13. # version. For a full list including contact information of contributors,
  14. # maintainers, and copyright holders, see the CONTRIBUTORS file.
  15. #
  16. # Original Copyright Notice from SQL-Ledger 2.6.17 (before the fork):
  17. # Copyright (C) 2000
  18. #
  19. # Author: DWS Systems Inc.
  20. # Web: http://www.sql-ledger.org
  21. #
  22. # Contributors: Thomas Bayen <bayen@gmx.de>
  23. # Antti Kaihola <akaihola@siba.fi>
  24. # Moritz Bunkus (tex)
  25. # Jim Rawlings <jim@your-dba.com> (DB2)
  26. #======================================================================
  27. #
  28. # This file has undergone whitespace cleanup.
  29. #
  30. #======================================================================
  31. #
  32. # main package
  33. #
  34. #======================================================================
  35. use Math::BigFloat lib => 'GMP';
  36. use LedgerSMB::Sysconfig;
  37. use List::Util qw(first);
  38. use LedgerSMB::Mailer;
  39. use Time::Local;
  40. use Cwd;
  41. use File::Copy;
  42. use charnames ':full';
  43. use open ':utf8';
  44. package Form;
  45. sub new {
  46. my $type = shift;
  47. my $argstr = shift;
  48. read( STDIN, $_, $ENV{CONTENT_LENGTH} );
  49. if ($argstr) {
  50. $_ = $argstr;
  51. }
  52. elsif ( $ENV{QUERY_STRING} ) {
  53. $_ = $ENV{QUERY_STRING};
  54. }
  55. elsif ( $ARGV[0] ) {
  56. $_ = $ARGV[0];
  57. }
  58. my $self = {};
  59. %$self = split /[&=]/;
  60. for ( keys %$self ) { $self->{$_} = unescape( "", $self->{$_} ) }
  61. if ( substr( $self->{action}, 0, 1 ) !~ /( |\.)/ ) {
  62. $self->{action} = lc $self->{action};
  63. $self->{action} =~ s/( |-|,|\#|\/|\.$)/_/g;
  64. $self->{nextsub} = lc $self->{nextsub};
  65. $self->{nextsub} =~ s/( |-|,|\#|\/|\.$)/_/g;
  66. }
  67. $self->{login} =~ s/[^a-zA-Z0-9._+\@'-]//g;
  68. $self->{menubar} = 1 if $self->{path} =~ /lynx/i;
  69. #menubar will be deprecated, replaced with below
  70. $self->{lynx} = 1 if $self->{path} =~ /lynx/i;
  71. $self->{version} = "SVN Trunk";
  72. $self->{dbversion} = "1.2.0";
  73. bless $self, $type;
  74. if ( $self->{path} ne 'bin/lynx' ) { $self->{path} = 'bin/mozilla'; }
  75. if ( ( $self->{script} )
  76. and not List::Util::first { $_ eq $self->{script} }
  77. @{LedgerSMB::Sysconfig::scripts} )
  78. {
  79. $self->error( 'Access Denied', __line__, __file__ );
  80. }
  81. if ( ( $self->{action} =~ /(:|')/ ) || ( $self->{nextsub} =~ /(:|')/ ) ) {
  82. $self->error( "Access Denied", __line__, __file__ );
  83. }
  84. for ( keys %$self ) { $self->{$_} =~ s/\N{NULL}//g }
  85. $self;
  86. }
  87. sub debug {
  88. my ( $self, $file ) = @_;
  89. if ($file) {
  90. open( FH, '>', "$file" ) or die $!;
  91. for ( sort keys %$self ) { print FH "$_ = $self->{$_}\n" }
  92. close(FH);
  93. }
  94. else {
  95. print "\n";
  96. for ( sort keys %$self ) { print "$_ = $self->{$_}\n" }
  97. }
  98. }
  99. sub encode_all {
  100. # TODO;
  101. }
  102. sub decode_all {
  103. # TODO
  104. }
  105. sub escape {
  106. my ( $self, $str, $beenthere ) = @_;
  107. # for Apache 2 we escape strings twice
  108. if ( ( $ENV{SERVER_SIGNATURE} =~ /Apache\/2\.(\d+)\.(\d+)/ )
  109. && !$beenthere )
  110. {
  111. $str = $self->escape( $str, 1 ) if $1 == 0 && $2 < 44;
  112. }
  113. utf8::encode($str);
  114. $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
  115. $str;
  116. }
  117. sub unescape {
  118. my ( $self, $str ) = @_;
  119. $str =~ tr/+/ /;
  120. $str =~ s/\\$//;
  121. utf8::encode($str) if utf8::is_utf8($str);
  122. $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
  123. utf8::decode($str);
  124. $str =~ s/\r?\n/\n/g;
  125. $str;
  126. }
  127. sub quote {
  128. my ( $self, $str ) = @_;
  129. if ( $str && !ref($str) ) {
  130. $str =~ s/"/&quot;/g;
  131. }
  132. $str;
  133. }
  134. sub unquote {
  135. my ( $self, $str ) = @_;
  136. if ( $str && !ref($str) ) {
  137. $str =~ s/&quot;/"/g;
  138. }
  139. $str;
  140. }
  141. sub hide_form {
  142. my $self = shift;
  143. if (@_) {
  144. for (@_) {
  145. print qq|<input type="hidden" name="$_" value="|
  146. . $self->quote( $self->{$_} )
  147. . qq|" />\n|;
  148. }
  149. }
  150. else {
  151. delete $self->{header};
  152. for ( sort keys %$self ) {
  153. print qq|<input type="hidden" name="$_" value="|
  154. . $self->quote( $self->{$_} )
  155. . qq|" />\n|;
  156. }
  157. }
  158. }
  159. sub error {
  160. my ( $self, $msg ) = @_;
  161. if ( $ENV{GATEWAY_INTERFACE} ) {
  162. $self->{msg} = $msg;
  163. $self->{format} = "html";
  164. $self->format_string('msg');
  165. delete $self->{pre};
  166. if ( !$self->{header} ) {
  167. $self->header;
  168. }
  169. print
  170. qq|<body><h2 class="error">Error!</h2> <p><b>$self->{msg}</b></body>|;
  171. exit;
  172. }
  173. else {
  174. if ( $ENV{error_function} ) {
  175. &{ $ENV{error_function} }($msg);
  176. }
  177. die "Error: $msg\n";
  178. }
  179. }
  180. sub info {
  181. my ( $self, $msg ) = @_;
  182. if ( $ENV{GATEWAY_INTERFACE} ) {
  183. $msg =~ s/\n/<br>/g;
  184. delete $self->{pre};
  185. if ( !$self->{header} ) {
  186. $self->header;
  187. print qq| <body>|;
  188. $self->{header} = 1;
  189. }
  190. print "<b>$msg</b>";
  191. }
  192. else {
  193. if ( $ENV{info_function} ) {
  194. &{ $ENV{info_function} }($msg);
  195. }
  196. else {
  197. print "$msg\n";
  198. }
  199. }
  200. }
  201. sub numtextrows {
  202. my ( $self, $str, $cols, $maxrows ) = @_;
  203. my $rows = 0;
  204. for ( split /\n/, $str ) {
  205. $rows += int( ( (length) - 2 ) / $cols ) + 1;
  206. }
  207. $maxrows = $rows unless defined $maxrows;
  208. return ( $rows > $maxrows ) ? $maxrows : $rows;
  209. }
  210. sub dberror {
  211. my ( $self, $msg ) = @_;
  212. $self->error( "$msg\n" . $DBI::errstr );
  213. }
  214. sub isblank {
  215. my ( $self, $name, $msg ) = @_;
  216. $self->error($msg) if $self->{$name} =~ /^\s*$/;
  217. }
  218. sub header {
  219. my ( $self, $init, $headeradd ) = @_;
  220. return if $self->{header};
  221. my ( $stylesheet, $favicon, $charset );
  222. if ( $ENV{GATEWAY_INTERFACE} ) {
  223. if ( $self->{stylesheet} && ( -f "css/$self->{stylesheet}" ) ) {
  224. $stylesheet =
  225. qq|<link rel="stylesheet" href="css/$self->{stylesheet}" type="text/css" title="LedgerSMB stylesheet" />\n|;
  226. }
  227. $self->{charset} ||= "utf-8";
  228. $charset =
  229. qq|<meta http-equiv="content-type" content="text/html; charset=$self->{charset}" />\n|;
  230. $self->{titlebar} =
  231. ( $self->{title} )
  232. ? "$self->{title} - $self->{titlebar}"
  233. : $self->{titlebar};
  234. print qq|Content-Type: text/html; charset=utf-8\n\n
  235. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  236. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  237. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  238. <head>
  239. <title>$self->{titlebar}</title>
  240. <meta http-equiv="Pragma" content="no-cache" />
  241. <meta http-equiv="Expires" content="-1" />
  242. <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  243. $stylesheet
  244. $charset
  245. <meta name="robots" content="noindex,nofollow" />
  246. $headeradd
  247. </head>
  248. $self->{pre} \n|;
  249. }
  250. $self->{header} = 1;
  251. }
  252. sub redirect {
  253. my ( $self, $msg ) = @_;
  254. if ( $self->{callback} || !$msg ) {
  255. main::redirect();
  256. exit;
  257. }
  258. else {
  259. $self->info($msg);
  260. }
  261. }
  262. sub sort_columns {
  263. my ( $self, @columns ) = @_;
  264. if ( $self->{sort} ) {
  265. if (@columns) {
  266. @columns = grep !/^$self->{sort}$/, @columns;
  267. splice @columns, 0, 0, $self->{sort};
  268. }
  269. }
  270. @columns;
  271. }
  272. sub sort_order {
  273. my ( $self, $columns, $ordinal ) = @_;
  274. # setup direction
  275. if ( $self->{direction} ) {
  276. if ( $self->{sort} eq $self->{oldsort} ) {
  277. if ( $self->{direction} eq 'ASC' ) {
  278. $self->{direction} = "DESC";
  279. }
  280. else {
  281. $self->{direction} = "ASC";
  282. }
  283. }
  284. }
  285. else {
  286. $self->{direction} = "ASC";
  287. }
  288. $self->{oldsort} = $self->{sort};
  289. my @a = $self->sort_columns( @{$columns} );
  290. if (%$ordinal) {
  291. $a[0] =
  292. ( $ordinal->{ $a[$_] } )
  293. ? "$ordinal->{$a[0]} $self->{direction}"
  294. : "$a[0] $self->{direction}";
  295. for ( 1 .. $#a ) {
  296. $a[$_] = $ordinal->{ $a[$_] } if $ordinal->{ $a[$_] };
  297. }
  298. }
  299. else {
  300. $a[0] .= " $self->{direction}";
  301. }
  302. $sortorder = join ',', @a;
  303. $sortorder;
  304. }
  305. sub format_amount {
  306. my ( $self, $myconfig, $amount, $places, $dash ) = @_;
  307. my $negative;
  308. if ($amount) {
  309. $amount = $self->parse_amount( $myconfig, $amount );
  310. $negative = ( $amount < 0 );
  311. $amount =~ s/-//;
  312. }
  313. if ( $places =~ /\d+/ ) {
  314. #$places = 4 if $places == 2;
  315. $amount = $self->round_amount( $amount, $places );
  316. }
  317. # is the amount negative
  318. # Parse $myconfig->{numberformat}
  319. my ( $ts, $ds ) = ( $1, $2 );
  320. if ($amount) {
  321. if ( $myconfig->{numberformat} ) {
  322. my ( $whole, $dec ) = split /\./, "$amount";
  323. $amount = join '', reverse split //, $whole;
  324. if ($places) {
  325. $dec .= "0" x $places;
  326. $dec = substr( $dec, 0, $places );
  327. }
  328. if ( $myconfig->{numberformat} eq '1,000.00' ) {
  329. $amount =~ s/\d{3,}?/$&,/g;
  330. $amount =~ s/,$//;
  331. $amount = join '', reverse split //, $amount;
  332. $amount .= "\.$dec" if ( $dec ne "" );
  333. }
  334. elsif ( $myconfig->{numberformat} eq '1 000.00' ) {
  335. $amount =~ s/\d{3,}?/$& /g;
  336. $amount =~ s/\s$//;
  337. $amount = join '', reverse split //, $amount;
  338. $amount .= "\.$dec" if ( $dec ne "" );
  339. }
  340. elsif ( $myconfig->{numberformat} eq "1'000.00" ) {
  341. $amount =~ s/\d{3,}?/$&'/g;
  342. $amount =~ s/'$//;
  343. $amount = join '', reverse split //, $amount;
  344. $amount .= "\.$dec" if ( $dec ne "" );
  345. }
  346. elsif ( $myconfig->{numberformat} eq '1.000,00' ) {
  347. $amount =~ s/\d{3,}?/$&./g;
  348. $amount =~ s/\.$//;
  349. $amount = join '', reverse split //, $amount;
  350. $amount .= ",$dec" if ( $dec ne "" );
  351. }
  352. elsif ( $myconfig->{numberformat} eq '1000,00' ) {
  353. $amount = "$whole";
  354. $amount .= ",$dec" if ( $dec ne "" );
  355. }
  356. elsif ( $myconfig->{numberformat} eq '1000.00' ) {
  357. $amount = "$whole";
  358. $amount .= ".$dec" if ( $dec ne "" );
  359. }
  360. if ( $dash =~ /-/ ) {
  361. $amount = ($negative) ? "($amount)" : "$amount";
  362. }
  363. elsif ( $dash =~ /DRCR/ ) {
  364. $amount = ($negative) ? "$amount DR" : "$amount CR";
  365. }
  366. else {
  367. $amount = ($negative) ? "-$amount" : "$amount";
  368. }
  369. }
  370. }
  371. else {
  372. if ( $dash eq "0" && $places ) {
  373. if ( $myconfig->{numberformat} =~ /0,00$/ ) {
  374. $amount = "0" . "," . "0" x $places;
  375. }
  376. else {
  377. $amount = "0" . "." . "0" x $places;
  378. }
  379. }
  380. else {
  381. $amount = ( $dash ne "" ) ? "$dash" : "";
  382. }
  383. }
  384. $amount;
  385. }
  386. sub parse_amount {
  387. my ( $self, $myconfig, $amount ) = @_;
  388. if ( ( $amount eq '' ) or ( ! defined $amount ) ) {
  389. $amount = 0;
  390. }
  391. if ( UNIVERSAL::isa( $amount, 'Math::BigFloat' ) )
  392. { # Amount may not be an object
  393. return $amount;
  394. }
  395. my $numberformat = $myconfig->{numberformat};
  396. if ( ( $numberformat eq '1.000,00' )
  397. || ( $numberformat eq '1000,00' ) )
  398. {
  399. $amount =~ s/\.//g;
  400. $amount =~ s/,/./;
  401. }
  402. elsif ( $numberformat eq '1 000.00' ) {
  403. $amount =~ s/\s//g;
  404. }
  405. elsif ( $numberformat eq "1'000.00" ) {
  406. $amount =~ s/'//g;
  407. }
  408. $amount =~ s/,//g;
  409. if ( $amount =~ s/\((\d*\.?\d*)\)/$1/ ) {
  410. $amount = $1 * -1;
  411. }
  412. elsif ( $amount =~ s/(\d*\.?\d*)\s?DR/$1/ ) {
  413. $amount = $1 * -1;
  414. }
  415. $amount =~ s/\s?CR//;
  416. $amount =~ /(\d*)\.(\d*)/;
  417. my $decimalplaces = length $1 + length $2;
  418. $amount = new Math::BigFloat($amount);
  419. return ( $amount * 1 );
  420. }
  421. sub round_amount {
  422. my ( $self, $amount, $places ) = @_;
  423. # These rounding rules follow from the previous implementation.
  424. # They should be changed to allow different rules for different accounts.
  425. Math::BigFloat->round_mode('+inf') if $amount >= 0;
  426. Math::BigFloat->round_mode('-inf') if $amount < 0;
  427. $amount = Math::BigFloat->new($amount)->ffround( -$places ) if $places >= 0;
  428. $amount = Math::BigFloat->new($amount)->ffround( -( $places - 1 ) )
  429. if $places < 0;
  430. $amount->precision(undef); #we are assuming whole cents so do not round
  431. #immediately on arithmatic. This is necessary
  432. #because Math::BigFloat is arithmatically
  433. #correct wrt accuracy and precision.
  434. return $amount;
  435. }
  436. sub db_parse_numeric {
  437. my $self = shift;
  438. my %args = @_;
  439. my ($sth, $arrayref, $hashref) = ($args{sth}, $args{arrayref},
  440. $args{hashref});
  441. my @types = @{$sth->{TYPE}};
  442. my @names = @{$sth->{NAME_lc}};
  443. for (0 .. $#names){
  444. if ($types[$_] == 3){
  445. $arrayref[$_] = Math::BigFloat->new($arrayref[$_])
  446. if defined $arrayref;
  447. $hashref->{$names[$_]} = Math::BigFloat->new($hashref->{$names[$_]})
  448. if defined $hashref;
  449. }
  450. }
  451. return ($hashref || $arrayref);
  452. }
  453. sub callproc {
  454. my $procname = shift @_;
  455. my $argstr = "";
  456. my @results;
  457. for ( 1 .. $#_ ) {
  458. $argstr .= "?, ";
  459. }
  460. $argstr =~ s/\, $//;
  461. $query = "SELECT * FROM $procname";
  462. $query =~ s/\(\)/$argstr/;
  463. my $sth = $self->{dbh}->prepare($query);
  464. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  465. push @results, $ref;
  466. }
  467. @results;
  468. }
  469. sub get_my_emp_num {
  470. my ( $self, $myconfig, $form ) = @_;
  471. %myconfig = %{$myconfig};
  472. my $dbh = $form->{dbh};
  473. # we got a connection, check the version
  474. my $query = qq|
  475. SELECT employeenumber FROM employee
  476. WHERE login = ?|;
  477. my $sth = $dbh->prepare($query);
  478. $sth->execute( $form->{login} ) || $form->dberror($query);
  479. $sth->execute;
  480. my ($id) = $sth->fetchrow_array;
  481. $sth->finish;
  482. $form->{'emp_num'} = $id;
  483. }
  484. sub format_string {
  485. my ( $self, @fields ) = @_;
  486. my $format = $self->{format};
  487. if ( $self->{format} =~ /(postscript|pdf)/ ) {
  488. $format = 'tex';
  489. }
  490. my %replace = (
  491. 'order' => {
  492. html => [ '<', '>', '\n', '\r' ],
  493. txt => [ '\n', '\r' ],
  494. tex => [
  495. quotemeta('\\'), '&', '\n', '\r',
  496. '\$', '%', '_', '#',
  497. quotemeta('^'), '{', '}', '<',
  498. '>', '£'
  499. ]
  500. },
  501. html => {
  502. '<' => '&lt;',
  503. '>' => '&gt;',
  504. '\n' => '<br />',
  505. '\r' => '<br />'
  506. },
  507. txt => { '\n' => "\n", '\r' => "\r" },
  508. tex => {
  509. '&' => '\&',
  510. '$' => '\$',
  511. '%' => '\%',
  512. '_' => '\_',
  513. '#' => '\#',
  514. quotemeta('^') => '\^\\',
  515. '{' => '\{',
  516. '}' => '\}',
  517. '<' => '$<$',
  518. '>' => '$>$',
  519. '\n' => '\newline ',
  520. '\r' => '\newline ',
  521. '£' => '\pounds ',
  522. quotemeta('\\') => '/'
  523. }
  524. );
  525. my $key;
  526. foreach $key ( @{ $replace{order}{$format} } ) {
  527. for (@fields) { $self->{$_} =~ s/$key/$replace{$format}{$key}/g }
  528. }
  529. }
  530. sub datetonum {
  531. my ( $self, $myconfig, $date, $picture ) = @_;
  532. if ( $date && $date =~ /\D/ ) {
  533. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  534. ( $yy, $mm, $dd ) = split /\D/, $date;
  535. }
  536. elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  537. ( $mm, $dd, $yy ) = split /\D/, $date;
  538. }
  539. elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  540. ( $dd, $mm, $yy ) = split /\D/, $date;
  541. }
  542. $dd *= 1;
  543. $mm *= 1;
  544. $yy += 2000 if length $yy == 2;
  545. $dd = substr( "0$dd", -2 );
  546. $mm = substr( "0$mm", -2 );
  547. $date = "$yy$mm$dd";
  548. }
  549. $date;
  550. }
  551. sub add_date {
  552. my ( $self, $myconfig, $date, $repeat, $unit ) = @_;
  553. my $diff = 0;
  554. my $spc = $myconfig->{dateformat};
  555. my $yy;
  556. my $mm;
  557. my $dd;
  558. $spc =~ s/\w//g;
  559. $spc = substr( $spc, 0, 1 );
  560. if ($date) {
  561. if ( $date =~ /\D/ ) {
  562. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  563. ( $yy, $mm, $dd ) = split /\D/, $date;
  564. }
  565. elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  566. ( $mm, $dd, $yy ) = split /\D/, $date;
  567. }
  568. elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  569. ( $dd, $mm, $yy ) = split /\D/, $date;
  570. }
  571. }
  572. else {
  573. # ISO
  574. ( $yy, $mm, $dd ) = ($date =~ /(....)(..)(..)/);
  575. }
  576. if ( $unit eq 'days' ) {
  577. $diff = $repeat * 86400;
  578. }
  579. elsif ( $unit eq 'weeks' ) {
  580. $diff = $repeat * 604800;
  581. }
  582. elsif ( $unit eq 'months' ) {
  583. $diff = $mm + $repeat;
  584. my $whole = int( $diff / 12 );
  585. $yy += $whole;
  586. $mm = ( $diff % 12 );
  587. $mm = '12' if $mm == 0;
  588. $yy-- if $mm == 12;
  589. $diff = 0;
  590. }
  591. elsif ( $unit eq 'years' ) {
  592. $yy += $repeat;
  593. }
  594. $mm--;
  595. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yy ) + $diff );
  596. $t[4]++;
  597. $mm = substr( "0$t[4]", -2 );
  598. $dd = substr( "0$t[3]", -2 );
  599. $yy = $t[5] + 1900;
  600. if ( $date =~ /\D/ ) {
  601. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  602. $date = "$yy$spc$mm$spc$dd";
  603. }
  604. elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  605. $date = "$mm$spc$dd$spc$yy";
  606. }
  607. elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  608. $date = "$dd$spc$mm$spc$yy";
  609. }
  610. }
  611. else {
  612. $date = "$yy$mm$dd";
  613. }
  614. }
  615. $date;
  616. }
  617. sub print_button {
  618. my ( $self, $button, $name ) = @_;
  619. print
  620. 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|;
  621. }
  622. # Database routines used throughout
  623. sub db_init {
  624. my ( $self, $myconfig ) = @_;
  625. $self->{dbh} = $self->dbconnect_noauto($myconfig) || $self->dberror();
  626. %date_query = (
  627. 'mm/dd/yy' => 'set DateStyle to \'SQL, US\'',
  628. 'mm-dd-yy' => 'set DateStyle to \'POSTGRES, US\'',
  629. 'dd/mm/yy' => 'set DateStyle to \'SQL, EUROPEAN\'',
  630. 'dd-mm-yy' => 'set DateStyle to \'POSTGRES, EUROPEAN\'',
  631. 'dd.mm.yy' => 'set DateStyle to \'GERMAN\''
  632. );
  633. $self->{dbh}->do( $date_query{ $myconfig->{dateformat} } );
  634. $self->{db_dateformat} = $myconfig->{dateformat}; #shim
  635. my $query = "SELECT t.extends,
  636. coalesce (t.table_name, 'custom_' || extends)
  637. || ':' || f.field_name as field_def
  638. FROM custom_table_catalog t
  639. JOIN custom_field_catalog f USING (table_id)";
  640. my $sth = $self->{dbh}->prepare($query);
  641. $sth->execute;
  642. my $ref;
  643. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  644. push @{ $self->{custom_db_fields}{ $ref->{extends} } },
  645. $ref->{field_def};
  646. }
  647. }
  648. sub run_custom_queries {
  649. my ( $self, $tablename, $query_type, $linenum ) = @_;
  650. my $dbh = $self->{dbh};
  651. if ( $query_type !~ /^(select|insert|update)$/i ) {
  652. $self->error(
  653. $locale->text(
  654. "Passed incorrect query type to run_custom_queries."
  655. )
  656. );
  657. }
  658. my @rc;
  659. my %temphash;
  660. my @templist;
  661. my @elements;
  662. my $query;
  663. my $ins_values;
  664. if ($linenum) {
  665. $linenum = "_$linenum";
  666. }
  667. $query_type = uc($query_type);
  668. for ( @{ $self->{custom_db_fields}{$tablename} } ) {
  669. @elements = split( /:/, $_ );
  670. push @{ $temphash{ $elements[0] } }, $elements[1];
  671. }
  672. for ( keys %temphash ) {
  673. my @data;
  674. my $ins_values;
  675. $query = "$query_type ";
  676. if ( $query_type eq 'UPDATE' ) {
  677. $query = "DELETE FROM $_ WHERE row_id = ?";
  678. my $sth = $dbh->prepare($query);
  679. $sth->execute( $self->{ "id" . "$linenum" } )
  680. || $self->dberror($query);
  681. }
  682. elsif ( $query_type eq 'INSERT' ) {
  683. $query .= " INTO $_ (";
  684. }
  685. my $first = 1;
  686. for ( @{ $temphash{$_} } ) {
  687. $query .= "$_";
  688. if ( $query_type eq 'UPDATE' ) {
  689. $query .= '= ?';
  690. }
  691. $ins_values .= "?, ";
  692. $query .= ", ";
  693. $first = 0;
  694. if ( $query_type eq 'UPDATE' or $query_type eq 'INSERT' ) {
  695. push @data, $self->{"$_$linenum"};
  696. }
  697. }
  698. if ( $query_type ne 'INSERT' ) {
  699. $query =~ s/, $//;
  700. }
  701. if ( $query_type eq 'SELECT' ) {
  702. $query .= " FROM $_";
  703. }
  704. if ( $query_type eq 'SELECT' or $query_type eq 'UPDATE' ) {
  705. $query .= " WHERE row_id = ?";
  706. }
  707. if ( $query_type eq 'INSERT' ) {
  708. $query .= " row_id) VALUES ($ins_values ?)";
  709. }
  710. if ( $query_type eq 'SELECT' ) {
  711. push @rc, [$query];
  712. }
  713. else {
  714. unshift( @data, $query );
  715. push @rc, [@data];
  716. }
  717. }
  718. if ( $query_type eq 'INSERT' ) {
  719. for (@rc) {
  720. $query = shift( @{$_} );
  721. $sth = $dbh->prepare($query)
  722. || $self->db_error($query);
  723. $sth->execute( @{$_}, $self->{id} )
  724. || $self->dberror($query);
  725. $sth->finish;
  726. $did_insert = 1;
  727. }
  728. }
  729. elsif ( $query_type eq 'UPDATE' ) {
  730. @rc = $self->run_custom_queries( $tablename, 'INSERT', $linenum );
  731. }
  732. elsif ( $query_type eq 'SELECT' ) {
  733. for (@rc) {
  734. $query = shift @{$_};
  735. $sth = $self->{dbh}->prepare($query);
  736. $sth->execute( $self->{id} );
  737. $ref = $sth->fetchrow_hashref(NAME_lc);
  738. for ( keys %{$ref} ) {
  739. $self->{$_} = $ref->{$_};
  740. }
  741. }
  742. }
  743. @rc;
  744. }
  745. sub dbconnect {
  746. my ( $self, $myconfig ) = @_;
  747. # connect to database
  748. my $dbh = DBI->connect( $myconfig->{dbconnect},
  749. $myconfig->{dbuser}, $myconfig->{dbpasswd} )
  750. or $self->dberror;
  751. $dbh->{pg_enable_utf8} = 1;
  752. # set db options
  753. if ( $myconfig->{dboptions} ) {
  754. $dbh->do( $myconfig->{dboptions} )
  755. || $self->dberror( $myconfig->{dboptions} );
  756. }
  757. $dbh;
  758. }
  759. sub dbconnect_noauto {
  760. my ( $self, $myconfig ) = @_;
  761. # connect to database
  762. $dbh = DBI->connect(
  763. $myconfig->{dbconnect}, $myconfig->{dbuser},
  764. $myconfig->{dbpasswd}, { AutoCommit => 0 }
  765. ) or $self->dberror;
  766. $dbh->{pg_enable_utf8} = 1;
  767. # set db options
  768. if ( $myconfig->{dboptions} ) {
  769. $dbh->do( $myconfig->{dboptions} );
  770. }
  771. $dbh;
  772. }
  773. sub dbquote {
  774. my ( $self, $var ) = @_;
  775. if ( $var eq '' ) {
  776. $_ = "NULL";
  777. }
  778. else {
  779. $_ = $self->{dbh}->quote($var);
  780. }
  781. $_;
  782. }
  783. sub update_balance {
  784. # This is a dangerous private function. All apps calling it must
  785. # be careful to avoid SQL injection issues
  786. my ( $self, $dbh, $table, $field, $where, $value ) = @_;
  787. # if we have a value, go do it
  788. if ($value) {
  789. # retrieve balance from table
  790. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  791. my ($balance) = $dbh->selectrow_array($query);
  792. $balance += $value;
  793. # update balance
  794. $query = "UPDATE $table SET $field = $balance WHERE $where";
  795. $dbh->do($query) || $self->dberror($query);
  796. }
  797. }
  798. sub update_exchangerate {
  799. my ( $self, $dbh, $curr, $transdate, $buy, $sell ) = @_;
  800. # some sanity check for currency
  801. return if ( $curr eq "" );
  802. my $query = qq|
  803. SELECT curr
  804. FROM exchangerate
  805. WHERE curr = ?
  806. AND transdate = ?
  807. FOR UPDATE|;
  808. my $sth = $self->{dbh}->prepare($query);
  809. $sth->execute( $curr, $transdate ) || $self->dberror($query);
  810. my $set;
  811. my @queryargs;
  812. if ( $buy && $sell ) {
  813. $set = "buy = ?, sell = ?";
  814. @queryargs = ( $buy, $sell );
  815. }
  816. elsif ($buy) {
  817. $set = "buy = ?";
  818. @queryargs = ($buy);
  819. }
  820. elsif ($sell) {
  821. $set = "sell = ?";
  822. @queryargs = ($sell);
  823. }
  824. if ( !$set ) {
  825. $self->error("Exchange rate missing!");
  826. }
  827. if ( $sth->fetchrow_array ) {
  828. $query = qq|UPDATE exchangerate
  829. SET $set
  830. WHERE curr = ?
  831. AND transdate = ?|;
  832. push( @queryargs, $curr, $transdate );
  833. }
  834. else {
  835. $query = qq|
  836. INSERT INTO exchangerate (
  837. curr, buy, sell, transdate)
  838. VALUES (?, ?, ?, ?)|;
  839. @queryargs = ( $curr, $buy, $sell, $transdate );
  840. }
  841. $sth->finish;
  842. $sth = $self->{dbh}->prepare($query);
  843. $sth->execute(@queryargs) || $self->dberror($query);
  844. }
  845. sub save_exchangerate {
  846. my ( $self, $myconfig, $currency, $transdate, $rate, $fld ) = @_;
  847. my ( $buy, $sell ) = ( 0, 0 );
  848. $buy = $rate if $fld eq 'buy';
  849. $sell = $rate if $fld eq 'sell';
  850. $self->update_exchangerate( $self->{dbh}, $currency, $transdate, $buy,
  851. $sell );
  852. }
  853. sub get_exchangerate {
  854. my ( $self, $dbh, $curr, $transdate, $fld ) = @_;
  855. my $exchangerate = 1;
  856. if ($transdate) {
  857. my $query = qq|
  858. SELECT $fld FROM exchangerate
  859. WHERE curr = ? AND transdate = ?|;
  860. $sth = $self->{dbh}->prepare($query);
  861. $sth->execute( $curr, $transdate );
  862. ($exchangerate) = $sth->fetchrow_array;
  863. $exchangerate = Math::BigFloat->new($exchangerate);
  864. }
  865. $sth->finish;
  866. $exchangerate;
  867. }
  868. sub check_exchangerate {
  869. my ( $self, $myconfig, $currency, $transdate, $fld ) = @_;
  870. return "" unless $transdate;
  871. my $query = qq|
  872. SELECT $fld
  873. FROM exchangerate
  874. WHERE curr = ? AND transdate = ?|;
  875. my $sth = $self->{dbh}->prepare($query);
  876. $sth->execute( $currenct, $transdate );
  877. my ($exchangerate) = $sth->fetchrow_array;
  878. $sth->finish;
  879. $exchangerate;
  880. }
  881. sub add_shipto {
  882. my ( $self, $dbh, $id ) = @_;
  883. my $shipto;
  884. foreach my $item (
  885. qw(name address1 address2 city state
  886. zipcode country contact phone fax email)
  887. )
  888. {
  889. if ( $self->{"shipto$item"} ne "" ) {
  890. $shipto = 1 if ( $self->{$item} ne $self->{"shipto$item"} );
  891. }
  892. }
  893. if ($shipto) {
  894. my $query = qq|
  895. INSERT INTO shipto
  896. (trans_id, shiptoname, shiptoaddress1,
  897. shiptoaddress2, shiptocity, shiptostate,
  898. shiptozipcode, shiptocountry, shiptocontact,
  899. shiptophone, shiptofax, shiptoemail)
  900. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  901. |;
  902. $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  903. $sth->execute(
  904. $id, $self->{shiptoname},
  905. $self->{shiptoaddress1}, $self->{shiptoaddress2},
  906. $self->{shiptocity}, $self->{shiptostate},
  907. $self->{shiptozipcode}, $self->{shiptocountry},
  908. $self->{shiptocontact}, $self->{shiptophone},
  909. $self->{shiptofax}, $self->{shiptoemail}
  910. ) || $self->dberror($query);
  911. $sth->finish;
  912. }
  913. }
  914. sub get_employee {
  915. my ( $self, $dbh ) = @_;
  916. my $login = $self->{login};
  917. $login =~ s/@.*//;
  918. my $query = qq|
  919. SELECT name, id
  920. FROM entity WHERE id IN (select entity_id
  921. FROM employee
  922. WHERE login = ?)|;
  923. $sth = $self->{dbh}->prepare($query);
  924. $sth->execute($login);
  925. my (@a) = $sth->fetchrow_array();
  926. $a[1] *= 1;
  927. $sth->finish;
  928. @a;
  929. }
  930. # this sub gets the id and name from $table
  931. sub get_name {
  932. my ( $self, $myconfig, $table, $transdate ) = @_;
  933. # connect to database
  934. my @queryargs;
  935. my $where;
  936. if ($transdate) {
  937. $where = qq|
  938. AND (startdate IS NULL OR startdate <= ?)
  939. AND (enddate IS NULL OR enddate >= ?)|;
  940. @queryargs = ( $transdate, $transdate );
  941. }
  942. my $name = $self->like( lc $self->{$table} );
  943. my $query = qq|
  944. SELECT * FROM $table
  945. WHERE (lower(name) LIKE ? OR ${table}number LIKE ?)
  946. $where
  947. ORDER BY name|;
  948. unshift( @queryargs, $name, $name );
  949. my $sth = $self->{dbh}->prepare($query);
  950. $sth->execute(@queryargs) || $self->dberror($query);
  951. my $i = 0;
  952. @{ $self->{name_list} } = ();
  953. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  954. push( @{ $self->{name_list} }, $ref );
  955. $i++;
  956. }
  957. $sth->finish;
  958. $i;
  959. }
  960. sub all_vc {
  961. my ( $self, $myconfig, $vc, $module, $dbh, $transdate, $job ) = @_;
  962. my $ref;
  963. my $disconnect = 0;
  964. $dbh = $self->{dbh};
  965. my $sth;
  966. my $query = qq|SELECT count(*) FROM $vc|;
  967. my $where;
  968. my @queryargs = ();
  969. if ($transdate) {
  970. $query .= qq| WHERE (startdate IS NULL OR startdate <= ?)
  971. AND (enddate IS NULL OR enddate >= ?)|;
  972. @queryargs = ( $transdate, $transdate );
  973. }
  974. $sth = $dbh->prepare($query);
  975. $sth->execute(@queryargs);
  976. my ($count) = $sth->fetchrow_array;
  977. $sth->finish;
  978. @queryargs = ();
  979. # build selection list
  980. if ( $count < $myconfig->{vclimit} ) {
  981. $self->{"${vc}_id"} *= 1;
  982. $where = "AND $where" if $where;
  983. $query = qq|SELECT id, name
  984. FROM entity
  985. WHERE id IN (select entity_id
  986. FROM $vc)
  987. $where
  988. UNION
  989. SELECT id,name
  990. FROM entity
  991. WHERE id = ?
  992. ORDER BY name|;
  993. push( @queryargs, $self->{"${vc}_id"} );
  994. $sth = $dbh->prepare($query);
  995. $sth->execute(@queryargs) || $self->dberror($query);
  996. @{ $self->{"all_$vc"} } = ();
  997. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  998. push @{ $self->{"all_$vc"} }, $ref;
  999. }
  1000. $sth->finish;
  1001. }
  1002. # get self
  1003. if ( !$self->{employee_id} ) {
  1004. ( $self->{employee}, $self->{employee_id} ) = split /--/,
  1005. $self->{employee};
  1006. ( $self->{employee}, $self->{employee_id} ) = $self->get_employee($dbh)
  1007. unless $self->{employee_id};
  1008. }
  1009. $self->all_employees( $myconfig, $dbh, $transdate, 1 );
  1010. $self->all_departments( $myconfig, $dbh, $vc );
  1011. $self->all_projects( $myconfig, $dbh, $transdate, $job );
  1012. # get language codes
  1013. $query = qq|SELECT *
  1014. FROM language
  1015. ORDER BY 2|;
  1016. $sth = $dbh->prepare($query);
  1017. $sth->execute || $self->dberror($query);
  1018. $self->{all_language} = ();
  1019. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1020. push @{ $self->{all_language} }, $ref;
  1021. }
  1022. $sth->finish;
  1023. $self->all_taxaccounts( $myconfig, $dbh, $transdate );
  1024. }
  1025. sub all_taxaccounts {
  1026. my ( $self, $myconfig, $dbh2, $transdate ) = @_;
  1027. my $dbh = $self->{dbh};
  1028. my $sth;
  1029. my $query;
  1030. my $where;
  1031. my @queryargs = ();
  1032. if ($transdate) {
  1033. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1034. push( @queryargs, $transdate );
  1035. }
  1036. if ( $self->{taxaccounts} ) {
  1037. # rebuild tax rates
  1038. $query = qq|SELECT t.rate, t.taxnumber
  1039. FROM tax t
  1040. JOIN chart c ON (c.id = t.chart_id)
  1041. WHERE c.accno = ?
  1042. $where
  1043. ORDER BY accno, validto|;
  1044. $sth = $dbh->prepare($query) || $self->dberror($query);
  1045. foreach my $accno ( split / /, $self->{taxaccounts} ) {
  1046. $sth->execute( $accno, @queryargs );
  1047. ( $self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"} ) =
  1048. $sth->fetchrow_array;
  1049. $sth->finish;
  1050. }
  1051. }
  1052. }
  1053. sub all_employees {
  1054. my ( $self, $myconfig, $dbh2, $transdate, $sales ) = @_;
  1055. my $dbh = $self->{dbh};
  1056. my @whereargs = ();
  1057. # setup employees/sales contacts
  1058. my $query = qq|
  1059. SELECT id, name
  1060. FROM entity
  1061. WHERE id IN (SELECT entity_id FROM employee
  1062. WHERE|;
  1063. if ($transdate) {
  1064. $query .= qq| (startdate IS NULL OR startdate <= ?)
  1065. AND (enddate IS NULL OR enddate >= ?) AND|;
  1066. @whereargs = ( $transdate, $transdate );
  1067. }
  1068. else {
  1069. $query .= qq| enddate IS NULL AND|;
  1070. }
  1071. if ($sales) {
  1072. $query .= qq| sales = '1' AND|;
  1073. }
  1074. $query =~ s/(WHERE|AND)$//;
  1075. $query .= qq|) ORDER BY name|;
  1076. my $sth = $dbh->prepare($query);
  1077. $sth->execute(@whereargs) || $self->dberror($query);
  1078. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1079. push @{ $self->{all_employee} }, $ref;
  1080. }
  1081. $sth->finish;
  1082. }
  1083. sub all_projects {
  1084. my ( $self, $myconfig, $dbh2, $transdate, $job ) = @_;
  1085. my $dbh = $self->{dbh};
  1086. my @queryargs = ();
  1087. my $where = "1 = 1";
  1088. $where = qq|id NOT IN (SELECT id
  1089. FROM parts
  1090. WHERE project_id > 0)| if !$job;
  1091. my $query = qq|SELECT *
  1092. FROM project
  1093. WHERE $where|;
  1094. if ( $self->{language_code} ) {
  1095. $query = qq|
  1096. SELECT pr.*, t.description AS translation
  1097. FROM project pr
  1098. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1099. WHERE t.language_code = ?|;
  1100. push( @queryargs, $self->{language_code} );
  1101. }
  1102. if ($transdate) {
  1103. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1104. AND (enddate IS NULL OR enddate >= ?)|;
  1105. push( @queryargs, $transdate, $transdate );
  1106. }
  1107. $query .= qq| ORDER BY projectnumber|;
  1108. $sth = $dbh->prepare($query);
  1109. $sth->execute(@queryargs) || $self->dberror($query);
  1110. @{ $self->{all_project} } = ();
  1111. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1112. push @{ $self->{all_project} }, $ref;
  1113. }
  1114. $sth->finish;
  1115. }
  1116. sub all_departments {
  1117. my ( $self, $myconfig, $dbh2, $vc ) = @_;
  1118. $dbh = $self->{dbh};
  1119. my $where = "1 = 1";
  1120. if ($vc) {
  1121. if ( $vc eq 'customer' ) {
  1122. $where = " role = 'P'";
  1123. }
  1124. }
  1125. my $query = qq|SELECT id, description
  1126. FROM department
  1127. WHERE $where
  1128. ORDER BY 2|;
  1129. my $sth = $dbh->prepare($query);
  1130. $sth->execute || $self->dberror($query);
  1131. @{ $self->{all_department} } = ();
  1132. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1133. push @{ $self->{all_department} }, $ref;
  1134. }
  1135. $sth->finish;
  1136. $self->all_years($myconfig);
  1137. }
  1138. sub all_years {
  1139. my ( $self, $myconfig, $dbh2 ) = @_;
  1140. $dbh = $self->{dbh};
  1141. # get years
  1142. my $query = qq|
  1143. SELECT (SELECT transdate FROM acc_trans ORDER BY transdate asc
  1144. LIMIT 1),
  1145. (SELECT transdate FROM acc_trans ORDER BY transdate desc
  1146. LIMIT 1)|;
  1147. my ( $startdate, $enddate ) = $dbh->selectrow_array($query);
  1148. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1149. ($startdate) = split /\W/, $startdate;
  1150. ($enddate) = split /\W/, $enddate;
  1151. }
  1152. else {
  1153. (@_) = split /\W/, $startdate;
  1154. $startdate = $_[2];
  1155. (@_) = split /\W/, $enddate;
  1156. $enddate = $_[2];
  1157. }
  1158. $self->{all_years} = ();
  1159. $startdate = substr( $startdate, 0, 4 );
  1160. $enddate = substr( $enddate, 0, 4 );
  1161. while ( $enddate >= $startdate ) {
  1162. push @{ $self->{all_years} }, $enddate--;
  1163. }
  1164. #this should probably be changed to use locale
  1165. %{ $self->{all_month} } = (
  1166. '01' => 'January',
  1167. '02' => 'February',
  1168. '03' => 'March',
  1169. '04' => 'April',
  1170. '05' => 'May ',
  1171. '06' => 'June',
  1172. '07' => 'July',
  1173. '08' => 'August',
  1174. '09' => 'September',
  1175. '10' => 'October',
  1176. '11' => 'November',
  1177. '12' => 'December'
  1178. );
  1179. }
  1180. sub create_links {
  1181. my ( $self, $module, $myconfig, $vc, $job ) = @_;
  1182. # get last customers or vendors
  1183. my ( $query, $sth );
  1184. if (!$self->{dbh}) {
  1185. $self->db_init($myconfig);
  1186. }
  1187. $dbh = $self->{dbh};
  1188. my %xkeyref = ();
  1189. # now get the account numbers
  1190. $query = qq|SELECT accno, description, link
  1191. FROM chart
  1192. WHERE link LIKE ?
  1193. ORDER BY accno|;
  1194. $sth = $dbh->prepare($query);
  1195. $sth->execute( "%" . "$module%" ) || $self->dberror($query);
  1196. $self->{accounts} = "";
  1197. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1198. foreach my $key ( split /:/, $ref->{link} ) {
  1199. if ( $key =~ /$module/ ) {
  1200. # cross reference for keys
  1201. $xkeyref{ $ref->{accno} } = $key;
  1202. push @{ $self->{"${module}_links"}{$key} },
  1203. {
  1204. accno => $ref->{accno},
  1205. description => $ref->{description}
  1206. };
  1207. $self->{accounts} .= "$ref->{accno} "
  1208. unless $key =~ /tax/;
  1209. }
  1210. }
  1211. }
  1212. $sth->finish;
  1213. my $arap = ( $vc eq 'customer' ) ? 'ar' : 'ap';
  1214. if ( $self->{id} ) {
  1215. $query = qq|
  1216. SELECT a.invnumber, a.transdate,
  1217. a.${vc}_id, a.datepaid, a.duedate, a.ordnumber,
  1218. a.taxincluded, a.curr AS currency, a.notes,
  1219. a.intnotes, c.name AS $vc, a.department_id,
  1220. d.description AS department,
  1221. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1222. a.employee_id, e.name AS employee,
  1223. c.language_code, a.ponumber
  1224. FROM $arap a
  1225. JOIN $vc c ON (a.${vc}_id = c.id)
  1226. LEFT JOIN employee e ON (e.id = a.employee_id)
  1227. LEFT JOIN department d ON (d.id = a.department_id)
  1228. WHERE a.id = ?|;
  1229. $sth = $dbh->prepare($query);
  1230. $sth->execute( $self->{id} ) || $self->dberror($query);
  1231. $ref = $sth->fetchrow_hashref(NAME_lc);
  1232. $self->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1233. foreach $key ( keys %$ref ) {
  1234. $self->{$key} = $ref->{$key};
  1235. }
  1236. $sth->finish;
  1237. # get printed, emailed
  1238. $query = qq|
  1239. SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1240. FROM status s WHERE s.trans_id = ?|;
  1241. $sth = $dbh->prepare($query);
  1242. $sth->execute( $self->{id} ) || $self->dberror($query);
  1243. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1244. $self->{printed} .= "$ref->{formname} "
  1245. if $ref->{printed};
  1246. $self->{emailed} .= "$ref->{formname} "
  1247. if $ref->{emailed};
  1248. $self->{queued} .= "$ref->{formname} " . "$ref->{spoolfile} "
  1249. if $ref->{spoolfile};
  1250. }
  1251. $sth->finish;
  1252. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1253. # get recurring
  1254. $self->get_recurring($dbh);
  1255. # get amounts from individual entries
  1256. $query = qq|
  1257. SELECT c.accno, c.description, a.source, a.amount,
  1258. a.memo, a.transdate, a.cleared, a.project_id,
  1259. p.projectnumber
  1260. FROM acc_trans a
  1261. JOIN chart c ON (c.id = a.chart_id)
  1262. LEFT JOIN project p ON (p.id = a.project_id)
  1263. WHERE a.trans_id = ?
  1264. AND a.fx_transaction = '0'
  1265. ORDER BY transdate|;
  1266. $sth = $dbh->prepare($query);
  1267. $sth->execute( $self->{id} ) || $self->dberror($query);
  1268. my $fld = ( $vc eq 'customer' ) ? 'buy' : 'sell';
  1269. $self->{exchangerate} =
  1270. $self->get_exchangerate( $dbh, $self->{currency}, $self->{transdate},
  1271. $fld );
  1272. # store amounts in {acc_trans}{$key} for multiple accounts
  1273. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1274. $ref->{exchangerate} =
  1275. $self->get_exchangerate( $dbh, $self->{currency},
  1276. $ref->{transdate}, $fld );
  1277. push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
  1278. }
  1279. $sth->finish;
  1280. }
  1281. else {
  1282. if ( !$self->{"$self->{vc}_id"} ) {
  1283. $self->lastname_used( $myconfig, $dbh, $vc, $module );
  1284. }
  1285. }
  1286. for (qw(current_date curr closedto revtrans)) {
  1287. if ($_ eq 'closedto'){
  1288. $query = qq|
  1289. SELECT value::date FROM defaults
  1290. WHERE setting_key = '$_'|;
  1291. } elsif ($_ eq 'current_date') {
  1292. $query = qq| select $_|;
  1293. } else {
  1294. $query = qq|
  1295. SELECT value FROM defaults
  1296. WHERE setting_key = '$_'|;
  1297. }
  1298. $sth = $dbh->prepare($query);
  1299. $sth->execute || $self->dberror($query);
  1300. ($val) = $sth->fetchrow_array();
  1301. if ( $_ eq 'curr' ) {
  1302. $self->{currencies} = $val;
  1303. }
  1304. else {
  1305. $self->{$_} = $val;
  1306. }
  1307. $sth->finish;
  1308. }
  1309. if (!$self->{id}){
  1310. $self->{transdate} = $self->{current_date};
  1311. }
  1312. $self->all_vc( $myconfig, $vc, $module, $dbh, $self->{transdate}, $job );
  1313. }
  1314. sub lastname_used {
  1315. my ( $self, $myconfig, $dbh2, $vc, $module ) = @_;
  1316. my $dbh = $self->{dbh};
  1317. $vc ||= $self->{vc}; # add default to correct for improper passing
  1318. my $arap = ( $vc eq 'customer' ) ? "ar" : "ap";
  1319. my $sth;
  1320. if ( $self->{type} =~ /_order/ ) {
  1321. $arap = 'oe';
  1322. $where = "quotation = '0'";
  1323. }
  1324. if ( $self->{type} =~ /_quotation/ ) {
  1325. $arap = 'oe';
  1326. $where = "quotation = '1'";
  1327. }
  1328. $where = "AND $where " if $where;
  1329. $inv_notes = "ct.invoice_notes," if $vc eq 'customer';
  1330. my $query = qq|
  1331. SELECT entity.name, ct.curr AS currency, ct.id AS ${vc}_id,
  1332. current_date + ct.terms AS duedate,
  1333. $inv_notes
  1334. ct.curr AS currency
  1335. FROM $vc ct
  1336. JOIN entity ON (ct.entity_id = entity.id)
  1337. WHERE entity.id = (select entity_id from $arap
  1338. where entity_id IS NOT NULL $where
  1339. order by id DESC limit 1)|;
  1340. $sth = $dbh->prepare($query);
  1341. $sth->execute() || $self->dberror($query);
  1342. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1343. for ( keys %$ref ) { $self->{$_} = $ref->{$_} }
  1344. $sth->finish;
  1345. }
  1346. sub current_date {
  1347. my ( $self, $myconfig, $thisdate, $days ) = @_;
  1348. my $dbh = $self->{dbh};
  1349. my $query;
  1350. $days *= 1;
  1351. if ($thisdate) {
  1352. my $dateformat = $myconfig->{dateformat};
  1353. if ( $myconfig->{dateformat} !~ /^y/ ) {
  1354. my @a = split /\D/, $thisdate;
  1355. $dateformat .= "yy" if ( length $a[2] > 2 );
  1356. }
  1357. if ( $thisdate !~ /\D/ ) {
  1358. $dateformat = 'yyyymmdd';
  1359. }
  1360. $query = qq|SELECT (to_date(?, ?)
  1361. + ?::interval)::date AS thisdate|;
  1362. @queryargs = ( $thisdate, $dateformat, sprintf('%d days', $days) );
  1363. }
  1364. else {
  1365. $query = qq|SELECT current_date AS thisdate|;
  1366. @queryargs = ();
  1367. }
  1368. $sth = $dbh->prepare($query);
  1369. $sth->execute(@queryargs);
  1370. ($thisdate) = $sth->fetchrow_array;
  1371. $thisdate;
  1372. }
  1373. sub like {
  1374. my ( $self, $str ) = @_;
  1375. "%$str%";
  1376. }
  1377. sub redo_rows {
  1378. my ( $self, $flds, $new, $count, $numrows ) = @_;
  1379. my @ndx = ();
  1380. for ( 1 .. $count ) {
  1381. push @ndx, { num => $new->[ $_ - 1 ]->{runningnumber}, ndx => $_ };
  1382. }
  1383. my $i = 0;
  1384. # fill rows
  1385. foreach my $item ( sort { $a->{num} <=> $b->{num} } @ndx ) {
  1386. $i++;
  1387. $j = $item->{ndx} - 1;
  1388. for ( @{$flds} ) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1389. }
  1390. # delete empty rows
  1391. for $i ( $count + 1 .. $numrows ) {
  1392. for ( @{$flds} ) { delete $self->{"${_}_$i"} }
  1393. }
  1394. }
  1395. sub get_partsgroup {
  1396. my ( $self, $myconfig, $p ) = @_;
  1397. my $dbh = $self->{dbh};
  1398. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1399. FROM partsgroup pg
  1400. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1401. my $where;
  1402. my $sortorder = "partsgroup";
  1403. if ( $p->{searchitems} eq 'part' ) {
  1404. $where = qq| WHERE (p.inventory_accno_id > 0
  1405. AND p.income_accno_id > 0)|;
  1406. }
  1407. if ( $p->{searchitems} eq 'service' ) {
  1408. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1409. }
  1410. if ( $p->{searchitems} eq 'assembly' ) {
  1411. $where = qq| WHERE p.assembly = '1'|;
  1412. }
  1413. if ( $p->{searchitems} eq 'labor' ) {
  1414. $where =
  1415. qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1416. }
  1417. if ( $p->{searchitems} eq 'nolabor' ) {
  1418. $where = qq| WHERE p.income_accno_id > 0|;
  1419. }
  1420. if ( $p->{all} ) {
  1421. $query = qq|SELECT id, partsgroup
  1422. FROM partsgroup|;
  1423. }
  1424. my @queryargs = ();
  1425. if ( $p->{language_code} ) {
  1426. $sortorder = "translation";
  1427. $query = qq|
  1428. SELECT DISTINCT pg.id, pg.partsgroup,
  1429. t.description AS translation
  1430. FROM partsgroup pg
  1431. JOIN parts p ON (p.partsgroup_id = pg.id)
  1432. LEFT JOIN translation t ON (t.trans_id = pg.id
  1433. AND t.language_code = ?)|;
  1434. @queryargs = ( $p->{language_code} );
  1435. }
  1436. $query .= qq| $where ORDER BY $sortorder|;
  1437. my $sth = $dbh->prepare($query);
  1438. $sth->execute(@queryargs) || $self->dberror($query);
  1439. $self->{all_partsgroup} = ();
  1440. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1441. push @{ $self->{all_partsgroup} }, $ref;
  1442. }
  1443. $sth->finish;
  1444. }
  1445. sub update_status {
  1446. my ( $self, $myconfig ) = @_;
  1447. # no id return
  1448. return unless $self->{id};
  1449. my $dbh = $self->{dbh};
  1450. my %queued = split / +/, $self->{queued};
  1451. my $spoolfile =
  1452. ( $queued{ $self->{formname} } )
  1453. ? "'$queued{$self->{formname}}'"
  1454. : 'NULL';
  1455. my $query = qq|DELETE FROM status
  1456. WHERE formname = ?
  1457. AND trans_id = ?|;
  1458. $sth = $dbh->prepare($query);
  1459. $sth->execute( $self->{formname}, $self->{id} ) || $self->dberror($query);
  1460. $sth->finish;
  1461. my $printed = ( $self->{printed} =~ /$self->{formname}/ ) ? "1" : "0";
  1462. my $emailed = ( $self->{emailed} =~ /$self->{formname}/ ) ? "1" : "0";
  1463. $query = qq|
  1464. INSERT INTO status
  1465. (trans_id, printed, emailed, spoolfile, formname)
  1466. VALUES (?, ?, ?, ?, ?)|;
  1467. $sth = $dbh->prepare($query);
  1468. $sth->execute( $self->{id}, $printed, $emailed, $spoolfile,
  1469. $self->{formname} );
  1470. $sth->finish;
  1471. }
  1472. sub save_status {
  1473. my ($self) = @_;
  1474. $dbh = $self->{dbh};
  1475. my $formnames = $self->{printed};
  1476. my $emailforms = $self->{emailed};
  1477. my $query = qq|DELETE FROM status
  1478. WHERE trans_id = ?|;
  1479. my $sth = $dbh->prepare($query);
  1480. $sth->execute( $self->{id} );
  1481. $sth->finish;
  1482. my %queued;
  1483. my $formname;
  1484. if ( $self->{queued} ) {
  1485. %queued = split / +/, $self->{queued};
  1486. foreach $formname ( keys %queued ) {
  1487. $printed = ( $self->{printed} =~ /$formname/ ) ? "1" : "0";
  1488. $emailed = ( $self->{emailed} =~ /$formname/ ) ? "1" : "0";
  1489. if ( $queued{$formname} ) {
  1490. $query = qq|
  1491. INSERT INTO status
  1492. (trans_id, printed, emailed,
  1493. spoolfile, formname)
  1494. VALUES (?, ?, ?, ?, ?)|;
  1495. $sth = $dbh->prepare($query);
  1496. $sth->execute( $self->{id}, $pinted, $emailed,
  1497. $queued{$formname}, $formname )
  1498. || $self->dberror($query);
  1499. $sth->finish;
  1500. }
  1501. $formnames =~ s/$formname//;
  1502. $emailforms =~ s/$formname//;
  1503. }
  1504. }
  1505. # save printed, emailed info
  1506. $formnames =~ s/^ +//g;
  1507. $emailforms =~ s/^ +//g;
  1508. my %status = ();
  1509. for ( split / +/, $formnames ) { $status{$_}{printed} = 1 }
  1510. for ( split / +/, $emailforms ) { $status{$_}{emailed} = 1 }
  1511. foreach my $formname ( keys %status ) {
  1512. $printed = ( $formnames =~ /$self->{formname}/ ) ? "1" : "0";
  1513. $emailed = ( $emailforms =~ /$self->{formname}/ ) ? "1" : "0";
  1514. $query = qq|
  1515. INSERT INTO status (trans_id, printed, emailed,
  1516. formname)
  1517. VALUES (?, ?, ?, ?)|;
  1518. $sth = $dbh->prepare($query);
  1519. $sth->execute( $self->{id}, $printed, $emailed, $formname );
  1520. $sth->finish;
  1521. }
  1522. $dbh->commit;
  1523. }
  1524. sub get_recurring {
  1525. my ($self) = @_;
  1526. $dbh = $self->{dbh};
  1527. my $query = qq/
  1528. SELECT s.*, se.formname || ':' || se.format AS emaila,
  1529. se.message, sp.formname || ':' ||
  1530. sp.format || ':' || sp.printer AS printa
  1531. FROM recurring s
  1532. LEFT JOIN recurringemail se ON (s.id = se.id)
  1533. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  1534. WHERE s.id = ?/;
  1535. my $sth = $dbh->prepare($query);
  1536. $sth->execute( $self->{id} ) || $self->dberror($query);
  1537. for (qw(email print)) { $self->{"recurring$_"} = "" }
  1538. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1539. for ( keys %$ref ) { $self->{"recurring$_"} = $ref->{$_} }
  1540. $self->{recurringemail} .= "$ref->{emaila}:";
  1541. $self->{recurringprint} .= "$ref->{printa}:";
  1542. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  1543. }
  1544. $sth->finish;
  1545. chop $self->{recurringemail};
  1546. chop $self->{recurringprint};
  1547. if ( $self->{recurringstartdate} ) {
  1548. $self->{recurringreference} =
  1549. $self->escape( $self->{recurringreference}, 1 );
  1550. $self->{recurringmessage} =
  1551. $self->escape( $self->{recurringmessage}, 1 );
  1552. for (
  1553. qw(reference startdate repeat unit howmany
  1554. payment print email message)
  1555. )
  1556. {
  1557. $self->{recurring} .= qq|$self->{"recurring$_"},|;
  1558. }
  1559. chop $self->{recurring};
  1560. }
  1561. }
  1562. sub save_recurring {
  1563. my ( $self, $dbh2, $myconfig ) = @_;
  1564. my $dbh = $self->{dbh};
  1565. my $query;
  1566. $query = qq|DELETE FROM recurring
  1567. WHERE id = ?|;
  1568. $sth = $dbh->prepare($query) || $self->dberror($query);
  1569. $sth->execute( $self->{id} ) || $self->dberror($query);
  1570. $query = qq|DELETE FROM recurringemail
  1571. WHERE id = ?|;
  1572. $sth = $dbh->prepare($query) || $self->dberror($query);
  1573. $sth->execute( $self->{id} ) || $self->dberror($query);
  1574. $query = qq|DELETE FROM recurringprint
  1575. WHERE id = ?|;
  1576. $sth = $dbh->prepare($query) || $self->dberror($query);
  1577. $sth->execute( $self->{id} ) || $self->dberror($query);
  1578. if ( $self->{recurring} ) {
  1579. my %s = ();
  1580. (
  1581. $s{reference}, $s{startdate}, $s{repeat},
  1582. $s{unit}, $s{howmany}, $s{payment},
  1583. $s{print}, $s{email}, $s{message}
  1584. ) = split /,/, $self->{recurring};
  1585. if ($s{howmany} == 0){
  1586. $self->error("Cannot set to recur 0 times");
  1587. }
  1588. for (qw(reference message)) { $s{$_} = $self->unescape( $s{$_} ) }
  1589. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  1590. # calculate enddate
  1591. my $advance = $s{repeat} * ( $s{howmany} - 1 );
  1592. my %interval;
  1593. $interval{'Pg'} =
  1594. "(date '$s{startdate}' + interval '$advance $s{unit}')";
  1595. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  1596. my ($enddate) = $dbh->selectrow_array($query);
  1597. # calculate nextdate
  1598. $query = qq|
  1599. SELECT current_date - ?::date AS a,
  1600. ?::date - current_date AS b|;
  1601. $sth = $dbh->prepare($query) || $self->dberror($query);
  1602. $sth->execute( $s{startdate}, $enddate );
  1603. my ( $a, $b ) = $sth->fetchrow_array;
  1604. if ( $a + $b ) {
  1605. $advance =
  1606. int( ( $a / ( $a + $b ) ) * ( $s{howmany} - 1 ) + 1 ) *
  1607. $s{repeat};
  1608. }
  1609. else {
  1610. $advance = 0;
  1611. }
  1612. my $nextdate = $enddate;
  1613. if ( $advance > 0 ) {
  1614. if ( $advance < ( $s{repeat} * $s{howmany} ) ) {
  1615. $query = qq|SELECT (date '$s{startdate}' + interval '$advance $s{unit}')|;
  1616. ($nextdate) = $dbh->selectrow_array($query);
  1617. }
  1618. }
  1619. else {
  1620. $nextdate = $s{startdate};
  1621. }
  1622. if ( $self->{recurringnextdate} ) {
  1623. $nextdate = $self->{recurringnextdate};
  1624. $query = qq|SELECT '$enddate' - date '$nextdate'|;
  1625. if ( $dbh->selectrow_array($query) < 0 ) {
  1626. undef $nextdate;
  1627. }
  1628. }
  1629. $self->{recurringpayment} *= 1;
  1630. $query = qq|
  1631. INSERT INTO recurring
  1632. (id, reference, startdate, enddate, nextdate,
  1633. repeat, unit, howmany, payment)
  1634. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  1635. $sth = $dbh->prepare($query);
  1636. $sth->execute(
  1637. $self->{id}, $s{reference}, $s{startdate},
  1638. $enddate, $nextdate, $s{repeat},
  1639. $s{unit}, $s{howmany}, $s{payment}
  1640. );
  1641. my @p;
  1642. my $p;
  1643. my $i;
  1644. my $sth;
  1645. if ( $s{email} ) {
  1646. # formname:format
  1647. @p = split /:/, $s{email};
  1648. $query =
  1649. qq|INSERT INTO recurringemail (id, formname, format, message)
  1650. VALUES (?, ?, ?, ?)|;
  1651. $sth = $dbh->prepare($query) || $self->dberror($query);
  1652. for ( $i = 0 ; $i <= $#p ; $i += 2 ) {
  1653. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $s{message} );
  1654. }
  1655. $sth->finish;
  1656. }
  1657. if ( $s{print} ) {
  1658. # formname:format:printer
  1659. @p = split /:/, $s{print};
  1660. $query =
  1661. qq|INSERT INTO recurringprint (id, formname, format, printer)
  1662. VALUES (?, ?, ?, ?)|;
  1663. $sth = $dbh->prepare($query) || $self->dberror($query);
  1664. for ( $i = 0 ; $i <= $#p ; $i += 3 ) {
  1665. $p = ( $p[ $i + 2 ] ) ? $p[ $i + 2 ] : "";
  1666. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $p );
  1667. }
  1668. $sth->finish;
  1669. }
  1670. }
  1671. $dbh->commit;
  1672. }
  1673. sub save_intnotes {
  1674. my ( $self, $myconfig, $vc ) = @_;
  1675. # no id return
  1676. return unless $self->{id};
  1677. my $dbh = $self->{dbh};
  1678. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  1679. $sth = $dbh->prepare($query);
  1680. $sth->execute( $self->{intnotes}, $self->{id} ) || $self->dberror($query);
  1681. $dbh->commit;
  1682. }
  1683. sub update_defaults {
  1684. my ( $self, $myconfig, $fld ) = @_;
  1685. if ( !$self->{dbh} && $self ) {
  1686. $self->db_init($myconfig);
  1687. }
  1688. my $dbh = $self->{dbh};
  1689. if ( !$self ) {
  1690. $dbh = $_[3];
  1691. }
  1692. my $query = qq|
  1693. SELECT value FROM defaults
  1694. WHERE setting_key = ? FOR UPDATE|;
  1695. $sth = $dbh->prepare($query);
  1696. $sth->execute($fld);
  1697. ($_) = $sth->fetchrow_array();
  1698. $_ = "0" unless $_;
  1699. # check for and replace
  1700. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  1701. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  1702. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  1703. # <?lsmb PHONE ?> for customer and vendors
  1704. my $num = $_;
  1705. ($num) = $num =~ /(\d+)/;
  1706. if ( defined $num ) {
  1707. my $incnum;
  1708. # if we have leading zeros check how long it is
  1709. if ( $num =~ /^0/ ) {
  1710. my $l = length $num;
  1711. $incnum = $num + 1;
  1712. $l -= length $incnum;
  1713. # pad it out with zeros
  1714. my $padzero = "0" x $l;
  1715. $incnum = ( "0" x $l ) . $incnum;
  1716. }
  1717. else {
  1718. $incnum = $num + 1;
  1719. }
  1720. s/$num/$incnum/;
  1721. }
  1722. my $dbvar = $_;
  1723. my $var = $_;
  1724. my $str;
  1725. my $param;
  1726. if (/<\?lsmb /) {
  1727. while (/<\?lsmb /) {
  1728. s/<\?lsmb .*? \?>//;
  1729. last unless $&;
  1730. $param = $&;
  1731. $str = "";
  1732. if ( $param =~ /<\?lsmb date \?>/i ) {
  1733. $str = (
  1734. $self->split_date(
  1735. $myconfig->{dateformat},
  1736. $self->{transdate}
  1737. )
  1738. )[0];
  1739. $var =~ s/$param/$str/;
  1740. }
  1741. if ( $param =~
  1742. /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i
  1743. )
  1744. {
  1745. my $fld = lc $&;
  1746. $fld =~ s/<\?lsmb //;
  1747. if ( $fld =~ /name/ ) {
  1748. if ( $self->{type} ) {
  1749. $fld = $self->{vc};
  1750. }
  1751. }
  1752. my $p = $param;
  1753. $p =~ s/(<|>|%)//g;
  1754. my @p = split / /, $p;
  1755. my @n = split / /, uc $self->{$fld};
  1756. if ( $#p > 0 ) {
  1757. for ( my $i = 1 ; $i <= $#p ; $i++ ) {
  1758. $str .= substr( $n[ $i - 1 ], 0, $p[$i] );
  1759. }
  1760. }
  1761. else {
  1762. ($str) = split /--/, $self->{$fld};
  1763. }
  1764. $var =~ s/$param/$str/;
  1765. $var =~ s/\W//g if $fld eq 'phone';
  1766. }
  1767. if ( $param =~ /<\?lsmb (yy|mm|dd)/i ) {
  1768. my $p = $param;
  1769. $p =~ s/(<|>|%)//g;
  1770. my $spc = $p;
  1771. $spc =~ s/\w//g;
  1772. $spc = substr( $spc, 0, 1 );
  1773. my %d = ( yy => 1, mm => 2, dd => 3 );
  1774. my @p = ();
  1775. my @a = $self->split_date( $myconfig->{dateformat},
  1776. $self->{transdate} );
  1777. for ( sort keys %d ) { push @p, $a[ $d{$_} ] if ( $p =~ /$_/ ) }
  1778. $str = join $spc, @p;
  1779. $var =~ s/$param/$str/;
  1780. }
  1781. if ( $param =~ /<\?lsmb curr/i ) {
  1782. $var =~ s/$param/$self->{currency}/;
  1783. }
  1784. }
  1785. }
  1786. $query = qq|
  1787. UPDATE defaults
  1788. SET value = ?
  1789. WHERE setting_key = ?|;
  1790. $sth = $dbh->prepare($query);
  1791. $sth->execute( $dbvar, $fld ) || $self->dberror($query);
  1792. $dbh->commit;
  1793. $var;
  1794. }
  1795. sub db_prepare_vars {
  1796. my $self = shift;
  1797. for (@_) {
  1798. if ( !$self->{$_} and $self->{$_} ne "0" ) {
  1799. undef $self->{$_};
  1800. }
  1801. }
  1802. }
  1803. sub split_date {
  1804. my ( $self, $dateformat, $date ) = @_;
  1805. my $mm;
  1806. my $dd;
  1807. my $yy;
  1808. my $rv;
  1809. if ( !$date ) {
  1810. my @d = localtime;
  1811. $dd = $d[3];
  1812. $mm = ++$d[4];
  1813. $yy = substr( $d[5], -2 );
  1814. $mm = substr( "0$mm", -2 );
  1815. $dd = substr( "0$dd", -2 );
  1816. }
  1817. if ( $dateformat =~ /^yy/ ) {
  1818. if ($date) {
  1819. if ( $date =~ /\D/ ) {
  1820. ( $yy, $mm, $dd ) = split /\D/, $date;
  1821. $mm *= 1;
  1822. $dd *= 1;
  1823. $mm = substr( "0$mm", -2 );
  1824. $dd = substr( "0$dd", -2 );
  1825. $yy = substr( $yy, -2 );
  1826. $rv = "$yy$mm$dd";
  1827. }
  1828. else {
  1829. $rv = $date;
  1830. }
  1831. }
  1832. else {
  1833. $rv = "$yy$mm$dd";
  1834. }
  1835. }
  1836. elsif ( $dateformat =~ /^mm/ ) {
  1837. if ($date) {
  1838. if ( $date =~ /\D/ ) {
  1839. ( $mm, $dd, $yy ) = split /\D/, $date;
  1840. $mm *= 1;
  1841. $dd *= 1;
  1842. $mm = substr( "0$mm", -2 );
  1843. $dd = substr( "0$dd", -2 );
  1844. $yy = substr( $yy, -2 );
  1845. $rv = "$mm$dd$yy";
  1846. }
  1847. else {
  1848. $rv = $date;
  1849. }
  1850. }
  1851. else {
  1852. $rv = "$mm$dd$yy";
  1853. }
  1854. }
  1855. elsif ( $dateformat =~ /^dd/ ) {
  1856. if ($date) {
  1857. if ( $date =~ /\D/ ) {
  1858. ( $dd, $mm, $yy ) = split /\D/, $date;
  1859. $mm *= 1;
  1860. $dd *= 1;
  1861. $mm = substr( "0$mm", -2 );
  1862. $dd = substr( "0$dd", -2 );
  1863. $yy = substr( $yy, -2 );
  1864. $rv = "$dd$mm$yy";
  1865. }
  1866. else {
  1867. $rv = $date;
  1868. }
  1869. }
  1870. else {
  1871. $rv = "$dd$mm$yy";
  1872. }
  1873. }
  1874. ( $rv, $yy, $mm, $dd );
  1875. }
  1876. sub format_date {
  1877. # takes an iso date in, and converts it to the date for printing
  1878. my ( $self, $date ) = @_;
  1879. my $datestring;
  1880. if ( $date =~ /^\d{4}\D/ ) { # is an ISO date
  1881. $datestring = $self->{db_dateformat};
  1882. my ( $yyyy, $mm, $dd ) = split( /\W/, $date );
  1883. $datestring =~ s/y+/$yyyy/;
  1884. $datestring =~ s/mm/$mm/;
  1885. $datestring =~ s/dd/$dd/;
  1886. }
  1887. else { # return date
  1888. $datestring = $date;
  1889. }
  1890. $datestring;
  1891. }
  1892. sub from_to {
  1893. my ( $self, $yyyy, $mm, $interval ) = @_;
  1894. my @t;
  1895. my $dd = 1;
  1896. my $fromdate = "$yyyy-${mm}-01";
  1897. my $bd = 1;
  1898. if ( defined $interval ) {
  1899. if ( $interval == 12 ) {
  1900. $yyyy++;
  1901. }
  1902. else {
  1903. if ( ( $mm += $interval ) > 12 ) {
  1904. $mm -= 12;
  1905. $yyyy++;
  1906. }
  1907. if ( $interval == 0 ) {
  1908. @t = localtime(time);
  1909. $dd = $t[3];
  1910. $mm = $t[4] + 1;
  1911. $yyyy = $t[5] + 1900;
  1912. $bd = 0;
  1913. }
  1914. }
  1915. }
  1916. else {
  1917. if ( ++$mm > 12 ) {
  1918. $mm -= 12;
  1919. $yyyy++;
  1920. }
  1921. }
  1922. $mm--;
  1923. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yyyy ) - $bd );
  1924. $t[4]++;
  1925. $t[4] = substr( "0$t[4]", -2 );
  1926. $t[3] = substr( "0$t[3]", -2 );
  1927. $t[5] += 1900;
  1928. ( $self->format_date($fromdate), $self->format_date("$t[5]-$t[4]-$t[3]") );
  1929. }
  1930. sub audittrail {
  1931. my ( $self, $dbh, $myconfig, $audittrail ) = @_;
  1932. # table, $reference, $formname, $action, $id, $transdate) = @_;
  1933. my $query;
  1934. my $rv;
  1935. my $disconnect;
  1936. if ( !$dbh ) {
  1937. $dbh = $self->{dbh};
  1938. }
  1939. # if we have an id add audittrail, otherwise get a new timestamp
  1940. my @queryargs;
  1941. if ( $audittrail->{id} ) {
  1942. $query = qq|
  1943. SELECT value FROM defaults
  1944. WHERE setting_key = 'audittrail'|;
  1945. if ( $dbh->selectrow_array($query) ) {
  1946. my ( $null, $employee_id ) = $self->get_employee($dbh);
  1947. if ( $self->{audittrail} && !$myconfig ) {
  1948. chop $self->{audittrail};
  1949. my @a = split /\|/, $self->{audittrail};
  1950. my %newtrail = ();
  1951. my $key;
  1952. my $i;
  1953. my @flds = qw(tablename reference formname action transdate);
  1954. # put into hash and remove dups
  1955. while (@a) {
  1956. $key = "$a[2]$a[3]";
  1957. $i = 0;
  1958. $newtrail{$key} = { map { $_ => $a[ $i++ ] } @flds };
  1959. splice @a, 0, 5;
  1960. }
  1961. $query = qq|
  1962. INSERT INTO audittrail
  1963. (trans_id, tablename, reference,
  1964. formname, action, transdate,
  1965. employee_id)
  1966. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  1967. my $sth = $dbh->prepare($query) || $self->dberror($query);
  1968. foreach $key (
  1969. sort {
  1970. $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
  1971. } keys %newtrail
  1972. )
  1973. {
  1974. $i = 2;
  1975. $sth->bind_param( 1, $audittrail->{id} );
  1976. for (@flds) {
  1977. $sth->bind_param( $i++, $newtrail{$key}{$_} );
  1978. }
  1979. $sth->bind_param( $i++, $employee_id );
  1980. $sth->execute() || $self->dberror($query);
  1981. $sth->finish;
  1982. }
  1983. }
  1984. if ( $audittrail->{transdate} ) {
  1985. $query = qq|
  1986. INSERT INTO audittrail (
  1987. trans_id, tablename, reference,
  1988. formname, action, employee_id,
  1989. transdate)
  1990. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  1991. @queryargs = (
  1992. $audittrail->{id}, $audittrail->{tablename},
  1993. $audittrail->{reference}, $audittrail->{formname},
  1994. $audittrail->{action}, $employee_id,
  1995. $audittrail->{transdate}
  1996. );
  1997. }
  1998. else {
  1999. $query = qq|
  2000. INSERT INTO audittrail
  2001. (trans_id, tablename, reference,
  2002. formname, action, employee_id)
  2003. VALUES (?, ?, ?, ?, ?, ?)|;
  2004. @queryargs = (
  2005. $audittrail->{id}, $audittrail->{tablename},
  2006. $audittrail->{reference}, $audittrail->{formname},
  2007. $audittrail->{action}, $employee_id,
  2008. );
  2009. }
  2010. $sth = $dbh->prepare($query);
  2011. $sth->execute(@queryargs) || $self->dberror($query);
  2012. }
  2013. }
  2014. else {
  2015. $query = qq|SELECT current_timestamp|;
  2016. my ($timestamp) = $dbh->selectrow_array($query);
  2017. $rv =
  2018. "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2019. }
  2020. $rv;
  2021. }
  2022. 1;