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