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