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