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