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