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