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