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