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