summaryrefslogtreecommitdiff
path: root/LedgerSMB/AA.pm
blob: 80d67a081472def24b5bcc17753fd5e5bee64ede (plain)
  1. #=====================================================================
  2. # LedgerSMB
  3. # Small Medium Business Accounting software
  4. # http://www.ledgersmb.org/
  5. # Copyright (C) 2006
  6. # This work contains copyrighted information from a number of sources all used
  7. # with permission.
  8. #
  9. # This file contains source code included with or based on SQL-Ledger which
  10. # is Copyright Dieter Simader and DWS Systems Inc. 2000-2005 and licensed
  11. # under the GNU General Public License version 2 or, at your option, any later
  12. # version. For a full list including contact information of contributors,
  13. # maintainers, and copyright holders, see the CONTRIBUTORS file.
  14. #
  15. # Original Copyright Notice from SQL-Ledger 2.6.17 (before the fork):
  16. # Copyright (C) 2006
  17. #
  18. # Author: DWS Systems Inc.
  19. # Web: http://www.sql-ledger.org
  20. #
  21. # Contributors:
  22. #
  23. #
  24. # See COPYRIGHT file for copyright information
  25. #======================================================================
  26. #
  27. # This file has undergone whitespace cleanup.
  28. #
  29. #======================================================================
  30. #
  31. # AR/AP backend routines
  32. # common routines
  33. #
  34. #======================================================================
  35. package AA;
  36. use LedgerSMB::Sysconfig;
  37. =pod
  38. =head1 post_transaction()
  39. Post transaction uses the following variables in the $form variable:
  40. * dbh - the database connection handle
  41. * currency - The current users' currency
  42. * defaultcurrency - The "normal" currency
  43. * department - Unknown
  44. * department_id - ID for the department
  45. * exchangerate - Conversion between currency and defaultcurrency
  46. * invnumber - invoice number
  47. * reverse - ?
  48. * rowcount - Number of rows in the invoice
  49. * taxaccounts - Apply taxes?
  50. * taxincluded - ?
  51. * transdate - Date of the transaction
  52. * vc - Vendor or customer - determines transaction type
  53. =cut
  54. sub post_transaction {
  55. my ( $self, $myconfig, $form ) = @_;
  56. for (1 .. $form->{rowcount}){
  57. $form->{"amount_$_"} = $form->parse_amount(
  58. $myconfig, $form->{"amount_$_"}
  59. );
  60. $form->{"amount_$_"} *= -1 if $form->{reverse};
  61. }
  62. # connect to database
  63. my $dbh = $form->{dbh};
  64. my $query;
  65. my $sth;
  66. my $null;
  67. ( $null, $form->{department_id} ) = split( /--/, $form->{department} );
  68. $form->{department_id} *= 1;
  69. my $ml = 1;
  70. my $table = 'ar';
  71. my $buysell = 'buy';
  72. my $ARAP = 'AR';
  73. my $invnumber = "sinumber";
  74. my $keepcleared;
  75. if ( $form->{vc} eq 'vendor' ) {
  76. $table = 'ap';
  77. $buysell = 'sell';
  78. $ARAP = 'AP';
  79. $ml = -1;
  80. $invnumber = "vinumber";
  81. }
  82. $form->{invnumber} = $form->update_defaults( $myconfig, $invnumber )
  83. unless $form->{invnumber};
  84. if ( $form->{currency} eq $form->{defaultcurrency} ) {
  85. $form->{exchangerate} = 1;
  86. }
  87. else {
  88. $exchangerate =
  89. $form->check_exchangerate( $myconfig, $form->{currency},
  90. $form->{transdate}, $buysell );
  91. $form->{exchangerate} =
  92. ($exchangerate)
  93. ? $exchangerate
  94. : $form->parse_amount( $myconfig, $form->{exchangerate} );
  95. }
  96. my @taxaccounts = split / /, $form->{taxaccounts};
  97. my $tax = 0;
  98. my $fxtax = 0;
  99. my $amount;
  100. my $diff;
  101. my %tax = ();
  102. my $accno;
  103. # add taxes
  104. foreach $accno (@taxaccounts) {
  105. $form->{"tax_$accno"} *= -1 if $form->{reverse};
  106. $fxtax += $tax{fxamount}{$accno} = $form->{"tax_$accno"};
  107. $tax += $tax{fxamount}{$accno};
  108. push @{ $form->{acc_trans}{taxes} },
  109. {
  110. accno => $accno,
  111. amount => $tax{fxamount}{$accno},
  112. project_id => undef,
  113. fx_transaction => 0
  114. };
  115. $amount = $tax{fxamount}{$accno} * $form->{exchangerate};
  116. $tax{amount}{$accno} = $form->round_amount( $amount - $diff, 2 );
  117. $diff = $tax{amount}{$accno} - ( $amount - $diff );
  118. $amount = $tax{amount}{$accno} - $tax{fxamount}{$accno};
  119. $tax += $amount;
  120. if ( $form->{currency} ne $form->{defaultcurrency} ) {
  121. push @{ $form->{acc_trans}{taxes} },
  122. {
  123. accno => $accno,
  124. amount => $amount,
  125. project_id => undef,
  126. fx_transaction => 1
  127. };
  128. }
  129. }
  130. my %amount = ();
  131. my $fxinvamount = 0;
  132. for ( 1 .. $form->{rowcount} ) {
  133. $fxinvamount += $amount{fxamount}{$_} = $form->{"amount_$_"};
  134. }
  135. $form->{taxincluded} *= 1;
  136. my $i;
  137. my $project_id;
  138. my $cleared = 0;
  139. $diff = 0;
  140. # deduct tax from amounts if tax included
  141. for $i ( 1 .. $form->{rowcount} ) {
  142. if ( $amount{fxamount}{$i} ) {
  143. if ( $form->{taxincluded} ) {
  144. $amount =
  145. ($fxinvamount)
  146. ? $fxtax * $amount{fxamount}{$i} / $fxinvamount
  147. : 0;
  148. $amount{fxamount}{$i} -= $amount;
  149. }
  150. # multiply by exchangerate
  151. $amount = $amount{fxamount}{$i} * $form->{exchangerate};
  152. $amount{amount}{$i} = $form->round_amount( $amount - $diff, 2 );
  153. $diff = $amount{amount}{$i} - ( $amount - $diff );
  154. ( $null, $project_id ) = split /--/, $form->{"projectnumber_$i"};
  155. $project_id ||= undef;
  156. ($accno) = split /--/, $form->{"${ARAP}_amount_$i"};
  157. if ($keepcleared) {
  158. $cleared = ( $form->{"cleared_$i"} ) ? 1 : 0;
  159. }
  160. push @{ $form->{acc_trans}{lineitems} },
  161. {
  162. accno => $accno,
  163. amount => $amount{fxamount}{$i},
  164. project_id => $project_id,
  165. description => $form->{"description_$i"},
  166. cleared => $cleared,
  167. fx_transaction => 0
  168. };
  169. if ( $form->{currency} ne $form->{defaultcurrency} ) {
  170. $amount = $amount{amount}{$i} - $amount{fxamount}{$i};
  171. push @{ $form->{acc_trans}{lineitems} },
  172. {
  173. accno => $accno,
  174. amount => $amount,
  175. project_id => $project_id,
  176. description => $form->{"description_$i"},
  177. cleared => $cleared,
  178. fx_transaction => 1
  179. };
  180. }
  181. }
  182. }
  183. my $invnetamount = 0;
  184. for ( @{ $form->{acc_trans}{lineitems} } ) { $invnetamount += $_->{amount} }
  185. my $invamount = $invnetamount + $tax;
  186. # adjust paidaccounts if there is no date in the last row
  187. $form->{paidaccounts}--
  188. unless ( $form->{"datepaid_$form->{paidaccounts}"} );
  189. if ( $form->{vc} ne "customer" ) {
  190. $form->{vc} = "vendor";
  191. }
  192. my $paid = 0;
  193. my $fxamount;
  194. $diff = 0;
  195. # add payments
  196. for $i ( 1 .. $form->{paidaccounts} ) {
  197. $form->{"paid_$i"} = $form->parse_amount(
  198. $myconfig, $form->{"paid_$i"}
  199. );
  200. $form->{"paid_$i"} *= -1 if $form->{reverse};
  201. $fxamount = $form->{"paid_$i"};
  202. if ($fxamount) {
  203. $paid += $fxamount;
  204. $paidamount = $fxamount * $form->{exchangerate};
  205. $amount = $form->round_amount( $paidamount - $diff, 2 );
  206. $diff = $amount - ( $paidamount - $diff );
  207. $form->{datepaid} = $form->{"datepaid_$i"};
  208. $paid{fxamount}{$i} = $fxamount;
  209. $paid{amount}{$i} = $amount;
  210. }
  211. }
  212. $fxinvamount += $fxtax unless $form->{taxincluded};
  213. $fxinvamount = $form->round_amount( $fxinvamount, 2 );
  214. $invamount = $form->round_amount( $invamount, 2 );
  215. $paid = $form->round_amount( $paid, 2 );
  216. $paid =
  217. ( $fxinvamount == $paid )
  218. ? $invamount
  219. : $form->round_amount( $paid * $form->{exchangerate}, 2 );
  220. $query = q|
  221. SELECT (SELECT value FROM defaults
  222. WHERE setting_key = 'fxgain_accno_id'),
  223. (SELECT value FROM defaults
  224. WHERE setting_key = 'fxloss_accno_id')|;
  225. my ( $fxgain_accno_id, $fxloss_accno_id ) = $dbh->selectrow_array($query);
  226. ( $null, $form->{employee_id} ) = split /--/, $form->{employee};
  227. unless ( $form->{employee_id} ) {
  228. ( $form->{employee}, $form->{employee_id} ) = $form->get_employee($dbh);
  229. }
  230. # check if id really exists
  231. if ( $form->{id} ) {
  232. my $id = $dbh->quote( $form->{id} );
  233. $keepcleared = 1;
  234. $query = qq|
  235. SELECT id
  236. FROM $table
  237. WHERE id = $id|;
  238. if ( $dbh->selectrow_array($query) ) {
  239. # delete detail records
  240. $query = qq|
  241. DELETE FROM acc_trans
  242. WHERE trans_id = $id|;
  243. $dbh->do($query) || $form->dberror($query);
  244. }
  245. }
  246. else {
  247. my $uid = localtime;
  248. $uid .= "$$";
  249. # The query is done like this as the login name maps to the users table
  250. # which maps to the user conf table, which links to an entity, to which
  251. # a person is also attached. This is done in this fashion because we
  252. # are using the current username as the "person" inserting the new
  253. # AR/AP Transaction.
  254. # ~A
  255. $query = qq|
  256. INSERT INTO $table (invnumber, person_id)
  257. VALUES (?, (select p.id from person p, entity e, users u
  258. where u.username = ?
  259. AND e.id = u.entity_id
  260. AND p.entity_id = e.id ))|;
  261. # the second param is undef, as the DBI api expects a hashref of
  262. # attributes to pass to $dbh->prepare. This is not used here.
  263. # ~A
  264. $dbh->do($query,undef,$uid,$form->{login}) || $form->dberror($query);
  265. $query = qq|
  266. SELECT id FROM $table
  267. WHERE invnumber = ?|;
  268. ( $form->{id} ) = $dbh->selectrow_array($query,undef,$uid);
  269. }
  270. # record last payment date in ar/ap table
  271. $form->{datepaid} = $form->{transdate} unless $form->{datepaid};
  272. my $datepaid = ($paid) ? qq|'$form->{datepaid}'| : 'NOW';
  273. $query = qq|
  274. UPDATE $table
  275. SET invnumber = ?,
  276. ordnumber = ?,
  277. transdate = ?,
  278. entity_credit_account = ?,
  279. taxincluded = ?,
  280. amount = ?,
  281. duedate = ?,
  282. paid = ?,
  283. datepaid = ?,
  284. netamount = ?,
  285. curr = ?,
  286. notes = ?,
  287. department_id = ?,
  288. ponumber = ?
  289. WHERE id = ?
  290. |;
  291. my @queryargs = (
  292. $form->{invnumber}, $form->{ordnumber},
  293. $form->{transdate}, $form->{"$form->{vc}_id"},
  294. $form->{taxincluded}, $invamount,
  295. $form->{duedate}, $paid,
  296. $datepaid, $invnetamout,
  297. $form->{currency}, $form->{notes},
  298. $form->{department_id},
  299. $form->{ponumber}, $form->{id}
  300. );
  301. $dbh->prepare($query)->execute(@queryargs) || $form->dberror($query);
  302. if (defined $form->{approved}) {
  303. $query = qq| UPDATE $table SET approved = ? WHERE id = ?|;
  304. $dbh->prepare($query)->execute($form->{approved}, $form->{id}) ||
  305. $form->dberror($query);
  306. if (!$form->{approved}){
  307. if (not defined $form->{batch_id}){
  308. $form->error($locale->text('Batch ID Missing'));
  309. }
  310. if ($form->{arap} eq 'ar'){
  311. $batch_class = 'receivable';
  312. } else {
  313. $batch_class = 'payable';
  314. }
  315. $query = qq|
  316. INSERT INTO voucher (batch_id, trans_id, batch_class)
  317. VALUES (?, ?, (select id from batch_class where class = ?))|;
  318. $dbh->prepare($query)->execute($form->{batch_id}, $form->{id},
  319. $batch_class) || $form->dberror($query);
  320. }
  321. }
  322. @queries = $form->run_custom_queries( $table, 'INSERT' );
  323. # update exchangerate
  324. my $buy = $form->{exchangerate};
  325. my $sell = 0;
  326. if ( $form->{vc} eq 'vendor' ) {
  327. $buy = 0;
  328. $sell = $form->{exchangerate};
  329. }
  330. if ( ( $form->{currency} ne $form->{defaultcurrency} ) && !$exchangerate ) {
  331. $form->update_exchangerate( $dbh, $form->{currency}, $form->{transdate},
  332. $buy, $sell );
  333. }
  334. my $ref;
  335. # add individual transactions
  336. foreach $ref ( @{ $form->{acc_trans}{lineitems} } ) {
  337. # insert detail records in acc_trans
  338. if ( $ref->{amount} ) {
  339. $query = qq|
  340. INSERT INTO acc_trans
  341. (trans_id, chart_id, amount,
  342. transdate, project_id, memo,
  343. fx_transaction, cleared)
  344. VALUES (?, (SELECT id FROM chart
  345. WHERE accno = ?),
  346. ?, ?, ?, ?, ?, ?)|;
  347. @queryargs = (
  348. $form->{id}, $ref->{accno},
  349. $ref->{amount} * $ml, $form->{transdate},
  350. $ref->{project_id}, $ref->{description},
  351. $ref->{fx_transaction}, $ref->{cleared}
  352. );
  353. $dbh->prepare($query)->execute(@queryargs)
  354. || $form->dberror($query);
  355. }
  356. }
  357. # save taxes
  358. foreach $ref ( @{ $form->{acc_trans}{taxes} } ) {
  359. if ( $ref->{amount} ) {
  360. $query = qq|
  361. INSERT INTO acc_trans
  362. (trans_id, chart_id, amount,
  363. transdate, fx_transaction)
  364. VALUES (?, (SELECT id FROM chart
  365. WHERE accno = ?),
  366. ?, ?, ?)|;
  367. @queryargs = (
  368. $form->{id}, $ref->{accno}, $ref->{amount} * $ml,
  369. $form->{transdate}, $ref->{fx_transaction}
  370. );
  371. $dbh->prepare($query)->execute(@queryargs)
  372. || $form->dberror($query);
  373. }
  374. }
  375. my $arap;
  376. # record ar/ap
  377. if ( ( $arap = $invamount ) ) {
  378. ($accno) = split /--/, $form->{$ARAP};
  379. $query = qq|
  380. INSERT INTO acc_trans
  381. (trans_id, chart_id, amount, transdate)
  382. VALUES (?, (SELECT id FROM chart
  383. WHERE accno = ?),
  384. ?, ?)|;
  385. @queryargs =
  386. ( $form->{id}, $accno, $invamount * -1 * $ml, $form->{transdate} );
  387. $dbh->prepare($query)->execute(@queryargs)
  388. || $form->dberror($query);
  389. }
  390. # if there is no amount force ar/ap
  391. if ( $fxinvamount == 0 ) {
  392. $arap = 1;
  393. }
  394. my $exchangerate;
  395. # add paid transactions
  396. for $i ( 1 .. $form->{paidaccounts} ) {
  397. if ( $paid{fxamount}{$i} ) {
  398. ($accno) = split( /--/, $form->{"${ARAP}_paid_$i"} );
  399. $form->{"datepaid_$i"} = $form->{transdate}
  400. unless ( $form->{"datepaid_$i"} );
  401. $exchangerate = 0;
  402. if ( $form->{currency} eq $form->{defaultcurrency} ) {
  403. $form->{"exchangerate_$i"} = 1;
  404. }
  405. else {
  406. $exchangerate =
  407. $form->check_exchangerate( $myconfig, $form->{currency},
  408. $form->{"datepaid_$i"}, $buysell );
  409. $form->{"exchangerate_$i"} =
  410. ($exchangerate)
  411. ? $exchangerate
  412. : $form->parse_amount( $myconfig,
  413. $form->{"exchangerate_$i"} );
  414. }
  415. # if there is no amount
  416. if ( $fxinvamount == 0 ) {
  417. $form->{exchangerate} = $form->{"exchangerate_$i"};
  418. }
  419. # ar/ap amount
  420. if ($arap) {
  421. ($accno) = split /--/, $form->{$ARAP};
  422. # add ar/ap
  423. $query = qq|
  424. INSERT INTO acc_trans
  425. (trans_id, chart_id,
  426. amount,transdate)
  427. VALUES (?, (SELECT id FROM chart
  428. WHERE accno = ?),
  429. ?, ?)|;
  430. @queryargs = (
  431. $form->{id}, $accno,
  432. $paid{amount}{$i} * $ml,
  433. $form->{"datepaid_$i"}
  434. );
  435. $dbh->prepare($query)->execute(@queryargs)
  436. || $form->dberror($query);
  437. }
  438. $arap = $paid{amount}{$i};
  439. # add payment
  440. if ( $paid{fxamount}{$i} ) {
  441. ($accno) = split /--/, $form->{"${ARAP}_paid_$i"};
  442. my $cleared = ( $form->{"cleared_$i"} ) ? 1 : 0;
  443. $amount = $paid{fxamount}{$i};
  444. $query = qq|
  445. INSERT INTO acc_trans
  446. (trans_id, chart_id, amount,
  447. transdate, source, memo,
  448. cleared)
  449. VALUES (?, (SELECT id FROM chart
  450. WHERE accno = ?),
  451. ?, ?, ?, ?, ?)|;
  452. @queryargs = (
  453. $form->{id}, $accno,
  454. $amount * -1 * $ml, $form->{"datepaid_$i"},
  455. $form->{"source_$i"}, $form->{"memo_$i"},
  456. $cleared
  457. );
  458. $dbh->prepare($query)->execute(@queryargs)
  459. || $form->dberror($query);
  460. if ( $form->{currency} ne $form->{defaultcurrency} ) {
  461. # exchangerate gain/loss
  462. $amount = (
  463. $form->round_amount(
  464. $paid{fxamount}{$i} * $form->{exchangerate}, 2 ) -
  465. $form->round_amount(
  466. $paid{fxamount}{$i} * $form->{"exchangerate_$i"}, 2
  467. )
  468. ) * -1;
  469. if ($amount) {
  470. my $accno_id =
  471. ( ( $amount * $ml ) > 0 )
  472. ? $fxgain_accno_id
  473. : $fxloss_accno_id;
  474. $query = qq|
  475. INSERT INTO acc_trans
  476. (trans_id,
  477. chart_id,
  478. amount,
  479. transdate,
  480. fx_transaction,
  481. cleared)
  482. VALUES (?, ?,
  483. ?,
  484. ?, '1', ?)|;
  485. @queryargs = (
  486. $form->{id}, $accno_id,
  487. $amount * $ml,
  488. $form->{"datepaid_$i"}, $cleared
  489. );
  490. $sth = $dbh->prepare($query);
  491. $sth->execute(@queryargs)
  492. || $form->dberror($query);
  493. }
  494. # exchangerate difference
  495. $amount = $paid{amount}{$i} - $paid{fxamount}{$i} + $amount;
  496. $query = qq|
  497. INSERT INTO acc_trans
  498. (trans_id, chart_id,
  499. amount,
  500. transdate,
  501. fx_transaction,
  502. cleared, source)
  503. VALUES (?, (SELECT id
  504. FROM chart
  505. WHERE accno
  506. = ?),
  507. ?, ?,
  508. '1', ?, ?)|;
  509. @queryargs = (
  510. $form->{id}, $accno,
  511. $amount * -1 * $ml,
  512. $form->{"datepaid_$i"},
  513. $cleared, $form->{"source_$i"}
  514. );
  515. $sth = $dbh->prepare($query);
  516. $sth->execute(@queryargs)
  517. || $form->dberror($query);
  518. }
  519. # update exchangerate record
  520. $buy = $form->{"exchangerate_$i"};
  521. $sell = 0;
  522. if ( $form->{vc} eq 'vendor' ) {
  523. $buy = 0;
  524. $sell = $form->{"exchangerate_$i"};
  525. }
  526. if ( ( $form->{currency} ne $form->{defaultcurrency} )
  527. && !$exchangerate )
  528. {
  529. $form->update_exchangerate( $dbh, $form->{currency},
  530. $form->{"datepaid_$i"},
  531. $buy, $sell );
  532. }
  533. }
  534. }
  535. }
  536. # save printed and queued
  537. $form->save_status($dbh);
  538. my %audittrail = (
  539. tablename => $table,
  540. reference => $form->{invnumber},
  541. formname => 'transaction',
  542. action => 'posted',
  543. id => $form->{id}
  544. );
  545. $form->audittrail( $dbh, "", \%audittrail );
  546. $form->save_recurring( $dbh, $myconfig );
  547. my $rc = $dbh->commit;
  548. $rc;
  549. }
  550. sub delete_transaction {
  551. my ( $self, $myconfig, $form ) = @_;
  552. # connect to database, turn AutoCommit off
  553. my $dbh = $form->{dbh};
  554. my $table = ( $form->{vc} eq 'customer' ) ? 'ar' : 'ap';
  555. my %audittrail = (
  556. tablename => $table,
  557. reference => $form->{invnumber},
  558. formname => 'transaction',
  559. action => 'deleted',
  560. id => $form->{id}
  561. );
  562. $form->audittrail( $dbh, "", \%audittrail );
  563. my $query = qq|DELETE FROM $table WHERE id = $form->{id}|;
  564. $dbh->do($query) || $form->dberror($query);
  565. $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
  566. $dbh->prepare($query)->execute( $form->{id} ) || $form->dberror($query);
  567. # get spool files
  568. $query = qq|SELECT spoolfile
  569. FROM status
  570. WHERE trans_id = ?
  571. AND spoolfile IS NOT NULL|;
  572. my $sth = $dbh->prepare($query);
  573. $sth->execute( $form->{id} ) || $form->dberror($query);
  574. my $spoolfile;
  575. my @spoolfiles = ();
  576. while ( ($spoolfile) = $sth->fetchrow_array ) {
  577. push @spoolfiles, $spoolfile;
  578. }
  579. $sth->finish;
  580. $query = qq|DELETE FROM status WHERE trans_id = ?|;
  581. $dbh->prepare($query)->execute( $form->{id} ) || $form->dberror($query);
  582. # commit
  583. my $rc = $dbh->commit;
  584. if ($rc) {
  585. foreach $spoolfile (@spoolfiles) {
  586. unlink "${LedgerSMB::Sysconfig::spool}/$spoolfile" if $spoolfile;
  587. }
  588. }
  589. $rc;
  590. }
  591. # This is going to get a little awkward because it involves delving into the
  592. # acc_trans table in order to avoid catching unapproved payment vouchers.
  593. sub transactions {
  594. my ( $self, $myconfig, $form ) = @_;
  595. # connect to database
  596. my $dbh = $form->{dbh};
  597. my $null;
  598. my $var;
  599. my $paid = "a.paid";
  600. my $ml = 1;
  601. my $ARAP = 'AR';
  602. my $table = 'ar';
  603. my $buysell = 'buy';
  604. my $acc_trans_join;
  605. my $acc_trans_flds;
  606. my $approved = ($form->{approved}) ? 'TRUE' : 'FALSE';
  607. if ( $form->{vc} eq 'vendor' ) {
  608. $ml = -1;
  609. $ARAP = 'AP';
  610. $table = 'ap';
  611. $buysell = 'sell';
  612. }
  613. $form->{db_dateformat} = $myconfig->{dateformat};
  614. ( $form->{transdatefrom}, $form->{transdateto} ) =
  615. $form->from_to( $form->{year}, $form->{month}, $form->{interval} )
  616. if (($form->{year} && $form->{month}) &&
  617. (!$form->{transdatefrom} && !$form->{transdateto}));
  618. my @paidargs = ();
  619. if ( $form->{outstanding} ) {
  620. $paid = qq|
  621. SELECT SUM(ac.amount) * -1 * $ml
  622. FROM acc_trans ac
  623. JOIN chart c ON (c.id = ac.chart_id)
  624. WHERE ac.trans_id = a.id
  625. AND ($approved OR ac.approved)
  626. AND (c.link LIKE '%${ARAP}_paid%'
  627. OR c.link = '')|;
  628. if ( $form->{transdateto} ) {
  629. $paid .= qq|
  630. AND ac.transdate <= ?|;
  631. # push @paidargs, $form->{transdateto};
  632. }
  633. $form->{summary} = 1;
  634. }
  635. if ( !$form->{summary} ) {
  636. $acc_trans_flds = qq|
  637. , c.accno, ac.source,
  638. pr.projectnumber, ac.memo AS description,
  639. ac.amount AS linetotal,
  640. i.description AS linedescription|;
  641. $acc_trans_join = qq|
  642. JOIN acc_trans ac ON (a.id = ac.trans_id)
  643. JOIN chart c ON (c.id = ac.chart_id)
  644. LEFT JOIN project pr ON (pr.id = ac.project_id)
  645. LEFT JOIN invoice i ON (i.id = ac.invoice_id)|;
  646. }
  647. my $query;
  648. if ($form->{outstanding}){
  649. # $form->{ARAP} is safe since it is set in calling scripts and not passed from the UA
  650. if ($form->{transdateto} eq ''){
  651. delete $form->{transdateto};
  652. }
  653. $query = qq|
  654. SELECT a.id, a.invnumber, a.ordnumber, a.transdate,
  655. a.duedate, a.netamount, a.amount, a.amount - sum(acs.amount) AS paid,
  656. a.invoice, a.datepaid, a.terms, a.notes,
  657. a.shipvia, a.shippingpoint,
  658. vce.name, vc.meta_number,
  659. a.entity_id, a.till,
  660. ex.$buysell AS exchangerate,
  661. d.description AS department,
  662. a.ponumber $acc_trans_fields
  663. FROM $table a
  664. JOIN entity_credit_account vc ON (a.entity_credit_account = vc.id)
  665. JOIN acc_trans acs ON (acs.trans_id = a.id)
  666. JOIN entity vce ON (vc.entity_id = vce.id)
  667. JOIN chart c ON (acs.chart_id = c.id)
  668. LEFT JOIN exchangerate ex ON (ex.curr = a.curr
  669. AND ex.transdate = a.transdate)
  670. LEFT JOIN department d ON (a.department_id = d.id)
  671. $acc_trans_join
  672. WHERE c.link = '$form->{ARAP}' AND
  673. (|.$dbh->quote($form->{transdateto}) . qq| IS NULL OR
  674. |.$dbh->quote($form->{transdateto}) . qq| >= acs.transdate)
  675. AND a.approved IS TRUE AND acs.approved IS TRUE
  676. GROUP BY a.id, a.invnumber, a.ordnumber, a.transdate, a.duedate, a.netamount,
  677. a.amount, a.terms, a.notes, a.shipvia, a.shippingpoint, vce.name,
  678. vc.meta_number, a.entity_id, a.till, ex.$buysell, d.description,
  679. a.ponumber, a.invoice, a.datepaid $acc_trans_fields
  680. HAVING abs(a.amount - (a.amount - sum(acs.amount))) > 0.005 |;
  681. } else {
  682. $query = qq|
  683. SELECT a.id, a.invnumber, a.ordnumber, a.transdate,
  684. a.duedate, a.netamount, a.amount, ($paid) AS paid,
  685. a.invoice, a.datepaid, a.terms, a.notes,
  686. a.shipvia, a.shippingpoint, ee.name AS employee,
  687. vce.name, vc.meta_number,
  688. a.entity_id, a.till, me.name AS manager, a.curr,
  689. ex.$buysell AS exchangerate,
  690. d.description AS department,
  691. a.ponumber $acc_trans_flds
  692. FROM $table a
  693. JOIN entity_credit_account vc ON (a.entity_credit_account = vc.id)
  694. JOIN employee e ON (a.person_id = e.entity_id)
  695. LEFT JOIN employee m ON (e.manager_id = m.entity_id)
  696. JOIN entity ee ON (e.entity_id = ee.id)
  697. LEFT JOIN entity me ON (m.entity_id = me.id)
  698. JOIN entity vce ON (vc.entity_id = vce.id)
  699. LEFT JOIN exchangerate ex ON (ex.curr = a.curr
  700. AND ex.transdate = a.transdate)
  701. LEFT JOIN department d ON (a.department_id = d.id)
  702. $acc_trans_join|;
  703. }
  704. my %ordinal = (
  705. id => 1,
  706. invnumber => 2,
  707. ordnumber => 3,
  708. transdate => 4,
  709. duedate => 5,
  710. datepaid => 10,
  711. shipvia => 13,
  712. shippingpoint => 14,
  713. employee => 15,
  714. name => 16,
  715. manager => 20,
  716. curr => 21,
  717. department => 23,
  718. ponumber => 24,
  719. accno => 25,
  720. source => 26,
  721. project => 27,
  722. description => 28
  723. );
  724. my @a = ( transdate, invnumber, name );
  725. push @a, "employee" if $form->{l_employee};
  726. push @a, "manager" if $form->{l_manager};
  727. my $sortorder = $form->sort_order( \@a, \%ordinal );
  728. my $where = "";
  729. if (!$form->{outstanding}){
  730. $where = "1 = 1";
  731. }
  732. if ($form->{"meta_number"}){
  733. $where .= " AND vc.meta_number = " . $dbh->quote($form->{meta_number});
  734. }
  735. if ( $form->{"$form->{vc}_id"} ) {
  736. $form->{entity_id} = $form->{$form->{vc}."_id"};
  737. $where .= qq| AND a.entity_id = $form->{entity_id}|;
  738. }
  739. else {
  740. if ( $form->{ $form->{vc} } ) {
  741. $var = $dbh->quote( $form->like( lc $form->{ $form->{vc} } ) );
  742. $where .= " AND lower(vce.name) LIKE $var";
  743. }
  744. }
  745. for (qw(department employee)) {
  746. if ( $form->{$_} ) {
  747. ( $null, $var ) = split /--/, $form->{$_};
  748. $var = $dbh->quote($var);
  749. $where .= " AND a.${_}_id = $var";
  750. }
  751. }
  752. for (qw(invnumber ordnumber)) {
  753. if ( $form->{$_} ) {
  754. $var = $dbh->quote( $form->like( lc $form->{$_} ) );
  755. $where .= " AND lower(a.$_) LIKE $var";
  756. $form->{open} = $form->{closed} = 0;
  757. }
  758. }
  759. if ( $form->{partsid} ) {
  760. my $partsid = $dbh->quote( $form->{partsid} );
  761. $where .= " AND a.id IN (select trans_id FROM invoice
  762. WHERE parts_id = $partsid)";
  763. }
  764. for (qw(ponumber shipvia notes)) {
  765. if ( $form->{$_} ) {
  766. $var = $dbh->quote( $form->like( lc $form->{$_} ) );
  767. $where .= " AND lower(a.$_) LIKE $var";
  768. }
  769. }
  770. if ( $form->{description} ) {
  771. if ($acc_trans_flds) {
  772. $var = $dbh->quote( $form->like( lc $form->{description} ) );
  773. $where .= " AND lower(ac.memo) LIKE $var
  774. OR lower(i.description) LIKE $var";
  775. }
  776. else {
  777. $where .= " AND a.id = 0";
  778. }
  779. }
  780. if ( $form->{source} ) {
  781. if ($acc_trans_flds) {
  782. $var = $dbh->quote( $form->like( lc $form->{source} ) );
  783. $where .= " AND lower(ac.source) LIKE $var";
  784. }
  785. else {
  786. $where .= " AND a.id = 0";
  787. }
  788. }
  789. my $transdatefrom = $dbh->quote( $form->{transdatefrom} );
  790. $where .= " AND a.transdate >= $transdatefrom"
  791. if $form->{transdatefrom};
  792. my $transdateto = $dbh->quote( $form->{transdateto} );
  793. $where .= " AND a.transdate <= $transdateto" if $form->{transdateto};
  794. if ( $form->{open} || $form->{closed} ) {
  795. unless ( $form->{open} && $form->{closed} ) {
  796. $where .= " AND a.amount != a.paid" if ( $form->{open} );
  797. $where .= " AND a.amount = a.paid" if ( $form->{closed} );
  798. }
  799. }
  800. if ( $form->{till} ne "" ) {
  801. $where .= " AND a.invoice = '1'
  802. AND a.till = $form->{till}";
  803. if ( $myconfig->{role} eq 'user' ) {
  804. my $login = $dbh->quote( $form->{login} );
  805. $where .= " AND e.entity_id = (select entity_id from users where username = $login";
  806. }
  807. }
  808. if ( $form->{$ARAP} ) {
  809. my ($accno) = split /--/, $form->{$ARAP};
  810. $accno = $dbh->quote($accno);
  811. $where .= qq|
  812. AND a.id IN (SELECT ac.trans_id
  813. FROM acc_trans ac
  814. JOIN chart c ON (c.id = ac.chart_id)
  815. WHERE a.id = ac.trans_id
  816. AND c.accno = $accno)|;
  817. }
  818. if ( $form->{description} ) {
  819. $var = $dbh->quote( $form->like( lc $form->{description} ) );
  820. $where .= qq|
  821. AND (a.id IN (SELECT DISTINCT trans_id
  822. FROM acc_trans
  823. WHERE lower(memo) LIKE $var)
  824. OR a.id IN
  825. (SELECT DISTINCT trans_id
  826. FROM invoice
  827. WHERE lower(description)
  828. LIKE $var))|;
  829. }
  830. if ($form->{invoice_type}) {
  831. if ( $form->{invoice_type} == 2 ) {
  832. $where .= qq|
  833. AND a.on_hold = 'f'
  834. |;
  835. }
  836. if ($form->{invoice_type} == 3) {
  837. $where .= qq|
  838. AND a.on_hold = 't'
  839. |;
  840. }
  841. }
  842. # the third state, all invoices, sets no explicit toggles. It just selects them all, as normal.
  843. # $approved is safe as it is set to either "TRUE" or "FALSE"
  844. if ($form->{outstanding}){
  845. if ($where ne ""){
  846. $query =~ s/GROUP BY / $where \n GROUP BY /;
  847. }
  848. $query .= "\n ORDER BY $sortorder";
  849. } else {
  850. $query .= "WHERE ($approved OR a.approved) AND $where
  851. ORDER BY $sortorder";
  852. }
  853. my $sth = $dbh->prepare($query);
  854. $sth->execute(@paidargs) || $form->dberror($query);
  855. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  856. $form->db_parse_numeric(sth => $sth, hashref => $ref);
  857. $ref->{exchangerate} = 1 unless $ref->{exchangerate};
  858. if ( $ref->{linetotal} <= 0 ) {
  859. $ref->{debit} = $ref->{linetotal} * -1;
  860. $ref->{credit} = 0;
  861. }
  862. else {
  863. $ref->{debit} = 0;
  864. $ref->{credit} = $ref->{linetotal};
  865. }
  866. if ( $ref->{invoice} ) {
  867. $ref->{description} ||= $ref->{linedescription};
  868. }
  869. push @{ $form->{transactions} }, $ref;
  870. }
  871. $sth->finish;
  872. $dbh->commit;
  873. }
  874. # this is used in IS, IR to retrieve the name
  875. sub get_name {
  876. my ( $self, $myconfig, $form ) = @_;
  877. # sanitize $form->{vc}
  878. if ( $form->{vc} ne 'customer' ) {
  879. $form->{vc} = 'vendor';
  880. }
  881. else {
  882. $form->{vc} = 'customer';
  883. }
  884. # connect to database
  885. my $dbh = $form->{dbh};
  886. my $dateformat = $myconfig->{dateformat};
  887. if ( $myconfig->{dateformat} !~ /^y/ ) {
  888. my @a = split /\W/, $form->{transdate};
  889. $dateformat .= "yy" if ( length $a[2] > 2 );
  890. }
  891. if ( $form->{transdate} !~ /\W/ ) {
  892. $dateformat = 'yyyymmdd';
  893. }
  894. my $duedate;
  895. $dateformat = $dbh->quote($dateformat);
  896. my $tdate = $dbh->quote( $form->{transdate} );
  897. $duedate = ( $form->{transdate} )
  898. ? "to_date($tdate, $dateformat)
  899. + c.terms"
  900. : "current_date + c.terms";
  901. $form->{"$form->{vc}_id"} *= 1;
  902. # get customer/vendor
  903. my $query = qq|
  904. SELECT entity.name AS $form->{vc}, c.discount,
  905. c.creditlimit,
  906. c.terms, c.taxincluded,
  907. c.curr AS currency,
  908. c.language_code, $duedate AS duedate,
  909. b.discount AS tradediscount,
  910. b.description AS business
  911. FROM entity_credit_account c
  912. JOIN entity ON (entity.id = c.entity_id)
  913. LEFT JOIN business b ON (b.id = c.business_id)
  914. WHERE c.id = ?|;
  915. # TODO: Add location join
  916. @queryargs = ( $form->{"$form->{vc}_id"} );
  917. my $sth = $dbh->prepare($query);
  918. $sth->execute(@queryargs) || $form->dberror($query);
  919. $ref = $sth->fetchrow_hashref(NAME_lc);
  920. $form->db_parse_numeric(sth => $sth, hashref => $ref);
  921. if ( $form->{id} ) {
  922. for (qw(currency employee employee_id intnotes)) {
  923. delete $ref->{$_};
  924. }
  925. }
  926. for ( keys %$ref ) { $form->{$_} = $ref->{$_} }
  927. $sth->finish;
  928. # TODO: Retrieve contact records
  929. my $buysell = ( $form->{vc} eq 'customer' ) ? "buy" : "sell";
  930. # if no currency use defaultcurrency
  931. $form->{currency} =
  932. ( $form->{currency} )
  933. ? $form->{currency}
  934. : $form->{defaultcurrency};
  935. $form->{exchangerate} = 0
  936. if $form->{currency} eq $form->{defaultcurrency};
  937. if ( $form->{transdate}
  938. && ( $form->{currency} ne $form->{defaultcurrency} ) )
  939. {
  940. $form->{exchangerate} =
  941. $form->get_exchangerate( $dbh, $form->{currency}, $form->{transdate},
  942. $buysell );
  943. }
  944. $form->{forex} = $form->{exchangerate};
  945. # if no employee, default to login
  946. ( $form->{employee}, $form->{employee_id} ) = $form->get_employee($dbh)
  947. unless $form->{employee_id};
  948. my $arap = ( $form->{vc} eq 'customer' ) ? 'ar' : 'ap';
  949. my $ARAP = uc $arap;
  950. $form->{creditremaining} = $form->{creditlimit};
  951. $query = qq|
  952. SELECT SUM(amount - paid)
  953. FROM $arap
  954. WHERE id = ?|;
  955. $sth = $dbh->prepare($query);
  956. $sth->execute( $form->{"$form->{vc}_id"} )
  957. || $form->dberror($query);
  958. ( $form->{creditremaining} ) -= $sth->fetchrow_array;
  959. $sth->finish;
  960. if ( $form->{vc} ne "customer" ) {
  961. $form->{vc} = 'vendor';
  962. }
  963. $query = qq|
  964. SELECT o.amount, (SELECT e.$buysell FROM exchangerate e
  965. WHERE e.curr = o.curr
  966. AND e.transdate = o.transdate)
  967. FROM oe o
  968. WHERE o.entity_id =
  969. (select entity_id from $form->{vc} WHERE id = ?)
  970. AND o.quotation = '0' AND o.closed = '0'|;
  971. $sth = $dbh->prepare($query);
  972. $sth->execute( $form->{"$form->{vc}_id"} ) || $form->dberror($query);
  973. while ( my @ref = $sth->fetchrow_array ) {
  974. $form->db_parse_numeric(sth => $sth, arrayref => \@ref);
  975. my ($amount, $exch) = @ref;
  976. $exch = 1 unless $exch;
  977. $form->{creditremaining} -= $amount * $exch;
  978. }
  979. $sth->finish;
  980. # get shipto if we did not converted an order or invoice
  981. if ( !$form->{shipto} ) {
  982. for (
  983. qw(shiptoname shiptoaddress1 shiptoaddress2
  984. shiptocity shiptostate shiptozipcode
  985. shiptocountry shiptocontact shiptophone
  986. shiptofax shiptoemail)
  987. )
  988. {
  989. delete $form->{$_};
  990. }
  991. ## needs fixing (SELECT *)
  992. $query = qq|
  993. SELECT *
  994. FROM shipto
  995. WHERE trans_id = $form->{"$form->{vc}_id"}|;
  996. $sth = $dbh->prepare($query);
  997. $sth->execute || $form->dberror($query);
  998. $ref = $sth->fetchrow_hashref(NAME_lc);
  999. for ( keys %$ref ) { $form->{$_} = $ref->{$_} }
  1000. $sth->finish;
  1001. }
  1002. # get taxes
  1003. $query = qq|
  1004. SELECT c.accno
  1005. FROM chart c
  1006. JOIN $form->{vc}tax ct ON (ct.chart_id = c.id)
  1007. WHERE ct.$form->{vc}_id = ?|;
  1008. $sth = $dbh->prepare($query);
  1009. $sth->execute( $form->{"$form->{vc}_id"} ) || $form->dberror($query);
  1010. my %tax;
  1011. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1012. $tax{ $ref->{accno} } = 1;
  1013. }
  1014. $sth->finish;
  1015. $transdate = $dbh->quote( $form->{transdate} );
  1016. my $where = qq|AND (t.validto >= $transdate OR t.validto IS NULL)|
  1017. if $form->{transdate};
  1018. # get tax rates and description
  1019. $query = qq|
  1020. SELECT c.accno, c.description, t.rate, t.taxnumber
  1021. FROM chart c
  1022. JOIN tax t ON (c.id = t.chart_id)
  1023. WHERE c.link LIKE '%${ARAP}_tax%'
  1024. $where
  1025. ORDER BY accno, validto|;
  1026. $sth = $dbh->prepare($query);
  1027. $sth->execute || $form->dberror($query);
  1028. $form->{taxaccounts} = "";
  1029. my %a = ();
  1030. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1031. $form->db_parse_numeric(sth => $sth, hashref => $hashref);
  1032. if ( $tax{ $ref->{accno} } ) {
  1033. if ( not exists $a{ $ref->{accno} } ) {
  1034. for (qw(rate description taxnumber)) {
  1035. $form->{"$ref->{accno}_$_"} = $ref->{$_};
  1036. }
  1037. $form->{taxaccounts} .= "$ref->{accno} ";
  1038. $a{ $ref->{accno} } = 1;
  1039. }
  1040. }
  1041. }
  1042. $sth->finish;
  1043. chop $form->{taxaccounts};
  1044. # setup last accounts used for this customer/vendor
  1045. if ( !$form->{id} && $form->{type} !~ /_(order|quotation)/ ) {
  1046. $query = qq|
  1047. SELECT c.accno, c.description, c.link,
  1048. c.category,
  1049. ac.project_id,
  1050. a.department_id
  1051. FROM chart c
  1052. JOIN acc_trans ac ON (ac.chart_id = c.id)
  1053. JOIN $arap a ON (a.id = ac.trans_id)
  1054. WHERE a.entity_id = ?
  1055. AND a.id = (SELECT max(id)
  1056. FROM $arap
  1057. WHERE entity_id =
  1058. ?)
  1059. |;
  1060. $sth = $dbh->prepare($query);
  1061. $sth->execute( $form->{"$form->{vc}_id"}, $form->{"$form->{vc}_id"} )
  1062. || $form->dberror($query);
  1063. my $i = 0;
  1064. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1065. $form->{department_id} = $ref->{department_id};
  1066. if ( $ref->{link} =~ /_amount/ ) {
  1067. $i++;
  1068. $form->{"$form->{ARAP}_amount_$i"} =
  1069. "$ref->{accno}--$ref->{description}"
  1070. if $ref->{accno};
  1071. $form->{"projectnumber_$i"} =
  1072. "$ref->{projectnumber}--" . "$ref->{project_id}"
  1073. if $ref->{project_id};
  1074. }
  1075. if ( $ref->{link} eq $form->{ARAP} ) {
  1076. $form->{ $form->{ARAP} } = $form->{"$form->{ARAP}_1"} =
  1077. "$ref->{accno}--" . "$ref->{description}"
  1078. if $ref->{accno};
  1079. }
  1080. }
  1081. $sth->finish;
  1082. $query = "select description from department where id = ?";
  1083. $sth = $dbh->prepare($query);
  1084. $sth->execute($form->{department_id});
  1085. ($form->{department}) = $sth->fetchrow_array;
  1086. $form->{rowcount} = $i if ( $i && !$form->{type} );
  1087. }
  1088. $dbh->commit;
  1089. }
  1090. 1;