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