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