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