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