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