summaryrefslogtreecommitdiff
path: root/LedgerSMB/IR.pm
blob: 2f799975d0c0f251806539d45b2b86d5448750b6 (plain)
  1. #=====================================================================
  2. # LedgerSMB
  3. # Small Medium Business Accounting software
  4. # http://www.ledgersmb.org/
  5. #
  6. # Copyright (C) 2006
  7. # This work contains copyrighted information from a number of sources all used
  8. # with permission.
  9. #
  10. # This file contains source code included with or based on SQL-Ledger which
  11. # is Copyright Dieter Simader and DWS Systems Inc. 2000-2005 and licensed
  12. # under the GNU General Public License version 2 or, at your option, any later
  13. # version. For a full list including contact information of contributors,
  14. # maintainers, and copyright holders, see the CONTRIBUTORS file.
  15. #
  16. # Original Copyright Notice from SQL-Ledger 2.6.17 (before the fork):
  17. # Copyright (C) 2000
  18. #
  19. # Author: DWS Systems Inc.
  20. # Web: http://www.sql-ledger.org
  21. #
  22. # Contributors: Jim Rawlings <jim@your-dba.com>
  23. #
  24. #======================================================================
  25. #
  26. # This file has undergone whitespace cleanup.
  27. #
  28. #======================================================================
  29. #
  30. # Inventory received module
  31. #
  32. #======================================================================
  33. package IR;
  34. use LedgerSMB::Tax;
  35. use LedgerSMB::PriceMatrix;
  36. use LedgerSMB::Sysconfig;
  37. use Math::BigFloat;
  38. sub post_invoice {
  39. my ( $self, $myconfig, $form ) = @_;
  40. my $dbh = $form->{dbh};
  41. $form->{invnumber} = $form->update_defaults( $myconfig, "vinumber", $dbh )
  42. unless $form->{invnumber};
  43. for ( 1 .. $form->{rowcount} ) {
  44. unless ( $form->{"deliverydate_$_"} ) {
  45. $form->{"deliverydate_$_"} = $form->{transdate};
  46. }
  47. }
  48. my $query;
  49. my $sth;
  50. my $ref;
  51. my $null;
  52. my $project_id;
  53. my $exchangerate = 0;
  54. my $allocated;
  55. my $taxrate;
  56. my $taxamount;
  57. my $diff = 0;
  58. my $item;
  59. my $invoice_id;
  60. my $keepcleared;
  61. ( $null, $form->{employee_id} ) = split /--/, $form->{employee};
  62. unless ( $form->{employee_id} ) {
  63. ( $form->{employee}, $form->{employee_id} ) = $form->get_employee($dbh);
  64. }
  65. ( $null, $form->{department_id} ) = split( /--/, $form->{department} );
  66. $form->{department_id} *= 1;
  67. $query = qq|
  68. SELECT (SELECT value FROM defaults
  69. WHERE setting_key = 'fxgain_accno_id')
  70. AS fxgain_accno_id,
  71. (SELECT value FROM defaults
  72. WHERE setting_key = 'fxloss_accno_id')
  73. AS fxloss_accno_id|;
  74. my ( $fxgain_accno_id, $fxloss_accno_id ) = $dbh->selectrow_array($query);
  75. $query = qq|
  76. SELECT inventory_accno_id, income_accno_id, expense_accno_id
  77. FROM parts
  78. WHERE id = ?|;
  79. my $pth = $dbh->prepare($query) || $form->dberror($query);
  80. my %updparts = ();
  81. if ( $form->{id} ) {
  82. my $sth;
  83. $keepcleared = 1;
  84. $query = qq|SELECT id FROM ap WHERE id = ?|;
  85. $sth = $dbh->prepare($query);
  86. $sth->execute( $form->{id} );
  87. if ( $sth->fetchrow_array ) {
  88. $query = qq|
  89. SELECT p.id, p.inventory_accno_id,
  90. p.income_accno_id
  91. FROM invoice i
  92. JOIN parts p ON (p.id = i.parts_id)
  93. WHERE i.trans_id = ?|;
  94. $sth = $dbh->prepare($query);
  95. $sth->execute( $form->{id} ) || $form->dberror($query);
  96. while ( $ref = $sth->fetchrow_hashref ) {
  97. if ( $ref->{inventory_accno_id}
  98. && $ref->{income_accno_id} )
  99. {
  100. $updparts{ $ref->{id} } = 1;
  101. }
  102. }
  103. $sth->finish;
  104. &reverse_invoice( $dbh, $form );
  105. }
  106. else {
  107. $query = qq|INSERT INTO ap (id) VALUES (?)|;
  108. $sth = $dbh->prepare($query);
  109. $sth->execute( $form->{id} ) || $form->dberror($query);
  110. }
  111. }
  112. my $uid = localtime;
  113. $uid .= "$$";
  114. if ( !$form->{id} ) {
  115. $query = qq|
  116. INSERT INTO ap (invnumber, employee_id)
  117. VALUES ('$uid', (SELECT id FROM employee
  118. WHERE login = ?))|;
  119. $sth = $dbh->prepare($query);
  120. $sth->execute( $form->{login} ) || $form->dberror($query);
  121. $query = qq|SELECT id FROM ap WHERE invnumber = '$uid'|;
  122. $sth = $dbh->prepare($query);
  123. $sth->execute || $form->dberror($query);
  124. ( $form->{id} ) = $sth->fetchrow_array;
  125. $sth->finish;
  126. }
  127. my $amount;
  128. my $grossamount;
  129. my $allocated;
  130. my $invamount = 0;
  131. my $invnetamount = 0;
  132. if ( $form->{currency} eq $form->{defaultcurrency} ) {
  133. $form->{exchangerate} = 1;
  134. }
  135. else {
  136. $exchangerate =
  137. $form->check_exchangerate( $myconfig, $form->{currency},
  138. $form->{transdate}, 'sell' );
  139. }
  140. $form->{exchangerate} =
  141. ($exchangerate)
  142. ? $exchangerate
  143. : $form->parse_amount( $myconfig, $form->{exchangerate} );
  144. for my $i ( 1 .. $form->{rowcount} ) {
  145. $form->{"qty_$i"} = $form->parse_amount( $myconfig, $form->{"qty_$i"} );
  146. if ( $form->{"qty_$i"} ) {
  147. $pth->execute( $form->{"id_$i"} );
  148. $ref = $pth->fetchrow_hashref(NAME_lc);
  149. for ( keys %$ref ) {
  150. $form->{"${_}_$i"} = $ref->{$_};
  151. }
  152. $pth->finish;
  153. # project
  154. if ( $form->{"projectnumber_$i"} ne "" ) {
  155. ( $null, $project_id ) =
  156. split /--/, $form->{"projectnumber_$i"};
  157. }
  158. # undo discount formatting
  159. $form->{"discount_$i"} =
  160. $form->parse_amount( $myconfig, $form->{"discount_$i"} ) / 100;
  161. # keep entered selling price
  162. my $fxsellprice =
  163. $form->parse_amount( $myconfig, $form->{"sellprice_$i"} );
  164. my ($dec) = ( $fxsellprice =~ /\.(\d+)/ );
  165. $dec = length $dec;
  166. my $decimalplaces = ( $dec > 2 ) ? $dec : 2;
  167. # deduct discount
  168. $form->{"sellprice_$i"} = $fxsellprice -
  169. $form->round_amount( $fxsellprice * $form->{"discount_$i"},
  170. $decimalplaces );
  171. # linetotal
  172. my $fxlinetotal =
  173. $form->round_amount( $form->{"sellprice_$i"} * $form->{"qty_$i"},
  174. 2 );
  175. $amount = $fxlinetotal * $form->{exchangerate};
  176. my $linetotal = $form->round_amount( $amount, 2 );
  177. $fxdiff += $amount - $linetotal;
  178. @taxaccounts = Tax::init_taxes(
  179. $form,
  180. $form->{"taxaccounts_$i"},
  181. $form->{'taxaccounts'}
  182. );
  183. $tax = Math::BigFloat->bzero();
  184. $fxtax = Math::BigFloat->bzero();
  185. if ( $form->{taxincluded} ) {
  186. $tax += $amount =
  187. Tax::calculate_taxes( \@taxaccounts, $form, $linetotal, 1 );
  188. $form->{"sellprice_$i"} -= $amount / $form->{"qty_$i"};
  189. }
  190. else {
  191. $tax += $amount =
  192. Tax::calculate_taxes( \@taxaccounts, $form, $linetotal, 0 );
  193. $fxtax +=
  194. Tax::calculate_taxes( \@taxaccounts, $form, $fxlinetotal, 0 );
  195. }
  196. for (@taxaccounts) {
  197. $form->{acc_trans}{ $form->{id} }{ $_->account }{amount} +=
  198. $_->value;
  199. }
  200. $grossamount = $form->round_amount( $linetotal, 2 );
  201. if ( $form->{taxincluded} ) {
  202. $amount = $form->round_amount( $tax, 2 );
  203. $linetotal -= $form->round_amount( $tax - $diff, 2 );
  204. $diff = ( $amount - $tax );
  205. }
  206. $amount = $form->round_amount( $linetotal, 2 );
  207. $allocated = 0;
  208. # adjust and round sellprice
  209. $form->{"sellprice_$i"} =
  210. $form->round_amount(
  211. $form->{"sellprice_$i"} * $form->{exchangerate},
  212. $decimalplaces );
  213. # save detail record in invoice table
  214. $query = qq|
  215. INSERT INTO invoice (description)
  216. VALUES ('$uid')|;
  217. $dbh->do($query) || $form->dberror($query);
  218. $query = qq|
  219. SELECT id FROM invoice
  220. WHERE description = '$uid'|;
  221. ($invoice_id) = $dbh->selectrow_array($query);
  222. if ( $form->{"inventory_accno_id_$i"} ) {
  223. #start patch bug 1749690 ###########################################################################################################
  224. # if this is a exit for the product
  225. if($form->{"qty_$i"}<0) {
  226. # check for unallocated entries at the same price to match our entry
  227. $query = qq|
  228. SELECT i.id, i.qty, i.allocated, a.transdate
  229. FROM invoice i
  230. JOIN parts p ON (p.id = i.parts_id)
  231. JOIN ap a ON (a.id = i.trans_id)
  232. WHERE i.parts_id = ? AND (i.qty + i.allocated) < 0 AND i.sellprice = ?
  233. ORDER BY transdate
  234. |;
  235. $sth = $dbh->prepare($query);
  236. $sth->execute( $form->{"id_$i"}, $form->{"sellprice_$i"}) || $form->dberror($query);
  237. my $totalqty = $form->{"qty_$i"};
  238. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  239. $form->db_parse_numeric(sth=>$sth, hashref => $ref);
  240. my $qty = $ref->{qty} + $ref->{allocated};
  241. if ( ( $qty - $totalqty ) < 0 ) { $qty = $totalqty; }
  242. # update allocated for sold item
  243. $form->update_balance( $dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1 );
  244. $allocated += $qty;
  245. last if ( ( $totalqty -= $qty ) >= 0 );
  246. }
  247. }
  248. # stop patch bug 1749690 ###########################################################################################################
  249. # add purchase to inventory
  250. push @{ $form->{acc_trans}{lineitems} },
  251. {
  252. chart_id => $form->{"inventory_accno_id_$i"},
  253. amount => $amount,
  254. fxgrossamount => $fxlinetotal +
  255. $form->round_amount( $fxtax, 2 ),
  256. grossamount => $grossamount,
  257. project_id => $project_id,
  258. invoice_id => $invoice_id
  259. };
  260. $updparts{ $form->{"id_$i"} } = 1;
  261. # update parts table
  262. $form->update_balance( $dbh, "parts", "onhand",
  263. qq|id = $form->{"id_$i"}|,
  264. $form->{"qty_$i"} )
  265. unless $form->{shipped};
  266. # check if we sold the item
  267. $query = qq|
  268. SELECT i.id, i.qty, i.allocated,
  269. i.trans_id, i.project_id,
  270. p.inventory_accno_id,
  271. p.expense_accno_id, a.transdate
  272. FROM invoice i
  273. JOIN parts p ON (p.id = i.parts_id)
  274. JOIN ar a ON (a.id = i.trans_id)
  275. WHERE i.parts_id = ?
  276. AND (i.qty + i.allocated) > 0
  277. ORDER BY transdate|;
  278. $sth = $dbh->prepare($query);
  279. $sth->execute( $form->{"id_$i"} )
  280. || $form->dberror($query);
  281. my $totalqty = $form->{"qty_$i"};
  282. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  283. $form->db_parse_numeric(sth=>$sth, hashref => $ref);
  284. my $qty = $ref->{qty} + $ref->{allocated};
  285. if ( ( $qty - $totalqty ) > 0 ) {
  286. $qty = $totalqty;
  287. }
  288. $linetotal =
  289. $form->round_amount( $form->{"sellprice_$i"} * $qty, 2 );
  290. if ($linetotal) {
  291. $query = qq|
  292. INSERT INTO acc_trans
  293. (trans_id,
  294. chart_id,
  295. amount,
  296. transdate,
  297. project_id,
  298. invoice_id)
  299. VALUES (?, ?, ?, ?,
  300. ?, ?)|;
  301. $sth = $dbh->prepare($query);
  302. $sth->execute(
  303. $ref->{trans_id}, $ref->{inventory_accno_id},
  304. $linetotal, $ref->{transdate},
  305. $ref->{project_id}, $invoice_id
  306. ) || $form->dberror($query);
  307. # add expense
  308. $query = qq|
  309. INSERT INTO acc_trans
  310. (trans_id,
  311. chart_id,
  312. amount,
  313. transdate,
  314. project_id,
  315. invoice_id)
  316. VALUES (?, ?, ?, ?,
  317. ?, ?)|;
  318. $sth = $dbh->prepare($query);
  319. $sth->execute(
  320. $ref->{trans_id}, $ref->{expense_accno_id},
  321. $linetotal * -1, $ref->{transdate},
  322. $ref->{project_id}, $invoice_id
  323. ) || $form->dberror($query);
  324. }
  325. # update allocated for sold item
  326. $form->update_balance( $dbh, "invoice", "allocated",
  327. qq|id = $ref->{id}|,
  328. $qty * -1 );
  329. $allocated += $qty;
  330. last if ( ( $totalqty -= $qty ) <= 0 );
  331. }
  332. $sth->finish;
  333. }
  334. else {
  335. # add purchase to expense
  336. push @{ $form->{acc_trans}{lineitems} },
  337. {
  338. chart_id => $form->{"expense_accno_id_$i"},
  339. amount => $amount,
  340. fxgrossamount => $fxlinetotal +
  341. $form->round_amount( $fxtax, 2 ),
  342. grossamount => $grossamount,
  343. project_id => $project_id,
  344. invoice_id => $invoice_id
  345. };
  346. }
  347. $query = qq|
  348. UPDATE invoice
  349. SET trans_id = ?,
  350. parts_id = ?,
  351. description = ?,
  352. qty = ?,
  353. sellprice = ?,
  354. fxsellprice = ?,
  355. discount = ?,
  356. allocated = ?,
  357. unit = ?,
  358. deliverydate = ?,
  359. project_id = ?,
  360. serialnumber = ?,
  361. notes = ?
  362. WHERE id = ?|;
  363. $sth = $dbh->prepare($query);
  364. $sth->execute(
  365. $form->{id}, $form->{"id_$i"},
  366. $form->{"description_$i"}, $form->{"qty_$i"} * -1,
  367. $form->{"sellprice_$i"}, $fxsellprice,
  368. $form->{"discount_$i"}, $allocated,
  369. $form->{"unit_$i"}, $form->{"deliverydate_$i"},
  370. $project_id, $form->{"serialnumber_$i"},
  371. $form->{"notes_$i"}, $invoice_id
  372. ) || $form->dberror($query);
  373. }
  374. }
  375. $form->{paid} = 0;
  376. for $i ( 1 .. $form->{paidaccounts} ) {
  377. $form->{"paid_$i"} =
  378. $form->parse_amount( $myconfig, $form->{"paid_$i"} );
  379. $form->{paid} += $form->{"paid_$i"};
  380. $form->{datepaid} = $form->{"datepaid_$i"}
  381. if ( $form->{"datepaid_$i"} );
  382. }
  383. # add lineitems + tax
  384. $amount = 0;
  385. $grossamount = 0;
  386. $fxgrossamount = 0;
  387. for ( @{ $form->{acc_trans}{lineitems} } ) {
  388. $amount += $_->{amount};
  389. $grossamount += $_->{grossamount};
  390. $fxgrossamount += $_->{fxgrossamount};
  391. }
  392. $invnetamount = $amount;
  393. $amount = 0;
  394. for ( split / /, $form->{taxaccounts} ) {
  395. $amount += $form->{acc_trans}{ $form->{id} }{$_}{amount} =
  396. $form->round_amount( $form->{acc_trans}{ $form->{id} }{$_}{amount},
  397. 2 );
  398. $form->{acc_trans}{ $form->{id} }{$_}{amount} *= -1;
  399. }
  400. $invamount = $invnetamount + $amount;
  401. $diff = 0;
  402. if ( $form->{taxincluded} ) {
  403. $diff = $form->round_amount( $grossamount - $invamount, 2 );
  404. $invamount += $diff;
  405. }
  406. $fxdiff = $form->round_amount( $fxdiff, 2 );
  407. $invnetamount += $fxdiff;
  408. $invamount += $fxdiff;
  409. if ( $form->round_amount( $form->{paid} - $fxgrossamount, 2 ) == 0 ) {
  410. $form->{paid} = $invamount;
  411. }
  412. else {
  413. $form->{paid} =
  414. $form->round_amount( $form->{paid} * $form->{exchangerate}, 2 );
  415. }
  416. foreach $ref ( sort { $b->{amount} <=> $a->{amount} }
  417. @{ $form->{acc_trans}{lineitems} } )
  418. {
  419. $amount = $ref->{amount} + $diff + $fxdiff;
  420. $query = qq|
  421. INSERT INTO acc_trans (trans_id, chart_id, amount,
  422. transdate, project_id, invoice_id)
  423. VALUES (?, ?, ?, ?, ?, ?)|;
  424. $sth = $dbh->prepare($query);
  425. $sth->execute(
  426. $form->{id}, $ref->{chart_id}, $amount * -1,
  427. $form->{transdate}, $ref->{project_id}, $ref->{invoice_id}
  428. ) || $form->dberror($query);
  429. $diff = 0;
  430. $fxdiff = 0;
  431. }
  432. $form->{payables} = $invamount;
  433. delete $form->{acc_trans}{lineitems};
  434. # update exchangerate
  435. if ( ( $form->{currency} ne $form->{defaultcurrency} ) && !$exchangerate ) {
  436. $form->update_exchangerate( $dbh, $form->{currency}, $form->{transdate},
  437. 0, $form->{exchangerate} );
  438. }
  439. # record payable
  440. if ( $form->{payables} ) {
  441. ($accno) = split /--/, $form->{AP};
  442. $query = qq|
  443. INSERT INTO acc_trans (trans_id, chart_id, amount,
  444. transdate)
  445. VALUES (?, (SELECT id FROM chart WHERE accno = ?),
  446. ?, ?)|;
  447. $sth = $dbh->prepare($query);
  448. $sth->execute( $form->{id}, $accno, $form->{payables},
  449. $form->{transdate} )
  450. || $form->dberror($query);
  451. }
  452. foreach my $trans_id ( keys %{ $form->{acc_trans} } ) {
  453. foreach my $accno ( keys %{ $form->{acc_trans}{$trans_id} } ) {
  454. $amount =
  455. $form->round_amount(
  456. $form->{acc_trans}{$trans_id}{$accno}{amount}, 2 );
  457. if ($amount) {
  458. $query = qq|
  459. INSERT INTO acc_trans
  460. (trans_id, chart_id, amount,
  461. transdate)
  462. VALUES (?, (SELECT id FROM chart
  463. WHERE accno = ?),
  464. ?, ?)|;
  465. $sth = $dbh->prepare($query);
  466. $sth->execute( $trans_id, $accno, $amount, $form->{transdate} )
  467. || $form->dberror($query);
  468. }
  469. }
  470. }
  471. # if there is no amount but a payment record payable
  472. if ( $invamount == 0 ) {
  473. $form->{payables} = 1;
  474. }
  475. my $cleared = 0;
  476. # record payments and offsetting AP
  477. for my $i ( 1 .. $form->{paidaccounts} ) {
  478. if ( $form->{"paid_$i"} ) {
  479. my ($accno) = split /--/, $form->{"AP_paid_$i"};
  480. $form->{"datepaid_$i"} = $form->{transdate}
  481. unless ( $form->{"datepaid_$i"} );
  482. $form->{datepaid} = $form->{"datepaid_$i"};
  483. $exchangerate = 0;
  484. if ( $form->{currency} eq $form->{defaultcurrency} ) {
  485. $form->{"exchangerate_$i"} = 1;
  486. }
  487. else {
  488. $exchangerate =
  489. $form->check_exchangerate( $myconfig, $form->{currency},
  490. $form->{"datepaid_$i"}, 'sell' );
  491. $form->{"exchangerate_$i"} =
  492. ($exchangerate)
  493. ? $exchangerate
  494. : $form->parse_amount( $myconfig,
  495. $form->{"exchangerate_$i"} );
  496. }
  497. # record AP
  498. $amount = (
  499. $form->round_amount(
  500. $form->{"paid_$i"} * $form->{exchangerate}, 2
  501. )
  502. ) * -1;
  503. if ( $form->{payables} ) {
  504. $query = qq|
  505. INSERT INTO acc_trans
  506. (trans_id, chart_id, amount,
  507. transdate)
  508. VALUES (?, (SELECT id FROM chart
  509. WHERE accno = ?),
  510. ?, ?)|;
  511. $sth = $dbh->prepare($query);
  512. $sth->execute( $form->{id}, $form->{AP}, $amount,
  513. $form->{"datepaid_$i"} )
  514. || $form->dberror($query);
  515. }
  516. if ($keepcleared) {
  517. $cleared = ( $form->{"cleared_$i"} ) ? 1 : 0;
  518. }
  519. # record payment
  520. $query = qq|
  521. INSERT INTO acc_trans
  522. (trans_id, chart_id, amount,
  523. transdate, source, memo, cleared)
  524. VALUES (?, (SELECT id FROM chart
  525. WHERE accno = ?),
  526. ?, ?, ?, ?, ?)|;
  527. $sth = $dbh->prepare($query);
  528. $sth->execute( $form->{id}, $accno, $form->{"paid_$i"},
  529. $form->{"datepaid_$i"},
  530. $form->{"source_$i"}, $form->{"memo_$i"}, $cleared )
  531. || $form->dberror($query);
  532. # exchangerate difference
  533. $amount = $form->round_amount(
  534. $form->{"paid_$i"} * $form->{"exchangerate_$i"} -
  535. $form->{"paid_$i"},
  536. 2
  537. );
  538. if ($amount) {
  539. $query = qq|
  540. INSERT INTO acc_trans
  541. (trans_id, chart_id, amount,
  542. transdate, source,
  543. fx_transaction, cleared)
  544. VALUES (?, (SELECT id FROM chart
  545. WHERE accno = ?),
  546. ?, ?, ?, '1', ?)|;
  547. $sth = $dbh->prepare($query);
  548. $sth->execute( $form->{id}, $accno, $amount,
  549. $form->{"datepaid_$i"},
  550. $form->{"source_$i"}, $cleared )
  551. || $form->dberror($query);
  552. }
  553. # gain/loss
  554. $amount = $form->round_amount(
  555. $form->round_amount( $form->{"paid_$i"} * $form->{exchangerate},
  556. 2 ) - $form->round_amount(
  557. $form->{"paid_$i"} * $form->{"exchangerate_$i"}, 2
  558. ),
  559. 2
  560. );
  561. if ($amount) {
  562. my $accno_id =
  563. ( $amount > 0 )
  564. ? $fxgain_accno_id
  565. : $fxloss_accno_id;
  566. $query = qq|
  567. INSERT INTO acc_trans
  568. (trans_id, chart_id, amount,
  569. transdate, fx_transaction,
  570. cleared)
  571. VALUES (?, ?, ?, ?, '1', ?)|;
  572. $sth = $dbh->prepare($query);
  573. $sth->execute( $form->{id}, $accno_id, $amount,
  574. $form->{"datepaid_$i"}, $cleared )
  575. || $form->dberror($query);
  576. }
  577. # update exchange rate
  578. if ( ( $form->{currency} ne $form->{defaultcurrency} )
  579. && !$exchangerate )
  580. {
  581. $form->update_exchangerate( $dbh, $form->{currency},
  582. $form->{"datepaid_$i"},
  583. 0, $form->{"exchangerate_$i"} );
  584. }
  585. }
  586. }
  587. # set values which could be empty
  588. $form->{taxincluded} *= 1;
  589. # save AP record
  590. $query = qq|
  591. UPDATE ap
  592. SET invnumber = ?,
  593. ordnumber = ?,
  594. quonumber = ?,
  595. transdate = ?,
  596. vendor_id = ?,
  597. amount = ?,
  598. netamount = ?,
  599. paid = ?,
  600. datepaid = ?,
  601. duedate = ?,
  602. invoice = '1',
  603. shippingpoint = ?,
  604. shipvia = ?,
  605. taxincluded = ?,
  606. notes = ?,
  607. intnotes = ?,
  608. curr = ?,
  609. department_id = ?,
  610. employee_id = ?,
  611. language_code = ?,
  612. ponumber = ?
  613. WHERE id = ?|;
  614. $sth = $dbh->prepare($query);
  615. $sth->execute(
  616. $form->{invnumber}, $form->{ordnumber}, $form->{quonumber},
  617. $form->{transdate}, $form->{vendor_id}, $invamount,
  618. $invnetamount, $form->{paid}, $form->{datepaid},
  619. $form->{duedate}, $form->{shippingpoint}, $form->{shipvia},
  620. $form->{taxincluded}, $form->{notes}, $form->{intnotes},
  621. $form->{currency}, $form->{department_id}, $form->{employee_id},
  622. $form->{language_code}, $form->{ponumber}, $form->{id}
  623. ) || $form->dberror($query);
  624. # add shipto
  625. $form->{name} = $form->{vendor};
  626. $form->{name} =~ s/--$form->{vendor_id}//;
  627. $form->add_shipto( $dbh, $form->{id} );
  628. my %audittrail = (
  629. tablename => 'ap',
  630. reference => $form->{invnumber},
  631. formname => $form->{type},
  632. action => 'posted',
  633. id => $form->{id}
  634. );
  635. $form->audittrail( $dbh, "", \%audittrail );
  636. foreach $item ( keys %updparts ) {
  637. $item = $dbh->quote($item);
  638. $query = qq|
  639. UPDATE parts
  640. SET avgcost = avgcost($item),
  641. lastcost = lastcost($item)
  642. WHERE id = $item|;
  643. $dbh->prepare($query) || $form->dberror($query);
  644. }
  645. my $rc = $dbh->commit;
  646. $rc;
  647. }
  648. sub reverse_invoice {
  649. my ( $dbh, $form ) = @_;
  650. my $query = qq|SELECT id FROM ap
  651. WHERE id = $form->{id}|;
  652. my ($id) = $dbh->selectrow_array($query);
  653. return unless $id;
  654. # reverse inventory items
  655. $query = qq|
  656. SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id,
  657. i.qty, i.allocated, i.sellprice, i.project_id
  658. FROM invoice i, parts p
  659. WHERE i.parts_id = p.id
  660. AND i.trans_id = ?|;
  661. my $sth = $dbh->prepare($query);
  662. $sth->execute( $form->{id} ) || $form->dberror($query);
  663. my $netamount = 0;
  664. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  665. $netamount +=
  666. $form->round_amount( $ref->{sellprice} * $ref->{qty} * -1, 2 );
  667. if ( $ref->{inventory_accno_id} ) {
  668. # update onhand
  669. $form->update_balance( $dbh, "parts", "onhand",
  670. qq|id = $ref->{parts_id}|,
  671. $ref->{qty} );
  672. # if $ref->{allocated} > 0 than we sold that many items
  673. if ( $ref->{allocated} > 0 ) {
  674. # get references for sold items
  675. $query = qq|
  676. SELECT i.id, i.trans_id, i.allocated,
  677. a.transdate
  678. FROM invoice i, ar a
  679. WHERE i.parts_id = ?
  680. AND i.allocated < 0
  681. AND i.trans_id = a.id
  682. ORDER BY transdate DESC|;
  683. my $sth = $dbh->prepare($query);
  684. $sth->execute( $ref->{parts_id} )
  685. || $form->dberror($query);
  686. while ( my $pthref = $sth->fetchrow_hashref(NAME_lc) ) {
  687. my $qty = $ref->{allocated};
  688. if ( ( $ref->{allocated} + $pthref->{allocated} ) > 0 ) {
  689. $qty = $pthref->{allocated} * -1;
  690. }
  691. my $amount =
  692. $form->round_amount( $ref->{sellprice} * $qty, 2 );
  693. #adjust allocated
  694. $form->update_balance( $dbh, "invoice", "allocated",
  695. qq|id = $pthref->{id}|, $qty );
  696. # add reversal for sale
  697. $ref->{project_id} *= 1;
  698. $query = qq|
  699. INSERT INTO acc_trans
  700. (trans_id,
  701. chart_id, amount,
  702. transdate,
  703. project_id)
  704. VALUES (?, ?, ?, ?, ?)|;
  705. $sth = $dbh->prepare($query);
  706. $sth->execute( $pthref->{trans_id},
  707. $ref->{expense_accno_id},
  708. $amount, $form->{transdate}, $ref->{project_id} )
  709. || $form->dberror($query);
  710. $query = qq|
  711. INSERT INTO acc_trans
  712. (trans_id, chart_id,
  713. amount, transdate,
  714. project_id)
  715. VALUES (?, ?, ?, ?, ?)|;
  716. $sth = $dbh->do($query);
  717. $sth->execute(
  718. $pthref->{trans_id},
  719. $ref->{inventory_accno_id},
  720. $amount * -1,
  721. $form->{transdate}, $ref->{project_id}
  722. ) || $form->dberror($query);
  723. last if ( ( $ref->{allocated} -= $qty ) <= 0 );
  724. }
  725. $sth->finish;
  726. }
  727. }
  728. }
  729. $sth->finish;
  730. # delete acc_trans
  731. $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
  732. $dbh->prepare($query);
  733. $sth->execute( $form->{id} ) || $form->dberror($query);
  734. # delete invoice entries
  735. $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
  736. $dbh->prepare($query);
  737. $sth->execute( $form->{id} ) || $form->dberror($query);
  738. $query = qq|DELETE FROM shipto WHERE trans_id = ?|;
  739. $dbh->prepare($query);
  740. $sth->execute( $form->{id} ) || $form->dberror($query);
  741. $dbh->commit;
  742. }
  743. sub delete_invoice {
  744. my ( $self, $myconfig, $form ) = @_;
  745. # connect to database
  746. my $dbh = $form->{dbh};
  747. my %audittrail = (
  748. tablename => 'ap',
  749. reference => $form->{invnumber},
  750. formname => $form->{type},
  751. action => 'deleted',
  752. id => $form->{id}
  753. );
  754. $form->audittrail( $dbh, "", \%audittrail );
  755. my $query = qq|SELECT parts_id FROM invoice WHERE trans_id = ?|;
  756. my $sth = $dbh->prepare($query);
  757. $sth->execute( $form->{id} ) || $form->dberror($query);
  758. my $item;
  759. my %updparts = ();
  760. while ( ($item) = $sth->fetchrow_array ) {
  761. $updparts{$item} = 1;
  762. }
  763. $sth->finish;
  764. &reverse_invoice( $dbh, $form );
  765. # delete AP record
  766. $query = qq|DELETE FROM ap WHERE id = ?|;
  767. my $sth = $dbh->prepare($query);
  768. $sth->execute( $form->{id} ) || $form->dberror($query);
  769. # delete spool files
  770. $query = qq|
  771. SELECT spoolfile FROM status
  772. WHERE trans_id = ?
  773. AND spoolfile IS NOT NULL|;
  774. my $sth = $dbh->prepare($query);
  775. $sth->execute( $form->{id} ) || $form->dberror($query);
  776. my $spoolfile;
  777. my @spoolfiles = ();
  778. while ( ($spoolfile) = $sth->fetchrow_array ) {
  779. push @spoolfiles, $spoolfile;
  780. }
  781. $sth->finish;
  782. # delete status entries
  783. $query = qq|DELETE FROM status WHERE trans_id = ?|;
  784. my $sth = $dbh->prepare($query);
  785. $sth->execute( $form->{id} ) || $form->dberror($query);
  786. if ($rc) {
  787. foreach $item ( keys %updparts ) {
  788. $item = $dbh->quote($item);
  789. $query = qq|
  790. UPDATE parts
  791. SET avgcost = avgcost($item),
  792. lastcost = lastcost($item)
  793. WHERE id = $item|;
  794. $dbh->do($query) || $form->dberror($query);
  795. }
  796. foreach $spoolfile (@spoolfiles) {
  797. unlink "${LedgerSMB::Sysconfig::spool}/$spoolfile"
  798. if $spoolfile;
  799. }
  800. }
  801. my $rc = $dbh->commit;
  802. $rc;
  803. }
  804. sub retrieve_invoice {
  805. my ( $self, $myconfig, $form ) = @_;
  806. # connect to database
  807. my $dbh = $form->{dbh};
  808. my $query;
  809. if ( $form->{id} ) {
  810. # get default accounts and last invoice number
  811. $query = qq|
  812. SELECT (select c.accno FROM chart c
  813. WHERE c.id = (SELECT value FROM defaults
  814. WHERE setting_key =
  815. 'inventory_accno_id'))
  816. AS inventory_accno,
  817. (SELECT c.accno FROM chart c
  818. WHERE c.id = (SELECT value FROM defaults
  819. WHERE setting_key =
  820. 'income_accno_id'))
  821. AS income_accno,
  822. (SELECT c.accno FROM chart c
  823. WHERE c.id = (SELECT value FROM defaults
  824. WHERE setting_key =
  825. 'expense_accno_id'))
  826. AS expense_accno,
  827. (SELECT c.accno FROM chart c
  828. WHERE c.id = (SELECT value FROM defaults
  829. WHERE setting_key =
  830. 'fxgain_accno_id'))
  831. AS fxgain_accno,
  832. (SELECT c.accno FROM chart c
  833. WHERE c.id = (SELECT value FROM defaults
  834. WHERE setting_key =
  835. 'fxloss_accno_id'))
  836. AS fxloss_accno,
  837. (SELECT value FROM defaults
  838. WHERE setting_key = 'curr') AS currencies|;
  839. }
  840. else {
  841. $query = qq|
  842. SELECT (select c.accno FROM chart c
  843. WHERE c.id = (SELECT value FROM defaults
  844. WHERE setting_key =
  845. 'inventory_accno_id'))
  846. AS inventory_accno,
  847. (SELECT c.accno FROM chart c
  848. WHERE c.id = (SELECT value FROM defaults
  849. WHERE setting_key =
  850. 'income_accno_id'))
  851. AS income_accno,
  852. (SELECT c.accno FROM chart c
  853. WHERE c.id = (SELECT value FROM defaults
  854. WHERE setting_key =
  855. 'expense_accno_id'))
  856. AS expense_accno,
  857. (SELECT c.accno FROM chart c
  858. WHERE c.id = (SELECT value FROM defaults
  859. WHERE setting_key =
  860. 'fxgain_accno_id'))
  861. AS fxgain_accno,
  862. (SELECT c.accno FROM chart c
  863. WHERE c.id = (SELECT value FROM defaults
  864. WHERE setting_key =
  865. 'fxloss_accno_id'))
  866. AS fxloss_accno,
  867. (SELECT value FROM defaults
  868. WHERE setting_key = 'curr') AS currencies,
  869. current_date AS transdate|;
  870. }
  871. my $sth = $dbh->prepare($query);
  872. $sth->execute || $form->dberror($query);
  873. my $ref = $sth->fetchrow_hashref(NAME_lc);
  874. for ( keys %$ref ) {
  875. $form->{$_} = $ref->{$_};
  876. }
  877. $sth->finish;
  878. if ( $form->{id} ) {
  879. $query = qq|
  880. SELECT a.invnumber, a.transdate, a.duedate,
  881. a.ordnumber, a.quonumber, a.paid, a.taxincluded,
  882. a.notes, a.intnotes, a.curr AS currency,
  883. a.vendor_id, a.language_code, a.ponumber
  884. FROM ap a
  885. WHERE id = ?|;
  886. $sth = $dbh->prepare($query);
  887. $sth->execute( $form->{id} ) || $form->dberror($query);
  888. $ref = $sth->fetchrow_hashref(NAME_lc);
  889. $form->db_parse_numeric(sth=>$sth, hashref=>$ref);
  890. for ( keys %$ref ) {
  891. $form->{$_} = $ref->{$_};
  892. }
  893. $sth->finish;
  894. # get shipto
  895. $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
  896. $sth = $dbh->prepare($query);
  897. $sth->execute( $form->{id} ) || $form->dberror($query);
  898. $ref = $sth->fetchrow_hashref(NAME_lc);
  899. for ( keys %$ref ) {
  900. $form->{$_} = $ref->{$_};
  901. }
  902. $sth->finish;
  903. # retrieve individual items
  904. $query = qq|
  905. SELECT p.partnumber, i.description, i.qty,
  906. i.fxsellprice, i.sellprice,
  907. i.parts_id AS id, i.unit, p.bin,
  908. i.deliverydate,
  909. pr.projectnumber, i.project_id,
  910. i.serialnumber,
  911. i.discount, i.notes, pg.partsgroup,
  912. p.partsgroup_id, p.partnumber AS sku,
  913. p.weight, p.onhand, p.inventory_accno_id,
  914. p.income_accno_id, p.expense_accno_id,
  915. t.description AS partsgrouptranslation
  916. FROM invoice i
  917. JOIN parts p ON (i.parts_id = p.id)
  918. LEFT JOIN project pr ON (i.project_id = pr.id)
  919. LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
  920. LEFT JOIN translation t
  921. ON (t.trans_id = p.partsgroup_id
  922. AND t.language_code = ?)
  923. WHERE i.trans_id = ?
  924. ORDER BY i.id|;
  925. $sth = $dbh->prepare($query);
  926. $sth->execute( $form->{language_code}, $form->{id} )
  927. || $form->dberror($query);
  928. # exchangerate defaults
  929. &exchangerate_defaults( $dbh, $form );
  930. # price matrix and vendor partnumber
  931. my $pmh = PriceMatrix::price_matrix_query( $dbh, $form );
  932. # tax rates for part
  933. $query = qq|
  934. SELECT c.accno
  935. FROM chart c
  936. JOIN partstax pt ON (pt.chart_id = c.id)
  937. WHERE pt.parts_id = ?|;
  938. my $tth = $dbh->prepare($query);
  939. my $ptref;
  940. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  941. $form->db_parse_numeric(sth=>$sth, hashref=>$ref);
  942. my ($dec) = ( $ref->{fxsellprice} =~ /\.(\d+)/ );
  943. $dec = length $dec;
  944. my $decimalplaces = ( $dec > 2 ) ? $dec : 2;
  945. $tth->execute( $ref->{id} );
  946. $ref->{taxaccounts} = "";
  947. my $taxrate = 0;
  948. while ( $ptref = $tth->fetchrow_hashref(NAME_lc) ) {
  949. $form->db_parse_numeric(sth => $tth, hashref => $ptref);
  950. $ref->{taxaccounts} .= "$ptref->{accno} ";
  951. $taxrate += $form->{"$ptref->{accno}_rate"};
  952. }
  953. $tth->finish;
  954. chop $ref->{taxaccounts};
  955. # price matrix
  956. $ref->{sellprice} =
  957. $form->round_amount(
  958. $ref->{fxsellprice} * $form->{ $form->{currency} },
  959. $decimalplaces );
  960. PriceMatrix::price_matrix( $pmh, $ref, $decimalplaces, $form,
  961. $myconfig );
  962. $ref->{sellprice} = $ref->{fxsellprice};
  963. $ref->{qty} *= -1;
  964. $ref->{partsgroup} = $ref->{partsgrouptranslation}
  965. if $ref->{partsgrouptranslation};
  966. push @{ $form->{invoice_details} }, $ref;
  967. }
  968. $sth->finish;
  969. }
  970. my $rc = $dbh->commit;
  971. $rc;
  972. }
  973. sub retrieve_item {
  974. my ( $self, $myconfig, $form ) = @_;
  975. $dbh = $form->{dbh};
  976. my $i = $form->{rowcount};
  977. my $null;
  978. my $var;
  979. # don't include assemblies or obsolete parts
  980. my $where = "WHERE p.assembly = '0' AND p.obsolete = '0'";
  981. if ( $form->{"partnumber_$i"} ne "" ) {
  982. $var = $dbh->quote( $form->like( lc $form->{"partnumber_$i"} ) );
  983. $where .= " AND lower(p.partnumber) LIKE $var";
  984. }
  985. if ( $form->{"description_$i"} ne "" ) {
  986. $var = $dbh->quote( $form->like( lc $form->{"description_$i"} ) );
  987. if ( $form->{language_code} ne "" ) {
  988. $where .= " AND lower(t1.description) LIKE $var";
  989. }
  990. else {
  991. $where .= " AND lower(p.description) LIKE $var";
  992. }
  993. }
  994. if ( $form->{"partsgroup_$i"} ne "" ) {
  995. ( $null, $var ) = split /--/, $form->{"partsgroup_$i"};
  996. $var = $dbh->quote($var);
  997. $where .= qq| AND p.partsgroup_id = $var|;
  998. }
  999. if ( $form->{"description_$i"} ne "" ) {
  1000. $where .= " ORDER BY 3";
  1001. }
  1002. else {
  1003. $where .= " ORDER BY 2";
  1004. }
  1005. my $query = qq|
  1006. SELECT p.id, p.partnumber, p.description,
  1007. pg.partsgroup, p.partsgroup_id,
  1008. p.lastcost AS sellprice, p.unit, p.bin, p.onhand,
  1009. p.notes, p.inventory_accno_id, p.income_accno_id,
  1010. p.expense_accno_id, p.partnumber AS sku, p.weight,
  1011. t1.description AS translation,
  1012. t2.description AS grouptranslation
  1013. FROM parts p
  1014. LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
  1015. LEFT JOIN translation t1
  1016. ON (t1.trans_id = p.id AND t1.language_code = ?)
  1017. LEFT JOIN translation t2
  1018. ON (t2.trans_id = p.partsgroup_id
  1019. AND t2.language_code = ?)
  1020. $where|;
  1021. my $sth = $dbh->prepare($query);
  1022. $sth->execute( $form->{language_code}, $form->{language_code} )
  1023. || $form->dberror($query);
  1024. # foreign currency
  1025. &exchangerate_defaults( $dbh, $form );
  1026. # taxes
  1027. $query = qq|
  1028. SELECT c.accno
  1029. FROM chart c
  1030. JOIN partstax pt ON (pt.chart_id = c.id)
  1031. WHERE pt.parts_id = ?|;
  1032. my $tth = $dbh->prepare($query) || $form->dberror($query);
  1033. # price matrix
  1034. my $pmh = PriceMatrix::price_matrix_query( $dbh, $form );
  1035. my $ref;
  1036. my $ptref;
  1037. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1038. $form->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1039. my ($dec) = ( $ref->{sellprice} =~ /\.(\d+)/ );
  1040. $dec = length $dec;
  1041. my $decimalplaces = ( $dec > 2 ) ? $dec : 2;
  1042. # get taxes for part
  1043. $tth->execute( $ref->{id} );
  1044. $ref->{taxaccounts} = "";
  1045. while ( $ptref = $tth->fetchrow_hashref(NAME_lc) ) {
  1046. $ref->{taxaccounts} .= "$ptref->{accno} ";
  1047. }
  1048. $tth->finish;
  1049. chop $ref->{taxaccounts};
  1050. # get vendor price and partnumber
  1051. PriceMatrix::price_matrix( $pmh, $ref, $decimalplaces, $form,
  1052. $myconfig );
  1053. $ref->{description} = $ref->{translation}
  1054. if $ref->{translation};
  1055. $ref->{partsgroup} = $ref->{grouptranslation}
  1056. if $ref->{grouptranslation};
  1057. push @{ $form->{item_list} }, $ref;
  1058. }
  1059. $sth->finish;
  1060. }
  1061. sub exchangerate_defaults {
  1062. my ( $dbh, $form ) = @_;
  1063. my $var;
  1064. # get default currencies
  1065. my $query = qq|
  1066. SELECT substr(value,1,3), value FROM defaults
  1067. WHERE setting_key = 'curr'|;
  1068. my $eth = $dbh->prepare($query) || $form->dberror($query);
  1069. $eth->execute;
  1070. ( $form->{defaultcurrency}, $form->{currencies} ) = $eth->fetchrow_array;
  1071. $eth->finish;
  1072. $query = qq|
  1073. SELECT sell
  1074. FROM exchangerate
  1075. WHERE curr = ?
  1076. AND transdate = ?|;
  1077. my $eth1 = $dbh->prepare($query) || $form->dberror($query);
  1078. $query = qq/
  1079. SELECT max(transdate || ' ' || sell || ' ' || curr)
  1080. FROM exchangerate
  1081. WHERE curr = ?/;
  1082. my $eth2 = $dbh->prepare($query) || $form->dberror($query);
  1083. # get exchange rates for transdate or max
  1084. foreach $var ( split /:/, substr( $form->{currencies}, 4 ) ) {
  1085. $eth1->execute( $var, $form->{transdate} );
  1086. @array = $eth1->fetchrow_array;
  1087. $form->db_parse_numeric(sth=> $eth1, arrayref=>\@array);
  1088. $form->{$var} = shift @array;
  1089. if ( !$form->{$var} ) {
  1090. $eth2->execute($var);
  1091. ( $form->{$var} ) = $eth2->fetchrow_array;
  1092. ( $null, $form->{$var} ) = split / /, $form->{$var};
  1093. $form->{$var} = 1 unless $form->{$var};
  1094. $eth2->finish;
  1095. }
  1096. $eth1->finish;
  1097. }
  1098. $form->{ $form->{currency} } = $form->{exchangerate}
  1099. if $form->{exchangerate};
  1100. $form->{ $form->{currency} } ||= 1;
  1101. $form->{ $form->{defaultcurrency} } = 1;
  1102. }
  1103. sub vendor_details {
  1104. my ( $self, $myconfig, $form ) = @_;
  1105. # connect to database
  1106. my $dbh = $form->{dbh};
  1107. # get rest for the vendor
  1108. my $query = qq|
  1109. SELECT vendornumber, name, address1, address2, city, state,
  1110. zipcode, country, contact, phone as vendorphone,
  1111. fax as vendorfax, vendornumber,
  1112. taxnumber AS vendortaxnumber, sic_code AS sic, iban, bic,
  1113. gifi_accno AS gifi, startdate, enddate
  1114. FROM vendor
  1115. WHERE id = ?|;
  1116. my $sth = $dbh->prepare($query);
  1117. $sth->execute( $form->{vendor_id} ) || $form->dberror($query);
  1118. $ref = $sth->fetchrow_hashref(NAME_lc);
  1119. for ( keys %$ref ) {
  1120. $form->{$_} = $ref->{$_};
  1121. }
  1122. $sth->finish;
  1123. }
  1124. sub item_links {
  1125. my ( $self, $myconfig, $form ) = @_;
  1126. # connect to database
  1127. my $dbh = $form->{dbh};
  1128. my $query = qq|
  1129. SELECT accno, description, link
  1130. FROM chart
  1131. WHERE link LIKE '%IC%'
  1132. ORDER BY accno|;
  1133. my $sth = $dbh->prepare($query);
  1134. $sth->execute || $form->dberror($query);
  1135. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1136. foreach my $key ( split( /:/, $ref->{link} ) ) {
  1137. if ( $key =~ /IC/ ) {
  1138. push @{ $form->{IC_links}{$key} },
  1139. {
  1140. accno => $ref->{accno},
  1141. description => $ref->{description}
  1142. };
  1143. }
  1144. }
  1145. }
  1146. $sth->finish;
  1147. }
  1148. 1;