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