summaryrefslogtreecommitdiff
path: root/LedgerSMB/IS.pm
blob: a8a7f81113972ca61d96f0da908f6133305631d1 (plain)
  1. #=====================================================================
  2. # LedgerSMB
  3. # Small Medium Business Accounting software
  4. # http://www.ledgersmb.org/
  5. #
  6. # Copyright (C) 2006
  7. # This work contains copyrighted information from a number of sources all used
  8. # with permission.
  9. #
  10. # This file contains source code included with or based on SQL-Ledger which
  11. # is Copyright Dieter Simader and DWS Systems Inc. 2000-2005 and licensed
  12. # under the GNU General Public License version 2 or, at your option, any later
  13. # version. For a full list including contact information of contributors,
  14. # maintainers, and copyright holders, see the CONTRIBUTORS file.
  15. #
  16. # Original Copyright Notice from SQL-Ledger 2.6.17 (before the fork):
  17. # Copyright (C) 2000
  18. #
  19. # Author: DWS Systems Inc.
  20. # Web: http://www.sql-ledger.org
  21. #
  22. # Contributors: Jim Rawlings <jim@your-dba.com>
  23. #`
  24. #======================================================================
  25. #
  26. # This file has NOT undergone whitespace cleanup.
  27. #
  28. #======================================================================
  29. #
  30. # Inventory invoicing module
  31. #
  32. #======================================================================
  33. package IS;
  34. 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. @queries = $form->run_custom_queries('ar', 'INSERT');
  487. }
  488. if ($form->{currency} eq $form->{defaultcurrency}) {
  489. $form->{exchangerate} = 1;
  490. } else {
  491. $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'buy');
  492. }
  493. $form->{exchangerate} = ($exchangerate) ? $exchangerate : $form->parse_amount($myconfig, $form->{exchangerate});
  494. my $i;
  495. my $item;
  496. my $allocated = 0;
  497. my $taxrate;
  498. my $tax;
  499. my $fxtax;
  500. my @taxaccounts;
  501. my $amount;
  502. my $grossamount;
  503. my $invamount = 0;
  504. my $invnetamount = 0;
  505. my $diff = 0;
  506. my $ml;
  507. my $invoice_id;
  508. my $ndx;
  509. foreach $i (1 .. $form->{rowcount}) {
  510. $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
  511. if ($form->{"qty_$i"}) {
  512. $pth->execute($form->{"id_$i"});
  513. $ref = $pth->fetchrow_hashref(NAME_lc);
  514. for (keys %$ref) { $form->{"${_}_$i"} = $ref->{$_} }
  515. $pth->finish;
  516. # project
  517. $project_id = 'NULL';
  518. if ($form->{"projectnumber_$i"}) {
  519. ($null, $project_id) = split /--/, $form->{"projectnumber_$i"};
  520. }
  521. $project_id = $form->{"project_id_$i"} if $form->{"project_id_$i"};
  522. # keep entered selling price
  523. my $fxsellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
  524. my ($dec) = ($fxsellprice =~ /\.(\d+)/);
  525. $dec = length $dec;
  526. my $decimalplaces = ($dec > 2) ? $dec : 2;
  527. # undo discount formatting
  528. $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"})/100;
  529. # deduct discount
  530. $form->{"sellprice_$i"} = $fxsellprice - $form->round_amount($fxsellprice * $form->{"discount_$i"}, $decimalplaces);
  531. # linetotal
  532. my $fxlinetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
  533. $amount = $fxlinetotal * $form->{exchangerate};
  534. my $linetotal = $form->round_amount($amount, 2);
  535. $fxdiff += $amount - $linetotal;
  536. @taxaccounts = split / /, $form->{"taxaccounts_$i"};
  537. $ml = 1;
  538. $tax = 0;
  539. $fxtax = 0;
  540. for (0 .. 1) {
  541. $taxrate = 0;
  542. # add tax rates
  543. for (@taxaccounts) { $taxrate += $form->{"${_}_rate"} if ($form->{"${_}_rate"} * $ml) > 0 }
  544. if ($form->{taxincluded}) {
  545. $tax += $amount = $linetotal * ($taxrate / (1 + ($taxrate * $ml)));
  546. $form->{"sellprice_$i"} -= $amount / $form->{"qty_$i"};
  547. $fxtax += $fxlinetotal * ($taxrate / (1 + ($taxrate * $ml)));
  548. } else {
  549. $tax += $amount = $linetotal * $taxrate;
  550. $fxtax += $fxlinetotal * $taxrate;
  551. }
  552. for (@taxaccounts) {
  553. $form->{acc_trans}{$form->{id}}{$_}{amount} += $amount * $form->{"${_}_rate"} / $taxrate if ($form->{"${_}_rate"} * $ml) > 0;
  554. }
  555. $ml = -1;
  556. }
  557. $grossamount = $form->round_amount($linetotal, 2);
  558. if ($form->{taxincluded}) {
  559. $amount = $form->round_amount($tax, 2);
  560. $linetotal -= $form->round_amount($tax - $diff, 2);
  561. $diff = ($amount - $tax);
  562. }
  563. # add linetotal to income
  564. $amount = $form->round_amount($linetotal, 2);
  565. push @{ $form->{acc_trans}{lineitems} }, {
  566. chart_id => $form->{"income_accno_id_$i"},
  567. amount => $amount,
  568. fxgrossamount => $fxlinetotal + $fxtax,
  569. grossamount => $grossamount,
  570. project_id => $project_id };
  571. $ndx = $#{@{$form->{acc_trans}{lineitems}}};
  572. $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
  573. if ($form->{"inventory_accno_id_$i"} || $form->{"assembly_$i"}) {
  574. if ($form->{"assembly_$i"}) {
  575. # do not update if assembly consists of all services
  576. $query = qq|SELECT sum(p.inventory_accno_id), p.assembly
  577. FROM parts p
  578. JOIN assembly a ON (a.parts_id = p.id)
  579. WHERE a.id = $form->{"id_$i"}
  580. GROUP BY p.assembly|;
  581. $sth = $dbh->prepare($query);
  582. $sth->execute || $form->dberror($query);
  583. my ($inv, $assembly) = $sth->fetchrow_array;
  584. $sth->finish;
  585. if ($inv || $assembly) {
  586. $form->update_balance($dbh,
  587. "parts",
  588. "onhand",
  589. qq|id = $form->{"id_$i"}|,
  590. $form->{"qty_$i"} * -1) unless $form->{shipped};
  591. }
  592. &process_assembly($dbh, $form, $form->{"id_$i"}, $form->{"qty_$i"}, $project_id);
  593. } else {
  594. $form->update_balance($dbh,
  595. "parts",
  596. "onhand",
  597. qq|id = $form->{"id_$i"}|,
  598. $form->{"qty_$i"} * -1) unless $form->{shipped};
  599. $allocated = &cogs($dbh, $form, $form->{"id_$i"}, $form->{"qty_$i"}, $project_id);
  600. }
  601. }
  602. # save detail record in invoice table
  603. $query = qq|INSERT INTO invoice (description)
  604. VALUES ('$uid')|;
  605. $dbh->do($query) || $form->dberror($query);
  606. $query = qq|SELECT id FROM invoice
  607. WHERE description = '$uid'|;
  608. ($invoice_id) = $dbh->selectrow_array($query);
  609. $query = qq|UPDATE invoice SET
  610. trans_id = $form->{id},
  611. parts_id = $form->{"id_$i"},
  612. description = |.$dbh->quote($form->{"description_$i"}).qq|,
  613. qty = $form->{"qty_$i"},
  614. sellprice = $form->{"sellprice_$i"},
  615. fxsellprice = $fxsellprice,
  616. discount = $form->{"discount_$i"},
  617. allocated = $allocated,
  618. unit = |.$dbh->quote($form->{"unit_$i"}).qq|,
  619. deliverydate = |.$form->dbquote($form->{"deliverydate_$i"}, SQL_DATE).qq|,
  620. project_id = $project_id,
  621. serialnumber = |.$dbh->quote($form->{"serialnumber_$i"}).qq|,
  622. notes = |.$dbh->quote($form->{"notes_$i"}).qq|
  623. WHERE id = $invoice_id|;
  624. $dbh->do($query) || $form->dberror($query);
  625. # add invoice_id
  626. $form->{acc_trans}{lineitems}[$ndx]->{invoice_id} = $invoice_id;
  627. }
  628. }
  629. $form->{paid} = 0;
  630. for $i (1 .. $form->{paidaccounts}) {
  631. $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
  632. $form->{paid} += $form->{"paid_$i"};
  633. $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"paid_$i"});
  634. }
  635. # add lineitems + tax
  636. $amount = 0;
  637. $grossamount = 0;
  638. $fxgrossamount = 0;
  639. for (@{ $form->{acc_trans}{lineitems} }) {
  640. $amount += $_->{amount};
  641. $grossamount += $_->{grossamount};
  642. $fxgrossamount += $_->{fxgrossamount};
  643. }
  644. $invnetamount = $amount;
  645. $amount = 0;
  646. for (split / /, $form->{taxaccounts}) { $amount += $form->{acc_trans}{$form->{id}}{$_}{amount} = $form->round_amount($form->{acc_trans}{$form->{id}}{$_}{amount}, 2) }
  647. $invamount = $invnetamount + $amount;
  648. $diff = 0;
  649. if ($form->{taxincluded}) {
  650. $diff = $form->round_amount($grossamount - $invamount, 2);
  651. $invamount += $diff;
  652. }
  653. $fxdiff = $form->round_amount($fxdiff,2);
  654. $invnetamount += $fxdiff;
  655. $invamount += $fxdiff;
  656. if ($form->round_amount($form->{paid} - $fxgrossamount,2) == 0) {
  657. $form->{paid} = $invamount;
  658. } else {
  659. $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate}, 2);
  660. }
  661. foreach $ref (sort { $b->{amount} <=> $a->{amount} } @ { $form->{acc_trans}{lineitems} }) {
  662. $amount = $ref->{amount} + $diff + $fxdiff;
  663. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  664. transdate, project_id, invoice_id)
  665. VALUES ($form->{id}, $ref->{chart_id}, $amount,
  666. '$form->{transdate}', $ref->{project_id}, $ref->{invoice_id})|;
  667. $dbh->do($query) || $form->dberror($query);
  668. $diff = 0;
  669. $fxdiff = 0;
  670. }
  671. $form->{receivables} = $invamount * -1;
  672. delete $form->{acc_trans}{lineitems};
  673. # update exchangerate
  674. if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
  675. $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, $form->{exchangerate}, 0);
  676. }
  677. # record receivable
  678. if ($form->{receivables}) {
  679. ($accno) = split /--/, $form->{AR};
  680. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  681. transdate)
  682. VALUES ($form->{id},
  683. (SELECT id FROM chart
  684. WHERE accno = '$accno'),
  685. $form->{receivables}, '$form->{transdate}')|;
  686. $dbh->do($query) || $form->dberror($query);
  687. }
  688. foreach my $trans_id (keys %{$form->{acc_trans}}) {
  689. foreach my $accno (keys %{$form->{acc_trans}{$trans_id}}) {
  690. $amount = $form->round_amount($form->{acc_trans}{$trans_id}{$accno}{amount}, 2);
  691. if ($amount) {
  692. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  693. transdate)
  694. VALUES ($trans_id, (SELECT id FROM chart
  695. WHERE accno = '$accno'),
  696. $amount, '$form->{transdate}')|;
  697. $dbh->do($query) || $form->dberror($query);
  698. }
  699. }
  700. }
  701. # if there is no amount but a payment record receivable
  702. if ($invamount == 0) {
  703. $form->{receivables} = 1;
  704. }
  705. my $cleared = 0;
  706. # record payments and offsetting AR
  707. for $i (1 .. $form->{paidaccounts}) {
  708. if ($form->{"paid_$i"}) {
  709. my ($accno) = split /--/, $form->{"AR_paid_$i"};
  710. $form->{"datepaid_$i"} = $form->{transdate} unless ($form->{"datepaid_$i"});
  711. $form->{datepaid} = $form->{"datepaid_$i"};
  712. $exchangerate = 0;
  713. if ($form->{currency} eq $form->{defaultcurrency}) {
  714. $form->{"exchangerate_$i"} = 1;
  715. } else {
  716. $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
  717. $form->{"exchangerate_$i"} = ($exchangerate) ? $exchangerate : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
  718. }
  719. # record AR
  720. $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
  721. if ($form->{receivables}) {
  722. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  723. transdate)
  724. VALUES ($form->{id}, (SELECT id FROM chart
  725. WHERE accno = '$form->{AR}'),
  726. $amount, '$form->{"datepaid_$i"}')|;
  727. $dbh->do($query) || $form->dberror($query);
  728. }
  729. # record payment
  730. $amount = $form->{"paid_$i"} * -1;
  731. if ($keepcleared) {
  732. $cleared = ($form->{"cleared_$i"}) ? 1 : 0;
  733. }
  734. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
  735. source, memo, cleared)
  736. VALUES ($form->{id}, (SELECT id FROM chart
  737. WHERE accno = '$accno'),
  738. $amount, '$form->{"datepaid_$i"}', |
  739. .$dbh->quote($form->{"source_$i"}).qq|, |
  740. .$dbh->quote($form->{"memo_$i"}).qq|, '$cleared')|;
  741. $dbh->do($query) || $form->dberror($query);
  742. # exchangerate difference
  743. $amount = $form->round_amount(($form->round_amount($form->{"paid_$i"} * $form->{"exchangerate_$i"} - $form->{"paid_$i"}, 2)) * -1, 2);
  744. if ($amount) {
  745. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  746. transdate, source, fx_transaction, cleared)
  747. VALUES ($form->{id}, (SELECT id FROM chart
  748. WHERE accno = '$accno'),
  749. $amount, '$form->{"datepaid_$i"}', |
  750. .$dbh->quote($form->{"source_$i"}).qq|, '1', '$cleared')|;
  751. $dbh->do($query) || $form->dberror($query);
  752. }
  753. # gain/loss
  754. $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);
  755. if ($amount) {
  756. my $accno_id = ($amount > 0) ? $fxgain_accno_id : $fxloss_accno_id;
  757. $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
  758. transdate, fx_transaction, cleared)
  759. VALUES ($form->{id}, $accno_id,
  760. $amount, '$form->{"datepaid_$i"}', '1', '$cleared')|;
  761. $dbh->do($query) || $form->dberror($query);
  762. }
  763. # update exchange rate
  764. if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
  765. $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, $form->{"exchangerate_$i"}, 0);
  766. }
  767. }
  768. }
  769. # set values which could be empty to 0
  770. $form->{terms} *= 1;
  771. $form->{taxincluded} *= 1;
  772. # if this is from a till
  773. my $till = ($form->{till}) ? qq|'$form->{till}'| : "NULL";
  774. $form->{invnumber} = $form->update_defaults($myconfig, "sinumber", $dbh) unless $form->{invnumber};
  775. # save AR record
  776. $query = qq|UPDATE ar set
  777. invnumber = |.$dbh->quote($form->{invnumber}).qq|,
  778. ordnumber = |.$dbh->quote($form->{ordnumber}).qq|,
  779. quonumber = |.$dbh->quote($form->{quonumber}).qq|,
  780. transdate = '$form->{transdate}',
  781. customer_id = $form->{customer_id},
  782. amount = $invamount,
  783. netamount = $invnetamount,
  784. paid = $form->{paid},
  785. datepaid = |.$form->dbquote($form->{datepaid}, SQL_DATE).qq|,
  786. duedate = |.$form->dbquote($form->{duedate}, SQL_DATE).qq|,
  787. invoice = '1',
  788. shippingpoint = |.$dbh->quote($form->{shippingpoint}).qq|,
  789. shipvia = |.$dbh->quote($form->{shipvia}).qq|,
  790. terms = $form->{terms},
  791. notes = |.$dbh->quote($form->{notes}).qq|,
  792. intnotes = |.$dbh->quote($form->{intnotes}).qq|,
  793. taxincluded = '$form->{taxincluded}',
  794. curr = '$form->{currency}',
  795. department_id = $form->{department_id},
  796. employee_id = $form->{employee_id},
  797. till = $till,
  798. language_code = '$form->{language_code}',
  799. ponumber = |.$dbh->quote($form->{ponumber}).qq|
  800. WHERE id = $form->{id}
  801. |;
  802. $dbh->do($query) || $form->dberror($query);
  803. # add shipto
  804. $form->{name} = $form->{customer};
  805. $form->{name} =~ s/--$form->{customer_id}//;
  806. $form->add_shipto($dbh, $form->{id});
  807. # save printed, emailed and queued
  808. $form->save_status($dbh);
  809. my %audittrail = ( tablename => 'ar',
  810. reference => $form->{invnumber},
  811. formname => $form->{type},
  812. action => 'posted',
  813. id => $form->{id} );
  814. $form->audittrail($dbh, "", \%audittrail);
  815. $form->save_recurring($dbh, $myconfig);
  816. my $rc = $dbh->commit;
  817. $dbh->disconnect;
  818. $rc;
  819. }
  820. sub process_assembly {
  821. my ($dbh, $form, $id, $totalqty, $project_id) = @_;
  822. my $query = qq|SELECT a.parts_id, a.qty, p.assembly,
  823. p.partnumber, p.description, p.unit,
  824. p.inventory_accno_id, p.income_accno_id,
  825. p.expense_accno_id
  826. FROM assembly a
  827. JOIN parts p ON (a.parts_id = p.id)
  828. WHERE a.id = $id|;
  829. my $sth = $dbh->prepare($query);
  830. $sth->execute || $form->dberror($query);
  831. my $allocated;
  832. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  833. $allocated = 0;
  834. $ref->{inventory_accno_id} *= 1;
  835. $ref->{expense_accno_id} *= 1;
  836. # multiply by number of assemblies
  837. $ref->{qty} *= $totalqty;
  838. if ($ref->{assembly}) {
  839. &process_assembly($dbh, $form, $ref->{parts_id}, $ref->{qty}, $project_id);
  840. next;
  841. } else {
  842. if ($ref->{inventory_accno_id}) {
  843. $allocated = &cogs($dbh, $form, $ref->{parts_id}, $ref->{qty}, $project_id);
  844. }
  845. }
  846. # save detail record for individual assembly item in invoice table
  847. $query = qq|INSERT INTO invoice (trans_id, description, parts_id, qty,
  848. sellprice, fxsellprice, allocated, assemblyitem, unit)
  849. VALUES
  850. ($form->{id}, |
  851. .$dbh->quote($ref->{description}).qq|,
  852. $ref->{parts_id}, $ref->{qty}, 0, 0, $allocated, 't', |
  853. .$dbh->quote($ref->{unit}).qq|)|;
  854. $dbh->do($query) || $form->dberror($query);
  855. }
  856. $sth->finish;
  857. }
  858. sub cogs {
  859. my ($dbh, $form, $id, $totalqty, $project_id) = @_;
  860. my $query = qq|SELECT i.id, i.trans_id, i.qty, i.allocated, i.sellprice,
  861. i.fxsellprice, p.inventory_accno_id, p.expense_accno_id
  862. FROM invoice i, parts p
  863. WHERE i.parts_id = p.id
  864. AND i.parts_id = $id
  865. AND (i.qty + i.allocated) < 0
  866. ORDER BY trans_id|;
  867. my $sth = $dbh->prepare($query);
  868. $sth->execute || $form->dberror($query);
  869. my $allocated = 0;
  870. my $qty;
  871. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  872. if (($qty = (($ref->{qty} * -1) - $ref->{allocated})) > $totalqty) {
  873. $qty = $totalqty;
  874. }
  875. $form->update_balance($dbh,
  876. "invoice",
  877. "allocated",
  878. qq|id = $ref->{id}|,
  879. $qty);
  880. # total expenses and inventory
  881. # sellprice is the cost of the item
  882. my $linetotal = $form->round_amount($ref->{sellprice} * $qty, 2);
  883. # add expense
  884. push @{ $form->{acc_trans}{lineitems} }, {
  885. chart_id => $ref->{expense_accno_id},
  886. amount => $linetotal * -1,
  887. project_id => $project_id,
  888. invoice_id => $ref->{id} };
  889. # deduct inventory
  890. push @{ $form->{acc_trans}{lineitems} }, {
  891. chart_id => $ref->{inventory_accno_id},
  892. amount => $linetotal,
  893. project_id => $project_id,
  894. invoice_id => $ref->{id} };
  895. # add allocated
  896. $allocated += -$qty;
  897. last if (($totalqty -= $qty) <= 0);
  898. }
  899. $sth->finish;
  900. $allocated;
  901. }
  902. sub reverse_invoice {
  903. my ($dbh, $form) = @_;
  904. my $query = qq|SELECT id FROM ar
  905. WHERE id = $form->{id}|;
  906. my ($id) = $dbh->selectrow_array($query);
  907. return unless $id;
  908. # reverse inventory items
  909. my $query = qq|SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly,
  910. p.inventory_accno_id
  911. FROM invoice i
  912. JOIN parts p ON (i.parts_id = p.id)
  913. WHERE i.trans_id = $form->{id}|;
  914. my $sth = $dbh->prepare($query);
  915. $sth->execute || $form->dberror($query);
  916. while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
  917. if ($ref->{inventory_accno_id} || $ref->{assembly}) {
  918. # if the invoice item is not an assemblyitem adjust parts onhand
  919. if (!$ref->{assemblyitem}) {
  920. # adjust onhand in parts table
  921. $form->update_balance($dbh,
  922. "parts",
  923. "onhand",
  924. qq|id = $ref->{parts_id}|,
  925. $ref->{qty});
  926. }
  927. # loop if it is an assembly
  928. next if ($ref->{assembly});
  929. # de-allocated purchases
  930. $query = qq|SELECT id, trans_id, allocated
  931. FROM invoice
  932. WHERE parts_id = $ref->{parts_id}
  933. AND allocated > 0
  934. ORDER BY trans_id DESC|;
  935. my $sth = $dbh->prepare($query);
  936. $sth->execute || $form->dberror($query);
  937. while (my $inhref = $sth->fetchrow_hashref(NAME_lc)) {
  938. $qty = $ref->{qty};
  939. if (($ref->{qty} - $inhref->{allocated}) > 0) {
  940. $qty = $inhref->{allocated};
  941. }
  942. # update invoice
  943. $form->update_balance($dbh,
  944. "invoice",
  945. "allocated",
  946. qq|id = $inhref->{id}|,
  947. $qty * -1);
  948. last if (($ref->{qty} -= $qty) <= 0);
  949. }
  950. $sth->finish;
  951. }
  952. }
  953. $sth->finish;
  954. # delete acc_trans
  955. $query = qq|DELETE FROM acc_trans
  956. WHERE trans_id = $form->{id}|;
  957. $dbh->do($query) || $form->dberror($query);
  958. # delete invoice entries
  959. $query = qq|DELETE FROM invoice
  960. WHERE trans_id = $form->{id}|;
  961. $dbh->do($query) || $form->dberror($query);
  962. $query = qq|DELETE FROM shipto
  963. WHERE trans_id = $form->{id}|;
  964. $dbh->do($query) || $form->dberror($query);
  965. $dbh->commit;
  966. }
  967. sub delete_invoice {
  968. my ($self, $myconfig, $form, $spool) = @_;
  969. # connect to database
  970. my $dbh = $form->dbconnect_noauto($myconfig);
  971. &reverse_invoice($dbh, $form);
  972. my %audittrail = ( tablename => 'ar',
  973. reference => $form->{invnumber},
  974. formname => $form->{type},
  975. action => 'deleted',
  976. id => $form->{id} );
  977. $form->audittrail($dbh, "", \%audittrail);
  978. # delete AR record
  979. my $query = qq|DELETE FROM ar
  980. WHERE id = $form->{id}|;
  981. $dbh->do($query) || $form->dberror($query);
  982. # delete spool files
  983. $query = qq|SELECT spoolfile FROM status
  984. WHERE trans_id = $form->{id}
  985. AND spoolfile IS NOT NULL|;
  986. my $sth = $dbh->prepare($query);
  987. $sth->execute || $form->dberror($query);
  988. my $spoolfile;
  989. my @spoolfiles = ();
  990. while (($spoolfile) = $sth->fetchrow_array) {
  991. push @spoolfiles, $spoolfile;
  992. }
  993. $sth->finish;
  994. # delete status entries
  995. $query = qq|DELETE FROM status
  996. WHERE trans_id = $form->{id}|;
  997. $dbh->do($query) || $form->dberror($query);
  998. my $rc = $dbh->commit;
  999. if ($rc) {
  1000. foreach $spoolfile (@spoolfiles) {
  1001. unlink "$spool/$spoolfile" if $spoolfile;
  1002. }
  1003. }
  1004. $dbh->disconnect;
  1005. $rc;
  1006. }
  1007. sub retrieve_invoice {
  1008. my ($self, $myconfig, $form) = @_;
  1009. # connect to database
  1010. my $dbh = $form->dbconnect_noauto($myconfig);
  1011. my $query;
  1012. if ($form->{id}) {
  1013. # get default accounts and last invoice number
  1014. $query = qq|SELECT d.curr AS currencies
  1015. FROM defaults d|;
  1016. } else {
  1017. $query = qq|SELECT d.curr AS currencies, current_date AS transdate
  1018. FROM defaults d|;
  1019. }
  1020. my $sth = $dbh->prepare($query);
  1021. $sth->execute || $form->dberror($query);
  1022. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1023. for (keys %$ref) { $form->{$_} = $ref->{$_} }
  1024. $sth->finish;
  1025. if ($form->{id}) {
  1026. # retrieve invoice
  1027. $query = qq|SELECT a.invnumber, a.ordnumber, a.quonumber,
  1028. a.transdate, a.paid,
  1029. a.shippingpoint, a.shipvia, a.terms, a.notes, a.intnotes,
  1030. a.duedate, a.taxincluded, a.curr AS currency,
  1031. a.employee_id, e.name AS employee, a.till, a.customer_id,
  1032. a.language_code, a.ponumber
  1033. FROM ar a
  1034. LEFT JOIN employee e ON (e.id = a.employee_id)
  1035. WHERE a.id = $form->{id}|;
  1036. $sth = $dbh->prepare($query);
  1037. $sth->execute || $form->dberror($query);
  1038. $ref = $sth->fetchrow_hashref(NAME_lc);
  1039. for (keys %$ref) { $form->{$_} = $ref->{$_} }
  1040. $sth->finish;
  1041. # get shipto
  1042. $query = qq|SELECT * FROM shipto
  1043. WHERE trans_id = $form->{id}|;
  1044. $sth = $dbh->prepare($query);
  1045. $sth->execute || $form->dberror($query);
  1046. $ref = $sth->fetchrow_hashref(NAME_lc);
  1047. for (keys %$ref) { $form->{$_} = $ref->{$_} }
  1048. $sth->finish;
  1049. # retrieve individual items
  1050. $query = qq|SELECT i.description, i.qty, i.fxsellprice, i.sellprice,
  1051. i.discount, i.parts_id AS id, i.unit, i.deliverydate,
  1052. i.project_id, pr.projectnumber, i.serialnumber, i.notes,
  1053. p.partnumber, p.assembly, p.bin,
  1054. pg.partsgroup, p.partsgroup_id, p.partnumber AS sku,
  1055. p.listprice, p.lastcost, p.weight, p.onhand,
  1056. p.inventory_accno_id, p.income_accno_id, p.expense_accno_id,
  1057. t.description AS partsgrouptranslation
  1058. FROM invoice i
  1059. JOIN parts p ON (i.parts_id = p.id)
  1060. LEFT JOIN project pr ON (i.project_id = pr.id)
  1061. LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
  1062. LEFT JOIN translation t ON (t.trans_id = p.partsgroup_id AND t.language_code = '$form->{language_code}')
  1063. WHERE i.trans_id = $form->{id}
  1064. AND NOT i.assemblyitem = '1'
  1065. ORDER BY i.id|;
  1066. $sth = $dbh->prepare($query);
  1067. $sth->execute || $form->dberror($query);
  1068. # foreign currency
  1069. &exchangerate_defaults($dbh, $form);
  1070. # query for price matrix
  1071. my $pmh = &price_matrix_query($dbh, $form);
  1072. # taxes
  1073. $query = qq|SELECT c.accno
  1074. FROM chart c
  1075. JOIN partstax pt ON (pt.chart_id = c.id)
  1076. WHERE pt.parts_id = ?|;
  1077. my $tth = $dbh->prepare($query) || $form->dberror($query);
  1078. my $taxrate;
  1079. my $ptref;
  1080. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1081. my ($dec) = ($ref->{fxsellprice} =~ /\.(\d+)/);
  1082. $dec = length $dec;
  1083. my $decimalplaces = ($dec > 2) ? $dec : 2;
  1084. $tth->execute($ref->{id});
  1085. $ref->{taxaccounts} = "";
  1086. $taxrate = 0;
  1087. while ($ptref = $tth->fetchrow_hashref(NAME_lc)) {
  1088. $ref->{taxaccounts} .= "$ptref->{accno} ";
  1089. $taxrate += $form->{"$ptref->{accno}_rate"};
  1090. }
  1091. $tth->finish;
  1092. chop $ref->{taxaccounts};
  1093. # price matrix
  1094. $ref->{sellprice} = ($ref->{fxsellprice} * $form->{$form->{currency}});
  1095. &price_matrix($pmh, $ref, $form->{transdate}, $decimalplaces, $form, $myconfig);
  1096. $ref->{sellprice} = $ref->{fxsellprice};
  1097. $ref->{partsgroup} = $ref->{partsgrouptranslation} if $ref->{partsgrouptranslation};
  1098. push @{ $form->{invoice_details} }, $ref;
  1099. }
  1100. $sth->finish;
  1101. }
  1102. my $rc = $dbh->commit;
  1103. $dbh->disconnect;
  1104. @queries = $form->run_custom_queries('ar', 'SELECT');
  1105. $form->{dbh}->commit;
  1106. $rc;
  1107. }
  1108. sub retrieve_item {
  1109. my ($self, $myconfig, $form) = @_;
  1110. # connect to database
  1111. my $dbh = $form->dbconnect($myconfig);
  1112. my $i = $form->{rowcount};
  1113. my $null;
  1114. my $var;
  1115. my $where = "WHERE p.obsolete = '0' AND NOT p.income_accno_id IS NULL";
  1116. if ($form->{"partnumber_$i"} ne "") {
  1117. $var = $form->like(lc $form->{"partnumber_$i"});
  1118. $where .= " AND lower(p.partnumber) LIKE '$var'";
  1119. }
  1120. if ($form->{"description_$i"} ne "") {
  1121. $var = $form->like(lc $form->{"description_$i"});
  1122. if ($form->{language_code} ne "") {
  1123. $where .= " AND lower(t1.description) LIKE '$var'";
  1124. } else {
  1125. $where .= " AND lower(p.description) LIKE '$var'";
  1126. }
  1127. }
  1128. if ($form->{"partsgroup_$i"} ne "") {
  1129. ($null, $var) = split /--/, $form->{"partsgroup_$i"};
  1130. $var *= 1;
  1131. if ($var == 0) {
  1132. # search by partsgroup, this is for the POS
  1133. $where .= qq| AND pg.partsgroup = '$form->{"partsgroup_$i"}'|;
  1134. } else {
  1135. $where .= qq| AND p.partsgroup_id = $var|;
  1136. }
  1137. }
  1138. if ($form->{"description_$i"} ne "") {
  1139. $where .= " ORDER BY 3";
  1140. } else {
  1141. $where .= " ORDER BY 2";
  1142. }
  1143. my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
  1144. p.listprice, p.lastcost,
  1145. p.unit, p.assembly, p.bin, p.onhand, p.notes,
  1146. p.inventory_accno_id, p.income_accno_id, p.expense_accno_id,
  1147. pg.partsgroup, p.partsgroup_id, p.partnumber AS sku,
  1148. p.weight,
  1149. t1.description AS translation,
  1150. t2.description AS grouptranslation
  1151. FROM parts p
  1152. LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
  1153. LEFT JOIN translation t1 ON (t1.trans_id = p.id AND t1.language_code = '$form->{language_code}')
  1154. LEFT JOIN translation t2 ON (t2.trans_id = p.partsgroup_id AND t2.language_code = '$form->{language_code}')
  1155. $where|;
  1156. my $sth = $dbh->prepare($query);
  1157. $sth->execute || $form->dberror($query);
  1158. my $ref;
  1159. my $ptref;
  1160. # setup exchange rates
  1161. &exchangerate_defaults($dbh, $form);
  1162. # taxes
  1163. $query = qq|SELECT c.accno
  1164. FROM chart c
  1165. JOIN partstax pt ON (c.id = pt.chart_id)
  1166. WHERE pt.parts_id = ?|;
  1167. my $tth = $dbh->prepare($query) || $form->dberror($query);
  1168. # price matrix
  1169. my $pmh = &price_matrix_query($dbh, $form);
  1170. my $transdate = $form->datetonum($myconfig, $form->{transdate});
  1171. while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
  1172. my ($dec) = ($ref->{sellprice} =~ /\.(\d+)/);
  1173. $dec = length $dec;
  1174. my $decimalplaces = ($dec > 2) ? $dec : 2;
  1175. # get taxes for part
  1176. $tth->execute($ref->{id});
  1177. $ref->{taxaccounts} = "";
  1178. while ($ptref = $tth->fetchrow_hashref(NAME_lc)) {
  1179. $ref->{taxaccounts} .= "$ptref->{accno} ";
  1180. }
  1181. $tth->finish;
  1182. chop $ref->{taxaccounts};
  1183. # get matrix
  1184. &price_matrix($pmh, $ref, $transdate, $decimalplaces, $form, $myconfig);
  1185. $ref->{description} = $ref->{translation} if $ref->{translation};
  1186. $ref->{partsgroup} = $ref->{grouptranslation} if $ref->{grouptranslation};
  1187. push @{ $form->{item_list} }, $ref;
  1188. }
  1189. $sth->finish;
  1190. $dbh->disconnect;
  1191. }
  1192. sub price_matrix_query {
  1193. my ($dbh, $form) = @_;
  1194. my $query = qq|SELECT p.id AS parts_id, 0 AS customer_id, 0 AS pricegroup_id,
  1195. 0 AS pricebreak, p.sellprice, NULL AS validfrom, NULL AS validto,
  1196. '$form->{defaultcurrency}' AS curr, '' AS pricegroup
  1197. FROM parts p
  1198. WHERE p.id = ?
  1199. UNION
  1200. SELECT p.*, g.pricegroup
  1201. FROM partscustomer p
  1202. LEFT JOIN pricegroup g ON (g.id = p.pricegroup_id)
  1203. WHERE p.parts_id = ?
  1204. AND p.customer_id = $form->{customer_id}
  1205. UNION
  1206. SELECT p.*, g.pricegroup
  1207. FROM partscustomer p
  1208. LEFT JOIN pricegroup g ON (g.id = p.pricegroup_id)
  1209. JOIN customer c ON (c.pricegroup_id = g.id)
  1210. WHERE p.parts_id = ?
  1211. AND c.id = $form->{customer_id}
  1212. UNION
  1213. SELECT p.*, '' AS pricegroup
  1214. FROM partscustomer p
  1215. WHERE p.customer_id = 0
  1216. AND p.pricegroup_id = 0
  1217. AND p.parts_id = ?
  1218. ORDER BY customer_id DESC, pricegroup_id DESC, pricebreak
  1219. |;
  1220. my $sth = $dbh->prepare($query) || $form->dberror($query);
  1221. $sth;
  1222. }
  1223. sub price_matrix {
  1224. my ($pmh, $ref, $transdate, $decimalplaces, $form, $myconfig) = @_;
  1225. $pmh->execute($ref->{id}, $ref->{id}, $ref->{id}, $ref->{id});
  1226. $ref->{pricematrix} = "";
  1227. my $customerprice;
  1228. my $pricegroupprice;
  1229. my $sellprice;
  1230. my $baseprice;
  1231. my $mref;
  1232. my %p = ();
  1233. my $i = 0;
  1234. while ($mref = $pmh->fetchrow_hashref(NAME_lc)) {
  1235. # check date
  1236. if ($mref->{validfrom}) {
  1237. next if $transdate < $form->datetonum($myconfig, $mref->{validfrom});
  1238. }
  1239. if ($mref->{validto}) {
  1240. next if $transdate > $form->datetonum($myconfig, $mref->{validto});
  1241. }
  1242. # convert price
  1243. $sellprice = $form->round_amount($mref->{sellprice} * $form->{$mref->{curr}}, $decimalplaces);
  1244. $mref->{pricebreak} *= 1;
  1245. if ($mref->{customer_id}) {
  1246. $p{$mref->{pricebreak}} = $sellprice;
  1247. $customerprice = 1;
  1248. }
  1249. if ($mref->{pricegroup_id}) {
  1250. if (!$customerprice) {
  1251. $p{$mref->{pricebreak}} = $sellprice;
  1252. $pricegroupprice = 1;
  1253. }
  1254. }
  1255. if (!$customerprice && !$pricegroupprice) {
  1256. $p{$mref->{pricebreak}} = $sellprice;
  1257. }
  1258. if (($mref->{pricebreak} + $mref->{customer_id} + $mref->{pricegroup_id}) == 0) {
  1259. $baseprice = $sellprice;
  1260. }
  1261. $i++;
  1262. }
  1263. $pmh->finish;
  1264. if (! exists $p{0}) {
  1265. $p{0} = $baseprice;
  1266. }
  1267. if ($i > 1) {
  1268. $ref->{sellprice} = $p{0};
  1269. for (sort { $a <=> $b } keys %p) { $ref->{pricematrix} .= "${_}:$p{$_} " }
  1270. } else {
  1271. $ref->{sellprice} = $form->round_amount($p{0} * (1 - $form->{tradediscount}), $decimalplaces);
  1272. $ref->{pricematrix} = "0:$ref->{sellprice} " if $ref->{sellprice};
  1273. }
  1274. chop $ref->{pricematrix};
  1275. }
  1276. sub exchangerate_defaults {
  1277. my ($dbh, $form) = @_;
  1278. my $var;
  1279. # get default currencies
  1280. my $query = qq|SELECT substr(curr,1,3), curr FROM defaults|;
  1281. my $eth = $dbh->prepare($query) || $form->dberror($query);
  1282. $eth->execute;
  1283. ($form->{defaultcurrency}, $form->{currencies}) = $eth->fetchrow_array;
  1284. $eth->finish;
  1285. $query = qq|SELECT buy
  1286. FROM exchangerate
  1287. WHERE curr = ?
  1288. AND transdate = ?|;
  1289. my $eth1 = $dbh->prepare($query) || $form->dberror($query);
  1290. $query = qq~SELECT max(transdate || ' ' || buy || ' ' || curr)
  1291. FROM exchangerate
  1292. WHERE curr = ?~;
  1293. my $eth2 = $dbh->prepare($query) || $form->dberror($query);
  1294. # get exchange rates for transdate or max
  1295. foreach $var (split /:/, substr($form->{currencies},4)) {
  1296. $eth1->execute($var, $form->{transdate});
  1297. ($form->{$var}) = $eth1->fetchrow_array;
  1298. if (! $form->{$var} ) {
  1299. $eth2->execute($var);
  1300. ($form->{$var}) = $eth2->fetchrow_array;
  1301. ($null, $form->{$var}) = split / /, $form->{$var};
  1302. $form->{$var} = 1 unless $form->{$var};
  1303. $eth2->finish;
  1304. }
  1305. $eth1->finish;
  1306. }
  1307. $form->{$form->{currency}} = $form->{exchangerate} if $form->{exchangerate};
  1308. $form->{$form->{currency}} ||= 1;
  1309. $form->{$form->{defaultcurrency}} = 1;
  1310. }
  1311. 1;