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