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