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