summaryrefslogtreecommitdiff
path: root/LedgerSMB/IS.pm
blob: a04a6dcf4e0d0bc41e53df1fb2740eb992cf5086 (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 invoicing module
  31. #
  32. #======================================================================
  33. package IS;
  34. use LedgerSMB::Tax;
  35. use LedgerSMB::PriceMatrix;
  36. use LedgerSMB::Sysconfig;
  37. sub invoice_details {
  38. use LedgerSMB::CP;
  39. my ($self, $myconfig, $form) = @_;
  40. $form->{duedate} = $form->{transdate} unless ($form->{duedate});
  41. # connect to database
  42. my $dbh = $form->{dbh};
  43. my $query = qq|
  44. SELECT ?::date - ?::date
  45. AS terms, value
  46. FROM defaults
  47. WHERE setting_key = 'weightunit'|;
  48. my $sth = $dbh->prepare($query);
  49. $sth->execute($form->{duedate}, $form->{transdate})
  50. || $form->dberror($query);
  51. ($form->{terms}, $form->{weightunit}) = $sth->fetchrow_array;
  52. $sth->finish;
  53. # this is for the template
  54. $form->{invdate} = $form->{transdate};
  55. my $tax = 0;
  56. my $item;
  57. my $i;
  58. my @sortlist = ();
  59. my $projectnumber;
  60. my $projectdescription;
  61. my $projectnumber_id;
  62. my $translation;
  63. my $partsgroup;
  64. my @taxaccounts;
  65. my %taxaccounts;
  66. my $tax;
  67. my $taxrate;
  68. my $taxamount;
  69. my %translations;
  70. $query = qq|
  71. SELECT p.description, t.description
  72. FROM project p
  73. LEFT JOIN translation t
  74. ON (t.trans_id = p.id
  75. AND t.language_code = ?)
  76. WHERE id = ?|;
  77. my $prh = $dbh->prepare($query) || $form->dberror($query);
  78. $query = qq|
  79. SELECT inventory_accno_id, income_accno_id,
  80. expense_accno_id, assembly, weight FROM parts
  81. WHERE id = ?|;
  82. my $pth = $dbh->prepare($query) || $form->dberror($query);
  83. my $sortby;
  84. # sort items by project and partsgroup
  85. for $i (1 .. $form->{rowcount} - 1) {
  86. # account numbers
  87. $pth->execute($form->{"id_$i"});
  88. $ref = $pth->fetchrow_hashref(NAME_lc);
  89. for (keys %$ref) { $form->{"${_}_$i"} = $ref->{$_} }
  90. $pth->finish;
  91. $projectnumber_id = 0;
  92. $projectnumber = "";
  93. $form->{partsgroup} = "";
  94. $form->{projectnumber} = "";
  95. if ($form->{groupprojectnumber} || $form->{grouppartsgroup}) {
  96. $inventory_accno_id =
  97. ($form->{"inventory_accno_id_$i"}
  98. || $form->{"assembly_$i"})
  99. ? "1"
  100. : "";
  101. if ($form->{groupprojectnumber}) {
  102. ($projectnumber, $projectnumber_id) =
  103. split /--/, $form->{"projectnumber_$i"};
  104. }
  105. if ($form->{grouppartsgroup}) {
  106. ($form->{partsgroup}) =
  107. split /--/, $form->{"partsgroup_$i"};
  108. }
  109. if ($projectnumber_id && $form->{groupprojectnumber}) {
  110. if ($translation{$projectnumber_id}) {
  111. $form->{projectnumber} =
  112. $translation{$projectnumber_id};
  113. } else {
  114. # get project description
  115. $prh->execute($projectnumber_id,
  116. $form->{language_code});
  117. ($projectdescription, $translation) =
  118. $prh->fetchrow_array;
  119. $prh->finish;
  120. $form->{projectnumber} =
  121. ($translation)
  122. ? "$projectnumber, $translation"
  123. : "$projectnumber, ".
  124. "$projectdescription";
  125. $translation{$projectnumber_id} =
  126. $form->{projectnumber};
  127. }
  128. }
  129. if ($form->{grouppartsgroup} && $form->{partsgroup}) {
  130. $form->{projectnumber} .= " / "
  131. if $projectnumber_id;
  132. $form->{projectnumber} .= $form->{partsgroup};
  133. }
  134. $form->format_string(projectnumber);
  135. }
  136. $sortby = qq|$projectnumber$form->{partsgroup}|;
  137. if ($form->{sortby} ne 'runningnumber') {
  138. for (qw(partnumber description bin)) {
  139. $sortby .= $form->{"${_}_$i"}
  140. if $form->{sortby} eq $_;
  141. }
  142. }
  143. push @sortlist, [ $i,
  144. qq|$projectnumber$form->{partsgroup}|.
  145. qq|$inventory_accno_id|,
  146. $form->{projectnumber}, $projectnumber_id,
  147. $form->{partsgroup}, $sortby ];
  148. }
  149. # sort the whole thing by project and group
  150. @sortlist = sort { $a->[5] cmp $b->[5] } @sortlist;
  151. my $runningnumber = 1;
  152. my $sameitem = "";
  153. my $subtotal;
  154. my $k = scalar @sortlist;
  155. my $j = 0;
  156. foreach $item (@sortlist) {
  157. $i = $item->[0];
  158. $j++;
  159. # heading
  160. if ($form->{groupprojectnumber} || $form->{grouppartsgroup}) {
  161. if ($item->[1] ne $sameitem) {
  162. $sameitem = $item->[1];
  163. $ok = 0;
  164. if ($form->{groupprojectnumber}) {
  165. $ok = $form->{"projectnumber_$i"};
  166. }
  167. if ($form->{grouppartsgroup}) {
  168. $ok = $form->{"partsgroup_$i"}
  169. unless $ok;
  170. }
  171. if ($ok) {
  172. if ($form->{"inventory_accno_id_$i"}
  173. || $form->{"assembly_$i"}) {
  174. push(@{ $form->{part} }, "");
  175. push(@{ $form->{service} },
  176. NULL);
  177. } else {
  178. push(@{ $form->{part} }, NULL);
  179. push(@{ $form->{service} }, "");
  180. }
  181. push(@{ $form->{description} },
  182. $item->[2]);
  183. for (
  184. qw(taxrates runningnumber number
  185. sku serialnumber bin qty ship
  186. unit deliverydate projectnumber
  187. sellprice listprice netprice
  188. discount discountrate linetotal
  189. weight itemnotes)
  190. ) {
  191. push(@{ $form->{$_} }, "");
  192. }
  193. push(@{ $form->{lineitems} },
  194. { amount => 0, tax => 0 });
  195. }
  196. }
  197. }
  198. $form->{"qty_$i"} =
  199. $form->parse_amount($myconfig, $form->{"qty_$i"});
  200. if ($form->{"qty_$i"}) {
  201. $form->{totalqty} += $form->{"qty_$i"};
  202. $form->{totalship} += $form->{"qty_$i"};
  203. $form->{totalweight} += ($form->{"qty_$i"}
  204. * $form->{"weight_$i"});
  205. $form->{totalweightship} += ($form->{"qty_$i"}
  206. * $form->{"weight_$i"});
  207. # add number, description and qty to $form->{number}...
  208. push(@{ $form->{runningnumber} }, $runningnumber++);
  209. push(@{ $form->{number} }, $form->{"partnumber_$i"});
  210. push(@{ $form->{sku} }, $form->{"sku_$i"});
  211. push(@{ $form->{serialnumber} },
  212. $form->{"serialnumber_$i"});
  213. push(@{ $form->{bin} }, $form->{"bin_$i"});
  214. push(@{ $form->{description} },
  215. $form->{"description_$i"});
  216. push(@{ $form->{itemnotes} }, $form->{"notes_$i"});
  217. push(@{ $form->{qty} },
  218. $form->format_amount(
  219. $myconfig, $form->{"qty_$i"}));
  220. push(@{ $form->{ship} },
  221. $form->format_amount(
  222. $myconfig, $form->{"qty_$i"}));
  223. push(@{ $form->{unit} }, $form->{"unit_$i"});
  224. push(@{ $form->{deliverydate} },
  225. $form->{"deliverydate_$i"});
  226. push(@{ $form->{projectnumber} },
  227. $form->{"projectnumber_$i"});
  228. push(@{ $form->{sellprice} }, $form->{"sellprice_$i"});
  229. push(@{ $form->{listprice} }, $form->{"listprice_$i"});
  230. push(@{ $form->{weight} },
  231. $form->format_amount(
  232. $myconfig,
  233. $form->{"weight_$i"}
  234. * $form->{"qty_$i"}));
  235. my $sellprice =
  236. $form->parse_amount(
  237. $myconfig, $form->{"sellprice_$i"});
  238. my ($dec) = ($sellprice =~ /\.(\d+)/);
  239. $dec = length $dec;
  240. my $decimalplaces = ($dec > 2) ? $dec : 2;
  241. my $discount =
  242. $form->round_amount(
  243. $sellprice
  244. * $form->parse_amount(
  245. $myconfig,
  246. $form->{"discount_$i"})
  247. /100,
  248. $decimalplaces);
  249. # keep a netprice as well, (sellprice - discount)
  250. $form->{"netprice_$i"} = $sellprice - $discount;
  251. my $linetotal = $form->round_amount(
  252. $form->{"qty_$i"} * $form->{"netprice_$i"}, 2);
  253. if ($form->{"inventory_accno_id_$i"}
  254. || $form->{"assembly_$i"}) {
  255. push(@{ $form->{part} }, $form->{"sku_$i"});
  256. push(@{ $form->{service} }, NULL);
  257. $form->{totalparts} += $linetotal;
  258. } else {
  259. push(@{ $form->{service} }, $form->{"sku_$i"});
  260. push(@{ $form->{part} }, NULL);
  261. $form->{totalservices} += $linetotal;
  262. }
  263. push(@{ $form->{netprice} },
  264. ($form->{"netprice_$i"})
  265. ? $form->format_amount(
  266. $myconfig, $form->{"netprice_$i"},
  267. $decimalplaces)
  268. : " ");
  269. $discount =
  270. ($discount)
  271. ? $form->format_amount(
  272. $myconfig, $discount * -1,
  273. $decimalplaces)
  274. : " ";
  275. $linetotal = ($linetotal) ? $linetotal : " ";
  276. push(@{ $form->{discount} }, $discount);
  277. push(@{ $form->{discountrate} },
  278. $form->format_amount(
  279. $myconfig, $form->{"discount_$i"}));
  280. $form->{total} += $linetotal;
  281. # this is for the subtotals for grouping
  282. $subtotal += $linetotal;
  283. $form->{"linetotal_$i"} =
  284. $form->format_amount($myconfig, $linetotal, 2);
  285. push(@{ $form->{linetotal} }, $form->{"linetotal_$i"});
  286. @taxaccounts = Tax::init_taxes(
  287. $form, $form->{"taxaccounts_$i"},
  288. $form->{"taxaccounts"});
  289. my $ml = 1;
  290. my @taxrates = ();
  291. $tax = 0;
  292. if ($form->{taxincluded}) {
  293. $taxamount = Tax::calculate_taxes(
  294. \@taxaccounts, $form, $linetotal, 1);
  295. $taxbase = ($linetotal - $taxamount);
  296. $tax += Tax::extract_taxes(
  297. \@taxaccounts, $form, $linetotal);
  298. } else {
  299. $taxamount = Tax::calculate_taxes(
  300. \@taxaccounts, $form, $linetotal, 0);
  301. $tax += Tax::apply_taxes(
  302. \@taxaccounts, $form, $linetotal);
  303. }
  304. foreach $item (@taxaccounts) {
  305. push @taxrates, 100 * $item->rate;
  306. $taxaccounts{$item->account} += $item->value;
  307. if ($form->{taxincluded}) {
  308. $taxbase{$item->account} += $taxbase;
  309. } else {
  310. $taxbase{$item->account} += $linetotal;
  311. }
  312. }
  313. push(@{ $form->{lineitems} },
  314. { amount => $linetotal,
  315. tax => $form->round_amount($tax, 2) });
  316. push(@{ $form->{taxrates} },
  317. join' ', sort { $a <=> $b } @taxrates);
  318. if ($form->{"assembly_$i"}) {
  319. $form->{stagger} = -1;
  320. &assembly_details(
  321. $myconfig, $form, $dbh,
  322. $form->{"id_$i"},
  323. $oid{$myconfig->{dbdriver}},
  324. $form->{"qty_$i"});
  325. }
  326. }
  327. # add subtotal
  328. if ($form->{groupprojectnumber} || $form->{grouppartsgroup}) {
  329. if ($subtotal) {
  330. if ($j < $k) {
  331. # look at next item
  332. if ($sortlist[$j]->[1] ne $sameitem) {
  333. if ($form->{"inventory_accno_id_$j"} || $form->{"assembly_$i"}) {
  334. push(@{ $form->{part} },
  335. "");
  336. push(@{$form->{service}},
  337. NULL);
  338. } else {
  339. push(@{$form->{service}},
  340. "");
  341. push(@{ $form->{part} },
  342. NULL);
  343. }
  344. for (
  345. qw(taxrates
  346. runningnumber number sku
  347. serialnumber bin qty
  348. ship unit deliverydate
  349. projectnumber sellprice
  350. listprice netprice
  351. discount discountrate
  352. weight itemnotes)
  353. ) {
  354. push(@{ $form->{$_} },
  355. "")
  356. }
  357. push(@{ $form->{description} },
  358. $form->{groupsubtotaldescription});
  359. push(@{ $form->{lineitems} },
  360. { amount => 0,
  361. tax => 0 });
  362. if ($form->{groupsubtotaldescription} ne "") {
  363. push(@{ $form->{linetotal} },
  364. $form->format_amount(
  365. $myconfig,
  366. $subtotal,
  367. 2));
  368. } else {
  369. push(@{$form->{linetotal}},
  370. "");
  371. }
  372. $subtotal = 0;
  373. }
  374. } else {
  375. # got last item
  376. if ($form->{groupsubtotaldescription}
  377. ne "") {
  378. if ($form->{"inventory_accno_id_$j"} || $form->{"assembly_$i"}) {
  379. push(@{ $form->{part} },
  380. "");
  381. push(@{$form->{service}},
  382. NULL);
  383. } else {
  384. push(@{$form->{service}},
  385. "");
  386. push(@{ $form->{part} },
  387. NULL);
  388. }
  389. for (
  390. qw(taxrates
  391. runningnumber number sku
  392. serialnumber bin qty
  393. ship unit deliverydate
  394. projectnumber sellprice
  395. listprice netprice
  396. discount discountrate
  397. weight itemnotes)
  398. ) {
  399. push(@{ $form->{$_} },
  400. "");
  401. }
  402. push(@{ $form->{description} },
  403. $form->{groupsubtotaldescription});
  404. push(@{ $form->{linetotal} },
  405. $form->format_amount(
  406. $myconfig,
  407. $subtotal,
  408. 2));
  409. push(@{ $form->{lineitems} },
  410. { amount => 0,
  411. tax => 0 });
  412. }
  413. }
  414. }
  415. }
  416. }
  417. $tax = 0;
  418. foreach my $item (sort keys %taxaccounts) {
  419. if ($form->round_amount($taxaccounts{$item}, 2)) {
  420. $tax += $taxamount =
  421. $form->round_amount($taxaccounts{$item}, 2);
  422. push(@{ $form->{taxbaseinclusive} },
  423. $form->{"${item}_taxbaseinclusive"}
  424. = $form->format_amount(
  425. $myconfig,
  426. $taxbase{$item} + $tax, 2));
  427. push(@{ $form->{taxbase} },
  428. $form->{"${item}_taxbase"}
  429. = $form->format_amount(
  430. $myconfig, $taxbase{$item}, 2));
  431. push(@{ $form->{tax} },
  432. $form->{"${item}_tax"}
  433. = $form->format_amount(
  434. $myconfig, $taxamount, 2));
  435. push(@{ $form->{taxdescription} },
  436. $form->{"${item}_description"});
  437. $form->{"${item}_taxrate"}
  438. = $form->format_amount(
  439. $myconfig,
  440. $form->{"${item}_rate"} * 100);
  441. push(@{ $form->{taxrate} }, $form->{"${item}_taxrate"});
  442. push(@{ $form->{taxnumber} },
  443. $form->{"${item}_taxnumber"});
  444. }
  445. }
  446. # adjust taxes for lineitems
  447. my $total = 0;
  448. for (@{ $form->{lineitems} }) {
  449. $total += $_->{tax};
  450. }
  451. if ($form->round_amount($total,2) != $form->round_amount($tax,2)) {
  452. # get largest amount
  453. for (reverse sort { $a->{tax} <=> $b->{tax} }
  454. @{ $form->{lineitems} }) {
  455. $_->{tax} -= $total - $tax;
  456. last;
  457. }
  458. }
  459. $i = 1;
  460. for (@{ $form->{lineitems} }) {
  461. push(@{ $form->{linetax} },
  462. $form->format_amount($myconfig, $_->{tax}, 2, ""));
  463. }
  464. for $i (1 .. $form->{paidaccounts}) {
  465. if ($form->{"paid_$i"}) {
  466. push(@{ $form->{payment} }, $form->{"paid_$i"});
  467. my ($accno, $description)
  468. = split /--/, $form->{"AR_paid_$i"};
  469. push(@{ $form->{paymentaccount} }, $description);
  470. push(@{ $form->{paymentdate} }, $form->{"datepaid_$i"});
  471. push(@{ $form->{paymentsource} }, $form->{"source_$i"});
  472. push(@{ $form->{paymentmemo} }, $form->{"memo_$i"});
  473. $form->{paid}
  474. += $form->parse_amount(
  475. $myconfig, $form->{"paid_$i"});
  476. }
  477. }
  478. for (qw(totalparts totalservices)) {
  479. $form->{$_} = $form->format_amount($myconfig, $form->{$_}, 2);
  480. }
  481. for (qw(totalqty totalship totalweight)) {
  482. $form->{$_} = $form->format_amount($myconfig, $form->{$_});
  483. }
  484. $form->{subtotal} = $form->format_amount($myconfig, $form->{total}, 2);
  485. $form->{invtotal} =
  486. ($form->{taxincluded}) ? $form->{total} : $form->{total} + $tax;
  487. my $c;
  488. if ($form->{language_code} ne "") {
  489. $c = new CP $form->{language_code};
  490. } else {
  491. $c = new CP $myconfig->{countrycode};
  492. }
  493. $c->init;
  494. my $whole;
  495. ($whole, $form->{decimal}) = split /\./, $form->{invtotal};
  496. $form->{decimal} .= "00";
  497. $form->{decimal} = substr($form->{decimal}, 0, 2);
  498. $form->{text_decimal} = $c->num2text($form->{decimal} * 1);
  499. $form->{text_amount} = $c->num2text($whole);
  500. $form->{integer_amount} = $form->format_amount($myconfig, $whole);
  501. $form->format_string(qw(text_amount text_decimal));
  502. $form->{total}
  503. = $form->format_amount(
  504. $myconfig, $form->{invtotal} - $form->{paid}, 2);
  505. $form->{invtotal}
  506. = $form->format_amount($myconfig, $form->{invtotal}, 2);
  507. $form->{paid} = $form->format_amount($myconfig, $form->{paid}, 2);
  508. $dbh->commit;
  509. }
  510. sub assembly_details {
  511. my ($myconfig, $form, $dbh2, $id, $oid, $qty) = @_;
  512. $dbh = $form->{dbh};
  513. my $sm = "";
  514. my $spacer;
  515. $form->{stagger}++;
  516. if ($form->{format} eq 'html') {
  517. $spacer = "&nbsp;" x (3 * ($form->{stagger} - 1))
  518. if $form->{stagger} > 1;
  519. }
  520. if ($form->{format} =~ /(postscript|pdf)/) {
  521. if ($form->{stagger} > 1) {
  522. $spacer = ($form->{stagger} - 1) * 3;
  523. $spacer = '\rule{'.$spacer.'mm}{0mm}';
  524. }
  525. }
  526. # get parts and push them onto the stack
  527. my $sortorder = "";
  528. if ($form->{grouppartsgroup}) {
  529. $sortorder = qq|ORDER BY pg.partsgroup|;
  530. }
  531. my $query = qq|
  532. SELECT p.partnumber, p.description, p.unit, a.qty,
  533. pg.partsgroup, p.partnumber AS sku
  534. FROM assembly a
  535. JOIN parts p ON (a.parts_id = p.id)
  536. LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
  537. WHERE a.bom = '1'
  538. AND a.id = ?
  539. $sortorder|;
  540. my $sth = $dbh->prepare($query);
  541. $sth->execute($id) || $form->dberror($query);
  542. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  543. for (qw(partnumber description partsgroup)) {
  544. $form->{"a_$_"} = $ref->{$_};
  545. $form->format_string("a_$_");
  546. }
  547. if ($form->{grouppartsgroup} && $ref->{partsgroup} ne $sm) {
  548. for (
  549. qw(taxrates runningnumber number sku
  550. serialnumber unit qty ship bin deliverydate
  551. projectnumber sellprice listprice netprice
  552. discount discountrate linetotal weight
  553. itemnotes)
  554. ) {
  555. push(@{ $form->{$_} }, "");
  556. }
  557. $sm =
  558. ($form->{"a_partsgroup"})
  559. ? $form->{"a_partsgroup"}
  560. : "--";
  561. push(@{ $form->{description} }, "$spacer$sm");
  562. push(@{ $form->{lineitems} },
  563. { amount => 0, tax => 0 });
  564. }
  565. if ($form->{stagger}) {
  566. push(@{ $form->{description} },
  567. $form->format_amount(
  568. $myconfig,
  569. $ref->{qty} * $form->{"qty_$i"})
  570. .qq| -- $form->{"a_partnumber"}|
  571. .qq|, $form->{"a_description"}|);
  572. for (
  573. qw(taxrates runningnumber number sku
  574. serialnumber unit qty ship bin deliverydate
  575. projectnumber sellprice listprice netprice
  576. discount discountrate linetotal weight
  577. itemnotes)
  578. ) {
  579. push(@{ $form->{$_} }, "");
  580. }
  581. } else {
  582. push(@{ $form->{description} },
  583. qq|$form->{"a_description"}|);
  584. push(@{ $form->{number} }, $form->{"a_partnumber"});
  585. push(@{ $form->{sku} }, $form->{"a_partnumber"});
  586. for (
  587. qw(taxrates runningnumber ship serialnumber
  588. reqdate projectnumber sellprice listprice
  589. netprice discount discountrate linetotal weight
  590. itemnotes)
  591. ) {
  592. push(@{ $form->{$_} }, "");
  593. }
  594. }
  595. push(@{ $form->{lineitems} }, { amount => 0, tax => 0 });
  596. push(@{ $form->{qty} },
  597. $form->format_amount($myconfig, $ref->{qty} * $qty));
  598. for (qw(unit bin)) {
  599. $form->{"a_$_"} = $ref->{$_};
  600. $form->format_string("a_$_");
  601. push(@{ $form->{$_} }, $form->{"a_$_"});
  602. }
  603. }
  604. $sth->finish;
  605. $form->{stagger}--;
  606. }
  607. sub project_description {
  608. my ($self, $dbh2, $id) = @_;
  609. $dbh = $form->{dbh};
  610. my $query = qq|
  611. SELECT description
  612. FROM project
  613. WHERE id = ?|;
  614. $sth = $dbh->prepare($query);
  615. $sth->execute($id);
  616. ($_) = $sth->fetchrow_array;
  617. $_;
  618. }
  619. sub customer_details {
  620. my ($self, $myconfig, $form) = @_;
  621. my $dbh = $form->{dbh};
  622. # get rest for the customer
  623. my $query = qq|
  624. SELECT customernumber, name, address1, address2, city,
  625. state, zipcode, country,
  626. contact, phone as customerphone, fax as customerfax,
  627. taxnumber AS customertaxnumber, sic_code AS sic, iban,
  628. bic, startdate, enddate
  629. FROM customer
  630. WHERE id = ?|;
  631. my $sth = $dbh->prepare($query);
  632. $sth->execute($form->{customer_id}) || $form->dberror($query);
  633. $ref = $sth->fetchrow_hashref(NAME_lc);
  634. for (keys %$ref) { $form->{$_} = $ref->{$_} }
  635. $sth->finish;
  636. $dbh->commit;
  637. }
  638. sub post_invoice {
  639. my ($self, $myconfig, $form) = @_;
  640. my $dbh = $form->{dbh};
  641. my $query;
  642. my $sth;
  643. my $null;
  644. my $project_id;
  645. my $exchangerate = 0;
  646. my $keepcleared = 0;
  647. %$form->{acc_trans} = ();
  648. ($null, $form->{employee_id}) = split /--/, $form->{employee};
  649. unless ($form->{employee_id}) {
  650. ($form->{employee}, $form->{employee_id})
  651. = $form->get_employee($dbh);
  652. }
  653. ($null, $form->{department_id}) = split(/--/, $form->{department});
  654. $form->{department_id} *= 1;
  655. $query = qq|
  656. SELECT (SELECT value FROM defaults
  657. WHERE setting_key = 'fxgain_accno_id')
  658. AS fxgain_accno_id,
  659. (SELECT value FROM defaults
  660. WHERE setting_key = 'fxloss_accno_id')
  661. AS fxloss_accno_id|;
  662. my ($fxgain_accno_id, $fxloss_accno_id) = $dbh->selectrow_array($query);
  663. $query = qq|
  664. SELECT p.assembly, p.inventory_accno_id,
  665. p.income_accno_id, p.expense_accno_id, p.project_id
  666. FROM parts p
  667. WHERE p.id = ?|;
  668. my $pth = $dbh->prepare($query) || $form->dberror($query);
  669. if ($form->{id}) {
  670. $keepcleared = 1;
  671. $query = qq|SELECT id FROM ar WHERE id = ?|;
  672. $sth = $dbh->prepare($query);
  673. $sth->execute($form->{id});
  674. if ($sth->fetchrow_array) {
  675. &reverse_invoice($dbh, $form);
  676. } else {
  677. $query = qq|INSERT INTO ar (id) VALUES (?)|;
  678. $sth = $dbh->prepare($query);
  679. $sth->execute($form->{id}) || $form->dberror($query);
  680. }
  681. }
  682. my $uid = localtime;
  683. $uid .= "$$";
  684. if (! $form->{id}) {
  685. $query = qq|
  686. INSERT INTO ar (invnumber, employee_id)
  687. VALUES ('$uid', ?)|;
  688. $sth = $dbh->prepare($query);
  689. $sth->execute($form->{employee_id}) || $form->dberror($query);
  690. $query = qq|SELECT id FROM ar WHERE invnumber = '$uid'|;
  691. $sth = $dbh->prepare($query);
  692. $sth->execute || $form->dberror($query);
  693. ($form->{id}) = $sth->fetchrow_array;
  694. $sth->finish;
  695. @queries = $form->run_custom_queries('ar', 'INSERT');
  696. }
  697. if ($form->{currency} eq $form->{defaultcurrency}) {
  698. $form->{exchangerate} = 1;
  699. } else {
  700. $exchangerate =
  701. $form->check_exchangerate(
  702. $myconfig, $form->{currency},
  703. $form->{transdate}, 'buy');
  704. }
  705. $form->{exchangerate} =
  706. ($exchangerate)
  707. ? $exchangerate
  708. : $form->parse_amount($myconfig, $form->{exchangerate});
  709. my $i;
  710. my $item;
  711. my $allocated = 0;
  712. my $taxrate;
  713. my $tax;
  714. my $fxtax;
  715. my @taxaccounts;
  716. my $amount;
  717. my $grossamount;
  718. my $invamount = 0;
  719. my $invnetamount = 0;
  720. my $diff = 0;
  721. my $ml;
  722. my $invoice_id;
  723. my $ndx;
  724. foreach $i (1 .. $form->{rowcount}) {
  725. $form->{"qty_$i"} =
  726. $form->parse_amount($myconfig, $form->{"qty_$i"});
  727. if ($form->{"qty_$i"}) {
  728. $pth->execute($form->{"id_$i"});
  729. $ref = $pth->fetchrow_hashref(NAME_lc);
  730. for (keys %$ref) { $form->{"${_}_$i"} = $ref->{$_} }
  731. $pth->finish;
  732. # project
  733. if ($form->{"projectnumber_$i"}) {
  734. ($null, $project_id)
  735. = split /--/,
  736. $form->{"projectnumber_$i"};
  737. }
  738. $project_id = $form->{"project_id_$i"}
  739. if $form->{"project_id_$i"};
  740. # keep entered selling price
  741. my $fxsellprice =
  742. $form->parse_amount(
  743. $myconfig, $form->{"sellprice_$i"});
  744. my ($dec) = ($fxsellprice =~ /\.(\d+)/);
  745. $dec = length $dec;
  746. my $decimalplaces = ($dec > 2) ? $dec : 2;
  747. # undo discount formatting
  748. $form->{"discount_$i"} =
  749. $form->parse_amount(
  750. $myconfig, $form->{"discount_$i"})/100;
  751. # deduct discount
  752. $form->{"sellprice_$i"} = $fxsellprice
  753. - $form->round_amount(
  754. $fxsellprice * $form->{"discount_$i"},
  755. $decimalplaces);
  756. # linetotal
  757. my $fxlinetotal = $form->round_amount(
  758. $form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
  759. $amount = $fxlinetotal * $form->{exchangerate};
  760. my $linetotal = $form->round_amount($amount, 2);
  761. $fxdiff += $amount - $linetotal;
  762. @taxaccounts = Tax::init_taxes(
  763. $form, $form->{"taxaccounts_$i"},
  764. $form->{"taxaccounts"});
  765. $ml = 1;
  766. $tax = Math::BigFloat->bzero();
  767. $fxtax = Math::BigFloat->bzero();
  768. if ($form->{taxincluded}) {
  769. $tax += $amount =
  770. Tax::calculate_taxes(
  771. \@taxaccounts, $form,
  772. $linetotal, 1);
  773. $form->{"sellprice_$i"} -= $amount
  774. / $form->{"qty_$i"};
  775. $fxtax += Tax::calculate_taxes(
  776. \@taxaccounts, $form, $linetotal, 1);
  777. } else {
  778. $tax += $amount = Tax::calculate_taxes(
  779. \@taxaccounts, $form, $linetotal, 0);
  780. $fxtax += Tax::calculate_taxes(
  781. \@taxaccounts, $form, $linetotal, 0);
  782. }
  783. for (@taxaccounts) {
  784. $form->{acc_trans}{$form->{id}}{$_->account}{amount} += $_->value;
  785. }
  786. $grossamount = $form->round_amount($linetotal, 2);
  787. if ($form->{taxincluded}) {
  788. $amount = $form->round_amount($tax, 2);
  789. $linetotal -= $form->round_amount(
  790. $tax - $diff, 2);
  791. $diff = ($amount - $tax);
  792. }
  793. # add linetotal to income
  794. $amount = $form->round_amount($linetotal, 2);
  795. push @{ $form->{acc_trans}{lineitems} }, {
  796. chart_id => $form->{"income_accno_id_$i"},
  797. amount => $amount,
  798. fxgrossamount => $fxlinetotal + $fxtax,
  799. grossamount => $grossamount,
  800. project_id => $project_id };
  801. $ndx = $#{@{$form->{acc_trans}{lineitems}}};
  802. $form->{"sellprice_$i"} =
  803. $form->round_amount(
  804. $form->{"sellprice_$i"}
  805. * $form->{exchangerate},
  806. $decimalplaces);
  807. if ($form->{"inventory_accno_id_$i"}
  808. || $form->{"assembly_$i"}) {
  809. if ($form->{"assembly_$i"}) {
  810. # If the assembly consists of all
  811. # services, we don't keep inventory,
  812. # so we should not update it
  813. $query = qq|
  814. SELECT sum(
  815. p.inventory_accno_id),
  816. p.assembly
  817. FROM parts p
  818. JOIN assembly a
  819. ON (a.parts_id = p.id)
  820. WHERE a.id = $form->{"id_$i"}
  821. GROUP BY p.assembly|;
  822. $sth = $dbh->prepare($query);
  823. $sth->execute($form->{"id_$i"})
  824. || $form->dberror($query);
  825. my ($inv, $assembly)
  826. = $sth->fetchrow_array;
  827. $sth->finish;
  828. if ($inv || $assembly) {
  829. $form->update_balance($dbh,
  830. "parts",
  831. "onhand",
  832. qq|id = |.
  833. qq|$form->{"id_$i"}|,
  834. $form->{"qty_$i"} * -1)
  835. unless $form->{shipped};
  836. }
  837. &process_assembly(
  838. $dbh, $form, $form->{"id_$i"},
  839. $form->{"qty_$i"}, $project_id);
  840. } else {
  841. $form->update_balance(
  842. $dbh, "parts", "onhand",
  843. qq|id = $form->{"id_$i"}|,
  844. $form->{"qty_$i"} * -1)
  845. unless $form->{shipped};
  846. $allocated = &cogs(
  847. $dbh, $form, $form->{"id_$i"},
  848. $form->{"qty_$i"}, $project_id);
  849. }
  850. }
  851. # save detail record in invoice table
  852. $query = qq|
  853. INSERT INTO invoice (description)
  854. VALUES ('$uid')|;
  855. $dbh->do($query) || $form->dberror($query);
  856. $query = qq|
  857. SELECT id FROM invoice
  858. WHERE description = '$uid'|;
  859. ($invoice_id) = $dbh->selectrow_array($query);
  860. unless ($form->{"deliverydate_$i"}){
  861. undef $form->{"deliverydate_$i"};
  862. }
  863. $query = qq|
  864. UPDATE invoice
  865. SET trans_id = ?,
  866. parts_id = ?,
  867. description = ?,
  868. qty = ?,
  869. sellprice = ?,
  870. fxsellprice = ?,
  871. discount = ?,
  872. allocated = ?,
  873. unit = ?,
  874. deliverydate = ?,
  875. project_id = ?,
  876. serialnumber = ?,
  877. notes = ?
  878. WHERE id = ?|;
  879. $sth = $dbh->prepare($query);
  880. $sth->execute(
  881. $form->{id}, $form->{"id_$i"},
  882. $form->{"description_$i"}, $form->{"qty_$i"},
  883. $form->{"sellprice_$i"}, $fxsellprice,
  884. $form->{"discount_$i"}, $allocated,
  885. $form->{"unit_$i"}, $form->{"deliverydate_$i"},
  886. $project_id, $form->{"serialnumber_$i"},
  887. $form->{"notes_$i"}, $invoice_id)
  888. || $form->dberror($query);
  889. # add invoice_id
  890. $form->{acc_trans}{lineitems}[$ndx]->{invoice_id}
  891. = $invoice_id;
  892. }
  893. }
  894. $form->{paid} = 0;
  895. for $i (1 .. $form->{paidaccounts}) {
  896. $form->{"paid_$i"} =
  897. $form->parse_amount($myconfig, $form->{"paid_$i"});
  898. $form->{paid} += $form->{"paid_$i"};
  899. $form->{datepaid} = $form->{"datepaid_$i"}
  900. if ($form->{"paid_$i"});
  901. }
  902. # add lineitems + tax
  903. $amount = 0;
  904. $grossamount = 0;
  905. $fxgrossamount = 0;
  906. for (@{ $form->{acc_trans}{lineitems} }) {
  907. $amount += $_->{amount};
  908. $grossamount += $_->{grossamount};
  909. $fxgrossamount += $_->{fxgrossamount};
  910. }
  911. $invnetamount = $amount;
  912. $amount = 0;
  913. for (split / /, $form->{taxaccounts}) {
  914. $amount +=
  915. $form->{acc_trans}{$form->{id}}{$_}{amount} =
  916. $form->round_amount(
  917. $form->{acc_trans}{$form->{id}}{$_}{amount},
  918. 2);
  919. }
  920. $invamount = $invnetamount + $amount;
  921. $diff = 0;
  922. if ($form->{taxincluded}) {
  923. $diff = $form->round_amount($grossamount - $invamount, 2);
  924. $invamount += $diff;
  925. }
  926. $fxdiff = $form->round_amount($fxdiff,2);
  927. $invnetamount += $fxdiff;
  928. $invamount += $fxdiff;
  929. if ($form->round_amount($form->{paid} - $fxgrossamount,2) == 0) {
  930. $form->{paid} = $invamount;
  931. } else {
  932. $form->{paid} = $form->round_amount(
  933. $form->{paid} * $form->{exchangerate}, 2);
  934. }
  935. foreach $ref (sort { $b->{amount} <=> $a->{amount} }
  936. @ { $form->{acc_trans}{lineitems} }) {
  937. $amount = $ref->{amount} + $diff + $fxdiff;
  938. $query = qq|
  939. INSERT INTO acc_trans
  940. (trans_id, chart_id, amount,
  941. transdate, project_id, invoice_id)
  942. VALUES (?, ?, ?, ?, ?, ?)|;
  943. $sth = $dbh->prepare($query);
  944. $sth->execute(
  945. $form->{id}, $ref->{chart_id}, $amount,
  946. $form->{transdate}, $ref->{project_id},
  947. $ref->{invoice_id})
  948. || $form->dberror($query);
  949. $diff = 0;
  950. $fxdiff = 0;
  951. }
  952. $form->{receivables} = $invamount * -1;
  953. delete $form->{acc_trans}{lineitems};
  954. # update exchangerate
  955. if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
  956. $form->update_exchangerate(
  957. $dbh, $form->{currency}, $form->{transdate},
  958. $form->{exchangerate}, 0);
  959. }
  960. # record receivable
  961. if ($form->{receivables}) {
  962. ($accno) = split /--/, $form->{AR};
  963. $query = qq|
  964. INSERT INTO acc_trans
  965. (trans_id, chart_id, amount, transdate)
  966. VALUES (?, (SELECT id FROM chart WHERE accno = ?),
  967. ?, ?)|;
  968. $sth = $dbh->prepare($query);
  969. $sth->execute(
  970. $form->{id}, $accno, $form->{receivables},
  971. $form->{transdate})
  972. || $form->dberror($query);
  973. }
  974. foreach my $trans_id (keys %{$form->{acc_trans}}) {
  975. foreach my $accno (keys %{$form->{acc_trans}{$trans_id}}) {
  976. $amount = $form->round_amount(
  977. $form->{acc_trans}{$trans_id}{$accno}{amount},
  978. 2);
  979. if ($amount) {
  980. $query = qq|
  981. INSERT INTO acc_trans
  982. (trans_id, chart_id, amount,
  983. transdate)
  984. VALUES (?, (SELECT id FROM chart
  985. WHERE accno = ?),
  986. ?, ?)|;
  987. $sth = $dbh->prepare($query);
  988. $sth->execute(
  989. $trans_id, $accno, $amount,
  990. $form->{transdate})
  991. || $form->dberror($query);
  992. }
  993. }
  994. }
  995. # if there is no amount but a payment record receivable
  996. if ($invamount == 0) {
  997. $form->{receivables} = 1;
  998. }
  999. my $cleared = 0;
  1000. # record payments and offsetting AR
  1001. for $i (1 .. $form->{paidaccounts}) {
  1002. if ($form->{"paid_$i"}) {
  1003. my ($accno) = split /--/, $form->{"AR_paid_$i"};
  1004. $form->{"datepaid_$i"} = $form->{transdate}
  1005. unless ($form->{"datepaid_$i"});
  1006. $form->{datepaid} = $form->{"datepaid_$i"};
  1007. $exchangerate = 0;
  1008. if ($form->{currency} eq $form->{defaultcurrency}) {
  1009. $form->{"exchangerate_$i"} = 1;
  1010. } else {
  1011. $exchangerate =
  1012. $form->check_exchangerate(
  1013. $myconfig, $form->{currency},
  1014. $form->{"datepaid_$i"}, 'buy');
  1015. $form->{"exchangerate_$i"} =
  1016. ($exchangerate)
  1017. ? $exchangerate
  1018. : $form->parse_amount(
  1019. $myconfig,
  1020. $form->{"exchangerate_$i"});
  1021. }
  1022. # record AR
  1023. $amount = $form->round_amount(
  1024. $form->{"paid_$i"} * $form->{exchangerate}, 2);
  1025. if ($form->{receivables}) {
  1026. $query = qq|
  1027. INSERT INTO acc_trans
  1028. (trans_id, chart_id, amount,
  1029. transdate)
  1030. VALUES (?, (SELECT id FROM chart
  1031. WHERE accno = ?),
  1032. ?, ?)|;
  1033. $sth = $dbh->prepare($query);
  1034. $sth->execute(
  1035. $form->{id}, $form->{AR}, $amount,
  1036. $form->{"datepaid_$i"})
  1037. || $form->dberror($query);
  1038. }
  1039. # record payment
  1040. $amount = $form->{"paid_$i"} * -1;
  1041. if ($keepcleared) {
  1042. $cleared = ($form->{"cleared_$i"}) ? 1 : 0;
  1043. }
  1044. $query = qq|
  1045. INSERT INTO acc_trans
  1046. (trans_id, chart_id, amount,
  1047. transdate, source, memo, cleared)
  1048. VALUES (?, (SELECT id FROM chart
  1049. WHERE accno = ?),
  1050. ?, ?, ?, ?, ?)|;
  1051. $sth = $dbh->prepare($query);
  1052. $sth->execute(
  1053. $form->{id}, $accno, $amount,
  1054. $form->{"datepaid_$i"}, $form->{"source_$i"},
  1055. $form->{"memo_$i"}, $cleared)
  1056. || $form->dberror($query);
  1057. # exchangerate difference
  1058. $amount = $form->round_amount(
  1059. ($form->round_amount(
  1060. $form->{"paid_$i"}
  1061. * $form->{"exchangerate_$i"}
  1062. - $form->{"paid_$i"}, 2)) * -1,
  1063. 2);
  1064. if ($amount) {
  1065. $query = qq|
  1066. INSERT INTO acc_trans
  1067. (trans_id, chart_id, amount,
  1068. transdate, source,
  1069. fx_transaction, cleared)
  1070. VALUES (?, (SELECT id FROM chart
  1071. WHERE accno = >),
  1072. ?, ?, ?, '1', ?)|;
  1073. $sth = $dbh->prepare($query);
  1074. $sth->execute(
  1075. $form->{id}, $accno, $amount,
  1076. $form->{"datepaid_$i"},
  1077. $form->{"source_$i"}, $cleared )
  1078. || $form->dberror($query);
  1079. }
  1080. # gain/loss
  1081. $amount = $form->round_amount(
  1082. ($form->round_amount(
  1083. $form->{"paid_$i"}
  1084. * $form->{exchangerate},2)
  1085. - $form->round_amount(
  1086. $form->{"paid_$i"}
  1087. * $form->{"exchangerate_$i"},2)
  1088. ) * -1,
  1089. 2);
  1090. if ($amount) {
  1091. my $accno_id =
  1092. ($amount > 0)
  1093. ? $fxgain_accno_id
  1094. : $fxloss_accno_id;
  1095. $query = qq|
  1096. INSERT INTO acc_trans (
  1097. trans_id, chart_id, amount,
  1098. transdate, fx_transaction,
  1099. cleared)
  1100. VALUES (?, ?, ?, ?, '1', ?)|;
  1101. $sth = $dbh->prepare($query);
  1102. $sth->execute(
  1103. $form->{id}, $accno_id, $amount,
  1104. $form->{"datepaid_$i"}, $cleared)
  1105. || $form->dberror($query);
  1106. }
  1107. # update exchange rate
  1108. if (($form->{currency} ne $form->{defaultcurrency})
  1109. && !$exchangerate) {
  1110. $form->update_exchangerate(
  1111. $dbh, $form->{currency},
  1112. $form->{"datepaid_$i"},
  1113. $form->{"exchangerate_$i"}, 0);
  1114. }
  1115. }
  1116. }
  1117. # set values which could be empty to 0
  1118. $form->{terms} *= 1;
  1119. $form->{taxincluded} *= 1;
  1120. $form->{invnumber} =
  1121. $form->update_defaults($myconfig, "sinumber", $dbh)
  1122. unless $form->{invnumber};
  1123. # save AR record
  1124. $query = qq|
  1125. UPDATE ar set
  1126. invnumber = ?,
  1127. ordnumber = ?,
  1128. quonumber = ?,
  1129. transdate = ?,
  1130. customer_id = ?,
  1131. amount = ?,
  1132. netamount = ?,
  1133. paid = ?,
  1134. datepaid = ?,
  1135. duedate = ?,
  1136. invoice = '1',
  1137. shippingpoint = ?,
  1138. shipvia = ?,
  1139. terms = ?,
  1140. notes = ?,
  1141. intnotes = ?,
  1142. taxincluded = ?,
  1143. curr = ?,
  1144. department_id = ?,
  1145. employee_id = ?,
  1146. till = ?,
  1147. language_code = ?,
  1148. ponumber = ?
  1149. WHERE id = ?
  1150. |;
  1151. $sth = $dbh->prepare($query);
  1152. $sth->execute(
  1153. $form->{invnumber}, $form->{ordnumber}, $form->{quonumber},
  1154. $form->{transdate}, $form->{customer_id}, $invamount,
  1155. $invnetamount, $form->{paid}, $form->{datepaid},
  1156. $form->{duedate}, $form->{shippingpoint}, $form->{shipvia},
  1157. $form->{terms}, $form->{notes}, $form->{intnotes},
  1158. $form->{taxincluded}, $form->{currency}, $form->{department_id},
  1159. $form->{employee_id}, $form->{till}, $form->{language_code},
  1160. $form->{ponumber}, $form->{id})
  1161. || $form->dberror($query);
  1162. # add shipto
  1163. $form->{name} = $form->{customer};
  1164. $form->{name} =~ s/--$form->{customer_id}//;
  1165. $form->add_shipto($dbh, $form->{id});
  1166. # save printed, emailed and queued
  1167. $form->save_status($dbh);
  1168. my %audittrail = (
  1169. tablename => 'ar',
  1170. reference => $form->{invnumber},
  1171. formname => $form->{type},
  1172. action => 'posted',
  1173. id => $form->{id} );
  1174. $form->audittrail($dbh, "", \%audittrail);
  1175. $form->save_recurring($dbh, $myconfig);
  1176. my $rc = $dbh->commit;
  1177. $rc;
  1178. }
  1179. sub process_assembly {
  1180. my ($dbh2, $form, $id, $totalqty, $project_id) = @_;
  1181. my $dbh = $form->{dbh};
  1182. my $query = qq|
  1183. SELECT a.parts_id, a.qty, p.assembly,
  1184. p.partnumber, p.description, p.unit,
  1185. p.inventory_accno_id, p.income_accno_id,
  1186. p.expense_accno_id
  1187. FROM assembly a
  1188. JOIN parts p ON (a.parts_id = p.id)
  1189. WHERE a.id = ?|;
  1190. my $sth = $dbh->prepare($query);
  1191. $sth->execute($id) || $form->dberror($query);
  1192. my $allocated;
  1193. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1194. $allocated = 0;
  1195. $ref->{inventory_accno_id} *= 1;
  1196. $ref->{expense_accno_id} *= 1;
  1197. # multiply by number of assemblies
  1198. $ref->{qty} *= $totalqty;
  1199. if ($ref->{assembly}) {
  1200. &process_assembly(
  1201. $dbh, $form, $ref->{parts_id}, $ref->{qty},
  1202. $project_id);
  1203. next;
  1204. } else {
  1205. if ($ref->{inventory_accno_id}) {
  1206. $allocated = &cogs(
  1207. $dbh, $form, $ref->{parts_id},
  1208. $ref->{qty}, $project_id);
  1209. }
  1210. }
  1211. $query = qq|
  1212. INSERT INTO invoice
  1213. (trans_id, description, parts_id, qty,
  1214. sellprice, fxsellprice, allocated,
  1215. assemblyitem, unit)
  1216. VALUES (?, ?, ?, ?, 0, 0, ?, 't', ?)|;
  1217. $sth = $dbh->prepare($query);
  1218. $sth->execute(
  1219. $form->{id}, $ref->{description}, $ref->{parts_id},
  1220. $ref->{qty}, $allocated, $ref->{unit})
  1221. || $form->dberror($query);
  1222. }
  1223. $sth->finish;
  1224. }
  1225. sub cogs {
  1226. my ($dbh2, $form, $id, $totalqty, $project_id) = @_;
  1227. my $dbh = $form->{dbh};
  1228. my $query = qq|
  1229. SELECT i.id, i.trans_id, i.qty, i.allocated, i.sellprice,
  1230. i.fxsellprice, p.inventory_accno_id,
  1231. p.expense_accno_id
  1232. FROM invoice i, parts p
  1233. WHERE i.parts_id = p.id
  1234. AND i.parts_id = ?
  1235. AND (i.qty + i.allocated) < 0
  1236. ORDER BY trans_id|;
  1237. my $sth = $dbh->prepare($query);
  1238. $sth->execute($id) || $form->dberror($query);
  1239. my $allocated = 0;
  1240. my $qty;
  1241. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1242. if (($qty = (($ref->{qty} * -1) - $ref->{allocated}))
  1243. > $totalqty) {
  1244. $qty = $totalqty;
  1245. }
  1246. $form->update_balance(
  1247. $dbh, "invoice", "allocated", qq|id = $ref->{id}|,
  1248. $qty);
  1249. # total expenses and inventory
  1250. # sellprice is the cost of the item
  1251. my $linetotal = $form->round_amount(
  1252. $ref->{sellprice} * $qty, 2);
  1253. # add expense
  1254. push @{ $form->{acc_trans}{lineitems} }, {
  1255. chart_id => $ref->{expense_accno_id},
  1256. amount => $linetotal * -1,
  1257. project_id => $project_id,
  1258. invoice_id => $ref->{id} };
  1259. # deduct inventory
  1260. push @{ $form->{acc_trans}{lineitems} }, {
  1261. chart_id => $ref->{inventory_accno_id},
  1262. amount => $linetotal,
  1263. project_id => $project_id,
  1264. invoice_id => $ref->{id} };
  1265. # add allocated
  1266. $allocated += -$qty;
  1267. last if (($totalqty -= $qty) <= 0);
  1268. }
  1269. $sth->finish;
  1270. $allocated;
  1271. $dbh->commit;
  1272. }
  1273. sub reverse_invoice {
  1274. my ($dbh2, $form) = @_;
  1275. my $dbh = $form->{dbh};
  1276. my $query = qq|
  1277. SELECT id FROM ar
  1278. WHERE id = ?|;
  1279. my $sth;
  1280. $sth = $dbh->prepare($query);
  1281. $sth->execute($form->{id});
  1282. my ($id) = $sth->fetchrow_array;
  1283. return unless $id;
  1284. # reverse inventory items
  1285. my $query = qq|
  1286. SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly,
  1287. p.inventory_accno_id
  1288. FROM invoice i
  1289. JOIN parts p ON (i.parts_id = p.id)
  1290. WHERE i.trans_id = ?|;
  1291. my $sth = $dbh->prepare($query);
  1292. $sth->execute($form->{id}) || $form->dberror($query);
  1293. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1294. if ($ref->{inventory_accno_id} || $ref->{assembly}) {
  1295. # if the invoice item is not an assemblyitem
  1296. # adjust parts onhand
  1297. if (!$ref->{assemblyitem}) {
  1298. # adjust onhand in parts table
  1299. $form->update_balance(
  1300. $dbh, "parts", "onhand",
  1301. qq|id = $ref->{parts_id}|, $ref->{qty});
  1302. }
  1303. # loop if it is an assembly
  1304. next if ($ref->{assembly});
  1305. # de-allocated purchases
  1306. $query = qq|
  1307. SELECT id, trans_id, allocated
  1308. FROM invoice
  1309. WHERE parts_id = ?
  1310. AND allocated > 0
  1311. ORDER BY trans_id DESC|;
  1312. my $sth = $dbh->prepare($query);
  1313. $sth->execute($ref->{parts_id})
  1314. || $form->dberror($query);
  1315. while (my $inhref = $sth->fetchrow_hashref(NAME_lc)) {
  1316. $qty = $ref->{qty};
  1317. if (($ref->{qty} - $inhref->{allocated}) > 0) {
  1318. $qty = $inhref->{allocated};
  1319. }
  1320. # update invoice
  1321. $form->update_balance(
  1322. $dbh, "invoice", "allocated",
  1323. qq|id = $inhref->{id}|, $qty * -1);
  1324. last if (($ref->{qty} -= $qty) <= 0);
  1325. }
  1326. $sth->finish;
  1327. }
  1328. }
  1329. $sth->finish;
  1330. # delete acc_trans
  1331. $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
  1332. $sth = $dbh->prepare($query);
  1333. $sth->execute($form->{id}) || $form->dberror($query);
  1334. # delete invoice entries
  1335. $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
  1336. $sth = $dbh->prepare($query);
  1337. $sth->execute($form->{id}) || $form->dberror($query);
  1338. $query = qq|DELETE FROM shipto WHERE trans_id = ?|;
  1339. $sth = $dbh->prepare($query);
  1340. $sth->execute($form->{id}) || $form->dberror($query);
  1341. $dbh->commit;
  1342. }
  1343. sub delete_invoice {
  1344. my ($self, $myconfig, $form) = @_;
  1345. my $dbh = $form->{dbh};
  1346. my $sth;
  1347. &reverse_invoice($dbh, $form);
  1348. my %audittrail = (
  1349. tablename => 'ar',
  1350. reference => $form->{invnumber},
  1351. formname => $form->{type},
  1352. action => 'deleted',
  1353. id => $form->{id} );
  1354. $form->audittrail($dbh, "", \%audittrail);
  1355. # delete AR record
  1356. my $query = qq|DELETE FROM ar WHERE id = ?|;
  1357. $sth = $dbh->prepare($query);
  1358. $sth->execute($form->{id}) || $form->dberror($query);
  1359. # delete spool files
  1360. $query = qq|
  1361. SELECT spoolfile FROM status
  1362. WHERE trans_id = ? AND spoolfile IS NOT NULL|;
  1363. $sth = $dbh->prepare($query);
  1364. $sth->execute($form->{id}) || $form->dberror($query);
  1365. my $spoolfile;
  1366. my @spoolfiles = ();
  1367. while (($spoolfile) = $sth->fetchrow_array) {
  1368. push @spoolfiles, $spoolfile;
  1369. }
  1370. $sth->finish;
  1371. # delete status entries
  1372. $query = qq|DELETE FROM status WHERE trans_id = ?|;
  1373. $sth = $dbh->prepare($query);
  1374. $sth->execute($form->{id}) || $form->dberror($query);
  1375. my $rc = $dbh->commit;
  1376. if ($rc) {
  1377. foreach $spoolfile (@spoolfiles) {
  1378. unlink "${LedgerSMB::Sysconfig::spool}/$spoolfile"
  1379. if $spoolfile;
  1380. }
  1381. }
  1382. $dbh->commit;
  1383. $rc;
  1384. }
  1385. sub retrieve_invoice {
  1386. my ($self, $myconfig, $form) = @_;
  1387. my $dbh = $form->{dbh};
  1388. my $query;
  1389. if ($form->{id}) {
  1390. # get default accounts and last invoice number
  1391. $query = qq|
  1392. SELECT value AS currencies FROM defaults
  1393. WHERE setting_key = 'curr'|;
  1394. } else {
  1395. $query = qq|
  1396. SELECT value AS currencies, current_date AS transdate
  1397. FROM defaults
  1398. WHERE setting_key = 'curr'|;
  1399. }
  1400. my $sth = $dbh->prepare($query);
  1401. $sth->execute || $form->dberror($query);
  1402. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1403. for (keys %$ref) { $form->{$_} = $ref->{$_} }
  1404. $sth->finish;
  1405. if ($form->{id}) {
  1406. # retrieve invoice
  1407. $query = qq|
  1408. SELECT a.invnumber, a.ordnumber, a.quonumber,
  1409. a.transdate, a.paid,
  1410. a.shippingpoint, a.shipvia, a.terms, a.notes,
  1411. a.intnotes,
  1412. a.duedate, a.taxincluded, a.curr AS currency,
  1413. a.employee_id, e.name AS employee, a.till,
  1414. a.customer_id,
  1415. a.language_code, a.ponumber
  1416. FROM ar a
  1417. LEFT JOIN employee e ON (e.id = a.employee_id)
  1418. WHERE a.id = ?|;
  1419. $sth = $dbh->prepare($query);
  1420. $sth->execute($form->{id}) || $form->dberror($query);
  1421. $ref = $sth->fetchrow_hashref(NAME_lc);
  1422. for (keys %$ref) { $form->{$_} = $ref->{$_} }
  1423. $sth->finish;
  1424. # get shipto
  1425. $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
  1426. $sth = $dbh->prepare($query);
  1427. $sth->execute($form->{id}) || $form->dberror($query);
  1428. $ref = $sth->fetchrow_hashref(NAME_lc);
  1429. for (keys %$ref) { $form->{$_} = $ref->{$_} }
  1430. $sth->finish;
  1431. # retrieve individual items
  1432. $query = qq|
  1433. SELECT i.description, i.qty, i.fxsellprice,
  1434. i.sellprice, i.discount, i.parts_id AS id,
  1435. i.unit, i.deliverydate, i.project_id,
  1436. pr.projectnumber, i.serialnumber, i.notes,
  1437. p.partnumber, p.assembly, p.bin,
  1438. pg.partsgroup, p.partsgroup_id,
  1439. p.partnumber AS sku, p.listprice, p.lastcost,
  1440. p.weight, p.onhand, p.inventory_accno_id,
  1441. p.income_accno_id, p.expense_accno_id,
  1442. t.description AS partsgrouptranslation
  1443. FROM invoice i
  1444. JOIN parts p ON (i.parts_id = p.id)
  1445. LEFT JOIN project pr ON (i.project_id = pr.id)
  1446. LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
  1447. LEFT JOIN translation t
  1448. ON (t.trans_id = p.partsgroup_id
  1449. AND t.language_code
  1450. = ?)
  1451. WHERE i.trans_id = ?
  1452. AND NOT i.assemblyitem = '1'
  1453. ORDER BY i.id|;
  1454. $sth = $dbh->prepare($query);
  1455. $sth->execute($form->{language_code}, $form->{id})
  1456. || $form->dberror($query);
  1457. # foreign currency
  1458. &exchangerate_defaults($dbh, $form);
  1459. # query for price matrix
  1460. my $pmh = PriceMatrix::price_matrix_query($dbh, $form);
  1461. # taxes
  1462. $query = qq|
  1463. SELECT c.accno
  1464. FROM chart c
  1465. JOIN partstax pt ON (pt.chart_id = c.id)
  1466. WHERE pt.parts_id = ?|;
  1467. my $tth = $dbh->prepare($query) || $form->dberror($query);
  1468. my $taxrate;
  1469. my $ptref;
  1470. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1471. my ($dec) = ($ref->{fxsellprice} =~ /\.(\d+)/);
  1472. $dec = length $dec;
  1473. my $decimalplaces = ($dec > 2) ? $dec : 2;
  1474. $tth->execute($ref->{id});
  1475. $ref->{taxaccounts} = "";
  1476. $taxrate = 0;
  1477. while ($ptref = $tth->fetchrow_hashref(NAME_lc)) {
  1478. $ref->{taxaccounts} .= "$ptref->{accno} ";
  1479. $taxrate += $form->{"$ptref->{accno}_rate"};
  1480. }
  1481. $tth->finish;
  1482. chop $ref->{taxaccounts};
  1483. # price matrix
  1484. $ref->{sellprice} =
  1485. ($ref->{fxsellprice}
  1486. * $form->{$form->{currency}});
  1487. PriceMatrix::price_matrix(
  1488. $pmh, $ref, $form->{transdate}, $decimalplaces,
  1489. $form, $myconfig);
  1490. $ref->{sellprice} = $ref->{fxsellprice};
  1491. $ref->{partsgroup} = $ref->{partsgrouptranslation}
  1492. if $ref->{partsgrouptranslation};
  1493. push @{ $form->{invoice_details} }, $ref;
  1494. }
  1495. $sth->finish;
  1496. }
  1497. @queries = $form->run_custom_queries('ar', 'SELECT');
  1498. my $rc = $dbh->commit;
  1499. $rc;
  1500. }
  1501. sub retrieve_item {
  1502. my ($self, $myconfig, $form) = @_;
  1503. my $dbh = $form->{dbh};
  1504. my $i = $form->{rowcount};
  1505. my $null;
  1506. my $var;
  1507. my $where = "WHERE p.obsolete = '0' AND NOT p.income_accno_id IS NULL";
  1508. if ($form->{"partnumber_$i"} ne "") {
  1509. $var = $dbh->quote($form->like(lc $form->{"partnumber_$i"}));
  1510. $where .= " AND lower(p.partnumber) LIKE $var";
  1511. }
  1512. if ($form->{"description_$i"} ne "") {
  1513. $var = $dbh->quote($form->like(lc $form->{"description_$i"}));
  1514. if ($form->{language_code} ne "") {
  1515. $where .= " AND lower(t1.description) LIKE $var";
  1516. } else {
  1517. $where .= " AND lower(p.description) LIKE $var";
  1518. }
  1519. }
  1520. if ($form->{"partsgroup_$i"} ne "") {
  1521. ($null, $var) = split /--/, $form->{"partsgroup_$i"};
  1522. $var = $dbh->quote($var);
  1523. if ($var == 0) {
  1524. # search by partsgroup, this is for the POS
  1525. $where .= qq| AND pg.partsgroup = |.
  1526. $dbh->quote($form->{"partsgroup_$i"});
  1527. } else {
  1528. $where .= qq| AND p.partsgroup_id = $var|;
  1529. }
  1530. }
  1531. if ($form->{"description_$i"} ne "") {
  1532. $where .= " ORDER BY 3";
  1533. } else {
  1534. $where .= " ORDER BY 2";
  1535. }
  1536. my $query = qq|
  1537. SELECT p.id, p.partnumber, p.description, p.sellprice,
  1538. p.listprice, p.lastcost, p.unit, p.assembly, p.bin,
  1539. p.onhand, p.notes, p.inventory_accno_id,
  1540. p.income_accno_id, p.expense_accno_id, pg.partsgroup,
  1541. p.partsgroup_id, p.partnumber AS sku, p.weight,
  1542. t1.description AS translation,
  1543. t2.description AS grouptranslation
  1544. FROM parts p
  1545. LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
  1546. LEFT JOIN translation t1
  1547. ON (t1.trans_id = p.id AND t1.language_code = ?)
  1548. LEFT JOIN translation t2
  1549. ON (t2.trans_id = p.partsgroup_id
  1550. AND t2.language_code = ?)
  1551. $where|;
  1552. my $sth = $dbh->prepare($query);
  1553. $sth->execute($form->{language_code}, $form->{language_code})
  1554. || $form->dberror($query);
  1555. my $ref;
  1556. my $ptref;
  1557. # setup exchange rates
  1558. &exchangerate_defaults($dbh, $form);
  1559. # taxes
  1560. $query = qq|
  1561. SELECT c.accno
  1562. FROM chart c
  1563. JOIN partstax pt ON (c.id = pt.chart_id)
  1564. WHERE pt.parts_id = ?|;
  1565. my $tth = $dbh->prepare($query) || $form->dberror($query);
  1566. # price matrix
  1567. my $pmh = PriceMatrix::price_matrix_query($dbh, $form);
  1568. my $transdate = $form->datetonum($myconfig, $form->{transdate});
  1569. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1570. my ($dec) = ($ref->{sellprice} =~ /\.(\d+)/);
  1571. $dec = length $dec;
  1572. my $decimalplaces = ($dec > 2) ? $dec : 2;
  1573. # get taxes for part
  1574. $tth->execute($ref->{id});
  1575. $ref->{taxaccounts} = "";
  1576. while ($ptref = $tth->fetchrow_hashref(NAME_lc)) {
  1577. $ref->{taxaccounts} .= "$ptref->{accno} ";
  1578. }
  1579. $tth->finish;
  1580. chop $ref->{taxaccounts};
  1581. # get matrix
  1582. PriceMatrix::price_matrix(
  1583. $pmh, $ref, $transdate, $decimalplaces, $form,
  1584. $myconfig);
  1585. $ref->{description} = $ref->{translation}
  1586. if $ref->{translation};
  1587. $ref->{partsgroup} = $ref->{grouptranslation}
  1588. if $ref->{grouptranslation};
  1589. push @{ $form->{item_list} }, $ref;
  1590. }
  1591. $sth->finish;
  1592. $dbh->commit;
  1593. }
  1594. sub exchangerate_defaults {
  1595. my ($dbh2, $form) = @_;
  1596. $dbh = $form->{dbh};
  1597. my $var;
  1598. # get default currencies
  1599. my $query = qq|
  1600. SELECT substr(value,1,3), value FROM defaults
  1601. WHERE setting_key = 'curr'|;
  1602. my $eth = $dbh->prepare($query) || $form->dberror($query);
  1603. $eth->execute;
  1604. ($form->{defaultcurrency}, $form->{currencies}) = $eth->fetchrow_array;
  1605. $eth->finish;
  1606. $query = qq|
  1607. SELECT buy
  1608. FROM exchangerate
  1609. WHERE curr = ?
  1610. AND transdate = ?|;
  1611. my $eth1 = $dbh->prepare($query) || $form->dberror($query);
  1612. $query = qq/
  1613. SELECT max(transdate || ' ' || buy || ' ' || curr)
  1614. FROM exchangerate
  1615. WHERE curr = ?/;
  1616. my $eth2 = $dbh->prepare($query) || $form->dberror($query);
  1617. # get exchange rates for transdate or max
  1618. foreach $var (split /:/, substr($form->{currencies},4)) {
  1619. $eth1->execute($var, $form->{transdate});
  1620. ($form->{$var}) = $eth1->fetchrow_array;
  1621. if (! $form->{$var} ) {
  1622. $eth2->execute($var);
  1623. ($form->{$var}) = $eth2->fetchrow_array;
  1624. ($null, $form->{$var}) = split / /, $form->{$var};
  1625. $form->{$var} = 1 unless $form->{$var};
  1626. $eth2->finish;
  1627. }
  1628. $eth1->finish;
  1629. }
  1630. $form->{$form->{currency}} = $form->{exchangerate}
  1631. if $form->{exchangerate};
  1632. $form->{$form->{currency}} ||= 1;
  1633. $form->{$form->{defaultcurrency}} = 1;
  1634. }
  1635. 1;