summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: 0633ced5c4e469fbb680a3a5d8edc812efa83102 (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. # Company name is stored in $self->{vendor} or $self->{customer}
  943. my $name = $self->like( lc $self->{$table} );
  944. # Vendor and Customer are now views into entity_credit_account.
  945. my $query = qq|
  946. SELECT * FROM $table t
  947. JOIN entity e ON t.entity_id = e.id
  948. WHERE (lower(e.name) LIKE ? OR t.${table}number LIKE ?)
  949. $where
  950. ORDER BY e.name|;
  951. unshift( @queryargs, $name, $name, $table );
  952. my $sth = $self->{dbh}->prepare($query);
  953. $sth->execute(@queryargs) || $self->dberror($query);
  954. my $i = 0;
  955. @{ $self->{name_list} } = ();
  956. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  957. push( @{ $self->{name_list} }, $ref );
  958. $i++;
  959. }
  960. $sth->finish;
  961. return $i;
  962. }
  963. sub all_vc {
  964. my ( $self, $myconfig, $vc, $module, $dbh, $transdate, $job ) = @_;
  965. my $ref;
  966. my $disconnect = 0;
  967. $dbh = $self->{dbh};
  968. my $sth;
  969. my $query = qq|SELECT count(*) FROM $vc|;
  970. my $where;
  971. my @queryargs = ();
  972. if ($transdate) {
  973. $query .= qq| WHERE (startdate IS NULL OR startdate <= ?)
  974. AND (enddate IS NULL OR enddate >= ?)|;
  975. @queryargs = ( $transdate, $transdate );
  976. }
  977. $sth = $dbh->prepare($query);
  978. $sth->execute(@queryargs);
  979. my ($count) = $sth->fetchrow_array;
  980. $sth->finish;
  981. @queryargs = ();
  982. # build selection list
  983. if ( $count < $myconfig->{vclimit} ) {
  984. $self->{"${vc}_id"} *= 1;
  985. $where = "AND $where" if $where;
  986. $query = qq|SELECT id, name
  987. FROM entity
  988. WHERE id IN (select entity_id
  989. FROM $vc)
  990. $where
  991. UNION
  992. SELECT id,name
  993. FROM entity
  994. WHERE id = ?
  995. ORDER BY name|;
  996. push( @queryargs, $self->{"${vc}_id"} );
  997. $sth = $dbh->prepare($query);
  998. $sth->execute(@queryargs) || $self->dberror($query);
  999. @{ $self->{"all_$vc"} } = ();
  1000. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1001. push @{ $self->{"all_$vc"} }, $ref;
  1002. }
  1003. $sth->finish;
  1004. }
  1005. # get self
  1006. if ( !$self->{employee_id} ) {
  1007. ( $self->{employee}, $self->{employee_id} ) = split /--/,
  1008. $self->{employee};
  1009. ( $self->{employee}, $self->{employee_id} ) = $self->get_employee($dbh)
  1010. unless $self->{employee_id};
  1011. }
  1012. $self->all_employees( $myconfig, $dbh, $transdate, 1 );
  1013. $self->all_departments( $myconfig, $dbh, $vc );
  1014. $self->all_projects( $myconfig, $dbh, $transdate, $job );
  1015. # get language codes
  1016. $query = qq|SELECT *
  1017. FROM language
  1018. ORDER BY 2|;
  1019. $sth = $dbh->prepare($query);
  1020. $sth->execute || $self->dberror($query);
  1021. $self->{all_language} = ();
  1022. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1023. push @{ $self->{all_language} }, $ref;
  1024. }
  1025. $sth->finish;
  1026. $self->all_taxaccounts( $myconfig, $dbh, $transdate );
  1027. }
  1028. sub all_taxaccounts {
  1029. my ( $self, $myconfig, $dbh2, $transdate ) = @_;
  1030. my $dbh = $self->{dbh};
  1031. my $sth;
  1032. my $query;
  1033. my $where;
  1034. my @queryargs = ();
  1035. if ($transdate) {
  1036. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1037. push( @queryargs, $transdate );
  1038. }
  1039. if ( $self->{taxaccounts} ) {
  1040. # rebuild tax rates
  1041. $query = qq|SELECT t.rate, t.taxnumber
  1042. FROM tax t
  1043. JOIN chart c ON (c.id = t.chart_id)
  1044. WHERE c.accno = ?
  1045. $where
  1046. ORDER BY accno, validto|;
  1047. $sth = $dbh->prepare($query) || $self->dberror($query);
  1048. foreach my $accno ( split / /, $self->{taxaccounts} ) {
  1049. $sth->execute( $accno, @queryargs );
  1050. ( $self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"} ) =
  1051. $sth->fetchrow_array;
  1052. $sth->finish;
  1053. }
  1054. }
  1055. }
  1056. sub all_employees {
  1057. my ( $self, $myconfig, $dbh2, $transdate, $sales ) = @_;
  1058. my $dbh = $self->{dbh};
  1059. my @whereargs = ();
  1060. # setup employees/sales contacts
  1061. my $query = qq|
  1062. SELECT id, name
  1063. FROM entity
  1064. WHERE id IN (SELECT entity_id FROM employee
  1065. WHERE|;
  1066. if ($transdate) {
  1067. $query .= qq| (startdate IS NULL OR startdate <= ?)
  1068. AND (enddate IS NULL OR enddate >= ?) AND|;
  1069. @whereargs = ( $transdate, $transdate );
  1070. }
  1071. else {
  1072. $query .= qq| enddate IS NULL AND|;
  1073. }
  1074. if ($sales) {
  1075. $query .= qq| sales = '1' AND|;
  1076. }
  1077. $query =~ s/(WHERE|AND)$//;
  1078. $query .= qq|) ORDER BY name|;
  1079. my $sth = $dbh->prepare($query);
  1080. $sth->execute(@whereargs) || $self->dberror($query);
  1081. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1082. push @{ $self->{all_employee} }, $ref;
  1083. }
  1084. $sth->finish;
  1085. }
  1086. sub all_projects {
  1087. my ( $self, $myconfig, $dbh2, $transdate, $job ) = @_;
  1088. my $dbh = $self->{dbh};
  1089. my @queryargs = ();
  1090. my $where = "1 = 1";
  1091. $where = qq|id NOT IN (SELECT id
  1092. FROM parts
  1093. WHERE project_id > 0)| if !$job;
  1094. my $query = qq|SELECT *
  1095. FROM project
  1096. WHERE $where|;
  1097. if ( $self->{language_code} ) {
  1098. $query = qq|
  1099. SELECT pr.*, t.description AS translation
  1100. FROM project pr
  1101. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1102. WHERE t.language_code = ?|;
  1103. push( @queryargs, $self->{language_code} );
  1104. }
  1105. if ($transdate) {
  1106. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1107. AND (enddate IS NULL OR enddate >= ?)|;
  1108. push( @queryargs, $transdate, $transdate );
  1109. }
  1110. $query .= qq| ORDER BY projectnumber|;
  1111. $sth = $dbh->prepare($query);
  1112. $sth->execute(@queryargs) || $self->dberror($query);
  1113. @{ $self->{all_project} } = ();
  1114. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1115. push @{ $self->{all_project} }, $ref;
  1116. }
  1117. $sth->finish;
  1118. }
  1119. sub all_departments {
  1120. my ( $self, $myconfig, $dbh2, $vc ) = @_;
  1121. $dbh = $self->{dbh};
  1122. my $where = "1 = 1";
  1123. if ($vc) {
  1124. if ( $vc eq 'customer' ) {
  1125. $where = " role = 'P'";
  1126. }
  1127. }
  1128. my $query = qq|SELECT id, description
  1129. FROM department
  1130. WHERE $where
  1131. ORDER BY 2|;
  1132. my $sth = $dbh->prepare($query);
  1133. $sth->execute || $self->dberror($query);
  1134. @{ $self->{all_department} } = ();
  1135. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1136. push @{ $self->{all_department} }, $ref;
  1137. }
  1138. $sth->finish;
  1139. $self->all_years($myconfig);
  1140. }
  1141. sub all_years {
  1142. my ( $self, $myconfig, $dbh2 ) = @_;
  1143. $dbh = $self->{dbh};
  1144. # get years
  1145. my $query = qq|
  1146. SELECT (SELECT transdate FROM acc_trans ORDER BY transdate asc
  1147. LIMIT 1),
  1148. (SELECT transdate FROM acc_trans ORDER BY transdate desc
  1149. LIMIT 1)|;
  1150. my ( $startdate, $enddate ) = $dbh->selectrow_array($query);
  1151. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1152. ($startdate) = split /\W/, $startdate;
  1153. ($enddate) = split /\W/, $enddate;
  1154. }
  1155. else {
  1156. (@_) = split /\W/, $startdate;
  1157. $startdate = $_[2];
  1158. (@_) = split /\W/, $enddate;
  1159. $enddate = $_[2];
  1160. }
  1161. $self->{all_years} = ();
  1162. $startdate = substr( $startdate, 0, 4 );
  1163. $enddate = substr( $enddate, 0, 4 );
  1164. while ( $enddate >= $startdate ) {
  1165. push @{ $self->{all_years} }, $enddate--;
  1166. }
  1167. #this should probably be changed to use locale
  1168. %{ $self->{all_month} } = (
  1169. '01' => 'January',
  1170. '02' => 'February',
  1171. '03' => 'March',
  1172. '04' => 'April',
  1173. '05' => 'May ',
  1174. '06' => 'June',
  1175. '07' => 'July',
  1176. '08' => 'August',
  1177. '09' => 'September',
  1178. '10' => 'October',
  1179. '11' => 'November',
  1180. '12' => 'December'
  1181. );
  1182. }
  1183. sub create_links {
  1184. my ( $self, $module, $myconfig, $vc, $job ) = @_;
  1185. # get last customers or vendors
  1186. my ( $query, $sth );
  1187. if (!$self->{dbh}) {
  1188. $self->db_init($myconfig);
  1189. }
  1190. $dbh = $self->{dbh};
  1191. my %xkeyref = ();
  1192. # now get the account numbers
  1193. $query = qq|SELECT accno, description, link
  1194. FROM chart
  1195. WHERE link LIKE ?
  1196. ORDER BY accno|;
  1197. $sth = $dbh->prepare($query);
  1198. $sth->execute( "%" . "$module%" ) || $self->dberror($query);
  1199. $self->{accounts} = "";
  1200. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1201. foreach my $key ( split /:/, $ref->{link} ) {
  1202. if ( $key =~ /$module/ ) {
  1203. # cross reference for keys
  1204. $xkeyref{ $ref->{accno} } = $key;
  1205. push @{ $self->{"${module}_links"}{$key} },
  1206. {
  1207. accno => $ref->{accno},
  1208. description => $ref->{description}
  1209. };
  1210. $self->{accounts} .= "$ref->{accno} "
  1211. unless $key =~ /tax/;
  1212. }
  1213. }
  1214. }
  1215. $sth->finish;
  1216. my $arap = ( $vc eq 'customer' ) ? 'ar' : 'ap';
  1217. if ( $self->{id} ) {
  1218. $query = qq|
  1219. SELECT a.invnumber, a.transdate,
  1220. a.${vc}_id, a.datepaid, a.duedate, a.ordnumber,
  1221. a.taxincluded, a.curr AS currency, a.notes,
  1222. a.intnotes, c.name AS $vc, a.department_id,
  1223. d.description AS department,
  1224. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1225. a.employee_id, e.name AS employee,
  1226. c.language_code, a.ponumber
  1227. FROM $arap a
  1228. JOIN $vc c ON (a.${vc}_id = c.id)
  1229. LEFT JOIN employee e ON (e.id = a.employee_id)
  1230. LEFT JOIN department d ON (d.id = a.department_id)
  1231. WHERE a.id = ?|;
  1232. $sth = $dbh->prepare($query);
  1233. $sth->execute( $self->{id} ) || $self->dberror($query);
  1234. $ref = $sth->fetchrow_hashref(NAME_lc);
  1235. $self->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1236. foreach $key ( keys %$ref ) {
  1237. $self->{$key} = $ref->{$key};
  1238. }
  1239. $sth->finish;
  1240. # get printed, emailed
  1241. $query = qq|
  1242. SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1243. FROM status s WHERE s.trans_id = ?|;
  1244. $sth = $dbh->prepare($query);
  1245. $sth->execute( $self->{id} ) || $self->dberror($query);
  1246. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1247. $self->{printed} .= "$ref->{formname} "
  1248. if $ref->{printed};
  1249. $self->{emailed} .= "$ref->{formname} "
  1250. if $ref->{emailed};
  1251. $self->{queued} .= "$ref->{formname} " . "$ref->{spoolfile} "
  1252. if $ref->{spoolfile};
  1253. }
  1254. $sth->finish;
  1255. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1256. # get recurring
  1257. $self->get_recurring($dbh);
  1258. # get amounts from individual entries
  1259. $query = qq|
  1260. SELECT c.accno, c.description, a.source, a.amount,
  1261. a.memo, a.transdate, a.cleared, a.project_id,
  1262. p.projectnumber
  1263. FROM acc_trans a
  1264. JOIN chart c ON (c.id = a.chart_id)
  1265. LEFT JOIN project p ON (p.id = a.project_id)
  1266. WHERE a.trans_id = ?
  1267. AND a.fx_transaction = '0'
  1268. ORDER BY transdate|;
  1269. $sth = $dbh->prepare($query);
  1270. $sth->execute( $self->{id} ) || $self->dberror($query);
  1271. my $fld = ( $vc eq 'customer' ) ? 'buy' : 'sell';
  1272. $self->{exchangerate} =
  1273. $self->get_exchangerate( $dbh, $self->{currency}, $self->{transdate},
  1274. $fld );
  1275. # store amounts in {acc_trans}{$key} for multiple accounts
  1276. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1277. $ref->{exchangerate} =
  1278. $self->get_exchangerate( $dbh, $self->{currency},
  1279. $ref->{transdate}, $fld );
  1280. push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
  1281. }
  1282. $sth->finish;
  1283. }
  1284. else {
  1285. if ( !$self->{"$self->{vc}_id"} ) {
  1286. $self->lastname_used( $myconfig, $dbh, $vc, $module );
  1287. }
  1288. }
  1289. for (qw(current_date curr closedto revtrans)) {
  1290. if ($_ eq 'closedto'){
  1291. $query = qq|
  1292. SELECT value::date FROM defaults
  1293. WHERE setting_key = '$_'|;
  1294. } elsif ($_ eq 'current_date') {
  1295. $query = qq| select $_|;
  1296. } else {
  1297. $query = qq|
  1298. SELECT value FROM defaults
  1299. WHERE setting_key = '$_'|;
  1300. }
  1301. $sth = $dbh->prepare($query);
  1302. $sth->execute || $self->dberror($query);
  1303. ($val) = $sth->fetchrow_array();
  1304. if ( $_ eq 'curr' ) {
  1305. $self->{currencies} = $val;
  1306. }
  1307. else {
  1308. $self->{$_} = $val;
  1309. }
  1310. $sth->finish;
  1311. }
  1312. if (!$self->{id}){
  1313. $self->{transdate} = $self->{current_date};
  1314. }
  1315. $self->all_vc( $myconfig, $vc, $module, $dbh, $self->{transdate}, $job );
  1316. }
  1317. sub lastname_used {
  1318. my ( $self, $myconfig, $dbh2, $vc, $module ) = @_;
  1319. my $dbh = $self->{dbh};
  1320. $vc ||= $self->{vc}; # add default to correct for improper passing
  1321. my $arap = ( $vc eq 'customer' ) ? "ar" : "ap";
  1322. my $sth;
  1323. if ( $self->{type} =~ /_order/ ) {
  1324. $arap = 'oe';
  1325. $where = "quotation = '0'";
  1326. }
  1327. if ( $self->{type} =~ /_quotation/ ) {
  1328. $arap = 'oe';
  1329. $where = "quotation = '1'";
  1330. }
  1331. $where = "AND $where " if $where;
  1332. $inv_notes = "ct.invoice_notes," if $vc eq 'customer';
  1333. my $query = qq|
  1334. SELECT entity.name, ct.curr AS currency, entity_id AS ${vc}_id,
  1335. current_date + ct.terms AS duedate,
  1336. $inv_notes
  1337. ct.curr AS currency
  1338. FROM $vc ct
  1339. JOIN entity ON (ct.entity_id = entity.id)
  1340. WHERE entity.id = (select entity_id from $arap
  1341. where entity_id IS NOT NULL $where
  1342. order by id DESC limit 1)|;
  1343. $sth = $dbh->prepare($query);
  1344. $sth->execute() || $self->dberror($query);
  1345. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1346. for ( keys %$ref ) { $self->{$_} = $ref->{$_} }
  1347. $sth->finish;
  1348. }
  1349. sub current_date {
  1350. my ( $self, $myconfig, $thisdate, $days ) = @_;
  1351. my $dbh = $self->{dbh};
  1352. my $query;
  1353. $days *= 1;
  1354. if ($thisdate) {
  1355. my $dateformat = $myconfig->{dateformat};
  1356. if ( $myconfig->{dateformat} !~ /^y/ ) {
  1357. my @a = split /\D/, $thisdate;
  1358. $dateformat .= "yy" if ( length $a[2] > 2 );
  1359. }
  1360. if ( $thisdate !~ /\D/ ) {
  1361. $dateformat = 'yyyymmdd';
  1362. }
  1363. $query = qq|SELECT (to_date(?, ?)
  1364. + ?::interval)::date AS thisdate|;
  1365. @queryargs = ( $thisdate, $dateformat, sprintf('%d days', $days) );
  1366. }
  1367. else {
  1368. $query = qq|SELECT current_date AS thisdate|;
  1369. @queryargs = ();
  1370. }
  1371. $sth = $dbh->prepare($query);
  1372. $sth->execute(@queryargs);
  1373. ($thisdate) = $sth->fetchrow_array;
  1374. $thisdate;
  1375. }
  1376. sub like {
  1377. my ( $self, $str ) = @_;
  1378. "%$str%";
  1379. }
  1380. sub redo_rows {
  1381. my ( $self, $flds, $new, $count, $numrows ) = @_;
  1382. my @ndx = ();
  1383. for ( 1 .. $count ) {
  1384. push @ndx, { num => $new->[ $_ - 1 ]->{runningnumber}, ndx => $_ };
  1385. }
  1386. my $i = 0;
  1387. # fill rows
  1388. foreach my $item ( sort { $a->{num} <=> $b->{num} } @ndx ) {
  1389. $i++;
  1390. $j = $item->{ndx} - 1;
  1391. for ( @{$flds} ) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1392. }
  1393. # delete empty rows
  1394. for $i ( $count + 1 .. $numrows ) {
  1395. for ( @{$flds} ) { delete $self->{"${_}_$i"} }
  1396. }
  1397. }
  1398. sub get_partsgroup {
  1399. my ( $self, $myconfig, $p ) = @_;
  1400. my $dbh = $self->{dbh};
  1401. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1402. FROM partsgroup pg
  1403. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1404. my $where;
  1405. my $sortorder = "partsgroup";
  1406. if ( $p->{searchitems} eq 'part' ) {
  1407. $where = qq| WHERE (p.inventory_accno_id > 0
  1408. AND p.income_accno_id > 0)|;
  1409. }
  1410. if ( $p->{searchitems} eq 'service' ) {
  1411. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1412. }
  1413. if ( $p->{searchitems} eq 'assembly' ) {
  1414. $where = qq| WHERE p.assembly = '1'|;
  1415. }
  1416. if ( $p->{searchitems} eq 'labor' ) {
  1417. $where =
  1418. qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1419. }
  1420. if ( $p->{searchitems} eq 'nolabor' ) {
  1421. $where = qq| WHERE p.income_accno_id > 0|;
  1422. }
  1423. if ( $p->{all} ) {
  1424. $query = qq|SELECT id, partsgroup
  1425. FROM partsgroup|;
  1426. }
  1427. my @queryargs = ();
  1428. if ( $p->{language_code} ) {
  1429. $sortorder = "translation";
  1430. $query = qq|
  1431. SELECT DISTINCT pg.id, pg.partsgroup,
  1432. t.description AS translation
  1433. FROM partsgroup pg
  1434. JOIN parts p ON (p.partsgroup_id = pg.id)
  1435. LEFT JOIN translation t ON (t.trans_id = pg.id
  1436. AND t.language_code = ?)|;
  1437. @queryargs = ( $p->{language_code} );
  1438. }
  1439. $query .= qq| $where ORDER BY $sortorder|;
  1440. my $sth = $dbh->prepare($query);
  1441. $sth->execute(@queryargs) || $self->dberror($query);
  1442. $self->{all_partsgroup} = ();
  1443. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1444. push @{ $self->{all_partsgroup} }, $ref;
  1445. }
  1446. $sth->finish;
  1447. }
  1448. sub update_status {
  1449. my ( $self, $myconfig ) = @_;
  1450. # no id return
  1451. return unless $self->{id};
  1452. my $dbh = $self->{dbh};
  1453. my %queued = split / +/, $self->{queued};
  1454. my $spoolfile =
  1455. ( $queued{ $self->{formname} } )
  1456. ? "'$queued{$self->{formname}}'"
  1457. : 'NULL';
  1458. my $query = qq|DELETE FROM status
  1459. WHERE formname = ?
  1460. AND trans_id = ?|;
  1461. $sth = $dbh->prepare($query);
  1462. $sth->execute( $self->{formname}, $self->{id} ) || $self->dberror($query);
  1463. $sth->finish;
  1464. my $printed = ( $self->{printed} =~ /$self->{formname}/ ) ? "1" : "0";
  1465. my $emailed = ( $self->{emailed} =~ /$self->{formname}/ ) ? "1" : "0";
  1466. $query = qq|
  1467. INSERT INTO status
  1468. (trans_id, printed, emailed, spoolfile, formname)
  1469. VALUES (?, ?, ?, ?, ?)|;
  1470. $sth = $dbh->prepare($query);
  1471. $sth->execute( $self->{id}, $printed, $emailed, $spoolfile,
  1472. $self->{formname} );
  1473. $sth->finish;
  1474. }
  1475. sub save_status {
  1476. my ($self) = @_;
  1477. $dbh = $self->{dbh};
  1478. my $formnames = $self->{printed};
  1479. my $emailforms = $self->{emailed};
  1480. my $query = qq|DELETE FROM status
  1481. WHERE trans_id = ?|;
  1482. my $sth = $dbh->prepare($query);
  1483. $sth->execute( $self->{id} );
  1484. $sth->finish;
  1485. my %queued;
  1486. my $formname;
  1487. if ( $self->{queued} ) {
  1488. %queued = split / +/, $self->{queued};
  1489. foreach $formname ( keys %queued ) {
  1490. $printed = ( $self->{printed} =~ /$formname/ ) ? "1" : "0";
  1491. $emailed = ( $self->{emailed} =~ /$formname/ ) ? "1" : "0";
  1492. if ( $queued{$formname} ) {
  1493. $query = qq|
  1494. INSERT INTO status
  1495. (trans_id, printed, emailed,
  1496. spoolfile, formname)
  1497. VALUES (?, ?, ?, ?, ?)|;
  1498. $sth = $dbh->prepare($query);
  1499. $sth->execute( $self->{id}, $pinted, $emailed,
  1500. $queued{$formname}, $formname )
  1501. || $self->dberror($query);
  1502. $sth->finish;
  1503. }
  1504. $formnames =~ s/$formname//;
  1505. $emailforms =~ s/$formname//;
  1506. }
  1507. }
  1508. # save printed, emailed info
  1509. $formnames =~ s/^ +//g;
  1510. $emailforms =~ s/^ +//g;
  1511. my %status = ();
  1512. for ( split / +/, $formnames ) { $status{$_}{printed} = 1 }
  1513. for ( split / +/, $emailforms ) { $status{$_}{emailed} = 1 }
  1514. foreach my $formname ( keys %status ) {
  1515. $printed = ( $formnames =~ /$self->{formname}/ ) ? "1" : "0";
  1516. $emailed = ( $emailforms =~ /$self->{formname}/ ) ? "1" : "0";
  1517. $query = qq|
  1518. INSERT INTO status (trans_id, printed, emailed,
  1519. formname)
  1520. VALUES (?, ?, ?, ?)|;
  1521. $sth = $dbh->prepare($query);
  1522. $sth->execute( $self->{id}, $printed, $emailed, $formname );
  1523. $sth->finish;
  1524. }
  1525. $dbh->commit;
  1526. }
  1527. sub get_recurring {
  1528. my ($self) = @_;
  1529. $dbh = $self->{dbh};
  1530. my $query = qq/
  1531. SELECT s.*, se.formname || ':' || se.format AS emaila,
  1532. se.message, sp.formname || ':' ||
  1533. sp.format || ':' || sp.printer AS printa
  1534. FROM recurring s
  1535. LEFT JOIN recurringemail se ON (s.id = se.id)
  1536. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  1537. WHERE s.id = ?/;
  1538. my $sth = $dbh->prepare($query);
  1539. $sth->execute( $self->{id} ) || $self->dberror($query);
  1540. for (qw(email print)) { $self->{"recurring$_"} = "" }
  1541. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1542. for ( keys %$ref ) { $self->{"recurring$_"} = $ref->{$_} }
  1543. $self->{recurringemail} .= "$ref->{emaila}:";
  1544. $self->{recurringprint} .= "$ref->{printa}:";
  1545. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  1546. }
  1547. $sth->finish;
  1548. chop $self->{recurringemail};
  1549. chop $self->{recurringprint};
  1550. if ( $self->{recurringstartdate} ) {
  1551. $self->{recurringreference} =
  1552. $self->escape( $self->{recurringreference}, 1 );
  1553. $self->{recurringmessage} =
  1554. $self->escape( $self->{recurringmessage}, 1 );
  1555. for (
  1556. qw(reference startdate repeat unit howmany
  1557. payment print email message)
  1558. )
  1559. {
  1560. $self->{recurring} .= qq|$self->{"recurring$_"},|;
  1561. }
  1562. chop $self->{recurring};
  1563. }
  1564. }
  1565. sub save_recurring {
  1566. my ( $self, $dbh2, $myconfig ) = @_;
  1567. my $dbh = $self->{dbh};
  1568. my $query;
  1569. $query = qq|DELETE FROM recurring
  1570. WHERE id = ?|;
  1571. $sth = $dbh->prepare($query) || $self->dberror($query);
  1572. $sth->execute( $self->{id} ) || $self->dberror($query);
  1573. $query = qq|DELETE FROM recurringemail
  1574. WHERE id = ?|;
  1575. $sth = $dbh->prepare($query) || $self->dberror($query);
  1576. $sth->execute( $self->{id} ) || $self->dberror($query);
  1577. $query = qq|DELETE FROM recurringprint
  1578. WHERE id = ?|;
  1579. $sth = $dbh->prepare($query) || $self->dberror($query);
  1580. $sth->execute( $self->{id} ) || $self->dberror($query);
  1581. if ( $self->{recurring} ) {
  1582. my %s = ();
  1583. (
  1584. $s{reference}, $s{startdate}, $s{repeat},
  1585. $s{unit}, $s{howmany}, $s{payment},
  1586. $s{print}, $s{email}, $s{message}
  1587. ) = split /,/, $self->{recurring};
  1588. if ($s{howmany} == 0){
  1589. $self->error("Cannot set to recur 0 times");
  1590. }
  1591. for (qw(reference message)) { $s{$_} = $self->unescape( $s{$_} ) }
  1592. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  1593. # calculate enddate
  1594. my $advance = $s{repeat} * ( $s{howmany} - 1 );
  1595. my %interval;
  1596. $interval{'Pg'} =
  1597. "(date '$s{startdate}' + interval '$advance $s{unit}')";
  1598. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  1599. my ($enddate) = $dbh->selectrow_array($query);
  1600. # calculate nextdate
  1601. $query = qq|
  1602. SELECT current_date - ?::date AS a,
  1603. ?::date - current_date AS b|;
  1604. $sth = $dbh->prepare($query) || $self->dberror($query);
  1605. $sth->execute( $s{startdate}, $enddate );
  1606. my ( $a, $b ) = $sth->fetchrow_array;
  1607. if ( $a + $b ) {
  1608. $advance =
  1609. int( ( $a / ( $a + $b ) ) * ( $s{howmany} - 1 ) + 1 ) *
  1610. $s{repeat};
  1611. }
  1612. else {
  1613. $advance = 0;
  1614. }
  1615. my $nextdate = $enddate;
  1616. if ( $advance > 0 ) {
  1617. if ( $advance < ( $s{repeat} * $s{howmany} ) ) {
  1618. $query = qq|SELECT (date '$s{startdate}' + interval '$advance $s{unit}')|;
  1619. ($nextdate) = $dbh->selectrow_array($query);
  1620. }
  1621. }
  1622. else {
  1623. $nextdate = $s{startdate};
  1624. }
  1625. if ( $self->{recurringnextdate} ) {
  1626. $nextdate = $self->{recurringnextdate};
  1627. $query = qq|SELECT '$enddate' - date '$nextdate'|;
  1628. if ( $dbh->selectrow_array($query) < 0 ) {
  1629. undef $nextdate;
  1630. }
  1631. }
  1632. $self->{recurringpayment} *= 1;
  1633. $query = qq|
  1634. INSERT INTO recurring
  1635. (id, reference, startdate, enddate, nextdate,
  1636. repeat, unit, howmany, payment)
  1637. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  1638. $sth = $dbh->prepare($query);
  1639. $sth->execute(
  1640. $self->{id}, $s{reference}, $s{startdate},
  1641. $enddate, $nextdate, $s{repeat},
  1642. $s{unit}, $s{howmany}, $s{payment}
  1643. );
  1644. my @p;
  1645. my $p;
  1646. my $i;
  1647. my $sth;
  1648. if ( $s{email} ) {
  1649. # formname:format
  1650. @p = split /:/, $s{email};
  1651. $query =
  1652. qq|INSERT INTO recurringemail (id, formname, format, message)
  1653. VALUES (?, ?, ?, ?)|;
  1654. $sth = $dbh->prepare($query) || $self->dberror($query);
  1655. for ( $i = 0 ; $i <= $#p ; $i += 2 ) {
  1656. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $s{message} );
  1657. }
  1658. $sth->finish;
  1659. }
  1660. if ( $s{print} ) {
  1661. # formname:format:printer
  1662. @p = split /:/, $s{print};
  1663. $query =
  1664. qq|INSERT INTO recurringprint (id, formname, format, printer)
  1665. VALUES (?, ?, ?, ?)|;
  1666. $sth = $dbh->prepare($query) || $self->dberror($query);
  1667. for ( $i = 0 ; $i <= $#p ; $i += 3 ) {
  1668. $p = ( $p[ $i + 2 ] ) ? $p[ $i + 2 ] : "";
  1669. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $p );
  1670. }
  1671. $sth->finish;
  1672. }
  1673. }
  1674. $dbh->commit;
  1675. }
  1676. sub save_intnotes {
  1677. my ( $self, $myconfig, $vc ) = @_;
  1678. # no id return
  1679. return unless $self->{id};
  1680. my $dbh = $self->{dbh};
  1681. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  1682. $sth = $dbh->prepare($query);
  1683. $sth->execute( $self->{intnotes}, $self->{id} ) || $self->dberror($query);
  1684. $dbh->commit;
  1685. }
  1686. sub update_defaults {
  1687. my ( $self, $myconfig, $fld ) = @_;
  1688. if ( !$self->{dbh} && $self ) {
  1689. $self->db_init($myconfig);
  1690. }
  1691. my $dbh = $self->{dbh};
  1692. if ( !$self ) {
  1693. $dbh = $_[3];
  1694. }
  1695. my $query = qq|
  1696. SELECT value FROM defaults
  1697. WHERE setting_key = ? FOR UPDATE|;
  1698. $sth = $dbh->prepare($query);
  1699. $sth->execute($fld);
  1700. ($_) = $sth->fetchrow_array();
  1701. $_ = "0" unless $_;
  1702. # check for and replace
  1703. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  1704. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  1705. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  1706. # <?lsmb PHONE ?> for customer and vendors
  1707. my $num = $_;
  1708. ($num) = $num =~ /(\d+)/;
  1709. if ( defined $num ) {
  1710. my $incnum;
  1711. # if we have leading zeros check how long it is
  1712. if ( $num =~ /^0/ ) {
  1713. my $l = length $num;
  1714. $incnum = $num + 1;
  1715. $l -= length $incnum;
  1716. # pad it out with zeros
  1717. my $padzero = "0" x $l;
  1718. $incnum = ( "0" x $l ) . $incnum;
  1719. }
  1720. else {
  1721. $incnum = $num + 1;
  1722. }
  1723. s/$num/$incnum/;
  1724. }
  1725. my $dbvar = $_;
  1726. my $var = $_;
  1727. my $str;
  1728. my $param;
  1729. if (/<\?lsmb /) {
  1730. while (/<\?lsmb /) {
  1731. s/<\?lsmb .*? \?>//;
  1732. last unless $&;
  1733. $param = $&;
  1734. $str = "";
  1735. if ( $param =~ /<\?lsmb date \?>/i ) {
  1736. $str = (
  1737. $self->split_date(
  1738. $myconfig->{dateformat},
  1739. $self->{transdate}
  1740. )
  1741. )[0];
  1742. $var =~ s/$param/$str/;
  1743. }
  1744. if ( $param =~
  1745. /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i
  1746. )
  1747. {
  1748. my $fld = lc $&;
  1749. $fld =~ s/<\?lsmb //;
  1750. if ( $fld =~ /name/ ) {
  1751. if ( $self->{type} ) {
  1752. $fld = $self->{vc};
  1753. }
  1754. }
  1755. my $p = $param;
  1756. $p =~ s/(<|>|%)//g;
  1757. my @p = split / /, $p;
  1758. my @n = split / /, uc $self->{$fld};
  1759. if ( $#p > 0 ) {
  1760. for ( my $i = 1 ; $i <= $#p ; $i++ ) {
  1761. $str .= substr( $n[ $i - 1 ], 0, $p[$i] );
  1762. }
  1763. }
  1764. else {
  1765. ($str) = split /--/, $self->{$fld};
  1766. }
  1767. $var =~ s/$param/$str/;
  1768. $var =~ s/\W//g if $fld eq 'phone';
  1769. }
  1770. if ( $param =~ /<\?lsmb (yy|mm|dd)/i ) {
  1771. my $p = $param;
  1772. $p =~ s/(<|>|%)//g;
  1773. my $spc = $p;
  1774. $spc =~ s/\w//g;
  1775. $spc = substr( $spc, 0, 1 );
  1776. my %d = ( yy => 1, mm => 2, dd => 3 );
  1777. my @p = ();
  1778. my @a = $self->split_date( $myconfig->{dateformat},
  1779. $self->{transdate} );
  1780. for ( sort keys %d ) { push @p, $a[ $d{$_} ] if ( $p =~ /$_/ ) }
  1781. $str = join $spc, @p;
  1782. $var =~ s/$param/$str/;
  1783. }
  1784. if ( $param =~ /<\?lsmb curr/i ) {
  1785. $var =~ s/$param/$self->{currency}/;
  1786. }
  1787. }
  1788. }
  1789. $query = qq|
  1790. UPDATE defaults
  1791. SET value = ?
  1792. WHERE setting_key = ?|;
  1793. $sth = $dbh->prepare($query);
  1794. $sth->execute( $dbvar, $fld ) || $self->dberror($query);
  1795. $dbh->commit;
  1796. $var;
  1797. }
  1798. sub db_prepare_vars {
  1799. my $self = shift;
  1800. for (@_) {
  1801. if ( !$self->{$_} and $self->{$_} ne "0" ) {
  1802. undef $self->{$_};
  1803. }
  1804. }
  1805. }
  1806. sub split_date {
  1807. my ( $self, $dateformat, $date ) = @_;
  1808. my $mm;
  1809. my $dd;
  1810. my $yy;
  1811. my $rv;
  1812. if ( !$date ) {
  1813. my @d = localtime;
  1814. $dd = $d[3];
  1815. $mm = ++$d[4];
  1816. $yy = substr( $d[5], -2 );
  1817. $mm = substr( "0$mm", -2 );
  1818. $dd = substr( "0$dd", -2 );
  1819. }
  1820. if ( $dateformat =~ /^yy/ ) {
  1821. if ($date) {
  1822. if ( $date =~ /\D/ ) {
  1823. ( $yy, $mm, $dd ) = split /\D/, $date;
  1824. $mm *= 1;
  1825. $dd *= 1;
  1826. $mm = substr( "0$mm", -2 );
  1827. $dd = substr( "0$dd", -2 );
  1828. $yy = substr( $yy, -2 );
  1829. $rv = "$yy$mm$dd";
  1830. }
  1831. else {
  1832. $rv = $date;
  1833. }
  1834. }
  1835. else {
  1836. $rv = "$yy$mm$dd";
  1837. }
  1838. }
  1839. elsif ( $dateformat =~ /^mm/ ) {
  1840. if ($date) {
  1841. if ( $date =~ /\D/ ) {
  1842. ( $mm, $dd, $yy ) = split /\D/, $date;
  1843. $mm *= 1;
  1844. $dd *= 1;
  1845. $mm = substr( "0$mm", -2 );
  1846. $dd = substr( "0$dd", -2 );
  1847. $yy = substr( $yy, -2 );
  1848. $rv = "$mm$dd$yy";
  1849. }
  1850. else {
  1851. $rv = $date;
  1852. }
  1853. }
  1854. else {
  1855. $rv = "$mm$dd$yy";
  1856. }
  1857. }
  1858. elsif ( $dateformat =~ /^dd/ ) {
  1859. if ($date) {
  1860. if ( $date =~ /\D/ ) {
  1861. ( $dd, $mm, $yy ) = split /\D/, $date;
  1862. $mm *= 1;
  1863. $dd *= 1;
  1864. $mm = substr( "0$mm", -2 );
  1865. $dd = substr( "0$dd", -2 );
  1866. $yy = substr( $yy, -2 );
  1867. $rv = "$dd$mm$yy";
  1868. }
  1869. else {
  1870. $rv = $date;
  1871. }
  1872. }
  1873. else {
  1874. $rv = "$dd$mm$yy";
  1875. }
  1876. }
  1877. ( $rv, $yy, $mm, $dd );
  1878. }
  1879. sub format_date {
  1880. # takes an iso date in, and converts it to the date for printing
  1881. my ( $self, $date ) = @_;
  1882. my $datestring;
  1883. if ( $date =~ /^\d{4}\D/ ) { # is an ISO date
  1884. $datestring = $self->{db_dateformat};
  1885. my ( $yyyy, $mm, $dd ) = split( /\W/, $date );
  1886. $datestring =~ s/y+/$yyyy/;
  1887. $datestring =~ s/mm/$mm/;
  1888. $datestring =~ s/dd/$dd/;
  1889. }
  1890. else { # return date
  1891. $datestring = $date;
  1892. }
  1893. $datestring;
  1894. }
  1895. sub from_to {
  1896. my ( $self, $yyyy, $mm, $interval ) = @_;
  1897. my @t;
  1898. my $dd = 1;
  1899. my $fromdate = "$yyyy-${mm}-01";
  1900. my $bd = 1;
  1901. if ( defined $interval ) {
  1902. if ( $interval == 12 ) {
  1903. $yyyy++;
  1904. }
  1905. else {
  1906. if ( ( $mm += $interval ) > 12 ) {
  1907. $mm -= 12;
  1908. $yyyy++;
  1909. }
  1910. if ( $interval == 0 ) {
  1911. @t = localtime(time);
  1912. $dd = $t[3];
  1913. $mm = $t[4] + 1;
  1914. $yyyy = $t[5] + 1900;
  1915. $bd = 0;
  1916. }
  1917. }
  1918. }
  1919. else {
  1920. if ( ++$mm > 12 ) {
  1921. $mm -= 12;
  1922. $yyyy++;
  1923. }
  1924. }
  1925. $mm--;
  1926. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yyyy ) - $bd );
  1927. $t[4]++;
  1928. $t[4] = substr( "0$t[4]", -2 );
  1929. $t[3] = substr( "0$t[3]", -2 );
  1930. $t[5] += 1900;
  1931. ( $self->format_date($fromdate), $self->format_date("$t[5]-$t[4]-$t[3]") );
  1932. }
  1933. sub audittrail {
  1934. my ( $self, $dbh, $myconfig, $audittrail ) = @_;
  1935. # table, $reference, $formname, $action, $id, $transdate) = @_;
  1936. my $query;
  1937. my $rv;
  1938. my $disconnect;
  1939. if ( !$dbh ) {
  1940. $dbh = $self->{dbh};
  1941. }
  1942. # if we have an id add audittrail, otherwise get a new timestamp
  1943. my @queryargs;
  1944. if ( $audittrail->{id} ) {
  1945. $query = qq|
  1946. SELECT value FROM defaults
  1947. WHERE setting_key = 'audittrail'|;
  1948. if ( $dbh->selectrow_array($query) ) {
  1949. my ( $null, $employee_id ) = $self->get_employee($dbh);
  1950. if ( $self->{audittrail} && !$myconfig ) {
  1951. chop $self->{audittrail};
  1952. my @a = split /\|/, $self->{audittrail};
  1953. my %newtrail = ();
  1954. my $key;
  1955. my $i;
  1956. my @flds = qw(tablename reference formname action transdate);
  1957. # put into hash and remove dups
  1958. while (@a) {
  1959. $key = "$a[2]$a[3]";
  1960. $i = 0;
  1961. $newtrail{$key} = { map { $_ => $a[ $i++ ] } @flds };
  1962. splice @a, 0, 5;
  1963. }
  1964. $query = qq|
  1965. INSERT INTO audittrail
  1966. (trans_id, tablename, reference,
  1967. formname, action, transdate,
  1968. employee_id)
  1969. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  1970. my $sth = $dbh->prepare($query) || $self->dberror($query);
  1971. foreach $key (
  1972. sort {
  1973. $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
  1974. } keys %newtrail
  1975. )
  1976. {
  1977. $i = 2;
  1978. $sth->bind_param( 1, $audittrail->{id} );
  1979. for (@flds) {
  1980. $sth->bind_param( $i++, $newtrail{$key}{$_} );
  1981. }
  1982. $sth->bind_param( $i++, $employee_id );
  1983. $sth->execute() || $self->dberror($query);
  1984. $sth->finish;
  1985. }
  1986. }
  1987. if ( $audittrail->{transdate} ) {
  1988. $query = qq|
  1989. INSERT INTO audittrail (
  1990. trans_id, tablename, reference,
  1991. formname, action, employee_id,
  1992. transdate)
  1993. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  1994. @queryargs = (
  1995. $audittrail->{id}, $audittrail->{tablename},
  1996. $audittrail->{reference}, $audittrail->{formname},
  1997. $audittrail->{action}, $employee_id,
  1998. $audittrail->{transdate}
  1999. );
  2000. }
  2001. else {
  2002. $query = qq|
  2003. INSERT INTO audittrail
  2004. (trans_id, tablename, reference,
  2005. formname, action, employee_id)
  2006. VALUES (?, ?, ?, ?, ?, ?)|;
  2007. @queryargs = (
  2008. $audittrail->{id}, $audittrail->{tablename},
  2009. $audittrail->{reference}, $audittrail->{formname},
  2010. $audittrail->{action}, $employee_id,
  2011. );
  2012. }
  2013. $sth = $dbh->prepare($query);
  2014. $sth->execute(@queryargs) || $self->dberror($query);
  2015. }
  2016. }
  2017. else {
  2018. $query = qq|SELECT current_timestamp|;
  2019. my ($timestamp) = $dbh->selectrow_array($query);
  2020. $rv =
  2021. "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2022. }
  2023. $rv;
  2024. }
  2025. 1;