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