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