summaryrefslogtreecommitdiff
path: root/LedgerSMB/IR.pm
blob: f3008ef32e4d5be311b6fa33ec3156a2041e6468 (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. $form->update_balance( $dbh, "invoice", "allocated",
  343. qq|id =$invoice_id|,$qty);
  344. $allocated += $qty;
  345. last if ( ( $totalqty -= $qty ) <= 0 );
  346. }
  347. $sth->finish;
  348. }
  349. else {
  350. # add purchase to expense
  351. push @{ $form->{acc_trans}{lineitems} },
  352. {
  353. chart_id => $form->{"expense_accno_id_$i"},
  354. amount => $amount,
  355. fxgrossamount => $fxlinetotal +
  356. $form->round_amount( $fxtax, 2 ),
  357. grossamount => $grossamount,
  358. project_id => $project_id,
  359. invoice_id => $invoice_id
  360. };
  361. }
  362. }
  363. }
  364. $form->{paid} = 0;
  365. for $i ( 1 .. $form->{paidaccounts} ) {
  366. $form->{"paid_$i"} =
  367. $form->parse_amount( $myconfig, $form->{"paid_$i"} );
  368. $form->{paid} += $form->{"paid_$i"};
  369. $form->{datepaid} = $form->{"datepaid_$i"}
  370. if ( $form->{"datepaid_$i"} );
  371. }
  372. # add lineitems + tax
  373. $amount = 0;
  374. $grossamount = 0;
  375. $fxgrossamount = 0;
  376. for ( @{ $form->{acc_trans}{lineitems} } ) {
  377. $amount += $_->{amount};
  378. $grossamount += $_->{grossamount};
  379. $fxgrossamount += $_->{fxgrossamount};
  380. }
  381. $invnetamount = $amount;
  382. $amount = 0;
  383. for ( split / /, $form->{taxaccounts} ) {
  384. $amount += $form->{acc_trans}{ $form->{id} }{$_}{amount} =
  385. $form->round_amount( $form->{acc_trans}{ $form->{id} }{$_}{amount},
  386. 2 );
  387. $form->{acc_trans}{ $form->{id} }{$_}{amount} *= -1;
  388. }
  389. $invamount = $invnetamount + $amount;
  390. $diff = 0;
  391. if ( $form->{taxincluded} ) {
  392. $diff = $form->round_amount( $grossamount - $invamount, 2 );
  393. $invamount += $diff;
  394. }
  395. $fxdiff = $form->round_amount( $fxdiff, 2 );
  396. $invnetamount += $fxdiff;
  397. $invamount += $fxdiff;
  398. if ( $form->round_amount( $form->{paid} - $fxgrossamount, 2 ) == 0 ) {
  399. $form->{paid} = $invamount;
  400. }
  401. else {
  402. $form->{paid} =
  403. $form->round_amount( $form->{paid} * $form->{exchangerate}, 2 );
  404. }
  405. foreach $ref ( sort { $b->{amount} <=> $a->{amount} }
  406. @{ $form->{acc_trans}{lineitems} } )
  407. {
  408. $amount = $ref->{amount} + $diff + $fxdiff;
  409. $query = qq|
  410. INSERT INTO acc_trans (trans_id, chart_id, amount,
  411. transdate, project_id, invoice_id)
  412. VALUES (?, ?, ?, ?, ?, ?)|;
  413. $sth = $dbh->prepare($query);
  414. $sth->execute(
  415. $form->{id}, $ref->{chart_id}, $amount * -1,
  416. $form->{transdate}, $ref->{project_id}, $ref->{invoice_id}
  417. ) || $form->dberror($query);
  418. $diff = 0;
  419. $fxdiff = 0;
  420. }
  421. $form->{payables} = $invamount;
  422. delete $form->{acc_trans}{lineitems};
  423. # update exchangerate
  424. if ( ( $form->{currency} ne $form->{defaultcurrency} ) && !$exchangerate ) {
  425. $form->update_exchangerate( $dbh, $form->{currency}, $form->{transdate},
  426. 0, $form->{exchangerate} );
  427. }
  428. # record payable
  429. if ( $form->{payables} ) {
  430. ($accno) = split /--/, $form->{AP};
  431. $query = qq|
  432. INSERT INTO acc_trans (trans_id, chart_id, amount,
  433. transdate)
  434. VALUES (?, (SELECT id FROM chart WHERE accno = ?),
  435. ?, ?)|;
  436. $sth = $dbh->prepare($query);
  437. $sth->execute( $form->{id}, $accno, $form->{payables},
  438. $form->{transdate} )
  439. || $form->dberror($query);
  440. }
  441. foreach my $trans_id ( keys %{ $form->{acc_trans} } ) {
  442. foreach my $accno ( keys %{ $form->{acc_trans}{$trans_id} } ) {
  443. $amount =
  444. $form->round_amount(
  445. $form->{acc_trans}{$trans_id}{$accno}{amount}, 2 );
  446. if ($amount) {
  447. $query = qq|
  448. INSERT INTO acc_trans
  449. (trans_id, chart_id, amount,
  450. transdate)
  451. VALUES (?, (SELECT id FROM chart
  452. WHERE accno = ?),
  453. ?, ?)|;
  454. $sth = $dbh->prepare($query);
  455. $sth->execute( $trans_id, $accno, $amount, $form->{transdate} )
  456. || $form->dberror($query);
  457. }
  458. }
  459. }
  460. # if there is no amount but a payment record payable
  461. if ( $invamount == 0 ) {
  462. $form->{payables} = 1;
  463. }
  464. my $cleared = 0;
  465. # record payments and offsetting AP
  466. for my $i ( 1 .. $form->{paidaccounts} ) {
  467. if ( $form->{"paid_$i"} ) {
  468. my ($accno) = split /--/, $form->{"AP_paid_$i"};
  469. $form->{"datepaid_$i"} = $form->{transdate}
  470. unless ( $form->{"datepaid_$i"} );
  471. $form->{datepaid} = $form->{"datepaid_$i"};
  472. $exchangerate = 0;
  473. if ( $form->{currency} eq $form->{defaultcurrency} ) {
  474. $form->{"exchangerate_$i"} = 1;
  475. }
  476. else {
  477. $exchangerate =
  478. $form->check_exchangerate( $myconfig, $form->{currency},
  479. $form->{"datepaid_$i"}, 'sell' );
  480. $form->{"exchangerate_$i"} =
  481. ($exchangerate)
  482. ? $exchangerate
  483. : $form->parse_amount( $myconfig,
  484. $form->{"exchangerate_$i"} );
  485. }
  486. # record AP
  487. $amount = (
  488. $form->round_amount(
  489. $form->{"paid_$i"} * $form->{exchangerate}, 2
  490. )
  491. ) * -1;
  492. if ( $form->{payables} ) {
  493. $query = qq|
  494. INSERT INTO acc_trans
  495. (trans_id, chart_id, amount,
  496. transdate)
  497. VALUES (?, (SELECT id FROM chart
  498. WHERE accno = ?),
  499. ?, ?)|;
  500. $sth = $dbh->prepare($query);
  501. $sth->execute( $form->{id}, $form->{AP}, $amount,
  502. $form->{"datepaid_$i"} )
  503. || $form->dberror($query);
  504. }
  505. if ($keepcleared) {
  506. $cleared = ( $form->{"cleared_$i"} ) ? 1 : 0;
  507. }
  508. # record payment
  509. $query = qq|
  510. INSERT INTO acc_trans
  511. (trans_id, chart_id, amount,
  512. transdate, source, memo, cleared)
  513. VALUES (?, (SELECT id FROM chart
  514. WHERE accno = ?),
  515. ?, ?, ?, ?, ?)|;
  516. $sth = $dbh->prepare($query);
  517. $sth->execute( $form->{id}, $accno, $form->{"paid_$i"},
  518. $form->{"datepaid_$i"},
  519. $form->{"source_$i"}, $form->{"memo_$i"}, $cleared )
  520. || $form->dberror($query);
  521. # exchangerate difference
  522. $amount = $form->round_amount(
  523. $form->{"paid_$i"} * $form->{"exchangerate_$i"} -
  524. $form->{"paid_$i"},
  525. 2
  526. );
  527. if ($amount) {
  528. $query = qq|
  529. INSERT INTO acc_trans
  530. (trans_id, chart_id, amount,
  531. transdate, source,
  532. fx_transaction, cleared)
  533. VALUES (?, (SELECT id FROM chart
  534. WHERE accno = ?),
  535. ?, ?, ?, '1', ?)|;
  536. $sth = $dbh->prepare($query);
  537. $sth->execute( $form->{id}, $accno, $amount,
  538. $form->{"datepaid_$i"},
  539. $form->{"source_$i"}, $cleared )
  540. || $form->dberror($query);
  541. }
  542. # gain/loss
  543. $amount = $form->round_amount(
  544. $form->round_amount( $form->{"paid_$i"} * $form->{exchangerate},
  545. 2 ) - $form->round_amount(
  546. $form->{"paid_$i"} * $form->{"exchangerate_$i"}, 2
  547. ),
  548. 2
  549. );
  550. if ($amount) {
  551. my $accno_id =
  552. ( $amount > 0 )
  553. ? $fxgain_accno_id
  554. : $fxloss_accno_id;
  555. $query = qq|
  556. INSERT INTO acc_trans
  557. (trans_id, chart_id, amount,
  558. transdate, fx_transaction,
  559. cleared)
  560. VALUES (?, ?, ?, ?, '1', ?)|;
  561. $sth = $dbh->prepare($query);
  562. $sth->execute( $form->{id}, $accno_id, $amount,
  563. $form->{"datepaid_$i"}, $cleared )
  564. || $form->dberror($query);
  565. }
  566. # update exchange rate
  567. if ( ( $form->{currency} ne $form->{defaultcurrency} )
  568. && !$exchangerate )
  569. {
  570. $form->update_exchangerate( $dbh, $form->{currency},
  571. $form->{"datepaid_$i"},
  572. 0, $form->{"exchangerate_$i"} );
  573. }
  574. }
  575. }
  576. # set values which could be empty
  577. $form->{taxincluded} *= 1;
  578. $form->{invnumber} = $form->update_defaults( $myconfig, "vinumber", $dbh )
  579. unless $form->{invnumber};
  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;