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