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