summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: 4d05549753b73048191651b4367c9b23166a8134 (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. # Handling of HTTP Basic Auth headers
  813. my $auth = $ENV{'HTTP_AUTHORIZATION'};
  814. $auth =~ s/Basic //i; # strip out basic authentication preface
  815. $auth = MIME::Base64::decode($auth);
  816. my ($login, $password) = split(/:/, $auth);
  817. $self->{dbh} = $self->dbconnect_noauto($myconfig) || $self->dberror();
  818. my %date_query = (
  819. 'mm/dd/yy' => 'set DateStyle to \'SQL, US\'',
  820. 'mm-dd-yy' => 'set DateStyle to \'POSTGRES, US\'',
  821. 'dd/mm/yy' => 'set DateStyle to \'SQL, EUROPEAN\'',
  822. 'dd-mm-yy' => 'set DateStyle to \'POSTGRES, EUROPEAN\'',
  823. 'dd.mm.yy' => 'set DateStyle to \'GERMAN\''
  824. );
  825. $self->{dbh}->do( $date_query{ $myconfig->{dateformat} } );
  826. $self->{db_dateformat} = $myconfig->{dateformat}; #shim
  827. my $query = "SELECT t.extends,
  828. coalesce (t.table_name, 'custom_' || extends)
  829. || ':' || f.field_name as field_def
  830. FROM custom_table_catalog t
  831. JOIN custom_field_catalog f USING (table_id)";
  832. my $sth = $self->{dbh}->prepare($query);
  833. $sth->execute;
  834. my $ref;
  835. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  836. push @{ $self->{custom_db_fields}{ $ref->{extends} } },
  837. $ref->{field_def};
  838. }
  839. }
  840. =item $form->run_custom_queries($tablename, $query_type[, $linenum]);
  841. Runs queries against custom fields for the specified $query_type against
  842. $tablename.
  843. Valid values for $query_type are any casing of 'SELECT', 'INSERT', and 'UPDATE'.
  844. =cut
  845. sub run_custom_queries {
  846. my ( $self, $tablename, $query_type, $linenum ) = @_;
  847. my $dbh = $self->{dbh};
  848. if ( $query_type !~ /^(select|insert|update)$/i ) {
  849. $self->error(
  850. "Passed incorrect query type to run_custom_queries."
  851. );
  852. }
  853. my @rc;
  854. my %temphash;
  855. my @templist;
  856. my @elements;
  857. my $query;
  858. my $did_insert;
  859. my $ins_values;
  860. my $sth;
  861. if ($linenum) {
  862. $linenum = "_$linenum";
  863. }
  864. $query_type = uc($query_type);
  865. for ( @{ $self->{custom_db_fields}{$tablename} } ) {
  866. @elements = split( /:/, $_ );
  867. push @{ $temphash{ $elements[0] } }, $elements[1];
  868. }
  869. for ( keys %temphash ) {
  870. my @data;
  871. my $ins_values;
  872. $query = "$query_type ";
  873. if ( $query_type eq 'UPDATE' ) {
  874. $query = "DELETE FROM $_ WHERE row_id = ?";
  875. my $sth = $dbh->prepare($query);
  876. $sth->execute( $self->{ "id" . "$linenum" } )
  877. || $self->dberror($query);
  878. }
  879. elsif ( $query_type eq 'INSERT' ) {
  880. $query .= " INTO $_ (";
  881. }
  882. my $first = 1;
  883. for ( @{ $temphash{$_} } ) {
  884. $query .= "$_";
  885. if ( $query_type eq 'UPDATE' ) {
  886. $query .= '= ?';
  887. }
  888. $ins_values .= "?, ";
  889. $query .= ", ";
  890. $first = 0;
  891. if ( $query_type eq 'UPDATE' or $query_type eq 'INSERT' ) {
  892. push @data, $self->{"$_$linenum"};
  893. }
  894. }
  895. if ( $query_type ne 'INSERT' ) {
  896. $query =~ s/, $//;
  897. }
  898. if ( $query_type eq 'SELECT' ) {
  899. $query .= " FROM $_";
  900. }
  901. if ( $query_type eq 'SELECT' or $query_type eq 'UPDATE' ) {
  902. $query .= " WHERE row_id = ?";
  903. }
  904. if ( $query_type eq 'INSERT' ) {
  905. $query .= " row_id) VALUES ($ins_values ?)";
  906. }
  907. if ( $query_type eq 'SELECT' ) {
  908. push @rc, [$query];
  909. }
  910. else {
  911. unshift( @data, $query );
  912. push @rc, [@data];
  913. }
  914. }
  915. if ( $query_type eq 'INSERT' ) {
  916. for (@rc) {
  917. $query = shift( @{$_} );
  918. $sth = $dbh->prepare($query)
  919. || $self->db_error($query);
  920. $sth->execute( @{$_}, $self->{id} )
  921. || $self->dberror($query);
  922. $sth->finish;
  923. $did_insert = 1;
  924. }
  925. }
  926. elsif ( $query_type eq 'UPDATE' ) {
  927. @rc = $self->run_custom_queries( $tablename, 'INSERT', $linenum );
  928. }
  929. elsif ( $query_type eq 'SELECT' ) {
  930. for (@rc) {
  931. my $query = shift @{$_};
  932. my $sth = $self->{dbh}->prepare($query);
  933. $sth->execute( $self->{id} );
  934. my $ref = $sth->fetchrow_hashref('NAME_lc');
  935. for ( keys %{$ref} ) {
  936. $self->{$_} = $ref->{$_};
  937. }
  938. }
  939. }
  940. @rc;
  941. }
  942. =item $form->dbconnect($myconfig);
  943. Returns an autocommit connection to the database specified in $myconfig.
  944. =cut
  945. sub dbconnect {
  946. my ( $self, $myconfig ) = @_;
  947. # connect to database
  948. my $dbh = DBI->connect( $myconfig->{dbconnect},
  949. $myconfig->{dbuser}, $myconfig->{dbpasswd} )
  950. or $self->dberror;
  951. $dbh->{pg_enable_utf8} = 1;
  952. # set db options
  953. if ( $myconfig->{dboptions} ) {
  954. $dbh->do( $myconfig->{dboptions} )
  955. || $self->dberror( $myconfig->{dboptions} );
  956. }
  957. $dbh;
  958. }
  959. =item $form->dbconnect_noauto($myconfig);
  960. Returns a non-autocommit connection to the database specified in $myconfig.
  961. =cut
  962. sub dbconnect_noauto {
  963. my ( $self, $myconfig ) = @_;
  964. # connect to database
  965. my $dbh = DBI->connect(
  966. $myconfig->{dbconnect}, $myconfig->{dbuser},
  967. $myconfig->{dbpasswd}, { AutoCommit => 0 }
  968. ) or $self->dberror;
  969. $dbh->{pg_enable_utf8} = 1;
  970. # set db options
  971. if ( $myconfig->{dboptions} ) {
  972. $dbh->do( $myconfig->{dboptions} );
  973. }
  974. $dbh;
  975. }
  976. =item $form->dbquote($var);
  977. If $var is an empty string, return NULL, otherwise return $var as quoted by
  978. $form->{dbh}->quote($var).
  979. =cut
  980. sub dbquote {
  981. my ( $self, $var ) = @_;
  982. if ( $var eq '' ) {
  983. $_ = "NULL";
  984. }
  985. else {
  986. $_ = $self->{dbh}->quote($var);
  987. }
  988. $_;
  989. }
  990. =item $form->update_balance($dbh, $table, $field, $where, $value);
  991. B<WARNING>: This is a dangerous private function. All apps calling it must be
  992. careful to avoid SQL injection issues.
  993. If $value is set, sets the value of $field in $table to the sum of the current
  994. stored value and $value. In order to not annihilate the values in $table,
  995. $where must contain a WHERE clause that limits the UPDATE to a single row.
  996. =cut
  997. sub update_balance {
  998. # This is a dangerous private function. All apps calling it must
  999. # be careful to avoid SQL injection issues
  1000. my ( $self, $dbh, $table, $field, $where, $value ) = @_;
  1001. $table = $dbh->quote_identifier($table);
  1002. $field = $dbh->quote_identifier($field);
  1003. # if we have a value, go do it
  1004. if ($value) {
  1005. # retrieve balance from table
  1006. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  1007. my ($balance) = $dbh->selectrow_array($query);
  1008. $balance = $dbh->quote($balance + $value);
  1009. # update balance
  1010. $query = "UPDATE $table SET $field = $balance WHERE $where";
  1011. $dbh->do($query) || $self->dberror($query);
  1012. }
  1013. }
  1014. =item $form->update_exchangerate($dbh, $curr, $transdate, $buy, $sell);
  1015. Updates the exchange rates $buy and $sell for the given $currency on $transdate.
  1016. If there is not yet an exchange rate for $currency on $transdate, an entry is
  1017. inserted. This returns without doing anything if $curr eq ''.
  1018. $dbh is not used, favouring $self->{dbh}.
  1019. =cut
  1020. sub update_exchangerate {
  1021. my ( $self, $dbh, $curr, $transdate, $buy, $sell ) = @_;
  1022. # some sanity check for currency
  1023. return if ( $curr eq "" );
  1024. my $query = qq|
  1025. SELECT curr
  1026. FROM exchangerate
  1027. WHERE curr = ?
  1028. AND transdate = ?
  1029. FOR UPDATE|;
  1030. my $sth = $self->{dbh}->prepare($query);
  1031. $sth->execute( $curr, $transdate ) || $self->dberror($query);
  1032. my $set;
  1033. my @queryargs;
  1034. if ( $buy && $sell ) {
  1035. $set = "buy = ?, sell = ?";
  1036. @queryargs = ( $buy, $sell );
  1037. }
  1038. elsif ($buy) {
  1039. $set = "buy = ?";
  1040. @queryargs = ($buy);
  1041. }
  1042. elsif ($sell) {
  1043. $set = "sell = ?";
  1044. @queryargs = ($sell);
  1045. }
  1046. if ( !$set ) {
  1047. $self->error("Exchange rate missing!");
  1048. }
  1049. if ( $sth->fetchrow_array ) {
  1050. $query = qq|UPDATE exchangerate
  1051. SET $set
  1052. WHERE curr = ?
  1053. AND transdate = ?|;
  1054. push( @queryargs, $curr, $transdate );
  1055. }
  1056. else {
  1057. $query = qq|
  1058. INSERT INTO exchangerate (
  1059. curr, buy, sell, transdate)
  1060. VALUES (?, ?, ?, ?)|;
  1061. @queryargs = ( $curr, $buy, $sell, $transdate );
  1062. }
  1063. $sth->finish;
  1064. $sth = $self->{dbh}->prepare($query);
  1065. $sth->execute(@queryargs) || $self->dberror($query);
  1066. }
  1067. =item $form->save_exchangerate($myconfig, $currency, $transdate, $rate, $fld);
  1068. Saves the exchange rate $rate for the given $currency on $transdate for the
  1069. provided purpose in $fld. $fld can be either 'buy' or 'sell'.
  1070. $myconfig is not used. $self->update_exchangerate is used for the majority of
  1071. the work.
  1072. =cut
  1073. sub save_exchangerate {
  1074. my ( $self, $myconfig, $currency, $transdate, $rate, $fld ) = @_;
  1075. my ( $buy, $sell ) = ( 0, 0 );
  1076. $buy = $rate if $fld eq 'buy';
  1077. $sell = $rate if $fld eq 'sell';
  1078. $self->update_exchangerate( $self->{dbh}, $currency, $transdate, $buy,
  1079. $sell );
  1080. }
  1081. =item $form->get_exchangerate($dbh, $curr, $transdate, $fld);
  1082. Returns the exchange rate in relation to the default currency for $currency on
  1083. $transdate for the purpose indicated by $fld. $fld can be either 'buy' or
  1084. 'sell' to get usable results.
  1085. $dbh is not used, favouring $self->{dbh}.
  1086. =cut
  1087. sub get_exchangerate {
  1088. my ( $self, $dbh, $curr, $transdate, $fld ) = @_;
  1089. my $exchangerate = 1;
  1090. my $sth;
  1091. if ($transdate) {
  1092. my $query = qq|
  1093. SELECT $fld FROM exchangerate
  1094. WHERE curr = ? AND transdate = ?|;
  1095. $sth = $self->{dbh}->prepare($query);
  1096. $sth->execute( $curr, $transdate );
  1097. ($exchangerate) = $sth->fetchrow_array;
  1098. $exchangerate = Math::BigFloat->new($exchangerate);
  1099. }
  1100. $sth->finish;
  1101. $exchangerate;
  1102. }
  1103. =item $form->check_exchangerate($myconfig, $currency, $transdate, $fld);
  1104. Returns some true value when an entry for $currency on $transdate is true for
  1105. the purpose indicated by $fld. $fld can be either 'buy' or 'sell' to get
  1106. usable results. Returns false if $transdate is not set.
  1107. $myconfig is not used.
  1108. =cut
  1109. sub check_exchangerate {
  1110. my ( $self, $myconfig, $currency, $transdate, $fld ) = @_;
  1111. return "" unless $transdate;
  1112. my $query = qq|
  1113. SELECT $fld
  1114. FROM exchangerate
  1115. WHERE curr = ? AND transdate = ?|;
  1116. my $sth = $self->{dbh}->prepare($query);
  1117. $sth->execute( $currency, $transdate );
  1118. my ($exchangerate) = $sth->fetchrow_array;
  1119. $sth->finish;
  1120. $exchangerate;
  1121. }
  1122. =item $form->add_shipto($dbh, $id);
  1123. Inserts a new address into the table shipto if the value of any of the shipto
  1124. address components in $form differs to the regular attribute in $form. The
  1125. inserted value of trans_id is $id, the other fields correspond with the shipto
  1126. address components of $form.
  1127. $dbh is unused.
  1128. =cut
  1129. sub add_shipto {
  1130. my ( $self, $dbh, $id ) = @_;
  1131. my $shipto;
  1132. foreach my $item (
  1133. qw(name address1 address2 city state
  1134. zipcode country contact phone fax email)
  1135. )
  1136. {
  1137. if ( $self->{"shipto$item"} ne "" ) {
  1138. $shipto = 1 if ( $self->{$item} ne $self->{"shipto$item"} );
  1139. }
  1140. }
  1141. if ($shipto) {
  1142. my $query = qq|
  1143. INSERT INTO shipto
  1144. (trans_id, shiptoname, shiptoaddress1,
  1145. shiptoaddress2, shiptocity, shiptostate,
  1146. shiptozipcode, shiptocountry, shiptocontact,
  1147. shiptophone, shiptofax, shiptoemail)
  1148. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1149. |;
  1150. my $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  1151. $sth->execute(
  1152. $id, $self->{shiptoname},
  1153. $self->{shiptoaddress1}, $self->{shiptoaddress2},
  1154. $self->{shiptocity}, $self->{shiptostate},
  1155. $self->{shiptozipcode}, $self->{shiptocountry},
  1156. $self->{shiptocontact}, $self->{shiptophone},
  1157. $self->{shiptofax}, $self->{shiptoemail}
  1158. ) || $self->dberror($query);
  1159. $sth->finish;
  1160. }
  1161. }
  1162. =item $form->get_employee($dbh);
  1163. Returns a list containing the name and id of the employee $form->{login}. Any
  1164. portion of $form->{login} including and past '@' are ignored.
  1165. $dbh is unused.
  1166. =cut
  1167. sub get_employee {
  1168. my ( $self, $dbh ) = @_;
  1169. my $login = $self->{login};
  1170. $login =~ s/@.*//;
  1171. my $query = qq|
  1172. SELECT name, id
  1173. FROM entity WHERE id IN (select entity_id
  1174. FROM employee
  1175. WHERE login = ?)|;
  1176. my $sth = $self->{dbh}->prepare($query);
  1177. $sth->execute($login);
  1178. my (@a) = $sth->fetchrow_array();
  1179. $a[1] *= 1;
  1180. $sth->finish;
  1181. @a;
  1182. }
  1183. =item $form->get_name($myconfig, $table[, $transdate])
  1184. Sets $form->{name_list} to refer to a list of customers or vendors whose names
  1185. or numbers match the value found in $form->{$table} and returns the number of
  1186. matches. $table can be 'vendor', 'customer', or 'employee'; if the optional
  1187. field $transdate is provided, the result set is further limited to $table
  1188. entries which were active on the provided date as determined by the start and
  1189. end dates. The elements of $form->{name_list} are references returned rows in
  1190. hashref form and are sorted by the name field. The fields of the hash are those
  1191. of the view $table and the table entity.
  1192. $myconfig is unused.
  1193. =cut
  1194. # this sub gets the id and name from $table
  1195. sub get_name {
  1196. my ( $self, $myconfig, $table, $transdate ) = @_;
  1197. my @queryargs;
  1198. my $where;
  1199. if ($transdate) {
  1200. $where = qq|
  1201. AND (startdate IS NULL OR startdate <= ?)
  1202. AND (enddate IS NULL OR enddate >= ?)|;
  1203. @queryargs = ( $transdate, $transdate );
  1204. }
  1205. # SC: Check for valid table/view name. Other values will cause SQL errors.
  1206. if ($table !~ /^(vendor|customer|employee)$/i) {
  1207. $self->error('Invalid name source');
  1208. }
  1209. # Company name is stored in $self->{vendor} or $self->{customer}
  1210. my $name = $self->like( lc $self->{$table} );
  1211. # Vendor and Customer are now views into entity_credit_account.
  1212. my $query = qq|
  1213. SELECT * FROM $table t
  1214. JOIN entity e ON t.entity_id = e.id
  1215. WHERE (lower(e.name) LIKE ? OR t.${table}number LIKE ?)
  1216. $where
  1217. ORDER BY e.name|;
  1218. unshift( @queryargs, $name, $name, $table );
  1219. my $sth = $self->{dbh}->prepare($query);
  1220. $sth->execute(@queryargs) || $self->dberror($query);
  1221. my $i = 0;
  1222. @{ $self->{name_list} } = ();
  1223. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1224. push( @{ $self->{name_list} }, $ref );
  1225. $i++;
  1226. }
  1227. $sth->finish;
  1228. return $i;
  1229. }
  1230. =item $form->all_vc($myconfig, $vc, $module, $dbh, $transdate, $job);
  1231. Populates the list referred to by $form->{all_${vc}} with hashes of either
  1232. vendor or customer id and name, ordered by the name. This will be vendor
  1233. details unless $vc is set to 'customer'. This list can be limited to only
  1234. vendors or customers which are usable on a given day by specifying $transdate.
  1235. As a further restriction, $form->{all_${vc}} will not be populated if the
  1236. number of vendors or customers that would be present in that list exceeds, or
  1237. is equal to, $myconfig->{vclimit}.
  1238. In addition to the possible population of $form->{all_${vc}},
  1239. $form->{employee_id} is looked up if not already set, the list
  1240. $form->{all_language} is populated using the language table and is sorted by the
  1241. description, and $form->all_employees, $form->all_departments,
  1242. $form->all_projects, and $form->all_taxaccounts are all run.
  1243. $module and $dbh are unused.
  1244. =cut
  1245. sub all_vc {
  1246. my ( $self, $myconfig, $vc, $module, $dbh, $transdate, $job ) = @_;
  1247. my $ref;
  1248. $dbh = $self->{dbh};
  1249. my $sth;
  1250. if ($vc eq 'customer'){
  1251. $self->{vc_class} = 2;
  1252. } else {
  1253. $self->{vc_class} = 1;
  1254. $vc = 'vendor';
  1255. }
  1256. my $query = qq|SELECT count(*) FROM entity_credit_account where entity_class = ?|;
  1257. my $where;
  1258. my @queryargs2 = ($self->{vc_class});
  1259. my @queryargs;
  1260. if ($transdate) {
  1261. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1262. AND (enddate IS NULL OR enddate >= ?)|;
  1263. $where = qq| (startdate IS NULL OR startdate <= ?)
  1264. AND (enddate IS NULL OR enddate >= ?)
  1265. AND entity_class = ?|;
  1266. push (@queryargs, $transdate, $transdate, $self->{vc_class});
  1267. push (@queryargs2, $transdate, $transdate);
  1268. } else {
  1269. $where = " true";
  1270. }
  1271. $sth = $dbh->prepare($query);
  1272. $sth->execute(@queryargs2);
  1273. my ($count) = $sth->fetchrow_array;
  1274. $sth->finish;
  1275. # build selection list
  1276. if ( $count < $myconfig->{vclimit} ) {
  1277. $self->{"${vc}_id"} *= 1;
  1278. $query = qq|SELECT id, name
  1279. FROM entity
  1280. WHERE id IN (select entity_id
  1281. FROM
  1282. entity_credit_account
  1283. WHERE
  1284. $where)
  1285. UNION
  1286. SELECT id,name
  1287. FROM entity
  1288. WHERE id = ?
  1289. ORDER BY name|;
  1290. push( @queryargs, $self->{"${vc}_id"} );
  1291. $sth = $dbh->prepare($query);
  1292. $sth->execute(@queryargs) || $self->dberror($query);
  1293. @{ $self->{"all_$vc"} } = ();
  1294. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1295. push @{ $self->{"all_$vc"} }, $ref;
  1296. }
  1297. $sth->finish;
  1298. }
  1299. # get self
  1300. if ( !$self->{employee_id} ) {
  1301. ( $self->{employee}, $self->{employee_id} ) = split /--/,
  1302. $self->{employee};
  1303. ( $self->{employee}, $self->{employee_id} ) = $self->get_employee($dbh)
  1304. unless $self->{employee_id};
  1305. }
  1306. $self->all_employees( $myconfig, $dbh, $transdate, 1 );
  1307. $self->all_departments( $myconfig, $dbh, $vc );
  1308. $self->all_projects( $myconfig, $dbh, $transdate, $job );
  1309. # get language codes
  1310. $query = qq|SELECT *
  1311. FROM language
  1312. ORDER BY 2|;
  1313. $sth = $dbh->prepare($query);
  1314. $sth->execute || $self->dberror($query);
  1315. $self->{all_language} = ();
  1316. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1317. push @{ $self->{all_language} }, $ref;
  1318. }
  1319. $sth->finish;
  1320. $self->all_taxaccounts( $myconfig, $dbh, $transdate );
  1321. }
  1322. =item $form->all_taxaccounts($myconfig, $dbh2[, $transdate]);
  1323. Get the tax rates and numbers for all the taxes in $form->{taxaccounts}. Does
  1324. nothing if $form->{taxaccounts} is false. Taxes are listed as a space seperated
  1325. list of account numbers from the chart. The retrieved values are placed within
  1326. $form->{${accno}_rate} and $form->{${accno}_taxnumber}. If $transdate is set,
  1327. then only process taxes that were valid on $transdate.
  1328. $myconfig and $dbh2 are unused.
  1329. =cut
  1330. sub all_taxaccounts {
  1331. my ( $self, $myconfig, $dbh2, $transdate ) = @_;
  1332. my $dbh = $self->{dbh};
  1333. my $sth;
  1334. my $query;
  1335. my $where;
  1336. my @queryargs = ();
  1337. if ($transdate) {
  1338. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1339. push( @queryargs, $transdate );
  1340. }
  1341. if ( $self->{taxaccounts} ) {
  1342. # rebuild tax rates
  1343. $query = qq|SELECT t.rate, t.taxnumber
  1344. FROM tax t
  1345. JOIN chart c ON (c.id = t.chart_id)
  1346. WHERE c.accno = ?
  1347. $where
  1348. ORDER BY accno, validto|;
  1349. $sth = $dbh->prepare($query) || $self->dberror($query);
  1350. foreach my $accno ( split / /, $self->{taxaccounts} ) {
  1351. $sth->execute( $accno, @queryargs );
  1352. ( $self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"} ) =
  1353. $sth->fetchrow_array;
  1354. $sth->finish;
  1355. }
  1356. }
  1357. }
  1358. =item $form->all_employees($myconfig, $dbh2, $transdate, $sales);
  1359. Sets $form->{all_employee} to be a reference to an array referencing hashes of
  1360. employee information. The hashes are of the form {'id' => id, 'name' => name}.
  1361. If $transdate is set, the query is limited to employees who are active on that
  1362. day. If $sales is true, only employees with the sales flag set are added.
  1363. $dbh2 is unused.
  1364. =cut
  1365. sub all_employees {
  1366. my ( $self, $myconfig, $dbh2, $transdate, $sales ) = @_;
  1367. my $dbh = $self->{dbh};
  1368. my @whereargs = ();
  1369. # setup employees/sales contacts
  1370. my $query = qq|
  1371. SELECT id, name
  1372. FROM entity
  1373. WHERE id IN (SELECT entity_id FROM employee
  1374. WHERE|;
  1375. if ($transdate) {
  1376. $query .= qq| (startdate IS NULL OR startdate <= ?)
  1377. AND (enddate IS NULL OR enddate >= ?) AND|;
  1378. @whereargs = ( $transdate, $transdate );
  1379. }
  1380. else {
  1381. $query .= qq| enddate IS NULL AND|;
  1382. }
  1383. if ($sales) {
  1384. $query .= qq| sales = '1' AND|;
  1385. }
  1386. $query =~ s/(WHERE|AND)$//;
  1387. $query .= qq|) ORDER BY name|;
  1388. my $sth = $dbh->prepare($query);
  1389. $sth->execute(@whereargs) || $self->dberror($query);
  1390. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1391. push @{ $self->{all_employee} }, $ref;
  1392. }
  1393. $sth->finish;
  1394. }
  1395. =item $form->all_projects($myconfig, $dbh2[, $transdate, $job]);
  1396. Populates the list referred to as $form->{all_project} with hashes detailing
  1397. all projects. If $job is true, limit the projects to those whose ids are not
  1398. also present in parts with a project_id > 0. If $transdate is set, the projects
  1399. are limited to those valid on $transdate. If $form->{language_code} is set,
  1400. include the translation description in the project list and limit to
  1401. translations with a matching language_code. The result list,
  1402. $form->{all_project}, is sorted by projectnumber.
  1403. $myconfig and $dbh2 are unused. $job appears to be part of attempted job-
  1404. costing support.
  1405. =cut
  1406. sub all_projects {
  1407. my ( $self, $myconfig, $dbh2, $transdate, $job ) = @_;
  1408. my $dbh = $self->{dbh};
  1409. my @queryargs = ();
  1410. my $where = "1 = 1";
  1411. $where = qq|id NOT IN (SELECT id
  1412. FROM parts
  1413. WHERE project_id > 0)| if !$job;
  1414. my $query = qq|SELECT *
  1415. FROM project
  1416. WHERE $where|;
  1417. if ( $self->{language_code} ) {
  1418. $query = qq|
  1419. SELECT pr.*, t.description AS translation
  1420. FROM project pr
  1421. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1422. WHERE t.language_code = ?|;
  1423. push( @queryargs, $self->{language_code} );
  1424. }
  1425. if ($transdate) {
  1426. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1427. AND (enddate IS NULL OR enddate >= ?)|;
  1428. push( @queryargs, $transdate, $transdate );
  1429. }
  1430. $query .= qq| ORDER BY projectnumber|;
  1431. my $sth = $dbh->prepare($query);
  1432. $sth->execute(@queryargs) || $self->dberror($query);
  1433. @{ $self->{all_project} } = ();
  1434. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1435. push @{ $self->{all_project} }, $ref;
  1436. }
  1437. $sth->finish;
  1438. }
  1439. =item $form->all_departments($myconfig, $dbh2, $vc);
  1440. Set $form->{all_department} to be a reference to a list of hashrefs describing
  1441. departments of the form {'id' => id, 'description' => description}. If $vc
  1442. is 'customer', further limit the results to those whose role is 'P' (Profit
  1443. Center).
  1444. This procedure is internally followed by a call to $form->all_years($myconfig).
  1445. $dbh2 is not used.
  1446. =cut
  1447. sub all_departments {
  1448. my ( $self, $myconfig, $dbh2, $vc ) = @_;
  1449. my $dbh = $self->{dbh};
  1450. my $where = "1 = 1";
  1451. if ($vc) {
  1452. if ( $vc eq 'customer' ) {
  1453. $where = " role = 'P'";
  1454. }
  1455. }
  1456. my $query = qq|SELECT id, description
  1457. FROM department
  1458. WHERE $where
  1459. ORDER BY 2|;
  1460. my $sth = $dbh->prepare($query);
  1461. $sth->execute || $self->dberror($query);
  1462. @{ $self->{all_department} } = ();
  1463. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1464. push @{ $self->{all_department} }, $ref;
  1465. }
  1466. $sth->finish;
  1467. $self->all_years($myconfig);
  1468. }
  1469. =item $form->all_years($myconfig[, $dbh2]);
  1470. Populates the hash $form->{all_month} with a mapping between a two-digit month
  1471. number and the English month name. Populates the list $form->{all_years} with
  1472. the years between the year of the oldest transaction date in acc_trans and the
  1473. newest, inclusive.
  1474. $dbh2 is unused.
  1475. =cut
  1476. sub all_years {
  1477. my ( $self, $myconfig, $dbh2 ) = @_;
  1478. my $dbh = $self->{dbh};
  1479. # get years
  1480. my $query = qq|
  1481. SELECT (SELECT transdate FROM acc_trans ORDER BY transdate asc
  1482. LIMIT 1),
  1483. (SELECT transdate FROM acc_trans ORDER BY transdate desc
  1484. LIMIT 1)|;
  1485. my ( $startdate, $enddate ) = $dbh->selectrow_array($query);
  1486. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1487. ($startdate) = split /\W/, $startdate;
  1488. ($enddate) = split /\W/, $enddate;
  1489. }
  1490. else {
  1491. (@_) = split /\W/, $startdate;
  1492. $startdate = $_[2];
  1493. (@_) = split /\W/, $enddate;
  1494. $enddate = $_[2];
  1495. }
  1496. $self->{all_years} = ();
  1497. $startdate = substr( $startdate, 0, 4 );
  1498. $enddate = substr( $enddate, 0, 4 );
  1499. while ( $enddate >= $startdate ) {
  1500. push @{ $self->{all_years} }, $enddate--;
  1501. }
  1502. #this should probably be changed to use locale
  1503. %{ $self->{all_month} } = (
  1504. '01' => 'January',
  1505. '02' => 'February',
  1506. '03' => 'March',
  1507. '04' => 'April',
  1508. '05' => 'May ',
  1509. '06' => 'June',
  1510. '07' => 'July',
  1511. '08' => 'August',
  1512. '09' => 'September',
  1513. '10' => 'October',
  1514. '11' => 'November',
  1515. '12' => 'December'
  1516. );
  1517. }
  1518. =item $form->create_links($module, $myconfig, $vc[, $job]);
  1519. Populates the hash referred to as $form->{${module}_links} details about
  1520. accounts that have $module in their link field. The hash is keyed upon link
  1521. elements such as 'AP_amount' and 'AR_tax' and they refer to lists of hashes
  1522. containing accno and description for the appropriate accounts. If the key does
  1523. not contain 'tax', the account number is appended to the space seperated list
  1524. $form->{accounts}. $module is typically 'AR' or 'AP' and is the base type of
  1525. the accounts looked up.
  1526. If $form->{id} is not set, check $form->{"$form->{vc}_id"}. If neither is set,
  1527. use $form->lastname_used to populate the details. If $form->{id} is set,
  1528. populate the invnumber, transdate, ${vc}_id, datepaid, duedate, ordnumber,
  1529. taxincluded, currency, notes, intnotes, ${vc}, department_id, department,
  1530. oldinvtotal, oldtotalpaid, employee_id, employee, language_code, ponumber,
  1531. reverse, printed, emailed, queued, recurring, exchangerate, and acc_trans
  1532. attributes of $form with details about the transaction $form->{id}. All of
  1533. these attributes, save for acc_trans, are scalar; $form->{acc_trans} refers to
  1534. a hash keyed by link elements whose values are lists of references to hashes
  1535. describing acc_trans table entries corresponding to the transaction $form->{id}.
  1536. The elements in the acc_trans entry hashes are accno, description, source,
  1537. amount, memo, transdate, cleared, project_id, projectnumber, and exchangerate.
  1538. The closedto, revtrans, and currencies $form attributes are filled with values
  1539. from the defaults table, while $form->{current_date} is populated with the
  1540. current date. If $form->{id} is not set, then $form->{transdate} also takes on
  1541. the current date.
  1542. After all this, it calls $form->all_vc to conclude.
  1543. =cut
  1544. sub create_links {
  1545. my ( $self, $module, $myconfig, $vc, $job ) = @_;
  1546. # get last customers or vendors
  1547. my ( $query, $sth );
  1548. if (!$self->{dbh}) {
  1549. $self->db_init($myconfig);
  1550. }
  1551. my $dbh = $self->{dbh};
  1552. my %xkeyref = ();
  1553. my $val;
  1554. my $ref;
  1555. my $key;
  1556. # now get the account numbers
  1557. $query = qq|SELECT accno, description, link
  1558. FROM chart
  1559. WHERE link LIKE ?
  1560. ORDER BY accno|;
  1561. $sth = $dbh->prepare($query);
  1562. $sth->execute( "%" . "$module%" ) || $self->dberror($query);
  1563. $self->{accounts} = "";
  1564. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1565. foreach my $key ( split /:/, $ref->{link} ) {
  1566. if ( $key =~ /$module/ ) {
  1567. # cross reference for keys
  1568. $xkeyref{ $ref->{accno} } = $key;
  1569. push @{ $self->{"${module}_links"}{$key} },
  1570. {
  1571. accno => $ref->{accno},
  1572. description => $ref->{description}
  1573. };
  1574. $self->{accounts} .= "$ref->{accno} "
  1575. unless $key =~ /tax/;
  1576. }
  1577. }
  1578. }
  1579. $sth->finish;
  1580. my $arap = ( $vc eq 'customer' ) ? 'ar' : 'ap';
  1581. $vc = 'vendor' unless $vc eq 'customer';
  1582. if ( $self->{id} ) {
  1583. $query = qq|
  1584. SELECT a.invnumber, a.transdate,
  1585. a.entity_id, a.datepaid, a.duedate, a.ordnumber,
  1586. a.taxincluded, a.curr AS currency, a.notes,
  1587. a.intnotes, ce.name AS $vc, a.department_id,
  1588. d.description AS department,
  1589. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1590. a.person_id, e.name AS employee,
  1591. c.language_code, a.ponumber, a.reverse
  1592. FROM $arap a
  1593. JOIN entity_credit_account c USING (entity_id)
  1594. JOIN entity ce ON (ce.id = c.entity_id)
  1595. LEFT JOIN employee er ON (er.entity_id = a.person_id)
  1596. LEFT JOIN entity e ON (er.entity_id = e.id)
  1597. LEFT JOIN department d ON (d.id = a.department_id)
  1598. WHERE a.id = ? AND c.entity_class =
  1599. (select id FROM entity_class
  1600. WHERE class ilike ?)|;
  1601. $sth = $dbh->prepare($query);
  1602. $sth->execute( $self->{id}, $self->{vc} ) || $self->dberror($query);
  1603. $ref = $sth->fetchrow_hashref('NAME_lc');
  1604. $self->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1605. foreach $key ( keys %$ref ) {
  1606. $self->{$key} = $ref->{$key};
  1607. }
  1608. $sth->finish;
  1609. # get printed, emailed
  1610. $query = qq|
  1611. SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1612. FROM status s WHERE s.trans_id = ?|;
  1613. $sth = $dbh->prepare($query);
  1614. $sth->execute( $self->{id} ) || $self->dberror($query);
  1615. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1616. $self->{printed} .= "$ref->{formname} "
  1617. if $ref->{printed};
  1618. $self->{emailed} .= "$ref->{formname} "
  1619. if $ref->{emailed};
  1620. $self->{queued} .= "$ref->{formname} " . "$ref->{spoolfile} "
  1621. if $ref->{spoolfile};
  1622. }
  1623. $sth->finish;
  1624. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1625. # get recurring
  1626. $self->get_recurring($dbh);
  1627. # get amounts from individual entries
  1628. $query = qq|
  1629. SELECT c.accno, c.description, a.source, a.amount,
  1630. a.memo, a.transdate, a.cleared, a.project_id,
  1631. p.projectnumber
  1632. FROM acc_trans a
  1633. JOIN chart c ON (c.id = a.chart_id)
  1634. LEFT JOIN project p ON (p.id = a.project_id)
  1635. WHERE a.trans_id = ?
  1636. AND a.fx_transaction = '0'
  1637. ORDER BY transdate|;
  1638. $sth = $dbh->prepare($query);
  1639. $sth->execute( $self->{id} ) || $self->dberror($query);
  1640. my $fld = ( $vc eq 'customer' ) ? 'buy' : 'sell';
  1641. $self->{exchangerate} =
  1642. $self->get_exchangerate( $dbh, $self->{currency}, $self->{transdate},
  1643. $fld );
  1644. # store amounts in {acc_trans}{$key} for multiple accounts
  1645. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1646. $ref->{exchangerate} =
  1647. $self->get_exchangerate( $dbh, $self->{currency},
  1648. $ref->{transdate}, $fld );
  1649. if ($self->{reverse}){
  1650. $ref->{amount} *= -1;
  1651. }
  1652. push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
  1653. }
  1654. $sth->finish;
  1655. }
  1656. else {
  1657. if ( !$self->{"$self->{vc}_id"} ) {
  1658. $self->lastname_used( $myconfig, $dbh, $vc, $module );
  1659. }
  1660. }
  1661. for (qw(current_date curr closedto revtrans)) {
  1662. if ($_ eq 'closedto'){
  1663. $query = qq|
  1664. SELECT value::date FROM defaults
  1665. WHERE setting_key = '$_'|;
  1666. } elsif ($_ eq 'current_date') {
  1667. $query = qq| select $_|;
  1668. } else {
  1669. $query = qq|
  1670. SELECT value FROM defaults
  1671. WHERE setting_key = '$_'|;
  1672. }
  1673. $sth = $dbh->prepare($query);
  1674. $sth->execute || $self->dberror($query);
  1675. ($val) = $sth->fetchrow_array();
  1676. if ( $_ eq 'curr' ) {
  1677. $self->{currencies} = $val;
  1678. }
  1679. else {
  1680. $self->{$_} = $val;
  1681. }
  1682. $sth->finish;
  1683. }
  1684. if (!$self->{id}){
  1685. $self->{transdate} = $self->{current_date};
  1686. }
  1687. $self->all_vc( $myconfig, $vc, $module, $dbh, $self->{transdate}, $job );
  1688. }
  1689. =item $form->lastname_used($myconfig, $dbh2, $vc, $module);
  1690. Fills the name, currency, ${vc}_id, duedate, and possibly invoice_notes
  1691. attributes of $form with the last used values for the transaction type specified
  1692. by both $vc and $form->{type}. $vc can be either 'vendor' or 'customer' and if
  1693. unspecified will take on the value given in $form->{vc}, defaulting to 'vendor'.
  1694. If $form->{type} matches /_order/, the transaction type used is order, if it
  1695. matches /_quotation/, quotations are looked through. If $form->{type} does not
  1696. match either of the above, then ar or ap transactions are used.
  1697. $myconfig, $dbh2, and $module are unused.
  1698. =cut
  1699. sub lastname_used {
  1700. my ( $self, $myconfig, $dbh2, $vc, $module ) = @_;
  1701. my $dbh = $self->{dbh};
  1702. $vc ||= $self->{vc}; # add default to correct for improper passing
  1703. my $arap;
  1704. my $where;
  1705. if ($vc eq 'customer') {
  1706. $arap = 'ar';
  1707. } else {
  1708. $arap = 'ap';
  1709. $vc = 'vendor';
  1710. }
  1711. my $sth;
  1712. if ( $self->{type} =~ /_order/ ) {
  1713. $arap = 'oe';
  1714. $where = "quotation = '0'";
  1715. }
  1716. if ( $self->{type} =~ /_quotation/ ) {
  1717. $arap = 'oe';
  1718. $where = "quotation = '1'";
  1719. }
  1720. $where = "AND $where " if $where;
  1721. my $inv_notes;
  1722. $inv_notes = "ct.invoice_notes," if $vc eq 'customer';
  1723. my $query = qq|
  1724. SELECT entity.name, ct.curr AS currency, entity_id AS ${vc}_id,
  1725. current_date + ct.terms AS duedate,
  1726. $inv_notes
  1727. ct.curr AS currency
  1728. FROM $vc ct
  1729. JOIN entity ON (ct.entity_id = entity.id)
  1730. WHERE entity.id = (select entity_id from $arap
  1731. where entity_id IS NOT NULL $where
  1732. order by id DESC limit 1)|;
  1733. $sth = $self->{dbh}->prepare($query);
  1734. $sth->execute() || $self->dberror($query);
  1735. my $ref = $sth->fetchrow_hashref('NAME_lc');
  1736. for ( keys %$ref ) { $self->{$_} = $ref->{$_} }
  1737. $sth->finish;
  1738. }
  1739. =item $form->current_date($myconfig[, $thisdate, $days]);
  1740. If $thisdate is false, get the current date from the database.
  1741. If $thisdate is true, get the date $days days from $thisdate in the date
  1742. format specified by $myconfig->{dateformat} from the database.
  1743. =cut
  1744. sub current_date {
  1745. my ( $self, $myconfig, $thisdate, $days ) = @_;
  1746. my $dbh = $self->{dbh};
  1747. my $query;
  1748. my @queryargs;
  1749. $days *= 1;
  1750. if ($thisdate) {
  1751. my $dateformat = $myconfig->{dateformat};
  1752. if ( $myconfig->{dateformat} !~ /^y/ ) {
  1753. my @a = split /\D/, $thisdate;
  1754. $dateformat .= "yy" if ( length $a[2] > 2 );
  1755. }
  1756. if ( $thisdate !~ /\D/ ) {
  1757. $dateformat = 'yyyymmdd';
  1758. }
  1759. $query = qq|SELECT (to_date(?, ?)
  1760. + ?::interval)::date AS thisdate|;
  1761. @queryargs = ( $thisdate, $dateformat, sprintf('%d days', $days) );
  1762. }
  1763. else {
  1764. $query = qq|SELECT current_date AS thisdate|;
  1765. @queryargs = ();
  1766. }
  1767. my $sth = $dbh->prepare($query);
  1768. $sth->execute(@queryargs);
  1769. my ($thisdate) = $sth->fetchrow_array;
  1770. $thisdate;
  1771. }
  1772. =item $form->like($str);
  1773. Returns '%$str%'
  1774. =cut
  1775. sub like {
  1776. my ( $self, $str ) = @_;
  1777. "%$str%";
  1778. }
  1779. =item $form->redo_rows($flds, $new, $count, $numrows);
  1780. $flds refers to a list of field names and $new refers to a list of row detail
  1781. hashes with the elements of $flds as keys as well as runningnumber for an order
  1782. or another multi-row item that normally expresses elements in the form
  1783. $form->{${fieldname}_${index}}.
  1784. For every $field in @{$flds} populates $form->{${field}_$i} with an appropriate
  1785. value from a $new detail hash where $i is an index between 1 and $count. The
  1786. ordering of the details is done in terms of the runningnumber element of the
  1787. row detail hashes in $new.
  1788. All $form attributes with names of the form ${field}_$i where the index $i is
  1789. between $count + 1 and $numrows is deleted.
  1790. =cut
  1791. sub redo_rows {
  1792. my ( $self, $flds, $new, $count, $numrows ) = @_;
  1793. my @ndx = ();
  1794. for ( 1 .. $count ) {
  1795. push @ndx, { num => $new->[ $_ - 1 ]->{runningnumber}, ndx => $_ };
  1796. }
  1797. my $i = 0;
  1798. # fill rows
  1799. foreach my $item ( sort { $a->{num} <=> $b->{num} } @ndx ) {
  1800. $i++;
  1801. my $j = $item->{ndx} - 1;
  1802. for ( @{$flds} ) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1803. }
  1804. # delete empty rows
  1805. for $i ( $count + 1 .. $numrows ) {
  1806. for ( @{$flds} ) { delete $self->{"${_}_$i"} }
  1807. }
  1808. }
  1809. =item $form->get_partsgroup($myconfig[, $p]);
  1810. Populates the list referred to as $form->{all_partsgroup}. $p refers to a hash
  1811. that describes which partsgroups to retrieve. $p->{searchitems} can be 'part',
  1812. 'service', 'assembly', 'labor', or 'nolabor' and will limit the groups to those
  1813. that contain the item type described. $p->{searchitems} and $p->{all} conflict.
  1814. If $p->{all} is set and $p->{language_code} is not, all partsgroups are
  1815. retrieved. If $p->{language_code} is set, also include the translation
  1816. description specified by $p->{language_code} for the partsgroup.
  1817. The results in $form->{all_partsgroup} are normally sorted by partsgroup name.
  1818. If a language_code is specified, the results are then sorted by the translated
  1819. description.
  1820. $myconfig is unused.
  1821. =cut
  1822. sub get_partsgroup {
  1823. my ( $self, $myconfig, $p ) = @_;
  1824. my $dbh = $self->{dbh};
  1825. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1826. FROM partsgroup pg
  1827. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1828. my $where;
  1829. my $sortorder = "partsgroup";
  1830. if ( $p->{searchitems} eq 'part' ) {
  1831. $where = qq| WHERE (p.inventory_accno_id > 0
  1832. AND p.income_accno_id > 0)|;
  1833. } elsif ( $p->{searchitems} eq 'service' ) {
  1834. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1835. } elsif ( $p->{searchitems} eq 'assembly' ) {
  1836. $where = qq| WHERE p.assembly = '1'|;
  1837. } elsif ( $p->{searchitems} eq 'labor' ) {
  1838. $where =
  1839. qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1840. } elsif ( $p->{searchitems} eq 'nolabor' ) {
  1841. $where = qq| WHERE p.income_accno_id > 0|;
  1842. }
  1843. if ( $p->{all} ) {
  1844. $query = qq|SELECT id, partsgroup
  1845. FROM partsgroup|;
  1846. }
  1847. my @queryargs = ();
  1848. if ( $p->{language_code} ) {
  1849. $sortorder = "translation";
  1850. $query = qq|
  1851. SELECT DISTINCT pg.id, pg.partsgroup,
  1852. t.description AS translation
  1853. FROM partsgroup pg
  1854. JOIN parts p ON (p.partsgroup_id = pg.id)
  1855. LEFT JOIN translation t ON (t.trans_id = pg.id
  1856. AND t.language_code = ?)|;
  1857. @queryargs = ( $p->{language_code} );
  1858. }
  1859. $query .= qq| $where ORDER BY $sortorder|;
  1860. my $sth = $dbh->prepare($query);
  1861. $sth->execute(@queryargs) || $self->dberror($query);
  1862. $self->{all_partsgroup} = ();
  1863. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1864. push @{ $self->{all_partsgroup} }, $ref;
  1865. }
  1866. $sth->finish;
  1867. }
  1868. =item $form->update_status($myconfig);
  1869. DELETEs all status rows which have a formname of $form->{formname} and a
  1870. trans_id of $form->{id}. INSERTs a new row into status where trans_id is
  1871. $form->{id}, formname is $form->{formname}, printed and emailed are true if
  1872. their respective $form attributes match /$form->{formname}/, and spoolfile is
  1873. the file extracted from the string $form->{queued} or NULL if there is no entry
  1874. for $form->{formname}.
  1875. $myconfig is unused.
  1876. =cut
  1877. sub update_status {
  1878. my ( $self, $myconfig ) = @_;
  1879. # no id return
  1880. return unless $self->{id};
  1881. my $dbh = $self->{dbh};
  1882. my %queued = split / +/, $self->{queued};
  1883. my $spoolfile =
  1884. ( $queued{ $self->{formname} } )
  1885. ? "'$queued{$self->{formname}}'"
  1886. : 'NULL';
  1887. my $query = qq|DELETE FROM status
  1888. WHERE formname = ?
  1889. AND trans_id = ?|;
  1890. my $sth = $dbh->prepare($query);
  1891. $sth->execute( $self->{formname}, $self->{id} ) || $self->dberror($query);
  1892. $sth->finish;
  1893. my $printed = ( $self->{printed} =~ /$self->{formname}/ ) ? "1" : "0";
  1894. my $emailed = ( $self->{emailed} =~ /$self->{formname}/ ) ? "1" : "0";
  1895. $query = qq|
  1896. INSERT INTO status
  1897. (trans_id, printed, emailed, spoolfile, formname)
  1898. VALUES (?, ?, ?, ?, ?)|;
  1899. $sth = $dbh->prepare($query);
  1900. $sth->execute( $self->{id}, $printed, $emailed, $spoolfile,
  1901. $self->{formname} );
  1902. $sth->finish;
  1903. }
  1904. =item $form->save_status();
  1905. Clears out any old status entries for $form->{id} and saves new status entries.
  1906. Queued form names are extracted from $form->{queued}. Printed and emailed form
  1907. names are extracted from $form->{printed} and $form->{emailed}. The queued,
  1908. printed, and emailed fields are space seperated lists.
  1909. =cut
  1910. sub save_status {
  1911. my ($self) = @_;
  1912. my $dbh = $self->{dbh};
  1913. my $formnames = $self->{printed};
  1914. my $emailforms = $self->{emailed};
  1915. my $query = qq|DELETE FROM status
  1916. WHERE trans_id = ?|;
  1917. my $sth = $dbh->prepare($query);
  1918. $sth->execute( $self->{id} );
  1919. $sth->finish;
  1920. my %queued;
  1921. my $formname;
  1922. my $printed;
  1923. my $emailed;
  1924. if ( $self->{queued} ) {
  1925. %queued = split / +/, $self->{queued};
  1926. foreach $formname ( keys %queued ) {
  1927. $printed = ( $self->{printed} =~ /$formname/ ) ? "1" : "0";
  1928. $emailed = ( $self->{emailed} =~ /$formname/ ) ? "1" : "0";
  1929. if ( $queued{$formname} ) {
  1930. $query = qq|
  1931. INSERT INTO status
  1932. (trans_id, printed, emailed,
  1933. spoolfile, formname)
  1934. VALUES (?, ?, ?, ?, ?)|;
  1935. $sth = $dbh->prepare($query);
  1936. $sth->execute( $self->{id}, $printed, $emailed,
  1937. $queued{$formname}, $formname )
  1938. || $self->dberror($query);
  1939. $sth->finish;
  1940. }
  1941. $formnames =~ s/$formname//;
  1942. $emailforms =~ s/$formname//;
  1943. }
  1944. }
  1945. # save printed, emailed info
  1946. $formnames =~ s/^ +//g;
  1947. $emailforms =~ s/^ +//g;
  1948. my %status = ();
  1949. for ( split / +/, $formnames ) { $status{$_}{printed} = 1 }
  1950. for ( split / +/, $emailforms ) { $status{$_}{emailed} = 1 }
  1951. foreach my $formname ( keys %status ) {
  1952. $printed = ( $formnames =~ /$self->{formname}/ ) ? "1" : "0";
  1953. $emailed = ( $emailforms =~ /$self->{formname}/ ) ? "1" : "0";
  1954. $query = qq|
  1955. INSERT INTO status (trans_id, printed, emailed,
  1956. formname)
  1957. VALUES (?, ?, ?, ?)|;
  1958. $sth = $dbh->prepare($query);
  1959. $sth->execute( $self->{id}, $printed, $emailed, $formname );
  1960. $sth->finish;
  1961. }
  1962. $dbh->commit;
  1963. }
  1964. =item $form->get_recurring();
  1965. Sets $form->{recurring} to contain info about the recurrence schedule for the
  1966. action $form->{id}. $form->{recurring} is of the same form used by
  1967. $form->save_recurring($dbh2, $myconfig).
  1968. reference,startdate,repeat,unit,howmany,payment,print,email,message
  1969. text date int text int int text text text
  1970. =cut
  1971. sub get_recurring {
  1972. my ($self) = @_;
  1973. my $dbh = $self->{dbh};
  1974. my $query = qq/
  1975. SELECT s.*, se.formname || ':' || se.format AS emaila,
  1976. se.message, sp.formname || ':' ||
  1977. sp.format || ':' || sp.printer AS printa
  1978. FROM recurring s
  1979. LEFT JOIN recurringemail se ON (s.id = se.id)
  1980. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  1981. WHERE s.id = ?/;
  1982. my $sth = $dbh->prepare($query);
  1983. $sth->execute( $self->{id} ) || $self->dberror($query);
  1984. for (qw(email print)) { $self->{"recurring$_"} = "" }
  1985. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1986. for ( keys %$ref ) { $self->{"recurring$_"} = $ref->{$_} }
  1987. $self->{recurringemail} .= "$ref->{emaila}:";
  1988. $self->{recurringprint} .= "$ref->{printa}:";
  1989. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  1990. }
  1991. $sth->finish;
  1992. chop $self->{recurringemail};
  1993. chop $self->{recurringprint};
  1994. if ( $self->{recurringstartdate} ) {
  1995. $self->{recurringreference} =
  1996. $self->escape( $self->{recurringreference}, 1 );
  1997. $self->{recurringmessage} =
  1998. $self->escape( $self->{recurringmessage}, 1 );
  1999. for (
  2000. qw(reference startdate repeat unit howmany
  2001. payment print email message)
  2002. )
  2003. {
  2004. $self->{recurring} .= qq|$self->{"recurring$_"},|;
  2005. }
  2006. chop $self->{recurring};
  2007. }
  2008. }
  2009. =item $form->save_recurring($dbh2, $myconfig);
  2010. Saves or deletes recurring transaction scheduling. $form->{id} is used to
  2011. determine the id used in the various recurring tables. A recurring transaction
  2012. schedule is deleted by having $form->{recurring} be false. For adding or
  2013. updating a schedule, $form->{recurring} is a comma seperated field with partial
  2014. subfield quoting of the form:
  2015. reference,startdate,repeat,unit,howmany,payment,print,email,message
  2016. text date int text int int text text text
  2017. =over
  2018. =item reference
  2019. A URI-encoded reference string for the recurrence set.
  2020. =item startdate
  2021. The index date for the recurrence.
  2022. =item repeat
  2023. The unitless repetition frequency.
  2024. =item unit
  2025. The interval unit used. Can be 'days', 'weeks', 'months', or 'years',
  2026. capitalisation and pluralisation ignored.
  2027. =item howmany
  2028. The number of recurrences for the transaction.
  2029. =item payment
  2030. Flag to indicate if a payment is included in the transaction.
  2031. =item print
  2032. A colon seperated list of formname:format:printer triplets.
  2033. =item email
  2034. A colon seperated list of formname:format pairs.
  2035. =item message
  2036. A URI-encoded message for the emails to be sent.
  2037. =back
  2038. Values for the nextdate and enddate columns of the recurring table are
  2039. calculated using startdate, repeat, unit, howmany, and the current database
  2040. date. All other fields of the recurring, recurringemail, and recurringprint are
  2041. obtained directly from $form->{recurring}.
  2042. B<WARNING>: This function does not check the validity of most subfields of
  2043. $form->{recurring}.
  2044. $dbh2 is not used.
  2045. =cut
  2046. sub save_recurring {
  2047. my ( $self, $dbh2, $myconfig ) = @_;
  2048. my $dbh = $self->{dbh};
  2049. my $query;
  2050. $query = qq|DELETE FROM recurring
  2051. WHERE id = ?|;
  2052. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2053. $sth->execute( $self->{id} ) || $self->dberror($query);
  2054. $query = qq|DELETE FROM recurringemail
  2055. WHERE id = ?|;
  2056. $sth = $dbh->prepare($query) || $self->dberror($query);
  2057. $sth->execute( $self->{id} ) || $self->dberror($query);
  2058. $query = qq|DELETE FROM recurringprint
  2059. WHERE id = ?|;
  2060. $sth = $dbh->prepare($query) || $self->dberror($query);
  2061. $sth->execute( $self->{id} ) || $self->dberror($query);
  2062. if ( $self->{recurring} ) {
  2063. my %s = ();
  2064. (
  2065. $s{reference}, $s{startdate}, $s{repeat},
  2066. $s{unit}, $s{howmany}, $s{payment},
  2067. $s{print}, $s{email}, $s{message}
  2068. ) = split /,/, $self->{recurring};
  2069. if ($s{unit} !~ /^(day|week|month|year)s?$/i){
  2070. $dbh->rollback;
  2071. $self->error("Invalid recurrence unit");
  2072. }
  2073. if ($s{howmany} == 0){
  2074. $self->error("Cannot set to recur 0 times");
  2075. }
  2076. for (qw(reference message)) { $s{$_} = $self->unescape( $s{$_} ) }
  2077. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  2078. # calculate enddate
  2079. my $advance = $s{repeat} * ( $s{howmany} - 1 );
  2080. my %interval;
  2081. $interval{'Pg'} =
  2082. "(?::date + interval '$advance $s{unit}')";
  2083. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  2084. my ($enddate) = $dbh->selectrow_array($query, undef, $s{startdate});
  2085. # calculate nextdate
  2086. $query = qq|
  2087. SELECT current_date - ?::date AS a,
  2088. ?::date - current_date AS b|;
  2089. $sth = $dbh->prepare($query) || $self->dberror($query);
  2090. $sth->execute( $s{startdate}, $enddate );
  2091. my ( $a, $b ) = $sth->fetchrow_array;
  2092. if ( $a + $b ) {
  2093. $advance =
  2094. int( ( $a / ( $a + $b ) ) * ( $s{howmany} - 1 ) + 1 ) *
  2095. $s{repeat};
  2096. }
  2097. else {
  2098. $advance = 0;
  2099. }
  2100. my $nextdate = $enddate;
  2101. if ( $advance > 0 ) {
  2102. if ( $advance < ( $s{repeat} * $s{howmany} ) ) {
  2103. $query = qq|SELECT (?::date + interval '$advance $s{unit}')|;
  2104. ($nextdate) = $dbh->selectrow_array($query, undef, $s{startdate});
  2105. }
  2106. }
  2107. else {
  2108. $nextdate = $s{startdate};
  2109. }
  2110. if ( $self->{recurringnextdate} ) {
  2111. $nextdate = $self->{recurringnextdate};
  2112. $query = qq|SELECT ?::date - ?::date|;
  2113. if ( $dbh->selectrow_array($query, undef, $enddate, $nextdate) < 0 ) {
  2114. undef $nextdate;
  2115. }
  2116. }
  2117. $self->{recurringpayment} *= 1;
  2118. $query = qq|
  2119. INSERT INTO recurring
  2120. (id, reference, startdate, enddate, nextdate,
  2121. repeat, unit, howmany, payment)
  2122. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  2123. $sth = $dbh->prepare($query);
  2124. $sth->execute(
  2125. $self->{id}, $s{reference}, $s{startdate},
  2126. $enddate, $nextdate, $s{repeat},
  2127. $s{unit}, $s{howmany}, $s{payment}
  2128. );
  2129. my @p;
  2130. my $p;
  2131. my $i;
  2132. my $sth;
  2133. if ( $s{email} ) {
  2134. # formname:format
  2135. @p = split /:/, $s{email};
  2136. $query =
  2137. qq|INSERT INTO recurringemail (id, formname, format, message)
  2138. VALUES (?, ?, ?, ?)|;
  2139. $sth = $dbh->prepare($query) || $self->dberror($query);
  2140. for ( $i = 0 ; $i <= $#p ; $i += 2 ) {
  2141. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $s{message} );
  2142. }
  2143. $sth->finish;
  2144. }
  2145. if ( $s{print} ) {
  2146. # formname:format:printer
  2147. @p = split /:/, $s{print};
  2148. $query =
  2149. qq|INSERT INTO recurringprint (id, formname, format, printer)
  2150. VALUES (?, ?, ?, ?)|;
  2151. $sth = $dbh->prepare($query) || $self->dberror($query);
  2152. for ( $i = 0 ; $i <= $#p ; $i += 3 ) {
  2153. $p = ( $p[ $i + 2 ] ) ? $p[ $i + 2 ] : "";
  2154. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $p );
  2155. }
  2156. $sth->finish;
  2157. }
  2158. }
  2159. $dbh->commit;
  2160. }
  2161. =item $form->save_intnotes($myconfig, $vc);
  2162. Sets the intnotes field of the entry in the table $vc that has the id
  2163. $form->{id} to the value of $form->{intnotes}.
  2164. Does nothing if $form->{id} is not set.
  2165. =cut
  2166. sub save_intnotes {
  2167. my ( $self, $myconfig, $vc ) = @_;
  2168. # no id return
  2169. return unless $self->{id};
  2170. my $dbh = $self->{dbh};
  2171. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  2172. my $sth = $dbh->prepare($query);
  2173. $sth->execute( $self->{intnotes}, $self->{id} ) || $self->dberror($query);
  2174. $dbh->commit;
  2175. }
  2176. =item $form->update_defaults($myconfig, $fld[, $dbh]);
  2177. Updates the defaults entry for the setting $fld following rules specified by
  2178. the existing value and returns the processed value that results. If $form is
  2179. false, such as the case when invoked as "Form::update_defaults('',...)", $dbh is
  2180. used as the handle. When $form is set, it uses $form->{dbh}, initialising the
  2181. connection if it does not yet exist. The entry $fld must exist prior to
  2182. executing this function and this update function does not handle the general
  2183. case of updating the defaults table.
  2184. B<NOTE>: rules handling is currently broken.
  2185. Rules followed by this function's processing:
  2186. =over
  2187. =item *
  2188. If digits are found in the field, increment the left-most set. This change,
  2189. unlike the others is reflected in the UPDATE.
  2190. =item *
  2191. Replace <?lsmb date ?> with the date specified in $form->{transdate} formatted
  2192. as $myconfig->{dateformat}.
  2193. =item *
  2194. Replace <?lsmb curr ?> with the value of $form->{currency}
  2195. =back
  2196. =cut
  2197. sub update_defaults {
  2198. my ( $self, $myconfig, $fld ) = @_;
  2199. if ( !$self->{dbh} && $self ) {
  2200. $self->db_init($myconfig);
  2201. }
  2202. my $dbh = $self->{dbh};
  2203. if ( !$self ) {
  2204. $dbh = $_[3];
  2205. }
  2206. my $query = qq|
  2207. SELECT value FROM defaults
  2208. WHERE setting_key = ? FOR UPDATE|;
  2209. my $sth = $dbh->prepare($query);
  2210. $sth->execute($fld);
  2211. ($_) = $sth->fetchrow_array();
  2212. $_ = "0" unless $_;
  2213. # check for and replace
  2214. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  2215. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  2216. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  2217. # <?lsmb PHONE ?> for customer and vendors
  2218. my $num = $_;
  2219. ($num) = $num =~ /(\d+)/;
  2220. if ( defined $num ) {
  2221. my $incnum;
  2222. # if we have leading zeros check how long it is
  2223. if ( $num =~ /^0/ ) {
  2224. my $l = length $num;
  2225. $incnum = $num + 1;
  2226. $l -= length $incnum;
  2227. # pad it out with zeros
  2228. my $padzero = "0" x $l;
  2229. $incnum = ( "0" x $l ) . $incnum;
  2230. }
  2231. else {
  2232. $incnum = $num + 1;
  2233. }
  2234. s/$num/$incnum/;
  2235. }
  2236. my $dbvar = $_;
  2237. my $var = $_;
  2238. my $str;
  2239. my $param;
  2240. if (/<\?lsmb /) {
  2241. while (/<\?lsmb /) {
  2242. s/<\?lsmb .*? \?>//;
  2243. last unless $&;
  2244. $param = $&;
  2245. $str = "";
  2246. if ( $param =~ /<\?lsmb date \?>/i ) {
  2247. $str = (
  2248. $self->split_date(
  2249. $myconfig->{dateformat},
  2250. $self->{transdate}
  2251. )
  2252. )[0];
  2253. $var =~ s/$param/$str/;
  2254. }
  2255. if ( $param =~
  2256. /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i
  2257. )
  2258. {
  2259. #SC: XXX hairy, undoc, possibly broken
  2260. my $fld = lc $&;
  2261. $fld =~ s/<\?lsmb //;
  2262. if ( $fld =~ /name/ ) {
  2263. if ( $self->{type} ) {
  2264. $fld = $self->{vc};
  2265. }
  2266. }
  2267. my $p = $param;
  2268. $p =~ s/(<|>|%)//g;
  2269. my @p = split / /, $p;
  2270. my @n = split / /, uc $self->{$fld};
  2271. if ( $#p > 0 ) {
  2272. for ( my $i = 1 ; $i <= $#p ; $i++ ) {
  2273. $str .= substr( $n[ $i - 1 ], 0, $p[$i] );
  2274. }
  2275. }
  2276. else {
  2277. ($str) = split /--/, $self->{$fld};
  2278. }
  2279. $var =~ s/$param/$str/;
  2280. $var =~ s/\W//g if $fld eq 'phone';
  2281. }
  2282. if ( $param =~ /<\?lsmb (yy|mm|dd)/i ) {
  2283. # SC: XXX Does this even work anymore?
  2284. my $p = $param;
  2285. $p =~ s/(<|>|%)//g;
  2286. my $spc = $p;
  2287. $spc =~ s/\w//g;
  2288. $spc = substr( $spc, 0, 1 );
  2289. my %d = ( yy => 1, mm => 2, dd => 3 );
  2290. my @p = ();
  2291. my @a = $self->split_date( $myconfig->{dateformat},
  2292. $self->{transdate} );
  2293. for ( sort keys %d ) { push @p, $a[ $d{$_} ] if ( $p =~ /$_/ ) }
  2294. $str = join $spc, @p;
  2295. $var =~ s/$param/$str/;
  2296. }
  2297. if ( $param =~ /<\?lsmb curr/i ) {
  2298. $var =~ s/$param/$self->{currency}/;
  2299. }
  2300. }
  2301. }
  2302. my $query = qq|
  2303. UPDATE defaults
  2304. SET value = ?
  2305. WHERE setting_key = ?|;
  2306. my $sth = $dbh->prepare($query);
  2307. $sth->execute( $dbvar, $fld ) || $self->dberror($query);
  2308. $dbh->commit;
  2309. $var;
  2310. }
  2311. =item $form->db_prepare_vars(var1, var2, ..., varI<n>)
  2312. Undefines $form->{varI<m>}, 1 <= I<m> <= I<n>, iff $form-<{varI<m> is both
  2313. false and not "0".
  2314. =cut
  2315. sub db_prepare_vars {
  2316. my $self = shift;
  2317. for (@_) {
  2318. if ( !$self->{$_} and $self->{$_} ne "0" ) {
  2319. undef $self->{$_};
  2320. }
  2321. }
  2322. }
  2323. =item $form->split_date($dateformat[, $date]);
  2324. Returns ($rv, $yy, $mm, $dd) for the provided $date, or the current date if no
  2325. date is provided. $rv is a seperator-free merging of the fields $yy, $mm, and
  2326. $dd in the ordering supplied by $dateformat. If the supplied $date does not
  2327. contain non-digit characters, $rv is $date and the other return values are
  2328. undefined.
  2329. $yy is two digits.
  2330. =cut
  2331. sub split_date {
  2332. my ( $self, $dateformat, $date ) = @_;
  2333. my $mm;
  2334. my $dd;
  2335. my $yy;
  2336. my $rv;
  2337. if ( !$date ) {
  2338. my @d = localtime;
  2339. $dd = $d[3];
  2340. $mm = ++$d[4];
  2341. $yy = substr( $d[5], -2 );
  2342. $mm = substr( "0$mm", -2 );
  2343. $dd = substr( "0$dd", -2 );
  2344. }
  2345. if ( $dateformat =~ /^yy/ ) {
  2346. if ($date) {
  2347. if ( $date =~ /\D/ ) {
  2348. ( $yy, $mm, $dd ) = split /\D/, $date;
  2349. $mm *= 1;
  2350. $dd *= 1;
  2351. $mm = substr( "0$mm", -2 );
  2352. $dd = substr( "0$dd", -2 );
  2353. $yy = substr( $yy, -2 );
  2354. $rv = "$yy$mm$dd";
  2355. }
  2356. else {
  2357. $rv = $date;
  2358. }
  2359. }
  2360. else {
  2361. $rv = "$yy$mm$dd";
  2362. }
  2363. }
  2364. elsif ( $dateformat =~ /^mm/ ) {
  2365. if ($date) {
  2366. if ( $date =~ /\D/ ) {
  2367. ( $mm, $dd, $yy ) = split /\D/, $date;
  2368. $mm *= 1;
  2369. $dd *= 1;
  2370. $mm = substr( "0$mm", -2 );
  2371. $dd = substr( "0$dd", -2 );
  2372. $yy = substr( $yy, -2 );
  2373. $rv = "$mm$dd$yy";
  2374. }
  2375. else {
  2376. $rv = $date;
  2377. }
  2378. }
  2379. else {
  2380. $rv = "$mm$dd$yy";
  2381. }
  2382. }
  2383. elsif ( $dateformat =~ /^dd/ ) {
  2384. if ($date) {
  2385. if ( $date =~ /\D/ ) {
  2386. ( $dd, $mm, $yy ) = split /\D/, $date;
  2387. $mm *= 1;
  2388. $dd *= 1;
  2389. $mm = substr( "0$mm", -2 );
  2390. $dd = substr( "0$dd", -2 );
  2391. $yy = substr( $yy, -2 );
  2392. $rv = "$dd$mm$yy";
  2393. }
  2394. else {
  2395. $rv = $date;
  2396. }
  2397. }
  2398. else {
  2399. $rv = "$dd$mm$yy";
  2400. }
  2401. }
  2402. ( $rv, $yy, $mm, $dd );
  2403. }
  2404. =item $form->format_date($date);
  2405. Returns $date converted from 'yyyy-mm-dd' format to the format specified by
  2406. $form->{db_dateformat}. If the supplied date does not match /^\d{4}\D/,
  2407. return the supplied date.
  2408. This function takes a four digit year and returns the date with a four digit
  2409. year.
  2410. =cut
  2411. sub format_date {
  2412. # takes an iso date in, and converts it to the date for printing
  2413. my ( $self, $date ) = @_;
  2414. my $datestring;
  2415. if ( $date =~ /^\d{4}\D/ ) { # is an ISO date
  2416. $datestring = $self->{db_dateformat};
  2417. my ( $yyyy, $mm, $dd ) = split( /\W/, $date );
  2418. $datestring =~ s/y+/$yyyy/;
  2419. $datestring =~ s/mm/$mm/;
  2420. $datestring =~ s/dd/$dd/;
  2421. }
  2422. else { # return date
  2423. $datestring = $date;
  2424. }
  2425. $datestring;
  2426. }
  2427. =item $form->from_to($yyyy, $mm[, $interval]);
  2428. Returns the date $yyyy-$mm-01 and the the last day of the month interval - 1
  2429. months from then in the form ($form->format_date(fromdate),
  2430. $form->format_date(later)). If $interval is false but defined, the later date
  2431. is the current date.
  2432. This function dies horribly when $mm + $interval > 24
  2433. =cut
  2434. sub from_to {
  2435. my ( $self, $yyyy, $mm, $interval ) = @_;
  2436. my @t;
  2437. my $dd = 1;
  2438. my $fromdate = "$yyyy-${mm}-01";
  2439. my $bd = 1;
  2440. if ( defined $interval ) {
  2441. if ( $interval == 12 ) {
  2442. $yyyy++;
  2443. }
  2444. else {
  2445. if ( ( $mm += $interval ) > 12 ) {
  2446. $mm -= 12;
  2447. $yyyy++;
  2448. }
  2449. if ( $interval == 0 ) {
  2450. @t = localtime(time);
  2451. $dd = $t[3];
  2452. $mm = $t[4] + 1;
  2453. $yyyy = $t[5] + 1900;
  2454. $bd = 0;
  2455. }
  2456. }
  2457. }
  2458. else {
  2459. if ( ++$mm > 12 ) {
  2460. $mm -= 12;
  2461. $yyyy++;
  2462. }
  2463. }
  2464. $mm--;
  2465. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yyyy ) - $bd );
  2466. $t[4]++;
  2467. $t[4] = substr( "0$t[4]", -2 );
  2468. $t[3] = substr( "0$t[3]", -2 );
  2469. $t[5] += 1900;
  2470. ( $self->format_date($fromdate), $self->format_date("$t[5]-$t[4]-$t[3]") );
  2471. }
  2472. =item $form->audittrail($dbh, $myconfig, $audittrail);
  2473. $audittrail is a hashref. If $audittrail->{id} is false, this function
  2474. retrieves the current time from the database and return a string of the form
  2475. "tablename|reference|formname|action|timestamp|" where all the values save
  2476. timestamp are taken directly from the $audittrail hashref.
  2477. If $audittrail->{id} is true but the value of audittrail in the defaults table
  2478. is '0', do nothing and return.
  2479. If $form->{audittrail} is true and $myconfig is false, $form->{audittrail} is
  2480. treated as a pipe seperated list (trailing pipe required) of the form:
  2481. table1|ref1|form1|action1|date1|...|tablen|refn|formn|actionn|daten|
  2482. All the entries described by $form->{audittrail} are inserted into the audit
  2483. table, taking on a transaction id of $audittrail->{id} and the employee id of
  2484. the calling user.
  2485. Irrespective of $form->{audittrail} and $myconfig status, this function will add
  2486. a record to the audittrail using the values contained within $audittrail,
  2487. substituting the current date if $audittrail->{transdate} is not set and the
  2488. employee id of the calling user.
  2489. =cut
  2490. sub audittrail {
  2491. my ( $self, $dbh, $myconfig, $audittrail ) = @_;
  2492. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2493. my $query;
  2494. my $rv;
  2495. my $disconnect;
  2496. if ( !$dbh ) {
  2497. $dbh = $self->{dbh};
  2498. }
  2499. my $sth;
  2500. my $query;
  2501. # if we have an id add audittrail, otherwise get a new timestamp
  2502. my @queryargs;
  2503. if ( $audittrail->{id} ) {
  2504. $query = qq|
  2505. SELECT value FROM defaults
  2506. WHERE setting_key = 'audittrail'|;
  2507. if ( $dbh->selectrow_array($query) ) {
  2508. my ( $null, $employee_id ) = $self->get_employee($dbh);
  2509. if ( $self->{audittrail} && !$myconfig ) {
  2510. chop $self->{audittrail};
  2511. my @a = split /\|/, $self->{audittrail};
  2512. my %newtrail = ();
  2513. my $key;
  2514. my $i;
  2515. my @flds = qw(tablename reference formname action transdate);
  2516. # put into hash and remove dups
  2517. while (@a) {
  2518. $key = "$a[2]$a[3]";
  2519. $i = 0;
  2520. $newtrail{$key} = { map { $_ => $a[ $i++ ] } @flds };
  2521. splice @a, 0, 5;
  2522. }
  2523. $query = qq|
  2524. INSERT INTO audittrail
  2525. (trans_id, tablename, reference,
  2526. formname, action, transdate,
  2527. employee_id)
  2528. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2529. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2530. foreach $key (
  2531. sort {
  2532. $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
  2533. } keys %newtrail
  2534. )
  2535. {
  2536. $i = 2;
  2537. $sth->bind_param( 1, $audittrail->{id} );
  2538. for (@flds) {
  2539. $sth->bind_param( $i++, $newtrail{$key}{$_} );
  2540. }
  2541. $sth->bind_param( $i++, $employee_id );
  2542. $sth->execute() || $self->dberror($query);
  2543. $sth->finish;
  2544. }
  2545. }
  2546. if ( $audittrail->{transdate} ) {
  2547. $query = qq|
  2548. INSERT INTO audittrail (
  2549. trans_id, tablename, reference,
  2550. formname, action, employee_id,
  2551. transdate)
  2552. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2553. @queryargs = (
  2554. $audittrail->{id}, $audittrail->{tablename},
  2555. $audittrail->{reference}, $audittrail->{formname},
  2556. $audittrail->{action}, $employee_id,
  2557. $audittrail->{transdate}
  2558. );
  2559. }
  2560. else {
  2561. $query = qq|
  2562. INSERT INTO audittrail
  2563. (trans_id, tablename, reference,
  2564. formname, action, employee_id)
  2565. VALUES (?, ?, ?, ?, ?, ?)|;
  2566. @queryargs = (
  2567. $audittrail->{id}, $audittrail->{tablename},
  2568. $audittrail->{reference}, $audittrail->{formname},
  2569. $audittrail->{action}, $employee_id,
  2570. );
  2571. }
  2572. $sth = $dbh->prepare($query);
  2573. $sth->execute(@queryargs) || $self->dberror($query);
  2574. }
  2575. }
  2576. else {
  2577. $query = qq|SELECT current_timestamp|;
  2578. my ($timestamp) = $dbh->selectrow_array($query);
  2579. $rv =
  2580. "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2581. }
  2582. $rv;
  2583. }
  2584. 1;
  2585. =back