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