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