summaryrefslogtreecommitdiff
path: root/LedgerSMB/IS.pm
blob: 9c117eb99f145b0576461c9fd8d8f029a08417ff (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. }
  637. sub post_invoice {
  638. my ($self, $myconfig, $form) = @_;
  639. my $dbh = $form->{dbh};
  640. my $query;
  641. my $sth;
  642. my $null;
  643. my $project_id;
  644. my $exchangerate = 0;
  645. my $keepcleared = 0;
  646. %$form->{acc_trans} = ();
  647. ($null, $form->{employee_id}) = split /--/, $form->{employee};
  648. unless ($form->{employee_id}) {
  649. ($form->{employee}, $form->{employee_id})
  650. = $form->get_employee($dbh);
  651. }
  652. ($null, $form->{department_id}) = split(/--/, $form->{department});
  653. $form->{department_id} *= 1;
  654. $query = qq|
  655. SELECT (SELECT value FROM defaults
  656. WHERE setting_key = 'fxgain_accno_id')
  657. AS fxgain_accno_id,
  658. (SELECT value FROM defaults
  659. WHERE setting_key = 'fxloss_accno_id')
  660. AS fxloss_accno_id|;
  661. my ($fxgain_accno_id, $fxloss_accno_id) = $dbh->selectrow_array($query);
  662. $query = qq|
  663. SELECT p.assembly, p.inventory_accno_id,
  664. p.income_accno_id, p.expense_accno_id, p.project_id
  665. FROM parts p
  666. WHERE p.id = ?|;
  667. my $pth = $dbh->prepare($query) || $form->dberror($query);
  668. if ($form->{id}) {
  669. $keepcleared = 1;
  670. $query = qq|SELECT id FROM ar WHERE id = ?|;
  671. $sth = $dbh->prepare($query);
  672. $sth->execute($form->{id});
  673. if ($sth->fetchrow_array) {
  674. &reverse_invoice($dbh, $form);
  675. } else {
  676. $query = qq|INSERT INTO ar (id) VALUES (?)|;
  677. $sth = $dbh->prepare($query);
  678. $sth->execute($form->{id}) || $form->dberror($query);
  679. }
  680. }
  681. my $uid = localtime;
  682. $uid .= "$$";
  683. if (! $form->{id}) {
  684. $query = qq|
  685. INSERT INTO ar (invnumber, employee_id)
  686. VALUES ('$uid', ?)|;
  687. $sth = $dbh->prepare($query);
  688. $sth->execute($form->{employee_id}) || $form->dberror($query);
  689. $query = qq|SELECT id FROM ar WHERE invnumber = '$uid'|;
  690. $sth = $dbh->prepare($query);
  691. $sth->execute || $form->dberror($query);
  692. ($form->{id}) = $sth->fetchrow_array;
  693. $sth->finish;
  694. @queries = $form->run_custom_queries('ar', 'INSERT');
  695. }
  696. if ($form->{currency} eq $form->{defaultcurrency}) {
  697. $form->{exchangerate} = 1;
  698. } else {
  699. $exchangerate =
  700. $form->check_exchangerate(
  701. $myconfig, $form->{currency},
  702. $form->{transdate}, 'buy');
  703. }
  704. $form->{exchangerate} =
  705. ($exchangerate)
  706. ? $exchangerate
  707. : $form->parse_amount($myconfig, $form->{exchangerate});
  708. my $i;
  709. my $item;
  710. my $allocated = 0;
  711. my $taxrate;
  712. my $tax;
  713. my $fxtax;
  714. my @taxaccounts;
  715. my $amount;
  716. my $grossamount;
  717. my $invamount = 0;
  718. my $invnetamount = 0;
  719. my $diff = 0;
  720. my $ml;
  721. my $invoice_id;
  722. my $ndx;
  723. foreach $i (1 .. $form->{rowcount}) {
  724. $form->{"qty_$i"} =
  725. $form->parse_amount($myconfig, $form->{"qty_$i"});
  726. if ($form->{"qty_$i"}) {
  727. $pth->execute($form->{"id_$i"});
  728. $ref = $pth->fetchrow_hashref(NAME_lc);
  729. for (keys %$ref) { $form->{"${_}_$i"} = $ref->{$_} }
  730. $pth->finish;
  731. # project
  732. if ($form->{"projectnumber_$i"}) {
  733. ($null, $project_id)
  734. = split /--/,
  735. $form->{"projectnumber_$i"};
  736. }
  737. $project_id = $form->{"project_id_$i"}
  738. if $form->{"project_id_$i"};
  739. # keep entered selling price
  740. my $fxsellprice =
  741. $form->parse_amount(
  742. $myconfig, $form->{"sellprice_$i"});
  743. my ($dec) = ($fxsellprice =~ /\.(\d+)/);
  744. $dec = length $dec;
  745. my $decimalplaces = ($dec > 2) ? $dec : 2;
  746. # undo discount formatting
  747. $form->{"discount_$i"} =
  748. $form->parse_amount(
  749. $myconfig, $form->{"discount_$i"})/100;
  750. # deduct discount
  751. $form->{"sellprice_$i"} = $fxsellprice
  752. - $form->round_amount(
  753. $fxsellprice * $form->{"discount_$i"},
  754. $decimalplaces);
  755. # linetotal
  756. my $fxlinetotal = $form->round_amount(
  757. $form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
  758. $amount = $fxlinetotal * $form->{exchangerate};
  759. my $linetotal = $form->round_amount($amount, 2);
  760. $fxdiff += $amount - $linetotal;
  761. @taxaccounts = Tax::init_taxes(
  762. $form, $form->{"taxaccounts_$i"},
  763. $form->{"taxaccounts"});
  764. $ml = 1;
  765. $tax = Math::BigFloat->bzero();
  766. $fxtax = Math::BigFloat->bzero();
  767. if ($form->{taxincluded}) {
  768. $tax += $amount =
  769. Tax::calculate_taxes(
  770. \@taxaccounts, $form,
  771. $linetotal, 1);
  772. $form->{"sellprice_$i"} -= $amount
  773. / $form->{"qty_$i"};
  774. $fxtax += Tax::calculate_taxes(
  775. \@taxaccounts, $form, $linetotal, 1);
  776. } else {
  777. $tax += $amount = Tax::calculate_taxes(
  778. \@taxaccounts, $form, $linetotal, 0);
  779. $fxtax += Tax::calculate_taxes(
  780. \@taxaccounts, $form, $linetotal, 0);
  781. }
  782. for (@taxaccounts) {
  783. $form->{acc_trans}{$form->{id}}{$_->account}{amount} += $_->value;
  784. }
  785. $grossamount = $form->round_amount($linetotal, 2);
  786. if ($form->{taxincluded}) {
  787. $amount = $form->round_amount($tax, 2);
  788. $linetotal -= $form->round_amount(
  789. $tax - $diff, 2);
  790. $diff = ($amount - $tax);
  791. }
  792. # add linetotal to income
  793. $amount = $form->round_amount($linetotal, 2);
  794. push @{ $form->{acc_trans}{lineitems} }, {
  795. chart_id => $form->{"income_accno_id_$i"},
  796. amount => $amount,
  797. fxgrossamount => $fxlinetotal + $fxtax,
  798. grossamount => $grossamount,
  799. project_id => $project_id };
  800. $ndx = $#{@{$form->{acc_trans}{lineitems}}};
  801. $form->{"sellprice_$i"} =
  802. $form->round_amount(
  803. $form->{"sellprice_$i"}
  804. * $form->{exchangerate},
  805. $decimalplaces);
  806. if ($form->{"inventory_accno_id_$i"}
  807. || $form->{"assembly_$i"}) {
  808. if ($form->{"assembly_$i"}) {
  809. # If the assembly consists of all
  810. # services, we don't keep inventory,
  811. # so we should not update it
  812. $query = qq|
  813. SELECT sum(
  814. p.inventory_accno_id),
  815. p.assembly
  816. FROM parts p
  817. JOIN assembly a
  818. ON (a.parts_id = p.id)
  819. WHERE a.id = $form->{"id_$i"}
  820. GROUP BY p.assembly|;
  821. $sth = $dbh->prepare($query);
  822. $sth->execute($form->{"id_$i"})
  823. || $form->dberror($query);
  824. my ($inv, $assembly)
  825. = $sth->fetchrow_array;
  826. $sth->finish;
  827. if ($inv || $assembly) {
  828. $form->update_balance($dbh,
  829. "parts",
  830. "onhand",
  831. qq|id = |.
  832. qq|$form->{"id_$i"}|,
  833. $form->{"qty_$i"} * -1)
  834. unless $form->{shipped};
  835. }
  836. &process_assembly(
  837. $dbh, $form, $form->{"id_$i"},
  838. $form->{"qty_$i"}, $project_id);
  839. } else {
  840. $form->update_balance(
  841. $dbh, "parts", "onhand",
  842. qq|id = $form->{"id_$i"}|,
  843. $form->{"qty_$i"} * -1)
  844. unless $form->{shipped};
  845. $allocated = &cogs(
  846. $dbh, $form, $form->{"id_$i"},
  847. $form->{"qty_$i"}, $project_id);
  848. }
  849. }
  850. # save detail record in invoice table
  851. $query = qq|
  852. INSERT INTO invoice (description)
  853. VALUES ('$uid')|;
  854. $dbh->do($query) || $form->dberror($query);
  855. $query = qq|
  856. SELECT id FROM invoice
  857. WHERE description = '$uid'|;
  858. ($invoice_id) = $dbh->selectrow_array($query);
  859. unless ($form->{"deliverydate_$i"}){
  860. undef $form->{"deliverydate_$i"};
  861. }
  862. $query = qq|
  863. UPDATE invoice
  864. SET trans_id = ?,
  865. parts_id = ?,
  866. description = ?,
  867. qty = ?,
  868. sellprice = ?,
  869. fxsellprice = ?,
  870. discount = ?,
  871. allocated = ?,
  872. unit = ?,
  873. deliverydate = ?,
  874. project_id = ?,
  875. serialnumber = ?,
  876. notes = ?
  877. WHERE id = ?|;
  878. $sth = $dbh->prepare($query);
  879. $sth->execute(
  880. $form->{id}, $form->{"id_$i"},
  881. $form->{"description_$i"}, $form->{"qty_$i"},
  882. $form->{"sellprice_$i"}, $fxsellprice,
  883. $form->{"discount_$i"}, $allocated,
  884. $form->{"unit_$i"}, $form->{"deliverydate_$i"},
  885. $project_id, $form->{"serialnumber_$i"},
  886. $form->{"notes_$i"}, $invoice_id)
  887. || $form->dberror($query);
  888. # add invoice_id
  889. $form->{acc_trans}{lineitems}[$ndx]->{invoice_id}
  890. = $invoice_id;
  891. }
  892. }
  893. $form->{paid} = 0;
  894. for $i (1 .. $form->{paidaccounts}) {
  895. $form->{"paid_$i"} =
  896. $form->parse_amount($myconfig, $form->{"paid_$i"});
  897. $form->{paid} += $form->{"paid_$i"};
  898. $form->{datepaid} = $form->{"datepaid_$i"}
  899. if ($form->{"paid_$i"});
  900. }
  901. # add lineitems + tax
  902. $amount = 0;
  903. $grossamount = 0;
  904. $fxgrossamount = 0;
  905. for (@{ $form->{acc_trans}{lineitems} }) {
  906. $amount += $_->{amount};
  907. $grossamount += $_->{grossamount};
  908. $fxgrossamount += $_->{fxgrossamount};
  909. }
  910. $invnetamount = $amount;
  911. $amount = 0;
  912. for (split / /, $form->{taxaccounts}) {
  913. $amount +=
  914. $form->{acc_trans}{$form->{id}}{$_}{amount} =
  915. $form->round_amount(
  916. $form->{acc_trans}{$form->{id}}{$_}{amount},
  917. 2);
  918. }
  919. $invamount = $invnetamount + $amount;
  920. $diff = 0;
  921. if ($form->{taxincluded}) {
  922. $diff = $form->round_amount($grossamount - $invamount, 2);
  923. $invamount += $diff;
  924. }
  925. $fxdiff = $form->round_amount($fxdiff,2);
  926. $invnetamount += $fxdiff;
  927. $invamount += $fxdiff;
  928. if ($form->round_amount($form->{paid} - $fxgrossamount,2) == 0) {
  929. $form->{paid} = $invamount;
  930. } else {
  931. $form->{paid} = $form->round_amount(
  932. $form->{paid} * $form->{exchangerate}, 2);
  933. }
  934. foreach $ref (sort { $b->{amount} <=> $a->{amount} }
  935. @ { $form->{acc_trans}{lineitems} }) {
  936. $amount = $ref->{amount} + $diff + $fxdiff;
  937. $query = qq|
  938. INSERT INTO acc_trans
  939. (trans_id, chart_id, amount,
  940. transdate, project_id, invoice_id)
  941. VALUES (?, ?, ?, ?, ?, ?)|;
  942. $sth = $dbh->prepare($query);
  943. $sth->execute(
  944. $form->{id}, $ref->{chart_id}, $amount,
  945. $form->{transdate}, $ref->{project_id},
  946. $ref->{invoice_id})
  947. || $form->dberror($query);
  948. $diff = 0;
  949. $fxdiff = 0;
  950. }
  951. $form->{receivables} = $invamount * -1;
  952. delete $form->{acc_trans}{lineitems};
  953. # update exchangerate
  954. if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
  955. $form->update_exchangerate(
  956. $dbh, $form->{currency}, $form->{transdate},
  957. $form->{exchangerate}, 0);
  958. }
  959. # record receivable
  960. if ($form->{receivables}) {
  961. ($accno) = split /--/, $form->{AR};
  962. $query = qq|
  963. INSERT INTO acc_trans
  964. (trans_id, chart_id, amount, transdate)
  965. VALUES (?, (SELECT id FROM chart WHERE accno = ?),
  966. ?, ?)|;
  967. $sth = $dbh->prepare($query);
  968. $sth->execute(
  969. $form->{id}, $accno, $form->{receivables},
  970. $form->{transdate})
  971. || $form->dberror($query);
  972. }
  973. foreach my $trans_id (keys %{$form->{acc_trans}}) {
  974. foreach my $accno (keys %{$form->{acc_trans}{$trans_id}}) {
  975. $amount = $form->round_amount(
  976. $form->{acc_trans}{$trans_id}{$accno}{amount},
  977. 2);
  978. if ($amount) {
  979. $query = qq|
  980. INSERT INTO acc_trans
  981. (trans_id, chart_id, amount,
  982. transdate)
  983. VALUES (?, (SELECT id FROM chart
  984. WHERE accno = ?),
  985. ?, ?)|;
  986. $sth = $dbh->prepare($query);
  987. $sth->execute(
  988. $trans_id, $accno, $amount,
  989. $form->{transdate})
  990. || $form->dberror($query);
  991. }
  992. }
  993. }
  994. # if there is no amount but a payment record receivable
  995. if ($invamount == 0) {
  996. $form->{receivables} = 1;
  997. }
  998. my $cleared = 0;
  999. # record payments and offsetting AR
  1000. for $i (1 .. $form->{paidaccounts}) {
  1001. if ($form->{"paid_$i"}) {
  1002. my ($accno) = split /--/, $form->{"AR_paid_$i"};
  1003. $form->{"datepaid_$i"} = $form->{transdate}
  1004. unless ($form->{"datepaid_$i"});
  1005. $form->{datepaid} = $form->{"datepaid_$i"};
  1006. $exchangerate = 0;
  1007. if ($form->{currency} eq $form->{defaultcurrency}) {
  1008. $form->{"exchangerate_$i"} = 1;
  1009. } else {
  1010. $exchangerate =
  1011. $form->check_exchangerate(
  1012. $myconfig, $form->{currency},
  1013. $form->{"datepaid_$i"}, 'buy');
  1014. $form->{"exchangerate_$i"} =
  1015. ($exchangerate)
  1016. ? $exchangerate
  1017. : $form->parse_amount(
  1018. $myconfig,
  1019. $form->{"exchangerate_$i"});
  1020. }
  1021. # record AR
  1022. $amount = $form->round_amount(
  1023. $form->{"paid_$i"} * $form->{exchangerate}, 2);
  1024. if ($form->{receivables}) {
  1025. $query = qq|
  1026. INSERT INTO acc_trans
  1027. (trans_id, chart_id, amount,
  1028. transdate)
  1029. VALUES (?, (SELECT id FROM chart
  1030. WHERE accno = ?),
  1031. ?, ?)|;
  1032. $sth = $dbh->prepare($query);
  1033. $sth->execute(
  1034. $form->{id}, $form->{AR}, $amount,
  1035. $form->{"datepaid_$i"})
  1036. || $form->dberror($query);
  1037. }
  1038. # record payment
  1039. $amount = $form->{"paid_$i"} * -1;
  1040. if ($keepcleared) {
  1041. $cleared = ($form->{"cleared_$i"}) ? 1 : 0;
  1042. }
  1043. $query = qq|
  1044. INSERT INTO acc_trans
  1045. (trans_id, chart_id, amount,
  1046. transdate, source, memo, cleared)
  1047. VALUES (?, (SELECT id FROM chart
  1048. WHERE accno = ?),
  1049. ?, ?, ?, ?, ?)|;
  1050. $sth = $dbh->prepare($query);
  1051. $sth->execute(
  1052. $form->{id}, $accno, $amount,
  1053. $form->{"datepaid_$i"}, $form->{"source_$i"},
  1054. $form->{"memo_$i"}, $cleared)
  1055. || $form->dberror($query);
  1056. # exchangerate difference
  1057. $amount = $form->round_amount(
  1058. ($form->round_amount(
  1059. $form->{"paid_$i"}
  1060. * $form->{"exchangerate_$i"}
  1061. - $form->{"paid_$i"}, 2)) * -1,
  1062. 2);
  1063. if ($amount) {
  1064. $query = qq|
  1065. INSERT INTO acc_trans
  1066. (trans_id, chart_id, amount,
  1067. transdate, source,
  1068. fx_transaction, cleared)
  1069. VALUES (?, (SELECT id FROM chart
  1070. WHERE accno = >),
  1071. ?, ?, ?, '1', ?)|;
  1072. $sth = $dbh->prepare($query);
  1073. $sth->execute(
  1074. $form->{id}, $accno, $amount,
  1075. $form->{"datepaid_$i"},
  1076. $form->{"source_$i"}, $cleared )
  1077. || $form->dberror($query);
  1078. }
  1079. # gain/loss
  1080. $amount = $form->round_amount(
  1081. ($form->round_amount(
  1082. $form->{"paid_$i"}
  1083. * $form->{exchangerate},2)
  1084. - $form->round_amount(
  1085. $form->{"paid_$i"}
  1086. * $form->{"exchangerate_$i"},2)
  1087. ) * -1,
  1088. 2);
  1089. if ($amount) {
  1090. my $accno_id =
  1091. ($amount > 0)
  1092. ? $fxgain_accno_id
  1093. : $fxloss_accno_id;
  1094. $query = qq|
  1095. INSERT INTO acc_trans (
  1096. trans_id, chart_id, amount,
  1097. transdate, fx_transaction,
  1098. cleared)
  1099. VALUES (?, ?, ?, ?, '1', ?)|;
  1100. $sth = $dbh->prepare($query);
  1101. $sth->execute(
  1102. $form->{id}, $accno_id, $amount,
  1103. $form->{"datepaid_$i"}, $cleared)
  1104. || $form->dberror($query);
  1105. }
  1106. # update exchange rate
  1107. if (($form->{currency} ne $form->{defaultcurrency})
  1108. && !$exchangerate) {
  1109. $form->update_exchangerate(
  1110. $dbh, $form->{currency},
  1111. $form->{"datepaid_$i"},
  1112. $form->{"exchangerate_$i"}, 0);
  1113. }
  1114. }
  1115. }
  1116. # set values which could be empty to 0
  1117. $form->{terms} *= 1;
  1118. $form->{taxincluded} *= 1;
  1119. $form->{invnumber} =
  1120. $form->update_defaults($myconfig, "sinumber", $dbh)
  1121. unless $form->{invnumber};
  1122. # save AR record
  1123. $query = qq|
  1124. UPDATE ar set
  1125. invnumber = ?,
  1126. ordnumber = ?,
  1127. quonumber = ?,
  1128. transdate = ?,
  1129. customer_id = ?,
  1130. amount = ?,
  1131. netamount = ?,
  1132. paid = ?,
  1133. datepaid = ?,
  1134. duedate = ?,
  1135. invoice = '1',
  1136. shippingpoint = ?,
  1137. shipvia = ?,
  1138. terms = ?,
  1139. notes = ?,
  1140. intnotes = ?,
  1141. taxincluded = ?,
  1142. curr = ?,
  1143. department_id = ?,
  1144. employee_id = ?,
  1145. till = ?,
  1146. language_code = ?,
  1147. ponumber = ?
  1148. WHERE id = ?
  1149. |;
  1150. $sth = $dbh->prepare($query);
  1151. $sth->execute(
  1152. $form->{invnumber}, $form->{ordnumber}, $form->{quonumber},
  1153. $form->{transdate}, $form->{customer_id}, $invamount,
  1154. $invnetamount, $form->{paid}, $form->{datepaid},
  1155. $form->{duedate}, $form->{shippingpoint}, $form->{shipvia},
  1156. $form->{terms}, $form->{notes}, $form->{intnotes},
  1157. $form->{taxincluded}, $form->{currency}, $form->{department_id},
  1158. $form->{employee_id}, $form->{till}, $form->{language_code},
  1159. $form->{ponumber}, $form->{id})
  1160. || $form->dberror($query);
  1161. # add shipto
  1162. $form->{name} = $form->{customer};
  1163. $form->{name} =~ s/--$form->{customer_id}//;
  1164. $form->add_shipto($dbh, $form->{id});
  1165. # save printed, emailed and queued
  1166. $form->save_status($dbh);
  1167. my %audittrail = (
  1168. tablename => 'ar',
  1169. reference => $form->{invnumber},
  1170. formname => $form->{type},
  1171. action => 'posted',
  1172. id => $form->{id} );
  1173. $form->audittrail($dbh, "", \%audittrail);
  1174. $form->save_recurring($dbh, $myconfig);
  1175. my $rc = $dbh->commit;
  1176. $rc;
  1177. }
  1178. sub process_assembly {
  1179. my ($dbh2, $form, $id, $totalqty, $project_id) = @_;
  1180. my $dbh = $form->{dbh};
  1181. my $query = qq|
  1182. SELECT a.parts_id, a.qty, p.assembly,
  1183. p.partnumber, p.description, p.unit,
  1184. p.inventory_accno_id, p.income_accno_id,
  1185. p.expense_accno_id
  1186. FROM assembly a
  1187. JOIN parts p ON (a.parts_id = p.id)
  1188. WHERE a.id = ?|;
  1189. my $sth = $dbh->prepare($query);
  1190. $sth->execute($id) || $form->dberror($query);
  1191. my $allocated;
  1192. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1193. $allocated = 0;
  1194. $ref->{inventory_accno_id} *= 1;
  1195. $ref->{expense_accno_id} *= 1;
  1196. # multiply by number of assemblies
  1197. $ref->{qty} *= $totalqty;
  1198. if ($ref->{assembly}) {
  1199. &process_assembly(
  1200. $dbh, $form, $ref->{parts_id}, $ref->{qty},
  1201. $project_id);
  1202. next;
  1203. } else {
  1204. if ($ref->{inventory_accno_id}) {
  1205. $allocated = &cogs(
  1206. $dbh, $form, $ref->{parts_id},
  1207. $ref->{qty}, $project_id);
  1208. }
  1209. }
  1210. $query = qq|
  1211. INSERT INTO invoice
  1212. (trans_id, description, parts_id, qty,
  1213. sellprice, fxsellprice, allocated,
  1214. assemblyitem, unit)
  1215. VALUES (?, ?, ?, ?, 0, 0, ?, 't', ?)|;
  1216. $sth = $dbh->prepare($query);
  1217. $sth->execute(
  1218. $form->{id}, $ref->{description}, $ref->{parts_id},
  1219. $ref->{qty}, $allocated, $ref->{unit})
  1220. || $form->dberror($query);
  1221. }
  1222. $sth->finish;
  1223. }
  1224. sub cogs {
  1225. my ($dbh2, $form, $id, $totalqty, $project_id) = @_;
  1226. my $dbh = $form->{dbh};
  1227. my $query = qq|
  1228. SELECT i.id, i.trans_id, i.qty, i.allocated, i.sellprice,
  1229. i.fxsellprice, p.inventory_accno_id,
  1230. p.expense_accno_id
  1231. FROM invoice i, parts p
  1232. WHERE i.parts_id = p.id
  1233. AND i.parts_id = ?
  1234. AND (i.qty + i.allocated) < 0
  1235. ORDER BY trans_id|;
  1236. my $sth = $dbh->prepare($query);
  1237. $sth->execute($id) || $form->dberror($query);
  1238. my $allocated = 0;
  1239. my $qty;
  1240. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1241. if (($qty = (($ref->{qty} * -1) - $ref->{allocated}))
  1242. > $totalqty) {
  1243. $qty = $totalqty;
  1244. }
  1245. $form->update_balance(
  1246. $dbh, "invoice", "allocated", qq|id = $ref->{id}|,
  1247. $qty);
  1248. # total expenses and inventory
  1249. # sellprice is the cost of the item
  1250. my $linetotal = $form->round_amount(
  1251. $ref->{sellprice} * $qty, 2);
  1252. # add expense
  1253. push @{ $form->{acc_trans}{lineitems} }, {
  1254. chart_id => $ref->{expense_accno_id},
  1255. amount => $linetotal * -1,
  1256. project_id => $project_id,
  1257. invoice_id => $ref->{id} };
  1258. # deduct inventory
  1259. push @{ $form->{acc_trans}{lineitems} }, {
  1260. chart_id => $ref->{inventory_accno_id},
  1261. amount => $linetotal,
  1262. project_id => $project_id,
  1263. invoice_id => $ref->{id} };
  1264. # add allocated
  1265. $allocated += -$qty;
  1266. last if (($totalqty -= $qty) <= 0);
  1267. }
  1268. $sth->finish;
  1269. $allocated;
  1270. }
  1271. sub reverse_invoice {
  1272. my ($dbh2, $form) = @_;
  1273. my $dbh = $form->{dbh};
  1274. my $query = qq|
  1275. SELECT id FROM ar
  1276. WHERE id = ?|;
  1277. my $sth;
  1278. $sth = $dbh->prepare($query);
  1279. $sth->execute($form->{id});
  1280. my ($id) = $sth->fetchrow_array;
  1281. return unless $id;
  1282. # reverse inventory items
  1283. my $query = qq|
  1284. SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly,
  1285. p.inventory_accno_id
  1286. FROM invoice i
  1287. JOIN parts p ON (i.parts_id = p.id)
  1288. WHERE i.trans_id = ?|;
  1289. my $sth = $dbh->prepare($query);
  1290. $sth->execute($form->{id}) || $form->dberror($query);
  1291. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  1292. if ($ref->{inventory_accno_id} || $ref->{assembly}) {
  1293. # if the invoice item is not an assemblyitem
  1294. # adjust parts onhand
  1295. if (!$ref->{assemblyitem}) {
  1296. # adjust onhand in parts table
  1297. $form->update_balance(
  1298. $dbh, "parts", "onhand",
  1299. qq|id = $ref->{parts_id}|, $ref->{qty});
  1300. }
  1301. # loop if it is an assembly
  1302. next if ($ref->{assembly});
  1303. # de-allocated purchases
  1304. $query = qq|
  1305. SELECT id, trans_id, allocated
  1306. FROM invoice
  1307. WHERE parts_id = ?
  1308. AND allocated > 0
  1309. ORDER BY trans_id DESC|;
  1310. my $sth = $dbh->prepare($query);
  1311. $sth->execute($ref->{parts_id})
  1312. || $form->dberror($query);
  1313. while (my $inhref = $sth->fetchrow_hashref(NAME_lc)) {
  1314. $qty = $ref->{qty};
  1315. if (($ref->{qty} - $inhref->{allocated}) > 0) {
  1316. $qty = $inhref->{allocated};
  1317. }
  1318. # update invoice
  1319. $form->update_balance(
  1320. $dbh, "invoice", "allocated",
  1321. qq|id = $inhref->{id}|, $qty * -1);
  1322. last if (($ref->{qty} -= $qty) <= 0);
  1323. }
  1324. $sth->finish;
  1325. }
  1326. }
  1327. $sth->finish;
  1328. # delete acc_trans
  1329. $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
  1330. $sth = $dbh->prepare($query);
  1331. $sth->execute($form->{id}) || $form->dberror($query);
  1332. # delete invoice entries
  1333. $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
  1334. $sth = $dbh->prepare($query);
  1335. $sth->execute($form->{id}) || $form->dberror($query);
  1336. $query = qq|DELETE FROM shipto WHERE trans_id = ?|;
  1337. $sth = $dbh->prepare($query);
  1338. $sth->execute($form->{id}) || $form->dberror($query);
  1339. $dbh->commit;
  1340. }
  1341. sub delete_invoice {
  1342. my ($self, $myconfig, $form) = @_;
  1343. my $dbh = $form->{dbh};
  1344. my $sth;
  1345. &reverse_invoice($dbh, $form);
  1346. my %audittrail = (
  1347. tablename => 'ar',
  1348. reference => $form->{invnumber},
  1349. formname => $form->{type},
  1350. action => 'deleted',
  1351. id => $form->{id} );
  1352. $form->audittrail($dbh, "", \%audittrail);
  1353. # delete AR record
  1354. my $query = qq|DELETE FROM ar WHERE id = ?|;
  1355. $sth = $dbh->prepare($query);
  1356. $sth->execute($form->{id}) || $form->dberror($query);
  1357. # delete spool files
  1358. $query = qq|
  1359. SELECT spoolfile FROM status
  1360. WHERE trans_id = ? AND spoolfile IS NOT NULL|;
  1361. $sth = $dbh->prepare($query);
  1362. $sth->execute($form->{id}) || $form->dberror($query);
  1363. my $spoolfile;
  1364. my @spoolfiles = ();
  1365. while (($spoolfile) = $sth->fetchrow_array) {
  1366. push @spoolfiles, $spoolfile;
  1367. }
  1368. $sth->finish;
  1369. # delete status entries
  1370. $query = qq|DELETE FROM status WHERE trans_id = ?|;
  1371. $sth = $dbh->prepare($query);
  1372. $sth->execute($form->{id}) || $form->dberror($query);
  1373. my $rc = $dbh->commit;
  1374. if ($rc) {
  1375. foreach $spoolfile (@spoolfiles) {
  1376. unlink "${LedgerSMB::Sysconfig::spool}/$spoolfile"
  1377. if $spoolfile;
  1378. }
  1379. }
  1380. $rc;
  1381. }
  1382. sub retrieve_invoice {
  1383. my ($self, $myconfig, $form) = @_;
  1384. my $dbh = $form->{dbh};
  1385. my $query;
  1386. if ($form->{id}) {
  1387. # get default accounts and last invoice number
  1388. $query = qq|
  1389. SELECT value AS currencies FROM defaults
  1390. WHERE setting_key = 'curr'|;
  1391. } else {
  1392. $query = qq|
  1393. SELECT value AS currencies, current_date AS transdate
  1394. FROM defaults
  1395. WHERE setting_key = 'curr'|;
  1396. }
  1397. my $sth = $dbh->prepare($query);
  1398. $sth->execute || $form->dberror($query);
  1399. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1400. for (keys %$ref) { $form->{$_} = $ref->{$_} }
  1401. $sth->finish;
  1402. if ($form->{id}) {
  1403. # retrieve invoice
  1404. $query = qq|
  1405. SELECT a.invnumber, a.ordnumber, a.quonumber,
  1406. a.transdate, a.paid,
  1407. a.shippingpoint, a.shipvia, a.terms, a.notes,
  1408. a.intnotes,
  1409. a.duedate, a.taxincluded, a.curr AS currency,
  1410. a.employee_id, e.name AS employee, a.till,
  1411. a.customer_id,
  1412. a.language_code, a.ponumber
  1413. FROM ar a
  1414. LEFT JOIN employee e ON (e.id = a.employee_id)
  1415. WHERE a.id = ?|;
  1416. $sth = $dbh->prepare($query);
  1417. $sth->execute($form->{id}) || $form->dberror($query);
  1418. $ref = $sth->fetchrow_hashref(NAME_lc);
  1419. for (keys %$ref) { $form->{$_} = $ref->{$_} }
  1420. $sth->finish;
  1421. # get shipto
  1422. $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
  1423. $sth = $dbh->prepare($query);
  1424. $sth->execute($form->{id}) || $form->dberror($query);
  1425. $ref = $sth->fetchrow_hashref(NAME_lc);
  1426. for (keys %$ref) { $form->{$_} = $ref->{$_} }
  1427. $sth->finish;
  1428. # retrieve individual items
  1429. $query = qq|
  1430. SELECT i.description, i.qty, i.fxsellprice,
  1431. i.sellprice, i.discount, i.parts_id AS id,
  1432. i.unit, i.deliverydate, i.project_id,
  1433. pr.projectnumber, i.serialnumber, i.notes,
  1434. p.partnumber, p.assembly, p.bin,
  1435. pg.partsgroup, p.partsgroup_id,
  1436. p.partnumber AS sku, p.listprice, p.lastcost,
  1437. p.weight, p.onhand, p.inventory_accno_id,
  1438. p.income_accno_id, p.expense_accno_id,
  1439. t.description AS partsgrouptranslation
  1440. FROM invoice i
  1441. JOIN parts p ON (i.parts_id = p.id)
  1442. LEFT JOIN project pr ON (i.project_id = pr.id)
  1443. LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
  1444. LEFT JOIN translation t
  1445. ON (t.trans_id = p.partsgroup_id
  1446. AND t.language_code
  1447. = ?)
  1448. WHERE i.trans_id = ?
  1449. AND NOT i.assemblyitem = '1'
  1450. ORDER BY i.id|;
  1451. $sth = $dbh->prepare($query);
  1452. $sth->execute($form->{language_code}, $form->{id})
  1453. || $form->dberror($query);
  1454. # foreign currency
  1455. &exchangerate_defaults($dbh, $form);
  1456. # query for price matrix
  1457. my $pmh = PriceMatrix::price_matrix_query($dbh, $form);
  1458. # taxes
  1459. $query = qq|
  1460. SELECT c.accno
  1461. FROM chart c
  1462. JOIN partstax pt ON (pt.chart_id = c.id)
  1463. WHERE pt.parts_id = ?|;
  1464. my $tth = $dbh->prepare($query) || $form->dberror($query);
  1465. my $taxrate;
  1466. my $ptref;
  1467. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1468. my ($dec) = ($ref->{fxsellprice} =~ /\.(\d+)/);
  1469. $dec = length $dec;
  1470. my $decimalplaces = ($dec > 2) ? $dec : 2;
  1471. $tth->execute($ref->{id});
  1472. $ref->{taxaccounts} = "";
  1473. $taxrate = 0;
  1474. while ($ptref = $tth->fetchrow_hashref(NAME_lc)) {
  1475. $ref->{taxaccounts} .= "$ptref->{accno} ";
  1476. $taxrate += $form->{"$ptref->{accno}_rate"};
  1477. }
  1478. $tth->finish;
  1479. chop $ref->{taxaccounts};
  1480. # price matrix
  1481. $ref->{sellprice} =
  1482. ($ref->{fxsellprice}
  1483. * $form->{$form->{currency}});
  1484. PriceMatrix::price_matrix(
  1485. $pmh, $ref, $form->{transdate}, $decimalplaces,
  1486. $form, $myconfig);
  1487. $ref->{sellprice} = $ref->{fxsellprice};
  1488. $ref->{partsgroup} = $ref->{partsgrouptranslation}
  1489. if $ref->{partsgrouptranslation};
  1490. push @{ $form->{invoice_details} }, $ref;
  1491. }
  1492. $sth->finish;
  1493. }
  1494. @queries = $form->run_custom_queries('ar', 'SELECT');
  1495. my $rc = $dbh->commit;
  1496. $rc;
  1497. }
  1498. sub retrieve_item {
  1499. my ($self, $myconfig, $form) = @_;
  1500. my $dbh = $form->{dbh};
  1501. my $i = $form->{rowcount};
  1502. my $null;
  1503. my $var;
  1504. my $where = "WHERE p.obsolete = '0' AND NOT p.income_accno_id IS NULL";
  1505. if ($form->{"partnumber_$i"} ne "") {
  1506. $var = $dbh->quote($form->like(lc $form->{"partnumber_$i"}));
  1507. $where .= " AND lower(p.partnumber) LIKE $var";
  1508. }
  1509. if ($form->{"description_$i"} ne "") {
  1510. $var = $dbh->quote($form->like(lc $form->{"description_$i"}));
  1511. if ($form->{language_code} ne "") {
  1512. $where .= " AND lower(t1.description) LIKE $var";
  1513. } else {
  1514. $where .= " AND lower(p.description) LIKE $var";
  1515. }
  1516. }
  1517. if ($form->{"partsgroup_$i"} ne "") {
  1518. ($null, $var) = split /--/, $form->{"partsgroup_$i"};
  1519. $var = $dbh->quote($var);
  1520. if ($var == 0) {
  1521. # search by partsgroup, this is for the POS
  1522. $where .= qq| AND pg.partsgroup = |.
  1523. $dbh->quote($form->{"partsgroup_$i"});
  1524. } else {
  1525. $where .= qq| AND p.partsgroup_id = $var|;
  1526. }
  1527. }
  1528. if ($form->{"description_$i"} ne "") {
  1529. $where .= " ORDER BY 3";
  1530. } else {
  1531. $where .= " ORDER BY 2";
  1532. }
  1533. my $query = qq|
  1534. SELECT p.id, p.partnumber, p.description, p.sellprice,
  1535. p.listprice, p.lastcost, p.unit, p.assembly, p.bin,
  1536. p.onhand, p.notes, p.inventory_accno_id,
  1537. p.income_accno_id, p.expense_accno_id, pg.partsgroup,
  1538. p.partsgroup_id, p.partnumber AS sku, p.weight,
  1539. t1.description AS translation,
  1540. t2.description AS grouptranslation
  1541. FROM parts p
  1542. LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
  1543. LEFT JOIN translation t1
  1544. ON (t1.trans_id = p.id AND t1.language_code = ?)
  1545. LEFT JOIN translation t2
  1546. ON (t2.trans_id = p.partsgroup_id
  1547. AND t2.language_code = ?)
  1548. $where|;
  1549. my $sth = $dbh->prepare($query);
  1550. $sth->execute($form->{language_code}, $form->{language_code})
  1551. || $form->dberror($query);
  1552. my $ref;
  1553. my $ptref;
  1554. # setup exchange rates
  1555. &exchangerate_defaults($dbh, $form);
  1556. # taxes
  1557. $query = qq|
  1558. SELECT c.accno
  1559. FROM chart c
  1560. JOIN partstax pt ON (c.id = pt.chart_id)
  1561. WHERE pt.parts_id = ?|;
  1562. my $tth = $dbh->prepare($query) || $form->dberror($query);
  1563. # price matrix
  1564. my $pmh = PriceMatrix::price_matrix_query($dbh, $form);
  1565. my $transdate = $form->datetonum($myconfig, $form->{transdate});
  1566. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1567. my ($dec) = ($ref->{sellprice} =~ /\.(\d+)/);
  1568. $dec = length $dec;
  1569. my $decimalplaces = ($dec > 2) ? $dec : 2;
  1570. # get taxes for part
  1571. $tth->execute($ref->{id});
  1572. $ref->{taxaccounts} = "";
  1573. while ($ptref = $tth->fetchrow_hashref(NAME_lc)) {
  1574. $ref->{taxaccounts} .= "$ptref->{accno} ";
  1575. }
  1576. $tth->finish;
  1577. chop $ref->{taxaccounts};
  1578. # get matrix
  1579. PriceMatrix::price_matrix(
  1580. $pmh, $ref, $transdate, $decimalplaces, $form,
  1581. $myconfig);
  1582. $ref->{description} = $ref->{translation}
  1583. if $ref->{translation};
  1584. $ref->{partsgroup} = $ref->{grouptranslation}
  1585. if $ref->{grouptranslation};
  1586. push @{ $form->{item_list} }, $ref;
  1587. }
  1588. $sth->finish;
  1589. }
  1590. sub exchangerate_defaults {
  1591. my ($dbh2, $form) = @_;
  1592. $dbh = $form->{dbh};
  1593. my $var;
  1594. # get default currencies
  1595. my $query = qq|
  1596. SELECT substr(value,1,3), value FROM defaults
  1597. WHERE setting_key = 'curr'|;
  1598. my $eth = $dbh->prepare($query) || $form->dberror($query);
  1599. $eth->execute;
  1600. ($form->{defaultcurrency}, $form->{currencies}) = $eth->fetchrow_array;
  1601. $eth->finish;
  1602. $query = qq|
  1603. SELECT buy
  1604. FROM exchangerate
  1605. WHERE curr = ?
  1606. AND transdate = ?|;
  1607. my $eth1 = $dbh->prepare($query) || $form->dberror($query);
  1608. $query = qq/
  1609. SELECT max(transdate || ' ' || buy || ' ' || curr)
  1610. FROM exchangerate
  1611. WHERE curr = ?/;
  1612. my $eth2 = $dbh->prepare($query) || $form->dberror($query);
  1613. # get exchange rates for transdate or max
  1614. foreach $var (split /:/, substr($form->{currencies},4)) {
  1615. $eth1->execute($var, $form->{transdate});
  1616. ($form->{$var}) = $eth1->fetchrow_array;
  1617. if (! $form->{$var} ) {
  1618. $eth2->execute($var);
  1619. ($form->{$var}) = $eth2->fetchrow_array;
  1620. ($null, $form->{$var}) = split / /, $form->{$var};
  1621. $form->{$var} = 1 unless $form->{$var};
  1622. $eth2->finish;
  1623. }
  1624. $eth1->finish;
  1625. }
  1626. $form->{$form->{currency}} = $form->{exchangerate}
  1627. if $form->{exchangerate};
  1628. $form->{$form->{currency}} ||= 1;
  1629. $form->{$form->{defaultcurrency}} = 1;
  1630. }
  1631. 1;