summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: 7cceffea9413715645bbd9138736f50e7fd7dae9 (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. if ($types[$_] == 3){
  620. $arrayref->[$_] = Math::BigFloat->new($arrayref->[$_])
  621. if defined $arrayref;
  622. $hashref->{$names[$_]} = Math::BigFloat->new($hashref->{$names[$_]})
  623. if defined $hashref;
  624. }
  625. }
  626. return ($hashref || $arrayref);
  627. }
  628. =item $form->get_my_emp_num($myconfig);
  629. Function to get the employee number of the user $form->{login}. $myconfig is
  630. only used to create %myconfig. $form->{emp_num} is set to the retrieved value.
  631. This function is currently (2007-08-02) only used by pos.conf.pl.
  632. =cut
  633. sub get_my_emp_num {
  634. my ( $self, $myconfig) = @_;
  635. my %myconfig = %{$myconfig};
  636. my $dbh = $self->{dbh};
  637. # we got a connection, check the version
  638. my $query = qq|
  639. SELECT employeenumber FROM employee
  640. WHERE login = ?|;
  641. my $sth = $dbh->prepare($query);
  642. $sth->execute( $self->{login} ) || $self->dberror($query);
  643. my ($id) = $sth->fetchrow_array;
  644. $sth->finish;
  645. $self->{'emp_num'} = $id;
  646. }
  647. =item $form->format_string(@fields);
  648. Escape the values of $form selected by @fields for the format specified by
  649. $form->{format}.
  650. =cut
  651. sub format_string {
  652. my ( $self, @fields ) = @_;
  653. my $format = $self->{format};
  654. if ( $self->{format} =~ /(postscript|pdf)/ ) {
  655. $format = 'tex';
  656. }
  657. my %replace = (
  658. 'order' => {
  659. html => [ '<', '>', '\n', '\r' ],
  660. txt => [ '\n', '\r' ],
  661. tex => [
  662. quotemeta('\\'), '&', '\n', '\r',
  663. '\$', '%', '_', '#',
  664. quotemeta('^'), '{', '}', '<',
  665. '>', '£'
  666. ]
  667. },
  668. html => {
  669. '<' => '&lt;',
  670. '>' => '&gt;',
  671. '\n' => '<br />',
  672. '\r' => '<br />'
  673. },
  674. txt => { '\n' => "\n", '\r' => "\r" },
  675. tex => {
  676. '&' => '\&',
  677. '$' => '\$',
  678. '%' => '\%',
  679. '_' => '\_',
  680. '#' => '\#',
  681. quotemeta('^') => '\^\\',
  682. '{' => '\{',
  683. '}' => '\}',
  684. '<' => '$<$',
  685. '>' => '$>$',
  686. '\n' => '\newline ',
  687. '\r' => '\newline ',
  688. '£' => '\pounds ',
  689. quotemeta('\\') => '/'
  690. }
  691. );
  692. my $key;
  693. foreach $key ( @{ $replace{order}{$format} } ) {
  694. for (@fields) { $self->{$_} =~ s/$key/$replace{$format}{$key}/g }
  695. }
  696. }
  697. =item $form->datetonum($myconfig, $date[, $picture]);
  698. Converts $date from the format $myconfig->{dateformat} to the format 'yyyymmdd'.
  699. If the year extracted is only two-digits, the year given is assumed to be in the
  700. range 2000-2099.
  701. If $date does not contain any digits, datetonum does nothing.
  702. $picture is ignored.
  703. =cut
  704. sub datetonum {
  705. my ( $self, $myconfig, $date, $picture ) = @_;
  706. if ( $date && $date =~ /\D/ ) {
  707. my $yy;
  708. my $mm;
  709. my $dd;
  710. if ( $date =~ /^\d{4}-\d\d-\d\d$/ ) {
  711. ( $yy, $mm, $dd ) = split /\D/, $date;
  712. } if ( $myconfig->{dateformat} =~ /^yy/ ) {
  713. ( $yy, $mm, $dd ) = split /\D/, $date;
  714. } elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  715. ( $mm, $dd, $yy ) = split /\D/, $date;
  716. } elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  717. ( $dd, $mm, $yy ) = split /\D/, $date;
  718. }
  719. $dd *= 1;
  720. $mm *= 1;
  721. $yy += 2000 if length $yy == 2;
  722. $dd = substr( "0$dd", -2 );
  723. $mm = substr( "0$mm", -2 );
  724. $date = "$yy$mm$dd";
  725. }
  726. $date;
  727. }
  728. =item $form->add_date($myconfig, $date, $repeat, $unit);
  729. Returns the date $repeat $units from $date in the input format. $date can
  730. either be in $myconfig->{dateformat} or 'yyyymmdd' (four digit year required for
  731. this option). The valid values for $unit are 'days', 'weeks', 'months', and
  732. 'years'.
  733. This function is unreliable for $unit values other than 'days' or 'weeks' and
  734. can die horribly.
  735. =cut
  736. sub add_date {
  737. my ( $self, $myconfig, $date, $repeat, $unit ) = @_;
  738. my $diff = 0;
  739. my $spc = $myconfig->{dateformat};
  740. my $yy;
  741. my $mm;
  742. my $dd;
  743. $spc =~ s/\w//g;
  744. $spc = substr( $spc, 0, 1 );
  745. if ($date) {
  746. if ( $date =~ /\D/ ) {
  747. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  748. ( $yy, $mm, $dd ) = split /\D/, $date;
  749. }
  750. elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  751. ( $mm, $dd, $yy ) = split /\D/, $date;
  752. }
  753. elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  754. ( $dd, $mm, $yy ) = split /\D/, $date;
  755. }
  756. }
  757. else {
  758. # ISO
  759. ( $yy, $mm, $dd ) = ($date =~ /(....)(..)(..)/);
  760. }
  761. if ( $unit eq 'days' ) {
  762. $diff = $repeat * 86400;
  763. }
  764. elsif ( $unit eq 'weeks' ) {
  765. $diff = $repeat * 604800;
  766. }
  767. elsif ( $unit eq 'months' ) {
  768. $diff = $mm + $repeat;
  769. my $whole = int( $diff / 12 );
  770. $yy += $whole;
  771. $mm = ( $diff % 12 );
  772. $mm = '12' if $mm == 0;
  773. $yy-- if $mm == 12;
  774. $diff = 0;
  775. }
  776. elsif ( $unit eq 'years' ) {
  777. $yy += $repeat;
  778. }
  779. $mm--;
  780. my @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yy ) + $diff );
  781. $t[4]++;
  782. $mm = substr( "0$t[4]", -2 );
  783. $dd = substr( "0$t[3]", -2 );
  784. $yy = $t[5] + 1900;
  785. if ( $date =~ /\D/ ) {
  786. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  787. $date = "$yy$spc$mm$spc$dd";
  788. }
  789. elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  790. $date = "$mm$spc$dd$spc$yy";
  791. }
  792. elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  793. $date = "$dd$spc$mm$spc$yy";
  794. }
  795. }
  796. else {
  797. $date = "$yy$mm$dd";
  798. }
  799. }
  800. $date;
  801. }
  802. =item $form->print_button($button, $name);
  803. Outputs a submit button to STDOUT. $button is a hashref that contains data
  804. about buttons, $name is the key for the element in $button to output. Each
  805. value in $button is a reference to a hash of two elements, 'key' and 'value'.
  806. $name is the value of the button that gets sent to the server when clicked,
  807. $button->{$name}{key} is the accesskey, and $button->{$name}{value} is the label
  808. for the button.
  809. =cut
  810. sub print_button {
  811. my ( $self, $button, $name ) = @_;
  812. print
  813. 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|;
  814. }
  815. # Database routines used throughout
  816. =item $form->db_init($myconfig);
  817. Connect to the database that $myconfig is set to use and initialise the base
  818. parameters. The connection handle becomes $form->{dbh} and
  819. $form->{custom_db_fields} is populated. The connection initiated has
  820. autocommit disabled.
  821. =cut
  822. sub db_init {
  823. my ( $self, $myconfig ) = @_;
  824. # Handling of HTTP Basic Auth headers
  825. my $auth = $ENV{'HTTP_AUTHORIZATION'};
  826. $auth =~ s/Basic //i; # strip out basic authentication preface
  827. $auth = MIME::Base64::decode($auth);
  828. my ($login, $password) = split(/:/, $auth);
  829. $self->{login} = $login;
  830. if (!$self->{company}){
  831. $self->{company} = $LedgerSMB::Sysconfig::default_db;
  832. }
  833. my $dbname = $self->{company};
  834. my $dbconfig = { dbconnect => "dbi:Pg:dbname=$dbname",
  835. dbuser => $login,
  836. dbpasswd => $password
  837. };
  838. $self->{dbh} = $self->dbconnect_noauto($dbconfig) || $self->dberror();
  839. my $dbh = $self->{dbh};
  840. my %date_query = (
  841. 'mm/dd/yy' => 'set DateStyle to \'SQL, US\'',
  842. 'mm-dd-yy' => 'set DateStyle to \'POSTGRES, US\'',
  843. 'dd/mm/yy' => 'set DateStyle to \'SQL, EUROPEAN\'',
  844. 'dd-mm-yy' => 'set DateStyle to \'POSTGRES, EUROPEAN\'',
  845. 'dd.mm.yy' => 'set DateStyle to \'GERMAN\''
  846. );
  847. $self->{dbh}->do( $date_query{ $myconfig->{dateformat} } );
  848. $self->{db_dateformat} = $myconfig->{dateformat}; #shim
  849. # This is the general version check
  850. my $sth = $dbh->prepare("
  851. SELECT value FROM defaults
  852. WHERE setting_key = 'version'");
  853. $sth->execute;
  854. my ($dbversion) = $sth->fetchrow_array;
  855. if ($dbversion ne $self->{dbversion}){
  856. $self->error("Database is not the expected version.");
  857. }
  858. my $query = "SELECT t.extends,
  859. coalesce (t.table_name, 'custom_' || extends)
  860. || ':' || f.field_name as field_def
  861. FROM custom_table_catalog t
  862. JOIN custom_field_catalog f USING (table_id)";
  863. my $sth = $self->{dbh}->prepare($query);
  864. $sth->execute;
  865. my $ref;
  866. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  867. push @{ $self->{custom_db_fields}{ $ref->{extends} } },
  868. $ref->{field_def};
  869. }
  870. }
  871. =item $form->run_custom_queries($tablename, $query_type[, $linenum]);
  872. Runs queries against custom fields for the specified $query_type against
  873. $tablename.
  874. Valid values for $query_type are any casing of 'SELECT', 'INSERT', and 'UPDATE'.
  875. =cut
  876. sub run_custom_queries {
  877. my ( $self, $tablename, $query_type, $linenum ) = @_;
  878. my $dbh = $self->{dbh};
  879. if ( $query_type !~ /^(select|insert|update)$/i ) {
  880. $self->error(
  881. "Passed incorrect query type to run_custom_queries."
  882. );
  883. }
  884. my @rc;
  885. my %temphash;
  886. my @templist;
  887. my @elements;
  888. my $query;
  889. my $did_insert;
  890. my $ins_values;
  891. my $sth;
  892. if ($linenum) {
  893. $linenum = "_$linenum";
  894. }
  895. $query_type = uc($query_type);
  896. for ( @{ $self->{custom_db_fields}{$tablename} } ) {
  897. @elements = split( /:/, $_ );
  898. push @{ $temphash{ $elements[0] } }, $elements[1];
  899. }
  900. for ( keys %temphash ) {
  901. my @data;
  902. my $ins_values;
  903. $query = "$query_type ";
  904. if ( $query_type eq 'UPDATE' ) {
  905. $query = "DELETE FROM $_ WHERE row_id = ?";
  906. my $sth = $dbh->prepare($query);
  907. $sth->execute( $self->{ "id" . "$linenum" } )
  908. || $self->dberror($query);
  909. }
  910. elsif ( $query_type eq 'INSERT' ) {
  911. $query .= " INTO $_ (";
  912. }
  913. my $first = 1;
  914. for ( @{ $temphash{$_} } ) {
  915. $query .= "$_";
  916. if ( $query_type eq 'UPDATE' ) {
  917. $query .= '= ?';
  918. }
  919. $ins_values .= "?, ";
  920. $query .= ", ";
  921. $first = 0;
  922. if ( $query_type eq 'UPDATE' or $query_type eq 'INSERT' ) {
  923. push @data, $self->{"$_$linenum"};
  924. }
  925. }
  926. if ( $query_type ne 'INSERT' ) {
  927. $query =~ s/, $//;
  928. }
  929. if ( $query_type eq 'SELECT' ) {
  930. $query .= " FROM $_";
  931. }
  932. if ( $query_type eq 'SELECT' or $query_type eq 'UPDATE' ) {
  933. $query .= " WHERE row_id = ?";
  934. }
  935. if ( $query_type eq 'INSERT' ) {
  936. $query .= " row_id) VALUES ($ins_values ?)";
  937. }
  938. if ( $query_type eq 'SELECT' ) {
  939. push @rc, [$query];
  940. }
  941. else {
  942. unshift( @data, $query );
  943. push @rc, [@data];
  944. }
  945. }
  946. if ( $query_type eq 'INSERT' ) {
  947. for (@rc) {
  948. $query = shift( @{$_} );
  949. $sth = $dbh->prepare($query)
  950. || $self->db_error($query);
  951. $sth->execute( @{$_}, $self->{id} )
  952. || $self->dberror($query);
  953. $sth->finish;
  954. $did_insert = 1;
  955. }
  956. }
  957. elsif ( $query_type eq 'UPDATE' ) {
  958. @rc = $self->run_custom_queries( $tablename, 'INSERT', $linenum );
  959. }
  960. elsif ( $query_type eq 'SELECT' ) {
  961. for (@rc) {
  962. my $query = shift @{$_};
  963. my $sth = $self->{dbh}->prepare($query);
  964. $sth->execute( $self->{id} );
  965. my $ref = $sth->fetchrow_hashref('NAME_lc');
  966. for ( keys %{$ref} ) {
  967. $self->{$_} = $ref->{$_};
  968. }
  969. }
  970. }
  971. @rc;
  972. }
  973. =item $form->dbconnect($myconfig);
  974. Returns an autocommit connection to the database specified in $myconfig.
  975. =cut
  976. sub dbconnect {
  977. my ( $self, $myconfig ) = @_;
  978. # connect to database
  979. my $dbh = DBI->connect( $myconfig->{dbconnect},
  980. $myconfig->{dbuser}, $myconfig->{dbpasswd} )
  981. or $self->dberror;
  982. $dbh->{pg_enable_utf8} = 1;
  983. # set db options
  984. if ( $myconfig->{dboptions} ) {
  985. $dbh->do( $myconfig->{dboptions} )
  986. || $self->dberror( $myconfig->{dboptions} );
  987. }
  988. $dbh;
  989. }
  990. =item $form->dbconnect_noauto($myconfig);
  991. Returns a non-autocommit connection to the database specified in $myconfig.
  992. =cut
  993. sub dbconnect_noauto {
  994. my ( $self, $myconfig ) = @_;
  995. # connect to database
  996. my $dbh = DBI->connect(
  997. $myconfig->{dbconnect}, $myconfig->{dbuser},
  998. $myconfig->{dbpasswd}, { AutoCommit => 0 }
  999. ) or $self->dberror;
  1000. $dbh->{pg_enable_utf8} = 1;
  1001. # set db options
  1002. if ( $myconfig->{dboptions} ) {
  1003. $dbh->do( $myconfig->{dboptions} );
  1004. }
  1005. $dbh;
  1006. }
  1007. =item $form->dbquote($var);
  1008. If $var is an empty string, return NULL, otherwise return $var as quoted by
  1009. $form->{dbh}->quote($var).
  1010. =cut
  1011. sub dbquote {
  1012. my ( $self, $var ) = @_;
  1013. if ( $var eq '' ) {
  1014. $_ = "NULL";
  1015. }
  1016. else {
  1017. $_ = $self->{dbh}->quote($var);
  1018. }
  1019. $_;
  1020. }
  1021. =item $form->update_balance($dbh, $table, $field, $where, $value);
  1022. B<WARNING>: This is a dangerous private function. All apps calling it must be
  1023. careful to avoid SQL injection issues.
  1024. If $value is set, sets the value of $field in $table to the sum of the current
  1025. stored value and $value. In order to not annihilate the values in $table,
  1026. $where must contain a WHERE clause that limits the UPDATE to a single row.
  1027. =cut
  1028. sub update_balance {
  1029. # This is a dangerous private function. All apps calling it must
  1030. # be careful to avoid SQL injection issues
  1031. my ( $self, $dbh, $table, $field, $where, $value ) = @_;
  1032. $table = $dbh->quote_identifier($table);
  1033. $field = $dbh->quote_identifier($field);
  1034. # if we have a value, go do it
  1035. if ($value) {
  1036. # retrieve balance from table
  1037. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  1038. my ($balance) = $dbh->selectrow_array($query);
  1039. $balance = $dbh->quote($balance + $value);
  1040. # update balance
  1041. $query = "UPDATE $table SET $field = $balance WHERE $where";
  1042. $dbh->do($query) || $self->dberror($query);
  1043. }
  1044. }
  1045. =item $form->update_exchangerate($dbh, $curr, $transdate, $buy, $sell);
  1046. Updates the exchange rates $buy and $sell for the given $currency on $transdate.
  1047. If there is not yet an exchange rate for $currency on $transdate, an entry is
  1048. inserted. This returns without doing anything if $curr eq ''.
  1049. $dbh is not used, favouring $self->{dbh}.
  1050. =cut
  1051. sub update_exchangerate {
  1052. my ( $self, $dbh, $curr, $transdate, $buy, $sell ) = @_;
  1053. # some sanity check for currency
  1054. return if ( $curr eq "" );
  1055. my $query = qq|
  1056. SELECT curr
  1057. FROM exchangerate
  1058. WHERE curr = ?
  1059. AND transdate = ?
  1060. FOR UPDATE|;
  1061. my $sth = $self->{dbh}->prepare($query);
  1062. $sth->execute( $curr, $transdate ) || $self->dberror($query);
  1063. my $set;
  1064. my @queryargs;
  1065. if ( $buy && $sell ) {
  1066. $set = "buy = ?, sell = ?";
  1067. @queryargs = ( $buy, $sell );
  1068. }
  1069. elsif ($buy) {
  1070. $set = "buy = ?";
  1071. @queryargs = ($buy);
  1072. }
  1073. elsif ($sell) {
  1074. $set = "sell = ?";
  1075. @queryargs = ($sell);
  1076. }
  1077. if ( !$set ) {
  1078. $self->error("Exchange rate missing!");
  1079. }
  1080. if ( $sth->fetchrow_array ) {
  1081. $query = qq|UPDATE exchangerate
  1082. SET $set
  1083. WHERE curr = ?
  1084. AND transdate = ?|;
  1085. push( @queryargs, $curr, $transdate );
  1086. }
  1087. else {
  1088. $query = qq|
  1089. INSERT INTO exchangerate (
  1090. curr, buy, sell, transdate)
  1091. VALUES (?, ?, ?, ?)|;
  1092. @queryargs = ( $curr, $buy, $sell, $transdate );
  1093. }
  1094. $sth->finish;
  1095. $sth = $self->{dbh}->prepare($query);
  1096. $sth->execute(@queryargs) || $self->dberror($query);
  1097. }
  1098. =item $form->save_exchangerate($myconfig, $currency, $transdate, $rate, $fld);
  1099. Saves the exchange rate $rate for the given $currency on $transdate for the
  1100. provided purpose in $fld. $fld can be either 'buy' or 'sell'.
  1101. $myconfig is not used. $self->update_exchangerate is used for the majority of
  1102. the work.
  1103. =cut
  1104. sub save_exchangerate {
  1105. my ( $self, $myconfig, $currency, $transdate, $rate, $fld ) = @_;
  1106. my ( $buy, $sell ) = ( 0, 0 );
  1107. $buy = $rate if $fld eq 'buy';
  1108. $sell = $rate if $fld eq 'sell';
  1109. $self->update_exchangerate( $self->{dbh}, $currency, $transdate, $buy,
  1110. $sell );
  1111. }
  1112. =item $form->get_exchangerate($dbh, $curr, $transdate, $fld);
  1113. Returns the exchange rate in relation to the default currency for $currency on
  1114. $transdate for the purpose indicated by $fld. $fld can be either 'buy' or
  1115. 'sell' to get usable results.
  1116. $dbh is not used, favouring $self->{dbh}.
  1117. =cut
  1118. sub get_exchangerate {
  1119. my ( $self, $dbh, $curr, $transdate, $fld ) = @_;
  1120. my $exchangerate = 1;
  1121. if ($transdate) {
  1122. my $query = qq|
  1123. SELECT $fld FROM exchangerate
  1124. WHERE curr = ? AND transdate = ?|;
  1125. my $sth = $self->{dbh}->prepare($query);
  1126. $sth->execute( $curr, $transdate );
  1127. ($exchangerate) = $sth->fetchrow_array;
  1128. $exchangerate = Math::BigFloat->new($exchangerate);
  1129. $sth->finish;
  1130. }
  1131. $exchangerate;
  1132. }
  1133. =item $form->check_exchangerate($myconfig, $currency, $transdate, $fld);
  1134. Returns some true value when an entry for $currency on $transdate is true for
  1135. the purpose indicated by $fld. $fld can be either 'buy' or 'sell' to get
  1136. usable results. Returns false if $transdate is not set.
  1137. $myconfig is not used.
  1138. =cut
  1139. sub check_exchangerate {
  1140. my ( $self, $myconfig, $currency, $transdate, $fld ) = @_;
  1141. return "" unless $transdate;
  1142. my $query = qq|
  1143. SELECT $fld
  1144. FROM exchangerate
  1145. WHERE curr = ? AND transdate = ?|;
  1146. my $sth = $self->{dbh}->prepare($query);
  1147. $sth->execute( $currency, $transdate );
  1148. my ($exchangerate) = $sth->fetchrow_array;
  1149. $sth->finish;
  1150. $exchangerate;
  1151. }
  1152. =item $form->add_shipto($dbh, $id);
  1153. Inserts a new address into the table shipto if the value of any of the shipto
  1154. address components in $form differs to the regular attribute in $form. The
  1155. inserted value of trans_id is $id, the other fields correspond with the shipto
  1156. address components of $form.
  1157. $dbh is unused.
  1158. =cut
  1159. sub add_shipto {
  1160. my ( $self, $dbh, $id ) = @_;
  1161. my $shipto;
  1162. foreach my $item (
  1163. qw(name address1 address2 city state
  1164. zipcode country contact phone fax email)
  1165. )
  1166. {
  1167. if ( $self->{"shipto$item"} ne "" ) {
  1168. $shipto = 1 if ( $self->{$item} ne $self->{"shipto$item"} );
  1169. }
  1170. }
  1171. if ($shipto) {
  1172. my $query = qq|
  1173. INSERT INTO shipto
  1174. (trans_id, shiptoname, shiptoaddress1,
  1175. shiptoaddress2, shiptocity, shiptostate,
  1176. shiptozipcode, shiptocountry, shiptocontact,
  1177. shiptophone, shiptofax, shiptoemail)
  1178. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1179. |;
  1180. my $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  1181. $sth->execute(
  1182. $id, $self->{shiptoname},
  1183. $self->{shiptoaddress1}, $self->{shiptoaddress2},
  1184. $self->{shiptocity}, $self->{shiptostate},
  1185. $self->{shiptozipcode}, $self->{shiptocountry},
  1186. $self->{shiptocontact}, $self->{shiptophone},
  1187. $self->{shiptofax}, $self->{shiptoemail}
  1188. ) || $self->dberror($query);
  1189. $sth->finish;
  1190. }
  1191. }
  1192. =item $form->get_employee($dbh);
  1193. Returns a list containing the name and id of the employee $form->{login}. Any
  1194. portion of $form->{login} including and past '@' are ignored.
  1195. $dbh is unused.
  1196. =cut
  1197. sub get_employee {
  1198. my ( $self, $dbh ) = @_;
  1199. my $login = $self->{login};
  1200. $login =~ s/@.*//;
  1201. my $query = qq|
  1202. SELECT name, id
  1203. FROM entity WHERE id IN (select entity_id
  1204. FROM employee
  1205. WHERE login = ?)|;
  1206. my $sth = $self->{dbh}->prepare($query);
  1207. $sth->execute($login);
  1208. my (@a) = $sth->fetchrow_array();
  1209. $a[1] *= 1;
  1210. $sth->finish;
  1211. @a;
  1212. }
  1213. =item $form->get_name($myconfig, $table[, $transdate])
  1214. Sets $form->{name_list} to refer to a list of customers or vendors whose names
  1215. or numbers match the value found in $form->{$table} and returns the number of
  1216. matches. $table can be 'vendor', 'customer', or 'employee'; if the optional
  1217. field $transdate is provided, the result set is further limited to $table
  1218. entries which were active on the provided date as determined by the start and
  1219. end dates. The elements of $form->{name_list} are references returned rows in
  1220. hashref form and are sorted by the name field. The fields of the hash are those
  1221. of the view $table and the table entity.
  1222. $myconfig is unused.
  1223. =cut
  1224. # this sub gets the id and name from $table
  1225. sub get_name {
  1226. my ( $self, $myconfig, $table, $transdate ) = @_;
  1227. my @queryargs;
  1228. my $where;
  1229. if ($transdate) {
  1230. $where = qq|
  1231. AND (startdate IS NULL OR startdate <= ?)
  1232. AND (enddate IS NULL OR enddate >= ?)|;
  1233. @queryargs = ( $transdate, $transdate );
  1234. }
  1235. # SC: Check for valid table/view name. Other values will cause SQL errors.
  1236. if ($table !~ /^(vendor|customer|employee)$/i) {
  1237. $self->error('Invalid name source');
  1238. }
  1239. # Company name is stored in $self->{vendor} or $self->{customer}
  1240. my $name = $self->like( lc $self->{$table} );
  1241. # Vendor and Customer are now views into entity_credit_account.
  1242. my $query = qq|
  1243. SELECT * FROM $table t
  1244. JOIN entity e ON t.entity_id = e.id
  1245. WHERE (lower(e.name) LIKE ? OR t.${table}number LIKE ?)
  1246. $where
  1247. ORDER BY e.name|;
  1248. unshift( @queryargs, $name, $self->like($self->{"${table}number"}) );
  1249. my $sth = $self->{dbh}->prepare($query);
  1250. $sth->execute(@queryargs) || $self->dberror($query);
  1251. my $i = 0;
  1252. @{ $self->{name_list} } = ();
  1253. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1254. push( @{ $self->{name_list} }, $ref );
  1255. $i++;
  1256. }
  1257. $sth->finish;
  1258. return $i;
  1259. }
  1260. =item $form->all_vc($myconfig, $vc, $module, $dbh, $transdate, $job);
  1261. Populates the list referred to by $form->{all_${vc}} with hashes of either
  1262. vendor or customer id and name, ordered by the name. This will be vendor
  1263. details unless $vc is set to 'customer'. This list can be limited to only
  1264. vendors or customers which are usable on a given day by specifying $transdate.
  1265. As a further restriction, $form->{all_${vc}} will not be populated if the
  1266. number of vendors or customers that would be present in that list exceeds, or
  1267. is equal to, $myconfig->{vclimit}.
  1268. In addition to the possible population of $form->{all_${vc}},
  1269. $form->{employee_id} is looked up if not already set, the list
  1270. $form->{all_language} is populated using the language table and is sorted by the
  1271. description, and $form->all_employees, $form->all_departments,
  1272. $form->all_projects, and $form->all_taxaccounts are all run.
  1273. $module and $dbh are unused.
  1274. =cut
  1275. sub all_vc {
  1276. my ( $self, $myconfig, $vc, $module, $dbh, $transdate, $job ) = @_;
  1277. my $ref;
  1278. $dbh = $self->{dbh};
  1279. my $sth;
  1280. if ($vc eq 'customer'){
  1281. $self->{vc_class} = 2;
  1282. } else {
  1283. $self->{vc_class} = 1;
  1284. $vc = 'vendor';
  1285. }
  1286. my $query = qq|SELECT count(*) FROM entity_credit_account where entity_class = ?|;
  1287. my $where;
  1288. my @queryargs2 = ($self->{vc_class});
  1289. my @queryargs;
  1290. if ($transdate) {
  1291. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1292. AND (enddate IS NULL OR enddate >= ?)|;
  1293. $where = qq| (startdate IS NULL OR startdate <= ?)
  1294. AND (enddate IS NULL OR enddate >= ?)
  1295. AND entity_class = ?|;
  1296. push (@queryargs, $transdate, $transdate, $self->{vc_class});
  1297. push (@queryargs2, $transdate, $transdate);
  1298. } else {
  1299. $where = " true";
  1300. }
  1301. $sth = $dbh->prepare($query);
  1302. $sth->execute(@queryargs2);
  1303. my ($count) = $sth->fetchrow_array;
  1304. $sth->finish;
  1305. # build selection list
  1306. if ( $count < $myconfig->{vclimit} ) {
  1307. $self->{"${vc}_id"} *= 1;
  1308. $query = qq|SELECT id, name
  1309. FROM entity
  1310. WHERE id IN (select entity_id
  1311. FROM
  1312. entity_credit_account
  1313. WHERE
  1314. $where)
  1315. UNION
  1316. SELECT id,name
  1317. FROM entity
  1318. WHERE id = ?
  1319. ORDER BY name|;
  1320. push( @queryargs, $self->{"${vc}_id"} );
  1321. $sth = $dbh->prepare($query);
  1322. $sth->execute(@queryargs) || $self->dberror($query);
  1323. @{ $self->{"all_$vc"} } = ();
  1324. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1325. push @{ $self->{"all_$vc"} }, $ref;
  1326. }
  1327. $sth->finish;
  1328. }
  1329. # get self
  1330. if ( !$self->{employee_id} ) {
  1331. ( $self->{employee}, $self->{employee_id} ) = split /--/,
  1332. $self->{employee};
  1333. ( $self->{employee}, $self->{employee_id} ) = $self->get_employee($dbh)
  1334. unless $self->{employee_id};
  1335. }
  1336. $self->all_employees( $myconfig, $dbh, $transdate, 1 );
  1337. $self->all_departments( $myconfig, $dbh, $vc );
  1338. $self->all_projects( $myconfig, $dbh, $transdate, $job );
  1339. # get language codes
  1340. $query = qq|SELECT *
  1341. FROM language
  1342. ORDER BY 2|;
  1343. $sth = $dbh->prepare($query);
  1344. $sth->execute || $self->dberror($query);
  1345. $self->{all_language} = ();
  1346. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1347. push @{ $self->{all_language} }, $ref;
  1348. }
  1349. $sth->finish;
  1350. $self->all_taxaccounts( $myconfig, $dbh, $transdate );
  1351. }
  1352. =item $form->all_taxaccounts($myconfig, $dbh2[, $transdate]);
  1353. Get the tax rates and numbers for all the taxes in $form->{taxaccounts}. Does
  1354. nothing if $form->{taxaccounts} is false. Taxes are listed as a space seperated
  1355. list of account numbers from the chart. The retrieved values are placed within
  1356. $form->{${accno}_rate} and $form->{${accno}_taxnumber}. If $transdate is set,
  1357. then only process taxes that were valid on $transdate.
  1358. $myconfig and $dbh2 are unused.
  1359. =cut
  1360. sub all_taxaccounts {
  1361. my ( $self, $myconfig, $dbh2, $transdate ) = @_;
  1362. my $dbh = $self->{dbh};
  1363. my $sth;
  1364. my $query;
  1365. my $where;
  1366. my @queryargs = ();
  1367. if ($transdate) {
  1368. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1369. push( @queryargs, $transdate );
  1370. }
  1371. if ( $self->{taxaccounts} ) {
  1372. # rebuild tax rates
  1373. $query = qq|SELECT t.rate, t.taxnumber
  1374. FROM tax t
  1375. JOIN chart c ON (c.id = t.chart_id)
  1376. WHERE c.accno = ?
  1377. $where
  1378. ORDER BY accno, validto|;
  1379. $sth = $dbh->prepare($query) || $self->dberror($query);
  1380. foreach my $accno ( split / /, $self->{taxaccounts} ) {
  1381. $sth->execute( $accno, @queryargs );
  1382. ( $self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"} ) =
  1383. $sth->fetchrow_array;
  1384. $sth->finish;
  1385. }
  1386. }
  1387. }
  1388. =item $form->all_employees($myconfig, $dbh2, $transdate, $sales);
  1389. Sets $form->{all_employee} to be a reference to an array referencing hashes of
  1390. employee information. The hashes are of the form {'id' => id, 'name' => name}.
  1391. If $transdate is set, the query is limited to employees who are active on that
  1392. day. If $sales is true, only employees with the sales flag set are added.
  1393. $dbh2 is unused.
  1394. =cut
  1395. sub all_employees {
  1396. my ( $self, $myconfig, $dbh2, $transdate, $sales ) = @_;
  1397. my $dbh = $self->{dbh};
  1398. my @whereargs = ();
  1399. # setup employees/sales contacts
  1400. my $query = qq|
  1401. SELECT id, name
  1402. FROM entity
  1403. WHERE id IN (SELECT entity_id FROM employee
  1404. WHERE|;
  1405. if ($transdate) {
  1406. $query .= qq| (startdate IS NULL OR startdate <= ?)
  1407. AND (enddate IS NULL OR enddate >= ?) AND|;
  1408. @whereargs = ( $transdate, $transdate );
  1409. }
  1410. else {
  1411. $query .= qq| enddate IS NULL AND|;
  1412. }
  1413. if ($sales) {
  1414. $query .= qq| sales = '1' AND|;
  1415. }
  1416. $query =~ s/(WHERE|AND)$//;
  1417. $query .= qq|) ORDER BY name|;
  1418. my $sth = $dbh->prepare($query);
  1419. $sth->execute(@whereargs) || $self->dberror($query);
  1420. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1421. push @{ $self->{all_employee} }, $ref;
  1422. }
  1423. $sth->finish;
  1424. }
  1425. =item $form->all_projects($myconfig, $dbh2[, $transdate, $job]);
  1426. Populates the list referred to as $form->{all_project} with hashes detailing
  1427. all projects. If $job is true, limit the projects to those whose ids are not
  1428. also present in parts with a project_id > 0. If $transdate is set, the projects
  1429. are limited to those valid on $transdate. If $form->{language_code} is set,
  1430. include the translation description in the project list and limit to
  1431. translations with a matching language_code. The result list,
  1432. $form->{all_project}, is sorted by projectnumber.
  1433. $myconfig and $dbh2 are unused. $job appears to be part of attempted job-
  1434. costing support.
  1435. =cut
  1436. sub all_projects {
  1437. my ( $self, $myconfig, $dbh2, $transdate, $job ) = @_;
  1438. my $dbh = $self->{dbh};
  1439. my @queryargs = ();
  1440. my $where = "1 = 1";
  1441. $where = qq|id NOT IN (SELECT id
  1442. FROM parts
  1443. WHERE project_id > 0)| if !$job;
  1444. my $query = qq|SELECT *
  1445. FROM project
  1446. WHERE $where|;
  1447. if ( $self->{language_code} ) {
  1448. $query = qq|
  1449. SELECT pr.*, t.description AS translation
  1450. FROM project pr
  1451. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1452. WHERE t.language_code = ?|;
  1453. push( @queryargs, $self->{language_code} );
  1454. }
  1455. if ($transdate) {
  1456. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1457. AND (enddate IS NULL OR enddate >= ?)|;
  1458. push( @queryargs, $transdate, $transdate );
  1459. }
  1460. $query .= qq| ORDER BY projectnumber|;
  1461. my $sth = $dbh->prepare($query);
  1462. $sth->execute(@queryargs) || $self->dberror($query);
  1463. @{ $self->{all_project} } = ();
  1464. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1465. push @{ $self->{all_project} }, $ref;
  1466. }
  1467. $sth->finish;
  1468. }
  1469. =item $form->all_departments($myconfig, $dbh2, $vc);
  1470. Set $form->{all_department} to be a reference to a list of hashrefs describing
  1471. departments of the form {'id' => id, 'description' => description}. If $vc
  1472. is 'customer', further limit the results to those whose role is 'P' (Profit
  1473. Center).
  1474. This procedure is internally followed by a call to $form->all_years($myconfig).
  1475. $dbh2 is not used.
  1476. =cut
  1477. sub all_departments {
  1478. my ( $self, $myconfig, $dbh2, $vc ) = @_;
  1479. my $dbh = $self->{dbh};
  1480. my $where = "1 = 1";
  1481. if ($vc) {
  1482. if ( $vc eq 'customer' ) {
  1483. $where = " role = 'P'";
  1484. }
  1485. }
  1486. my $query = qq|SELECT id, description
  1487. FROM department
  1488. WHERE $where
  1489. ORDER BY 2|;
  1490. my $sth = $dbh->prepare($query);
  1491. $sth->execute || $self->dberror($query);
  1492. @{ $self->{all_department} } = ();
  1493. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1494. push @{ $self->{all_department} }, $ref;
  1495. }
  1496. $sth->finish;
  1497. $self->all_years($myconfig);
  1498. }
  1499. =item $form->all_languages($myconfig);
  1500. Set $form->{all_language} to be a reference to a list of hashrefs describing
  1501. languages using the form {'code' => code, 'description' => description}.
  1502. =cut
  1503. sub all_languages {
  1504. my ( $self ) = @_;
  1505. my $dbh = $self->{dbh};
  1506. my $query = qq|
  1507. SELECT code, description
  1508. FROM language
  1509. ORDER BY description|;
  1510. my $sth = $dbh->prepare($query);
  1511. $sth->execute || $self->dberror($query);
  1512. $self->{all_language} = [];
  1513. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1514. push @{ $self->{all_language} }, $ref;
  1515. }
  1516. $sth->finish;
  1517. }
  1518. =item $form->all_years($myconfig[, $dbh2]);
  1519. Populates the hash $form->{all_month} with a mapping between a two-digit month
  1520. number and the English month name. Populates the list $form->{all_years} with
  1521. the years between the year of the oldest transaction date in acc_trans and the
  1522. newest, inclusive.
  1523. $dbh2 is unused.
  1524. =cut
  1525. sub all_years {
  1526. my ( $self, $myconfig, $dbh2 ) = @_;
  1527. my $dbh = $self->{dbh};
  1528. # get years
  1529. my $query = qq|
  1530. SELECT (SELECT transdate FROM acc_trans ORDER BY transdate asc
  1531. LIMIT 1),
  1532. (SELECT transdate FROM acc_trans ORDER BY transdate desc
  1533. LIMIT 1)|;
  1534. my ( $startdate, $enddate ) = $dbh->selectrow_array($query);
  1535. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1536. ($startdate) = split /\W/, $startdate;
  1537. ($enddate) = split /\W/, $enddate;
  1538. }
  1539. else {
  1540. (@_) = split /\W/, $startdate;
  1541. $startdate = $_[2];
  1542. (@_) = split /\W/, $enddate;
  1543. $enddate = $_[2];
  1544. }
  1545. $self->{all_years} = ();
  1546. $startdate = substr( $startdate, 0, 4 );
  1547. $enddate = substr( $enddate, 0, 4 );
  1548. while ( $enddate >= $startdate ) {
  1549. push @{ $self->{all_years} }, $enddate--;
  1550. }
  1551. #this should probably be changed to use locale
  1552. %{ $self->{all_month} } = (
  1553. '01' => 'January',
  1554. '02' => 'February',
  1555. '03' => 'March',
  1556. '04' => 'April',
  1557. '05' => 'May ',
  1558. '06' => 'June',
  1559. '07' => 'July',
  1560. '08' => 'August',
  1561. '09' => 'September',
  1562. '10' => 'October',
  1563. '11' => 'November',
  1564. '12' => 'December'
  1565. );
  1566. }
  1567. =item $form->create_links($module, $myconfig, $vc[, $job]);
  1568. Populates the hash referred to as $form->{${module}_links} details about
  1569. accounts that have $module in their link field. The hash is keyed upon link
  1570. elements such as 'AP_amount' and 'AR_tax' and they refer to lists of hashes
  1571. containing accno and description for the appropriate accounts. If the key does
  1572. not contain 'tax', the account number is appended to the space seperated list
  1573. $form->{accounts}. $module is typically 'AR' or 'AP' and is the base type of
  1574. the accounts looked up.
  1575. If $form->{id} is not set, check $form->{"$form->{vc}_id"}. If neither is set,
  1576. use $form->lastname_used to populate the details. If $form->{id} is set,
  1577. populate the invnumber, transdate, ${vc}_id, datepaid, duedate, ordnumber,
  1578. taxincluded, currency, notes, intnotes, ${vc}, department_id, department,
  1579. oldinvtotal, oldtotalpaid, employee_id, employee, language_code, ponumber,
  1580. reverse, printed, emailed, queued, recurring, exchangerate, and acc_trans
  1581. attributes of $form with details about the transaction $form->{id}. All of
  1582. these attributes, save for acc_trans, are scalar; $form->{acc_trans} refers to
  1583. a hash keyed by link elements whose values are lists of references to hashes
  1584. describing acc_trans table entries corresponding to the transaction $form->{id}.
  1585. The elements in the acc_trans entry hashes are accno, description, source,
  1586. amount, memo, transdate, cleared, project_id, projectnumber, and exchangerate.
  1587. The closedto, revtrans, and currencies $form attributes are filled with values
  1588. from the defaults table, while $form->{current_date} is populated with the
  1589. current date. If $form->{id} is not set, then $form->{transdate} also takes on
  1590. the current date.
  1591. After all this, it calls $form->all_vc to conclude.
  1592. =cut
  1593. sub create_links {
  1594. my ( $self, $module, $myconfig, $vc, $job ) = @_;
  1595. # get last customers or vendors
  1596. my ( $query, $sth );
  1597. if (!$self->{dbh}) {
  1598. $self->db_init($myconfig);
  1599. }
  1600. my $dbh = $self->{dbh};
  1601. my %xkeyref = ();
  1602. my $val;
  1603. my $ref;
  1604. my $key;
  1605. # now get the account numbers
  1606. $query = qq|SELECT accno, description, link
  1607. FROM chart
  1608. WHERE link LIKE ?
  1609. ORDER BY accno|;
  1610. $sth = $dbh->prepare($query);
  1611. $sth->execute( "%" . "$module%" ) || $self->dberror($query);
  1612. $self->{accounts} = "";
  1613. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1614. foreach my $key ( split /:/, $ref->{link} ) {
  1615. if ( $key =~ /$module/ ) {
  1616. # cross reference for keys
  1617. $xkeyref{ $ref->{accno} } = $key;
  1618. push @{ $self->{"${module}_links"}{$key} },
  1619. {
  1620. accno => $ref->{accno},
  1621. description => $ref->{description}
  1622. };
  1623. $self->{accounts} .= "$ref->{accno} "
  1624. unless $key =~ /tax/;
  1625. }
  1626. }
  1627. }
  1628. $sth->finish;
  1629. my $arap = ( $vc eq 'customer' ) ? 'ar' : 'ap';
  1630. $vc = 'vendor' unless $vc eq 'customer';
  1631. if ( $self->{id} ) {
  1632. $query = qq|
  1633. SELECT a.invnumber, a.transdate,
  1634. a.entity_id, a.datepaid, a.duedate, a.ordnumber,
  1635. a.taxincluded, a.curr AS currency, a.notes,
  1636. a.intnotes, ce.name AS $vc, a.department_id,
  1637. d.description AS department,
  1638. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1639. a.person_id, e.name AS employee,
  1640. c.language_code, a.ponumber, a.reverse
  1641. FROM $arap a
  1642. JOIN entity_credit_account c USING (entity_id)
  1643. JOIN entity ce ON (ce.id = c.entity_id)
  1644. LEFT JOIN employee er ON (er.entity_id = a.person_id)
  1645. LEFT JOIN entity e ON (er.entity_id = e.id)
  1646. LEFT JOIN department d ON (d.id = a.department_id)
  1647. WHERE a.id = ? AND c.entity_class =
  1648. (select id FROM entity_class
  1649. WHERE class ilike ?)|;
  1650. $sth = $dbh->prepare($query);
  1651. $sth->execute( $self->{id}, $self->{vc} ) || $self->dberror($query);
  1652. $ref = $sth->fetchrow_hashref('NAME_lc');
  1653. $self->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1654. foreach $key ( keys %$ref ) {
  1655. $self->{$key} = $ref->{$key};
  1656. }
  1657. $sth->finish;
  1658. # get printed, emailed
  1659. $query = qq|
  1660. SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1661. FROM status s WHERE s.trans_id = ?|;
  1662. $sth = $dbh->prepare($query);
  1663. $sth->execute( $self->{id} ) || $self->dberror($query);
  1664. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1665. $self->{printed} .= "$ref->{formname} "
  1666. if $ref->{printed};
  1667. $self->{emailed} .= "$ref->{formname} "
  1668. if $ref->{emailed};
  1669. $self->{queued} .= "$ref->{formname} " . "$ref->{spoolfile} "
  1670. if $ref->{spoolfile};
  1671. }
  1672. $sth->finish;
  1673. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1674. # get recurring
  1675. $self->get_recurring($dbh);
  1676. # get amounts from individual entries
  1677. $query = qq|
  1678. SELECT c.accno, c.description, a.source, a.amount,
  1679. a.memo, a.transdate, a.cleared, a.project_id,
  1680. p.projectnumber
  1681. FROM acc_trans a
  1682. JOIN chart c ON (c.id = a.chart_id)
  1683. LEFT JOIN project p ON (p.id = a.project_id)
  1684. WHERE a.trans_id = ?
  1685. AND a.fx_transaction = '0'
  1686. ORDER BY transdate|;
  1687. $sth = $dbh->prepare($query);
  1688. $sth->execute( $self->{id} ) || $self->dberror($query);
  1689. my $fld = ( $vc eq 'customer' ) ? 'buy' : 'sell';
  1690. $self->{exchangerate} =
  1691. $self->get_exchangerate( $dbh, $self->{currency}, $self->{transdate},
  1692. $fld );
  1693. # store amounts in {acc_trans}{$key} for multiple accounts
  1694. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1695. $ref->{exchangerate} =
  1696. $self->get_exchangerate( $dbh, $self->{currency},
  1697. $ref->{transdate}, $fld );
  1698. if ($self->{reverse}){
  1699. $ref->{amount} *= -1;
  1700. }
  1701. push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
  1702. }
  1703. $sth->finish;
  1704. }
  1705. else {
  1706. if ( !$self->{"$self->{vc}_id"} ) {
  1707. $self->lastname_used( $myconfig, $dbh, $vc, $module );
  1708. }
  1709. }
  1710. for (qw(current_date curr closedto revtrans)) {
  1711. if ($_ eq 'closedto'){
  1712. $query = qq|
  1713. SELECT value::date FROM defaults
  1714. WHERE setting_key = '$_'|;
  1715. } elsif ($_ eq 'current_date') {
  1716. $query = qq| select $_|;
  1717. } else {
  1718. $query = qq|
  1719. SELECT value FROM defaults
  1720. WHERE setting_key = '$_'|;
  1721. }
  1722. $sth = $dbh->prepare($query);
  1723. $sth->execute || $self->dberror($query);
  1724. ($val) = $sth->fetchrow_array();
  1725. if ( $_ eq 'curr' ) {
  1726. $self->{currencies} = $val;
  1727. }
  1728. else {
  1729. $self->{$_} = $val;
  1730. }
  1731. $sth->finish;
  1732. }
  1733. if (!$self->{id} && !$self->{transdate}){
  1734. $self->{transdate} = $self->{current_date};
  1735. }
  1736. $self->all_vc( $myconfig, $vc, $module, $dbh, $self->{transdate}, $job );
  1737. }
  1738. =item $form->lastname_used($myconfig, $dbh2, $vc, $module);
  1739. Fills the name, currency, ${vc}_id, duedate, and possibly invoice_notes
  1740. attributes of $form with the last used values for the transaction type specified
  1741. by both $vc and $form->{type}. $vc can be either 'vendor' or 'customer' and if
  1742. unspecified will take on the value given in $form->{vc}, defaulting to 'vendor'.
  1743. If $form->{type} matches /_order/, the transaction type used is order, if it
  1744. matches /_quotation/, quotations are looked through. If $form->{type} does not
  1745. match either of the above, then ar or ap transactions are used.
  1746. $myconfig, $dbh2, and $module are unused.
  1747. =cut
  1748. sub lastname_used {
  1749. my ( $self, $myconfig, $dbh2, $vc, $module ) = @_;
  1750. my $dbh = $self->{dbh};
  1751. $vc ||= $self->{vc}; # add default to correct for improper passing
  1752. my $arap;
  1753. my $where;
  1754. if ($vc eq 'customer') {
  1755. $arap = 'ar';
  1756. } else {
  1757. $arap = 'ap';
  1758. $vc = 'vendor';
  1759. }
  1760. my $sth;
  1761. if ( $self->{type} =~ /_order/ ) {
  1762. $arap = 'oe';
  1763. $where = "quotation = '0'";
  1764. }
  1765. if ( $self->{type} =~ /_quotation/ ) {
  1766. $arap = 'oe';
  1767. $where = "quotation = '1'";
  1768. }
  1769. $where = "AND $where " if $where;
  1770. my $inv_notes;
  1771. $inv_notes = "ct.invoice_notes," if $vc eq 'customer';
  1772. my $query = qq|
  1773. SELECT entity.name, ct.curr AS currency, entity_id AS ${vc}_id,
  1774. current_date + ct.terms AS duedate,
  1775. $inv_notes
  1776. ct.curr AS currency
  1777. FROM $vc ct
  1778. JOIN entity ON (ct.entity_id = entity.id)
  1779. WHERE entity.id = (select entity_id from $arap
  1780. where entity_id IS NOT NULL $where
  1781. order by id DESC limit 1)|;
  1782. $sth = $self->{dbh}->prepare($query);
  1783. $sth->execute() || $self->dberror($query);
  1784. my $ref = $sth->fetchrow_hashref('NAME_lc');
  1785. for ( keys %$ref ) { $self->{$_} = $ref->{$_} }
  1786. $sth->finish;
  1787. }
  1788. =item $form->current_date($myconfig[, $thisdate, $days]);
  1789. If $thisdate is false, get the current date from the database.
  1790. If $thisdate is true, get the date $days days from $thisdate in the date
  1791. format specified by $myconfig->{dateformat} from the database.
  1792. =cut
  1793. sub current_date {
  1794. my ( $self, $myconfig, $thisdate, $days ) = @_;
  1795. my $dbh = $self->{dbh};
  1796. my $query;
  1797. my @queryargs;
  1798. $days *= 1;
  1799. if ($thisdate) {
  1800. my $dateformat = $myconfig->{dateformat};
  1801. if ( $myconfig->{dateformat} !~ /^y/ ) {
  1802. my @a = split /\D/, $thisdate;
  1803. $dateformat .= "yy" if ( length $a[2] > 2 );
  1804. }
  1805. if ( $thisdate !~ /\D/ ) {
  1806. $dateformat = 'yyyymmdd';
  1807. }
  1808. $query = qq|SELECT (to_date(?, ?)
  1809. + ?::interval)::date AS thisdate|;
  1810. @queryargs = ( $thisdate, $dateformat, sprintf('%d days', $days) );
  1811. }
  1812. else {
  1813. $query = qq|SELECT current_date AS thisdate|;
  1814. @queryargs = ();
  1815. }
  1816. my $sth = $dbh->prepare($query);
  1817. $sth->execute(@queryargs);
  1818. my ($thisdate) = $sth->fetchrow_array;
  1819. $thisdate;
  1820. }
  1821. =item $form->like($str);
  1822. Returns '%$str%'
  1823. =cut
  1824. sub like {
  1825. my ( $self, $str ) = @_;
  1826. "%$str%";
  1827. }
  1828. =item $form->redo_rows($flds, $new, $count, $numrows);
  1829. $flds refers to a list of field names and $new refers to a list of row detail
  1830. hashes with the elements of $flds as keys as well as runningnumber for an order
  1831. or another multi-row item that normally expresses elements in the form
  1832. $form->{${fieldname}_${index}}.
  1833. For every $field in @{$flds} populates $form->{${field}_$i} with an appropriate
  1834. value from a $new detail hash where $i is an index between 1 and $count. The
  1835. ordering of the details is done in terms of the runningnumber element of the
  1836. row detail hashes in $new.
  1837. All $form attributes with names of the form ${field}_$i where the index $i is
  1838. between $count + 1 and $numrows is deleted.
  1839. =cut
  1840. sub redo_rows {
  1841. my ( $self, $flds, $new, $count, $numrows ) = @_;
  1842. my @ndx = ();
  1843. for ( 1 .. $count ) {
  1844. push @ndx, { num => $new->[ $_ - 1 ]->{runningnumber}, ndx => $_ };
  1845. }
  1846. my $i = 0;
  1847. # fill rows
  1848. foreach my $item ( sort { $a->{num} <=> $b->{num} } @ndx ) {
  1849. $i++;
  1850. my $j = $item->{ndx} - 1;
  1851. for ( @{$flds} ) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1852. }
  1853. # delete empty rows
  1854. for $i ( $count + 1 .. $numrows ) {
  1855. for ( @{$flds} ) { delete $self->{"${_}_$i"} }
  1856. }
  1857. }
  1858. =item $form->get_partsgroup($myconfig[, $p]);
  1859. Populates the list referred to as $form->{all_partsgroup}. $p refers to a hash
  1860. that describes which partsgroups to retrieve. $p->{searchitems} can be 'part',
  1861. 'service', 'assembly', 'labor', or 'nolabor' and will limit the groups to those
  1862. that contain the item type described. $p->{searchitems} and $p->{all} conflict.
  1863. If $p->{all} is set and $p->{language_code} is not, all partsgroups are
  1864. retrieved. If $p->{language_code} is set, also include the translation
  1865. description specified by $p->{language_code} for the partsgroup.
  1866. The results in $form->{all_partsgroup} are normally sorted by partsgroup name.
  1867. If a language_code is specified, the results are then sorted by the translated
  1868. description.
  1869. $myconfig is unused.
  1870. =cut
  1871. sub get_partsgroup {
  1872. my ( $self, $myconfig, $p ) = @_;
  1873. my $dbh = $self->{dbh};
  1874. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1875. FROM partsgroup pg
  1876. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1877. my $where;
  1878. my $sortorder = "partsgroup";
  1879. if ( $p->{searchitems} eq 'part' ) {
  1880. $where = qq| WHERE (p.inventory_accno_id > 0
  1881. AND p.income_accno_id > 0)|;
  1882. } elsif ( $p->{searchitems} eq 'service' ) {
  1883. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1884. } elsif ( $p->{searchitems} eq 'assembly' ) {
  1885. $where = qq| WHERE p.assembly = '1'|;
  1886. } elsif ( $p->{searchitems} eq 'labor' ) {
  1887. $where =
  1888. qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1889. } elsif ( $p->{searchitems} eq 'nolabor' ) {
  1890. $where = qq| WHERE p.income_accno_id > 0|;
  1891. }
  1892. if ( $p->{all} ) {
  1893. $query = qq|SELECT id, partsgroup
  1894. FROM partsgroup|;
  1895. }
  1896. my @queryargs = ();
  1897. if ( $p->{language_code} ) {
  1898. $sortorder = "translation";
  1899. $query = qq|
  1900. SELECT DISTINCT pg.id, pg.partsgroup,
  1901. t.description AS translation
  1902. FROM partsgroup pg
  1903. JOIN parts p ON (p.partsgroup_id = pg.id)
  1904. LEFT JOIN translation t ON (t.trans_id = pg.id
  1905. AND t.language_code = ?)|;
  1906. @queryargs = ( $p->{language_code} );
  1907. }
  1908. $query .= qq| $where ORDER BY $sortorder|;
  1909. my $sth = $dbh->prepare($query);
  1910. $sth->execute(@queryargs) || $self->dberror($query);
  1911. $self->{all_partsgroup} = ();
  1912. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  1913. push @{ $self->{all_partsgroup} }, $ref;
  1914. }
  1915. $sth->finish;
  1916. }
  1917. =item $form->update_status($myconfig);
  1918. DELETEs all status rows which have a formname of $form->{formname} and a
  1919. trans_id of $form->{id}. INSERTs a new row into status where trans_id is
  1920. $form->{id}, formname is $form->{formname}, printed and emailed are true if
  1921. their respective $form attributes match /$form->{formname}/, and spoolfile is
  1922. the file extracted from the string $form->{queued} or NULL if there is no entry
  1923. for $form->{formname}.
  1924. $myconfig is unused.
  1925. =cut
  1926. sub update_status {
  1927. my ( $self, $myconfig ) = @_;
  1928. # no id return
  1929. return unless $self->{id};
  1930. my $dbh = $self->{dbh};
  1931. my %queued = split / +/, $self->{queued};
  1932. my $spoolfile =
  1933. ( $queued{ $self->{formname} } )
  1934. ? "'$queued{$self->{formname}}'"
  1935. : 'NULL';
  1936. my $query = qq|DELETE FROM status
  1937. WHERE formname = ?
  1938. AND trans_id = ?|;
  1939. my $sth = $dbh->prepare($query);
  1940. $sth->execute( $self->{formname}, $self->{id} ) || $self->dberror($query);
  1941. $sth->finish;
  1942. my $printed = ( $self->{printed} =~ /$self->{formname}/ ) ? "1" : "0";
  1943. my $emailed = ( $self->{emailed} =~ /$self->{formname}/ ) ? "1" : "0";
  1944. $query = qq|
  1945. INSERT INTO status
  1946. (trans_id, printed, emailed, spoolfile, formname)
  1947. VALUES (?, ?, ?, ?, ?)|;
  1948. $sth = $dbh->prepare($query);
  1949. $sth->execute( $self->{id}, $printed, $emailed, $spoolfile,
  1950. $self->{formname} );
  1951. $sth->finish;
  1952. }
  1953. =item $form->save_status();
  1954. Clears out any old status entries for $form->{id} and saves new status entries.
  1955. Queued form names are extracted from $form->{queued}. Printed and emailed form
  1956. names are extracted from $form->{printed} and $form->{emailed}. The queued,
  1957. printed, and emailed fields are space seperated lists.
  1958. =cut
  1959. sub save_status {
  1960. my ($self) = @_;
  1961. my $dbh = $self->{dbh};
  1962. my $formnames = $self->{printed};
  1963. my $emailforms = $self->{emailed};
  1964. my $query = qq|DELETE FROM status
  1965. WHERE trans_id = ?|;
  1966. my $sth = $dbh->prepare($query);
  1967. $sth->execute( $self->{id} );
  1968. $sth->finish;
  1969. my %queued;
  1970. my $formname;
  1971. my $printed;
  1972. my $emailed;
  1973. if ( $self->{queued} ) {
  1974. %queued = split / +/, $self->{queued};
  1975. foreach $formname ( keys %queued ) {
  1976. $printed = ( $self->{printed} =~ /$formname/ ) ? "1" : "0";
  1977. $emailed = ( $self->{emailed} =~ /$formname/ ) ? "1" : "0";
  1978. if ( $queued{$formname} ) {
  1979. $query = qq|
  1980. INSERT INTO status
  1981. (trans_id, printed, emailed,
  1982. spoolfile, formname)
  1983. VALUES (?, ?, ?, ?, ?)|;
  1984. $sth = $dbh->prepare($query);
  1985. $sth->execute( $self->{id}, $printed, $emailed,
  1986. $queued{$formname}, $formname )
  1987. || $self->dberror($query);
  1988. $sth->finish;
  1989. }
  1990. $formnames =~ s/$formname//;
  1991. $emailforms =~ s/$formname//;
  1992. }
  1993. }
  1994. # save printed, emailed info
  1995. $formnames =~ s/^ +//g;
  1996. $emailforms =~ s/^ +//g;
  1997. my %status = ();
  1998. for ( split / +/, $formnames ) { $status{$_}{printed} = 1 }
  1999. for ( split / +/, $emailforms ) { $status{$_}{emailed} = 1 }
  2000. foreach my $formname ( keys %status ) {
  2001. $printed = ( $formnames =~ /$self->{formname}/ ) ? "1" : "0";
  2002. $emailed = ( $emailforms =~ /$self->{formname}/ ) ? "1" : "0";
  2003. $query = qq|
  2004. INSERT INTO status (trans_id, printed, emailed,
  2005. formname)
  2006. VALUES (?, ?, ?, ?)|;
  2007. $sth = $dbh->prepare($query);
  2008. $sth->execute( $self->{id}, $printed, $emailed, $formname );
  2009. $sth->finish;
  2010. }
  2011. $dbh->commit;
  2012. }
  2013. =item $form->get_recurring();
  2014. Sets $form->{recurring} to contain info about the recurrence schedule for the
  2015. action $form->{id}. $form->{recurring} is of the same form used by
  2016. $form->save_recurring($dbh2, $myconfig).
  2017. reference,startdate,repeat,unit,howmany,payment,print,email,message
  2018. text date int text int int text text text
  2019. =cut
  2020. sub get_recurring {
  2021. my ($self) = @_;
  2022. my $dbh = $self->{dbh};
  2023. my $query = qq/
  2024. SELECT s.*, se.formname || ':' || se.format AS emaila,
  2025. se.message, sp.formname || ':' ||
  2026. sp.format || ':' || sp.printer AS printa
  2027. FROM recurring s
  2028. LEFT JOIN recurringemail se ON (s.id = se.id)
  2029. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  2030. WHERE s.id = ?/;
  2031. my $sth = $dbh->prepare($query);
  2032. $sth->execute( $self->{id} ) || $self->dberror($query);
  2033. for (qw(email print)) { $self->{"recurring$_"} = "" }
  2034. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  2035. for ( keys %$ref ) { $self->{"recurring$_"} = $ref->{$_} }
  2036. $self->{recurringemail} .= "$ref->{emaila}:";
  2037. $self->{recurringprint} .= "$ref->{printa}:";
  2038. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  2039. }
  2040. $sth->finish;
  2041. chop $self->{recurringemail};
  2042. chop $self->{recurringprint};
  2043. if ( $self->{recurringstartdate} ) {
  2044. $self->{recurringreference} =
  2045. $self->escape( $self->{recurringreference}, 1 );
  2046. $self->{recurringmessage} =
  2047. $self->escape( $self->{recurringmessage}, 1 );
  2048. for (
  2049. qw(reference startdate repeat unit howmany
  2050. payment print email message)
  2051. )
  2052. {
  2053. $self->{recurring} .= qq|$self->{"recurring$_"},|;
  2054. }
  2055. chop $self->{recurring};
  2056. }
  2057. }
  2058. =item $form->save_recurring($dbh2, $myconfig);
  2059. Saves or deletes recurring transaction scheduling. $form->{id} is used to
  2060. determine the id used in the various recurring tables. A recurring transaction
  2061. schedule is deleted by having $form->{recurring} be false. For adding or
  2062. updating a schedule, $form->{recurring} is a comma seperated field with partial
  2063. subfield quoting of the form:
  2064. reference,startdate,repeat,unit,howmany,payment,print,email,message
  2065. text date int text int int text text text
  2066. =over
  2067. =item reference
  2068. A URI-encoded reference string for the recurrence set.
  2069. =item startdate
  2070. The index date for the recurrence.
  2071. =item repeat
  2072. The unitless repetition frequency.
  2073. =item unit
  2074. The interval unit used. Can be 'days', 'weeks', 'months', or 'years',
  2075. capitalisation and pluralisation ignored.
  2076. =item howmany
  2077. The number of recurrences for the transaction.
  2078. =item payment
  2079. Flag to indicate if a payment is included in the transaction.
  2080. =item print
  2081. A colon seperated list of formname:format:printer triplets.
  2082. =item email
  2083. A colon seperated list of formname:format pairs.
  2084. =item message
  2085. A URI-encoded message for the emails to be sent.
  2086. =back
  2087. Values for the nextdate and enddate columns of the recurring table are
  2088. calculated using startdate, repeat, unit, howmany, and the current database
  2089. date. All other fields of the recurring, recurringemail, and recurringprint are
  2090. obtained directly from $form->{recurring}.
  2091. B<WARNING>: This function does not check the validity of most subfields of
  2092. $form->{recurring}.
  2093. $dbh2 is not used.
  2094. =cut
  2095. sub save_recurring {
  2096. my ( $self, $dbh2, $myconfig ) = @_;
  2097. my $dbh = $self->{dbh};
  2098. my $query;
  2099. $query = qq|DELETE FROM recurring
  2100. WHERE id = ?|;
  2101. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2102. $sth->execute( $self->{id} ) || $self->dberror($query);
  2103. $query = qq|DELETE FROM recurringemail
  2104. WHERE id = ?|;
  2105. $sth = $dbh->prepare($query) || $self->dberror($query);
  2106. $sth->execute( $self->{id} ) || $self->dberror($query);
  2107. $query = qq|DELETE FROM recurringprint
  2108. WHERE id = ?|;
  2109. $sth = $dbh->prepare($query) || $self->dberror($query);
  2110. $sth->execute( $self->{id} ) || $self->dberror($query);
  2111. if ( $self->{recurring} ) {
  2112. my %s = ();
  2113. (
  2114. $s{reference}, $s{startdate}, $s{repeat},
  2115. $s{unit}, $s{howmany}, $s{payment},
  2116. $s{print}, $s{email}, $s{message}
  2117. ) = split /,/, $self->{recurring};
  2118. if ($s{unit} !~ /^(day|week|month|year)s?$/i){
  2119. $dbh->rollback;
  2120. $self->error("Invalid recurrence unit");
  2121. }
  2122. if ($s{howmany} == 0){
  2123. $self->error("Cannot set to recur 0 times");
  2124. }
  2125. for (qw(reference message)) { $s{$_} = $self->unescape( $s{$_} ) }
  2126. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  2127. # calculate enddate
  2128. my $advance = $s{repeat} * ( $s{howmany} - 1 );
  2129. my %interval;
  2130. $interval{'Pg'} =
  2131. "(?::date + interval '$advance $s{unit}')";
  2132. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  2133. my ($enddate) = $dbh->selectrow_array($query, undef, $s{startdate});
  2134. # calculate nextdate
  2135. $query = qq|
  2136. SELECT current_date - ?::date AS a,
  2137. ?::date - current_date AS b|;
  2138. $sth = $dbh->prepare($query) || $self->dberror($query);
  2139. $sth->execute( $s{startdate}, $enddate );
  2140. my ( $a, $b ) = $sth->fetchrow_array;
  2141. if ( $a + $b ) {
  2142. $advance =
  2143. int( ( $a / ( $a + $b ) ) * ( $s{howmany} - 1 ) + 1 ) *
  2144. $s{repeat};
  2145. }
  2146. else {
  2147. $advance = 0;
  2148. }
  2149. my $nextdate = $enddate;
  2150. if ( $advance > 0 ) {
  2151. if ( $advance < ( $s{repeat} * $s{howmany} ) ) {
  2152. $query = qq|SELECT (?::date + interval '$advance $s{unit}')|;
  2153. ($nextdate) = $dbh->selectrow_array($query, undef, $s{startdate});
  2154. }
  2155. }
  2156. else {
  2157. $nextdate = $s{startdate};
  2158. }
  2159. if ( $self->{recurringnextdate} ) {
  2160. $nextdate = $self->{recurringnextdate};
  2161. $query = qq|SELECT ?::date - ?::date|;
  2162. if ( $dbh->selectrow_array($query, undef, $enddate, $nextdate) < 0 ) {
  2163. undef $nextdate;
  2164. }
  2165. }
  2166. $self->{recurringpayment} *= 1;
  2167. $query = qq|
  2168. INSERT INTO recurring
  2169. (id, reference, startdate, enddate, nextdate,
  2170. repeat, unit, howmany, payment)
  2171. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  2172. $sth = $dbh->prepare($query);
  2173. $sth->execute(
  2174. $self->{id}, $s{reference}, $s{startdate},
  2175. $enddate, $nextdate, $s{repeat},
  2176. $s{unit}, $s{howmany}, $s{payment}
  2177. );
  2178. my @p;
  2179. my $p;
  2180. my $i;
  2181. my $sth;
  2182. if ( $s{email} ) {
  2183. # formname:format
  2184. @p = split /:/, $s{email};
  2185. $query =
  2186. qq|INSERT INTO recurringemail (id, formname, format, message)
  2187. VALUES (?, ?, ?, ?)|;
  2188. $sth = $dbh->prepare($query) || $self->dberror($query);
  2189. for ( $i = 0 ; $i <= $#p ; $i += 2 ) {
  2190. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $s{message} );
  2191. }
  2192. $sth->finish;
  2193. }
  2194. if ( $s{print} ) {
  2195. # formname:format:printer
  2196. @p = split /:/, $s{print};
  2197. $query =
  2198. qq|INSERT INTO recurringprint (id, formname, format, printer)
  2199. VALUES (?, ?, ?, ?)|;
  2200. $sth = $dbh->prepare($query) || $self->dberror($query);
  2201. for ( $i = 0 ; $i <= $#p ; $i += 3 ) {
  2202. $p = ( $p[ $i + 2 ] ) ? $p[ $i + 2 ] : "";
  2203. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $p );
  2204. }
  2205. $sth->finish;
  2206. }
  2207. }
  2208. $dbh->commit;
  2209. }
  2210. =item $form->save_intnotes($myconfig, $vc);
  2211. Sets the intnotes field of the entry in the table $vc that has the id
  2212. $form->{id} to the value of $form->{intnotes}.
  2213. Does nothing if $form->{id} is not set.
  2214. =cut
  2215. sub save_intnotes {
  2216. my ( $self, $myconfig, $vc ) = @_;
  2217. # no id return
  2218. return unless $self->{id};
  2219. my $dbh = $self->{dbh};
  2220. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  2221. my $sth = $dbh->prepare($query);
  2222. $sth->execute( $self->{intnotes}, $self->{id} ) || $self->dberror($query);
  2223. $dbh->commit;
  2224. }
  2225. =item $form->update_defaults($myconfig, $fld[, $dbh]);
  2226. Updates the defaults entry for the setting $fld following rules specified by
  2227. the existing value and returns the processed value that results. If $form is
  2228. false, such as the case when invoked as "Form::update_defaults('',...)", $dbh is
  2229. used as the handle. When $form is set, it uses $form->{dbh}, initialising the
  2230. connection if it does not yet exist. The entry $fld must exist prior to
  2231. executing this function and this update function does not handle the general
  2232. case of updating the defaults table.
  2233. B<NOTE>: rules handling is currently broken.
  2234. Rules followed by this function's processing:
  2235. =over
  2236. =item *
  2237. If digits are found in the field, increment the left-most set. This change,
  2238. unlike the others is reflected in the UPDATE.
  2239. =item *
  2240. Replace <?lsmb date ?> with the date specified in $form->{transdate} formatted
  2241. as $myconfig->{dateformat}.
  2242. =item *
  2243. Replace <?lsmb curr ?> with the value of $form->{currency}
  2244. =back
  2245. =cut
  2246. sub update_defaults {
  2247. my ( $self, $myconfig, $fld ) = @_;
  2248. if ( !$self->{dbh} && $self ) {
  2249. $self->db_init($myconfig);
  2250. }
  2251. my $dbh = $self->{dbh};
  2252. if ( !$self ) {
  2253. $dbh = $_[3];
  2254. }
  2255. my $query = qq|
  2256. SELECT value FROM defaults
  2257. WHERE setting_key = ? FOR UPDATE|;
  2258. my $sth = $dbh->prepare($query);
  2259. $sth->execute($fld);
  2260. ($_) = $sth->fetchrow_array();
  2261. $_ = "0" unless $_;
  2262. # check for and replace
  2263. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  2264. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  2265. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  2266. # <?lsmb PHONE ?> for customer and vendors
  2267. my $num = $_;
  2268. ($num) = $num =~ /(\d+)/;
  2269. if ( defined $num ) {
  2270. my $incnum;
  2271. # if we have leading zeros check how long it is
  2272. if ( $num =~ /^0/ ) {
  2273. my $l = length $num;
  2274. $incnum = $num + 1;
  2275. $l -= length $incnum;
  2276. # pad it out with zeros
  2277. my $padzero = "0" x $l;
  2278. $incnum = ( "0" x $l ) . $incnum;
  2279. }
  2280. else {
  2281. $incnum = $num + 1;
  2282. }
  2283. s/$num/$incnum/;
  2284. }
  2285. my $dbvar = $_;
  2286. my $var = $_;
  2287. my $str;
  2288. my $param;
  2289. if (/<\?lsmb /) {
  2290. while (/<\?lsmb /) {
  2291. s/<\?lsmb .*? \?>//;
  2292. last unless $&;
  2293. $param = $&;
  2294. $str = "";
  2295. if ( $param =~ /<\?lsmb date \?>/i ) {
  2296. $str = (
  2297. $self->split_date(
  2298. $myconfig->{dateformat},
  2299. $self->{transdate}
  2300. )
  2301. )[0];
  2302. $var =~ s/$param/$str/;
  2303. }
  2304. if ( $param =~
  2305. /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i
  2306. )
  2307. {
  2308. #SC: XXX hairy, undoc, possibly broken
  2309. my $fld = lc $&;
  2310. $fld =~ s/<\?lsmb //;
  2311. if ( $fld =~ /name/ ) {
  2312. if ( $self->{type} ) {
  2313. $fld = $self->{vc};
  2314. }
  2315. }
  2316. my $p = $param;
  2317. $p =~ s/(<|>|%)//g;
  2318. my @p = split / /, $p;
  2319. my @n = split / /, uc $self->{$fld};
  2320. if ( $#p > 0 ) {
  2321. for ( my $i = 1 ; $i <= $#p ; $i++ ) {
  2322. $str .= substr( $n[ $i - 1 ], 0, $p[$i] );
  2323. }
  2324. }
  2325. else {
  2326. ($str) = split /--/, $self->{$fld};
  2327. }
  2328. $var =~ s/$param/$str/;
  2329. $var =~ s/\W//g if $fld eq 'phone';
  2330. }
  2331. if ( $param =~ /<\?lsmb (yy|mm|dd)/i ) {
  2332. # SC: XXX Does this even work anymore?
  2333. my $p = $param;
  2334. $p =~ s/(<|>|%)//g;
  2335. my $spc = $p;
  2336. $spc =~ s/\w//g;
  2337. $spc = substr( $spc, 0, 1 );
  2338. my %d = ( yy => 1, mm => 2, dd => 3 );
  2339. my @p = ();
  2340. my @a = $self->split_date( $myconfig->{dateformat},
  2341. $self->{transdate} );
  2342. for ( sort keys %d ) { push @p, $a[ $d{$_} ] if ( $p =~ /$_/ ) }
  2343. $str = join $spc, @p;
  2344. $var =~ s/$param/$str/;
  2345. }
  2346. if ( $param =~ /<\?lsmb curr/i ) {
  2347. $var =~ s/$param/$self->{currency}/;
  2348. }
  2349. }
  2350. }
  2351. my $query = qq|
  2352. UPDATE defaults
  2353. SET value = ?
  2354. WHERE setting_key = ?|;
  2355. my $sth = $dbh->prepare($query);
  2356. $sth->execute( $dbvar, $fld ) || $self->dberror($query);
  2357. $dbh->commit;
  2358. $var;
  2359. }
  2360. =item $form->db_prepare_vars(var1, var2, ..., varI<n>)
  2361. Undefines $form->{varI<m>}, 1 <= I<m> <= I<n>, iff $form-<{varI<m> is both
  2362. false and not "0".
  2363. =cut
  2364. sub db_prepare_vars {
  2365. my $self = shift;
  2366. for (@_) {
  2367. if ( !$self->{$_} and $self->{$_} ne "0" ) {
  2368. undef $self->{$_};
  2369. }
  2370. }
  2371. }
  2372. =item $form->split_date($dateformat[, $date]);
  2373. Returns ($rv, $yy, $mm, $dd) for the provided $date, or the current date if no
  2374. date is provided. $rv is a seperator-free merging of the fields $yy, $mm, and
  2375. $dd in the ordering supplied by $dateformat. If the supplied $date does not
  2376. contain non-digit characters, $rv is $date and the other return values are
  2377. undefined.
  2378. $yy is two digits.
  2379. =cut
  2380. sub split_date {
  2381. my ( $self, $dateformat, $date ) = @_;
  2382. my $mm;
  2383. my $dd;
  2384. my $yy;
  2385. my $rv;
  2386. if ( !$date ) {
  2387. my @d = localtime;
  2388. $dd = $d[3];
  2389. $mm = ++$d[4];
  2390. $yy = substr( $d[5], -2 );
  2391. $mm = substr( "0$mm", -2 );
  2392. $dd = substr( "0$dd", -2 );
  2393. }
  2394. if ( $dateformat =~ /^yy/ ) {
  2395. if ($date) {
  2396. if ( $date =~ /\D/ ) {
  2397. ( $yy, $mm, $dd ) = split /\D/, $date;
  2398. $mm *= 1;
  2399. $dd *= 1;
  2400. $mm = substr( "0$mm", -2 );
  2401. $dd = substr( "0$dd", -2 );
  2402. $yy = substr( $yy, -2 );
  2403. $rv = "$yy$mm$dd";
  2404. }
  2405. else {
  2406. $rv = $date;
  2407. }
  2408. }
  2409. else {
  2410. $rv = "$yy$mm$dd";
  2411. }
  2412. }
  2413. elsif ( $dateformat =~ /^mm/ ) {
  2414. if ($date) {
  2415. if ( $date =~ /\D/ ) {
  2416. ( $mm, $dd, $yy ) = split /\D/, $date;
  2417. $mm *= 1;
  2418. $dd *= 1;
  2419. $mm = substr( "0$mm", -2 );
  2420. $dd = substr( "0$dd", -2 );
  2421. $yy = substr( $yy, -2 );
  2422. $rv = "$mm$dd$yy";
  2423. }
  2424. else {
  2425. $rv = $date;
  2426. }
  2427. }
  2428. else {
  2429. $rv = "$mm$dd$yy";
  2430. }
  2431. }
  2432. elsif ( $dateformat =~ /^dd/ ) {
  2433. if ($date) {
  2434. if ( $date =~ /\D/ ) {
  2435. ( $dd, $mm, $yy ) = split /\D/, $date;
  2436. $mm *= 1;
  2437. $dd *= 1;
  2438. $mm = substr( "0$mm", -2 );
  2439. $dd = substr( "0$dd", -2 );
  2440. $yy = substr( $yy, -2 );
  2441. $rv = "$dd$mm$yy";
  2442. }
  2443. else {
  2444. $rv = $date;
  2445. }
  2446. }
  2447. else {
  2448. $rv = "$dd$mm$yy";
  2449. }
  2450. }
  2451. ( $rv, $yy, $mm, $dd );
  2452. }
  2453. =item $form->format_date($date);
  2454. Returns $date converted from 'yyyy-mm-dd' format to the format specified by
  2455. $form->{db_dateformat}. If the supplied date does not match /^\d{4}\D/,
  2456. return the supplied date.
  2457. This function takes a four digit year and returns the date with a four digit
  2458. year.
  2459. =cut
  2460. sub format_date {
  2461. # takes an iso date in, and converts it to the date for printing
  2462. my ( $self, $date ) = @_;
  2463. my $datestring;
  2464. if ( $date =~ /^\d{4}\D/ ) { # is an ISO date
  2465. $datestring = $self->{db_dateformat};
  2466. my ( $yyyy, $mm, $dd ) = split( /\W/, $date );
  2467. $datestring =~ s/y+/$yyyy/;
  2468. $datestring =~ s/mm/$mm/;
  2469. $datestring =~ s/dd/$dd/;
  2470. }
  2471. else { # return date
  2472. $datestring = $date;
  2473. }
  2474. $datestring;
  2475. }
  2476. =item $form->from_to($yyyy, $mm[, $interval]);
  2477. Returns the date $yyyy-$mm-01 and the the last day of the month interval - 1
  2478. months from then in the form ($form->format_date(fromdate),
  2479. $form->format_date(later)). If $interval is false but defined, the later date
  2480. is the current date.
  2481. This function dies horribly when $mm + $interval > 24
  2482. =cut
  2483. sub from_to {
  2484. my ( $self, $yyyy, $mm, $interval ) = @_;
  2485. my @t;
  2486. my $dd = 1;
  2487. my $fromdate = "$yyyy-${mm}-01";
  2488. my $bd = 1;
  2489. if ( defined $interval ) {
  2490. if ( $interval == 12 ) {
  2491. $yyyy++;
  2492. }
  2493. else {
  2494. if ( ( $mm += $interval ) > 12 ) {
  2495. $mm -= 12;
  2496. $yyyy++;
  2497. }
  2498. if ( $interval == 0 ) {
  2499. @t = localtime(time);
  2500. $dd = $t[3];
  2501. $mm = $t[4] + 1;
  2502. $yyyy = $t[5] + 1900;
  2503. $bd = 0;
  2504. }
  2505. }
  2506. }
  2507. else {
  2508. if ( ++$mm > 12 ) {
  2509. $mm -= 12;
  2510. $yyyy++;
  2511. }
  2512. }
  2513. $mm--;
  2514. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yyyy ) - $bd );
  2515. $t[4]++;
  2516. $t[4] = substr( "0$t[4]", -2 );
  2517. $t[3] = substr( "0$t[3]", -2 );
  2518. $t[5] += 1900;
  2519. ( $self->format_date($fromdate), $self->format_date("$t[5]-$t[4]-$t[3]") );
  2520. }
  2521. =item $form->audittrail($dbh, $myconfig, $audittrail);
  2522. $audittrail is a hashref. If $audittrail->{id} is false, this function
  2523. retrieves the current time from the database and return a string of the form
  2524. "tablename|reference|formname|action|timestamp|" where all the values save
  2525. timestamp are taken directly from the $audittrail hashref.
  2526. If $audittrail->{id} is true but the value of audittrail in the defaults table
  2527. is '0', do nothing and return.
  2528. If $form->{audittrail} is true and $myconfig is false, $form->{audittrail} is
  2529. treated as a pipe seperated list (trailing pipe required) of the form:
  2530. table1|ref1|form1|action1|date1|...|tablen|refn|formn|actionn|daten|
  2531. All the entries described by $form->{audittrail} are inserted into the audit
  2532. table, taking on a transaction id of $audittrail->{id} and the employee id of
  2533. the calling user.
  2534. Irrespective of $form->{audittrail} and $myconfig status, this function will add
  2535. a record to the audittrail using the values contained within $audittrail,
  2536. substituting the current date if $audittrail->{transdate} is not set and the
  2537. employee id of the calling user.
  2538. =cut
  2539. sub audittrail {
  2540. my ( $self, $dbh, $myconfig, $audittrail ) = @_;
  2541. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2542. my $query;
  2543. my $rv;
  2544. my $disconnect;
  2545. if ( !$dbh ) {
  2546. $dbh = $self->{dbh};
  2547. }
  2548. my $sth;
  2549. my $query;
  2550. # if we have an id add audittrail, otherwise get a new timestamp
  2551. my @queryargs;
  2552. if ( $audittrail->{id} ) {
  2553. $query = qq|
  2554. SELECT value FROM defaults
  2555. WHERE setting_key = 'audittrail'|;
  2556. if ( $dbh->selectrow_array($query) ) {
  2557. my ( $null, $employee_id ) = $self->get_employee($dbh);
  2558. if ( $self->{audittrail} && !$myconfig ) {
  2559. chop $self->{audittrail};
  2560. my @a = split /\|/, $self->{audittrail};
  2561. my %newtrail = ();
  2562. my $key;
  2563. my $i;
  2564. my @flds = qw(tablename reference formname action transdate);
  2565. # put into hash and remove dups
  2566. while (@a) {
  2567. $key = "$a[2]$a[3]";
  2568. $i = 0;
  2569. $newtrail{$key} = { map { $_ => $a[ $i++ ] } @flds };
  2570. splice @a, 0, 5;
  2571. }
  2572. $query = qq|
  2573. INSERT INTO audittrail
  2574. (trans_id, tablename, reference,
  2575. formname, action, transdate,
  2576. employee_id)
  2577. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2578. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2579. foreach $key (
  2580. sort {
  2581. $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
  2582. } keys %newtrail
  2583. )
  2584. {
  2585. $i = 2;
  2586. $sth->bind_param( 1, $audittrail->{id} );
  2587. for (@flds) {
  2588. $sth->bind_param( $i++, $newtrail{$key}{$_} );
  2589. }
  2590. $sth->bind_param( $i++, $employee_id );
  2591. $sth->execute() || $self->dberror($query);
  2592. $sth->finish;
  2593. }
  2594. }
  2595. if ( $audittrail->{transdate} ) {
  2596. $query = qq|
  2597. INSERT INTO audittrail (
  2598. trans_id, tablename, reference,
  2599. formname, action, employee_id,
  2600. transdate)
  2601. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2602. @queryargs = (
  2603. $audittrail->{id}, $audittrail->{tablename},
  2604. $audittrail->{reference}, $audittrail->{formname},
  2605. $audittrail->{action}, $employee_id,
  2606. $audittrail->{transdate}
  2607. );
  2608. }
  2609. else {
  2610. $query = qq|
  2611. INSERT INTO audittrail
  2612. (trans_id, tablename, reference,
  2613. formname, action, employee_id)
  2614. VALUES (?, ?, ?, ?, ?, ?)|;
  2615. @queryargs = (
  2616. $audittrail->{id}, $audittrail->{tablename},
  2617. $audittrail->{reference}, $audittrail->{formname},
  2618. $audittrail->{action}, $employee_id,
  2619. );
  2620. }
  2621. $sth = $dbh->prepare($query);
  2622. $sth->execute(@queryargs) || $self->dberror($query);
  2623. }
  2624. }
  2625. else {
  2626. $query = qq|SELECT current_timestamp|;
  2627. my ($timestamp) = $dbh->selectrow_array($query);
  2628. $rv =
  2629. "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2630. }
  2631. $rv;
  2632. }
  2633. 1;
  2634. =back