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