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