summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: e205c0de72608f5ecb8e9f47fa9ef9dd80b43de9 (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. sub callproc {
  592. my $procname = shift @_;
  593. my $argstr = "";
  594. my @results;
  595. for ( 1 .. $#_ ) {
  596. $argstr .= "?, ";
  597. }
  598. $argstr =~ s/\, $//;
  599. $query = "SELECT * FROM $procname";
  600. $query =~ s/\(\)/$argstr/;
  601. my $sth = $self->{dbh}->prepare($query);
  602. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  603. push @results, $ref;
  604. }
  605. @results;
  606. }
  607. sub get_my_emp_num {
  608. my ( $self, $myconfig, $form ) = @_;
  609. %myconfig = %{$myconfig};
  610. my $dbh = $form->{dbh};
  611. # we got a connection, check the version
  612. my $query = qq|
  613. SELECT employeenumber FROM employee
  614. WHERE login = ?|;
  615. my $sth = $dbh->prepare($query);
  616. $sth->execute( $form->{login} ) || $form->dberror($query);
  617. $sth->execute;
  618. my ($id) = $sth->fetchrow_array;
  619. $sth->finish;
  620. $form->{'emp_num'} = $id;
  621. }
  622. =item $form->format_string(@fields);
  623. Escape the values of $form selected by @fields for the format specified by
  624. $form->{format}.
  625. =cut
  626. sub format_string {
  627. my ( $self, @fields ) = @_;
  628. my $format = $self->{format};
  629. if ( $self->{format} =~ /(postscript|pdf)/ ) {
  630. $format = 'tex';
  631. }
  632. my %replace = (
  633. 'order' => {
  634. html => [ '<', '>', '\n', '\r' ],
  635. txt => [ '\n', '\r' ],
  636. tex => [
  637. quotemeta('\\'), '&', '\n', '\r',
  638. '\$', '%', '_', '#',
  639. quotemeta('^'), '{', '}', '<',
  640. '>', '£'
  641. ]
  642. },
  643. html => {
  644. '<' => '&lt;',
  645. '>' => '&gt;',
  646. '\n' => '<br />',
  647. '\r' => '<br />'
  648. },
  649. txt => { '\n' => "\n", '\r' => "\r" },
  650. tex => {
  651. '&' => '\&',
  652. '$' => '\$',
  653. '%' => '\%',
  654. '_' => '\_',
  655. '#' => '\#',
  656. quotemeta('^') => '\^\\',
  657. '{' => '\{',
  658. '}' => '\}',
  659. '<' => '$<$',
  660. '>' => '$>$',
  661. '\n' => '\newline ',
  662. '\r' => '\newline ',
  663. '£' => '\pounds ',
  664. quotemeta('\\') => '/'
  665. }
  666. );
  667. my $key;
  668. foreach $key ( @{ $replace{order}{$format} } ) {
  669. for (@fields) { $self->{$_} =~ s/$key/$replace{$format}{$key}/g }
  670. }
  671. }
  672. =item $form->datetonum($myconfig, $date[, $picture]);
  673. Converts $date from the format $myconfig->{dateformat} to the format 'yyyymmdd'.
  674. If the year extracted is only two-digits, the year given is assumed to be in the
  675. range 2000-2099.
  676. If $date does not contain any digits, datetonum does nothing.
  677. $picture is ignored.
  678. =cut
  679. sub datetonum {
  680. my ( $self, $myconfig, $date, $picture ) = @_;
  681. if ( $date && $date =~ /\D/ ) {
  682. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  683. ( $yy, $mm, $dd ) = split /\D/, $date;
  684. }
  685. elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  686. ( $mm, $dd, $yy ) = split /\D/, $date;
  687. }
  688. elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  689. ( $dd, $mm, $yy ) = split /\D/, $date;
  690. }
  691. $dd *= 1;
  692. $mm *= 1;
  693. $yy += 2000 if length $yy == 2;
  694. $dd = substr( "0$dd", -2 );
  695. $mm = substr( "0$mm", -2 );
  696. $date = "$yy$mm$dd";
  697. }
  698. $date;
  699. }
  700. =item $form->add_date($myconfig, $date, $repeat, $unit);
  701. Returns the date $repeat $units from $date in the input format. $date can
  702. either be in $myconfig->{dateformat} or 'yyyymmdd' (four digit year required for
  703. this option). The valid values for $unit are 'days', 'weeks', 'months', and
  704. 'years'.
  705. This function is unreliable for $unit values other than 'days' or 'weeks' and
  706. can die horribly.
  707. =cut
  708. sub add_date {
  709. my ( $self, $myconfig, $date, $repeat, $unit ) = @_;
  710. my $diff = 0;
  711. my $spc = $myconfig->{dateformat};
  712. my $yy;
  713. my $mm;
  714. my $dd;
  715. $spc =~ s/\w//g;
  716. $spc = substr( $spc, 0, 1 );
  717. if ($date) {
  718. if ( $date =~ /\D/ ) {
  719. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  720. ( $yy, $mm, $dd ) = split /\D/, $date;
  721. }
  722. elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  723. ( $mm, $dd, $yy ) = split /\D/, $date;
  724. }
  725. elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  726. ( $dd, $mm, $yy ) = split /\D/, $date;
  727. }
  728. }
  729. else {
  730. # ISO
  731. ( $yy, $mm, $dd ) = ($date =~ /(....)(..)(..)/);
  732. }
  733. if ( $unit eq 'days' ) {
  734. $diff = $repeat * 86400;
  735. }
  736. elsif ( $unit eq 'weeks' ) {
  737. $diff = $repeat * 604800;
  738. }
  739. elsif ( $unit eq 'months' ) {
  740. $diff = $mm + $repeat;
  741. my $whole = int( $diff / 12 );
  742. $yy += $whole;
  743. $mm = ( $diff % 12 );
  744. $mm = '12' if $mm == 0;
  745. $yy-- if $mm == 12;
  746. $diff = 0;
  747. }
  748. elsif ( $unit eq 'years' ) {
  749. $yy += $repeat;
  750. }
  751. $mm--;
  752. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yy ) + $diff );
  753. $t[4]++;
  754. $mm = substr( "0$t[4]", -2 );
  755. $dd = substr( "0$t[3]", -2 );
  756. $yy = $t[5] + 1900;
  757. if ( $date =~ /\D/ ) {
  758. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  759. $date = "$yy$spc$mm$spc$dd";
  760. }
  761. elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  762. $date = "$mm$spc$dd$spc$yy";
  763. }
  764. elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  765. $date = "$dd$spc$mm$spc$yy";
  766. }
  767. }
  768. else {
  769. $date = "$yy$mm$dd";
  770. }
  771. }
  772. $date;
  773. }
  774. =item $form->print_button($button, $name);
  775. Outputs a submit button to STDOUT. $button is a hashref that contains data
  776. about buttons, $name is the key for the element in $button to output. Each
  777. value in $button is a reference to a hash of two elements, 'key' and 'value'.
  778. $name is the value of the button that gets sent to the server when clicked,
  779. $button->{$name}{key} is the accesskey, and $button->{$name}{value} is the label
  780. for the button.
  781. =cut
  782. sub print_button {
  783. my ( $self, $button, $name ) = @_;
  784. print
  785. 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|;
  786. }
  787. # Database routines used throughout
  788. =item $form->db_init($myconfig);
  789. Connect to the database that $myconfig is set to use and initialise the base
  790. parameters. The connection handle becomes $form->{dbh} and
  791. $form->{custom_db_fields} is populated. The connection initiated has
  792. autocommit disabled.
  793. =cut
  794. sub db_init {
  795. my ( $self, $myconfig ) = @_;
  796. $self->{dbh} = $self->dbconnect_noauto($myconfig) || $self->dberror();
  797. %date_query = (
  798. 'mm/dd/yy' => 'set DateStyle to \'SQL, US\'',
  799. 'mm-dd-yy' => 'set DateStyle to \'POSTGRES, US\'',
  800. 'dd/mm/yy' => 'set DateStyle to \'SQL, EUROPEAN\'',
  801. 'dd-mm-yy' => 'set DateStyle to \'POSTGRES, EUROPEAN\'',
  802. 'dd.mm.yy' => 'set DateStyle to \'GERMAN\''
  803. );
  804. $self->{dbh}->do( $date_query{ $myconfig->{dateformat} } );
  805. $self->{db_dateformat} = $myconfig->{dateformat}; #shim
  806. my $query = "SELECT t.extends,
  807. coalesce (t.table_name, 'custom_' || extends)
  808. || ':' || f.field_name as field_def
  809. FROM custom_table_catalog t
  810. JOIN custom_field_catalog f USING (table_id)";
  811. my $sth = $self->{dbh}->prepare($query);
  812. $sth->execute;
  813. my $ref;
  814. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  815. push @{ $self->{custom_db_fields}{ $ref->{extends} } },
  816. $ref->{field_def};
  817. }
  818. }
  819. sub run_custom_queries {
  820. my ( $self, $tablename, $query_type, $linenum ) = @_;
  821. my $dbh = $self->{dbh};
  822. if ( $query_type !~ /^(select|insert|update)$/i ) {
  823. $self->error(
  824. $locale->text(
  825. "Passed incorrect query type to run_custom_queries."
  826. )
  827. );
  828. }
  829. my @rc;
  830. my %temphash;
  831. my @templist;
  832. my @elements;
  833. my $query;
  834. my $ins_values;
  835. if ($linenum) {
  836. $linenum = "_$linenum";
  837. }
  838. $query_type = uc($query_type);
  839. for ( @{ $self->{custom_db_fields}{$tablename} } ) {
  840. @elements = split( /:/, $_ );
  841. push @{ $temphash{ $elements[0] } }, $elements[1];
  842. }
  843. for ( keys %temphash ) {
  844. my @data;
  845. my $ins_values;
  846. $query = "$query_type ";
  847. if ( $query_type eq 'UPDATE' ) {
  848. $query = "DELETE FROM $_ WHERE row_id = ?";
  849. my $sth = $dbh->prepare($query);
  850. $sth->execute( $self->{ "id" . "$linenum" } )
  851. || $self->dberror($query);
  852. }
  853. elsif ( $query_type eq 'INSERT' ) {
  854. $query .= " INTO $_ (";
  855. }
  856. my $first = 1;
  857. for ( @{ $temphash{$_} } ) {
  858. $query .= "$_";
  859. if ( $query_type eq 'UPDATE' ) {
  860. $query .= '= ?';
  861. }
  862. $ins_values .= "?, ";
  863. $query .= ", ";
  864. $first = 0;
  865. if ( $query_type eq 'UPDATE' or $query_type eq 'INSERT' ) {
  866. push @data, $self->{"$_$linenum"};
  867. }
  868. }
  869. if ( $query_type ne 'INSERT' ) {
  870. $query =~ s/, $//;
  871. }
  872. if ( $query_type eq 'SELECT' ) {
  873. $query .= " FROM $_";
  874. }
  875. if ( $query_type eq 'SELECT' or $query_type eq 'UPDATE' ) {
  876. $query .= " WHERE row_id = ?";
  877. }
  878. if ( $query_type eq 'INSERT' ) {
  879. $query .= " row_id) VALUES ($ins_values ?)";
  880. }
  881. if ( $query_type eq 'SELECT' ) {
  882. push @rc, [$query];
  883. }
  884. else {
  885. unshift( @data, $query );
  886. push @rc, [@data];
  887. }
  888. }
  889. if ( $query_type eq 'INSERT' ) {
  890. for (@rc) {
  891. $query = shift( @{$_} );
  892. $sth = $dbh->prepare($query)
  893. || $self->db_error($query);
  894. $sth->execute( @{$_}, $self->{id} )
  895. || $self->dberror($query);
  896. $sth->finish;
  897. $did_insert = 1;
  898. }
  899. }
  900. elsif ( $query_type eq 'UPDATE' ) {
  901. @rc = $self->run_custom_queries( $tablename, 'INSERT', $linenum );
  902. }
  903. elsif ( $query_type eq 'SELECT' ) {
  904. for (@rc) {
  905. $query = shift @{$_};
  906. $sth = $self->{dbh}->prepare($query);
  907. $sth->execute( $self->{id} );
  908. $ref = $sth->fetchrow_hashref(NAME_lc);
  909. for ( keys %{$ref} ) {
  910. $self->{$_} = $ref->{$_};
  911. }
  912. }
  913. }
  914. @rc;
  915. }
  916. =item $form->dbconnect($myconfig);
  917. Returns an autocommit connection to the database specified in $myconfig.
  918. =cut
  919. sub dbconnect {
  920. my ( $self, $myconfig ) = @_;
  921. # connect to database
  922. my $dbh = DBI->connect( $myconfig->{dbconnect},
  923. $myconfig->{dbuser}, $myconfig->{dbpasswd} )
  924. or $self->dberror;
  925. $dbh->{pg_enable_utf8} = 1;
  926. # set db options
  927. if ( $myconfig->{dboptions} ) {
  928. $dbh->do( $myconfig->{dboptions} )
  929. || $self->dberror( $myconfig->{dboptions} );
  930. }
  931. $dbh;
  932. }
  933. =item $form->dbconnect_noauto($myconfig);
  934. Returns a non-autocommit connection to the database specified in $myconfig.
  935. =cut
  936. sub dbconnect_noauto {
  937. my ( $self, $myconfig ) = @_;
  938. # connect to database
  939. $dbh = DBI->connect(
  940. $myconfig->{dbconnect}, $myconfig->{dbuser},
  941. $myconfig->{dbpasswd}, { AutoCommit => 0 }
  942. ) or $self->dberror;
  943. $dbh->{pg_enable_utf8} = 1;
  944. # set db options
  945. if ( $myconfig->{dboptions} ) {
  946. $dbh->do( $myconfig->{dboptions} );
  947. }
  948. $dbh;
  949. }
  950. =item $form->dbquote($var);
  951. If $var is an empty string, return NULL, otherwise return $var as quoted by
  952. $form->{dbh}->quote($var).
  953. =cut
  954. sub dbquote {
  955. my ( $self, $var ) = @_;
  956. if ( $var eq '' ) {
  957. $_ = "NULL";
  958. }
  959. else {
  960. $_ = $self->{dbh}->quote($var);
  961. }
  962. $_;
  963. }
  964. sub update_balance {
  965. # This is a dangerous private function. All apps calling it must
  966. # be careful to avoid SQL injection issues
  967. my ( $self, $dbh, $table, $field, $where, $value ) = @_;
  968. # if we have a value, go do it
  969. if ($value) {
  970. # retrieve balance from table
  971. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  972. my ($balance) = $dbh->selectrow_array($query);
  973. $balance += $value;
  974. # update balance
  975. $query = "UPDATE $table SET $field = $balance WHERE $where";
  976. $dbh->do($query) || $self->dberror($query);
  977. }
  978. }
  979. =item $form->update_exchangerate($dbh, $curr, $transdate, $buy, $sell);
  980. Updates the exchange rates $buy and $sell for the given $currency on $transdate.
  981. If there is not yet an exchange rate for $currency on $transdate, an entry is
  982. inserted. This returns without doing anything if $curr eq ''.
  983. $dbh is not used, favouring $self->{dbh}.
  984. =cut
  985. sub update_exchangerate {
  986. my ( $self, $dbh, $curr, $transdate, $buy, $sell ) = @_;
  987. # some sanity check for currency
  988. return if ( $curr eq "" );
  989. my $query = qq|
  990. SELECT curr
  991. FROM exchangerate
  992. WHERE curr = ?
  993. AND transdate = ?
  994. FOR UPDATE|;
  995. my $sth = $self->{dbh}->prepare($query);
  996. $sth->execute( $curr, $transdate ) || $self->dberror($query);
  997. my $set;
  998. my @queryargs;
  999. if ( $buy && $sell ) {
  1000. $set = "buy = ?, sell = ?";
  1001. @queryargs = ( $buy, $sell );
  1002. }
  1003. elsif ($buy) {
  1004. $set = "buy = ?";
  1005. @queryargs = ($buy);
  1006. }
  1007. elsif ($sell) {
  1008. $set = "sell = ?";
  1009. @queryargs = ($sell);
  1010. }
  1011. if ( !$set ) {
  1012. $self->error("Exchange rate missing!");
  1013. }
  1014. if ( $sth->fetchrow_array ) {
  1015. $query = qq|UPDATE exchangerate
  1016. SET $set
  1017. WHERE curr = ?
  1018. AND transdate = ?|;
  1019. push( @queryargs, $curr, $transdate );
  1020. }
  1021. else {
  1022. $query = qq|
  1023. INSERT INTO exchangerate (
  1024. curr, buy, sell, transdate)
  1025. VALUES (?, ?, ?, ?)|;
  1026. @queryargs = ( $curr, $buy, $sell, $transdate );
  1027. }
  1028. $sth->finish;
  1029. $sth = $self->{dbh}->prepare($query);
  1030. $sth->execute(@queryargs) || $self->dberror($query);
  1031. }
  1032. =item $form->save_exchangerate($myconfig, $currency, $transdate, $rate, $fld);
  1033. Saves the exchange rate $rate for the given $currency on $transdate for the
  1034. provided purpose in $fld. $fld can be either 'buy' or 'sell'.
  1035. $myconfig is not used. $self->update_exchangerate is used for the majority of
  1036. the work.
  1037. =cut
  1038. sub save_exchangerate {
  1039. my ( $self, $myconfig, $currency, $transdate, $rate, $fld ) = @_;
  1040. my ( $buy, $sell ) = ( 0, 0 );
  1041. $buy = $rate if $fld eq 'buy';
  1042. $sell = $rate if $fld eq 'sell';
  1043. $self->update_exchangerate( $self->{dbh}, $currency, $transdate, $buy,
  1044. $sell );
  1045. }
  1046. =item $form->get_exchangerate($dbh, $curr, $transdate, $fld);
  1047. Returns the exchange rate in relation to the default currency for $currency on
  1048. $transdate for the purpose indicated by $fld. $fld can be either 'buy' or
  1049. 'sell' to get usable results.
  1050. $dbh is not used, favouring $self->{dbh}.
  1051. =cut
  1052. sub get_exchangerate {
  1053. my ( $self, $dbh, $curr, $transdate, $fld ) = @_;
  1054. my $exchangerate = 1;
  1055. if ($transdate) {
  1056. my $query = qq|
  1057. SELECT $fld FROM exchangerate
  1058. WHERE curr = ? AND transdate = ?|;
  1059. $sth = $self->{dbh}->prepare($query);
  1060. $sth->execute( $curr, $transdate );
  1061. ($exchangerate) = $sth->fetchrow_array;
  1062. $exchangerate = Math::BigFloat->new($exchangerate);
  1063. }
  1064. $sth->finish;
  1065. $exchangerate;
  1066. }
  1067. =item $form->check_exchangerate($myconfig, $currency, $transdate, $fld);
  1068. Returns some true value when an entry for $currency on $transdate is true for
  1069. the purpose indicated by $fld. $fld can be either 'buy' or 'sell' to get
  1070. usable results. Returns false if $transdate is not set.
  1071. $myconfig is not used.
  1072. =cut
  1073. sub check_exchangerate {
  1074. my ( $self, $myconfig, $currency, $transdate, $fld ) = @_;
  1075. return "" unless $transdate;
  1076. my $query = qq|
  1077. SELECT $fld
  1078. FROM exchangerate
  1079. WHERE curr = ? AND transdate = ?|;
  1080. my $sth = $self->{dbh}->prepare($query);
  1081. $sth->execute( $currency, $transdate );
  1082. my ($exchangerate) = $sth->fetchrow_array;
  1083. $sth->finish;
  1084. $exchangerate;
  1085. }
  1086. sub add_shipto {
  1087. my ( $self, $dbh, $id ) = @_;
  1088. my $shipto;
  1089. foreach my $item (
  1090. qw(name address1 address2 city state
  1091. zipcode country contact phone fax email)
  1092. )
  1093. {
  1094. if ( $self->{"shipto$item"} ne "" ) {
  1095. $shipto = 1 if ( $self->{$item} ne $self->{"shipto$item"} );
  1096. }
  1097. }
  1098. if ($shipto) {
  1099. my $query = qq|
  1100. INSERT INTO shipto
  1101. (trans_id, shiptoname, shiptoaddress1,
  1102. shiptoaddress2, shiptocity, shiptostate,
  1103. shiptozipcode, shiptocountry, shiptocontact,
  1104. shiptophone, shiptofax, shiptoemail)
  1105. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1106. |;
  1107. $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  1108. $sth->execute(
  1109. $id, $self->{shiptoname},
  1110. $self->{shiptoaddress1}, $self->{shiptoaddress2},
  1111. $self->{shiptocity}, $self->{shiptostate},
  1112. $self->{shiptozipcode}, $self->{shiptocountry},
  1113. $self->{shiptocontact}, $self->{shiptophone},
  1114. $self->{shiptofax}, $self->{shiptoemail}
  1115. ) || $self->dberror($query);
  1116. $sth->finish;
  1117. }
  1118. }
  1119. sub get_employee {
  1120. my ( $self, $dbh ) = @_;
  1121. my $login = $self->{login};
  1122. $login =~ s/@.*//;
  1123. my $query = qq|
  1124. SELECT name, id
  1125. FROM entity WHERE id IN (select entity_id
  1126. FROM employee
  1127. WHERE login = ?)|;
  1128. $sth = $self->{dbh}->prepare($query);
  1129. $sth->execute($login);
  1130. my (@a) = $sth->fetchrow_array();
  1131. $a[1] *= 1;
  1132. $sth->finish;
  1133. @a;
  1134. }
  1135. # this sub gets the id and name from $table
  1136. sub get_name {
  1137. my ( $self, $myconfig, $table, $transdate ) = @_;
  1138. # connect to database
  1139. my @queryargs;
  1140. my $where;
  1141. if ($transdate) {
  1142. $where = qq|
  1143. AND (startdate IS NULL OR startdate <= ?)
  1144. AND (enddate IS NULL OR enddate >= ?)|;
  1145. @queryargs = ( $transdate, $transdate );
  1146. }
  1147. # Company name is stored in $self->{vendor} or $self->{customer}
  1148. my $name = $self->like( lc $self->{$table} );
  1149. # Vendor and Customer are now views into entity_credit_account.
  1150. my $query = qq|
  1151. SELECT * FROM $table t
  1152. JOIN entity e ON t.entity_id = e.id
  1153. WHERE (lower(e.name) LIKE ? OR t.${table}number LIKE ?)
  1154. $where
  1155. ORDER BY e.name|;
  1156. unshift( @queryargs, $name, $name, $table );
  1157. my $sth = $self->{dbh}->prepare($query);
  1158. $sth->execute(@queryargs) || $self->dberror($query);
  1159. my $i = 0;
  1160. @{ $self->{name_list} } = ();
  1161. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1162. push( @{ $self->{name_list} }, $ref );
  1163. $i++;
  1164. }
  1165. $sth->finish;
  1166. return $i;
  1167. }
  1168. sub all_vc {
  1169. my ( $self, $myconfig, $vc, $module, $dbh, $transdate, $job ) = @_;
  1170. my $ref;
  1171. my $disconnect = 0;
  1172. $dbh = $self->{dbh};
  1173. my $sth;
  1174. if ($vc eq 'customer'){
  1175. $self->{vc_class} = 2;
  1176. } else {
  1177. $self->{vc_class} = 1;
  1178. }
  1179. my $query = qq|SELECT count(*) FROM entity_credit_account where entity_class = ?|;
  1180. my $where;
  1181. my @queryargs = ($self->{vc_class});
  1182. if ($transdate) {
  1183. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1184. AND (enddate IS NULL OR enddate >= ?)|;
  1185. push (@queryargs, $transdate, $transdate );
  1186. }
  1187. $sth = $dbh->prepare($query);
  1188. $sth->execute(@queryargs);
  1189. my ($count) = $sth->fetchrow_array;
  1190. $sth->finish;
  1191. @queryargs = ();
  1192. # build selection list
  1193. if ( $count < $myconfig->{vclimit} ) {
  1194. $self->{"${vc}_id"} *= 1;
  1195. $where = "AND $where" if $where;
  1196. $query = qq|SELECT id, name
  1197. FROM entity
  1198. WHERE id IN (select entity_id
  1199. FROM $vc)
  1200. $where
  1201. UNION
  1202. SELECT id,name
  1203. FROM entity
  1204. WHERE id = ?
  1205. ORDER BY name|;
  1206. push( @queryargs, $self->{"${vc}_id"} );
  1207. $sth = $dbh->prepare($query);
  1208. $sth->execute(@queryargs) || $self->dberror($query);
  1209. @{ $self->{"all_$vc"} } = ();
  1210. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1211. push @{ $self->{"all_$vc"} }, $ref;
  1212. }
  1213. $sth->finish;
  1214. }
  1215. # get self
  1216. if ( !$self->{employee_id} ) {
  1217. ( $self->{employee}, $self->{employee_id} ) = split /--/,
  1218. $self->{employee};
  1219. ( $self->{employee}, $self->{employee_id} ) = $self->get_employee($dbh)
  1220. unless $self->{employee_id};
  1221. }
  1222. $self->all_employees( $myconfig, $dbh, $transdate, 1 );
  1223. $self->all_departments( $myconfig, $dbh, $vc );
  1224. $self->all_projects( $myconfig, $dbh, $transdate, $job );
  1225. # get language codes
  1226. $query = qq|SELECT *
  1227. FROM language
  1228. ORDER BY 2|;
  1229. $sth = $dbh->prepare($query);
  1230. $sth->execute || $self->dberror($query);
  1231. $self->{all_language} = ();
  1232. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1233. push @{ $self->{all_language} }, $ref;
  1234. }
  1235. $sth->finish;
  1236. $self->all_taxaccounts( $myconfig, $dbh, $transdate );
  1237. }
  1238. sub all_taxaccounts {
  1239. my ( $self, $myconfig, $dbh2, $transdate ) = @_;
  1240. my $dbh = $self->{dbh};
  1241. my $sth;
  1242. my $query;
  1243. my $where;
  1244. my @queryargs = ();
  1245. if ($transdate) {
  1246. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1247. push( @queryargs, $transdate );
  1248. }
  1249. if ( $self->{taxaccounts} ) {
  1250. # rebuild tax rates
  1251. $query = qq|SELECT t.rate, t.taxnumber
  1252. FROM tax t
  1253. JOIN chart c ON (c.id = t.chart_id)
  1254. WHERE c.accno = ?
  1255. $where
  1256. ORDER BY accno, validto|;
  1257. $sth = $dbh->prepare($query) || $self->dberror($query);
  1258. foreach my $accno ( split / /, $self->{taxaccounts} ) {
  1259. $sth->execute( $accno, @queryargs );
  1260. ( $self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"} ) =
  1261. $sth->fetchrow_array;
  1262. $sth->finish;
  1263. }
  1264. }
  1265. }
  1266. sub all_employees {
  1267. my ( $self, $myconfig, $dbh2, $transdate, $sales ) = @_;
  1268. my $dbh = $self->{dbh};
  1269. my @whereargs = ();
  1270. # setup employees/sales contacts
  1271. my $query = qq|
  1272. SELECT id, name
  1273. FROM entity
  1274. WHERE id IN (SELECT entity_id FROM employee
  1275. WHERE|;
  1276. if ($transdate) {
  1277. $query .= qq| (startdate IS NULL OR startdate <= ?)
  1278. AND (enddate IS NULL OR enddate >= ?) AND|;
  1279. @whereargs = ( $transdate, $transdate );
  1280. }
  1281. else {
  1282. $query .= qq| enddate IS NULL AND|;
  1283. }
  1284. if ($sales) {
  1285. $query .= qq| sales = '1' AND|;
  1286. }
  1287. $query =~ s/(WHERE|AND)$//;
  1288. $query .= qq|) ORDER BY name|;
  1289. my $sth = $dbh->prepare($query);
  1290. $sth->execute(@whereargs) || $self->dberror($query);
  1291. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1292. push @{ $self->{all_employee} }, $ref;
  1293. }
  1294. $sth->finish;
  1295. }
  1296. sub all_projects {
  1297. my ( $self, $myconfig, $dbh2, $transdate, $job ) = @_;
  1298. my $dbh = $self->{dbh};
  1299. my @queryargs = ();
  1300. my $where = "1 = 1";
  1301. $where = qq|id NOT IN (SELECT id
  1302. FROM parts
  1303. WHERE project_id > 0)| if !$job;
  1304. my $query = qq|SELECT *
  1305. FROM project
  1306. WHERE $where|;
  1307. if ( $self->{language_code} ) {
  1308. $query = qq|
  1309. SELECT pr.*, t.description AS translation
  1310. FROM project pr
  1311. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1312. WHERE t.language_code = ?|;
  1313. push( @queryargs, $self->{language_code} );
  1314. }
  1315. if ($transdate) {
  1316. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1317. AND (enddate IS NULL OR enddate >= ?)|;
  1318. push( @queryargs, $transdate, $transdate );
  1319. }
  1320. $query .= qq| ORDER BY projectnumber|;
  1321. $sth = $dbh->prepare($query);
  1322. $sth->execute(@queryargs) || $self->dberror($query);
  1323. @{ $self->{all_project} } = ();
  1324. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1325. push @{ $self->{all_project} }, $ref;
  1326. }
  1327. $sth->finish;
  1328. }
  1329. sub all_departments {
  1330. my ( $self, $myconfig, $dbh2, $vc ) = @_;
  1331. $dbh = $self->{dbh};
  1332. my $where = "1 = 1";
  1333. if ($vc) {
  1334. if ( $vc eq 'customer' ) {
  1335. $where = " role = 'P'";
  1336. }
  1337. }
  1338. my $query = qq|SELECT id, description
  1339. FROM department
  1340. WHERE $where
  1341. ORDER BY 2|;
  1342. my $sth = $dbh->prepare($query);
  1343. $sth->execute || $self->dberror($query);
  1344. @{ $self->{all_department} } = ();
  1345. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1346. push @{ $self->{all_department} }, $ref;
  1347. }
  1348. $sth->finish;
  1349. $self->all_years($myconfig);
  1350. }
  1351. sub all_years {
  1352. my ( $self, $myconfig, $dbh2 ) = @_;
  1353. $dbh = $self->{dbh};
  1354. # get years
  1355. my $query = qq|
  1356. SELECT (SELECT transdate FROM acc_trans ORDER BY transdate asc
  1357. LIMIT 1),
  1358. (SELECT transdate FROM acc_trans ORDER BY transdate desc
  1359. LIMIT 1)|;
  1360. my ( $startdate, $enddate ) = $dbh->selectrow_array($query);
  1361. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1362. ($startdate) = split /\W/, $startdate;
  1363. ($enddate) = split /\W/, $enddate;
  1364. }
  1365. else {
  1366. (@_) = split /\W/, $startdate;
  1367. $startdate = $_[2];
  1368. (@_) = split /\W/, $enddate;
  1369. $enddate = $_[2];
  1370. }
  1371. $self->{all_years} = ();
  1372. $startdate = substr( $startdate, 0, 4 );
  1373. $enddate = substr( $enddate, 0, 4 );
  1374. while ( $enddate >= $startdate ) {
  1375. push @{ $self->{all_years} }, $enddate--;
  1376. }
  1377. #this should probably be changed to use locale
  1378. %{ $self->{all_month} } = (
  1379. '01' => 'January',
  1380. '02' => 'February',
  1381. '03' => 'March',
  1382. '04' => 'April',
  1383. '05' => 'May ',
  1384. '06' => 'June',
  1385. '07' => 'July',
  1386. '08' => 'August',
  1387. '09' => 'September',
  1388. '10' => 'October',
  1389. '11' => 'November',
  1390. '12' => 'December'
  1391. );
  1392. }
  1393. sub create_links {
  1394. my ( $self, $module, $myconfig, $vc, $job ) = @_;
  1395. # get last customers or vendors
  1396. my ( $query, $sth );
  1397. if (!$self->{dbh}) {
  1398. $self->db_init($myconfig);
  1399. }
  1400. $dbh = $self->{dbh};
  1401. my %xkeyref = ();
  1402. # now get the account numbers
  1403. $query = qq|SELECT accno, description, link
  1404. FROM chart
  1405. WHERE link LIKE ?
  1406. ORDER BY accno|;
  1407. $sth = $dbh->prepare($query);
  1408. $sth->execute( "%" . "$module%" ) || $self->dberror($query);
  1409. $self->{accounts} = "";
  1410. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1411. foreach my $key ( split /:/, $ref->{link} ) {
  1412. if ( $key =~ /$module/ ) {
  1413. # cross reference for keys
  1414. $xkeyref{ $ref->{accno} } = $key;
  1415. push @{ $self->{"${module}_links"}{$key} },
  1416. {
  1417. accno => $ref->{accno},
  1418. description => $ref->{description}
  1419. };
  1420. $self->{accounts} .= "$ref->{accno} "
  1421. unless $key =~ /tax/;
  1422. }
  1423. }
  1424. }
  1425. $sth->finish;
  1426. my $arap = ( $vc eq 'customer' ) ? 'ar' : 'ap';
  1427. if ( $self->{id} ) {
  1428. $query = qq|
  1429. SELECT a.invnumber, a.transdate,
  1430. a.${vc}_id, a.datepaid, a.duedate, a.ordnumber,
  1431. a.taxincluded, a.curr AS currency, a.notes,
  1432. a.intnotes, c.name AS $vc, a.department_id,
  1433. d.description AS department,
  1434. a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
  1435. a.employee_id, e.name AS employee,
  1436. c.language_code, a.ponumber, a.reverse
  1437. FROM $arap a
  1438. JOIN $vc c ON (a.${vc}_id = c.id)
  1439. LEFT JOIN employee e ON (e.id = a.employee_id)
  1440. LEFT JOIN department d ON (d.id = a.department_id)
  1441. WHERE a.id = ?|;
  1442. $sth = $dbh->prepare($query);
  1443. $sth->execute( $self->{id} ) || $self->dberror($query);
  1444. $ref = $sth->fetchrow_hashref(NAME_lc);
  1445. $self->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1446. foreach $key ( keys %$ref ) {
  1447. $self->{$key} = $ref->{$key};
  1448. }
  1449. $sth->finish;
  1450. # get printed, emailed
  1451. $query = qq|
  1452. SELECT s.printed, s.emailed, s.spoolfile, s.formname
  1453. FROM status s WHERE s.trans_id = ?|;
  1454. $sth = $dbh->prepare($query);
  1455. $sth->execute( $self->{id} ) || $self->dberror($query);
  1456. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1457. $self->{printed} .= "$ref->{formname} "
  1458. if $ref->{printed};
  1459. $self->{emailed} .= "$ref->{formname} "
  1460. if $ref->{emailed};
  1461. $self->{queued} .= "$ref->{formname} " . "$ref->{spoolfile} "
  1462. if $ref->{spoolfile};
  1463. }
  1464. $sth->finish;
  1465. for (qw(printed emailed queued)) { $self->{$_} =~ s/ +$//g }
  1466. # get recurring
  1467. $self->get_recurring($dbh);
  1468. # get amounts from individual entries
  1469. $query = qq|
  1470. SELECT c.accno, c.description, a.source, a.amount,
  1471. a.memo, a.transdate, a.cleared, a.project_id,
  1472. p.projectnumber
  1473. FROM acc_trans a
  1474. JOIN chart c ON (c.id = a.chart_id)
  1475. LEFT JOIN project p ON (p.id = a.project_id)
  1476. WHERE a.trans_id = ?
  1477. AND a.fx_transaction = '0'
  1478. ORDER BY transdate|;
  1479. $sth = $dbh->prepare($query);
  1480. $sth->execute( $self->{id} ) || $self->dberror($query);
  1481. my $fld = ( $vc eq 'customer' ) ? 'buy' : 'sell';
  1482. $self->{exchangerate} =
  1483. $self->get_exchangerate( $dbh, $self->{currency}, $self->{transdate},
  1484. $fld );
  1485. # store amounts in {acc_trans}{$key} for multiple accounts
  1486. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1487. $ref->{exchangerate} =
  1488. $self->get_exchangerate( $dbh, $self->{currency},
  1489. $ref->{transdate}, $fld );
  1490. if ($form->{reverse}){
  1491. $ref->{amount} *= -1;
  1492. }
  1493. push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
  1494. }
  1495. $sth->finish;
  1496. }
  1497. else {
  1498. if ( !$self->{"$self->{vc}_id"} ) {
  1499. $self->lastname_used( $myconfig, $dbh, $vc, $module );
  1500. }
  1501. }
  1502. for (qw(current_date curr closedto revtrans)) {
  1503. if ($_ eq 'closedto'){
  1504. $query = qq|
  1505. SELECT value::date FROM defaults
  1506. WHERE setting_key = '$_'|;
  1507. } elsif ($_ eq 'current_date') {
  1508. $query = qq| select $_|;
  1509. } else {
  1510. $query = qq|
  1511. SELECT value FROM defaults
  1512. WHERE setting_key = '$_'|;
  1513. }
  1514. $sth = $dbh->prepare($query);
  1515. $sth->execute || $self->dberror($query);
  1516. ($val) = $sth->fetchrow_array();
  1517. if ( $_ eq 'curr' ) {
  1518. $self->{currencies} = $val;
  1519. }
  1520. else {
  1521. $self->{$_} = $val;
  1522. }
  1523. $sth->finish;
  1524. }
  1525. if (!$self->{id}){
  1526. $self->{transdate} = $self->{current_date};
  1527. }
  1528. $self->all_vc( $myconfig, $vc, $module, $dbh, $self->{transdate}, $job );
  1529. }
  1530. sub lastname_used {
  1531. my ( $self, $myconfig, $dbh2, $vc, $module ) = @_;
  1532. my $dbh = $self->{dbh};
  1533. $vc ||= $self->{vc}; # add default to correct for improper passing
  1534. my $arap = ( $vc eq 'customer' ) ? "ar" : "ap";
  1535. my $sth;
  1536. if ( $self->{type} =~ /_order/ ) {
  1537. $arap = 'oe';
  1538. $where = "quotation = '0'";
  1539. }
  1540. if ( $self->{type} =~ /_quotation/ ) {
  1541. $arap = 'oe';
  1542. $where = "quotation = '1'";
  1543. }
  1544. $where = "AND $where " if $where;
  1545. $inv_notes = "ct.invoice_notes," if $vc eq 'customer';
  1546. my $query = qq|
  1547. SELECT entity.name, ct.curr AS currency, entity_id AS ${vc}_id,
  1548. current_date + ct.terms AS duedate,
  1549. $inv_notes
  1550. ct.curr AS currency
  1551. FROM $vc ct
  1552. JOIN entity ON (ct.entity_id = entity.id)
  1553. WHERE entity.id = (select entity_id from $arap
  1554. where entity_id IS NOT NULL $where
  1555. order by id DESC limit 1)|;
  1556. $sth = $self->{dbh}->prepare($query);
  1557. $sth->execute() || $self->dberror($query);
  1558. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1559. for ( keys %$ref ) { $self->{$_} = $ref->{$_} }
  1560. $sth->finish;
  1561. }
  1562. =item $form->current_date($myconfig[, $thisdate, $days]);
  1563. If $thisdate is false, get the current date from the database.
  1564. If $thisdate is true, get the date $days days from $thisdate in the date
  1565. format specified by $myconfig->{dateformat} from the database.
  1566. =cut
  1567. sub current_date {
  1568. my ( $self, $myconfig, $thisdate, $days ) = @_;
  1569. my $dbh = $self->{dbh};
  1570. my $query;
  1571. $days *= 1;
  1572. if ($thisdate) {
  1573. my $dateformat = $myconfig->{dateformat};
  1574. if ( $myconfig->{dateformat} !~ /^y/ ) {
  1575. my @a = split /\D/, $thisdate;
  1576. $dateformat .= "yy" if ( length $a[2] > 2 );
  1577. }
  1578. if ( $thisdate !~ /\D/ ) {
  1579. $dateformat = 'yyyymmdd';
  1580. }
  1581. $query = qq|SELECT (to_date(?, ?)
  1582. + ?::interval)::date AS thisdate|;
  1583. @queryargs = ( $thisdate, $dateformat, sprintf('%d days', $days) );
  1584. }
  1585. else {
  1586. $query = qq|SELECT current_date AS thisdate|;
  1587. @queryargs = ();
  1588. }
  1589. $sth = $dbh->prepare($query);
  1590. $sth->execute(@queryargs);
  1591. ($thisdate) = $sth->fetchrow_array;
  1592. $thisdate;
  1593. }
  1594. =item $form->like($str);
  1595. Returns '%$str%'
  1596. =cut
  1597. sub like {
  1598. my ( $self, $str ) = @_;
  1599. "%$str%";
  1600. }
  1601. sub redo_rows {
  1602. my ( $self, $flds, $new, $count, $numrows ) = @_;
  1603. my @ndx = ();
  1604. for ( 1 .. $count ) {
  1605. push @ndx, { num => $new->[ $_ - 1 ]->{runningnumber}, ndx => $_ };
  1606. }
  1607. my $i = 0;
  1608. # fill rows
  1609. foreach my $item ( sort { $a->{num} <=> $b->{num} } @ndx ) {
  1610. $i++;
  1611. $j = $item->{ndx} - 1;
  1612. for ( @{$flds} ) { $self->{"${_}_$i"} = $new->[$j]->{$_} }
  1613. }
  1614. # delete empty rows
  1615. for $i ( $count + 1 .. $numrows ) {
  1616. for ( @{$flds} ) { delete $self->{"${_}_$i"} }
  1617. }
  1618. }
  1619. sub get_partsgroup {
  1620. my ( $self, $myconfig, $p ) = @_;
  1621. my $dbh = $self->{dbh};
  1622. my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
  1623. FROM partsgroup pg
  1624. JOIN parts p ON (p.partsgroup_id = pg.id)|;
  1625. my $where;
  1626. my $sortorder = "partsgroup";
  1627. if ( $p->{searchitems} eq 'part' ) {
  1628. $where = qq| WHERE (p.inventory_accno_id > 0
  1629. AND p.income_accno_id > 0)|;
  1630. }
  1631. if ( $p->{searchitems} eq 'service' ) {
  1632. $where = qq| WHERE p.inventory_accno_id IS NULL|;
  1633. }
  1634. if ( $p->{searchitems} eq 'assembly' ) {
  1635. $where = qq| WHERE p.assembly = '1'|;
  1636. }
  1637. if ( $p->{searchitems} eq 'labor' ) {
  1638. $where =
  1639. qq| WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
  1640. }
  1641. if ( $p->{searchitems} eq 'nolabor' ) {
  1642. $where = qq| WHERE p.income_accno_id > 0|;
  1643. }
  1644. if ( $p->{all} ) {
  1645. $query = qq|SELECT id, partsgroup
  1646. FROM partsgroup|;
  1647. }
  1648. my @queryargs = ();
  1649. if ( $p->{language_code} ) {
  1650. $sortorder = "translation";
  1651. $query = qq|
  1652. SELECT DISTINCT pg.id, pg.partsgroup,
  1653. t.description AS translation
  1654. FROM partsgroup pg
  1655. JOIN parts p ON (p.partsgroup_id = pg.id)
  1656. LEFT JOIN translation t ON (t.trans_id = pg.id
  1657. AND t.language_code = ?)|;
  1658. @queryargs = ( $p->{language_code} );
  1659. }
  1660. $query .= qq| $where ORDER BY $sortorder|;
  1661. my $sth = $dbh->prepare($query);
  1662. $sth->execute(@queryargs) || $self->dberror($query);
  1663. $self->{all_partsgroup} = ();
  1664. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1665. push @{ $self->{all_partsgroup} }, $ref;
  1666. }
  1667. $sth->finish;
  1668. }
  1669. sub update_status {
  1670. my ( $self, $myconfig ) = @_;
  1671. # no id return
  1672. return unless $self->{id};
  1673. my $dbh = $self->{dbh};
  1674. my %queued = split / +/, $self->{queued};
  1675. my $spoolfile =
  1676. ( $queued{ $self->{formname} } )
  1677. ? "'$queued{$self->{formname}}'"
  1678. : 'NULL';
  1679. my $query = qq|DELETE FROM status
  1680. WHERE formname = ?
  1681. AND trans_id = ?|;
  1682. $sth = $dbh->prepare($query);
  1683. $sth->execute( $self->{formname}, $self->{id} ) || $self->dberror($query);
  1684. $sth->finish;
  1685. my $printed = ( $self->{printed} =~ /$self->{formname}/ ) ? "1" : "0";
  1686. my $emailed = ( $self->{emailed} =~ /$self->{formname}/ ) ? "1" : "0";
  1687. $query = qq|
  1688. INSERT INTO status
  1689. (trans_id, printed, emailed, spoolfile, formname)
  1690. VALUES (?, ?, ?, ?, ?)|;
  1691. $sth = $dbh->prepare($query);
  1692. $sth->execute( $self->{id}, $printed, $emailed, $spoolfile,
  1693. $self->{formname} );
  1694. $sth->finish;
  1695. }
  1696. sub save_status {
  1697. my ($self) = @_;
  1698. $dbh = $self->{dbh};
  1699. my $formnames = $self->{printed};
  1700. my $emailforms = $self->{emailed};
  1701. my $query = qq|DELETE FROM status
  1702. WHERE trans_id = ?|;
  1703. my $sth = $dbh->prepare($query);
  1704. $sth->execute( $self->{id} );
  1705. $sth->finish;
  1706. my %queued;
  1707. my $formname;
  1708. if ( $self->{queued} ) {
  1709. %queued = split / +/, $self->{queued};
  1710. foreach $formname ( keys %queued ) {
  1711. $printed = ( $self->{printed} =~ /$formname/ ) ? "1" : "0";
  1712. $emailed = ( $self->{emailed} =~ /$formname/ ) ? "1" : "0";
  1713. if ( $queued{$formname} ) {
  1714. $query = qq|
  1715. INSERT INTO status
  1716. (trans_id, printed, emailed,
  1717. spoolfile, formname)
  1718. VALUES (?, ?, ?, ?, ?)|;
  1719. $sth = $dbh->prepare($query);
  1720. $sth->execute( $self->{id}, $pinted, $emailed,
  1721. $queued{$formname}, $formname )
  1722. || $self->dberror($query);
  1723. $sth->finish;
  1724. }
  1725. $formnames =~ s/$formname//;
  1726. $emailforms =~ s/$formname//;
  1727. }
  1728. }
  1729. # save printed, emailed info
  1730. $formnames =~ s/^ +//g;
  1731. $emailforms =~ s/^ +//g;
  1732. my %status = ();
  1733. for ( split / +/, $formnames ) { $status{$_}{printed} = 1 }
  1734. for ( split / +/, $emailforms ) { $status{$_}{emailed} = 1 }
  1735. foreach my $formname ( keys %status ) {
  1736. $printed = ( $formnames =~ /$self->{formname}/ ) ? "1" : "0";
  1737. $emailed = ( $emailforms =~ /$self->{formname}/ ) ? "1" : "0";
  1738. $query = qq|
  1739. INSERT INTO status (trans_id, printed, emailed,
  1740. formname)
  1741. VALUES (?, ?, ?, ?)|;
  1742. $sth = $dbh->prepare($query);
  1743. $sth->execute( $self->{id}, $printed, $emailed, $formname );
  1744. $sth->finish;
  1745. }
  1746. $dbh->commit;
  1747. }
  1748. sub get_recurring {
  1749. my ($self) = @_;
  1750. $dbh = $self->{dbh};
  1751. my $query = qq/
  1752. SELECT s.*, se.formname || ':' || se.format AS emaila,
  1753. se.message, sp.formname || ':' ||
  1754. sp.format || ':' || sp.printer AS printa
  1755. FROM recurring s
  1756. LEFT JOIN recurringemail se ON (s.id = se.id)
  1757. LEFT JOIN recurringprint sp ON (s.id = sp.id)
  1758. WHERE s.id = ?/;
  1759. my $sth = $dbh->prepare($query);
  1760. $sth->execute( $self->{id} ) || $self->dberror($query);
  1761. for (qw(email print)) { $self->{"recurring$_"} = "" }
  1762. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1763. for ( keys %$ref ) { $self->{"recurring$_"} = $ref->{$_} }
  1764. $self->{recurringemail} .= "$ref->{emaila}:";
  1765. $self->{recurringprint} .= "$ref->{printa}:";
  1766. for (qw(emaila printa)) { delete $self->{"recurring$_"} }
  1767. }
  1768. $sth->finish;
  1769. chop $self->{recurringemail};
  1770. chop $self->{recurringprint};
  1771. if ( $self->{recurringstartdate} ) {
  1772. $self->{recurringreference} =
  1773. $self->escape( $self->{recurringreference}, 1 );
  1774. $self->{recurringmessage} =
  1775. $self->escape( $self->{recurringmessage}, 1 );
  1776. for (
  1777. qw(reference startdate repeat unit howmany
  1778. payment print email message)
  1779. )
  1780. {
  1781. $self->{recurring} .= qq|$self->{"recurring$_"},|;
  1782. }
  1783. chop $self->{recurring};
  1784. }
  1785. }
  1786. sub save_recurring {
  1787. my ( $self, $dbh2, $myconfig ) = @_;
  1788. my $dbh = $self->{dbh};
  1789. my $query;
  1790. $query = qq|DELETE FROM recurring
  1791. WHERE id = ?|;
  1792. $sth = $dbh->prepare($query) || $self->dberror($query);
  1793. $sth->execute( $self->{id} ) || $self->dberror($query);
  1794. $query = qq|DELETE FROM recurringemail
  1795. WHERE id = ?|;
  1796. $sth = $dbh->prepare($query) || $self->dberror($query);
  1797. $sth->execute( $self->{id} ) || $self->dberror($query);
  1798. $query = qq|DELETE FROM recurringprint
  1799. WHERE id = ?|;
  1800. $sth = $dbh->prepare($query) || $self->dberror($query);
  1801. $sth->execute( $self->{id} ) || $self->dberror($query);
  1802. if ( $self->{recurring} ) {
  1803. my %s = ();
  1804. (
  1805. $s{reference}, $s{startdate}, $s{repeat},
  1806. $s{unit}, $s{howmany}, $s{payment},
  1807. $s{print}, $s{email}, $s{message}
  1808. ) = split /,/, $self->{recurring};
  1809. if ($s{howmany} == 0){
  1810. $self->error("Cannot set to recur 0 times");
  1811. }
  1812. for (qw(reference message)) { $s{$_} = $self->unescape( $s{$_} ) }
  1813. for (qw(repeat howmany payment)) { $s{$_} *= 1 }
  1814. # calculate enddate
  1815. my $advance = $s{repeat} * ( $s{howmany} - 1 );
  1816. my %interval;
  1817. $interval{'Pg'} =
  1818. "(date '$s{startdate}' + interval '$advance $s{unit}')";
  1819. $query = qq|SELECT $interval{$myconfig->{dbdriver}}|;
  1820. my ($enddate) = $dbh->selectrow_array($query);
  1821. # calculate nextdate
  1822. $query = qq|
  1823. SELECT current_date - ?::date AS a,
  1824. ?::date - current_date AS b|;
  1825. $sth = $dbh->prepare($query) || $self->dberror($query);
  1826. $sth->execute( $s{startdate}, $enddate );
  1827. my ( $a, $b ) = $sth->fetchrow_array;
  1828. if ( $a + $b ) {
  1829. $advance =
  1830. int( ( $a / ( $a + $b ) ) * ( $s{howmany} - 1 ) + 1 ) *
  1831. $s{repeat};
  1832. }
  1833. else {
  1834. $advance = 0;
  1835. }
  1836. my $nextdate = $enddate;
  1837. if ( $advance > 0 ) {
  1838. if ( $advance < ( $s{repeat} * $s{howmany} ) ) {
  1839. $query = qq|SELECT (date '$s{startdate}' + interval '$advance $s{unit}')|;
  1840. ($nextdate) = $dbh->selectrow_array($query);
  1841. }
  1842. }
  1843. else {
  1844. $nextdate = $s{startdate};
  1845. }
  1846. if ( $self->{recurringnextdate} ) {
  1847. $nextdate = $self->{recurringnextdate};
  1848. $query = qq|SELECT '$enddate' - date '$nextdate'|;
  1849. if ( $dbh->selectrow_array($query) < 0 ) {
  1850. undef $nextdate;
  1851. }
  1852. }
  1853. $self->{recurringpayment} *= 1;
  1854. $query = qq|
  1855. INSERT INTO recurring
  1856. (id, reference, startdate, enddate, nextdate,
  1857. repeat, unit, howmany, payment)
  1858. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)|;
  1859. $sth = $dbh->prepare($query);
  1860. $sth->execute(
  1861. $self->{id}, $s{reference}, $s{startdate},
  1862. $enddate, $nextdate, $s{repeat},
  1863. $s{unit}, $s{howmany}, $s{payment}
  1864. );
  1865. my @p;
  1866. my $p;
  1867. my $i;
  1868. my $sth;
  1869. if ( $s{email} ) {
  1870. # formname:format
  1871. @p = split /:/, $s{email};
  1872. $query =
  1873. qq|INSERT INTO recurringemail (id, formname, format, message)
  1874. VALUES (?, ?, ?, ?)|;
  1875. $sth = $dbh->prepare($query) || $self->dberror($query);
  1876. for ( $i = 0 ; $i <= $#p ; $i += 2 ) {
  1877. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $s{message} );
  1878. }
  1879. $sth->finish;
  1880. }
  1881. if ( $s{print} ) {
  1882. # formname:format:printer
  1883. @p = split /:/, $s{print};
  1884. $query =
  1885. qq|INSERT INTO recurringprint (id, formname, format, printer)
  1886. VALUES (?, ?, ?, ?)|;
  1887. $sth = $dbh->prepare($query) || $self->dberror($query);
  1888. for ( $i = 0 ; $i <= $#p ; $i += 3 ) {
  1889. $p = ( $p[ $i + 2 ] ) ? $p[ $i + 2 ] : "";
  1890. $sth->execute( $self->{id}, $p[$i], $p[ $i + 1 ], $p );
  1891. }
  1892. $sth->finish;
  1893. }
  1894. }
  1895. $dbh->commit;
  1896. }
  1897. sub save_intnotes {
  1898. my ( $self, $myconfig, $vc ) = @_;
  1899. # no id return
  1900. return unless $self->{id};
  1901. my $dbh = $self->{dbh};
  1902. my $query = qq|UPDATE $vc SET intnotes = ? WHERE id = ?|;
  1903. $sth = $dbh->prepare($query);
  1904. $sth->execute( $self->{intnotes}, $self->{id} ) || $self->dberror($query);
  1905. $dbh->commit;
  1906. }
  1907. sub update_defaults {
  1908. my ( $self, $myconfig, $fld ) = @_;
  1909. if ( !$self->{dbh} && $self ) {
  1910. $self->db_init($myconfig);
  1911. }
  1912. my $dbh = $self->{dbh};
  1913. if ( !$self ) {
  1914. $dbh = $_[3];
  1915. }
  1916. my $query = qq|
  1917. SELECT value FROM defaults
  1918. WHERE setting_key = ? FOR UPDATE|;
  1919. $sth = $dbh->prepare($query);
  1920. $sth->execute($fld);
  1921. ($_) = $sth->fetchrow_array();
  1922. $_ = "0" unless $_;
  1923. # check for and replace
  1924. # <?lsmb DATE ?>, <?lsmb YYMMDD ?>, <?lsmb YEAR ?>, <?lsmb MONTH ?>, <?lsmb DAY ?> or variations of
  1925. # <?lsmb NAME 1 1 3 ?>, <?lsmb BUSINESS ?>, <?lsmb BUSINESS 10 ?>, <?lsmb CURR... ?>
  1926. # <?lsmb DESCRIPTION 1 1 3 ?>, <?lsmb ITEM 1 1 3 ?>, <?lsmb PARTSGROUP 1 1 3 ?> only for parts
  1927. # <?lsmb PHONE ?> for customer and vendors
  1928. my $num = $_;
  1929. ($num) = $num =~ /(\d+)/;
  1930. if ( defined $num ) {
  1931. my $incnum;
  1932. # if we have leading zeros check how long it is
  1933. if ( $num =~ /^0/ ) {
  1934. my $l = length $num;
  1935. $incnum = $num + 1;
  1936. $l -= length $incnum;
  1937. # pad it out with zeros
  1938. my $padzero = "0" x $l;
  1939. $incnum = ( "0" x $l ) . $incnum;
  1940. }
  1941. else {
  1942. $incnum = $num + 1;
  1943. }
  1944. s/$num/$incnum/;
  1945. }
  1946. my $dbvar = $_;
  1947. my $var = $_;
  1948. my $str;
  1949. my $param;
  1950. if (/<\?lsmb /) {
  1951. while (/<\?lsmb /) {
  1952. s/<\?lsmb .*? \?>//;
  1953. last unless $&;
  1954. $param = $&;
  1955. $str = "";
  1956. if ( $param =~ /<\?lsmb date \?>/i ) {
  1957. $str = (
  1958. $self->split_date(
  1959. $myconfig->{dateformat},
  1960. $self->{transdate}
  1961. )
  1962. )[0];
  1963. $var =~ s/$param/$str/;
  1964. }
  1965. if ( $param =~
  1966. /<\?lsmb (name|business|description|item|partsgroup|phone|custom)/i
  1967. )
  1968. {
  1969. my $fld = lc $&;
  1970. $fld =~ s/<\?lsmb //;
  1971. if ( $fld =~ /name/ ) {
  1972. if ( $self->{type} ) {
  1973. $fld = $self->{vc};
  1974. }
  1975. }
  1976. my $p = $param;
  1977. $p =~ s/(<|>|%)//g;
  1978. my @p = split / /, $p;
  1979. my @n = split / /, uc $self->{$fld};
  1980. if ( $#p > 0 ) {
  1981. for ( my $i = 1 ; $i <= $#p ; $i++ ) {
  1982. $str .= substr( $n[ $i - 1 ], 0, $p[$i] );
  1983. }
  1984. }
  1985. else {
  1986. ($str) = split /--/, $self->{$fld};
  1987. }
  1988. $var =~ s/$param/$str/;
  1989. $var =~ s/\W//g if $fld eq 'phone';
  1990. }
  1991. if ( $param =~ /<\?lsmb (yy|mm|dd)/i ) {
  1992. my $p = $param;
  1993. $p =~ s/(<|>|%)//g;
  1994. my $spc = $p;
  1995. $spc =~ s/\w//g;
  1996. $spc = substr( $spc, 0, 1 );
  1997. my %d = ( yy => 1, mm => 2, dd => 3 );
  1998. my @p = ();
  1999. my @a = $self->split_date( $myconfig->{dateformat},
  2000. $self->{transdate} );
  2001. for ( sort keys %d ) { push @p, $a[ $d{$_} ] if ( $p =~ /$_/ ) }
  2002. $str = join $spc, @p;
  2003. $var =~ s/$param/$str/;
  2004. }
  2005. if ( $param =~ /<\?lsmb curr/i ) {
  2006. $var =~ s/$param/$self->{currency}/;
  2007. }
  2008. }
  2009. }
  2010. $query = qq|
  2011. UPDATE defaults
  2012. SET value = ?
  2013. WHERE setting_key = ?|;
  2014. $sth = $dbh->prepare($query);
  2015. $sth->execute( $dbvar, $fld ) || $self->dberror($query);
  2016. $dbh->commit;
  2017. $var;
  2018. }
  2019. sub db_prepare_vars {
  2020. my $self = shift;
  2021. for (@_) {
  2022. if ( !$self->{$_} and $self->{$_} ne "0" ) {
  2023. undef $self->{$_};
  2024. }
  2025. }
  2026. }
  2027. =item $form->split_date($dateformat[, $date]);
  2028. Returns ($rv, $yy, $mm, $dd) for the provided $date, or the current date if no
  2029. date is provided. $rv is a seperator-free merging of the fields $yy, $mm, and
  2030. $dd in the ordering supplied by $dateformat. If the supplied $date does not
  2031. contain non-digit characters, $rv is $date and the other return values are
  2032. undefined.
  2033. $yy is two digits.
  2034. =cut
  2035. sub split_date {
  2036. my ( $self, $dateformat, $date ) = @_;
  2037. my $mm;
  2038. my $dd;
  2039. my $yy;
  2040. my $rv;
  2041. if ( !$date ) {
  2042. my @d = localtime;
  2043. $dd = $d[3];
  2044. $mm = ++$d[4];
  2045. $yy = substr( $d[5], -2 );
  2046. $mm = substr( "0$mm", -2 );
  2047. $dd = substr( "0$dd", -2 );
  2048. }
  2049. if ( $dateformat =~ /^yy/ ) {
  2050. if ($date) {
  2051. if ( $date =~ /\D/ ) {
  2052. ( $yy, $mm, $dd ) = split /\D/, $date;
  2053. $mm *= 1;
  2054. $dd *= 1;
  2055. $mm = substr( "0$mm", -2 );
  2056. $dd = substr( "0$dd", -2 );
  2057. $yy = substr( $yy, -2 );
  2058. $rv = "$yy$mm$dd";
  2059. }
  2060. else {
  2061. $rv = $date;
  2062. }
  2063. }
  2064. else {
  2065. $rv = "$yy$mm$dd";
  2066. }
  2067. }
  2068. elsif ( $dateformat =~ /^mm/ ) {
  2069. if ($date) {
  2070. if ( $date =~ /\D/ ) {
  2071. ( $mm, $dd, $yy ) = split /\D/, $date;
  2072. $mm *= 1;
  2073. $dd *= 1;
  2074. $mm = substr( "0$mm", -2 );
  2075. $dd = substr( "0$dd", -2 );
  2076. $yy = substr( $yy, -2 );
  2077. $rv = "$mm$dd$yy";
  2078. }
  2079. else {
  2080. $rv = $date;
  2081. }
  2082. }
  2083. else {
  2084. $rv = "$mm$dd$yy";
  2085. }
  2086. }
  2087. elsif ( $dateformat =~ /^dd/ ) {
  2088. if ($date) {
  2089. if ( $date =~ /\D/ ) {
  2090. ( $dd, $mm, $yy ) = split /\D/, $date;
  2091. $mm *= 1;
  2092. $dd *= 1;
  2093. $mm = substr( "0$mm", -2 );
  2094. $dd = substr( "0$dd", -2 );
  2095. $yy = substr( $yy, -2 );
  2096. $rv = "$dd$mm$yy";
  2097. }
  2098. else {
  2099. $rv = $date;
  2100. }
  2101. }
  2102. else {
  2103. $rv = "$dd$mm$yy";
  2104. }
  2105. }
  2106. ( $rv, $yy, $mm, $dd );
  2107. }
  2108. =item $form->format_date($date);
  2109. Returns $date converted from 'yyyy-mm-dd' format to the format specified by
  2110. $form->{db_dateformat}. If the supplied date does not match /^\d{4}\D/,
  2111. return the supplied date.
  2112. This function takes a four digit year and returns the date with a four digit
  2113. year.
  2114. =cut
  2115. sub format_date {
  2116. # takes an iso date in, and converts it to the date for printing
  2117. my ( $self, $date ) = @_;
  2118. my $datestring;
  2119. if ( $date =~ /^\d{4}\D/ ) { # is an ISO date
  2120. $datestring = $self->{db_dateformat};
  2121. my ( $yyyy, $mm, $dd ) = split( /\W/, $date );
  2122. $datestring =~ s/y+/$yyyy/;
  2123. $datestring =~ s/mm/$mm/;
  2124. $datestring =~ s/dd/$dd/;
  2125. }
  2126. else { # return date
  2127. $datestring = $date;
  2128. }
  2129. $datestring;
  2130. }
  2131. =item $form->from_to($yyyy, $mm[, $interval]);
  2132. Returns the date $yyyy-$mm-01 and the the last day of the month interval - 1
  2133. months from then in the form ($form->format_date(fromdate),
  2134. $form->format_date(later)). If $interval is false but defined, the later date
  2135. is the current date.
  2136. This function dies horribly when $mm + $interval > 24
  2137. =cut
  2138. sub from_to {
  2139. my ( $self, $yyyy, $mm, $interval ) = @_;
  2140. my @t;
  2141. my $dd = 1;
  2142. my $fromdate = "$yyyy-${mm}-01";
  2143. my $bd = 1;
  2144. if ( defined $interval ) {
  2145. if ( $interval == 12 ) {
  2146. $yyyy++;
  2147. }
  2148. else {
  2149. if ( ( $mm += $interval ) > 12 ) {
  2150. $mm -= 12;
  2151. $yyyy++;
  2152. }
  2153. if ( $interval == 0 ) {
  2154. @t = localtime(time);
  2155. $dd = $t[3];
  2156. $mm = $t[4] + 1;
  2157. $yyyy = $t[5] + 1900;
  2158. $bd = 0;
  2159. }
  2160. }
  2161. }
  2162. else {
  2163. if ( ++$mm > 12 ) {
  2164. $mm -= 12;
  2165. $yyyy++;
  2166. }
  2167. }
  2168. $mm--;
  2169. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yyyy ) - $bd );
  2170. $t[4]++;
  2171. $t[4] = substr( "0$t[4]", -2 );
  2172. $t[3] = substr( "0$t[3]", -2 );
  2173. $t[5] += 1900;
  2174. ( $self->format_date($fromdate), $self->format_date("$t[5]-$t[4]-$t[3]") );
  2175. }
  2176. sub audittrail {
  2177. my ( $self, $dbh, $myconfig, $audittrail ) = @_;
  2178. # table, $reference, $formname, $action, $id, $transdate) = @_;
  2179. my $query;
  2180. my $rv;
  2181. my $disconnect;
  2182. if ( !$dbh ) {
  2183. $dbh = $self->{dbh};
  2184. }
  2185. # if we have an id add audittrail, otherwise get a new timestamp
  2186. my @queryargs;
  2187. if ( $audittrail->{id} ) {
  2188. $query = qq|
  2189. SELECT value FROM defaults
  2190. WHERE setting_key = 'audittrail'|;
  2191. if ( $dbh->selectrow_array($query) ) {
  2192. my ( $null, $employee_id ) = $self->get_employee($dbh);
  2193. if ( $self->{audittrail} && !$myconfig ) {
  2194. chop $self->{audittrail};
  2195. my @a = split /\|/, $self->{audittrail};
  2196. my %newtrail = ();
  2197. my $key;
  2198. my $i;
  2199. my @flds = qw(tablename reference formname action transdate);
  2200. # put into hash and remove dups
  2201. while (@a) {
  2202. $key = "$a[2]$a[3]";
  2203. $i = 0;
  2204. $newtrail{$key} = { map { $_ => $a[ $i++ ] } @flds };
  2205. splice @a, 0, 5;
  2206. }
  2207. $query = qq|
  2208. INSERT INTO audittrail
  2209. (trans_id, tablename, reference,
  2210. formname, action, transdate,
  2211. employee_id)
  2212. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2213. my $sth = $dbh->prepare($query) || $self->dberror($query);
  2214. foreach $key (
  2215. sort {
  2216. $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
  2217. } keys %newtrail
  2218. )
  2219. {
  2220. $i = 2;
  2221. $sth->bind_param( 1, $audittrail->{id} );
  2222. for (@flds) {
  2223. $sth->bind_param( $i++, $newtrail{$key}{$_} );
  2224. }
  2225. $sth->bind_param( $i++, $employee_id );
  2226. $sth->execute() || $self->dberror($query);
  2227. $sth->finish;
  2228. }
  2229. }
  2230. if ( $audittrail->{transdate} ) {
  2231. $query = qq|
  2232. INSERT INTO audittrail (
  2233. trans_id, tablename, reference,
  2234. formname, action, employee_id,
  2235. transdate)
  2236. VALUES (?, ?, ?, ?, ?, ?, ?)|;
  2237. @queryargs = (
  2238. $audittrail->{id}, $audittrail->{tablename},
  2239. $audittrail->{reference}, $audittrail->{formname},
  2240. $audittrail->{action}, $employee_id,
  2241. $audittrail->{transdate}
  2242. );
  2243. }
  2244. else {
  2245. $query = qq|
  2246. INSERT INTO audittrail
  2247. (trans_id, tablename, reference,
  2248. formname, action, employee_id)
  2249. VALUES (?, ?, ?, ?, ?, ?)|;
  2250. @queryargs = (
  2251. $audittrail->{id}, $audittrail->{tablename},
  2252. $audittrail->{reference}, $audittrail->{formname},
  2253. $audittrail->{action}, $employee_id,
  2254. );
  2255. }
  2256. $sth = $dbh->prepare($query);
  2257. $sth->execute(@queryargs) || $self->dberror($query);
  2258. }
  2259. }
  2260. else {
  2261. $query = qq|SELECT current_timestamp|;
  2262. my ($timestamp) = $dbh->selectrow_array($query);
  2263. $rv =
  2264. "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
  2265. }
  2266. $rv;
  2267. }
  2268. 1;
  2269. =back