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