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