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