summaryrefslogtreecommitdiff
path: root/LedgerSMB/IS.pm
blob: 324675a69a7d23f48a90df327ab94b2202292719 (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|;
  350. }
  351. my $query = qq|SELECT p.partnumber, p.description, p.unit, a.qty,
  352. pg.partsgroup, p.partnumber AS sku
  353. FROM assembly a
  354. JOIN parts p ON (a.parts_id = p.id)
  355. LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
  356. WHERE a.bom = '1'
  357. AND a.id = '$id'
  358. $sortorder|;
  359. my $sth = $dbh->prepare($query);
  360. $sth->execute || $form->dberror($query);
  361. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  362. for (qw(partnumber description partsgroup)) {
  363. $form->{"a_$_"} = $ref->{$_};
  364. $form->format_string("a_$_");
  365. }
  366. if ($form->{grouppartsgroup} && $ref->{partsgroup} ne $sm) {
  367. for (qw(taxrates runningnumber number sku serialnumber unit qty ship bin deliverydate projectnumber sellprice listprice netprice discount discountrate linetotal weight itemnotes)) { push(@{ $form->{$_} }, "") }
  368. $sm = ($form->{"a_partsgroup"}) ? $form->{"a_partsgroup"} : "--";
  369. push(@{ $form->{description} }, "$spacer$sm");
  370. push(@{ $form->{lineitems} }, { amount => 0, tax => 0 });
  371. }
  372. if ($form->{stagger}) {
  373. push(@{ $form->{description} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq| -- $form->{"a_partnumber"}, $form->{"a_description"}|);
  374. for (qw(taxrates runningnumber number sku serialnumber unit qty ship bin deliverydate projectnumber sellprice listprice netprice discount discountrate linetotal weight itemnotes)) { push(@{ $form->{$_} }, "") }
  375. } else {
  376. push(@{ $form->{description} }, qq|$form->{"a_description"}|);
  377. push(@{ $form->{number} }, $form->{"a_partnumber"});
  378. push(@{ $form->{sku} }, $form->{"a_partnumber"});
  379. for (qw(taxrates runningnumber ship serialnumber reqdate projectnumber sellprice listprice netprice discount discountrate linetotal weight itemnotes)) { push(@{ $form->{$_} }, "") }
  380. }
  381. push(@{ $form->{lineitems} }, { amount => 0, tax => 0 });
  382. push(@{ $form->{qty} }, $form->format_amount($myconfig, $ref->{qty} * $qty));
  383. for (qw(unit bin)) {
  384. $form->{"a_$_"} = $ref->{$_};
  385. $form->format_string("a_$_");
  386. push(@{ $form->{$_} }, $form->{"a_$_"});
  387. }
  388. }
  389. $sth->finish;
  390. $form->{stagger}--;
  391. }
  392. sub project_description {
  393. my ($self, $dbh, $id) = @_;
  394. my $query = qq|SELECT description
  395. FROM project
  396. WHERE id = $id|;
  397. ($_) = $dbh->selectrow_array($query);
  398. $_;
  399. }
  400. sub customer_details {
  401. my ($self, $myconfig, $form) = @_;
  402. # connect to database
  403. my $dbh = $form->dbconnect($myconfig);
  404. # get rest for the customer
  405. my $query = qq|SELECT customernumber, name, address1, address2, city,
  406. state, zipcode, country,
  407. contact, phone as customerphone, fax as customerfax,
  408. taxnumber AS customertaxnumber, sic_code AS sic, iban, bic,
  409. startdate, enddate
  410. FROM customer
  411. WHERE id = $form->{customer_id}|;
  412. my $sth = $dbh->prepare($query);
  413. $sth->execute || $form->dberror($query);
  414. $ref = $sth->fetchrow_hashref(NAME_lc);
  415. for (keys %$ref) { $form->{$_} = $ref->{$_} }
  416. $sth->finish;
  417. $dbh->disconnect;
  418. }
  419. sub post_invoice {
  420. my ($self, $myconfig, $form) = @_;
  421. # connect to database, turn off autocommit
  422. my $dbh = $form->dbconnect_noauto($myconfig);
  423. my $query;
  424. my $sth;
  425. my $null;
  426. my $project_id;
  427. my $exchangerate = 0;
  428. my $keepcleared = 0;
  429. %$form->{acc_trans} = ();
  430. ($null, $form->{employee_id}) = split /--/, $form->{employee};
  431. unless ($form->{employee_id}) {
  432. ($form->{employee}, $form->{employee_id}) = $form->get_employee($dbh);
  433. }
  434. ($null, $form->{department_id}) = split(/--/, $form->{department});
  435. $form->{department_id} *= 1;
  436. $query = qq|SELECT fxgain_accno_id, fxloss_accno_id
  437. FROM defaults|;
  438. my ($fxgain_accno_id, $fxloss_accno_id) = $dbh->selectrow_array($query);
  439. $query = qq|SELECT p.assembly, p.inventory_accno_id,
  440. p.income_accno_id, p.expense_accno_id, p.project_id
  441. FROM parts p
  442. WHERE p.id = ?|;
  443. my $pth = $dbh->prepare($query) || $form->dberror($query);
  444. if ($form->{id}) {
  445. $keepcleared = 1;
  446. $query = qq|SELECT id FROM ar
  447. WHERE id = $form->{id}|;
  448. if ($dbh->selectrow_array($query)) {
  449. &reverse_invoice($dbh, $form);
  450. } else {
  451. $query = qq|INSERT INTO ar (id)
  452. VALUES ($form->{id})|;
  453. $dbh->do($query) || $form->dberror($query);
  454. }
  455. }
  456. my $uid = localtime;
  457. $uid .= "$$";
  458. if (! $form->{id}) {
  459. $query = qq|INSERT INTO ar (invnumber, employee_id)
  460. VALUES ('$uid', $form->{employee_id})|;
  461. $dbh->do($query) || $form->dberror($query);
  462. $query = qq|SELECT id FROM ar
  463. WHERE invnumber = '$uid'|;
  464. $sth = $dbh->prepare($query);
  465. $sth->execute || $form->dberror($query);
  466. ($form->{id}) = $sth->fetchrow_array;
  467. $sth->finish;
  468. }
  469. if ($form->{currency} eq $form->{defaultcurrency}) {
  470. $form->{exchangerate} = 1;
  471. } else {
  472. $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'buy');
  473. }
  474. $form->{exchangerate} = ($exchangerate) ? $exchangerate : $form->parse_amount($myconfig, $form->{exchangerate});
  475. my $i;
  476. my $item;
  477. my $allocated = 0;
  478. my $taxrate;
  479. my $tax;
  480. my $fxtax;
  481. my @taxaccounts;
  482. my $amount;
  483. my $grossamount;
  484. my $invamount = 0;
  485. my $invnetamount = 0;
  486. my $diff = 0;
  487. my $ml;
  488. my $invoice_id;
  489. my $ndx;
  490. foreach $i (1 .. $form->{rowcount}) {
  491. $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
  492. if ($form->{"qty_$i"}) {
  493. $pth->execute($form->{"id_$i"});
  494. $ref = $pth->fetchrow_hashref(NAME_lc);
  495. for (keys %$ref) { $form->{"${_}_$i"} = $ref->{$_} }
  496. $pth->finish;
  497. # project
  498. $project_id = 'NULL';
  499. if ($form->{"projectnumber_$i"}) {
  500. ($null, $project_id) = split /--/, $form->{"projectnumber_$i"};
  501. }
  502. $project_id = $form->{"project_id_$i"} if $form->{"project_id_$i"};
  503. # keep entered selling price
  504. my $fxsellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
  505. my ($dec) = ($fxsellprice =~ /\.(\d+)/);
  506. $dec = length $dec;
  507. my $decimalplaces = ($dec > 2) ? $dec : 2;
  508. # undo discount formatting
  509. $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"})/100;
  510. # deduct discount
  511. $form->{"sellprice_$i"} = $fxsellprice - $form->round_amount($fxsellprice * $form->{"discount_$i"}, $decimalplaces);
  512. # linetotal
  513. my $fxlinetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
  514. $amount = $fxlinetotal * $form->{exchangerate};
  515. my $linetotal = $form->round_amount($amount, 2);
  516. $fxdiff += $amount - $linetotal;
  517. @taxaccounts = split / /, $form->{"taxaccounts_$i"};
  518. $ml = 1;
  519. $tax = 0;
  520. $fxtax = 0;
  521. for (0 .. 1) {
  522. $taxrate = 0;
  523. # add tax rates
  524. for (@taxaccounts) { $taxrate += $form->{"${_}_rate"} if ($form->{"${_}_rate"} * $ml) > 0 }
  525. if ($form->{taxincluded}) {
  526. $tax += $amount = $linetotal * ($taxrate / (1 + ($taxrate * $ml)));
  527. $form->{"sellprice_$i"} -= $amount / $form->{"qty_$i"};
  528. $fxtax += $fxlinetotal * ($taxrate / (1 + ($taxrate * $ml)));
  529. } else {
  530. $tax += $amount = $linetotal * $taxrate;
  531. $fxtax += $fxlinetotal * $taxrate;
  532. }
  533. for (@taxaccounts) {
  534. $form->{acc_trans}{$form->{id}}{$_}{amount} += $amount * $form->{"${_}_rate"} / $taxrate if ($form->{"${_}_rate"} * $ml) > 0;
  535. }
  536. $ml = -1;
  537. }
  538. $grossamount = $form->round_amount($linetotal, 2);
  539. if ($form->{taxincluded}) {
  540. $amount = $form->round_amount($tax, 2);
  541. $linetotal -= $form->round_amount($tax - $diff, 2);
  542. $diff = ($amount - $tax);
  543. }
  544. # add linetotal to income
  545. $amount = $form->round_amount($linetotal, 2);
  546. push @{ $form->{acc_trans}{lineitems} }, {
  547. chart_id => $form->{"income_accno_id_$i"},
  548. amount => $amount,
  549. fxgrossamount => $fxlinetotal + $fxtax,
  550. grossamount => $grossamount,
  551. project_id => $project_id };
  552. $ndx = $#{@{$form->{acc_trans}{lineitems}}};
  553. $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
  554. if ($form->{"inventory_accno_id_$i"} || $form->{"assembly_$i"}) {
  555. if ($form->{"assembly_$i"}) {
  556. # do not update if assembly consists of all services
  557. $query = qq|SELECT sum(p.inventory_accno_id), p.assembly
  558. FROM parts p
  559. JOIN assembly a ON (a.parts_id = p.id)
  560. WHERE a.id = $form->{"id_$i"}
  561. GROUP BY p.assembly|;
  562. $sth = $dbh->prepare($query);
  563. $sth->execute || $form->dberror($query);
  564. my ($inv, $assembly) = $sth->fetchrow_array;
  565. $sth->finish;
  566. if ($inv || $assembly) {
  567. $form->update_balance($dbh,
  568. "parts",
  569. "onhand",
  570. qq|id = $form->{"id_$i"}|,
  571. $form->{"qty_$i"} * -1) unless $form->{shipped};
  572. }
  573. &process_assembly($dbh, $form, $form->{"id_$i"}, $form->{"qty_$i"}, $project_id);
  574. } else {
  575. $form->update_balance($dbh,
  576. "parts",
  577. "onhand",
  578. qq|id = $form->{"id_$i"}|,
  579. $form->{"qty_$i"} * -1) unless $form->{shipped};
  580. $allocated = &cogs($dbh, $form, $form->{"id_$i"}, $form->{"qty_$i"}, $project_id);
  581. }
  582. }
  583. # save detail record in invoice table
  584. $query = qq|INSERT INTO invoice (description)
  585. VALUES ('$uid')|;
  586. $dbh->do($query) || $form->dberror($query);
  587. $query = qq|SELECT id FROM invoice
  588. WHERE description = '$uid'|;
  589. ($invoice_id) = $dbh->selectrow_array($query);
  590. $query = qq|UPDATE invoice SET
  591. trans_id = $form->{id},
  592. parts_id = $form->{"id_$i"},
  593. description = |.$dbh->quote($form->{"description_$i"}).qq|,
  594. qty = $form->{"qty_$i"},
  595. sellprice = $form->{"sellprice_$i"},
  596. fxsellprice = $fxsellprice,
  597. discount = $form->{"discount_$i"},
  598. allocated = $allocated,
  599. unit = |.$dbh->quote($form->{"unit_$i"}).qq|,
  600. deliverydate = |.$form->dbquote($form->{"deliverydate_$i"}, SQL_DATE).qq|,
  601. project_id = $project_id,
  602. serialnumber = |.$dbh->quote($form->{"serialnumber_$i"}).qq|,
  603. notes = |.$dbh->quote($form->{"notes_$i"}).qq|
  604. WHERE id = $invoice_id|;
  605. $dbh->do($query) || $form->dberror($query);
  606. # add invoice_id
  607. $form->{acc_trans}{lineitems}[$ndx]->{invoice_id} = $invoice_id;
  608. }
  609. }
  610. $form->{paid} = 0;
  611. for $i (1 .. $form->{paidaccounts}) {
  612. $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
  613. $form->{paid} += $form->{"paid_$i"};
  614. $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"paid_$i"});
  615. }
  616. # add lineitems + tax
  617. $amount = 0;
  618. $grossamount = 0;
  619. $fxgrossamount = 0;
  620. for (@{ $form->{acc_trans}{lineitems} }) {
  621. $amount += $_->{amount};
  622. $grossamount += $_->{grossamount};
  623. $fxgrossamount += $_->{fxgrossamount};
  624. }
  625. $invnetamount = $amount;
  626. $amount = 0;
  627. for (split / /, $form->{taxaccounts}) { $amount += $form->{acc_trans}{$form->{id}}{$_}{amount} = $form->round_amount($form->{acc_trans}{$form->{id}}{$_}{amount}, 2) }
  628. $invamount = $invnetamount + $amount;
  629. $diff = 0;
  630. if ($form->{taxincluded}) {
  631. $diff = $form->round_amount($grossamount - $invamount, 2);
  632. $invamount += $diff;
  633. }
  634. $fxdiff = $form->round_amount($fxdiff,2);
  635. $invnetamount += $fxdiff;
  636. $invamount += $fxdiff;
  637. if ($form->round_amount($form->{paid} - $fxgrossamount,2) == 0) {
  638. $form->{paid} = $invamount;
  639. } else {
  640. $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate}, 2);
  641. }
  642. foreach $ref (sort { $b->{amount} <=> $a->{amount} } @ { $form->{acc_trans}{lineitems} }) {
  643. $amount = $ref->{amount} + $diff + $fxdiff;
  644. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  645. transdate, project_id, invoice_id)
  646. VALUES ($form->{id}, $ref->{chart_id}, $amount,
  647. '$form->{transdate}', $ref->{project_id}, $ref->{invoice_id})|;
  648. $dbh->do($query) || $form->dberror($query);
  649. $diff = 0;
  650. $fxdiff = 0;
  651. }
  652. $form->{receivables} = $invamount * -1;
  653. delete $form->{acc_trans}{lineitems};
  654. # update exchangerate
  655. if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
  656. $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, $form->{exchangerate}, 0);
  657. }
  658. # record receivable
  659. if ($form->{receivables}) {
  660. ($accno) = split /--/, $form->{AR};
  661. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  662. transdate)
  663. VALUES ($form->{id},
  664. (SELECT id FROM chart
  665. WHERE accno = '$accno'),
  666. $form->{receivables}, '$form->{transdate}')|;
  667. $dbh->do($query) || $form->dberror($query);
  668. }
  669. foreach my $trans_id (keys %{$form->{acc_trans}}) {
  670. foreach my $accno (keys %{$form->{acc_trans}{$trans_id}}) {
  671. $amount = $form->round_amount($form->{acc_trans}{$trans_id}{$accno}{amount}, 2);
  672. if ($amount) {
  673. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  674. transdate)
  675. VALUES ($trans_id, (SELECT id FROM chart
  676. WHERE accno = '$accno'),
  677. $amount, '$form->{transdate}')|;
  678. $dbh->do($query) || $form->dberror($query);
  679. }
  680. }
  681. }
  682. # if there is no amount but a payment record receivable
  683. if ($invamount == 0) {
  684. $form->{receivables} = 1;
  685. }
  686. my $cleared = 0;
  687. # record payments and offsetting AR
  688. for $i (1 .. $form->{paidaccounts}) {
  689. if ($form->{"paid_$i"}) {
  690. my ($accno) = split /--/, $form->{"AR_paid_$i"};
  691. $form->{"datepaid_$i"} = $form->{transdate} unless ($form->{"datepaid_$i"});
  692. $form->{datepaid} = $form->{"datepaid_$i"};
  693. $exchangerate = 0;
  694. if ($form->{currency} eq $form->{defaultcurrency}) {
  695. $form->{"exchangerate_$i"} = 1;
  696. } else {
  697. $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
  698. $form->{"exchangerate_$i"} = ($exchangerate) ? $exchangerate : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
  699. }
  700. # record AR
  701. $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
  702. if ($form->{receivables}) {
  703. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  704. transdate)
  705. VALUES ($form->{id}, (SELECT id FROM chart
  706. WHERE accno = '$form->{AR}'),
  707. $amount, '$form->{"datepaid_$i"}')|;
  708. $dbh->do($query) || $form->dberror($query);
  709. }
  710. # record payment
  711. $amount = $form->{"paid_$i"} * -1;
  712. if ($keepcleared) {
  713. $cleared = ($form->{"cleared_$i"}) ? 1 : 0;
  714. }
  715. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
  716. source, memo, cleared)
  717. VALUES ($form->{id}, (SELECT id FROM chart
  718. WHERE accno = '$accno'),
  719. $amount, '$form->{"datepaid_$i"}', |
  720. .$dbh->quote($form->{"source_$i"}).qq|, |
  721. .$dbh->quote($form->{"memo_$i"}).qq|, '$cleared')|;
  722. $dbh->do($query) || $form->dberror($query);
  723. # exchangerate difference
  724. $amount = $form->round_amount(($form->round_amount($form->{"paid_$i"} * $form->{"exchangerate_$i"} - $form->{"paid_$i"}, 2)) * -1, 2);
  725. if ($amount) {
  726. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  727. transdate, source, fx_transaction, cleared)
  728. VALUES ($form->{id}, (SELECT id FROM chart
  729. WHERE accno = '$accno'),
  730. $amount, '$form->{"datepaid_$i"}', |
  731. .$dbh->quote($form->{"source_$i"}).qq|, '1', '$cleared')|;
  732. $dbh->do($query) || $form->dberror($query);
  733. }
  734. # gain/loss
  735. $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);
  736. if ($amount) {
  737. my $accno_id = ($amount > 0) ? $fxgain_accno_id : $fxloss_accno_id;
  738. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  739. transdate, fx_transaction, cleared)
  740. VALUES ($form->{id}, $accno_id,
  741. $amount, '$form->{"datepaid_$i"}', '1', '$cleared')|;
  742. $dbh->do($query) || $form->dberror($query);
  743. }
  744. # update exchange rate
  745. if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
  746. $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, $form->{"exchangerate_$i"}, 0);
  747. }
  748. }
  749. }
  750. # set values which could be empty to 0
  751. $form->{terms} *= 1;
  752. $form->{taxincluded} *= 1;
  753. # if this is from a till
  754. my $till = ($form->{till}) ? qq|'$form->{till}'| : "NULL";
  755. $form->{invnumber} = $form->update_defaults($myconfig, "sinumber", $dbh) unless $form->{invnumber};
  756. # save AR record
  757. $query = qq|UPDATE ar set
  758. invnumber = |.$dbh->quote($form->{invnumber}).qq|,
  759. ordnumber = |.$dbh->quote($form->{ordnumber}).qq|,
  760. quonumber = |.$dbh->quote($form->{quonumber}).qq|,
  761. transdate = '$form->{transdate}',
  762. customer_id = $form->{customer_id},
  763. amount = $invamount,
  764. netamount = $invnetamount,
  765. paid = $form->{paid},
  766. datepaid = |.$form->dbquote($form->{datepaid}, SQL_DATE).qq|,
  767. duedate = |.$form->dbquote($form->{duedate}, SQL_DATE).qq|,
  768. invoice = '1',
  769. shippingpoint = |.$dbh->quote($form->{shippingpoint}).qq|,
  770. shipvia = |.$dbh->quote($form->{shipvia}).qq|,
  771. terms = $form->{terms},
  772. notes = |.$dbh->quote($form->{notes}).qq|,
  773. intnotes = |.$dbh->quote($form->{intnotes}).qq|,
  774. taxincluded = '$form->{taxincluded}',
  775. curr = '$form->{currency}',
  776. department_id = $form->{department_id},
  777. employee_id = $form->{employee_id},
  778. till = $till,
  779. language_code = '$form->{language_code}',
  780. ponumber = |.$dbh->quote($form->{ponumber}).qq|
  781. WHERE id = $form->{id}
  782. |;
  783. $dbh->do($query) || $form->dberror($query);
  784. # add shipto
  785. $form->{name} = $form->{customer};
  786. $form->{name} =~ s/--$form->{customer_id}//;
  787. $form->add_shipto($dbh, $form->{id});
  788. # save printed, emailed and queued
  789. $form->save_status($dbh);
  790. my %audittrail = ( tablename => 'ar',
  791. reference => $form->{invnumber},
  792. formname => $form->{type},
  793. action => 'posted',
  794. id => $form->{id} );
  795. $form->audittrail($dbh, "", \%audittrail);
  796. $form->save_recurring($dbh, $myconfig);
  797. my $rc = $dbh->commit;
  798. $dbh->disconnect;
  799. $rc;
  800. }
  801. sub process_assembly {
  802. my ($dbh, $form, $id, $totalqty, $project_id) = @_;
  803. my $query = qq|SELECT a.parts_id, a.qty, p.assembly,
  804. p.partnumber, p.description, p.unit,
  805. p.inventory_accno_id, p.income_accno_id,
  806. p.expense_accno_id
  807. FROM assembly a
  808. JOIN parts p ON (a.parts_id = p.id)
  809. WHERE a.id = $id|;
  810. my $sth = $dbh->prepare($query);
  811. $sth->execute || $form->dberror($query);
  812. my $allocated;
  813. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  814. $allocated = 0;
  815. $ref->{inventory_accno_id} *= 1;
  816. $ref->{expense_accno_id} *= 1;
  817. # multiply by number of assemblies
  818. $ref->{qty} *= $totalqty;
  819. if ($ref->{assembly}) {
  820. &process_assembly($dbh, $form, $ref->{parts_id}, $ref->{qty}, $project_id);
  821. next;
  822. } else {
  823. if ($ref->{inventory_accno_id}) {
  824. $allocated = &cogs($dbh, $form, $ref->{parts_id}, $ref->{qty}, $project_id);
  825. }
  826. }
  827. # save detail record for individual assembly item in invoice table
  828. $query = qq|INSERT INTO invoice (trans_id, description, parts_id, qty,
  829. sellprice, fxsellprice, allocated, assemblyitem, unit)
  830. VALUES
  831. ($form->{id}, |
  832. .$dbh->quote($ref->{description}).qq|,
  833. $ref->{parts_id}, $ref->{qty}, 0, 0, $allocated, 't', |
  834. .$dbh->quote($ref->{unit}).qq|)|;
  835. $dbh->do($query) || $form->dberror($query);
  836. }
  837. $sth->finish;
  838. }
  839. sub cogs {
  840. my ($dbh, $form, $id, $totalqty, $project_id) = @_;
  841. my $query = qq|SELECT i.id, i.trans_id, i.qty, i.allocated, i.sellprice,
  842. i.fxsellprice, p.inventory_accno_id, p.expense_accno_id
  843. FROM invoice i, parts p
  844. WHERE i.parts_id = p.id
  845. AND i.parts_id = $id
  846. AND (i.qty + i.allocated) < 0
  847. ORDER BY trans_id|;
  848. my $sth = $dbh->prepare($query);
  849. $sth->execute || $form->dberror($query);
  850. my $allocated = 0;
  851. my $qty;
  852. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  853. if (($qty = (($ref->{qty} * -1) - $ref->{allocated})) > $totalqty) {
  854. $qty = $totalqty;
  855. }
  856. $form->update_balance($dbh,
  857. "invoice",
  858. "allocated",
  859. qq|id = $ref->{id}|,
  860. $qty);
  861. # total expenses and inventory
  862. # sellprice is the cost of the item
  863. my $linetotal = $form->round_amount($ref->{sellprice} * $qty, 2);
  864. # add expense
  865. push @{ $form->{acc_trans}{lineitems} }, {
  866. chart_id => $ref->{expense_accno_id},
  867. amount => $linetotal * -1,
  868. project_id => $project_id,
  869. invoice_id => $ref->{id} };
  870. # deduct inventory
  871. push @{ $form->{acc_trans}{lineitems} }, {
  872. chart_id => $ref->{inventory_accno_id},
  873. amount => $linetotal,
  874. project_id => $project_id,
  875. invoice_id => $ref->{id} };
  876. # add allocated
  877. $allocated += -$qty;
  878. last if (($totalqty -= $qty) <= 0);
  879. }
  880. $sth->finish;
  881. $allocated;
  882. }
  883. sub reverse_invoice {
  884. my ($dbh, $form) = @_;
  885. my $query = qq|SELECT id FROM ar
  886. WHERE id = $form->{id}|;
  887. my ($id) = $dbh->selectrow_array($query);
  888. return unless $id;
  889. # reverse inventory items
  890. my $query = qq|SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly,
  891. p.inventory_accno_id
  892. FROM invoice i
  893. JOIN parts p ON (i.parts_id = p.id)
  894. WHERE i.trans_id = $form->{id}|;
  895. my $sth = $dbh->prepare($query);
  896. $sth->execute || $form->dberror($query);
  897. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  898. if ($ref->{inventory_accno_id} || $ref->{assembly}) {
  899. # if the invoice item is not an assemblyitem adjust parts onhand
  900. if (!$ref->{assemblyitem}) {
  901. # adjust onhand in parts table
  902. $form->update_balance($dbh,
  903. "parts",
  904. "onhand",
  905. qq|id = $ref->{parts_id}|,
  906. $ref->{qty});
  907. }
  908. # loop if it is an assembly
  909. next if ($ref->{assembly});
  910. # de-allocated purchases
  911. $query = qq|SELECT id, trans_id, allocated
  912. FROM invoice
  913. WHERE parts_id = $ref->{parts_id}
  914. AND allocated > 0
  915. ORDER BY trans_id DESC|;
  916. my $sth = $dbh->prepare($query);
  917. $sth->execute || $form->dberror($query);
  918. while (my $inhref = $sth->fetchrow_hashref(NAME_lc)) {
  919. $qty = $ref->{qty};
  920. if (($ref->{qty} - $inhref->{allocated}) > 0) {
  921. $qty = $inhref->{allocated};
  922. }
  923. # update invoice
  924. $form->update_balance($dbh,
  925. "invoice",
  926. "allocated",
  927. qq|id = $inhref->{id}|,
  928. $qty * -1);
  929. last if (($ref->{qty} -= $qty) <= 0);
  930. }
  931. $sth->finish;
  932. }
  933. }
  934. $sth->finish;
  935. # delete acc_trans
  936. $query = qq|DELETE FROM acc_trans
  937. WHERE trans_id = $form->{id}|;
  938. $dbh->do($query) || $form->dberror($query);
  939. # delete invoice entries
  940. $query = qq|DELETE FROM invoice
  941. WHERE trans_id = $form->{id}|;
  942. $dbh->do($query) || $form->dberror($query);
  943. $query = qq|DELETE FROM shipto
  944. WHERE trans_id = $form->{id}|;
  945. $dbh->do($query) || $form->dberror($query);
  946. $dbh->commit;
  947. }
  948. sub delete_invoice {
  949. my ($self, $myconfig, $form, $spool) = @_;
  950. # connect to database
  951. my $dbh = $form->dbconnect_noauto($myconfig);
  952. &reverse_invoice($dbh, $form);
  953. my %audittrail = ( tablename => 'ar',
  954. reference => $form->{invnumber},
  955. formname => $form->{type},
  956. action => 'deleted',
  957. id => $form->{id} );
  958. $form->audittrail($dbh, "", \%audittrail);
  959. # delete AR record
  960. my $query = qq|DELETE FROM ar
  961. WHERE id = $form->{id}|;
  962. $dbh->do($query) || $form->dberror($query);
  963. # delete spool files
  964. $query = qq|SELECT spoolfile FROM status
  965. WHERE trans_id = $form->{id}
  966. AND spoolfile IS NOT NULL|;
  967. my $sth = $dbh->prepare($query);
  968. $sth->execute || $form->dberror($query);
  969. my $spoolfile;
  970. my @spoolfiles = ();
  971. while (($spoolfile) = $sth->fetchrow_array) {
  972. push @spoolfiles, $spoolfile;
  973. }
  974. $sth->finish;
  975. # delete status entries
  976. $query = qq|DELETE FROM status
  977. WHERE trans_id = $form->{id}|;
  978. $dbh->do($query) || $form->dberror($query);
  979. my $rc = $dbh->commit;
  980. if ($rc) {
  981. foreach $spoolfile (@spoolfiles) {
  982. unlink "$spool/$spoolfile" if $spoolfile;
  983. }
  984. }
  985. $dbh->disconnect;
  986. $rc;
  987. }
  988. sub retrieve_invoice {
  989. my ($self, $myconfig, $form) = @_;
  990. # connect to database
  991. my $dbh = $form->dbconnect_noauto($myconfig);
  992. my $query;
  993. if ($form->{id}) {
  994. # get default accounts and last invoice number
  995. $query = qq|SELECT d.curr AS currencies
  996. FROM defaults d|;
  997. } else {
  998. $query = qq|SELECT d.curr AS currencies, current_date AS transdate
  999. FROM defaults d|;
  1000. }
  1001. my $sth = $dbh->prepare($query);
  1002. $sth->execute || $form->dberror($query);
  1003. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1004. for (keys %$ref) { $form->{$_} = $ref->{$_} }
  1005. $sth->finish;
  1006. if ($form->{id}) {
  1007. # retrieve invoice
  1008. $query = qq|SELECT a.invnumber, a.ordnumber, a.quonumber,
  1009. a.transdate, a.paid,
  1010. a.shippingpoint, a.shipvia, a.terms, a.notes, a.intnotes,
  1011. a.duedate, a.taxincluded, a.curr AS currency,
  1012. a.employee_id, e.name AS employee, a.till, a.customer_id,
  1013. a.language_code, a.ponumber
  1014. FROM ar a
  1015. LEFT JOIN employee e ON (e.id = a.employee_id)
  1016. WHERE a.id = $form->{id}|;
  1017. $sth = $dbh->prepare($query);
  1018. $sth->execute || $form->dberror($query);
  1019. $ref = $sth->fetchrow_hashref(NAME_lc);
  1020. for (keys %$ref) { $form->{$_} = $ref->{$_} }
  1021. $sth->finish;
  1022. # get shipto
  1023. $query = qq|SELECT * FROM shipto
  1024. WHERE trans_id = $form->{id}|;
  1025. $sth = $dbh->prepare($query);
  1026. $sth->execute || $form->dberror($query);
  1027. $ref = $sth->fetchrow_hashref(NAME_lc);
  1028. for (keys %$ref) { $form->{$_} = $ref->{$_} }
  1029. $sth->finish;
  1030. # retrieve individual items
  1031. $query = qq|SELECT i.description, i.qty, i.fxsellprice, i.sellprice,
  1032. i.discount, i.parts_id AS id, i.unit, i.deliverydate,
  1033. i.project_id, pr.projectnumber, i.serialnumber, i.notes,
  1034. p.partnumber, p.assembly, p.bin,
  1035. pg.partsgroup, p.partsgroup_id, p.partnumber AS sku,
  1036. p.listprice, p.lastcost, p.weight, p.onhand,
  1037. p.inventory_accno_id, p.income_accno_id, p.expense_accno_id,
  1038. t.description AS partsgrouptranslation
  1039. FROM invoice i
  1040. JOIN parts p ON (i.parts_id = p.id)
  1041. LEFT JOIN project pr ON (i.project_id = pr.id)
  1042. LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
  1043. LEFT JOIN translation t ON (t.trans_id = p.partsgroup_id AND t.language_code = '$form->{language_code}')
  1044. WHERE i.trans_id = $form->{id}
  1045. AND NOT i.assemblyitem = '1'
  1046. ORDER BY i.id|;
  1047. $sth = $dbh->prepare($query);
  1048. $sth->execute || $form->dberror($query);
  1049. # foreign currency
  1050. &exchangerate_defaults($dbh, $form);
  1051. # query for price matrix
  1052. my $pmh = &price_matrix_query($dbh, $form);
  1053. # taxes
  1054. $query = qq|SELECT c.accno
  1055. FROM chart c
  1056. JOIN partstax pt ON (pt.chart_id = c.id)
  1057. WHERE pt.parts_id = ?|;
  1058. my $tth = $dbh->prepare($query) || $form->dberror($query);
  1059. my $taxrate;
  1060. my $ptref;
  1061. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1062. my ($dec) = ($ref->{fxsellprice} =~ /\.(\d+)/);
  1063. $dec = length $dec;
  1064. my $decimalplaces = ($dec > 2) ? $dec : 2;
  1065. $tth->execute($ref->{id});
  1066. $ref->{taxaccounts} = "";
  1067. $taxrate = 0;
  1068. while ($ptref = $tth->fetchrow_hashref(NAME_lc)) {
  1069. $ref->{taxaccounts} .= "$ptref->{accno} ";
  1070. $taxrate += $form->{"$ptref->{accno}_rate"};
  1071. }
  1072. $tth->finish;
  1073. chop $ref->{taxaccounts};
  1074. # price matrix
  1075. $ref->{sellprice} = ($ref->{fxsellprice} * $form->{$form->{currency}});
  1076. &price_matrix($pmh, $ref, $form->{transdate}, $decimalplaces, $form, $myconfig);
  1077. $ref->{sellprice} = $ref->{fxsellprice};
  1078. $ref->{partsgroup} = $ref->{partsgrouptranslation} if $ref->{partsgrouptranslation};
  1079. push @{ $form->{invoice_details} }, $ref;
  1080. }
  1081. $sth->finish;
  1082. }
  1083. my $rc = $dbh->commit;
  1084. $dbh->disconnect;
  1085. $rc;
  1086. }
  1087. sub retrieve_item {
  1088. my ($self, $myconfig, $form) = @_;
  1089. # connect to database
  1090. my $dbh = $form->dbconnect($myconfig);
  1091. my $i = $form->{rowcount};
  1092. my $null;
  1093. my $var;
  1094. my $where = "WHERE p.obsolete = '0' AND NOT p.income_accno_id IS NULL";
  1095. if ($form->{"partnumber_$i"} ne "") {
  1096. $var = $form->like(lc $form->{"partnumber_$i"});
  1097. $where .= " AND lower(p.partnumber) LIKE '$var'";
  1098. }
  1099. if ($form->{"description_$i"} ne "") {
  1100. $var = $form->like(lc $form->{"description_$i"});
  1101. if ($form->{language_code} ne "") {
  1102. $where .= " AND lower(t1.description) LIKE '$var'";
  1103. } else {
  1104. $where .= " AND lower(p.description) LIKE '$var'";
  1105. }
  1106. }
  1107. if ($form->{"partsgroup_$i"} ne "") {
  1108. ($null, $var) = split /--/, $form->{"partsgroup_$i"};
  1109. $var *= 1;
  1110. if ($var == 0) {
  1111. # search by partsgroup, this is for the POS
  1112. $where .= qq| AND pg.partsgroup = '$form->{"partsgroup_$i"}'|;
  1113. } else {
  1114. $where .= qq| AND p.partsgroup_id = $var|;
  1115. }
  1116. }
  1117. if ($form->{"description_$i"} ne "") {
  1118. $where .= " ORDER BY 3";
  1119. } else {
  1120. $where .= " ORDER BY 2";
  1121. }
  1122. my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
  1123. p.listprice, p.lastcost,
  1124. p.unit, p.assembly, p.bin, p.onhand, p.notes,
  1125. p.inventory_accno_id, p.income_accno_id, p.expense_accno_id,
  1126. pg.partsgroup, p.partsgroup_id, p.partnumber AS sku,
  1127. p.weight,
  1128. t1.description AS translation,
  1129. t2.description AS grouptranslation
  1130. FROM parts p
  1131. LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
  1132. LEFT JOIN translation t1 ON (t1.trans_id = p.id AND t1.language_code = '$form->{language_code}')
  1133. LEFT JOIN translation t2 ON (t2.trans_id = p.partsgroup_id AND t2.language_code = '$form->{language_code}')
  1134. $where|;
  1135. my $sth = $dbh->prepare($query);
  1136. $sth->execute || $form->dberror($query);
  1137. my $ref;
  1138. my $ptref;
  1139. # setup exchange rates
  1140. &exchangerate_defaults($dbh, $form);
  1141. # taxes
  1142. $query = qq|SELECT c.accno
  1143. FROM chart c
  1144. JOIN partstax pt ON (c.id = pt.chart_id)
  1145. WHERE pt.parts_id = ?|;
  1146. my $tth = $dbh->prepare($query) || $form->dberror($query);
  1147. # price matrix
  1148. my $pmh = &price_matrix_query($dbh, $form);
  1149. my $transdate = $form->datetonum($myconfig, $form->{transdate});
  1150. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1151. my ($dec) = ($ref->{sellprice} =~ /\.(\d+)/);
  1152. $dec = length $dec;
  1153. my $decimalplaces = ($dec > 2) ? $dec : 2;
  1154. # get taxes for part
  1155. $tth->execute($ref->{id});
  1156. $ref->{taxaccounts} = "";
  1157. while ($ptref = $tth->fetchrow_hashref(NAME_lc)) {
  1158. $ref->{taxaccounts} .= "$ptref->{accno} ";
  1159. }
  1160. $tth->finish;
  1161. chop $ref->{taxaccounts};
  1162. # get matrix
  1163. &price_matrix($pmh, $ref, $transdate, $decimalplaces, $form, $myconfig);
  1164. $ref->{description} = $ref->{translation} if $ref->{translation};
  1165. $ref->{partsgroup} = $ref->{grouptranslation} if $ref->{grouptranslation};
  1166. push @{ $form->{item_list} }, $ref;
  1167. }
  1168. $sth->finish;
  1169. $dbh->disconnect;
  1170. }
  1171. sub price_matrix_query {
  1172. my ($dbh, $form) = @_;
  1173. my $query = qq|SELECT p.id AS parts_id, 0 AS customer_id, 0 AS pricegroup_id,
  1174. 0 AS pricebreak, p.sellprice, NULL AS validfrom, NULL AS validto,
  1175. '$form->{defaultcurrency}' AS curr, '' AS pricegroup
  1176. FROM parts p
  1177. WHERE p.id = ?
  1178. UNION
  1179. SELECT p.*, g.pricegroup
  1180. FROM partscustomer p
  1181. LEFT JOIN pricegroup g ON (g.id = p.pricegroup_id)
  1182. WHERE p.parts_id = ?
  1183. AND p.customer_id = $form->{customer_id}
  1184. UNION
  1185. SELECT p.*, g.pricegroup
  1186. FROM partscustomer p
  1187. LEFT JOIN pricegroup g ON (g.id = p.pricegroup_id)
  1188. JOIN customer c ON (c.pricegroup_id = g.id)
  1189. WHERE p.parts_id = ?
  1190. AND c.id = $form->{customer_id}
  1191. UNION
  1192. SELECT p.*, '' AS pricegroup
  1193. FROM partscustomer p
  1194. WHERE p.customer_id = 0
  1195. AND p.pricegroup_id = 0
  1196. AND p.parts_id = ?
  1197. ORDER BY customer_id DESC, pricegroup_id DESC, pricebreak
  1198. |;
  1199. my $sth = $dbh->prepare($query) || $form->dberror($query);
  1200. $sth;
  1201. }
  1202. sub price_matrix {
  1203. my ($pmh, $ref, $transdate, $decimalplaces, $form, $myconfig) = @_;
  1204. $pmh->execute($ref->{id}, $ref->{id}, $ref->{id}, $ref->{id});
  1205. $ref->{pricematrix} = "";
  1206. my $customerprice;
  1207. my $pricegroupprice;
  1208. my $sellprice;
  1209. my $baseprice;
  1210. my $mref;
  1211. my %p = ();
  1212. my $i = 0;
  1213. while ($mref = $pmh->fetchrow_hashref(NAME_lc)) {
  1214. # check date
  1215. if ($mref->{validfrom}) {
  1216. next if $transdate < $form->datetonum($myconfig, $mref->{validfrom});
  1217. }
  1218. if ($mref->{validto}) {
  1219. next if $transdate > $form->datetonum($myconfig, $mref->{validto});
  1220. }
  1221. # convert price
  1222. $sellprice = $form->round_amount($mref->{sellprice} * $form->{$mref->{curr}}, $decimalplaces);
  1223. $mref->{pricebreak} *= 1;
  1224. if ($mref->{customer_id}) {
  1225. $p{$mref->{pricebreak}} = $sellprice;
  1226. $customerprice = 1;
  1227. }
  1228. if ($mref->{pricegroup_id}) {
  1229. if (!$customerprice) {
  1230. $p{$mref->{pricebreak}} = $sellprice;
  1231. $pricegroupprice = 1;
  1232. }
  1233. }
  1234. if (!$customerprice && !$pricegroupprice) {
  1235. $p{$mref->{pricebreak}} = $sellprice;
  1236. }
  1237. if (($mref->{pricebreak} + $mref->{customer_id} + $mref->{pricegroup_id}) == 0) {
  1238. $baseprice = $sellprice;
  1239. }
  1240. $i++;
  1241. }
  1242. $pmh->finish;
  1243. if (! exists $p{0}) {
  1244. $p{0} = $baseprice;
  1245. }
  1246. if ($i > 1) {
  1247. $ref->{sellprice} = $p{0};
  1248. for (sort { $a <=> $b } keys %p) { $ref->{pricematrix} .= "${_}:$p{$_} " }
  1249. } else {
  1250. $ref->{sellprice} = $form->round_amount($p{0} * (1 - $form->{tradediscount}), $decimalplaces);
  1251. $ref->{pricematrix} = "0:$ref->{sellprice} " if $ref->{sellprice};
  1252. }
  1253. chop $ref->{pricematrix};
  1254. }
  1255. sub exchangerate_defaults {
  1256. my ($dbh, $form) = @_;
  1257. my $var;
  1258. # get default currencies
  1259. my $query = qq|SELECT substr(curr,1,3), curr FROM defaults|;
  1260. my $eth = $dbh->prepare($query) || $form->dberror($query);
  1261. $eth->execute;
  1262. ($form->{defaultcurrency}, $form->{currencies}) = $eth->fetchrow_array;
  1263. $eth->finish;
  1264. $query = qq|SELECT buy
  1265. FROM exchangerate
  1266. WHERE curr = ?
  1267. AND transdate = ?|;
  1268. my $eth1 = $dbh->prepare($query) || $form->dberror($query);
  1269. $query = qq~SELECT max(transdate || ' ' || buy || ' ' || curr)
  1270. FROM exchangerate
  1271. WHERE curr = ?~;
  1272. my $eth2 = $dbh->prepare($query) || $form->dberror($query);
  1273. # get exchange rates for transdate or max
  1274. foreach $var (split /:/, substr($form->{currencies},4)) {
  1275. $eth1->execute($var, $form->{transdate});
  1276. ($form->{$var}) = $eth1->fetchrow_array;
  1277. if (! $form->{$var} ) {
  1278. $eth2->execute($var);
  1279. ($form->{$var}) = $eth2->fetchrow_array;
  1280. ($null, $form->{$var}) = split / /, $form->{$var};
  1281. $form->{$var} = 1 unless $form->{$var};
  1282. $eth2->finish;
  1283. }
  1284. $eth1->finish;
  1285. }
  1286. $form->{$form->{currency}} = $form->{exchangerate} if $form->{exchangerate};
  1287. $form->{$form->{currency}} ||= 1;
  1288. $form->{$form->{defaultcurrency}} = 1;
  1289. }
  1290. 1;