summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: b8cd8f706abfcc6cdd0e0818a4849325e689d06b (plain)
  1. =head1 NAME
  2. Form
  3. =head1 SYNOPSIS
  4. This module provides general legacy support functions and the central object
  5. =head1 STATUS
  6. Deprecated
  7. =head1 COPYRIGHT
  8. #====================================================================
  9. # LedgerSMB
  10. # Small Medium Business Accounting software
  11. # http://www.ledgersmb.org/
  12. #
  13. # Copyright (C) 2006
  14. # This work contains copyrighted information from a number of sources
  15. # all used with permission.
  16. #
  17. # This file contains source code included with or based on SQL-Ledger
  18. # which is Copyright Dieter Simader and DWS Systems Inc. 2000-2005
  19. # and licensed under the GNU General Public License version 2 or, at
  20. # your option, any later version. For a full list including contact
  21. # information of contributors, maintainers, and copyright holders,
  22. # see the CONTRIBUTORS file.
  23. #
  24. # Original Copyright Notice from SQL-Ledger 2.6.17 (before the fork):
  25. # Copyright (C) 2000
  26. #
  27. # Author: DWS Systems Inc.
  28. # Web: http://www.sql-ledger.org
  29. #
  30. # Contributors: Thomas Bayen <bayen@gmx.de>
  31. # Antti Kaihola <akaihola@siba.fi>
  32. # Moritz Bunkus (tex)
  33. # Jim Rawlings <jim@your-dba.com> (DB2)
  34. #====================================================================
  35. #
  36. # This file has undergone whitespace cleanup.
  37. #
  38. #====================================================================
  39. #
  40. # main package
  41. #
  42. #====================================================================
  43. =head1 METHODS
  44. =over
  45. =cut
  46. #inline documentation
  47. use strict;
  48. use Math::BigFloat lib => 'GMP';
  49. use LedgerSMB::Sysconfig;
  50. use List::Util qw(first);
  51. use Time::Local;
  52. use Cwd;
  53. use File::Copy;
  54. use charnames ':full';
  55. use open ':utf8';
  56. package Form;
  57. =item new Form([$argstr])
  58. Returns a reference to new Form object. The initial set of attributes is
  59. obtained from $argstr, a CGI query string, or $ARGV[0]. All the values are
  60. run through unescape to undo any URI encoding.
  61. The version and dbversion attributes are set to hardcoded values; action,
  62. nextsub, path, script, and login are filtered to remove some dangerous values.
  63. Both menubar and lynx are set if path matches lynx.
  64. $form->error may be called to deny access on some attribute values.
  65. =cut
  66. sub new {
  67. my $type = shift;
  68. my $argstr = shift;
  69. if ($ENV{CONTENT_LENGTH} > $LedgerSMB::Sysconfig::max_post_size; ) {
  70. print "Status: 413\n Request entity too large\n\n";
  71. die "Error: Request entity too large\n";
  72. }
  73. read( STDIN, $_, $ENV{CONTENT_LENGTH} );
  74. if ($argstr) {
  75. $_ = $argstr;
  76. }
  77. elsif ( $ENV{QUERY_STRING} ) {
  78. $_ = $ENV{QUERY_STRING};
  79. }
  80. elsif ( $ARGV[0] ) {
  81. $_ = $ARGV[0];
  82. }
  83. my $self = {};
  84. %$self = split /[&=]/;
  85. for ( keys %$self ) { $self->{$_} = unescape( "", $self->{$_} ) }
  86. if ( substr( $self->{action}, 0, 1 ) !~ /( |\.)/ ) {
  87. $self->{action} = lc $self->{action};
  88. $self->{action} =~ s/( |-|,|\#|\/|\.$)/_/g;
  89. $self->{nextsub} = lc $self->{nextsub};
  90. $self->{nextsub} =~ s/( |-|,|\#|\/|\.$)/_/g;
  91. }
  92. $self->{login} =~ s/[^a-zA-Z0-9._+\@'-]//g;
  93. if (!$self->{company} && $ENV{HTTP_COOKIE}){
  94. $ENV{HTTP_COOKIE} =~ s/;\s*/;/g;
  95. my %cookie;
  96. my @cookies = split /;/, $ENV{HTTP_COOKIE};
  97. foreach (@cookies) {
  98. my ( $name, $value ) = split /=/, $_, 2;
  99. $cookie{$name} = $value;
  100. }
  101. my $ccookie = $cookie{LedgerSMB};
  102. $ccookie =~ s/.*:([^:]*)$/$1/;
  103. $self->{company} = $ccookie;
  104. }
  105. $self->{menubar} = 1 if $self->{path} =~ /lynx/i;
  106. #menubar will be deprecated, replaced with below
  107. $self->{lynx} = 1 if $self->{path} =~ /lynx/i;
  108. $self->{version} = "SVN Trunk";
  109. $self->{dbversion} = "1.2.0";
  110. bless $self, $type;
  111. if ( $self->{path} ne 'bin/lynx' ) { $self->{path} = 'bin/mozilla'; }
  112. if ( ( $self->{script} )
  113. and not List::Util::first { $_ eq $self->{script} }
  114. @{LedgerSMB::Sysconfig::scripts} )
  115. {
  116. $self->error( 'Access Denied', __LINE__, __FILE__ );
  117. }
  118. if ( ( $self->{action} =~ /(:|')/ ) || ( $self->{nextsub} =~ /(:|')/ ) ) {
  119. $self->error( "Access Denied", __LINE__, __FILE__ );
  120. }
  121. for ( keys %$self ) { $self->{$_} =~ s/\N{NULL}//g }
  122. if ( ($self->{action} eq 'redirect') || ($self->{nextsub} eq 'redirect') ) {
  123. $self->error( "Access Denied", __LINE__, __FILE__ );
  124. }
  125. $self;
  126. }
  127. =item $form->debug([$file]);
  128. Outputs the sorted contents of $form. If a filename is specified, log to it,
  129. otherwise output to STDOUT.
  130. =cut
  131. sub debug {
  132. my ( $self, $file ) = @_;
  133. if ($file) {
  134. open( FH, '>', "$file" ) or die $!;
  135. for ( sort keys %$self ) { print FH "$_ = $self->{$_}\n" }
  136. close(FH);
  137. }
  138. else {
  139. print "\n";
  140. for ( sort keys %$self ) { print "$_ = $self->{$_}\n" }
  141. }
  142. }
  143. =item $form->encode_all();
  144. Does nothing and is unused. Contains merely the comment # TODO;
  145. =cut
  146. sub encode_all {
  147. # TODO;
  148. }
  149. =item $form->decode_all();
  150. Does nothing and is unused. Contains merely the comment # TODO
  151. =cut
  152. sub decode_all {
  153. # TODO
  154. }
  155. =item $form->escape($str[, $beenthere]);
  156. Returns the URI-encoded $str. $beenthere is a boolean that when true forces a
  157. single encoding run. When false, it escapes the string twice if it detects
  158. that it is running on a version of Apache 2.0 earlier than 2.0.44.
  159. Note that recurring transaction support depends on this function escaping ','.
  160. =cut
  161. sub escape {
  162. my ( $self, $str, $beenthere ) = @_;
  163. # for Apache 2 we escape strings twice
  164. if ( ( $ENV{SERVER_SIGNATURE} =~ /Apache\/2\.(\d+)\.(\d+)/ )
  165. && !$beenthere )
  166. {
  167. $str = $self->escape( $str, 1 ) if $1 == 0 && $2 < 44;
  168. }
  169. utf8::encode($str);
  170. # SC: Adding commas to the ignore list will break recurring transactions
  171. $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
  172. $str;
  173. }
  174. =item $form->unescape($str);
  175. Returns the unencoded form of the URI-encoded $str.
  176. =cut
  177. sub unescape {
  178. my ( $self, $str ) = @_;
  179. $str =~ tr/+/ /;
  180. $str =~ s/\\$//;
  181. utf8::encode($str) if utf8::is_utf8($str);
  182. $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
  183. utf8::decode($str);
  184. $str =~ s/\r?\n/\n/g;
  185. $str;
  186. }
  187. =item $form->quote($str);
  188. Replaces all double quotes in $str with '&quot;'. Does nothing if $str is a
  189. reference.
  190. =cut
  191. sub quote {
  192. my ( $self, $str ) = @_;
  193. if ( $str && !ref($str) ) {
  194. $str =~ s/"/&quot;/g;
  195. }
  196. $str;
  197. }
  198. =item $form->unquote($str);
  199. Replaces all '&quot;' in $str with double quotes. Does nothing if $str is a
  200. reference.
  201. =cut
  202. sub unquote {
  203. my ( $self, $str ) = @_;
  204. if ( $str && !ref($str) ) {
  205. $str =~ s/&quot;/"/g;
  206. }
  207. $str;
  208. }
  209. =item $form->hide_form([...]);
  210. Outputs hidden HTML form fields to STDOUT. If values are passed into this
  211. function, only those $form values are output. If no values are passed in, all
  212. $form values are output as well as deleting $form->{header}. Values from the
  213. $form object are run through $form->quote, whereas keys/names are not.
  214. Sample output:
  215. <input type="hidden" name="login" value="testuser" />
  216. =cut
  217. sub hide_form {
  218. my $self = shift;
  219. if (@_) {
  220. for (@_) {
  221. print qq|<input type="hidden" name="$_" value="|
  222. . $self->quote( $self->{$_} )
  223. . qq|" />\n|;
  224. }
  225. }
  226. else {
  227. delete $self->{header};
  228. for ( sort keys %$self ) {
  229. print qq|<input type="hidden" name="$_" value="|
  230. . $self->quote( $self->{$_} )
  231. . qq|" />\n|;
  232. }
  233. }
  234. }
  235. =item $form->error($msg);
  236. Output an error message, $msg. If a CGI environment is detected, this outputs
  237. an HTTP and HTML header section if required, and displays the message after
  238. running it through $form->format_string. If it is not a CGI environment and
  239. $ENV{error_function} is set, call the specified function with $msg as the sole
  240. argument. Otherwise, this function simply dies with $msg.
  241. This function does not return. Execution is terminated at the end of the
  242. appropriate path.
  243. =cut
  244. sub error {
  245. my ( $self, $msg ) = @_;
  246. if ( $ENV{GATEWAY_INTERFACE} ) {
  247. $self->{msg} = $msg;
  248. $self->{format} = "html";
  249. $self->format_string('msg');
  250. delete $self->{pre};
  251. if ( !$self->{header} ) {
  252. $self->header;
  253. }
  254. print
  255. qq|<body><h2 class="error">Error!</h2> <p><b>$self->{msg}</b></body>|;
  256. exit;
  257. }
  258. else {
  259. if ( $ENV{error_function} ) {
  260. __PACKAGE__->can($ENV{error_function})->($msg);
  261. }
  262. die "Error: $msg\n";
  263. }
  264. }
  265. =item $form->info($msg);
  266. Output an informational message, $msg. If a CGI environment is detected, this
  267. outputs an HTTP and HTML header section if required, and displays the message
  268. in bold tags without escaping. If it is not a CGI environment and
  269. $ENV{info_function} is set, call the specified function with $msg as the sole
  270. argument. Otherwise, this function simply prints $msg to STDOUT.
  271. =cut
  272. sub info {
  273. my ( $self, $msg ) = @_;
  274. if ( $ENV{GATEWAY_INTERFACE} ) {
  275. $msg =~ s/\n/<br>/g;
  276. delete $self->{pre};
  277. if ( !$self->{header} ) {
  278. $self->header;
  279. print qq| <body>|;
  280. $self->{header} = 1;
  281. }
  282. print "<b>$msg</b>";
  283. }
  284. else {
  285. if ( $ENV{info_function} ) {
  286. __PACKAGE__->can($ENV{info_function})->($msg);
  287. }
  288. else {
  289. print "$msg\n";
  290. }
  291. }
  292. }
  293. =item $form->numtextrows($str, $cols[, $maxrows]);
  294. Returns the number of rows of $cols columns can be formed by $str. If $maxrows
  295. is set and the number of rows is greater than $maxrows, this returns $maxrows.
  296. In the determination of rowcount, newline characters, "\n", are taken into
  297. account while spaces are not.
  298. =cut
  299. sub numtextrows {
  300. my ( $self, $str, $cols, $maxrows ) = @_;
  301. my $rows = 0;
  302. for ( split /\n/, $str ) {
  303. $rows += int( ( (length) - 2 ) / $cols ) + 1;
  304. }
  305. $maxrows = $rows unless defined $maxrows;
  306. return ( $rows > $maxrows ) ? $maxrows : $rows;
  307. }
  308. =item $form->dberror($msg);
  309. Outputs a message as in $form->error but with $DBI::errstr automatically
  310. appended to $msg.
  311. =cut
  312. sub dberror {
  313. my ( $self, $msg ) = @_;
  314. $self->error( "$msg\n" . $DBI::errstr );
  315. }
  316. =item $form->isblank($name, $msg);
  317. Calls $form->error($msg) if the value of $form->{$name} matches /^\s*$/.
  318. =cut
  319. sub isblank {
  320. my ( $self, $name, $msg ) = @_;
  321. $self->error($msg) if $self->{$name} =~ /^\s*$/;
  322. }
  323. =item $form->header([$init, $headeradd]);
  324. Outputs HTML and HTTP headers and sets $form->{header} to indicate that headers
  325. have been output. If called with $form->{header} set or in a non-CGI
  326. environment, does not output anything. $init is ignored. $headeradd is data
  327. to be added to the <head> portion of the output headers. $form->{stylesheet},
  328. $form->{title}, $form->{titlebar}, and $form->{pre} all affect the output of
  329. this function.
  330. If the stylesheet indicated by $form->{stylesheet} exists, output a link tag
  331. to reference it. If $form->{title} is false, the title text is the value of
  332. $form->{titlebar}. If $form->{title} is true, the title text takes the form of
  333. "$form->{title} - $form->{titlebar}". The value of $form->{pre} is output
  334. immediately after the closing of <head>.
  335. =cut
  336. sub header {
  337. my ( $self, $init, $headeradd ) = @_;
  338. return if $self->{header};
  339. my ( $stylesheet, $favicon, $charset );
  340. if ( $ENV{GATEWAY_INTERFACE} ) {
  341. if ( $self->{stylesheet} && ( -f "css/$self->{stylesheet}" ) ) {
  342. $stylesheet =
  343. qq|<link rel="stylesheet" href="css/$self->{stylesheet}" type="text/css" title="LedgerSMB stylesheet" />\n|;
  344. }
  345. $self->{charset} ||= "utf-8";
  346. $charset =
  347. qq|<meta http-equiv="content-type" content="text/html; charset=$self->{charset}" />\n|;
  348. $self->{titlebar} =
  349. ( $self->{title} )
  350. ? "$self->{title} - $self->{titlebar}"
  351. : $self->{titlebar};
  352. print qq|Content-Type: text/html; charset=utf-8\n\n
  353. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  354. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  355. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  356. <head>
  357. <title>$self->{titlebar}</title>
  358. <meta http-equiv="Pragma" content="no-cache" />
  359. <meta http-equiv="Expires" content="-1" />
  360. <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  361. $stylesheet
  362. $charset
  363. <meta name="robots" content="noindex,nofollow" />
  364. $headeradd
  365. </head>
  366. $self->{pre} \n|;
  367. }
  368. $self->{header} = 1;
  369. }
  370. =item $form->redirect([$msg]);
  371. If $form->{callback} is set or $msg is not set, call the redirect function in
  372. common.pl. If main::redirect returns, exit.
  373. Otherwise, output $msg as an informational message with $form->info($msg).
  374. =cut
  375. sub redirect {
  376. my ( $self, $msg ) = @_;
  377. if ( $self->{callback} || !$msg ) {
  378. main::redirect();
  379. exit;
  380. }
  381. else {
  382. $self->info($msg);
  383. }
  384. }
  385. =item $form->sort_columns(@columns);
  386. Sorts the list @columns. If $form->{sort} is unset, do nothing. If the value
  387. of $form->{sort} does not exist in @columns, returns the list formed by the
  388. value of $form->{sort} followed by the values of @columns. If the value of
  389. $form->{sort} is in @columns, return the list formed by @columns with the value
  390. of $form->{sort} moved to the head of the list.
  391. =cut
  392. sub sort_columns {
  393. my ( $self, @columns ) = @_;
  394. if ( $self->{sort} ) {
  395. $self->{sort} =~ s/^"*(.*?)"*$/$1/;
  396. if (@columns) {
  397. @columns = grep !/^$self->{sort}$/, @columns;
  398. if ($self->{sort} !~ /^\w*$/){
  399. $self->{sort} = $self->{dbh}->quote_identifier($self->{sort});
  400. }
  401. splice @columns, 0, 0, $self->{sort};
  402. }
  403. }
  404. @columns;
  405. }
  406. =item $form->sort_order($columns[, $ordinal]);
  407. Returns a string that contains ordering details for the columns in SQL form.
  408. $columns is a reference to a list of columns, $ordinal is a reference to a hash
  409. that maps column names to ordinal positions. This function depends upon the
  410. values of $form->{direction}, $form->{sort}, and $form->{oldsort}.
  411. If $form->{direction} is false, it becomes 'ASC'. If $form->{direction} is true
  412. and $form->{sort} and $form->{oldsort} are equal, reverse the order specified by
  413. $form->{direction}. $form->{oldsort} is set to the same value as $form->{sort}
  414. The actual sorting of $columns happens as in $form->sort_columns(@$columns).
  415. If $ordinal is set, the positions given by it are substituted for the names of
  416. columns returned.
  417. =cut
  418. sub sort_order {
  419. my ( $self, $columns, $ordinal ) = @_;
  420. # setup direction
  421. if ( $self->{direction} ) {
  422. if ( $self->{sort} eq $self->{oldsort} ) {
  423. if ( $self->{direction} eq 'ASC' ) {
  424. $self->{direction} = "DESC";
  425. }
  426. else {
  427. $self->{direction} = "ASC";
  428. }
  429. }
  430. }
  431. else {
  432. $self->{direction} = "ASC";
  433. }
  434. $self->{oldsort} = $self->{sort};
  435. my @a = $self->sort_columns( @{$columns} );
  436. if (ref $ordinal eq 'HASH') {
  437. $a[0] =
  438. ( $ordinal->{ $a[$_] } )
  439. ? "$ordinal->{$a[0]} $self->{direction}"
  440. : "$a[0] $self->{direction}";
  441. for ( 1 .. $#a ) {
  442. $a[$_] = $ordinal->{ $a[$_] } if $ordinal->{ $a[$_] };
  443. }
  444. }
  445. else {
  446. $a[0] .= " $self->{direction}";
  447. }
  448. my $sortorder = join ',', @a;
  449. $sortorder;
  450. }
  451. =item $form->format_amount($myconfig, $amount, $places, $dash);
  452. Returns $amount as formatted in the form specified by $form->{numberformat}.
  453. $places is the number of decimal places to have in the output. $dash indicates
  454. how to represent conditions surrounding values.
  455. +-------+----------+---------+------+
  456. | $dash | -1.00 | 1.00 | 0.00 |
  457. +-------+----------+---------+------+
  458. | - | (1.00) | 1.00 | - |
  459. | DRCR | 1.00 DR | 1.00 CR | DRCR |
  460. | 0 | -1.00 | 1.00 | 0.00 |
  461. | x | -1.00 | 1.00 | x |
  462. | undef | -1.00 | 1.00 | |
  463. +-------+----------+---------+------+
  464. Sample behaviour of the formatted output of various numbers for select $dash
  465. values.
  466. =cut
  467. sub format_amount {
  468. my ( $self, $myconfig, $amount, $places, $dash ) = @_;
  469. my $negative;
  470. if ($amount) {
  471. $amount = $self->parse_amount( $myconfig, $amount );
  472. $negative = ( $amount < 0 );
  473. $amount =~ s/-//;
  474. }
  475. if ( $places =~ /\d+/ ) {
  476. #$places = 4 if $places == 2;
  477. $amount = $self->round_amount( $amount, $places );
  478. }
  479. # is the amount negative
  480. # Parse $myconfig->{numberformat}
  481. my ( $ts, $ds ) = ( $1, $2 );
  482. if ($amount) {
  483. if ( $myconfig->{numberformat} ) {
  484. my ( $whole, $dec ) = split /\./, "$amount";
  485. $amount = join '', reverse split //, $whole;
  486. if ($places) {
  487. $dec .= "0" x $places;
  488. $dec = substr( $dec, 0, $places );
  489. }
  490. if ( $myconfig->{numberformat} eq '1,000.00' ) {
  491. $amount =~ s/\d{3,}?/$&,/g;
  492. $amount =~ s/,$//;
  493. $amount = join '', reverse split //, $amount;
  494. $amount .= "\.$dec" if ( $dec ne "" );
  495. }
  496. elsif ( $myconfig->{numberformat} eq '1 000.00' ) {
  497. $amount =~ s/\d{3,}?/$& /g;
  498. $amount =~ s/\s$//;
  499. $amount = join '', reverse split //, $amount;
  500. $amount .= "\.$dec" if ( $dec ne "" );
  501. }
  502. elsif ( $myconfig->{numberformat} eq "1'000.00" ) {
  503. $amount =~ s/\d{3,}?/$&'/g;
  504. $amount =~ s/'$//;
  505. $amount = join '', reverse split //, $amount;
  506. $amount .= "\.$dec" if ( $dec ne "" );
  507. }
  508. elsif ( $myconfig->{numberformat} eq '1.000,00' ) {
  509. $amount =~ s/\d{3,}?/$&./g;
  510. $amount =~ s/\.$//;
  511. $amount = join '', reverse split //, $amount;
  512. $amount .= ",$dec" if ( $dec ne "" );
  513. }
  514. elsif ( $myconfig->{numberformat} eq '1000,00' ) {
  515. $amount = "$whole";
  516. $amount .= ",$dec" if ( $dec ne "" );
  517. }
  518. elsif ( $myconfig->{numberformat} eq '1000.00' ) {
  519. $amount = "$whole";
  520. $amount .= ".$dec" if ( $dec ne "" );
  521. }
  522. if ( $dash =~ /-/ ) {
  523. $amount = ($negative) ? "($amount)" : "$amount";
  524. }
  525. elsif ( $dash =~ /DRCR/ ) {
  526. $amount = ($negative) ? "$amount DR" : "$amount CR";
  527. }
  528. else {
  529. $amount = ($negative) ? "-$amount" : "$amount";
  530. }
  531. }
  532. }
  533. else {
  534. if ( $dash eq "0" && $places ) {
  535. if ( $myconfig->{numberformat} =~ /0,00$/ ) {
  536. $amount = "0" . "," . "0" x $places;
  537. }
  538. else {
  539. $amount = "0" . "." . "0" x $places;
  540. }
  541. }
  542. else {
  543. $amount = ( $dash ne "" ) ? "$dash" : "";
  544. }
  545. }
  546. $amount;
  547. }
  548. =item $form->parse_amount($myconfig, $amount);
  549. Return a Math::BigFloat containing the value of $amount where $amount is
  550. formatted as $myconfig->{numberformat}. If $amount is '' or undefined, it is
  551. treated as zero. DRCR and parenthesis notation is accepted in addition to
  552. negative sign notation.
  553. Calls $form->error if the value is NaN.
  554. =cut
  555. sub parse_amount {
  556. my ( $self, $myconfig, $amount ) = @_;
  557. if ( ( $amount eq '' ) or ( ! defined $amount ) ) {
  558. $amount = 0;
  559. }
  560. if ( UNIVERSAL::isa( $amount, 'Math::BigFloat' ) )
  561. { # Amount may not be an object
  562. return $amount;
  563. }
  564. my $numberformat = $myconfig->{numberformat};
  565. if ( ( $numberformat eq '1.000,00' )
  566. || ( $numberformat eq '1000,00' ) )
  567. {
  568. $amount =~ s/\.//g;
  569. $amount =~ s/,/./;
  570. }
  571. elsif ( $numberformat eq '1 000.00' ) {
  572. $amount =~ s/\s//g;
  573. }
  574. elsif ( $numberformat eq "1'000.00" ) {
  575. $amount =~ s/'//g;
  576. }
  577. $amount =~ s/,//g;
  578. if ( $amount =~ s/\((\d*\.?\d*)\)/$1/ ) {
  579. $amount = $1 * -1;
  580. }
  581. elsif ( $amount =~ s/(\d*\.?\d*)\s?DR/$1/ ) {
  582. $amount = $1 * -1;
  583. }
  584. $amount =~ s/\s?CR//;
  585. $amount =~ /(\d*)\.(\d*)/;
  586. my $decimalplaces = length $1 + length $2;
  587. $amount = new Math::BigFloat($amount);
  588. if ($amount->is_nan){
  589. $self->error("Invalid number detected during parsing");
  590. }
  591. return ( $amount * 1 );
  592. }
  593. =item $form->round_amount($amount, $places);
  594. Rounds the provided $amount to $places decimal places.
  595. =cut
  596. sub round_amount {
  597. my ( $self, $amount, $places ) = @_;
  598. # These rounding rules follow from the previous implementation.
  599. # They should be changed to allow different rules for different accounts.
  600. Math::BigFloat->round_mode('+inf') if $amount >= 0;
  601. Math::BigFloat->round_mode('-inf') if $amount < 0;
  602. $amount = Math::BigFloat->new($amount)->ffround( -$places ) if $places >= 0;
  603. $amount = Math::BigFloat->new($amount)->ffround( -( $places - 1 ) )
  604. if $places < 0;
  605. $amount->precision(undef); #we are assuming whole cents so do not round
  606. #immediately on arithmatic. This is necessary
  607. #because Math::BigFloat is arithmatically
  608. #correct wrt accuracy and precision.
  609. return $amount;
  610. }
  611. =item $form->db_parse_numeric('sth' => $sth, ['arrayref' => $arrayref, 'hashref' => $hashref])
  612. Converts numeric values in the result set $arrayref or $hashref to
  613. Math::BigFloat using $sth to determine which fields are numeric.
  614. =cut
  615. sub db_parse_numeric {
  616. my $self = shift;
  617. my %args = @_;
  618. my ($sth, $arrayref, $hashref) = ($args{sth}, $args{arrayref},
  619. $args{hashref});
  620. my @types = @{$sth->{TYPE}};
  621. my @names = @{$sth->{NAME_lc}};
  622. for (0 .. $#names){
  623. # numeric float4/real
  624. if ($types[$_] == 3 or $types[$_] ==2) {
  625. $arrayref->[$_] = Math::BigFloat->new($arrayref->[$_])
  626. if defined $arrayref;
  627. $hashref->{$names[$_]} = Math::BigFloat->new($hashref->{$names[$_]})
  628. if defined $hashref;
  629. }
  630. }
  631. return ($hashref || $arrayref);
  632. }
  633. =item $form->get_my_emp_num($myconfig);
  634. Function to get the employee number of the user $form->{login}. $myconfig is
  635. only used to create %myconfig. $form->{emp_num} is set to the retrieved value.
  636. This function is currently (2007-08-02) only used by pos.conf.pl.
  637. =cut
  638. sub get_my_emp_num {
  639. my ( $self, $myconfig) = @_;
  640. my %myconfig = %{$myconfig};
  641. my $dbh = $self->{dbh};
  642. # we got a connection, check the version
  643. my $query = qq|
  644. SELECT employeenumber FROM employee
  645. WHERE login = ?|;
  646. my $sth = $dbh->prepare($query);
  647. $sth->execute( $self->{login} ) || $self->dberror($query);
  648. my ($id) = $sth->fetchrow_array;
  649. $sth->finish;
  650. $self->{'emp_num'} = $id;
  651. }
  652. =item $form->format_string(@fields);
  653. Escape the values of $form selected by @fields for the format specified by
  654. $form->{format}.
  655. =cut
  656. sub format_string {
  657. my ( $self, @fields ) = @_;
  658. my $format = $self->{format};
  659. if ( $self->{format} =~ /(postscript|pdf)/ ) {
  660. $format = 'tex';
  661. }
  662. my %replace = (
  663. 'order' => {
  664. html => [ '<', '>', '\n', '\r' ],
  665. txt => [ '\n', '\r' ],
  666. tex => [
  667. quotemeta('\\'), '&', '\n', '\r',
  668. '\$', '%', '_', '#',
  669. quotemeta('^'), '{', '}', '<',
  670. '>', '£'
  671. ]
  672. },
  673. html => {
  674. '<' => '&lt;',
  675. '>' => '&gt;',
  676. '\n' => '<br />',
  677. '\r' => '<br />'
  678. },
  679. txt => { '\n' => "\n", '\r' => "\r" },
  680. tex => {
  681. '&' => '\&',
  682. '$' => '\$',
  683. '%' => '\%',
  684. '_' => '\_',
  685. '#' => '\#',
  686. quotemeta('^') => '\^\\',
  687. '{' => '\{',
  688. '}' => '\}',
  689. '<' => '$<$',
  690. '>' => '$>$',
  691. '\n' => '\newline ',
  692. '\r' => '\newline ',
  693. '£' => '\pounds ',
  694. quotemeta('\\') => '/'
  695. }
  696. );
  697. my $key;
  698. foreach $key ( @{ $replace{order}{$format} } ) {
  699. for (@fields) { $self->{$_} =~ s/$key/$replace{$format}{$key}/g }
  700. }
  701. }
  702. =item $form->datetonum($myconfig, $date[, $picture]);
  703. Converts $date from the format $myconfig->{dateformat} to the format 'yyyymmdd'.
  704. If the year extracted is only two-digits, the year given is assumed to be in the
  705. range 2000-2099.
  706. If $date does not contain any digits, datetonum does nothing.
  707. $picture is ignored.
  708. =cut
  709. sub datetonum {
  710. my ( $self, $myconfig, $date, $picture ) = @_;
  711. if ( $date && $date =~ /\D/ ) {
  712. my $yy;
  713. my $mm;
  714. my $dd;
  715. if ( $date =~ /^\d{4}-\d\d-\d\d$/ ) {
  716. ( $yy, $mm, $dd ) = split /\D/, $date;
  717. } if ( $myconfig->{dateformat} =~ /^yy/ ) {
  718. ( $yy, $mm, $dd ) = split /\D/, $date;
  719. } elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  720. ( $mm, $dd, $yy ) = split /\D/, $date;
  721. } elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  722. ( $dd, $mm, $yy ) = split /\D/, $date;
  723. }
  724. $dd *= 1;
  725. $mm *= 1;
  726. $yy += 2000 if length $yy == 2;
  727. $dd = substr( "0$dd", -2 );
  728. $mm = substr( "0$mm", -2 );
  729. $date = "$yy$mm$dd";
  730. }
  731. $date;
  732. }
  733. =item $form->add_date($myconfig, $date, $repeat, $unit);
  734. Returns the date $repeat $units from $date in the input format. $date can
  735. either be in $myconfig->{dateformat} or 'yyyymmdd' (four digit year required for
  736. this option). The valid values for $unit are 'days', 'weeks', 'months', and
  737. 'years'.
  738. This function is unreliable for $unit values other than 'days' or 'weeks' and
  739. can die horribly.
  740. =cut
  741. sub add_date {
  742. my ( $self, $myconfig, $date, $repeat, $unit ) = @_;
  743. my $diff = 0;
  744. my $spc = $myconfig->{dateformat};
  745. my $yy;
  746. my $mm;
  747. my $dd;
  748. $spc =~ s/\w//g;
  749. $spc = substr( $spc, 0, 1 );
  750. if ($date) {
  751. if ( $date =~ /\D/ ) {
  752. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  753. ( $yy, $mm, $dd ) = split /\D/, $date;
  754. }
  755. elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  756. ( $mm, $dd, $yy ) = split /\D/, $date;
  757. }
  758. elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  759. ( $dd, $mm, $yy ) = split /\D/, $date;
  760. }
  761. }
  762. else {
  763. # ISO
  764. ( $yy, $mm, $dd ) = ($date =~ /(....)(..)(..)/);
  765. }
  766. if ( $unit eq 'days' ) {
  767. $diff = $repeat * 86400;
  768. }
  769. elsif ( $unit eq 'weeks' ) {
  770. $diff = $repeat * 604800;
  771. }
  772. elsif ( $unit eq 'months' ) {
  773. $diff = $mm + $repeat;
  774. my $whole = int( $diff / 12 );
  775. $yy += $whole;
  776. $mm = ( $diff % 12 );
  777. $mm = '12' if $mm == 0;
  778. $yy-- if $mm == 12;
  779. $diff = 0;
  780. }
  781. elsif ( $unit eq 'years' ) {
  782. $yy += $repeat;
  783. }
  784. $mm--;
  785. my @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yy ) + $diff );
  786. $t[4]++;
  787. $mm = substr( "0$t[4]", -2 );
  788. $dd = substr( "0$t[3]", -2 );
  789. $yy = $t[5] + 1900;
  790. if ( $date =~ /\D/ ) {
  791. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  792. $date = "$yy$spc$mm$spc$dd";
  793. }
  794. elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  795. $date = "$mm$spc$dd$spc$yy";
  796. }
  797. elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  798. $date = "$dd$spc$mm$spc$yy";
  799. }
  800. }
  801. else {
  802. $date = "$yy$mm$dd";
  803. }
  804. }
  805. $date;
  806. }
  807. =item $form->print_button($button, $name);
  808. Outputs a submit button to STDOUT. $button is a hashref that contains data
  809. about buttons, $name is the key for the element in $button to output. Each
  810. value in $button is a reference to a hash of two elements, 'key' and 'value'.
  811. $name is the value of the button that gets sent to the server when clicked,
  812. $button->{$name}{key} is the accesskey, and $button->{$name}{value} is the label
  813. for the button.
  814. =cut
  815. sub print_button {
  816. my ( $self, $button, $name ) = @_;
  817. print
  818. 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|;
  819. }
  820. # Database routines used throughout
  821. =item $form->db_init($myconfig);
  822. Connect to the database that $myconfig is set to use and initialise the base
  823. parameters. The connection handle becomes $form->{dbh} and
  824. $form->{custom_db_fields} is populated. The connection initiated has
  825. autocommit disabled.
  826. =cut
  827. sub db_init {
  828. my ( $self, $myconfig ) = @_;
  829. # Handling of HTTP Basic Auth headers
  830. my $auth = $ENV{'HTTP_AUTHORIZATION'};
  831. $auth =~ s/Basic //i; # strip out basic authentication preface
  832. $auth = MIME::Base64::decode($auth);
  833. my ($login, $password) = split(/:/, $auth);
  834. $self->{login} = $login;
  835. if (!$self->{company}){
  836. $self->{company} = $LedgerSMB::Sysconfig::default_db;
  837. }
  838. my $dbname = $self->{company};
  839. my $dbconfig = { dbconnect => "dbi:Pg:dbname=$dbname",
  840. dbuser => $login,
  841. dbpasswd => $password
  842. };
  843. $self->{dbh} = $self->dbconnect_noauto($dbconfig) || $self->dberror();
  844. $self->{dbh}->{pg_server_prepare} = 0;
  845. my $dbh = $self->{dbh};
  846. my %date_query = (
  847. 'mm/dd/yy' => 'set DateStyle to \'SQL, US\'',
  848. 'mm-dd-yy' => 'set DateStyle to \'POSTGRES, US\'',
  849. 'dd/mm/yy' => 'set DateStyle to \'SQL, EUROPEAN\'',
  850. 'dd-mm-yy' => 'set DateStyle to \'POSTGRES, EUROPEAN\'',
  851. 'dd.mm.yy' => 'set DateStyle to \'GERMAN\''
  852. );
  853. $self->{dbh}->do( $date_query{ $myconfig->{dateformat} } );
  854. $self->{db_dateformat} = $myconfig->{dateformat}; #shim
  855. # This is the general version check
  856. my $sth = $dbh->prepare("
  857. SELECT value FROM defaults
  858. WHERE setting_key = 'version'");
  859. $sth->execute;
  860. my ($dbversion) = $sth->fetchrow_array;
  861. if ($dbversion ne $self->{dbversion}){
  862. $self->error("Database is not the expected version.");
  863. }
  864. my $query = "SELECT t.extends,
  865. coalesce (t.table_name, 'custom_' || extends)
  866. || ':' || f.field_name as field_def
  867. FROM custom_table_catalog t
  868. JOIN custom_field_catalog f USING (table_id)";
  869. my $sth = $self->{dbh}->prepare($query);
  870. $sth->execute;
  871. my $ref;
  872. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  873. push @{ $self->{custom_db_fields}{ $ref->{extends} } },
  874. $ref->{field_def};
  875. }
  876. }
  877. =item $form->run_custom_queries($tablename, $query_type[, $linenum]);
  878. Runs queries against custom fields for the specified $query_type against
  879. $tablename.
  880. Valid values for $query_type are any casing of 'SELECT', 'INSERT', and 'UPDATE'.
  881. =cut
  882. sub run_custom_queries {
  883. my ( $self, $tablename, $query_type, $linenum ) = @_;
  884. my $dbh = $self->{dbh};
  885. if ( $query_type !~ /^(select|insert|update)$/i ) {
  886. $self->error(
  887. "Passed incorrect query type to run_custom_queries."
  888. );
  889. }
  890. my @rc;
  891. my %temphash;
  892. my @templist;
  893. my @elements;
  894. my $query;
  895. my $did_insert;
  896. my $ins_values;
  897. my $sth;
  898. if ($linenum) {
  899. $linenum = "_$linenum";
  900. }
  901. $query_type = uc($query_type);
  902. for ( @{ $self->{custom_db_fields}{$tablename} } ) {
  903. @elements = split( /:/, $_ );
  904. push @{ $temphash{ $elements[0] } }, $elements[1];
  905. }
  906. for ( keys %temphash ) {
  907. my @data;
  908. my $ins_values;
  909. $query = "$query_type ";
  910. if ( $query_type eq 'UPDATE' ) {
  911. $query = "DELETE FROM $_ WHERE row_id = ?";
  912. my $sth = $dbh->prepare($query);
  913. $sth->execute( $self->{ "id" . "$linenum" } )
  914. || $self->dberror($query);
  915. }
  916. elsif ( $query_type eq 'INSERT' ) {
  917. $query .= " INTO $_ (";
  918. }
  919. my $first = 1;
  920. for ( @{ $temphash{$_} } ) {
  921. $query .= "$_";
  922. if ( $query_type eq 'UPDATE' ) {
  923. $query .= '= ?';
  924. }
  925. $ins_values .= "?, ";
  926. $query .= ", ";
  927. $first = 0;
  928. if ( $query_type eq 'UPDATE' or $query_type eq 'INSERT' ) {
  929. push @data, $self->{"$_$linenum"};
  930. }
  931. }
  932. if ( $query_type ne 'INSERT' ) {
  933. $query =~ s/, $//;
  934. }
  935. if ( $query_type eq 'SELECT' ) {
  936. $query .= " FROM $_";
  937. }
  938. if ( $query_type eq 'SELECT' or $query_type eq 'UPDATE' ) {
  939. $query .= " WHERE row_id = ?";
  940. }
  941. if ( $query_type eq 'INSERT' ) {
  942. $query .= " row_id) VALUES ($ins_values ?)";
  943. }
  944. if ( $query_type eq 'SELECT' ) {
  945. push @rc, [$query];
  946. }
  947. else {
  948. unshift( @data, $query );
  949. push @rc, [@data];
  950. }
  951. }
  952. if ( $query_type eq 'INSERT' ) {
  953. for (@rc) {
  954. $query = shift( @{$_} );
  955. $sth = $dbh->prepare($query)
  956. || $self->db_error($query);
  957. $sth->execute( @{$_}, $self->{id} )
  958. || $self->dberror($query);
  959. $sth->finish;
  960. $did_insert = 1;
  961. }
  962. }
  963. elsif ( $query_type eq 'UPDATE' ) {
  964. @rc = $self->run_custom_queries( $tablename, 'INSERT', $linenum );
  965. }
  966. elsif ( $query_type eq 'SELECT' ) {
  967. for (@rc) {
  968. my $query = shift @{$_};
  969. my $sth = $self->{dbh}->prepare($query);
  970. $sth->execute( $self->{id} );
  971. my $ref = $sth->fetchrow_hashref('NAME_lc');
  972. for ( keys %{$ref} ) {
  973. $self->{$_} = $ref->{$_};
  974. }
  975. }
  976. }
  977. @rc;
  978. }
  979. =item $form->dbconnect($myconfig);
  980. Returns an autocommit connection to the database specified in $myconfig.
  981. =cut
  982. sub dbconnect {
  983. my ( $self, $myconfig ) = @_;
  984. # connect to database
  985. my $dbh = DBI->connect( $myconfig->{dbconnect},
  986. $myconfig->{dbuser}, $myconfig->{dbpasswd} )
  987. or $self->dberror;
  988. $dbh->{pg_enable_utf8} = 1;
  989. # set db options
  990. if ( $myconfig->{dboptions} ) {
  991. $dbh->do( $myconfig->{dboptions} )
  992. || $self->dberror( $myconfig->{dboptions} );
  993. }
  994. $dbh;
  995. }
  996. =item $form->dbconnect_noauto($myconfig);
  997. Returns a non-autocommit connection to the database specified in $myconfig.
  998. =cut
  999. sub dbconnect_noauto {
  1000. my ( $self, $myconfig ) = @_;
  1001. # connect to database
  1002. my $dbh = DBI->connect(
  1003. $myconfig->{dbconnect}, $myconfig->{dbuser},
  1004. $myconfig->{dbpasswd}, { AutoCommit => 0 }
  1005. ) or $self->dberror;
  1006. $dbh->{pg_enable_utf8} = 1;
  1007. # set db options
  1008. if ( $myconfig->{dboptions} ) {
  1009. $dbh->do( $myconfig->{dboptions} );
  1010. }
  1011. $dbh;
  1012. }
  1013. =item $form->dbquote($var);
  1014. If $var is an empty string, return NULL, otherwise return $var as quoted by
  1015. $form->{dbh}->quote($var).
  1016. =cut
  1017. sub dbquote {
  1018. my ( $self, $var ) = @_;
  1019. if ( $var eq '' ) {
  1020. $_ = "NULL";
  1021. }
  1022. else {
  1023. $_ = $self->{dbh}->quote($var);
  1024. }
  1025. $_;
  1026. }
  1027. =item $form->update_balance($dbh, $table, $field, $where, $value);
  1028. B<WARNING>: This is a dangerous private function. All apps calling it must be
  1029. careful to avoid SQL injection issues.
  1030. If $value is set, sets the value of $field in $table to the sum of the current
  1031. stored value and $value. In order to not annihilate the values in $table,
  1032. $where must contain a WHERE clause that limits the UPDATE to a single row.
  1033. =cut
  1034. sub update_balance {
  1035. # This is a dangerous private function. All apps calling it must
  1036. # be careful to avoid SQL injection issues
  1037. my ( $self, $dbh, $table, $field, $where, $value ) = @_;
  1038. $table = $dbh->quote_identifier($table);
  1039. $field = $dbh->quote_identifier($field);
  1040. # if we have a value, go do it
  1041. if ($value) {
  1042. # retrieve balance from table
  1043. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  1044. my ($balance) = $dbh->selectrow_array($query);
  1045. $balance = $dbh->quote($balance + $value);
  1046. # update balance
  1047. $query = "UPDATE $table SET $field = $balance WHERE $where";
  1048. $dbh->do($query) || $self->dberror($query);
  1049. }
  1050. }
  1051. =item $form->update_exchangerate($dbh, $curr, $transdate, $buy, $sell);
  1052. Updates the exchange rates $buy and $sell for the given $currency on $transdate.
  1053. If there is not yet an exchange rate for $currency on $transdate, an entry is
  1054. inserted. This returns without doing anything if $curr eq ''.
  1055. $dbh is not used, favouring $self->{dbh}.
  1056. =cut
  1057. sub update_exchangerate {
  1058. my ( $self, $dbh, $curr, $transdate, $buy, $sell ) = @_;
  1059. # some sanity check for currency
  1060. return if ( $curr eq "" );
  1061. my $query = qq|
  1062. SELECT curr
  1063. FROM exchangerate
  1064. WHERE curr = ?
  1065. AND transdate = ?
  1066. FOR UPDATE|;
  1067. my $sth = $self->{dbh}->prepare($query);
  1068. $sth->execute( $curr, $transdate ) || $self->dberror($query);
  1069. my $set;
  1070. my @queryargs;
  1071. if ( $buy && $sell ) {
  1072. $set = "buy = ?, sell = ?";
  1073. @queryargs = ( $buy, $sell );
  1074. }
  1075. elsif ($buy) {
  1076. $set = "buy = ?";
  1077. @queryargs = ($buy);
  1078. }
  1079. elsif ($sell) {
  1080. $set = "sell = ?";
  1081. @queryargs = ($sell);
  1082. }
  1083. if ( !$set ) {
  1084. $self->error("Exchange rate missing!");
  1085. }
  1086. if ( $sth->fetchrow_array ) {
  1087. $query = qq|UPDATE exchangerate
  1088. SET $set
  1089. WHERE curr = ?
  1090. AND transdate = ?|;
  1091. push( @queryargs, $curr, $transdate );
  1092. }
  1093. else {
  1094. $query = qq|
  1095. INSERT INTO exchangerate (
  1096. curr, buy, sell, transdate)
  1097. VALUES (?, ?, ?, ?)|;
  1098. @queryargs = ( $curr, $buy, $sell, $transdate );
  1099. }
  1100. $sth->finish;
  1101. $sth = $self->{dbh}->prepare($query);
  1102. $sth->execute(@queryargs) || $self->dberror($query);
  1103. }
  1104. =item $form->save_exchangerate($myconfig, $currency, $transdate, $rate, $fld);
  1105. Saves the exchange rate $rate for the given $currency on $transdate for the
  1106. provided purpose in $fld. $fld can be either 'buy' or 'sell'.
  1107. $myconfig is not used. $self->update_exchangerate is used for the majority of
  1108. the work.
  1109. =cut
  1110. sub save_exchangerate {
  1111. my ( $self, $myconfig, $currency, $transdate, $rate, $fld ) = @_;
  1112. my ( $buy, $sell ) = ( 0, 0 );
  1113. $buy = $rate if $fld eq 'buy';
  1114. $sell = $rate if $fld eq 'sell';
  1115. $self->update_exchangerate( $self->{dbh}, $currency, $transdate, $buy,
  1116. $sell );
  1117. }
  1118. =item $form->get_exchangerate($dbh, $curr, $transdate, $fld);
  1119. Returns the exchange rate in relation to the default currency for $currency on
  1120. $transdate for the purpose indicated by $fld. $fld can be either 'buy' or
  1121. 'sell' to get usable results.
  1122. $dbh is not used, favouring $self->{dbh}.
  1123. =cut
  1124. sub get_exchangerate {
  1125. my ( $self, $dbh, $curr, $transdate, $fld ) = @_;
  1126. my $exchangerate = 1;
  1127. if ($transdate) {
  1128. my $query = qq|
  1129. SELECT $fld FROM exchangerate
  1130. WHERE curr = ? AND transdate = ?|;
  1131. my $sth = $self->{dbh}->prepare($query);
  1132. $sth->execute( $curr, $transdate );
  1133. ($exchangerate) = $sth->fetchrow_array;
  1134. $exchangerate = Math::BigFloat->new($exchangerate);
  1135. $sth->finish;
  1136. }
  1137. $exchangerate;
  1138. }
  1139. =item $form->check_exchangerate($myconfig, $currency, $transdate, $fld);
  1140. Returns some true value when an entry for $currency on $transdate is true for
  1141. the purpose indicated by $fld. $fld can be either 'buy' or 'sell' to get
  1142. usable results. Returns false if $transdate is not set.
  1143. $myconfig is not used.
  1144. =cut
  1145. sub check_exchangerate {
  1146. my ( $self, $myconfig, $currency, $transdate, $fld ) = @_;
  1147. return "" unless $transdate;
  1148. my $query = qq|
  1149. SELECT $fld
  1150. FROM exchangerate
  1151. WHERE curr = ? AND transdate = ?|;
  1152. my $sth = $self->{dbh}->prepare($query);
  1153. $sth->execute( $currency, $transdate );
  1154. my @array = $sth->fetchrow_array;
  1155. $self->db_parse_numeric(sth => $sth, arrayref => \@array);
  1156. my ($exchangerate) = @array;
  1157. $sth->finish;
  1158. $exchangerate;
  1159. }
  1160. =item $form->add_shipto($dbh, $id);
  1161. Inserts a new address into the table shipto if the value of any of the shipto
  1162. address components in $form differs to the regular attribute in $form. The
  1163. inserted value of trans_id is $id, the other fields correspond with the shipto
  1164. address components of $form.
  1165. $dbh is unused.
  1166. =cut
  1167. sub add_shipto {
  1168. my ( $self, $dbh, $id ) = @_;
  1169. my $shipto;
  1170. foreach my $item (
  1171. qw(name address1 address2 city state
  1172. zipcode country contact phone fax email)
  1173. )
  1174. {
  1175. if ( $self->{"shipto$item"} ne "" ) {
  1176. $shipto = 1 if ( $self->{$item} ne $self->{"shipto$item"} );
  1177. }
  1178. }
  1179. if ($shipto) {
  1180. my $query = qq|
  1181. INSERT INTO shipto
  1182. (trans_id, shiptoname, shiptoaddress1,
  1183. shiptoaddress2, shiptocity, shiptostate,
  1184. shiptozipcode, shiptocountry, shiptocontact,
  1185. shiptophone, shiptofax, shiptoemail)
  1186. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1187. |;
  1188. my $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  1189. $sth->execute(
  1190. $id, $self->{shiptoname},
  1191. $self->{shiptoaddress1}, $self->{shiptoaddress2},
  1192. $self->{shiptocity}, $self->{shiptostate},
  1193. $self->{shiptozipcode}, $self->{shiptocountry},
  1194. $self->{shiptocontact}, $self->{shiptophone},
  1195. $self->{shiptofax}, $self->{shiptoemail}
  1196. ) || $self->dberror($query);
  1197. $sth->finish;
  1198. }
  1199. }
  1200. =item $form->get_employee($dbh);
  1201. Returns a list containing the name and id of the employee $form->{login}. Any
  1202. portion of $form->{login} including and past '@' are ignored.
  1203. $dbh is unused.
  1204. =cut
  1205. sub get_employee {
  1206. my ( $self, $dbh ) = @_;
  1207. my $login = $self->{login};
  1208. $login =~ s/@.*//;
  1209. my $query = qq|
  1210. SELECT name, id
  1211. FROM entity WHERE id IN (select entity_id
  1212. FROM users
  1213. WHERE username = ?)|;
  1214. my $sth = $self->{dbh}->prepare($query);
  1215. $sth->execute($login);
  1216. my (@a) = $sth->fetchrow_array();
  1217. $a[1] *= 1;
  1218. $sth->finish;
  1219. @a;
  1220. }
  1221. =item $form->get_name($myconfig, $table[, $transdate])
  1222. Sets $form->{name_list} to refer to a list of customers or vendors whose names
  1223. or numbers match the value found in $form->{$table} and returns the number of
  1224. matches. $table can be 'vendor', 'customer', or 'employee'; if the optional
  1225. field $transdate is provided, the result set is further limited to $table
  1226. entries which were active on the provided date as determined by the start and
  1227. end dates. The elements of $form->{name_list} are references returned rows in
  1228. hashref form and are sorted by the name field. The fields of the hash are those
  1229. of the view $table and the table entity.
  1230. $myconfig is unused.
  1231. =cut
  1232. # this sub gets the id and name from $table
  1233. sub get_name {
  1234. my ( $self, $myconfig, $table, $transdate ) = @_;
  1235. my @queryargs;
  1236. my $where;
  1237. if ($transdate) {
  1238. $where = qq|
  1239. AND (c.startdate IS NULL OR c.startdate <= ?)
  1240. AND (c.enddate IS NULL OR c.enddate >= ?)|;
  1241. @queryargs = ( $transdate, $transdate );
  1242. }
  1243. # SC: Check for valid table/view name. Other values will cause SQL errors.
  1244. if ($table !~ /^(vendor|customer|employee)$/i) {
  1245. $self->error('Invalid name source');
  1246. }
  1247. # Company name is stored in $self->{vendor} or $self->{customer}
  1248. if ($self->{"${table}number"} eq ''){
  1249. $self->{"${table}number"} = $self->{$table};
  1250. }
  1251. my $name = $self->like( lc $self->{$table} );
  1252. # Vendor and Customer are now views into entity_credit_account.
  1253. my $query = qq/
  1254. SELECT c.*, e.name FROM entity_credit_account c
  1255. JOIN entity e ON (c.entity_id = e.id)
  1256. WHERE (lower(e.name) LIKE ?
  1257. OR c.meta_number LIKE ?)
  1258. $where
  1259. ORDER BY e.name/;
  1260. unshift( @queryargs, $name, $self->{"${table}number"} );
  1261. my $sth = $self->{dbh}->prepare($query);
  1262. $sth->execute(@queryargs) || $self->dberror($query);
  1263. my $i = 0;
  1264. @{ $self->{name_list} } = ();
  1265. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1266. push( @{ $self->{name_list} }, $ref );
  1267. $i++;
  1268. }
  1269. $sth->finish;
  1270. return $i;
  1271. }
  1272. =item $form->all_vc($myconfig, $vc, $module, $dbh, $transdate, $job);
  1273. Populates the list referred to by $form->{all_${vc}} with hashes of either
  1274. vendor or customer id and name, ordered by the name. This will be vendor
  1275. details unless $vc is set to 'customer'. This list can be limited to only
  1276. vendors or customers which are usable on a given day by specifying $transdate.
  1277. As a further restriction, $form->{all_${vc}} will not be populated if the
  1278. number of vendors or customers that would be present in that list exceeds, or
  1279. is equal to, $myconfig->{vclimit}.
  1280. In addition to the possible population of $form->{all_${vc}},
  1281. $form->{employee_id} is looked up if not already set, the list
  1282. $form->{all_language} is populated using the language table and is sorted by the
  1283. description, and $form->all_employees, $form->all_departments,
  1284. $form->all_projects, and $form->all_taxaccounts are all run.
  1285. $module and $dbh are unused.
  1286. =cut
  1287. sub all_vc {
  1288. my ( $self, $myconfig, $vc, $module, $dbh, $transdate, $job ) = @_;
  1289. my $ref;
  1290. my $table;
  1291. if ($module eq 'AR'){
  1292. $table = 'ar';
  1293. } elsif ($module eq 'AP'){
  1294. $table = 'ap';
  1295. }
  1296. $dbh = $self->{dbh};
  1297. my $sth;
  1298. if ($vc eq 'customer'){
  1299. $self->{vc_class} = 1;
  1300. } else {
  1301. $self->{vc_class} = 2;
  1302. $vc = 'vendor';
  1303. }
  1304. my $query = qq|SELECT count(*) FROM entity_credit_account ec
  1305. where ec.entity_class = ?|;
  1306. my $where;
  1307. my @queryargs2 = ($self->{vc_class});
  1308. my @queryargs;
  1309. if ($transdate) {
  1310. $query .= qq| AND (ec.startdate IS NULL OR ec.startdate <= ?)
  1311. AND (ec.enddate IS NULL OR ec.enddate >= ?)|;
  1312. $where = qq| (ec.startdate IS NULL OR ec.startdate <= ?)
  1313. AND (ec.enddate IS NULL OR ec.enddate >= ?)
  1314. AND ec.entity_class = ?|;
  1315. push (@queryargs, $transdate, $transdate, $self->{vc_class});
  1316. push (@queryargs2, $transdate, $transdate);
  1317. } else {
  1318. $where = " true";
  1319. }
  1320. $sth = $dbh->prepare($query);
  1321. $sth->execute(@queryargs2);
  1322. my ($count) = $sth->fetchrow_array;
  1323. $sth->finish;
  1324. # build selection list
  1325. if ( $count < $myconfig->{vclimit} ) {
  1326. $self->{"${vc}_id"} *= 1;
  1327. # TODO: Alter this so that it pulls up the entity_credit_account
  1328. # instead of the entity_id. --CT
  1329. $query = qq|
  1330. SELECT ec.id, e.name
  1331. FROM entity e
  1332. JOIN entity_credit_account ec ON (ec.entity_id = e.id)
  1333. WHERE ec.id = ? OR $where
  1334. ORDER BY name|;
  1335. push( @queryargs, $self->{"${vc}_id"} );
  1336. $sth = $dbh->prepare($query);
  1337. $sth->execute(@queryargs) || $self->dberror($query);
  1338. @{ $self->{"all_$vc"} } = ();
  1339. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1340. push @{ $self->{"all_$vc"} }, $ref;
  1341. }
  1342. $sth->finish;
  1343. } elsif ($self->{id}) {
  1344. $query = qq|
  1345. SELECT ec.id, e.name
  1346. FROM entity e
  1347. JOIN entity_credit_account ec ON (ec.entity_id = e.id)
  1348. WHERE ec.id = (select entity_credit_account FROM $table
  1349. WHERE id = ?)
  1350. ORDER BY name|;
  1351. $sth = $self->{dbh}->prepare($query);
  1352. $sth->execute($self->{id});
  1353. ($self->{"${vc}_id"}, $self->{$vc}) = $sth->fetchrow_array();
  1354. }
  1355. # get self
  1356. if ( !$self->{employee_id} ) {
  1357. ( $self->{employee}, $self->{employee_id} ) = split /--/,
  1358. $self->{employee};
  1359. ( $self->{employee}, $self->{employee_id} ) = $self->get_employee($dbh)
  1360. unless $self->{employee_id};
  1361. }
  1362. $self->all_employees( $myconfig, $dbh, $transdate, 1 );
  1363. $self->all_departments( $myconfig, $dbh, $vc );
  1364. $self->all_projects( $myconfig, $dbh, $transdate, $job );
  1365. # get language codes
  1366. $query = qq|SELECT *
  1367. FROM language
  1368. ORDER BY 2|;
  1369. $sth = $dbh->prepare($query);
  1370. $sth->execute || $self->dberror($query);
  1371. $self->{all_language} = ();
  1372. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1373. push @{ $self->{all_language} }, $ref;
  1374. }
  1375. $sth->finish;
  1376. $self->all_taxaccounts( $myconfig, $dbh, $transdate );
  1377. }
  1378. =item $form->all_accounts()
  1379. Sets $form->{accounts} to all accounts. Returns the list as well.
  1380. Example: my @account_list = $form->all_accounts();
  1381. =cut
  1382. sub all_accounts {
  1383. my ($self) = @_;
  1384. my $ref;
  1385. $self->{all_accounts} = [];
  1386. my $sth = $self->{dbh}->prepare('SELECT * FROM chart_list_all()');
  1387. $sth->execute || $self->dberror('SELECT * FROM chart_list_all()');
  1388. while ($ref = $sth->fetchrow_hashref('NAME_lc')){
  1389. push(@{$self->{all_accounts}}, $ref);
  1390. }
  1391. $sth->finish;
  1392. return @{$self->{all_accounts}};
  1393. }
  1394. =item $form->all_taxaccounts($myconfig, $dbh2[, $transdate]);
  1395. Get the tax rates and numbers for all the taxes in $form->{taxaccounts}. Does
  1396. nothing if $form->{taxaccounts} is false. Taxes are listed as a space seperated
  1397. list of account numbers from the chart. The retrieved values are placed within
  1398. $form->{${accno}_rate} and $form->{${accno}_taxnumber}. If $transdate is set,
  1399. then only process taxes that were valid on $transdate.
  1400. $myconfig and $dbh2 are unused.
  1401. =cut
  1402. sub all_taxaccounts {
  1403. my ( $self, $myconfig, $dbh2, $transdate ) = @_;
  1404. my $dbh = $self->{dbh};
  1405. my $sth;
  1406. my $query;
  1407. my $where;
  1408. my @queryargs = ();
  1409. if ($transdate) {
  1410. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1411. push( @queryargs, $transdate );
  1412. }
  1413. if ( $self->{taxaccounts} ) {
  1414. # rebuild tax rates
  1415. $query = qq|SELECT t.rate, t.taxnumber
  1416. FROM tax t
  1417. JOIN chart c ON (c.id = t.chart_id)
  1418. WHERE c.accno = ?
  1419. $where
  1420. ORDER BY accno, validto|;
  1421. $sth = $dbh->prepare($query) || $self->dberror($query);
  1422. foreach my $accno ( split / /, $self->{taxaccounts} ) {
  1423. $sth->execute( $accno, @queryargs );
  1424. ( $self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"} ) =
  1425. $sth->fetchrow_array;
  1426. $sth->finish;
  1427. }
  1428. }
  1429. }
  1430. =item $form->all_employees($myconfig, $dbh2, $transdate, $sales);
  1431. Sets $form->{all_employee} to be a reference to an array referencing hashes of
  1432. employee information. The hashes are of the form {'id' => id, 'name' => name}.
  1433. If $transdate is set, the query is limited to employees who are active on that
  1434. day. If $sales is true, only employees with the sales flag set are added.
  1435. $dbh2 is unused.
  1436. =cut
  1437. sub all_employees {
  1438. my ( $self, $myconfig, $dbh2, $transdate, $sales ) = @_;
  1439. my $dbh = $self->{dbh};
  1440. my @whereargs = ();
  1441. # setup employees/sales contacts
  1442. my $query = qq|
  1443. SELECT id, name
  1444. FROM entity
  1445. WHERE id IN (SELECT entity_id FROM employee
  1446. WHERE|;
  1447. if ($transdate) {
  1448. $query .= qq| (startdate IS NULL OR startdate <= ?)
  1449. AND (enddate IS NULL OR enddate >= ?) AND|;
  1450. @whereargs = ( $transdate, $transdate );
  1451. }
  1452. else {
  1453. $query .= qq| enddate IS NULL AND|;
  1454. }
  1455. if ($sales) {
  1456. $query .= qq| sales = '1' AND|;
  1457. }
  1458. $query =~ s/(WHERE|AND)$//;
  1459. $query .= qq|) ORDER BY name|;
  1460. my $sth = $dbh->prepare($query);
  1461. $sth->execute(@whereargs) || $self->dberror($query);
  1462. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1463. push @{ $self->{all_employee} }, $ref;
  1464. }
  1465. $sth->finish;
  1466. }
  1467. =item $form->all_projects($myconfig, $dbh2[, $transdate, $job]);
  1468. Populates the list referred to as $form->{all_project} with hashes detailing
  1469. all projects. If $job is true, limit the projects to those whose ids are not
  1470. also present in parts with a project_id > 0. If $transdate is set, the projects
  1471. are limited to those valid on $transdate. If $form->{language_code} is set,
  1472. include the translation description in the project list and limit to
  1473. translations with a matching language_code. The result list,
  1474. $form->{all_project}, is sorted by projectnumber.
  1475. $myconfig and $dbh2 are unused. $job appears to be part of attempted job-
  1476. costing support.
  1477. =cut
  1478. sub all_projects {
  1479. my ( $self, $myconfig, $dbh2, $transdate, $job ) = @_;
  1480. my $dbh = $self->{dbh};
  1481. my @queryargs = ();
  1482. my $where = "1 = 1";
  1483. $where = qq|id NOT IN (SELECT id
  1484. FROM parts
  1485. WHERE project_id > 0)| if !$job;
  1486. my $query = qq|SELECT *
  1487. FROM project
  1488. WHERE $where|;
  1489. if ( $self->{language_code} ) {
  1490. $query = qq|
  1491. SELECT pr.*, t.description AS translation
  1492. FROM project pr
  1493. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1494. WHERE t.language_code = ?|;
  1495. push( @queryargs, $self->{language_code} );
  1496. }
  1497. if ($transdate) {
  1498. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1499. AND (enddate IS NULL OR enddate >= ?)|;
  1500. push( @queryargs, $transdate, $transdate );
  1501. }
  1502. $query .= qq| ORDER BY projectnumber|;
  1503. my $sth = $dbh->prepare($query);
  1504. $sth->execute(@queryargs) || $self->dberror($query);
  1505. @{ $self->{all_project} } = ();
  1506. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1507. push @{ $self->{all_project} }, $ref;
  1508. }
  1509. $sth->finish;
  1510. }
  1511. =item $form->all_departments($myconfig, $dbh2, $vc);
  1512. Set $form->{all_department} to be a reference to a list of hashrefs describing
  1513. departments of the form {'id' => id, 'description' => description}. If $vc
  1514. is 'customer', further limit the results to those whose role is 'P' (Profit
  1515. Center).
  1516. This procedure is internally followed by a call to $form->all_years($myconfig).
  1517. $dbh2 is not used.
  1518. =cut
  1519. sub all_departments {
  1520. my ( $self, $myconfig, $dbh2, $vc ) = @_;
  1521. my $dbh = $self->{dbh};
  1522. my $where = "1 = 1";
  1523. if ($vc) {
  1524. if ( $vc eq 'customer' ) {
  1525. $where = " role = 'P'";
  1526. }
  1527. }
  1528. my $query = qq|SELECT id, description
  1529. FROM department
  1530. WHERE $where
  1531. ORDER BY 2|;
  1532. my $sth = $dbh->prepare($query);
  1533. $sth->execute || $self->dberror($query);
  1534. @{ $self->{all_department} } = ();
  1535. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1536. push @{ $self->{all_department} }, $ref;
  1537. }
  1538. $sth->finish;
  1539. $self->all_years($myconfig);
  1540. }
  1541. =item $form->all_languages($myconfig);
  1542. Set $form->{all_language} to be a reference to a list of hashrefs describing
  1543. languages using the form {'code' => code, 'description' => description}.
  1544. =cut
  1545. sub all_languages {
  1546. my ( $self ) = @_;
  1547. my $dbh = $self->{dbh};
  1548. my $query = qq|
  1549. SELECT code, description
  1550. FROM language
  1551. ORDER BY description|;
  1552. my $sth = $dbh->prepare($query);
  1553. $sth->execute || $self->dberror($query);
  1554. $self->{all_language} = [];
  1555. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1556. push @{ $self->{all_language} }, $ref;
  1557. }
  1558. $sth->finish;
  1559. }
  1560. =item $form->all_years($myconfig[, $dbh2]);
  1561. Populates the hash $form->{all_month} with a mapping between a two-digit month
  1562. number and the English month name. Populates the list $form->{all_years} with
  1563. all years which contain transactions.
  1564. $dbh2 is unused.
  1565. =cut
  1566. sub all_years {
  1567. my ( $self, $myconfig ) = @_;
  1568. my $dbh = $self->{dbh};
  1569. $self->{all_years} = [];
  1570. # get years
  1571. my $query = qq|
  1572. SELECT extract('YEARS' FROM transdate) FROM acc_trans
  1573. GROUP BY extract('YEARS' FROM transdate) ORDER BY 1 DESC|;
  1574. my $sth = $dbh->prepare($query);
  1575. $sth->execute();
  1576. while (my ($year) = $sth->fetchrow_array()){
  1577. push @{$self->{all_years}}, $year;
  1578. }
  1579. #this should probably be changed to use locale
  1580. %{ $self->{all_month} } = (
  1581. '01' => 'January',
  1582. '02' => 'February',
  1583. '03' => 'March',
  1584. '04' => 'April',
  1585. '05' => 'May ',
  1586. '06' => 'June',
  1587. '07' => 'July',
  1588. '08' => 'August',
  1589. '09' => 'September',
  1590. '10' => 'October',
  1591. '11' => 'November',
  1592. '12' => 'December'
  1593. );
  1594. }
  1595. =item $form->create_links($module, $myconfig, $vc[, $job]);
  1596. Populates the hash referred to as $form->{${module}_links} details about
  1597. accounts that have $module in their link field. The hash is keyed upon link
  1598. elements such as 'AP_amount' and 'AR_tax' and they refer to lists of hashes
  1599. containing accno and description for the appropriate accounts. If the key does
  1600. not contain 'tax', the account number is appended to the space seperated list
  1601. $form->{accounts}. $module is typically 'AR' or 'AP' and is the base type of
  1602. the accounts looked up.
  1603. If $form->{id} is not set, check $form->{"$form->{vc}_id"}. If neither is set,
  1604. use $form->lastname_used to populate the details. If $form->{id} is set,
  1605. populate the invnumber, transdate, ${vc}_id, datepaid, duedate, ordnumber,
  1606. taxincluded, currency, notes, intnotes, ${vc}, department_id, department,
  1607. oldinvtotal, oldtotalpaid, employee_id, employee, language_code, ponumber,
  1608. reverse, printed, emailed, queued, recurring, exchangerate, and acc_trans
  1609. attributes of $form with details about the transaction $form->{id}. All of
  1610. these attributes, save for acc_trans, are scalar; $form->{acc_trans} refers to
  1611. a hash keyed by link elements whose values are lists of references to hashes
  1612. describing acc_trans table entries corresponding to the transaction $form->{id}.
  1613. The elements in the acc_trans entry hashes are accno, description, source,
  1614. amount, memo, transdate, cleared, project_id, projectnumber, and exchangerate.
  1615. The closedto, separate_duties, revtrans, and currencies $form attributes are filled with values
  1616. from the defaults table, while $form->{current_date} is populated with the
  1617. current date. If $form->{id} is not set, then $form->{transdate} also takes on
  1618. the current date.
  1619. After all this, it calls $form->all_vc to conclude.
  1620. =cut
  1621. sub create_links {
  1622. my ( $self, $module, $myconfig, $vc, $job ) = @_;
  1623. # get last customers or vendors
  1624. my ( $query, $sth );
  1625. if (!$self->{dbh}) {
  1626. $self->db_init($myconfig);
  1627. }
  1628. my $dbh = $self->{dbh};
  1629. my %xkeyref = ();
  1630. my $val;
  1631. my $ref;
  1632. my $key;
  1633. # now get the account numbers
  1634. $query = qq|SELECT accno, description, link
  1635. FROM chart
  1636. WHERE link LIKE ?
  1637. ORDER BY accno|;
  1638. $sth = $dbh->prepare($query);
  1639. $sth->execute( "%" . "$module%" ) || $self->dberror($query);
  1640. $self->{accounts} = "";
  1641. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1642. foreach my $key ( split /:/, $ref->{link} ) {
  1643. if ( $key =~ /$module/ ) {
  1644. # cross reference for keys
  1645. $xkeyref{ $ref->{accno} } = $key;
  1646. push @{ $self->{"${module}_links"}{$key} },
  1647. {
  1648. accno => $ref->{accno},
  1649. description => $ref->{description}
  1650. };
  1651. $self->{accounts} .= "$ref->{accno} "
  1652. unless $key =~ /tax/;
  1653. }
  1654. }
  1655. }
  1656. $sth->finish;
  1657. my $arap = ( $vc eq 'customer' ) ? 'ar' : 'ap';
  1658. $vc = 'vendor' unless $vc eq 'customer';
  1659. if ( $self->{id} ) {
  1660. $query = qq|
  1661. SELECT a.invnumber, a.transdate,
  1662. a.entity_credit_account AS entity_id,
  1663. a.datepaid, a.duedate, a.ordnumber,
  1664. a.taxincluded, a.curr AS currency, a.notes,
  1665. a.intnotes, ce.name AS $vc, a.department_id,
  1666. d.description AS department,
  1667. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1668. a.person_id, e.name AS employee,
  1669. c.language_code, a.ponumber, a.reverse
  1670. FROM $arap a
  1671. JOIN entity_credit_account c USING (entity_id)
  1672. JOIN entity ce ON (ce.id = c.entity_id)
  1673. LEFT JOIN employee er ON (er.entity_id = a.person_id)
  1674. LEFT JOIN entity e ON (er.entity_id = e.id)
  1675. LEFT JOIN department d ON (d.id = a.department_id)
  1676. WHERE a.id = ? AND c.entity_class =
  1677. (select id FROM entity_class
  1678. WHERE class ilike ?)|;
  1679. $sth = $dbh->prepare($query);
  1680. $sth->execute( $self->{id}, $self->{vc} ) || $self->dberror($query);
  1681. $ref = $sth->fetchrow_hashref('NAME_lc');
  1682. $self->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1683. foreach $key ( keys %$ref ) {
  1684. $self->{$key} = $ref->{$key};
  1685. }
  1686. $sth->finish;
  1687. # get printed, emailed
  1688. $query = qq|
  1689. SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1690. FROM status s WHERE s.trans_id = ?|;
  1691. $sth = $dbh->prepare($query);
  1692. $sth->execute( $self->{id} ) || $self->dberror($query);
  1693. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1694. $self->{printed} .= "$ref->{formname} "
  1695. if $ref->{printed};
  1696. $self->{emailed} .= "$ref->{formname} "
  1697. if $ref->{emailed};
  1698. $self->{queued} .= "$ref->{formname} " . "$ref->{spoolfile} "
  1699. if $ref->{spoolfile};
  1700. }
  1701. $sth->finish;
  1702. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1703. # get recurring
  1704. $self->get_recurring($dbh);
  1705. # get amounts from individual entries
  1706. $query = qq|
  1707. SELECT c.accno, c.description, a.source, a.amount,
  1708. a.memo, a.transdate, a.cleared, a.project_id,
  1709. p.projectnumber
  1710. FROM acc_trans a
  1711. JOIN chart c ON (c.id = a.chart_id)
  1712. LEFT JOIN project p ON (p.id = a.project_id)
  1713. WHERE a.trans_id = ?
  1714. AND a.fx_transaction = '0'
  1715. ORDER BY transdate|;
  1716. $sth = $dbh->prepare($query);
  1717. $sth->execute( $self->{id} ) || $self->dberror($query);
  1718. my $fld = ( $vc eq 'customer' ) ? 'buy' : 'sell';
  1719. $self->{exchangerate} =
  1720. $self->get_exchangerate( $dbh, $self->{currency}, $self->{transdate},
  1721. $fld );
  1722. # store amounts in {acc_trans}{$key} for multiple accounts
  1723. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1724. $ref->{exchangerate} =
  1725. $self->get_exchangerate( $dbh, $self->{currency},
  1726. $ref->{transdate}, $fld );
  1727. if ($self->{reverse}){
  1728. $ref->{amount} *= -1;
  1729. }
  1730. push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
  1731. }
  1732. $sth->finish;
  1733. }
  1734. else {
  1735. if ( !$self->{"$self->{vc}_id"} ) {
  1736. $self->lastname_used( $myconfig, $dbh, $vc, $module );
  1737. }
  1738. }
  1739. for (qw(separate_duties current_date curr closedto revtrans)) {
  1740. if ($_ eq 'closedto'){
  1741. $query = qq|
  1742. SELECT value::date FROM defaults
  1743. WHERE setting_key = '$_'|;
  1744. } elsif ($_ eq 'current_date') {
  1745. $query = qq| select $_|;
  1746. } else {
  1747. $query = qq|
  1748. SELECT value FROM defaults
  1749. WHERE setting_key = '$_'|;
  1750. }
  1751. $sth = $dbh->prepare($query);
  1752. $sth->execute || $self->dberror($query);
  1753. ($val) = $sth->fetchrow_array();
  1754. if ( $_ eq 'curr' ) {
  1755. $self->{currencies} = $val;
  1756. }
  1757. else {
  1758. $self->{$_} = $val;
  1759. }
  1760. $sth->finish;
  1761. }
  1762. if (!$self->{id} && !$self->{transdate}){
  1763. $self->{transdate} = $self->{current_date};
  1764. }
  1765. $self->all_vc( $myconfig, $vc, $module, $dbh, $self->{transdate}, $job );
  1766. }
  1767. =item $form->lastname_used($myconfig, $dbh2, $vc, $module);
  1768. Fills the name, currency, ${vc}_id, duedate, and possibly invoice_notes
  1769. attributes of $form with the last used values for the transaction type specified
  1770. by both $vc and $form->{type}. $vc can be either 'vendor' or 'customer' and if
  1771. unspecified will take on the value given in $form->{vc}, defaulting to 'vendor'.
  1772. If $form->{type} matches /_order/, the transaction type used is order, if it
  1773. matches /_quotation/, quotations are looked through. If $form->{type} does not
  1774. match either of the above, then ar or ap transactions are used.
  1775. $myconfig, $dbh2, and $module are unused.
  1776. =cut
  1777. sub lastname_used {
  1778. my ( $self, $myconfig, $dbh2, $vc, $module ) = @_;
  1779. my $dbh = $self->{dbh};
  1780. $vc ||= $self->{vc}; # add default to correct for improper passing
  1781. my $arap;
  1782. my $where;
  1783. if ($vc eq 'customer') {
  1784. $arap = 'ar';
  1785. } else {
  1786. $arap = 'ap';
  1787. $vc = 'vendor';
  1788. }
  1789. my $sth;
  1790. if ( $self->{type} =~ /_order/ ) {
  1791. $arap = 'oe';
  1792. $where = "quotation = '0'";
  1793. }
  1794. if ( $self->{type} =~ /_quotation/ ) {
  1795. $arap = 'oe';
  1796. $where = "quotation = '1'";
  1797. }
  1798. $where = "AND $where " if $where;
  1799. my $inv_notes;
  1800. $inv_notes = "ct.invoice_notes," if $vc eq 'customer';
  1801. my $query = qq|
  1802. SELECT entity.name, ct.curr AS currency, entity_id AS ${vc}_id,
  1803. current_date + ct.terms AS duedate,
  1804. $inv_notes
  1805. ct.curr AS currency
  1806. FROM $vc ct
  1807. JOIN entity ON (ct.entity_id = entity.id)
  1808. WHERE entity.id = (select entity_id from $arap
  1809. where entity_id IS NOT NULL $where
  1810. order by id DESC limit 1)|;
  1811. $sth = $self->{dbh}->prepare($query);
  1812. $sth->execute() || $self->dberror($query);
  1813. my $ref = $sth->fetchrow_hashref('NAME_lc');
  1814. for ( keys %$ref ) { $self->{$_} = $ref->{$_} }
  1815. $sth->finish;
  1816. }
  1817. =item $form->current_date($myconfig[, $thisdate, $days]);
  1818. If $thisdate is false, get the current date from the database.
  1819. If $thisdate is true, get the date $days days from $thisdate in the date
  1820. format specified by $myconfig->{dateformat} from the database.
  1821. =cut
  1822. sub current_date {
  1823. my ( $self, $myconfig, $thisdate, $days ) = @_;
  1824. my $dbh = $self->{dbh};
  1825. my $query;
  1826. my @queryargs;
  1827. $days *= 1;
  1828. if ($thisdate) {
  1829. my $dateformat = $myconfig->{dateformat};
  1830. if ( $myconfig->{dateformat} !~ /^y/ ) {
  1831. my @a = split /\D/, $thisdate;
  1832. $dateformat .= "yy" if ( length $a[2] > 2 );
  1833. }
  1834. if ( $thisdate !~ /\D/ ) {
  1835. $dateformat = 'yyyymmdd';
  1836. }
  1837. $query = qq|SELECT (to_date(?, ?)
  1838. + ?::interval)::date AS thisdate|;
  1839. @queryargs = ( $thisdate, $dateformat, sprintf('%d days', $days) );
  1840. }
  1841. else {
  1842. $query = qq|SELECT current_date AS thisdate|;
  1843. @queryargs = ();
  1844. }
  1845. my $sth = $dbh->prepare($query);
  1846. $sth->execute(@queryargs);
  1847. my ($thisdate) = $sth->fetchrow_array;
  1848. $thisdate;
  1849. }
  1850. =item $form->like($str);
  1851. Returns '%$str%'
  1852. =cut
  1853. sub like {
  1854. my ( $self, $str ) = @_;
  1855. "%$str%";
  1856. }
  1857. =item $form->redo_rows($flds, $new, $count, $numrows);
  1858. $flds refers to a list of field names and $new refers to a list of row detail
  1859. hashes with the elements of $flds as keys as well as runningnumber for an order
  1860. or another multi-row item that normally expresses elements in the form
  1861. $form->{${fieldname}_${index}}.
  1862. For every $field in @{$flds} populates $form->{${field}_$i} with an appropriate
  1863. value from a $new detail hash where $i is an index between 1 and $count. The
  1864. ordering of the details is done in terms of the runningnumber element of the
  1865. row detail hashes in $new.
  1866. All $form attributes with names of the form ${field}_$i where the index $i is
  1867. between $count + 1 and $numrows is deleted.
  1868. =cut
  1869. sub redo_rows {
  1870. my ( $self, $flds, $new, $count, $numrows ) = @_;
  1871. my @ndx = ();
  1872. for ( 1 .. $count ) {
  1873. push @ndx, { num => $new->[ $_ - 1 ]->{runningnumber}, ndx => $_ };
  1874. }
  1875. my $i = 0;
  1876. # fill rows
  1877. foreach my $item ( sort { $a->{num} <=> $b->{num} } @ndx ) {
  1878. $i++;
  1879. my $j = $item->{ndx} - 1;
  1880. for ( @{$flds} ) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1881. }
  1882. # delete empty rows
  1883. for $i ( $count + 1 .. $numrows ) {
  1884. for ( @{$flds} ) { delete $self->{"${_}_$i"} }
  1885. }
  1886. }
  1887. =item $form->get_partsgroup($myconfig[, $p]);
  1888. Populates the list referred to as $form->{all_partsgroup}. $p refers to a hash
  1889. that describes which partsgroups to retrieve. $p->{searchitems} can be 'part',
  1890. 'service', 'assembly', 'labor', or 'nolabor' and will limit the groups to those
  1891. that contain the item type described. $p->{searchitems} and $p->{all} conflict.
  1892. If $p->{all} is set and $p->{language_code} is not, all partsgroups are
  1893. retrieved. If $p->{language_code} is set, also include the translation
  1894. description specified by $p->{language_code} for the partsgroup.
  1895. The results in $form->{all_partsgroup} are normally sorted by partsgroup name.
  1896. If a language_code is specified, the results are then sorted by the translated
  1897. description.
  1898. $myconfig is unused.
  1899. =cut
  1900. sub get_partsgroup {
  1901. my ( $self, $myconfig, $p ) = @_;
  1902. my $dbh = $self->{dbh};
  1903. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1904. FROM partsgroup pg
  1905. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1906. my $where;
  1907. my $sortorder = "partsgroup";
  1908. if ( $p->{searchitems} eq 'part' ) {
  1909. $where = qq| WHERE (p.inventory_accno_id > 0
  1910. AND p.income_accno_id > 0)|;
  1911. } elsif ( $p->{searchitems} eq 'service' ) {
  1912. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1913. } elsif ( $p->{searchitems} eq 'assembly' ) {
  1914. $where = qq| WHERE p.assembly = '1'|;
  1915. } elsif ( $p->{searchitems} eq 'labor' ) {
  1916. $where =
  1917. qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1918. } elsif ( $p->{searchitems} eq 'nolabor' ) {
  1919. $where = qq| WHERE p.income_accno_id > 0|;
  1920. }
  1921. if ( $p->{all} ) {
  1922. $query = qq|SELECT id, partsgroup
  1923. FROM partsgroup|;
  1924. }
  1925. my @queryargs = ();
  1926. if ( $p->{language_code} ) {
  1927. $sortorder = "translation";
  1928. $query = qq|
  1929. SELECT DISTINCT pg.id, pg.partsgroup,
  1930. t.description AS translation
  1931. FROM partsgroup pg
  1932. JOIN parts p ON (p.partsgroup_id = pg.id)
  1933. LEFT JOIN translation t ON (t.trans_id = pg.id
  1934. AND t.language_code = ?)|;
  1935. @queryargs = ( $p->{language_code} );
  1936. }
  1937. $query .= qq| $where ORDER BY $sortorder|;
  1938. my $sth = $dbh->prepare($query);
  1939. $sth->execute(@queryargs) || $self->dberror($query);
  1940. $self->{all_partsgroup} = ();
  1941. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1942. push @{ $self->{all_partsgroup} }, $ref;
  1943. }
  1944. $sth->finish;
  1945. }
  1946. =item $form->update_status($myconfig);
  1947. DELETEs all status rows which have a formname of $form->{formname} and a
  1948. trans_id of $form->{id}. INSERTs a new row into status where trans_id is
  1949. $form->{id}, formname is $form->{formname}, printed and emailed are true if
  1950. their respective $form attributes match /$form->{formname}/, and spoolfile is
  1951. the file extracted from the string $form->{queued} or NULL if there is no entry
  1952. for $form->{formname}.
  1953. $myconfig is unused.
  1954. =cut
  1955. sub update_status {
  1956. my ( $self, $myconfig ) = @_;
  1957. # no id return
  1958. return unless $self->{id};
  1959. my $dbh = $self->{dbh};
  1960. my %queued = split / +/, $self->{queued};
  1961. my $spoolfile =
  1962. ( $queued{ $self->{formname} } )
  1963. ? "'$queued{$self->{formname}}'"
  1964. : 'NULL';
  1965. my $query = qq|DELETE FROM status
  1966. WHERE formname = ?
  1967. AND trans_id = ?|;
  1968. my $sth = $dbh->prepare($query);
  1969. $sth->execute( $self->{formname}, $self->{id} ) || $self->dberror($query);
  1970. $sth->finish;
  1971. my $printed = ( $self->{printed} =~ /$self->{formname}/ ) ? "1" : "0";
  1972. my $emailed = ( $self->{emailed} =~ /$self->{formname}/ ) ? "1" : "0";
  1973. $query = qq|
  1974. INSERT INTO status
  1975. (trans_id, printed, emailed, spoolfile, formname)
  1976. VALUES (?, ?, ?, ?, ?)|;
  1977. $sth = $dbh->prepare($query);
  1978. $sth->execute( $self->{id}, $printed, $emailed, $spoolfile,
  1979. $self->{formname} );
  1980. $sth->finish;
  1981. }
  1982. =item $form->save_status();
  1983. Clears out any old status entries for $form->{id} and saves new status entries.
  1984. Queued form names are extracted from $form->{queued}. Printed and emailed form
  1985. names are extracted from $form->{printed} and $form->{emailed}. The queued,
  1986. printed, and emailed fields are space seperated lists.
  1987. =cut
  1988. sub save_status {
  1989. my ($self) = @_;
  1990. my $dbh = $self->{dbh};
  1991. my $formnames = $self->{printed};
  1992. my $emailforms = $self->{emailed};
  1993. my $query = qq|DELETE FROM status
  1994. WHERE trans_id = ?|;
  1995. my $sth = $dbh->prepare($query);
  1996. $sth->execute( $self->{id} );
  1997. $sth->finish;
  1998. my %queued;
  1999. my $formname;
  2000. my $printed;
  2001. my $emailed;
  2002. if ( $self->{queued} ) {
  2003. %queued = split / +/, $self->{queued};
  2004. foreach $formname ( keys %queued ) {
  2005. $printed = ( $self->{printed} =~ /$formname/ ) ? "1" : "0";
  2006. $emailed = ( $self->{emailed} =~ /$formname/ ) ? "1" : "0";
  2007. if ( $queued{$formname} ) {
  2008. $query = qq|
  2009. INSERT INTO status
  2010. (trans_id, printed, emailed,
  2011. spoolfile, formname)
  2012. VALUES (?, ?, ?, ?, ?)|;
  2013. $sth = $dbh->prepare($query);
  2014. $sth->execute( $self->{id}, $printed, $emailed,
  2015. $queued{$formname}, $formname )
  2016. || $self->dberror($query);
  2017. $sth->finish;
  2018. }
  2019. $formnames =~ s/$formname//;
  2020. $emailforms =~ s/$formname//;
  2021. }
  2022. }
  2023. # save printed, emailed info
  2024. $formnames =~ s/^ +//g;
  2025. $emailforms =~ s/^ +//g;
  2026. my %status = ();
  2027. for ( split / +/, $formnames ) { $status{$_}{printed} = 1 }
  2028. for ( split / +/, $emailforms ) { $status{$_}{emailed} = 1 }
  2029. foreach my $formname ( keys %status ) {
  2030. $printed = ( $formnames =~ /$self->{formname}/ ) ? "1" : "0";
  2031. $emailed = ( $emailforms =~ /$self->{formname}/ ) ? "1" : "0";
  2032. $query = qq|
  2033. INSERT INTO status (trans_id, printed, emailed,
  2034. formname)
  2035. VALUES (?, ?, ?, ?)|;
  2036. $sth = $dbh->prepare($query);
  2037. $sth->execute( $self->{id}, $printed, $emailed, $formname );
  2038. $sth->finish;
  2039. }
  2040. $dbh->commit;
  2041. }
  2042. =item $form->get_recurring();
  2043. Sets $form->{recurring} to contain info about the recurrence schedule for the
  2044. action $form->{id}. $form->{recurring} is of the same form used by
  2045. $form->save_recurring($dbh2, $myconfig).
  2046. reference,startdate,repeat,unit,howmany,payment,print,email,message
  2047. text date int text int int text text text
  2048. =cut
  2049. sub get_recurring {
  2050. my ($self) = @_;
  2051. my $dbh = $self->{dbh};
  2052. my $query = qq/
  2053. SELECT s.*, se.formname || ':' || se.format AS emaila,
  2054. se.message, sp.formname || ':' ||
  2055. sp.format || ':' || sp.printer AS printa
  2056. FROM recurring s
  2057. LEFT JOIN recurringemail se ON (s.id = se.id)
  2058. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  2059. WHERE s.id = ?/;
  2060. my $sth = $dbh->prepare($query);
  2061. $sth->execute( $self->{id} ) || $self->dberror($query);
  2062. for (qw(email print)) { $self->{"recurring$_"} = "" }
  2063. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  2064. for ( keys %$ref ) { $self->{"recurring$_"} = $ref->{$_} }
  2065. $self->{recurringemail} .= "$ref->{emaila}:";
  2066. $self->{recurringprint} .= "$ref->{printa}:";
  2067. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  2068. }
  2069. $sth->finish;
  2070. chop $self->{recurringemail};
  2071. chop $self->{recurringprint};
  2072. if ( $self->{recurringstartdate} ) {
  2073. $self->{recurringreference} =
  2074. $self->escape( $self->{recurringreference}, 1 );
  2075. $self->{recurringmessage} =
  2076. $self->escape( $self->{recurringmessage}, 1 );
  2077. for (
  2078. qw(reference startdate repeat unit howmany
  2079. payment print email message)
  2080. )
  2081. {
  2082. $self->{recurring} .= qq|$self->{"recurring$_"},|;
  2083. }
  2084. chop $self->{recurring};
  2085. }
  2086. }
  2087. =item $form->save_recurring($dbh2, $myconfig);
  2088. Saves or deletes recurring transaction scheduling. $form->{id} is used to
  2089. determine the id used in the various recurring tables. A recurring transaction
  2090. schedule is deleted by having $form->{recurring} be false. For adding or
  2091. updating a schedule, $form->{recurring} is a comma seperated field with partial
  2092. subfield quoting of the form:
  2093. reference,startdate,repeat,unit,howmany,payment,print,email,message
  2094. text date int text int int text text text
  2095. =over
  2096. =item reference
  2097. A URI-encoded reference string for the recurrence set.
  2098. =item startdate
  2099. The index date for the recurrence.
  2100. =item repeat
  2101. The unitless repetition frequency.
  2102. =item unit
  2103. The interval unit used. Can be 'days', 'weeks', 'months', or 'years',
  2104. capitalisation and pluralisation ignored.
  2105. =item howmany
  2106. The number of recurrences for the transaction.
  2107. =item payment
  2108. Flag to indicate if a payment is included in the transaction.
  2109. =item print
  2110. A colon seperated list of formname:format:printer triplets.
  2111. =item email
  2112. A colon seperated list of formname:format pairs.
  2113. =item message
  2114. A URI-encoded message for the emails to be sent.
  2115. =back
  2116. Values for the nextdate and enddate columns of the recurring table are
  2117. calculated using startdate, repeat, unit, howmany, and the current database
  2118. date. All other fields of the recurring, recurringemail, and recurringprint are
  2119. obtained directly from $form->{recurring}.
  2120. B<WARNING>: This function does not check the validity of most subfields of
  2121. $form->{recurring}.
  2122. $dbh2 is not used.
  2123. =cut
  2124. sub save_recurring {
  2125. my ( $self, $dbh2, $myconfig ) = @_;
  2126. my $dbh = $self->{dbh};
  2127. my $query;
  2128. $query = qq|DELETE FROM recurring
  2129. WHERE id = ?|;
  2130. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2131. $sth->execute( $self->{id} ) || $self->dberror($query);
  2132. $query = qq|DELETE FROM recurringemail
  2133. WHERE id = ?|;
  2134. $sth = $dbh->prepare($query) || $self->dberror($query);
  2135. $sth->execute( $self->{id} ) || $self->dberror($query);
  2136. $query = qq|DELETE FROM recurringprint
  2137. WHERE id = ?|;
  2138. $sth = $dbh->prepare($query) || $self->dberror($query);
  2139. $sth->execute( $self->{id} ) || $self->dberror($query);
  2140. if ( $self->{recurring} ) {
  2141. my %s = ();
  2142. (
  2143. $s{reference}, $s{startdate}, $s{repeat},
  2144. $s{unit}, $s{howmany}, $s{payment},
  2145. $s{print}, $s{email}, $s{message}
  2146. ) = split /,/, $self->{recurring};
  2147. if ($s{unit} !~ /^(day|week|month|year)s?$/i){
  2148. $dbh->rollback;
  2149. $self->error("Invalid recurrence unit");
  2150. }
  2151. if ($s{howmany} == 0){
  2152. $self->error("Cannot set to recur 0 times");
  2153. }
  2154. for (qw(reference message)) { $s{$_} = $self->unescape( $s{$_} ) }
  2155. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  2156. # calculate enddate
  2157. my $advance = $s{repeat} * ( $s{howmany} - 1 );
  2158. my %interval;
  2159. $interval{'Pg'} =
  2160. "(?::date + interval '$advance $s{unit}')";
  2161. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  2162. my ($enddate) = $dbh->selectrow_array($query, undef, $s{startdate});
  2163. # calculate nextdate
  2164. $query = qq|
  2165. SELECT current_date - ?::date AS a,
  2166. ?::date - current_date AS b|;
  2167. $sth = $dbh->prepare($query) || $self->dberror($query);
  2168. $sth->execute( $s{startdate}, $enddate );
  2169. my ( $a, $b ) = $sth->fetchrow_array;
  2170. if ( $a + $b ) {
  2171. $advance =
  2172. int( ( $a / ( $a + $b ) ) * ( $s{howmany} - 1 ) + 1 ) *
  2173. $s{repeat};
  2174. }
  2175. else {
  2176. $advance = 0;
  2177. }
  2178. my $nextdate = $enddate;
  2179. if ( $advance > 0 ) {
  2180. if ( $advance < ( $s{repeat} * $s{howmany} ) ) {
  2181. $query = qq|SELECT (?::date + interval '$advance $s{unit}')|;
  2182. ($nextdate) = $dbh->selectrow_array($query, undef, $s{startdate});
  2183. }
  2184. }
  2185. else {
  2186. $nextdate = $s{startdate};
  2187. }
  2188. if ( $self->{recurringnextdate} ) {
  2189. $nextdate = $self->{recurringnextdate};
  2190. $query = qq|SELECT ?::date - ?::date|;
  2191. if ( $dbh->selectrow_array($query, undef, $enddate, $nextdate) < 0 ) {
  2192. undef $nextdate;
  2193. }
  2194. }
  2195. $self->{recurringpayment} *= 1;
  2196. $query = qq|
  2197. INSERT INTO recurring
  2198. (id, reference, startdate, enddate, nextdate,
  2199. repeat, unit, howmany, payment)
  2200. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  2201. $sth = $dbh->prepare($query);
  2202. $sth->execute(
  2203. $self->{id}, $s{reference}, $s{startdate},
  2204. $enddate, $nextdate, $s{repeat},
  2205. $s{unit}, $s{howmany}, $s{payment}
  2206. );
  2207. my @p;
  2208. my $p;
  2209. my $i;
  2210. my $sth;
  2211. if ( $s{email} ) {
  2212. # formname:format
  2213. @p = split /:/, $s{email};
  2214. $query =
  2215. qq|INSERT INTO recurringemail (id, formname, format, message)
  2216. VALUES (?, ?, ?, ?)|;
  2217. $sth = $dbh->prepare($query) || $self->dberror($query);
  2218. for ( $i = 0 ; $i <= $#p ; $i += 2 ) {
  2219. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $s{message} );
  2220. }
  2221. $sth->finish;
  2222. }
  2223. if ( $s{print} ) {
  2224. # formname:format:printer
  2225. @p = split /:/, $s{print};
  2226. $query =
  2227. qq|INSERT INTO recurringprint (id, formname, format, printer)
  2228. VALUES (?, ?, ?, ?)|;
  2229. $sth = $dbh->prepare($query) || $self->dberror($query);
  2230. for ( $i = 0 ; $i <= $#p ; $i += 3 ) {
  2231. $p = ( $p[ $i + 2 ] ) ? $p[ $i + 2 ] : "";
  2232. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $p );
  2233. }
  2234. $sth->finish;
  2235. }
  2236. }
  2237. $dbh->commit;
  2238. }
  2239. =item $form->save_intnotes($myconfig, $vc);
  2240. Sets the intnotes field of the entry in the table $vc that has the id
  2241. $form->{id} to the value of $form->{intnotes}.
  2242. Does nothing if $form->{id} is not set.
  2243. =cut
  2244. sub save_intnotes {
  2245. my ( $self, $myconfig, $vc ) = @_;
  2246. # no id return
  2247. return unless $self->{id};
  2248. my $dbh = $self->{dbh};
  2249. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  2250. my $sth = $dbh->prepare($query);
  2251. $sth->execute( $self->{intnotes}, $self->{id} ) || $self->dberror($query);
  2252. $dbh->commit;
  2253. }
  2254. =item $form->update_defaults($myconfig, $fld[, $dbh]);
  2255. Updates the defaults entry for the setting $fld following rules specified by
  2256. the existing value and returns the processed value that results. If $form is
  2257. false, such as the case when invoked as "Form::update_defaults('',...)", $dbh is
  2258. used as the handle. When $form is set, it uses $form->{dbh}, initialising the
  2259. connection if it does not yet exist. The entry $fld must exist prior to
  2260. executing this function and this update function does not handle the general
  2261. case of updating the defaults table.
  2262. B<NOTE>: rules handling is currently broken.
  2263. Rules followed by this function's processing:
  2264. =over
  2265. =item *
  2266. If digits are found in the field, increment the left-most set. This change,
  2267. unlike the others is reflected in the UPDATE.
  2268. =item *
  2269. Replace <?lsmb date ?> with the date specified in $form->{transdate} formatted
  2270. as $myconfig->{dateformat}.
  2271. =item *
  2272. Replace <?lsmb curr ?> with the value of $form->{currency}
  2273. =back
  2274. =cut
  2275. sub update_defaults {
  2276. my ( $self, $myconfig, $fld ) = @_;
  2277. if ( !$self->{dbh} && $self ) {
  2278. $self->db_init($myconfig);
  2279. }
  2280. my $dbh = $self->{dbh};
  2281. if ( !$self ) {
  2282. $dbh = $_[3];
  2283. }
  2284. my $query = qq|
  2285. SELECT value FROM defaults
  2286. WHERE setting_key = ? FOR UPDATE|;
  2287. my $sth = $dbh->prepare($query);
  2288. $sth->execute($fld);
  2289. ($_) = $sth->fetchrow_array();
  2290. $_ = "0" unless $_;
  2291. # check for and replace
  2292. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  2293. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  2294. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  2295. # <?lsmb PHONE ?> for customer and vendors
  2296. my $num = $_;
  2297. ($num) = $num =~ /(\d+)/;
  2298. if ( defined $num ) {
  2299. my $incnum;
  2300. # if we have leading zeros check how long it is
  2301. if ( $num =~ /^0/ ) {
  2302. my $l = length $num;
  2303. $incnum = $num + 1;
  2304. $l -= length $incnum;
  2305. # pad it out with zeros
  2306. my $padzero = "0" x $l;
  2307. $incnum = ( "0" x $l ) . $incnum;
  2308. }
  2309. else {
  2310. $incnum = $num + 1;
  2311. }
  2312. s/$num/$incnum/;
  2313. }
  2314. my $dbvar = $_;
  2315. my $var = $_;
  2316. my $str;
  2317. my $param;
  2318. if (/<\?lsmb /) {
  2319. while (/<\?lsmb /) {
  2320. s/<\?lsmb .*? \?>//;
  2321. last unless $&;
  2322. $param = $&;
  2323. $str = "";
  2324. if ( $param =~ /<\?lsmb date \?>/i ) {
  2325. $str = (
  2326. $self->split_date(
  2327. $myconfig->{dateformat},
  2328. $self->{transdate}
  2329. )
  2330. )[0];
  2331. $var =~ s/$param/$str/;
  2332. }
  2333. if ( $param =~
  2334. /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i
  2335. )
  2336. {
  2337. #SC: XXX hairy, undoc, possibly broken
  2338. my $fld = lc $&;
  2339. $fld =~ s/<\?lsmb //;
  2340. if ( $fld =~ /name/ ) {
  2341. if ( $self->{type} ) {
  2342. $fld = $self->{vc};
  2343. }
  2344. }
  2345. my $p = $param;
  2346. $p =~ s/(<|>|%)//g;
  2347. my @p = split / /, $p;
  2348. my @n = split / /, uc $self->{$fld};
  2349. if ( $#p > 0 ) {
  2350. for ( my $i = 1 ; $i <= $#p ; $i++ ) {
  2351. $str .= substr( $n[ $i - 1 ], 0, $p[$i] );
  2352. }
  2353. }
  2354. else {
  2355. ($str) = split /--/, $self->{$fld};
  2356. }
  2357. $var =~ s/$param/$str/;
  2358. $var =~ s/\W//g if $fld eq 'phone';
  2359. }
  2360. if ( $param =~ /<\?lsmb (yy|mm|dd)/i ) {
  2361. # SC: XXX Does this even work anymore?
  2362. my $p = $param;
  2363. $p =~ s/(<|>|%)//g;
  2364. my $spc = $p;
  2365. $spc =~ s/\w//g;
  2366. $spc = substr( $spc, 0, 1 );
  2367. my %d = ( yy => 1, mm => 2, dd => 3 );
  2368. my @p = ();
  2369. my @a = $self->split_date( $myconfig->{dateformat},
  2370. $self->{transdate} );
  2371. for ( sort keys %d ) { push @p, $a[ $d{$_} ] if ( $p =~ /$_/ ) }
  2372. $str = join $spc, @p;
  2373. $var =~ s/$param/$str/;
  2374. }
  2375. if ( $param =~ /<\?lsmb curr/i ) {
  2376. $var =~ s/$param/$self->{currency}/;
  2377. }
  2378. }
  2379. }
  2380. my $query = qq|
  2381. UPDATE defaults
  2382. SET value = ?
  2383. WHERE setting_key = ?|;
  2384. my $sth = $dbh->prepare($query);
  2385. $sth->execute( $dbvar, $fld ) || $self->dberror($query);
  2386. $dbh->commit;
  2387. $var;
  2388. }
  2389. =item $form->db_prepare_vars(var1, var2, ..., varI<n>)
  2390. Undefines $form->{varI<m>}, 1 <= I<m> <= I<n>, iff $form-<{varI<m> is both
  2391. false and not "0".
  2392. =cut
  2393. sub db_prepare_vars {
  2394. my $self = shift;
  2395. for (@_) {
  2396. if ( !$self->{$_} and $self->{$_} ne "0" ) {
  2397. undef $self->{$_};
  2398. }
  2399. }
  2400. }
  2401. =item $form->split_date($dateformat[, $date]);
  2402. Returns ($rv, $yy, $mm, $dd) for the provided $date, or the current date if no
  2403. date is provided. $rv is a seperator-free merging of the fields $yy, $mm, and
  2404. $dd in the ordering supplied by $dateformat. If the supplied $date does not
  2405. contain non-digit characters, $rv is $date and the other return values are
  2406. undefined.
  2407. $yy is two digits.
  2408. =cut
  2409. sub split_date {
  2410. my ( $self, $dateformat, $date ) = @_;
  2411. my $mm;
  2412. my $dd;
  2413. my $yy;
  2414. my $rv;
  2415. if ( !$date ) {
  2416. my @d = localtime;
  2417. $dd = $d[3];
  2418. $mm = ++$d[4];
  2419. $yy = substr( $d[5], -2 );
  2420. $mm = substr( "0$mm", -2 );
  2421. $dd = substr( "0$dd", -2 );
  2422. }
  2423. if ( $dateformat =~ /^yy/ ) {
  2424. if ($date) {
  2425. if ( $date =~ /\D/ ) {
  2426. ( $yy, $mm, $dd ) = split /\D/, $date;
  2427. $mm *= 1;
  2428. $dd *= 1;
  2429. $mm = substr( "0$mm", -2 );
  2430. $dd = substr( "0$dd", -2 );
  2431. $yy = substr( $yy, -2 );
  2432. $rv = "$yy$mm$dd";
  2433. }
  2434. else {
  2435. $rv = $date;
  2436. }
  2437. }
  2438. else {
  2439. $rv = "$yy$mm$dd";
  2440. }
  2441. }
  2442. elsif ( $dateformat =~ /^mm/ ) {
  2443. if ($date) {
  2444. if ( $date =~ /\D/ ) {
  2445. ( $mm, $dd, $yy ) = split /\D/, $date;
  2446. $mm *= 1;
  2447. $dd *= 1;
  2448. $mm = substr( "0$mm", -2 );
  2449. $dd = substr( "0$dd", -2 );
  2450. $yy = substr( $yy, -2 );
  2451. $rv = "$mm$dd$yy";
  2452. }
  2453. else {
  2454. $rv = $date;
  2455. }
  2456. }
  2457. else {
  2458. $rv = "$mm$dd$yy";
  2459. }
  2460. }
  2461. elsif ( $dateformat =~ /^dd/ ) {
  2462. if ($date) {
  2463. if ( $date =~ /\D/ ) {
  2464. ( $dd, $mm, $yy ) = split /\D/, $date;
  2465. $mm *= 1;
  2466. $dd *= 1;
  2467. $mm = substr( "0$mm", -2 );
  2468. $dd = substr( "0$dd", -2 );
  2469. $yy = substr( $yy, -2 );
  2470. $rv = "$dd$mm$yy";
  2471. }
  2472. else {
  2473. $rv = $date;
  2474. }
  2475. }
  2476. else {
  2477. $rv = "$dd$mm$yy";
  2478. }
  2479. }
  2480. ( $rv, $yy, $mm, $dd );
  2481. }
  2482. =item $form->format_date($date);
  2483. Returns $date converted from 'yyyy-mm-dd' format to the format specified by
  2484. $form->{db_dateformat}. If the supplied date does not match /^\d{4}\D/,
  2485. return the supplied date.
  2486. This function takes a four digit year and returns the date with a four digit
  2487. year.
  2488. =cut
  2489. sub format_date {
  2490. # takes an iso date in, and converts it to the date for printing
  2491. my ( $self, $date ) = @_;
  2492. my $datestring;
  2493. if ( $date =~ /^\d{4}\D/ ) { # is an ISO date
  2494. $datestring = $self->{db_dateformat};
  2495. my ( $yyyy, $mm, $dd ) = split( /\W/, $date );
  2496. $datestring =~ s/y+/$yyyy/;
  2497. $datestring =~ s/mm/$mm/;
  2498. $datestring =~ s/dd/$dd/;
  2499. }
  2500. else { # return date
  2501. $datestring = $date;
  2502. }
  2503. $datestring;
  2504. }
  2505. =item $form->from_to($yyyy, $mm[, $interval]);
  2506. Returns the date $yyyy-$mm-01 and the the last day of the month interval - 1
  2507. months from then in the form ($form->format_date(fromdate),
  2508. $form->format_date(later)). If $interval is false but defined, the later date
  2509. is the current date.
  2510. This function dies horribly when $mm + $interval > 24
  2511. =cut
  2512. sub from_to {
  2513. my ( $self, $yyyy, $mm, $interval ) = @_;
  2514. my @t;
  2515. my $dd = 1;
  2516. my $fromdate = "$yyyy-${mm}-01";
  2517. my $bd = 1;
  2518. if ( defined $interval ) {
  2519. if ( $interval == 12 ) {
  2520. $yyyy++;
  2521. }
  2522. else {
  2523. if ( ( $mm += $interval ) > 12 ) {
  2524. $mm -= 12;
  2525. $yyyy++;
  2526. }
  2527. if ( $interval == 0 ) {
  2528. @t = localtime(time);
  2529. $dd = $t[3];
  2530. $mm = $t[4] + 1;
  2531. $yyyy = $t[5] + 1900;
  2532. $bd = 0;
  2533. }
  2534. }
  2535. }
  2536. else {
  2537. if ( ++$mm > 12 ) {
  2538. $mm -= 12;
  2539. $yyyy++;
  2540. }
  2541. }
  2542. $mm--;
  2543. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yyyy ) - $bd );
  2544. $t[4]++;
  2545. $t[4] = substr( "0$t[4]", -2 );
  2546. $t[3] = substr( "0$t[3]", -2 );
  2547. $t[5] += 1900;
  2548. return ( $self->format_date($fromdate), $self->format_date("$t[5]-$t[4]-$t[3]") );
  2549. }
  2550. =item $form->audittrail($dbh, $myconfig, $audittrail);
  2551. $audittrail is a hashref. If $audittrail->{id} is false, this function
  2552. retrieves the current time from the database and return a string of the form
  2553. "tablename|reference|formname|action|timestamp|" where all the values save
  2554. timestamp are taken directly from the $audittrail hashref.
  2555. If $audittrail->{id} is true but the value of audittrail in the defaults table
  2556. is '0', do nothing and return.
  2557. If $form->{audittrail} is true and $myconfig is false, $form->{audittrail} is
  2558. treated as a pipe seperated list (trailing pipe required) of the form:
  2559. table1|ref1|form1|action1|date1|...|tablen|refn|formn|actionn|daten|
  2560. All the entries described by $form->{audittrail} are inserted into the audit
  2561. table, taking on a transaction id of $audittrail->{id} and the employee id of
  2562. the calling user.
  2563. Irrespective of $form->{audittrail} and $myconfig status, this function will add
  2564. a record to the audittrail using the values contained within $audittrail,
  2565. substituting the current date if $audittrail->{transdate} is not set and the
  2566. employee id of the calling user.
  2567. =cut
  2568. sub audittrail {
  2569. my ( $self, $dbh, $myconfig, $audittrail ) = @_;
  2570. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2571. my $query;
  2572. my $rv;
  2573. my $disconnect;
  2574. if ( !$dbh ) {
  2575. $dbh = $self->{dbh};
  2576. }
  2577. my $sth;
  2578. my $query;
  2579. # if we have an id add audittrail, otherwise get a new timestamp
  2580. my @queryargs;
  2581. if ( $audittrail->{id} ) {
  2582. $query = qq|
  2583. SELECT value FROM defaults
  2584. WHERE setting_key = 'audittrail'|;
  2585. if ( $dbh->selectrow_array($query) ) {
  2586. my ( $null, $employee_id ) = $self->get_employee($dbh);
  2587. if ( $self->{audittrail} && !$myconfig ) {
  2588. chop $self->{audittrail};
  2589. my @a = split /\|/, $self->{audittrail};
  2590. my %newtrail = ();
  2591. my $key;
  2592. my $i;
  2593. my @flds = qw(tablename reference formname action transdate);
  2594. # put into hash and remove dups
  2595. while (@a) {
  2596. $key = "$a[2]$a[3]";
  2597. $i = 0;
  2598. $newtrail{$key} = { map { $_ => $a[ $i++ ] } @flds };
  2599. splice @a, 0, 5;
  2600. }
  2601. $query = qq|
  2602. INSERT INTO audittrail
  2603. (trans_id, tablename, reference,
  2604. formname, action, transdate,
  2605. employee_id)
  2606. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2607. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2608. foreach $key (
  2609. sort {
  2610. $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
  2611. } keys %newtrail
  2612. )
  2613. {
  2614. $i = 2;
  2615. $sth->bind_param( 1, $audittrail->{id} );
  2616. for (@flds) {
  2617. $sth->bind_param( $i++, $newtrail{$key}{$_} );
  2618. }
  2619. $sth->bind_param( $i++, $employee_id );
  2620. $sth->execute() || $self->dberror($query);
  2621. $sth->finish;
  2622. }
  2623. }
  2624. if ( $audittrail->{transdate} ) {
  2625. $query = qq|
  2626. INSERT INTO audittrail (
  2627. trans_id, tablename, reference,
  2628. formname, action, employee_id,
  2629. transdate)
  2630. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2631. @queryargs = (
  2632. $audittrail->{id}, $audittrail->{tablename},
  2633. $audittrail->{reference}, $audittrail->{formname},
  2634. $audittrail->{action}, $employee_id,
  2635. $audittrail->{transdate}
  2636. );
  2637. }
  2638. else {
  2639. $query = qq|
  2640. INSERT INTO audittrail
  2641. (trans_id, tablename, reference,
  2642. formname, action, employee_id)
  2643. VALUES (?, ?, ?, ?, ?, ?)|;
  2644. @queryargs = (
  2645. $audittrail->{id}, $audittrail->{tablename},
  2646. $audittrail->{reference}, $audittrail->{formname},
  2647. $audittrail->{action}, $employee_id,
  2648. );
  2649. }
  2650. $sth = $dbh->prepare($query);
  2651. $sth->execute(@queryargs) || $self->dberror($query);
  2652. }
  2653. }
  2654. else {
  2655. $query = qq|SELECT current_timestamp|;
  2656. my ($timestamp) = $dbh->selectrow_array($query);
  2657. $rv =
  2658. "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2659. }
  2660. $rv;
  2661. }
  2662. 1;
  2663. =back