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