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