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