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