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