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