summaryrefslogtreecommitdiff
path: root/LedgerSMB/IR.pm
blob: 9f2da830558d17f33aacdee8f9291e6963b5a7be (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 NOT undergone whitespace cleanup.
  27. #
  28. #======================================================================
  29. #
  30. # Inventory received module
  31. #
  32. #======================================================================
  33. package IR;
  34. use LedgerSMB::Tax;
  35. use LedgerSMB::PriceMatrix;
  36. sub post_invoice {
  37. my ($self, $myconfig, $form) = @_;
  38. # connect to database, turn off autocommit
  39. my $dbh = $form->dbconnect_noauto($myconfig);
  40. my $query;
  41. my $sth;
  42. my $ref;
  43. my $null;
  44. my $project_id;
  45. my $exchangerate = 0;
  46. my $allocated;
  47. my $taxrate;
  48. my $taxamount;
  49. my $diff = 0;
  50. my $item;
  51. my $invoice_id;
  52. my $keepcleared;
  53. ($null, $form->{employee_id}) = split /--/, $form->{employee};
  54. unless ($form->{employee_id}) {
  55. ($form->{employee}, $form->{employee_id}) = $form->get_employee($dbh);
  56. }
  57. ($null, $form->{department_id}) = split(/--/, $form->{department});
  58. $form->{department_id} *= 1;
  59. $query = qq|SELECT fxgain_accno_id, fxloss_accno_id
  60. FROM defaults d|;
  61. my ($fxgain_accno_id, $fxloss_accno_id) = $dbh->selectrow_array($query);
  62. $query = qq|SELECT inventory_accno_id, income_accno_id, expense_accno_id
  63. FROM parts
  64. WHERE id = ?|;
  65. my $pth = $dbh->prepare($query) || $form->dberror($query);
  66. my %updparts = ();
  67. if ($form->{id}) {
  68. $keepcleared = 1;
  69. $query = qq|SELECT id FROM ap
  70. WHERE id = $form->{id}|;
  71. if ($dbh->selectrow_array($query)) {
  72. $query = qq|SELECT p.id, p.inventory_accno_id, p.income_accno_id
  73. FROM invoice i
  74. JOIN parts p ON (p.id = i.parts_id)
  75. WHERE i.trans_id = $form->{id}|;
  76. $sth = $dbh->prepare($query);
  77. $sth->execute || $form->dberror($query);
  78. while ($ref = $sth->fetchrow_hashref) {
  79. if ($ref->{inventory_accno_id} && $ref->{income_accno_id}) {
  80. $updparts{$ref->{id}} = 1;
  81. }
  82. }
  83. $sth->finish;
  84. &reverse_invoice($dbh, $form);
  85. } else {
  86. $query = qq|INSERT INTO ap (id)
  87. VALUES ($form->{id})|;
  88. $dbh->do($query) || $form->dberror($query);
  89. }
  90. }
  91. my $uid = localtime;
  92. $uid .= "$$";
  93. if (! $form->{id}) {
  94. $query = qq|INSERT INTO ap (invnumber, employee_id)
  95. VALUES ('$uid', (SELECT id FROM employee
  96. WHERE login = '$form->{login}'))|;
  97. $dbh->do($query) || $form->dberror($query);
  98. $query = qq|SELECT id FROM ap
  99. WHERE invnumber = '$uid'|;
  100. $sth = $dbh->prepare($query);
  101. $sth->execute || $form->dberror($query);
  102. ($form->{id}) = $sth->fetchrow_array;
  103. $sth->finish;
  104. }
  105. my $amount;
  106. my $grossamount;
  107. my $allocated;
  108. my $invamount = 0;
  109. my $invnetamount = 0;
  110. if ($form->{currency} eq $form->{defaultcurrency}) {
  111. $form->{exchangerate} = 1;
  112. } else {
  113. $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
  114. }
  115. $form->{exchangerate} = ($exchangerate) ? $exchangerate : $form->parse_amount($myconfig, $form->{exchangerate});
  116. for my $i (1 .. $form->{rowcount}) {
  117. $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
  118. if ($form->{"qty_$i"}) {
  119. $pth->execute($form->{"id_$i"});
  120. $ref = $pth->fetchrow_hashref(NAME_lc);
  121. for (keys %$ref) {
  122. $form->{"${_}_$i"} = $ref->{$_};
  123. }
  124. $pth->finish;
  125. # project
  126. $project_id = 'NULL';
  127. if ($form->{"projectnumber_$i"} ne "") {
  128. ($null, $project_id) = split /--/, $form->{"projectnumber_$i"};
  129. }
  130. # undo discount formatting
  131. $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
  132. # keep entered selling price
  133. my $fxsellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
  134. my ($dec) = ($fxsellprice =~ /\.(\d+)/);
  135. $dec = length $dec;
  136. my $decimalplaces = ($dec > 2) ? $dec : 2;
  137. # deduct discount
  138. $form->{"sellprice_$i"} = $fxsellprice - $form->round_amount($fxsellprice * $form->{"discount_$i"}, $decimalplaces);
  139. # linetotal
  140. my $fxlinetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
  141. $amount = $fxlinetotal * $form->{exchangerate};
  142. my $linetotal = $form->round_amount($amount, 2);
  143. $fxdiff += $amount - $linetotal;
  144. @taxaccounts = Tax::init_taxes($form, $form->{"taxaccounts_$i"});
  145. $tax = Math::BigFloat->bzero();
  146. $fxtax = Math::BigFloat->bzero();
  147. if ($form->{taxincluded}) {
  148. $tax += $amount = Tax::calculate_taxes(\@taxaccounts, $form,
  149. $linetotal, 1);
  150. $form->{"sellprice_$i"} -= $amount / $form{"qty_$i"};
  151. } else {
  152. $tax += $amount = Tax::calculate_taxes(\@taxaccounts, $form,
  153. $linetotal, 0);
  154. $fxtax += Tax::calculate_taxes(\@taxaccounts, $form,
  155. $fxlinetotal, 0);
  156. }
  157. for (@taxaccounts) {
  158. $form->{acc_trans}{$form->{id}}{$_->account}{amount} += $_->value;
  159. }
  160. $grossamount = $form->round_amount($linetotal, 2);
  161. if ($form->{taxincluded}) {
  162. $amount = $form->round_amount($tax, 2);
  163. $linetotal -= $form->round_amount($tax - $diff, 2);
  164. $diff = ($amount - $tax);
  165. }
  166. $amount = $form->round_amount($linetotal, 2);
  167. $allocated = 0;
  168. # adjust and round sellprice
  169. $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
  170. # save detail record in invoice table
  171. $query = qq|INSERT INTO invoice (description)
  172. VALUES ('$uid')|;
  173. $dbh->do($query) || $form->dberror($query);
  174. $query = qq|SELECT id FROM invoice
  175. WHERE description = '$uid'|;
  176. ($invoice_id) = $dbh->selectrow_array($query);
  177. $query = qq|UPDATE invoice SET
  178. trans_id = $form->{id},
  179. parts_id = $form->{"id_$i"},
  180. description = |.$dbh->quote($form->{"description_$i"}).qq|,
  181. qty = $form->{"qty_$i"} * -1,
  182. sellprice = $form->{"sellprice_$i"},
  183. fxsellprice = $fxsellprice,
  184. discount = $form->{"discount_$i"},
  185. allocated = $allocated,
  186. unit = |.$dbh->quote($form->{"unit_$i"}).qq|,
  187. deliverydate = |.$form->dbquote($form->{"deliverydate_$i"}, SQL_DATE).qq|,
  188. project_id = $project_id,
  189. serialnumber = |.$dbh->quote($form->{"serialnumber_$i"}).qq|,
  190. notes = |.$dbh->quote($form->{"notes_$i"}).qq|
  191. WHERE id = $invoice_id|;
  192. $dbh->do($query) || $form->dberror($query);
  193. if ($form->{"inventory_accno_id_$i"}) {
  194. # add purchase to inventory
  195. push @{ $form->{acc_trans}{lineitems} }, {
  196. chart_id => $form->{"inventory_accno_id_$i"},
  197. amount => $amount,
  198. fxgrossamount => $fxlinetotal + $form->round_amount($fxtax, 2),
  199. grossamount => $grossamount,
  200. project_id => $project_id,
  201. invoice_id => $invoice_id };
  202. $updparts{$form->{"id_$i"}} = 1;
  203. # update parts table
  204. $form->update_balance($dbh,
  205. "parts",
  206. "onhand",
  207. qq|id = $form->{"id_$i"}|,
  208. $form->{"qty_$i"}) unless $form->{shipped};
  209. # check if we sold the item
  210. $query = qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.project_id,
  211. p.inventory_accno_id, p.expense_accno_id, a.transdate
  212. FROM invoice i
  213. JOIN parts p ON (p.id = i.parts_id)
  214. JOIN ar a ON (a.id = i.trans_id)
  215. WHERE i.parts_id = $form->{"id_$i"}
  216. AND (i.qty + i.allocated) > 0
  217. ORDER BY transdate|;
  218. $sth = $dbh->prepare($query);
  219. $sth->execute || $form->dberror($query);
  220. my $totalqty = $form->{"qty_$i"};
  221. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  222. my $qty = $ref->{qty} + $ref->{allocated};
  223. if (($qty - $totalqty) > 0) {
  224. $qty = $totalqty;
  225. }
  226. $linetotal = $form->round_amount($form->{"sellprice_$i"} * $qty, 2);
  227. $ref->{project_id} ||= 'NULL';
  228. # add entry for inventory, this one is for the sold item
  229. if ($linetotal) {
  230. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  231. transdate, project_id, invoice_id)
  232. VALUES ($ref->{trans_id}, $ref->{inventory_accno_id},
  233. $linetotal, '$ref->{transdate}', $ref->{project_id},
  234. $invoice_id)|;
  235. $dbh->do($query) || $form->dberror($query);
  236. # add expense
  237. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  238. transdate, project_id, invoice_id)
  239. VALUES ($ref->{trans_id}, $ref->{expense_accno_id},
  240. |. ($linetotal * -1) .qq|, '$ref->{transdate}',
  241. $ref->{project_id}, $invoice_id)|;
  242. $dbh->do($query) || $form->dberror($query);
  243. }
  244. # update allocated for sold item
  245. $form->update_balance($dbh,
  246. "invoice",
  247. "allocated",
  248. qq|id = $ref->{id}|,
  249. $qty * -1);
  250. $allocated += $qty;
  251. last if (($totalqty -= $qty) <= 0);
  252. }
  253. $sth->finish;
  254. } else {
  255. # add purchase to expense
  256. push @{ $form->{acc_trans}{lineitems} }, {
  257. chart_id => $form->{"expense_accno_id_$i"},
  258. amount => $amount,
  259. fxgrossamount => $fxlinetotal + $form->round_amount($fxtax, 2),
  260. grossamount => $grossamount,
  261. project_id => $project_id,
  262. invoice_id => $invoice_id };
  263. }
  264. }
  265. }
  266. $form->{paid} = 0;
  267. for $i (1 .. $form->{paidaccounts}) {
  268. $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
  269. $form->{paid} += $form->{"paid_$i"};
  270. $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
  271. }
  272. # add lineitems + tax
  273. $amount = 0;
  274. $grossamount = 0;
  275. $fxgrossamount = 0;
  276. for (@{ $form->{acc_trans}{lineitems} }) {
  277. $amount += $_->{amount};
  278. $grossamount += $_->{grossamount};
  279. $fxgrossamount += $_->{fxgrossamount};
  280. }
  281. $invnetamount = $amount;
  282. $amount = 0;
  283. for (split / /, $form->{taxaccounts}) {
  284. $amount += $form->{acc_trans}{$form->{id}}{$_}{amount} = $form->round_amount($form->{acc_trans}{$form->{id}}{$_}{amount}, 2);
  285. $form->{acc_trans}{$form->{id}}{$_}{amount} *= -1;
  286. }
  287. $invamount = $invnetamount + $amount;
  288. $diff = 0;
  289. if ($form->{taxincluded}) {
  290. $diff = $form->round_amount($grossamount - $invamount, 2);
  291. $invamount += $diff;
  292. }
  293. $fxdiff = $form->round_amount($fxdiff,2);
  294. $invnetamount += $fxdiff;
  295. $invamount += $fxdiff;
  296. if ($form->round_amount($form->{paid} - $fxgrossamount,2) == 0) {
  297. $form->{paid} = $invamount;
  298. } else {
  299. $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate}, 2);
  300. }
  301. foreach $ref (sort { $b->{amount} <=> $a->{amount} } @ { $form->{acc_trans}{lineitems} }) {
  302. $amount = $ref->{amount} + $diff + $fxdiff;
  303. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  304. transdate, project_id, invoice_id)
  305. VALUES ($form->{id}, $ref->{chart_id}, $amount * -1,
  306. '$form->{transdate}', $ref->{project_id}, $ref->{invoice_id})|;
  307. $dbh->do($query) || $form->dberror($query);
  308. $diff = 0;
  309. $fxdiff = 0;
  310. }
  311. $form->{payables} = $invamount;
  312. delete $form->{acc_trans}{lineitems};
  313. # update exchangerate
  314. if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
  315. $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, 0, $form->{exchangerate});
  316. }
  317. # record payable
  318. if ($form->{payables}) {
  319. ($accno) = split /--/, $form->{AP};
  320. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  321. transdate)
  322. VALUES ($form->{id},
  323. (SELECT id FROM chart
  324. WHERE accno = '$accno'),
  325. $form->{payables}, '$form->{transdate}')|;
  326. $dbh->do($query) || $form->dberror($query);
  327. }
  328. foreach my $trans_id (keys %{$form->{acc_trans}}) {
  329. foreach my $accno (keys %{ $form->{acc_trans}{$trans_id} }) {
  330. $amount = $form->round_amount($form->{acc_trans}{$trans_id}{$accno}{amount}, 2);
  331. if ($amount) {
  332. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  333. transdate)
  334. VALUES ($trans_id, (SELECT id FROM chart
  335. WHERE accno = '$accno'),
  336. $amount, '$form->{transdate}')|;
  337. $dbh->do($query) || $form->dberror($query);
  338. }
  339. }
  340. }
  341. # if there is no amount but a payment record payable
  342. if ($invamount == 0) {
  343. $form->{payables} = 1;
  344. }
  345. my $cleared = 0;
  346. # record payments and offsetting AP
  347. for my $i (1 .. $form->{paidaccounts}) {
  348. if ($form->{"paid_$i"}) {
  349. my ($accno) = split /--/, $form->{"AP_paid_$i"};
  350. $form->{"datepaid_$i"} = $form->{transdate} unless ($form->{"datepaid_$i"});
  351. $form->{datepaid} = $form->{"datepaid_$i"};
  352. $exchangerate = 0;
  353. if ($form->{currency} eq $form->{defaultcurrency}) {
  354. $form->{"exchangerate_$i"} = 1;
  355. } else {
  356. $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
  357. $form->{"exchangerate_$i"} = ($exchangerate) ? $exchangerate : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
  358. }
  359. # record AP
  360. $amount = ($form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2)) * -1;
  361. if ($form->{payables}) {
  362. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  363. transdate)
  364. VALUES ($form->{id}, (SELECT id FROM chart
  365. WHERE accno = '$form->{AP}'),
  366. $amount, '$form->{"datepaid_$i"}')|;
  367. $dbh->do($query) || $form->dberror($query);
  368. }
  369. if ($keepcleared) {
  370. $cleared = ($form->{"cleared_$i"}) ? 1 : 0;
  371. }
  372. # record payment
  373. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
  374. source, memo, cleared)
  375. VALUES ($form->{id}, (SELECT id FROM chart
  376. WHERE accno = '$accno'),
  377. $form->{"paid_$i"}, '$form->{"datepaid_$i"}', |
  378. .$dbh->quote($form->{"source_$i"}).qq|, |
  379. .$dbh->quote($form->{"memo_$i"}).qq|, '$cleared')|;
  380. $dbh->do($query) || $form->dberror($query);
  381. # exchangerate difference
  382. $amount = $form->round_amount($form->{"paid_$i"} * $form->{"exchangerate_$i"} - $form->{"paid_$i"}, 2);
  383. if ($amount) {
  384. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  385. transdate, source, fx_transaction, cleared)
  386. VALUES ($form->{id}, (SELECT id FROM chart
  387. WHERE accno = '$accno'),
  388. $amount, '$form->{"datepaid_$i"}', |
  389. .$dbh->quote($form->{"source_$i"}).qq|, '1', '$cleared')|;
  390. $dbh->do($query) || $form->dberror($query);
  391. }
  392. # gain/loss
  393. $amount = $form->round_amount($form->round_amount($form->{"paid_$i"} * $form->{exchangerate},2) - $form->round_amount($form->{"paid_$i"} * $form->{"exchangerate_$i"},2), 2);
  394. if ($amount) {
  395. my $accno_id = ($amount > 0) ? $fxgain_accno_id : $fxloss_accno_id;
  396. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  397. transdate, fx_transaction, cleared)
  398. VALUES ($form->{id}, $accno_id,
  399. $amount, '$form->{"datepaid_$i"}', '1', '$cleared')|;
  400. $dbh->do($query) || $form->dberror($query);
  401. }
  402. # update exchange rate
  403. if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
  404. $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"});
  405. }
  406. }
  407. }
  408. # set values which could be empty
  409. $form->{taxincluded} *= 1;
  410. $form->{invnumber} = $form->update_defaults($myconfig, "vinumber", $dbh) unless $form->{invnumber};
  411. # save AP record
  412. $query = qq|UPDATE ap set
  413. invnumber = |.$dbh->quote($form->{invnumber}).qq|,
  414. ordnumber = |.$dbh->quote($form->{ordnumber}).qq|,
  415. quonumber = |.$dbh->quote($form->{quonumber}).qq|,
  416. transdate = '$form->{transdate}',
  417. vendor_id = $form->{vendor_id},
  418. amount = $invamount,
  419. netamount = $invnetamount,
  420. paid = $form->{paid},
  421. datepaid = |.$form->dbquote($form->{datepaid}, SQL_DATE).qq|,
  422. duedate = |.$form->dbquote($form->{duedate}, SQL_DATE).qq|,
  423. invoice = '1',
  424. shippingpoint = |.$dbh->quote($form->{shippingpoint}).qq|,
  425. shipvia = |.$dbh->quote($form->{shipvia}).qq|,
  426. taxincluded = '$form->{taxincluded}',
  427. notes = |.$dbh->quote($form->{notes}).qq|,
  428. intnotes = |.$dbh->quote($form->{intnotes}).qq|,
  429. curr = '$form->{currency}',
  430. department_id = $form->{department_id},
  431. employee_id = $form->{employee_id},
  432. language_code = '$form->{language_code}',
  433. ponumber = |.$dbh->quote($form->{ponumber}).qq|
  434. WHERE id = $form->{id}|;
  435. $dbh->do($query) || $form->dberror($query);
  436. # add shipto
  437. $form->{name} = $form->{vendor};
  438. $form->{name} =~ s/--$form->{vendor_id}//;
  439. $form->add_shipto($dbh, $form->{id});
  440. my %audittrail = ( tablename => 'ap',
  441. reference => $form->{invnumber},
  442. formname => $form->{type},
  443. action => 'posted',
  444. id => $form->{id} );
  445. $form->audittrail($dbh, "", \%audittrail);
  446. my $rc = $dbh->commit;
  447. foreach $item (keys %updparts) {
  448. $query = qq|UPDATE parts SET
  449. avgcost = avgcost($item),
  450. lastcost = lastcost($item)
  451. WHERE id = $item|;
  452. $dbh->do($query) || $form->dberror($query);
  453. $dbh->commit;
  454. }
  455. $dbh->disconnect;
  456. $rc;
  457. }
  458. sub reverse_invoice {
  459. my ($dbh, $form) = @_;
  460. my $query = qq|SELECT id FROM ap
  461. WHERE id = $form->{id}|;
  462. my ($id) = $dbh->selectrow_array($query);
  463. return unless $id;
  464. # reverse inventory items
  465. $query = qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id,
  466. i.qty, i.allocated, i.sellprice, i.project_id
  467. FROM invoice i, parts p
  468. WHERE i.parts_id = p.id
  469. AND i.trans_id = $form->{id}|;
  470. my $sth = $dbh->prepare($query);
  471. $sth->execute || $form->dberror($query);
  472. my $netamount = 0;
  473. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  474. $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
  475. if ($ref->{inventory_accno_id}) {
  476. # update onhand
  477. $form->update_balance($dbh,
  478. "parts",
  479. "onhand",
  480. qq|id = $ref->{parts_id}|,
  481. $ref->{qty});
  482. # if $ref->{allocated} > 0 than we sold that many items
  483. if ($ref->{allocated} > 0) {
  484. # get references for sold items
  485. $query = qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
  486. FROM invoice i, ar a
  487. WHERE i.parts_id = $ref->{parts_id}
  488. AND i.allocated < 0
  489. AND i.trans_id = a.id
  490. ORDER BY transdate DESC|;
  491. my $sth = $dbh->prepare($query);
  492. $sth->execute || $form->dberror($query);
  493. while (my $pthref = $sth->fetchrow_hashref(NAME_lc)) {
  494. my $qty = $ref->{allocated};
  495. if (($ref->{allocated} + $pthref->{allocated}) > 0) {
  496. $qty = $pthref->{allocated} * -1;
  497. }
  498. my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
  499. #adjust allocated
  500. $form->update_balance($dbh,
  501. "invoice",
  502. "allocated",
  503. qq|id = $pthref->{id}|,
  504. $qty);
  505. # add reversal for sale
  506. $ref->{project_id} *= 1;
  507. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  508. transdate, project_id)
  509. VALUES ($pthref->{trans_id}, $ref->{expense_accno_id},
  510. $amount, '$form->{transdate}', $ref->{project_id})|;
  511. $dbh->do($query) || $form->dberror($query);
  512. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  513. transdate, project_id)
  514. VALUES ($pthref->{trans_id}, $ref->{inventory_accno_id},
  515. $amount * -1, '$form->{transdate}', $ref->{project_id})|;
  516. $dbh->do($query) || $form->dberror($query);
  517. last if (($ref->{allocated} -= $qty) <= 0);
  518. }
  519. $sth->finish;
  520. }
  521. }
  522. }
  523. $sth->finish;
  524. # delete acc_trans
  525. $query = qq|DELETE FROM acc_trans
  526. WHERE trans_id = $form->{id}|;
  527. $dbh->do($query) || $form->dberror($query);
  528. # delete invoice entries
  529. $query = qq|DELETE FROM invoice
  530. WHERE trans_id = $form->{id}|;
  531. $dbh->do($query) || $form->dberror($query);
  532. $query = qq|DELETE FROM shipto
  533. WHERE trans_id = $form->{id}|;
  534. $dbh->do($query) || $form->dberror($query);
  535. $dbh->commit;
  536. }
  537. sub delete_invoice {
  538. my ($self, $myconfig, $form) = @_;
  539. # connect to database
  540. my $dbh = $form->dbconnect_noauto($myconfig);
  541. my %audittrail = ( tablename => 'ap',
  542. reference => $form->{invnumber},
  543. formname => $form->{type},
  544. action => 'deleted',
  545. id => $form->{id} );
  546. $form->audittrail($dbh, "", \%audittrail);
  547. my $query = qq|SELECT parts_id FROM invoice
  548. WHERE trans_id = $form->{id}|;
  549. my $sth = $dbh->prepare($query);
  550. $sth->execute || $form->dberror($query);
  551. my $item;
  552. my %updparts = ();
  553. while (($item) = $sth->fetchrow_array) {
  554. $updparts{$item} = 1;
  555. }
  556. $sth->finish;
  557. &reverse_invoice($dbh, $form);
  558. # delete AP record
  559. $query = qq|DELETE FROM ap
  560. WHERE id = $form->{id}|;
  561. $dbh->do($query) || $form->dberror($query);
  562. # delete spool files
  563. $query = qq|SELECT spoolfile FROM status
  564. WHERE trans_id = $form->{id}
  565. AND spoolfile IS NOT NULL|;
  566. my $sth = $dbh->prepare($query);
  567. $sth->execute || $form->dberror($query);
  568. my $spoolfile;
  569. my @spoolfiles = ();
  570. while (($spoolfile) = $sth->fetchrow_array) {
  571. push @spoolfiles, $spoolfile;
  572. }
  573. $sth->finish;
  574. # delete status entries
  575. $query = qq|DELETE FROM status
  576. WHERE trans_id = $form->{id}|;
  577. $dbh->do($query) || $form->dberror($query);
  578. my $rc = $dbh->commit;
  579. if ($rc) {
  580. foreach $item (keys %updparts) {
  581. $query = qq|UPDATE parts SET
  582. avgcost = avgcost($item),
  583. lastcost = lastcost($item)
  584. WHERE id = $item|;
  585. $dbh->do($query) || $form->dberror($query);
  586. $dbh->commit;
  587. }
  588. foreach $spoolfile (@spoolfiles) {
  589. unlink "$spool/$spoolfile" if $spoolfile;
  590. }
  591. }
  592. $dbh->disconnect;
  593. $rc;
  594. }
  595. sub retrieve_invoice {
  596. my ($self, $myconfig, $form) = @_;
  597. # connect to database
  598. my $dbh = $form->dbconnect_noauto($myconfig);
  599. my $query;
  600. if ($form->{id}) {
  601. # get default accounts and last invoice number
  602. $query = qq|SELECT (SELECT c.accno FROM chart c
  603. WHERE d.inventory_accno_id = c.id) AS inventory_accno,
  604. (SELECT c.accno FROM chart c
  605. WHERE d.income_accno_id = c.id) AS income_accno,
  606. (SELECT c.accno FROM chart c
  607. WHERE d.expense_accno_id = c.id) AS expense_accno,
  608. (SELECT c.accno FROM chart c
  609. WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
  610. (SELECT c.accno FROM chart c
  611. WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
  612. d.curr AS currencies
  613. FROM defaults d|;
  614. } else {
  615. $query = qq|SELECT (SELECT c.accno FROM chart c
  616. WHERE d.inventory_accno_id = c.id) AS inventory_accno,
  617. (SELECT c.accno FROM chart c
  618. WHERE d.income_accno_id = c.id) AS income_accno,
  619. (SELECT c.accno FROM chart c
  620. WHERE d.expense_accno_id = c.id) AS expense_accno,
  621. (SELECT c.accno FROM chart c
  622. WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
  623. (SELECT c.accno FROM chart c
  624. WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
  625. d.curr AS currencies,
  626. current_date AS transdate
  627. FROM defaults d|;
  628. }
  629. my $sth = $dbh->prepare($query);
  630. $sth->execute || $form->dberror($query);
  631. my $ref = $sth->fetchrow_hashref(NAME_lc);
  632. for (keys %$ref) {
  633. $form->{$_} = $ref->{$_};
  634. }
  635. $sth->finish;
  636. if ($form->{id}) {
  637. # retrieve invoice
  638. $query = qq|SELECT a.invnumber, a.transdate, a.duedate,
  639. a.ordnumber, a.quonumber, a.paid, a.taxincluded, a.notes,
  640. a.intnotes, a.curr AS currency, a.vendor_id, a.language_code,
  641. a.ponumber
  642. FROM ap a
  643. WHERE id = $form->{id}|;
  644. $sth = $dbh->prepare($query);
  645. $sth->execute || $form->dberror($query);
  646. $ref = $sth->fetchrow_hashref(NAME_lc);
  647. for (keys %$ref) {
  648. $form->{$_} = $ref->{$_};
  649. }
  650. $sth->finish;
  651. # get shipto
  652. $query = qq|SELECT * FROM shipto
  653. WHERE trans_id = $form->{id}|;
  654. $sth = $dbh->prepare($query);
  655. $sth->execute || $form->dberror($query);
  656. $ref = $sth->fetchrow_hashref(NAME_lc);
  657. for (keys %$ref) {
  658. $form->{$_} = $ref->{$_};
  659. }
  660. $sth->finish;
  661. # retrieve individual items
  662. $query = qq|SELECT
  663. p.partnumber, i.description, i.qty, i.fxsellprice, i.sellprice,
  664. i.parts_id AS id, i.unit, p.bin, i.deliverydate,
  665. pr.projectnumber,
  666. i.project_id, i.serialnumber, i.discount, i.notes,
  667. pg.partsgroup, p.partsgroup_id, p.partnumber AS sku,
  668. p.weight, p.onhand,
  669. p.inventory_accno_id, p.income_accno_id, p.expense_accno_id,
  670. t.description AS partsgrouptranslation
  671. FROM invoice i
  672. JOIN parts p ON (i.parts_id = p.id)
  673. LEFT JOIN project pr ON (i.project_id = pr.id)
  674. LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
  675. LEFT JOIN translation t ON (t.trans_id = p.partsgroup_id AND t.language_code = '$form->{language_code}')
  676. WHERE i.trans_id = $form->{id}
  677. ORDER BY i.id|;
  678. $sth = $dbh->prepare($query);
  679. $sth->execute || $form->dberror($query);
  680. # exchangerate defaults
  681. &exchangerate_defaults($dbh, $form);
  682. # price matrix and vendor partnumber
  683. my $pmh = PriceMatrix::PriceMatrixQuery($dbh, $form);
  684. # tax rates for part
  685. $query = qq|SELECT c.accno
  686. FROM chart c
  687. JOIN partstax pt ON (pt.chart_id = c.id)
  688. WHERE pt.parts_id = ?|;
  689. my $tth = $dbh->prepare($query);
  690. my $ptref;
  691. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  692. my ($dec) = ($ref->{fxsellprice} =~ /\.(\d+)/);
  693. $dec = length $dec;
  694. my $decimalplaces = ($dec > 2) ? $dec : 2;
  695. $tth->execute($ref->{id});
  696. $ref->{taxaccounts} = "";
  697. my $taxrate = 0;
  698. while ($ptref = $tth->fetchrow_hashref(NAME_lc)) {
  699. $ref->{taxaccounts} .= "$ptref->{accno} ";
  700. $taxrate += $form->{"$ptref->{accno}_rate"};
  701. }
  702. $tth->finish;
  703. chop $ref->{taxaccounts};
  704. # price matrix
  705. $ref->{sellprice} = $form->round_amount($ref->{fxsellprice} * $form->{$form->{currency}}, $decimalplaces);
  706. PriceMatrix::price_matrix($pmh, $ref, $decimalplaces, $form, $myconfig);
  707. $ref->{sellprice} = $ref->{fxsellprice};
  708. $ref->{qty} *= -1;
  709. $ref->{partsgroup} = $ref->{partsgrouptranslation} if $ref->{partsgrouptranslation};
  710. push @{ $form->{invoice_details} }, $ref;
  711. }
  712. $sth->finish;
  713. }
  714. my $rc = $dbh->commit;
  715. $dbh->disconnect;
  716. $rc;
  717. }
  718. sub retrieve_item {
  719. my ($self, $myconfig, $form) = @_;
  720. my $i = $form->{rowcount};
  721. my $null;
  722. my $var;
  723. # don't include assemblies or obsolete parts
  724. my $where = "WHERE p.assembly = '0' AND p.obsolete = '0'";
  725. if ($form->{"partnumber_$i"} ne "") {
  726. $var = $form->like(lc $form->{"partnumber_$i"});
  727. $where .= " AND lower(p.partnumber) LIKE '$var'";
  728. }
  729. if ($form->{"description_$i"} ne "") {
  730. $var = $form->like(lc $form->{"description_$i"});
  731. if ($form->{language_code} ne "") {
  732. $where .= " AND lower(t1.description) LIKE '$var'";
  733. } else {
  734. $where .= " AND lower(p.description) LIKE '$var'";
  735. }
  736. }
  737. if ($form->{"partsgroup_$i"} ne "") {
  738. ($null, $var) = split /--/, $form->{"partsgroup_$i"};
  739. $var *= 1;
  740. $where .= qq| AND p.partsgroup_id = $var|;
  741. }
  742. if ($form->{"description_$i"} ne "") {
  743. $where .= " ORDER BY 3";
  744. } else {
  745. $where .= " ORDER BY 2";
  746. }
  747. # connect to database
  748. my $dbh = $form->dbconnect($myconfig);
  749. my $query = qq|SELECT p.id, p.partnumber, p.description,
  750. pg.partsgroup, p.partsgroup_id,
  751. p.lastcost AS sellprice, p.unit, p.bin, p.onhand, p.notes,
  752. p.inventory_accno_id, p.income_accno_id, p.expense_accno_id,
  753. p.partnumber AS sku, p.weight,
  754. t1.description AS translation,
  755. t2.description AS grouptranslation
  756. FROM parts p
  757. LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
  758. LEFT JOIN translation t1 ON (t1.trans_id = p.id AND t1.language_code = '$form->{language_code}')
  759. LEFT JOIN translation t2 ON (t2.trans_id = p.partsgroup_id AND t2.language_code = '$form->{language_code}')
  760. $where|;
  761. my $sth = $dbh->prepare($query);
  762. $sth->execute || $form->dberror($query);
  763. # foreign currency
  764. &exchangerate_defaults($dbh, $form);
  765. # taxes
  766. $query = qq|SELECT c.accno
  767. FROM chart c
  768. JOIN partstax pt ON (pt.chart_id = c.id)
  769. WHERE pt.parts_id = ?|;
  770. my $tth = $dbh->prepare($query) || $form->dberror($query);
  771. # price matrix
  772. my $pmh = PriceMatrix::price_matrix_query($dbh, $form);
  773. my $ref;
  774. my $ptref;
  775. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  776. my ($dec) = ($ref->{sellprice} =~ /\.(\d+)/);
  777. $dec = length $dec;
  778. my $decimalplaces = ($dec > 2) ? $dec : 2;
  779. # get taxes for part
  780. $tth->execute($ref->{id});
  781. $ref->{taxaccounts} = "";
  782. while ($ptref = $tth->fetchrow_hashref(NAME_lc)) {
  783. $ref->{taxaccounts} .= "$ptref->{accno} ";
  784. }
  785. $tth->finish;
  786. chop $ref->{taxaccounts};
  787. # get vendor price and partnumber
  788. PriceMatrix::price_matrix($pmh, $ref, $decimalplaces, $form, $myconfig);
  789. $ref->{description} = $ref->{translation} if $ref->{translation};
  790. $ref->{partsgroup} = $ref->{grouptranslation} if $ref->{grouptranslation};
  791. push @{ $form->{item_list} }, $ref;
  792. }
  793. $sth->finish;
  794. $dbh->disconnect;
  795. }
  796. sub exchangerate_defaults {
  797. my ($dbh, $form) = @_;
  798. my $var;
  799. # get default currencies
  800. my $query = qq|SELECT substr(curr,1,3), curr FROM defaults|;
  801. my $eth = $dbh->prepare($query) || $form->dberror($query);
  802. $eth->execute;
  803. ($form->{defaultcurrency}, $form->{currencies}) = $eth->fetchrow_array;
  804. $eth->finish;
  805. $query = qq|SELECT sell
  806. FROM exchangerate
  807. WHERE curr = ?
  808. AND transdate = ?|;
  809. my $eth1 = $dbh->prepare($query) || $form->dberror($query);
  810. $query = qq~SELECT max(transdate || ' ' || sell || ' ' || curr)
  811. FROM exchangerate
  812. WHERE curr = ?~;
  813. my $eth2 = $dbh->prepare($query) || $form->dberror($query);
  814. # get exchange rates for transdate or max
  815. foreach $var (split /:/, substr($form->{currencies},4)) {
  816. $eth1->execute($var, $form->{transdate});
  817. ($form->{$var}) = $eth1->fetchrow_array;
  818. if (! $form->{$var} ) {
  819. $eth2->execute($var);
  820. ($form->{$var}) = $eth2->fetchrow_array;
  821. ($null, $form->{$var}) = split / /, $form->{$var};
  822. $form->{$var} = 1 unless $form->{$var};
  823. $eth2->finish;
  824. }
  825. $eth1->finish;
  826. }
  827. $form->{$form->{currency}} = $form->{exchangerate} if $form->{exchangerate};
  828. $form->{$form->{currency}} ||= 1;
  829. $form->{$form->{defaultcurrency}} = 1;
  830. }
  831. sub vendor_details {
  832. my ($self, $myconfig, $form) = @_;
  833. # connect to database
  834. my $dbh = $form->dbconnect($myconfig);
  835. # get rest for the vendor
  836. my $query = qq|SELECT vendornumber, name, address1, address2, city, state,
  837. zipcode, country,
  838. contact, phone as vendorphone, fax as vendorfax, vendornumber,
  839. taxnumber AS vendortaxnumber, sic_code AS sic, iban, bic,
  840. gifi_accno AS gifi, startdate, enddate
  841. FROM vendor
  842. WHERE id = $form->{vendor_id}|;
  843. my $sth = $dbh->prepare($query);
  844. $sth->execute || $form->dberror($query);
  845. $ref = $sth->fetchrow_hashref(NAME_lc);
  846. for (keys %$ref) {
  847. $form->{$_} = $ref->{$_};
  848. }
  849. $sth->finish;
  850. $dbh->disconnect;
  851. }
  852. sub item_links {
  853. my ($self, $myconfig, $form) = @_;
  854. # connect to database
  855. my $dbh = $form->dbconnect($myconfig);
  856. my $query = qq|SELECT accno, description, link
  857. FROM chart
  858. WHERE link LIKE '%IC%'
  859. ORDER BY accno|;
  860. my $sth = $dbh->prepare($query);
  861. $sth->execute || $form->dberror($query);
  862. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  863. foreach my $key (split(/:/, $ref->{link})) {
  864. if ($key =~ /IC/) {
  865. push @{ $form->{IC_links}{$key} }, { accno => $ref->{accno},
  866. description => $ref->{description} };
  867. }
  868. }
  869. }
  870. $sth->finish;
  871. }
  872. 1;