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