summaryrefslogtreecommitdiff
path: root/LedgerSMB/IS.pm
blob: 0fb7203a182dd018637f69927abd0aa685f02361 (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 undergone whitespace cleanup.
  27. #
  28. #======================================================================
  29. #
  30. # Inventory invoicing module
  31. #
  32. #======================================================================
  33. package IS;
  34. use LedgerSMB::Tax;
  35. use LedgerSMB::PriceMatrix;
  36. use LedgerSMB::Sysconfig;
  37. sub invoice_details {
  38. use LedgerSMB::CP;
  39. my ( $self, $myconfig, $form ) = @_;
  40. $form->{duedate} = $form->{transdate} unless ( $form->{duedate} );
  41. # connect to database
  42. my $dbh = $form->{dbh};
  43. my $query = qq|
  44. SELECT ?::date - ?::date
  45. AS terms, value
  46. FROM defaults
  47. WHERE setting_key = 'weightunit'|;
  48. my $sth = $dbh->prepare($query);
  49. $sth->execute( $form->{duedate}, $form->{transdate} )
  50. || $form->dberror($query);
  51. ( $form->{terms}, $form->{weightunit} ) = $sth->fetchrow_array;
  52. $sth->finish;
  53. # this is for the template
  54. $form->{invdate} = $form->{transdate};
  55. my $tax = 0;
  56. my $item;
  57. my $i;
  58. my @sortlist = ();
  59. my $projectnumber;
  60. my $projectdescription;
  61. my $projectnumber_id;
  62. my $translation;
  63. my $partsgroup;
  64. my @taxaccounts;
  65. my %taxaccounts;
  66. my $tax;
  67. my $taxrate;
  68. my $taxamount;
  69. my %translations;
  70. $query = qq|
  71. SELECT p.description, t.description
  72. FROM project p
  73. LEFT JOIN translation t
  74. ON (t.trans_id = p.id
  75. AND t.language_code = ?)
  76. WHERE id = ?|;
  77. my $prh = $dbh->prepare($query) || $form->dberror($query);
  78. $query = qq|
  79. SELECT inventory_accno_id, income_accno_id,
  80. expense_accno_id, assembly, weight FROM parts
  81. WHERE id = ?|;
  82. my $pth = $dbh->prepare($query) || $form->dberror($query);
  83. my $sortby;
  84. # sort items by project and partsgroup
  85. for $i ( 1 .. $form->{rowcount} - 1 ) {
  86. # account numbers
  87. $pth->execute( $form->{"id_$i"} );
  88. $ref = $pth->fetchrow_hashref(NAME_lc);
  89. for ( keys %$ref ) { $form->{"${_}_$i"} = $ref->{$_} }
  90. $pth->finish;
  91. $projectnumber_id = 0;
  92. $projectnumber = "";
  93. $form->{partsgroup} = "";
  94. $form->{projectnumber} = "";
  95. if ( $form->{groupprojectnumber} || $form->{grouppartsgroup} ) {
  96. $inventory_accno_id =
  97. ( $form->{"inventory_accno_id_$i"} || $form->{"assembly_$i"} )
  98. ? "1"
  99. : "";
  100. if ( $form->{groupprojectnumber} ) {
  101. ( $projectnumber, $projectnumber_id ) =
  102. split /--/, $form->{"projectnumber_$i"};
  103. }
  104. if ( $form->{grouppartsgroup} ) {
  105. ( $form->{partsgroup} ) =
  106. split /--/, $form->{"partsgroup_$i"};
  107. }
  108. if ( $projectnumber_id && $form->{groupprojectnumber} ) {
  109. if ( $translation{$projectnumber_id} ) {
  110. $form->{projectnumber} = $translation{$projectnumber_id};
  111. }
  112. else {
  113. # get project description
  114. $prh->execute( $projectnumber_id, $form->{language_code} );
  115. ( $projectdescription, $translation ) =
  116. $prh->fetchrow_array;
  117. $prh->finish;
  118. $form->{projectnumber} =
  119. ($translation)
  120. ? "$projectnumber, $translation"
  121. : "$projectnumber, " . "$projectdescription";
  122. $translation{$projectnumber_id} = $form->{projectnumber};
  123. }
  124. }
  125. if ( $form->{grouppartsgroup} && $form->{partsgroup} ) {
  126. $form->{projectnumber} .= " / "
  127. if $projectnumber_id;
  128. $form->{projectnumber} .= $form->{partsgroup};
  129. }
  130. $form->format_string(projectnumber);
  131. }
  132. $sortby = qq|$projectnumber$form->{partsgroup}|;
  133. if ( $form->{sortby} ne 'runningnumber' ) {
  134. for (qw(partnumber description bin)) {
  135. $sortby .= $form->{"${_}_$i"}
  136. if $form->{sortby} eq $_;
  137. }
  138. }
  139. push @sortlist,
  140. [
  141. $i,
  142. qq|$projectnumber$form->{partsgroup}| . qq|$inventory_accno_id|,
  143. $form->{projectnumber},
  144. $projectnumber_id,
  145. $form->{partsgroup},
  146. $sortby
  147. ];
  148. }
  149. # sort the whole thing by project and group
  150. @sortlist = sort { $a->[5] cmp $b->[5] } @sortlist;
  151. my $runningnumber = 1;
  152. my $sameitem = "";
  153. my $subtotal;
  154. my $k = scalar @sortlist;
  155. my $j = 0;
  156. foreach $item (@sortlist) {
  157. $i = $item->[0];
  158. $j++;
  159. # heading
  160. if ( $form->{groupprojectnumber} || $form->{grouppartsgroup} ) {
  161. if ( $item->[1] ne $sameitem ) {
  162. $sameitem = $item->[1];
  163. $ok = 0;
  164. if ( $form->{groupprojectnumber} ) {
  165. $ok = $form->{"projectnumber_$i"};
  166. }
  167. if ( $form->{grouppartsgroup} ) {
  168. $ok = $form->{"partsgroup_$i"}
  169. unless $ok;
  170. }
  171. if ($ok) {
  172. if ( $form->{"inventory_accno_id_$i"}
  173. || $form->{"assembly_$i"} )
  174. {
  175. push( @{ $form->{part} }, "" );
  176. push( @{ $form->{service} }, NULL );
  177. }
  178. else {
  179. push( @{ $form->{part} }, NULL );
  180. push( @{ $form->{service} }, "" );
  181. }
  182. push( @{ $form->{description} }, $item->[2] );
  183. for (
  184. qw(taxrates runningnumber number
  185. sku serialnumber bin qty ship
  186. unit deliverydate projectnumber
  187. sellprice listprice netprice
  188. discount discountrate linetotal
  189. weight itemnotes)
  190. )
  191. {
  192. push( @{ $form->{$_} }, "" );
  193. }
  194. push( @{ $form->{lineitems} }, { amount => 0, tax => 0 } );
  195. }
  196. }
  197. }
  198. $form->{"qty_$i"} = $form->parse_amount( $myconfig, $form->{"qty_$i"} );
  199. if ( $form->{"qty_$i"} ) {
  200. $form->{discount} = [] if ref $form->{discount} ne 'ARRAY';
  201. $form->{totalqty} += $form->{"qty_$i"};
  202. $form->{totalship} += $form->{"qty_$i"};
  203. $form->{totalweight} +=
  204. ( $form->{"qty_$i"} * $form->{"weight_$i"} );
  205. $form->{totalweightship} +=
  206. ( $form->{"qty_$i"} * $form->{"weight_$i"} );
  207. # add number, description and qty to $form->{number}...
  208. push( @{ $form->{runningnumber} }, $runningnumber++ );
  209. push( @{ $form->{number} }, $form->{"partnumber_$i"} );
  210. push( @{ $form->{sku} }, $form->{"sku_$i"} );
  211. push( @{ $form->{serialnumber} }, $form->{"serialnumber_$i"} );
  212. push( @{ $form->{bin} }, $form->{"bin_$i"} );
  213. push( @{ $form->{description} }, $form->{"description_$i"} );
  214. push( @{ $form->{itemnotes} }, $form->{"notes_$i"} );
  215. push(
  216. @{ $form->{qty} },
  217. $form->format_amount( $myconfig, $form->{"qty_$i"} )
  218. );
  219. push(
  220. @{ $form->{ship} },
  221. $form->format_amount( $myconfig, $form->{"qty_$i"} )
  222. );
  223. push( @{ $form->{unit} }, $form->{"unit_$i"} );
  224. push( @{ $form->{deliverydate} }, $form->{"deliverydate_$i"} );
  225. push( @{ $form->{projectnumber} }, $form->{"projectnumber_$i"} );
  226. push( @{ $form->{sellprice} }, $form->{"sellprice_$i"} );
  227. push( @{ $form->{listprice} }, $form->{"listprice_$i"} );
  228. push(
  229. @{ $form->{weight} },
  230. $form->format_amount(
  231. $myconfig, $form->{"weight_$i"} * $form->{"qty_$i"}
  232. )
  233. );
  234. my $sellprice =
  235. $form->parse_amount( $myconfig, $form->{"sellprice_$i"} );
  236. my ($dec) = ( $sellprice =~ /\.(\d+)/ );
  237. $dec = length $dec;
  238. my $decimalplaces = ( $dec > 2 ) ? $dec : 2;
  239. my $discount = $form->round_amount(
  240. $sellprice *
  241. $form->parse_amount( $myconfig, $form->{"discount_$i"} ) /
  242. 100,
  243. $decimalplaces
  244. );
  245. # keep a netprice as well, (sellprice - discount)
  246. $form->{"netprice_$i"} = $sellprice - $discount;
  247. my $linetotal =
  248. $form->round_amount( $form->{"qty_$i"} * $form->{"netprice_$i"},
  249. 2 );
  250. if ( $form->{"inventory_accno_id_$i"}
  251. || $form->{"assembly_$i"} )
  252. {
  253. push( @{ $form->{part} }, $form->{"sku_$i"} );
  254. push( @{ $form->{service} }, NULL );
  255. $form->{totalparts} += $linetotal;
  256. }
  257. else {
  258. push( @{ $form->{service} }, $form->{"sku_$i"} );
  259. push( @{ $form->{part} }, NULL );
  260. $form->{totalservices} += $linetotal;
  261. }
  262. push(
  263. @{ $form->{netprice} },
  264. ( $form->{"netprice_$i"} )
  265. ? $form->format_amount( $myconfig, $form->{"netprice_$i"},
  266. $decimalplaces )
  267. : " "
  268. );
  269. $discount =
  270. ($discount)
  271. ? $form->format_amount( $myconfig, $discount * -1,
  272. $decimalplaces )
  273. : " ";
  274. push( @{ $form->{discount} }, $discount );
  275. push(
  276. @{ $form->{discountrate} },
  277. $form->format_amount( $myconfig, $form->{"discount_$i"} )
  278. );
  279. $form->{total} += $linetotal;
  280. # this is for the subtotals for grouping
  281. $subtotal += $linetotal;
  282. $form->{"linetotal_$i"} =
  283. $form->format_amount( $myconfig, $linetotal, 2 );
  284. $form->{"linetotal_$i"} = '0.00' unless $form->{"linetotal_$i"};
  285. push( @{ $form->{linetotal} }, $form->{"linetotal_$i"} );
  286. @taxaccounts = Tax::init_taxes(
  287. $form,
  288. $form->{"taxaccounts_$i"},
  289. $form->{"taxaccounts"}
  290. );
  291. my $ml = 1;
  292. my @taxrates = ();
  293. $tax = 0;
  294. if ( $form->{taxincluded} ) {
  295. $taxamount =
  296. Tax::calculate_taxes( \@taxaccounts, $form, $linetotal, 1 );
  297. $taxbase = ( $linetotal - $taxamount );
  298. $tax += Tax::extract_taxes( \@taxaccounts, $form, $linetotal );
  299. }
  300. else {
  301. $taxamount =
  302. Tax::calculate_taxes( \@taxaccounts, $form, $linetotal, 0 );
  303. $tax += Tax::apply_taxes( \@taxaccounts, $form, $linetotal );
  304. }
  305. foreach $item (@taxaccounts) {
  306. push @taxrates, 100 * $item->rate;
  307. $taxaccounts{ $item->account } += $item->value;
  308. if ( $form->{taxincluded} ) {
  309. $taxbase{ $item->account } += $taxbase;
  310. }
  311. else {
  312. $taxbase{ $item->account } += $linetotal;
  313. }
  314. }
  315. push(
  316. @{ $form->{lineitems} },
  317. {
  318. amount => $linetotal,
  319. tax => $form->round_amount( $tax, 2 )
  320. }
  321. );
  322. push( @{ $form->{taxrates} },
  323. join ' ', sort { $a <=> $b } @taxrates );
  324. if ( $form->{"assembly_$i"} ) {
  325. $form->{stagger} = -1;
  326. &assembly_details( $myconfig, $form, $dbh, $form->{"id_$i"},
  327. $oid{ $myconfig->{dbdriver} },
  328. $form->{"qty_$i"} );
  329. }
  330. }
  331. # add subtotal
  332. if ( $form->{groupprojectnumber} || $form->{grouppartsgroup} ) {
  333. if ($subtotal) {
  334. if ( $j < $k ) {
  335. # look at next item
  336. if ( $sortlist[$j]->[1] ne $sameitem ) {
  337. if ( $form->{"inventory_accno_id_$j"}
  338. || $form->{"assembly_$i"} )
  339. {
  340. push( @{ $form->{part} }, "" );
  341. push( @{ $form->{service} }, NULL );
  342. }
  343. else {
  344. push( @{ $form->{service} }, "" );
  345. push( @{ $form->{part} }, NULL );
  346. }
  347. for (
  348. qw(taxrates
  349. runningnumber number sku
  350. serialnumber bin qty
  351. ship unit deliverydate
  352. projectnumber sellprice
  353. listprice netprice
  354. discount discountrate
  355. weight itemnotes)
  356. )
  357. {
  358. push( @{ $form->{$_} }, "" );
  359. }
  360. push(
  361. @{ $form->{description} },
  362. $form->{groupsubtotaldescription}
  363. );
  364. push(
  365. @{ $form->{lineitems} },
  366. {
  367. amount => 0,
  368. tax => 0
  369. }
  370. );
  371. if ( $form->{groupsubtotaldescription} ne "" ) {
  372. push(
  373. @{ $form->{linetotal} },
  374. $form->format_amount( $myconfig, $subtotal, 2 )
  375. );
  376. }
  377. else {
  378. push( @{ $form->{linetotal} }, "" );
  379. }
  380. $subtotal = 0;
  381. }
  382. }
  383. else {
  384. # got last item
  385. if ( $form->{groupsubtotaldescription} ne "" ) {
  386. if ( $form->{"inventory_accno_id_$j"}
  387. || $form->{"assembly_$i"} )
  388. {
  389. push( @{ $form->{part} }, "" );
  390. push( @{ $form->{service} }, NULL );
  391. }
  392. else {
  393. push( @{ $form->{service} }, "" );
  394. push( @{ $form->{part} }, NULL );
  395. }
  396. for (
  397. qw(taxrates
  398. runningnumber number sku
  399. serialnumber bin qty
  400. ship unit deliverydate
  401. projectnumber sellprice
  402. listprice netprice
  403. discount discountrate
  404. weight itemnotes)
  405. )
  406. {
  407. push( @{ $form->{$_} }, "" );
  408. }
  409. push(
  410. @{ $form->{description} },
  411. $form->{groupsubtotaldescription}
  412. );
  413. push(
  414. @{ $form->{linetotal} },
  415. $form->format_amount( $myconfig, $subtotal, 2 )
  416. );
  417. push(
  418. @{ $form->{lineitems} },
  419. {
  420. amount => 0,
  421. tax => 0
  422. }
  423. );
  424. }
  425. }
  426. }
  427. }
  428. }
  429. $tax = 0;
  430. foreach my $item ( sort keys %taxaccounts ) {
  431. if ( $form->round_amount( $taxaccounts{$item}, 2 ) ) {
  432. $tax += $taxamount = $form->round_amount( $taxaccounts{$item}, 2 );
  433. push(
  434. @{ $form->{taxbaseinclusive} },
  435. $form->{"${item}_taxbaseinclusive"} =
  436. $form->format_amount( $myconfig, $taxbase{$item} + $tax, 2 )
  437. );
  438. push(
  439. @{ $form->{taxbase} },
  440. $form->{"${item}_taxbase"} =
  441. $form->format_amount( $myconfig, $taxbase{$item}, 2 )
  442. );
  443. push(
  444. @{ $form->{tax} },
  445. $form->{"${item}_tax"} =
  446. $form->format_amount( $myconfig, $taxamount, 2 )
  447. );
  448. push( @{ $form->{taxdescription} },
  449. $form->{"${item}_description"} );
  450. $form->{"${item}_taxrate"} =
  451. $form->format_amount( $myconfig, $form->{"${item}_rate"} * 100 );
  452. push( @{ $form->{taxrate} }, $form->{"${item}_taxrate"} );
  453. push( @{ $form->{taxnumber} }, $form->{"${item}_taxnumber"} );
  454. }
  455. }
  456. # adjust taxes for lineitems
  457. my $total = 0;
  458. for ( @{ $form->{lineitems} } ) {
  459. $total += $_->{tax};
  460. }
  461. if ( $form->round_amount( $total, 2 ) != $form->round_amount( $tax, 2 ) ) {
  462. # get largest amount
  463. for ( reverse sort { $a->{tax} <=> $b->{tax} } @{ $form->{lineitems} } )
  464. {
  465. $_->{tax} -= $total - $tax;
  466. last;
  467. }
  468. }
  469. $i = 1;
  470. for ( @{ $form->{lineitems} } ) {
  471. push(
  472. @{ $form->{linetax} },
  473. $form->format_amount( $myconfig, $_->{tax}, 2, "" )
  474. );
  475. }
  476. for $i ( 1 .. $form->{paidaccounts} ) {
  477. if ( $form->{"paid_$i"} ) {
  478. push( @{ $form->{payment} }, $form->{"paid_$i"} );
  479. my ( $accno, $description ) = split /--/, $form->{"AR_paid_$i"};
  480. push( @{ $form->{paymentaccount} }, $description );
  481. push( @{ $form->{paymentdate} }, $form->{"datepaid_$i"} );
  482. push( @{ $form->{paymentsource} }, $form->{"source_$i"} );
  483. push( @{ $form->{paymentmemo} }, $form->{"memo_$i"} );
  484. $form->{paid} +=
  485. $form->parse_amount( $myconfig, $form->{"paid_$i"} );
  486. }
  487. }
  488. for (qw(totalparts totalservices)) {
  489. $form->{$_} = $form->format_amount( $myconfig, $form->{$_}, 2 );
  490. }
  491. for (qw(totalqty totalship totalweight)) {
  492. $form->{$_} = $form->format_amount( $myconfig, $form->{$_} );
  493. }
  494. $form->{subtotal} = $form->format_amount( $myconfig, $form->{total}, 2 );
  495. $form->{subtotal} = '0.00' unless $form->{subtotal};
  496. $form->{invtotal} =
  497. ( $form->{taxincluded} ) ? $form->{total} : $form->{total} + $tax;
  498. my $c;
  499. if ( $form->{language_code} ne "" ) {
  500. $c = new CP $form->{language_code};
  501. }
  502. else {
  503. $c = new CP $myconfig->{countrycode};
  504. }
  505. $c->init;
  506. my $whole;
  507. ( $whole, $form->{decimal} ) = split /\./, $form->{invtotal};
  508. $form->{decimal} .= "00";
  509. $form->{decimal} = substr( $form->{decimal}, 0, 2 );
  510. $form->{text_decimal} = $c->num2text( $form->{decimal} * 1 );
  511. $form->{text_amount} = $c->num2text($whole);
  512. $form->{integer_amount} = $form->format_amount( $myconfig, $whole );
  513. $form->format_string(qw(text_amount text_decimal));
  514. $form->{total} =
  515. $form->format_amount( $myconfig, $form->{invtotal} - $form->{paid}, 2 );
  516. $form->{invtotal} = $form->format_amount( $myconfig, $form->{invtotal}, 2 );
  517. $form->{paid} = $form->format_amount( $myconfig, $form->{paid}, 2 );
  518. $dbh->commit;
  519. }
  520. sub assembly_details {
  521. my ( $myconfig, $form, $dbh2, $id, $oid, $qty ) = @_;
  522. $dbh = $form->{dbh};
  523. my $sm = "";
  524. my $spacer;
  525. $form->{stagger}++;
  526. if ( $form->{format} eq 'html' ) {
  527. $spacer = "&nbsp;" x ( 3 * ( $form->{stagger} - 1 ) )
  528. if $form->{stagger} > 1;
  529. }
  530. if ( $form->{format} =~ /(postscript|pdf)/ ) {
  531. if ( $form->{stagger} > 1 ) {
  532. $spacer = ( $form->{stagger} - 1 ) * 3;
  533. $spacer = '\rule{' . $spacer . 'mm}{0mm}';
  534. }
  535. }
  536. # get parts and push them onto the stack
  537. my $sortorder = "";
  538. if ( $form->{grouppartsgroup} ) {
  539. $sortorder = qq|ORDER BY pg.partsgroup|;
  540. }
  541. my $query = qq|
  542. SELECT p.partnumber, p.description, p.unit, a.qty,
  543. pg.partsgroup, p.partnumber AS sku
  544. FROM assembly a
  545. JOIN parts p ON (a.parts_id = p.id)
  546. LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
  547. WHERE a.bom = '1'
  548. AND a.id = ?
  549. $sortorder|;
  550. my $sth = $dbh->prepare($query);
  551. $sth->execute($id) || $form->dberror($query);
  552. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  553. for (qw(partnumber description partsgroup)) {
  554. $form->{"a_$_"} = $ref->{$_};
  555. $form->format_string("a_$_");
  556. }
  557. if ( $form->{grouppartsgroup} && $ref->{partsgroup} ne $sm ) {
  558. for (
  559. qw(taxrates runningnumber number sku
  560. serialnumber unit qty ship bin deliverydate
  561. projectnumber sellprice listprice netprice
  562. discount discountrate linetotal weight
  563. itemnotes)
  564. )
  565. {
  566. push( @{ $form->{$_} }, "" );
  567. }
  568. $sm =
  569. ( $form->{"a_partsgroup"} )
  570. ? $form->{"a_partsgroup"}
  571. : "--";
  572. push( @{ $form->{description} }, "$spacer$sm" );
  573. push( @{ $form->{lineitems} }, { amount => 0, tax => 0 } );
  574. }
  575. if ( $form->{stagger} ) {
  576. push(
  577. @{ $form->{description} },
  578. $form->format_amount( $myconfig,
  579. $ref->{qty} * $form->{"qty_$i"} )
  580. . qq| -- $form->{"a_partnumber"}|
  581. . qq|, $form->{"a_description"}|
  582. );
  583. for (
  584. qw(taxrates runningnumber number sku
  585. serialnumber unit qty ship bin deliverydate
  586. projectnumber sellprice listprice netprice
  587. discount discountrate linetotal weight
  588. itemnotes)
  589. )
  590. {
  591. push( @{ $form->{$_} }, "" );
  592. }
  593. }
  594. else {
  595. push( @{ $form->{description} }, qq|$form->{"a_description"}| );
  596. push( @{ $form->{number} }, $form->{"a_partnumber"} );
  597. push( @{ $form->{sku} }, $form->{"a_partnumber"} );
  598. for (
  599. qw(taxrates runningnumber ship serialnumber
  600. reqdate projectnumber sellprice listprice
  601. netprice discount discountrate linetotal weight
  602. itemnotes)
  603. )
  604. {
  605. push( @{ $form->{$_} }, "" );
  606. }
  607. }
  608. push( @{ $form->{lineitems} }, { amount => 0, tax => 0 } );
  609. push(
  610. @{ $form->{qty} },
  611. $form->format_amount( $myconfig, $ref->{qty} * $qty )
  612. );
  613. for (qw(unit bin)) {
  614. $form->{"a_$_"} = $ref->{$_};
  615. $form->format_string("a_$_");
  616. push( @{ $form->{$_} }, $form->{"a_$_"} );
  617. }
  618. }
  619. $sth->finish;
  620. $form->{stagger}--;
  621. }
  622. sub project_description {
  623. my ( $self, $dbh2, $id ) = @_;
  624. $dbh = $form->{dbh};
  625. my $query = qq|
  626. SELECT description
  627. FROM project
  628. WHERE id = ?|;
  629. $sth = $dbh->prepare($query);
  630. $sth->execute($id);
  631. ($_) = $sth->fetchrow_array;
  632. $_;
  633. }
  634. sub customer_details {
  635. my ( $self, $myconfig, $form ) = @_;
  636. my $dbh = $form->{dbh};
  637. # get rest for the customer
  638. my $query = qq|
  639. SELECT c.customernumber, e.name, l.line_one as address1,
  640. l.line_two as address2, l.city AS city,
  641. '' as state, l.mail_code AS zipcode,
  642. country.name as country,
  643. '' as contact, '' as customerphone, '' as customerfax,
  644. '' AS customertaxnumber, sic_code AS sic, iban,
  645. bic, startdate, enddate
  646. FROM customer c
  647. JOIN company cm ON c.entity_id = cm.entity_id
  648. JOIN entity e ON (c.entity_id = e.id)
  649. JOIN company_to_location cl ON cm.id = cl.company_id
  650. JOIN location l ON cl.location_id = l.id
  651. JOIN country ON l.country_id = country.id
  652. WHERE e.id = ?|;
  653. my $sth = $dbh->prepare($query);
  654. $sth->execute( $form->{customer_id} ) || $form->dberror($query);
  655. $ref = $sth->fetchrow_hashref(NAME_lc);
  656. for ( keys %$ref ) { $form->{$_} = $ref->{$_} }
  657. $sth->finish;
  658. }
  659. sub post_invoice {
  660. my ( $self, $myconfig, $form ) = @_;
  661. $form->{invnumber} = $form->update_defaults( $myconfig, "sinumber", $dbh )
  662. unless $form->{invnumber};
  663. my $dbh = $form->{dbh};
  664. my $query;
  665. my $sth;
  666. my $null;
  667. my $project_id;
  668. my $exchangerate = 0;
  669. my $keepcleared = 0;
  670. %$form->{acc_trans} = ();
  671. if ($form->{id}){
  672. delete_invoice($self, $myconfig, $form);
  673. }
  674. ( $null, $form->{employee_id} ) = split /--/, $form->{employee};
  675. unless ( $form->{employee_id} ) {
  676. ( $form->{employee}, $form->{employee_id} ) = $form->get_employee($dbh);
  677. }
  678. ( $null, $form->{department_id} ) = split( /--/, $form->{department} );
  679. $form->{department_id} *= 1;
  680. $query = qq|
  681. SELECT (SELECT value FROM defaults
  682. WHERE setting_key = 'fxgain_accno_id')
  683. AS fxgain_accno_id,
  684. (SELECT value FROM defaults
  685. WHERE setting_key = 'fxloss_accno_id')
  686. AS fxloss_accno_id|;
  687. my ( $fxgain_accno_id, $fxloss_accno_id ) = $dbh->selectrow_array($query);
  688. $query = qq|
  689. SELECT p.assembly, p.inventory_accno_id,
  690. p.income_accno_id, p.expense_accno_id, p.project_id
  691. FROM parts p
  692. WHERE p.id = ?|;
  693. my $pth = $dbh->prepare($query) || $form->dberror($query);
  694. if ( $form->{id} ) {
  695. $keepcleared = 1;
  696. $query = qq|SELECT id FROM ar WHERE id = ?|;
  697. $sth = $dbh->prepare($query);
  698. $sth->execute( $form->{id} );
  699. if ( $sth->fetchrow_array ) {
  700. &reverse_invoice( $dbh, $form );
  701. }
  702. else {
  703. $query = qq|INSERT INTO ar (id) VALUES (?)|;
  704. $sth = $dbh->prepare($query);
  705. $sth->execute( $form->{id} ) || $form->dberror($query);
  706. }
  707. }
  708. my $uid = localtime;
  709. $uid .= "$$";
  710. if ( !$form->{id} ) {
  711. $query = qq|
  712. INSERT INTO ar (invnumber, person_id)
  713. VALUES ('$uid', ?)|;
  714. $sth = $dbh->prepare($query);
  715. $sth->execute( $form->{employee_id} ) || $form->dberror($query);
  716. $query = qq|SELECT id FROM ar WHERE invnumber = '$uid'|;
  717. $sth = $dbh->prepare($query);
  718. $sth->execute || $form->dberror($query);
  719. ( $form->{id} ) = $sth->fetchrow_array;
  720. $sth->finish;
  721. @queries = $form->run_custom_queries( 'ar', 'INSERT' );
  722. }
  723. if ( $form->{currency} eq $form->{defaultcurrency} ) {
  724. $form->{exchangerate} = 1;
  725. }
  726. else {
  727. $exchangerate =
  728. $form->check_exchangerate( $myconfig, $form->{currency},
  729. $form->{transdate}, 'buy' );
  730. }
  731. $form->{exchangerate} =
  732. ($exchangerate)
  733. ? $exchangerate
  734. : $form->parse_amount( $myconfig, $form->{exchangerate} );
  735. my $i;
  736. my $item;
  737. my $allocated = 0;
  738. my $taxrate;
  739. my $tax;
  740. my $fxtax;
  741. my @taxaccounts;
  742. my $amount;
  743. my $grossamount;
  744. my $invamount = 0;
  745. my $invnetamount = 0;
  746. my $diff = 0;
  747. my $ml;
  748. my $invoice_id;
  749. my $ndx;
  750. for (keys %$form) {
  751. if (UNIVERSAL::isa( $form->{$_}, 'Math::BigFloat' )){
  752. $form->{$_} = $form->{$_}->bstr();
  753. }
  754. }
  755. foreach $i ( 1 .. $form->{rowcount} ) {
  756. $form->{"qty_$i"} = $form->parse_amount( $myconfig, $form->{"qty_$i"} );
  757. if ($form->{reverse}){
  758. $form->{"qty_$i"} *= -1;
  759. }
  760. if ( $form->{"qty_$i"} ) {
  761. $pth->execute( $form->{"id_$i"} );
  762. $ref = $pth->fetchrow_hashref(NAME_lc);
  763. for ( keys %$ref ) { $form->{"${_}_$i"} = $ref->{$_} }
  764. $pth->finish;
  765. # project
  766. if ( $form->{"projectnumber_$i"} ) {
  767. ( $null, $project_id ) = split /--/,
  768. $form->{"projectnumber_$i"};
  769. }
  770. $project_id = $form->{"project_id_$i"}
  771. if $form->{"project_id_$i"};
  772. # keep entered selling price
  773. my $fxsellprice =
  774. $form->parse_amount( $myconfig, $form->{"sellprice_$i"} );
  775. my ($dec) = ( $fxsellprice =~ /\.(\d+)/ );
  776. $dec = length $dec;
  777. my $decimalplaces = ( $dec > 2 ) ? $dec : 2;
  778. # undo discount formatting
  779. $form->{"discount_$i"} =
  780. $form->parse_amount( $myconfig, $form->{"discount_$i"} ) / 100;
  781. # deduct discount
  782. $form->{"sellprice_$i"} = $fxsellprice -
  783. $form->round_amount( $fxsellprice * $form->{"discount_$i"},
  784. $decimalplaces );
  785. # linetotal
  786. my $fxlinetotal =
  787. $form->round_amount( $form->{"sellprice_$i"} * $form->{"qty_$i"},
  788. 2 );
  789. $amount = $fxlinetotal * $form->{exchangerate};
  790. my $linetotal = $form->round_amount( $amount, 2 );
  791. $fxdiff += $amount - $linetotal;
  792. @taxaccounts = Tax::init_taxes(
  793. $form,
  794. $form->{"taxaccounts_$i"},
  795. $form->{"taxaccounts"}
  796. );
  797. $ml = 1;
  798. $tax = Math::BigFloat->bzero();
  799. $fxtax = Math::BigFloat->bzero();
  800. if ( $form->{taxincluded} ) {
  801. $tax += $amount =
  802. Tax::calculate_taxes( \@taxaccounts, $form, $linetotal, 1 );
  803. $form->{"sellprice_$i"} -= $amount / $form->{"qty_$i"};
  804. $fxtax +=
  805. Tax::calculate_taxes( \@taxaccounts, $form, $linetotal, 1 );
  806. }
  807. else {
  808. $tax += $amount =
  809. Tax::calculate_taxes( \@taxaccounts, $form, $linetotal, 0 );
  810. $fxtax +=
  811. Tax::calculate_taxes( \@taxaccounts, $form, $linetotal, 0 );
  812. }
  813. for (@taxaccounts) {
  814. $form->{acc_trans}{ $form->{id} }{ $_->account }{amount} +=
  815. $_->value;
  816. }
  817. $grossamount = $form->round_amount( $linetotal, 2 );
  818. if ( $form->{taxincluded} ) {
  819. $amount = $form->round_amount( $tax, 2 );
  820. $linetotal -= $form->round_amount( $tax - $diff, 2 );
  821. $diff = ( $amount - $tax );
  822. }
  823. # add linetotal to income
  824. $amount = $form->round_amount( $linetotal, 2 );
  825. push @{ $form->{acc_trans}{lineitems} },
  826. {
  827. chart_id => $form->{"income_accno_id_$i"},
  828. amount => $amount,
  829. fxgrossamount => $fxlinetotal + $fxtax,
  830. grossamount => $grossamount,
  831. project_id => $project_id
  832. };
  833. $ndx = $#{ @{ $form->{acc_trans}{lineitems} } };
  834. $form->{"sellprice_$i"} =
  835. $form->round_amount(
  836. $form->{"sellprice_$i"} * $form->{exchangerate},
  837. $decimalplaces );
  838. if ( $form->{"inventory_accno_id_$i"}
  839. || $form->{"assembly_$i"} )
  840. {
  841. if ( $form->{"assembly_$i"} ) {
  842. # If the assembly consists of all
  843. # services, we don't keep inventory,
  844. # so we should not update it
  845. $query = qq|
  846. SELECT sum(
  847. p.inventory_accno_id),
  848. p.assembly
  849. FROM parts p
  850. JOIN assembly a
  851. ON (a.parts_id = p.id)
  852. WHERE a.id = ?
  853. GROUP BY p.assembly|;
  854. $sth = $dbh->prepare($query);
  855. $sth->execute( $form->{"id_$i"} )
  856. || $form->dberror($query);
  857. my ( $inv, $assembly ) = $sth->fetchrow_array;
  858. $sth->finish;
  859. if ( $inv || $assembly ) {
  860. $form->update_balance(
  861. $dbh, "parts", "onhand",
  862. qq|id = | . qq|$form->{"id_$i"}|,
  863. $form->{"qty_$i"} * -1
  864. ) unless $form->{shipped};
  865. }
  866. &process_assembly( $dbh, $form, $form->{"id_$i"},
  867. $form->{"qty_$i"}, $project_id );
  868. }
  869. else {
  870. $form->update_balance(
  871. $dbh, "parts", "onhand",
  872. qq|id = $form->{"id_$i"}|,
  873. $form->{"qty_$i"} * -1
  874. ) unless $form->{shipped};
  875. $allocated = cogs(
  876. $dbh, $form,
  877. $form->{"id_$i"}, $form->{"qty_$i"},
  878. $project_id, $form->{"sellprice_$i"},
  879. );
  880. }
  881. }
  882. # save detail record in invoice table
  883. $query = qq|
  884. INSERT INTO invoice (description)
  885. VALUES ('$uid')|;
  886. $dbh->do($query) || $form->dberror($query);
  887. $query = qq|
  888. SELECT id FROM invoice
  889. WHERE description = '$uid'|;
  890. ($invoice_id) = $dbh->selectrow_array($query);
  891. unless ( $form->{"deliverydate_$i"} ) {
  892. undef $form->{"deliverydate_$i"};
  893. }
  894. $query = qq|
  895. UPDATE invoice
  896. SET trans_id = ?,
  897. parts_id = ?,
  898. description = ?,
  899. qty = ?,
  900. sellprice = ?,
  901. fxsellprice = ?,
  902. discount = ?,
  903. allocated = ?,
  904. unit = ?,
  905. deliverydate = ?,
  906. project_id = ?,
  907. serialnumber = ?,
  908. notes = ?
  909. WHERE id = ?|;
  910. $sth = $dbh->prepare($query);
  911. $sth->execute(
  912. $form->{id}, $form->{"id_$i"},
  913. $form->{"description_$i"}, $form->{"qty_$i"},
  914. $form->{"sellprice_$i"}, $fxsellprice,
  915. $form->{"discount_$i"}, $allocated,
  916. $form->{"unit_$i"}, $form->{"deliverydate_$i"},
  917. $project_id, $form->{"serialnumber_$i"},
  918. $form->{"notes_$i"},
  919. $invoice_id
  920. ) || $form->dberror($query);
  921. if (defined $form->{approved}) {
  922. $query = qq| UPDATE ar SET approved = ? WHERE id = ?|;
  923. $dbh->prepare($query)->execute($form->{approved}, $form->{id})
  924. || $form->dberror($query);
  925. if (!$form->{approved}){
  926. if (not defined $form->{batch_id}){
  927. $form->error($locale->text('Batch ID Missing'));
  928. }
  929. $query = qq|
  930. INSERT INTO voucher (batch_id, trans_id) VALUES (?, ?)|;
  931. $sth = $dbh->prepare($query);
  932. $sth->execute($form->{batch_id}, $form->{id}) ||
  933. $form->dberror($query);
  934. }
  935. }
  936. # add invoice_id
  937. $form->{acc_trans}{lineitems}[$ndx]->{invoice_id} = $invoice_id;
  938. }
  939. }
  940. $form->{paid} = 0;
  941. for $i ( 1 .. $form->{paidaccounts} ) {
  942. $form->{"paid_$i"} =
  943. $form->parse_amount( $myconfig, $form->{"paid_$i"} )->bstr();
  944. $form->{paid} += $form->{"paid_$i"};
  945. $form->{datepaid} = $form->{"datepaid_$i"}
  946. if ( $form->{"paid_$i"} );
  947. }
  948. # add lineitems + tax
  949. $amount = 0;
  950. $grossamount = 0;
  951. $fxgrossamount = 0;
  952. for ( @{ $form->{acc_trans}{lineitems} } ) {
  953. $amount += $_->{amount};
  954. $grossamount += $_->{grossamount};
  955. $fxgrossamount += $_->{fxgrossamount};
  956. }
  957. $invnetamount = $amount;
  958. $amount = 0;
  959. for ( split / /, $form->{taxaccounts} ) {
  960. $amount += $form->{acc_trans}{ $form->{id} }{$_}{amount} =
  961. $form->round_amount( $form->{acc_trans}{ $form->{id} }{$_}{amount},
  962. 2 );
  963. }
  964. $invamount = $invnetamount + $amount;
  965. $diff = 0;
  966. if ( $form->{taxincluded} ) {
  967. $diff = $form->round_amount( $grossamount - $invamount, 2 );
  968. $invamount += $diff;
  969. }
  970. $fxdiff = $form->round_amount( $fxdiff, 2 );
  971. $invnetamount += $fxdiff;
  972. $invamount += $fxdiff;
  973. if ( $form->round_amount( $form->{paid} - $fxgrossamount, 2 ) == 0 ) {
  974. $form->{paid} = $invamount;
  975. }
  976. else {
  977. $form->{paid} =
  978. $form->round_amount( $form->{paid} * $form->{exchangerate}, 2 );
  979. }
  980. foreach $ref ( sort { $b->{amount} <=> $a->{amount} }
  981. @{ $form->{acc_trans}{lineitems} } )
  982. {
  983. $amount = $ref->{amount} + $diff + $fxdiff;
  984. $query = qq|
  985. INSERT INTO acc_trans
  986. (trans_id, chart_id, amount,
  987. transdate, project_id, invoice_id)
  988. VALUES (?, ?, ?, ?, ?, ?)|;
  989. $sth = $dbh->prepare($query);
  990. $sth->execute( $form->{id}, $ref->{chart_id}, $amount,
  991. $form->{transdate}, $ref->{project_id}, $ref->{invoice_id} )
  992. || $form->dberror($query);
  993. $diff = 0;
  994. $fxdiff = 0;
  995. }
  996. $form->{receivables} = $invamount * -1;
  997. delete $form->{acc_trans}{lineitems};
  998. # update exchangerate
  999. if ( ( $form->{currency} ne $form->{defaultcurrency} ) && !$exchangerate ) {
  1000. $form->update_exchangerate( $dbh, $form->{currency}, $form->{transdate},
  1001. $form->{exchangerate}, 0 );
  1002. }
  1003. # record receivable
  1004. if ( $form->{receivables} ) {
  1005. ($accno) = split /--/, $form->{AR};
  1006. $query = qq|
  1007. INSERT INTO acc_trans
  1008. (trans_id, chart_id, amount, transdate)
  1009. VALUES (?, (SELECT id FROM chart WHERE accno = ?),
  1010. ?, ?)|;
  1011. $sth = $dbh->prepare($query);
  1012. $sth->execute( $form->{id}, $accno, $form->{receivables},
  1013. $form->{transdate} )
  1014. || $form->dberror($query);
  1015. }
  1016. foreach my $trans_id ( keys %{ $form->{acc_trans} } ) {
  1017. foreach my $accno ( keys %{ $form->{acc_trans}{$trans_id} } ) {
  1018. $amount =
  1019. $form->round_amount(
  1020. $form->{acc_trans}{$trans_id}{$accno}{amount}, 2 );
  1021. if ($amount) {
  1022. $query = qq|
  1023. INSERT INTO acc_trans
  1024. (trans_id, chart_id, amount,
  1025. transdate)
  1026. VALUES (?, (SELECT id FROM chart
  1027. WHERE accno = ?),
  1028. ?, ?)|;
  1029. $sth = $dbh->prepare($query);
  1030. $sth->execute( $trans_id, $accno, $amount, $form->{transdate} )
  1031. || $form->dberror($query);
  1032. }
  1033. }
  1034. }
  1035. # if there is no amount but a payment record receivable
  1036. if ( $invamount == 0 ) {
  1037. $form->{receivables} = 1;
  1038. }
  1039. my $cleared = 0;
  1040. # record payments and offsetting AR
  1041. for $i ( 1 .. $form->{paidaccounts} ) {
  1042. if ( $form->{"paid_$i"} ) {
  1043. my ($accno) = split /--/, $form->{"AR_paid_$i"};
  1044. $form->{"datepaid_$i"} = $form->{transdate}
  1045. unless ( $form->{"datepaid_$i"} );
  1046. $form->{datepaid} = $form->{"datepaid_$i"};
  1047. $exchangerate = 0;
  1048. if ( $form->{currency} eq $form->{defaultcurrency} ) {
  1049. $form->{"exchangerate_$i"} = 1;
  1050. }
  1051. else {
  1052. $exchangerate =
  1053. $form->check_exchangerate( $myconfig, $form->{currency},
  1054. $form->{"datepaid_$i"}, 'buy' );
  1055. $form->{"exchangerate_$i"} =
  1056. ($exchangerate)
  1057. ? $exchangerate
  1058. : $form->parse_amount( $myconfig,
  1059. $form->{"exchangerate_$i"} );
  1060. }
  1061. # record AR
  1062. $amount =
  1063. $form->round_amount( $form->{"paid_$i"} * $form->{exchangerate},
  1064. 2 );
  1065. if ( $form->{receivables} ) {
  1066. $query = qq|
  1067. INSERT INTO acc_trans
  1068. (trans_id, chart_id, amount,
  1069. transdate)
  1070. VALUES (?, (SELECT id FROM chart
  1071. WHERE accno = ?),
  1072. ?, ?)|;
  1073. $sth = $dbh->prepare($query);
  1074. $sth->execute( $form->{id}, $form->{AR}, $amount,
  1075. $form->{"datepaid_$i"} )
  1076. || $form->dberror($query);
  1077. }
  1078. # record payment
  1079. $amount = $form->{"paid_$i"} * -1;
  1080. if ($keepcleared) {
  1081. $cleared = ( $form->{"cleared_$i"} ) ? 1 : 0;
  1082. }
  1083. $query = qq|
  1084. INSERT INTO acc_trans
  1085. (trans_id, chart_id, amount,
  1086. transdate, source, memo, cleared)
  1087. VALUES (?, (SELECT id FROM chart
  1088. WHERE accno = ?),
  1089. ?, ?, ?, ?, ?)|;
  1090. $sth = $dbh->prepare($query);
  1091. $sth->execute( $form->{id}, $accno, $amount, $form->{"datepaid_$i"},
  1092. $form->{"source_$i"}, $form->{"memo_$i"}, $cleared )
  1093. || $form->dberror($query);
  1094. # exchangerate difference
  1095. $amount = $form->round_amount(
  1096. (
  1097. $form->round_amount(
  1098. $form->{"paid_$i"} * $form->{"exchangerate_$i"} -
  1099. $form->{"paid_$i"},
  1100. 2
  1101. )
  1102. ) * -1,
  1103. 2
  1104. );
  1105. if ($amount) {
  1106. $query = qq|
  1107. INSERT INTO acc_trans
  1108. (trans_id, chart_id, amount,
  1109. transdate, source,
  1110. fx_transaction, cleared)
  1111. VALUES (?, (SELECT id FROM chart
  1112. WHERE accno = >),
  1113. ?, ?, ?, '1', ?)|;
  1114. $sth = $dbh->prepare($query);
  1115. $sth->execute( $form->{id}, $accno, $amount,
  1116. $form->{"datepaid_$i"},
  1117. $form->{"source_$i"}, $cleared )
  1118. || $form->dberror($query);
  1119. }
  1120. # gain/loss
  1121. $amount = $form->round_amount(
  1122. (
  1123. $form->round_amount(
  1124. $form->{"paid_$i"} * $form->{exchangerate}, 2 ) -
  1125. $form->round_amount(
  1126. $form->{"paid_$i"} * $form->{"exchangerate_$i"}, 2
  1127. )
  1128. ) * -1,
  1129. 2
  1130. );
  1131. if ($amount) {
  1132. my $accno_id =
  1133. ( $amount > 0 )
  1134. ? $fxgain_accno_id
  1135. : $fxloss_accno_id;
  1136. $query = qq|
  1137. INSERT INTO acc_trans (
  1138. trans_id, chart_id, amount,
  1139. transdate, fx_transaction,
  1140. cleared)
  1141. VALUES (?, ?, ?, ?, '1', ?)|;
  1142. $sth = $dbh->prepare($query);
  1143. $sth->execute( $form->{id}, $accno_id, $amount,
  1144. $form->{"datepaid_$i"}, $cleared )
  1145. || $form->dberror($query);
  1146. }
  1147. # update exchange rate
  1148. if ( ( $form->{currency} ne $form->{defaultcurrency} )
  1149. && !$exchangerate )
  1150. {
  1151. $form->update_exchangerate(
  1152. $dbh, $form->{currency},
  1153. $form->{"datepaid_$i"},
  1154. $form->{"exchangerate_$i"}, 0
  1155. );
  1156. }
  1157. }
  1158. }
  1159. # set values which could be empty to 0
  1160. $form->{terms} *= 1;
  1161. $form->{taxincluded} *= 1;
  1162. # save AR record
  1163. $query = qq|
  1164. UPDATE ar set
  1165. invnumber = ?,
  1166. ordnumber = ?,
  1167. quonumber = ?,
  1168. transdate = ?,
  1169. entity_credit_account = ?,
  1170. amount = ?,
  1171. netamount = ?,
  1172. paid = ?,
  1173. datepaid = ?,
  1174. duedate = ?,
  1175. invoice = '1',
  1176. shippingpoint = ?,
  1177. shipvia = ?,
  1178. terms = ?,
  1179. notes = ?,
  1180. intnotes = ?,
  1181. taxincluded = ?,
  1182. curr = ?,
  1183. department_id = ?,
  1184. person_id = ?,
  1185. till = ?,
  1186. language_code = ?,
  1187. ponumber = ?
  1188. WHERE id = ?
  1189. |;
  1190. $sth = $dbh->prepare($query);
  1191. $sth->execute(
  1192. $form->{invnumber}, $form->{ordnumber},
  1193. $form->{quonumber}, $form->{transdate} || 'now',
  1194. $form->{customer_id}, $invamount,
  1195. $invnetamount, $form->{paid},
  1196. $form->{datepaid} || 'now', $form->{duedate} || 'now',
  1197. $form->{shippingpoint}, $form->{shipvia},
  1198. $form->{terms}, $form->{notes},
  1199. $form->{intnotes}, $form->{taxincluded},
  1200. $form->{currency}, $form->{department_id},
  1201. $form->{employee_id}, $form->{till},
  1202. $form->{language_code}, $form->{ponumber},
  1203. $form->{id}
  1204. ) || $form->dberror($query);
  1205. # add shipto
  1206. $form->{name} = $form->{customer};
  1207. $form->{name} =~ s/--$form->{customer_id}//;
  1208. $form->add_shipto( $dbh, $form->{id} );
  1209. # save printed, emailed and queued
  1210. $form->save_status($dbh);
  1211. my %audittrail = (
  1212. tablename => 'ar',
  1213. reference => $form->{invnumber},
  1214. formname => $form->{type},
  1215. action => 'posted',
  1216. id => $form->{id}
  1217. );
  1218. $form->audittrail( $dbh, "", \%audittrail );
  1219. $form->save_recurring( $dbh, $myconfig );
  1220. my $rc = $dbh->commit;
  1221. $rc;
  1222. }
  1223. sub process_assembly {
  1224. my ( $dbh2, $form, $id, $totalqty, $project_id ) = @_;
  1225. my $dbh = $form->{dbh};
  1226. my $query = qq|
  1227. SELECT a.parts_id, a.qty, p.assembly,
  1228. p.partnumber, p.description, p.unit,
  1229. p.inventory_accno_id, p.income_accno_id,
  1230. p.expense_accno_id
  1231. FROM assembly a
  1232. JOIN parts p ON (a.parts_id = p.id)
  1233. WHERE a.id = ?|;
  1234. my $sth = $dbh->prepare($query);
  1235. $sth->execute($id) || $form->dberror($query);
  1236. my $allocated;
  1237. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1238. $allocated = 0;
  1239. $ref->{inventory_accno_id} *= 1;
  1240. $ref->{expense_accno_id} *= 1;
  1241. # multiply by number of assemblies
  1242. $ref->{qty} *= $totalqty;
  1243. if ( $ref->{assembly} ) {
  1244. &process_assembly( $dbh, $form, $ref->{parts_id}, $ref->{qty},
  1245. $project_id );
  1246. next;
  1247. }
  1248. else {
  1249. if ( $ref->{inventory_accno_id} ) {
  1250. $allocated =
  1251. &cogs( $dbh, $form, $ref->{parts_id}, $ref->{qty},
  1252. $project_id );
  1253. }
  1254. }
  1255. $query = qq|
  1256. INSERT INTO invoice
  1257. (trans_id, description, parts_id, qty,
  1258. sellprice, fxsellprice, allocated,
  1259. assemblyitem, unit)
  1260. VALUES (?, ?, ?, ?, 0, 0, ?, 't', ?)|;
  1261. my $sth = $dbh->prepare($query);
  1262. $sth->execute( $form->{id}, $ref->{description}, $ref->{parts_id},
  1263. $ref->{qty}, $allocated, $ref->{unit} )
  1264. || $form->dberror($query);
  1265. }
  1266. $sth->finish;
  1267. }
  1268. sub cogs {
  1269. # This is nearly entirely rewritten since 1.2.8 based in part on the works
  1270. # of Victor Sterpu and Dieter Simader (see CONTRIBUTORS for more
  1271. # information). However, there are a number of areas where I have
  1272. # substantially rewritten the logic. This function is heavily annotated
  1273. # largely because COGS/invoices are still scheduled to be re-engineered in
  1274. # 1.4 so it is a good idea to have records of opinions in the code.-- CT
  1275. my ( $dbh2, $form, $id, $totalqty, $project_id, $sellprice) = @_;
  1276. my $dbh = $form->{dbh};
  1277. my $query;
  1278. my $allocated = 0;
  1279. if ($totalqty == 0) {
  1280. return 0;
  1281. }
  1282. elsif ($totalqty > 0) {
  1283. # If the quantity is positive, we do a standard FIFO COGS calculation.
  1284. # In this case, we are going to order the queue by transdate and trans_id
  1285. # as this is the best way of doing this perpetually. We don't want out
  1286. # of order entry to screw with the books. Of course if someone wants to
  1287. # implement LIFO, this would be the place to do it. -- CT
  1288. my $query = qq|
  1289. SELECT i.id, i.trans_id, i.qty, i.allocated, i.sellprice,
  1290. i.fxsellprice, p.inventory_accno_id,
  1291. p.expense_accno_id,
  1292. (i.qty * -1) - i.allocated AS available
  1293. FROM invoice i
  1294. JOIN parts p ON (i.parts_id = p.id)
  1295. JOIN ap a ON (i.trans_id = a.id)
  1296. WHERE i.parts_id = ? AND (i.qty + i.allocated) < 0
  1297. ORDER BY a.transdate, i.trans_id|;
  1298. my $sth = $dbh->prepare($query);
  1299. $sth->execute($id) || $form->dberror($query);
  1300. my $qty;
  1301. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1302. $form->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1303. if ( $ref->{available} >= $totalqty ) {
  1304. $qty = $totalqty;
  1305. }
  1306. else {
  1307. $qty = $ref->{available};
  1308. }
  1309. $form->update_balance( $dbh, "invoice", "allocated",
  1310. qq|id = $ref->{id}|, $qty );
  1311. # total expenses and inventory
  1312. # sellprice is the cost of the item
  1313. my $linetotal = $form->round_amount($ref->{sellprice} * $qty, 2);
  1314. # add expense
  1315. push @{ $form->{acc_trans}{lineitems} },
  1316. {
  1317. chart_id => $ref->{expense_accno_id},
  1318. amount => $linetotal * -1,
  1319. project_id => $project_id,
  1320. invoice_id => $ref->{id}
  1321. };
  1322. # deduct inventory
  1323. push @{ $form->{acc_trans}{lineitems} },
  1324. {
  1325. chart_id => $ref->{inventory_accno_id},
  1326. amount => $linetotal,
  1327. project_id => $project_id,
  1328. invoice_id => $ref->{id}
  1329. };
  1330. # subtract from allocated
  1331. $allocated -= $qty;
  1332. last if ( ( $totalqty -= $qty ) <= 0 );
  1333. }
  1334. $sth->finish;
  1335. }
  1336. else {
  1337. # In this case, the quantity is negative. So we are looking at a
  1338. # reversing entry for partial COGS. The two workflows supported here
  1339. # are those involved in voiding an invoice or returning some items on it.
  1340. # If there are unallocated items for the current invoice at the end, we
  1341. # will throw an error until we have an understanding of other workflows
  1342. # that need to be supported. -- CT
  1343. #
  1344. # Note: Victor's original patch selected items to reverse based on
  1345. # sell price. This causes issues with restocking fees and the like so
  1346. # I am removing that restriction. This should be discussed more fully
  1347. # however. -- CT
  1348. $query = qq|
  1349. SELECT i.id, i.qty, i.allocated, a.transdate,
  1350. -1 * (i.allocated + i.qty) AS available,
  1351. p.expense_accno_id, p.inventory_accno_id
  1352. FROM invoice i
  1353. JOIN parts p ON (p.id = i.parts_id)
  1354. JOIN ar a ON (a.id = i.trans_id)
  1355. WHERE i.parts_id = ? AND (i.qty + i.allocated) > 0
  1356. ORDER BY transdate
  1357. |;
  1358. $sth = $dbh->prepare($query);
  1359. $sth->execute($id) || $form->dberror($query);
  1360. my $qty;
  1361. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1362. $form->db_parse_numeric(sth=>$sth, hashref => $ref);
  1363. if ($totalqty < $ref->{available}){
  1364. $qty = $ref->{available};
  1365. } else {
  1366. $qty = $totalqty;
  1367. }
  1368. # update allocated for sold item
  1369. $form->update_balance(
  1370. $dbh, "invoice", "allocated",
  1371. qq|id = $ref->{id}|, $qty
  1372. );
  1373. # Note: No COGS calculations on reversed short sale invoices.
  1374. # This merely prevents COGS calculations in the future agaisnt
  1375. # such short invoices. -- CT
  1376. $totalqty -= $qty;
  1377. $allocated -= $qty;
  1378. last if $totalqty == 0;
  1379. }
  1380. # If the total quantity is still less than zero, we must assume that
  1381. # this is just an invoice which has been voided or products returns
  1382. # but is not merely representing a voided short sale, and therefore
  1383. # we need to unallocate the items from AP. There has been some debate
  1384. # as to how to approach this, and I think it is safest to unallocate
  1385. # the most recently allocated AP items of the same type regardless of
  1386. # the relevant dates of the invoices. I can see cases where this
  1387. # might require adjustments, however. -- CT
  1388. if ($totalqty < 0){
  1389. $query = qq|
  1390. SELECT i.allocated, i.sellprice, p.inventory_accno_id,
  1391. p.expense_accno_id, i.id
  1392. FROM invoice i
  1393. JOIN parts p ON (i.parts_id = p.id)
  1394. JOIN ap a ON (i.trans_id = a.id)
  1395. WHERE allocated > 0
  1396. AND i.parts_id = ?
  1397. ORDER BY a.transdate DESC, a.id DESC
  1398. |;
  1399. my $sth = $dbh->prepare($query);
  1400. $sth->execute($id);
  1401. while (my $ref = $sth->fetchrow_hashref(NAME_lc)){
  1402. my $qty = $ref->{allocated} * -1;
  1403. $qty = ($qty < $totalqty) ? $totalqty : $qty;
  1404. my $linetotal = $qty*$ref->{sellprice};
  1405. push @{ $form->{acc_trans}{lineitems} },
  1406. {
  1407. chart_id => $ref->{expense_accno_id},
  1408. amount => $linetotal,
  1409. project_id => $project_id,
  1410. invoice_id => $ref->{id}
  1411. };
  1412. push @{ $form->{acc_trans}{lineitems} },
  1413. {
  1414. chart_id => $ref->{inventory_accno_id},
  1415. amount => -$linetotal,
  1416. project_id => $project_id,
  1417. invoice_id => $ref->{id}
  1418. };
  1419. $form->update_balance(
  1420. $dbh, "invoice", "allocated",
  1421. qq|id = $ref->{id}|, $qty
  1422. );
  1423. $totalqty -= $qty;
  1424. $allocated -= $qty;
  1425. last if $totalqty == 0;
  1426. }
  1427. }
  1428. # If we still have less than 0 total quantity, this is not a return
  1429. # or a void. Throw an error. If there are valid workflows that throw
  1430. # this error, they will require more work to address and will not work
  1431. # safely with the current system. -- CT
  1432. if ($totalqty < 0){
  1433. $form->error("Too many reversed items on an invoice");
  1434. }
  1435. elsif ($totalqty > 0){
  1436. $form->error("Unexpected and invalid quantity allocated.".
  1437. " Aborting.");
  1438. }
  1439. }
  1440. return $allocated;
  1441. }
  1442. sub reverse_invoice {
  1443. my ( $dbh2, $form ) = @_;
  1444. my $dbh = $form->{dbh};
  1445. my $query = qq|
  1446. SELECT id FROM ar
  1447. WHERE id = ?|;
  1448. my $sth;
  1449. $sth = $dbh->prepare($query);
  1450. $sth->execute( $form->{id} );
  1451. my ($id) = $sth->fetchrow_array;
  1452. return unless $id;
  1453. # reverse inventory items
  1454. my $query = qq|
  1455. SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly,
  1456. p.inventory_accno_id
  1457. FROM invoice i
  1458. JOIN parts p ON (i.parts_id = p.id)
  1459. WHERE i.trans_id = ?|;
  1460. my $sth = $dbh->prepare($query);
  1461. $sth->execute( $form->{id} ) || $form->dberror($query);
  1462. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1463. if ( $ref->{inventory_accno_id} || $ref->{assembly} ) {
  1464. # if the invoice item is not an assemblyitem
  1465. # adjust parts onhand
  1466. if ( !$ref->{assemblyitem} ) {
  1467. # adjust onhand in parts table
  1468. $form->update_balance( $dbh, "parts", "onhand",
  1469. qq|id = $ref->{parts_id}|,
  1470. $ref->{qty} );
  1471. }
  1472. # loop if it is an assembly
  1473. next if ( $ref->{assembly} );
  1474. # de-allocated purchases
  1475. $query = qq|
  1476. SELECT id, trans_id, allocated
  1477. FROM invoice
  1478. WHERE parts_id = ?
  1479. AND allocated > 0
  1480. ORDER BY trans_id DESC|;
  1481. my $sth = $dbh->prepare($query);
  1482. $sth->execute( $ref->{parts_id} )
  1483. || $form->dberror($query);
  1484. while ( my $inhref = $sth->fetchrow_hashref(NAME_lc) ) {
  1485. $qty = $ref->{qty};
  1486. if ( ( $ref->{qty} - $inhref->{allocated} ) > 0 ) {
  1487. $qty = $inhref->{allocated};
  1488. }
  1489. # update invoice
  1490. $form->update_balance( $dbh, "invoice", "allocated",
  1491. qq|id = $inhref->{id}|,
  1492. $qty * -1 );
  1493. last if ( ( $ref->{qty} -= $qty ) <= 0 );
  1494. }
  1495. $sth->finish;
  1496. }
  1497. }
  1498. $sth->finish;
  1499. # delete acc_trans
  1500. $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
  1501. $sth = $dbh->prepare($query);
  1502. $sth->execute( $form->{id} ) || $form->dberror($query);
  1503. # delete invoice entries
  1504. $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
  1505. $sth = $dbh->prepare($query);
  1506. $sth->execute( $form->{id} ) || $form->dberror($query);
  1507. $query = qq|DELETE FROM shipto WHERE trans_id = ?|;
  1508. $sth = $dbh->prepare($query);
  1509. $sth->execute( $form->{id} ) || $form->dberror($query);
  1510. $dbh->commit;
  1511. }
  1512. sub delete_invoice {
  1513. my ( $self, $myconfig, $form ) = @_;
  1514. my $dbh = $form->{dbh};
  1515. my $sth;
  1516. &reverse_invoice( $dbh, $form );
  1517. my %audittrail = (
  1518. tablename => 'ar',
  1519. reference => $form->{invnumber},
  1520. formname => $form->{type},
  1521. action => 'deleted',
  1522. id => $form->{id}
  1523. );
  1524. $form->audittrail( $dbh, "", \%audittrail );
  1525. # delete AR record
  1526. my $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
  1527. $sth = $dbh->prepare($query);
  1528. $sth->execute( $form->{id} ) || $form->dberror($query);
  1529. $sth->finish;
  1530. $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
  1531. $sth = $dbh->prepare($query);
  1532. $sth->execute( $form->{id} ) || $form->dberror($query);
  1533. $sth->finish;
  1534. $query = qq|DELETE FROM ar WHERE id = ?|;
  1535. $sth = $dbh->prepare($query);
  1536. $sth->execute( $form->{id} ) || $form->dberror($query);
  1537. $sth->finish;
  1538. # delete spool files
  1539. $query = qq|
  1540. SELECT spoolfile FROM status
  1541. WHERE trans_id = ? AND spoolfile IS NOT NULL|;
  1542. $sth = $dbh->prepare($query);
  1543. $sth->execute( $form->{id} ) || $form->dberror($query);
  1544. my $spoolfile;
  1545. my @spoolfiles = ();
  1546. while ( ($spoolfile) = $sth->fetchrow_array ) {
  1547. push @spoolfiles, $spoolfile;
  1548. }
  1549. $sth->finish;
  1550. # delete status entries
  1551. $query = qq|DELETE FROM status WHERE trans_id = ?|;
  1552. $sth = $dbh->prepare($query);
  1553. $sth->execute( $form->{id} ) || $form->dberror($query);
  1554. my $rc = $dbh->commit;
  1555. if ($rc) {
  1556. foreach $spoolfile (@spoolfiles) {
  1557. unlink "${LedgerSMB::Sysconfig::spool}/$spoolfile"
  1558. if $spoolfile;
  1559. }
  1560. }
  1561. $rc;
  1562. }
  1563. sub retrieve_invoice {
  1564. my ( $self, $myconfig, $form ) = @_;
  1565. my $dbh = $form->{dbh};
  1566. my $query;
  1567. if ( $form->{id} ) {
  1568. # get default accounts and last invoice number
  1569. $query = qq|
  1570. SELECT value AS currencies FROM defaults
  1571. WHERE setting_key = 'curr'|;
  1572. }
  1573. else {
  1574. $query = qq|
  1575. SELECT value AS currencies, current_date AS transdate
  1576. FROM defaults
  1577. WHERE setting_key = 'curr'|;
  1578. }
  1579. my $sth = $dbh->prepare($query);
  1580. $sth->execute || $form->dberror($query);
  1581. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1582. for ( keys %$ref ) { $form->{$_} = $ref->{$_} }
  1583. $sth->finish;
  1584. if ( $form->{id} ) {
  1585. # retrieve invoice
  1586. $query = qq|
  1587. SELECT a.invnumber, a.ordnumber, a.quonumber,
  1588. a.transdate, a.paid,
  1589. a.shippingpoint, a.shipvia, a.terms, a.notes,
  1590. a.intnotes,
  1591. a.duedate, a.taxincluded, a.curr AS currency,
  1592. a.person_id, e.name AS employee, a.till,
  1593. a.entity_id, a.reverse,
  1594. a.language_code, a.ponumber,
  1595. a.on_hold
  1596. FROM ar a
  1597. LEFT JOIN employee em ON (em.entity_id = a.person_id)
  1598. INNER JOIN entity e ON e.id = em.entity_id
  1599. WHERE a.id = ?|;
  1600. $sth = $dbh->prepare($query);
  1601. $sth->execute( $form->{id} ) || $form->dberror($query);
  1602. $ref = $sth->fetchrow_hashref(NAME_lc);
  1603. $form->db_parse_numeric(sth=> $sth, hashref=>$ref_);
  1604. for ( keys %$ref ) { $form->{$_} = $ref->{$_} }
  1605. $sth->finish;
  1606. # get shipto
  1607. $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
  1608. $sth = $dbh->prepare($query);
  1609. $sth->execute( $form->{id} ) || $form->dberror($query);
  1610. $ref = $sth->fetchrow_hashref(NAME_lc);
  1611. for ( keys %$ref ) { $form->{$_} = $ref->{$_} }
  1612. $sth->finish;
  1613. # retrieve individual items
  1614. $query = qq|
  1615. SELECT i.description, i.qty, i.fxsellprice,
  1616. i.sellprice, i.discount, i.parts_id AS id,
  1617. i.unit, i.deliverydate, i.project_id,
  1618. pr.projectnumber, i.serialnumber, i.notes,
  1619. p.partnumber, p.assembly, p.bin,
  1620. pg.partsgroup, p.partsgroup_id,
  1621. p.partnumber AS sku, p.listprice, p.lastcost,
  1622. p.weight, p.onhand, p.inventory_accno_id,
  1623. p.income_accno_id, p.expense_accno_id,
  1624. t.description AS partsgrouptranslation
  1625. FROM invoice i
  1626. JOIN parts p ON (i.parts_id = p.id)
  1627. LEFT JOIN project pr ON (i.project_id = pr.id)
  1628. LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
  1629. LEFT JOIN translation t
  1630. ON (t.trans_id = p.partsgroup_id
  1631. AND t.language_code
  1632. = ?)
  1633. WHERE i.trans_id = ?
  1634. AND NOT i.assemblyitem = '1'
  1635. ORDER BY i.id|;
  1636. $sth = $dbh->prepare($query);
  1637. $sth->execute( $form->{language_code}, $form->{id} )
  1638. || $form->dberror($query);
  1639. # foreign currency
  1640. &exchangerate_defaults( $dbh, $form );
  1641. # query for price matrix
  1642. my $pmh = PriceMatrix::price_matrix_query( $dbh, $form );
  1643. # taxes
  1644. $query = qq|
  1645. SELECT c.accno
  1646. FROM chart c
  1647. JOIN partstax pt ON (pt.chart_id = c.id)
  1648. WHERE pt.parts_id = ?|;
  1649. my $tth = $dbh->prepare($query) || $form->dberror($query);
  1650. my $taxrate;
  1651. my $ptref;
  1652. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1653. $form->db_parse_numeric(sth=>$sth, hashref => $ref);
  1654. $ref->{qty} *= -1 if $form->{reverse};
  1655. my ($dec) = ( $ref->{fxsellprice} =~ /\.(\d+)/ );
  1656. $dec = length $dec;
  1657. my $decimalplaces = ( $dec > 2 ) ? $dec : 2;
  1658. $tth->execute( $ref->{id} );
  1659. $ref->{taxaccounts} = "";
  1660. $taxrate = 0;
  1661. while ( $ptref = $tth->fetchrow_hashref(NAME_lc) ) {
  1662. $ref->{taxaccounts} .= "$ptref->{accno} ";
  1663. $taxrate += $form->{"$ptref->{accno}_rate"};
  1664. }
  1665. $tth->finish;
  1666. chop $ref->{taxaccounts};
  1667. # price matrix
  1668. $ref->{sellprice} =
  1669. ( $ref->{fxsellprice} * $form->{ $form->{currency} } );
  1670. PriceMatrix::price_matrix( $pmh, $ref, $form->{transdate},
  1671. $decimalplaces, $form, $myconfig );
  1672. $ref->{sellprice} = $ref->{fxsellprice};
  1673. $ref->{partsgroup} = $ref->{partsgrouptranslation}
  1674. if $ref->{partsgrouptranslation};
  1675. push @{ $form->{invoice_details} }, $ref;
  1676. }
  1677. $sth->finish;
  1678. }
  1679. @queries = $form->run_custom_queries( 'ar', 'SELECT' );
  1680. my $rc = $dbh->commit;
  1681. $rc;
  1682. }
  1683. sub retrieve_item {
  1684. my ( $self, $myconfig, $form ) = @_;
  1685. my $dbh = $form->{dbh};
  1686. my $i = $form->{rowcount};
  1687. my $null;
  1688. my $var;
  1689. my $where = "WHERE p.obsolete = '0' AND NOT p.income_accno_id IS NULL";
  1690. if ( $form->{"partnumber_$i"} ne "" ) {
  1691. $var = $dbh->quote( $form->like( lc $form->{"partnumber_$i"} ) );
  1692. $where .= " AND lower(p.partnumber) LIKE $var";
  1693. }
  1694. if ( $form->{"description_$i"} ne "" ) {
  1695. $var = $dbh->quote( $form->like( lc $form->{"description_$i"} ) );
  1696. if ( $form->{language_code} ne "" ) {
  1697. $where .= " AND lower(t1.description) LIKE $var";
  1698. }
  1699. else {
  1700. $where .= " AND lower(p.description) LIKE $var";
  1701. }
  1702. }
  1703. if ( $form->{"partsgroup_$i"} ne "" ) {
  1704. ( $null, $var ) = split /--/, $form->{"partsgroup_$i"};
  1705. if ( ! $var ) {
  1706. # search by partsgroup, this is for the POS
  1707. $where .=
  1708. qq| AND pg.partsgroup = |
  1709. . $dbh->quote( $form->{"partsgroup_$i"} );
  1710. }
  1711. else {
  1712. $var = $dbh->quote($var);
  1713. $where .= qq| AND p.partsgroup_id = $var|;
  1714. }
  1715. }
  1716. if ( $form->{"description_$i"} ne "" ) {
  1717. $where .= " ORDER BY 3";
  1718. }
  1719. else {
  1720. $where .= " ORDER BY 2";
  1721. }
  1722. my $query = qq|
  1723. SELECT p.id, p.partnumber, p.description, p.sellprice,
  1724. p.listprice, p.lastcost, p.unit, p.assembly, p.bin,
  1725. p.onhand, p.notes, p.inventory_accno_id,
  1726. p.income_accno_id, p.expense_accno_id, pg.partsgroup,
  1727. p.partsgroup_id, p.partnumber AS sku, p.weight,
  1728. t1.description AS translation,
  1729. t2.description AS grouptranslation
  1730. FROM parts p
  1731. LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
  1732. LEFT JOIN translation t1
  1733. ON (t1.trans_id = p.id AND t1.language_code = ?)
  1734. LEFT JOIN translation t2
  1735. ON (t2.trans_id = p.partsgroup_id
  1736. AND t2.language_code = ?)
  1737. $where|;
  1738. my $sth = $dbh->prepare($query);
  1739. $sth->execute( $form->{language_code}, $form->{language_code} )
  1740. || $form->dberror($query);
  1741. my $ref;
  1742. my $ptref;
  1743. # setup exchange rates
  1744. &exchangerate_defaults( $dbh, $form );
  1745. # taxes
  1746. $query = qq|
  1747. SELECT c.accno
  1748. FROM chart c
  1749. JOIN partstax pt ON (c.id = pt.chart_id)
  1750. WHERE pt.parts_id = ?|;
  1751. my $tth = $dbh->prepare($query) || $form->dberror($query);
  1752. # price matrix
  1753. my $pmh = PriceMatrix::price_matrix_query( $dbh, $form );
  1754. my $transdate = $form->datetonum( $myconfig, $form->{transdate} );
  1755. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1756. $form->db_parse_numeric(sth => $sth, hashref => $ref);
  1757. my ($dec) = ( $ref->{sellprice} =~ /\.(\d+)/ );
  1758. $dec = length $dec;
  1759. my $decimalplaces = ( $dec > 2 ) ? $dec : 2;
  1760. # get taxes for part
  1761. $tth->execute( $ref->{id} );
  1762. $ref->{taxaccounts} = "";
  1763. while ( $ptref = $tth->fetchrow_hashref(NAME_lc) ) {
  1764. $ref->{taxaccounts} .= "$ptref->{accno} ";
  1765. }
  1766. $tth->finish;
  1767. chop $ref->{taxaccounts};
  1768. # get matrix
  1769. PriceMatrix::price_matrix( $pmh, $ref, $transdate, $decimalplaces,
  1770. $form, $myconfig );
  1771. $ref->{description} = $ref->{translation}
  1772. if $ref->{translation};
  1773. $ref->{partsgroup} = $ref->{grouptranslation}
  1774. if $ref->{grouptranslation};
  1775. push @{ $form->{item_list} }, $ref;
  1776. }
  1777. $sth->finish;
  1778. }
  1779. sub exchangerate_defaults {
  1780. my ( $dbh2, $form ) = @_;
  1781. $dbh = $form->{dbh};
  1782. my $var;
  1783. # get default currencies
  1784. my $query = qq|
  1785. SELECT substr(value,1,3), value FROM defaults
  1786. WHERE setting_key = 'curr'|;
  1787. my $eth = $dbh->prepare($query) || $form->dberror($query);
  1788. $eth->execute;
  1789. ( $form->{defaultcurrency}, $form->{currencies} ) = $eth->fetchrow_array;
  1790. $eth->finish;
  1791. $query = qq|
  1792. SELECT buy
  1793. FROM exchangerate
  1794. WHERE curr = ?
  1795. AND transdate = ?|;
  1796. my $eth1 = $dbh->prepare($query) || $form->dberror($query);
  1797. $query = qq/
  1798. SELECT max(transdate || ' ' || buy || ' ' || curr)
  1799. FROM exchangerate
  1800. WHERE curr = ?/;
  1801. my $eth2 = $dbh->prepare($query) || $form->dberror($query);
  1802. # get exchange rates for transdate or max
  1803. foreach $var ( split /:/, substr( $form->{currencies}, 4 ) ) {
  1804. $eth1->execute( $var, $form->{transdate} );
  1805. ( $form->{$var} ) = $eth1->fetchrow_array;
  1806. if ( !$form->{$var} ) {
  1807. $eth2->execute($var);
  1808. ( $form->{$var} ) = $eth2->fetchrow_array;
  1809. ( $null, $form->{$var} ) = split / /, $form->{$var};
  1810. $form->{$var} = 1 unless $form->{$var};
  1811. $eth2->finish;
  1812. }
  1813. $eth1->finish;
  1814. }
  1815. $form->{ $form->{currency} } = $form->{exchangerate}
  1816. if $form->{exchangerate};
  1817. $form->{ $form->{currency} } ||= 1;
  1818. $form->{ $form->{defaultcurrency} } = 1;
  1819. }
  1820. =pod
  1821. =cut
  1822. sub toggle_on_hold {
  1823. my $self = shift @_;
  1824. my $form = shift @_;
  1825. if ($form->{id}) { # it's an existing (.. probably) invoice.
  1826. my $dbh = $form->{dbh};
  1827. my $sth = $dbh->prepare("SELECT on_hold from ar where ar.id = ?");
  1828. $sth->execute($form->{id});
  1829. my $state = $sth->fetchrow_array;
  1830. my $sth;
  1831. my $n_s; # new state
  1832. if ($state[0] == 't') {
  1833. # Turn it off
  1834. $n_s = 'f';
  1835. } else {
  1836. $n_s = 't';
  1837. }
  1838. my $sth = $dbh->prepare("update ar set on_hold = ?::boolean where ar.id = ?");
  1839. my $code = $dbh->execute($ns, $form->{id});
  1840. return 1;
  1841. } else { # This shouldn't even be possible, but check for it anyway.
  1842. # Definitely, DEFINITELY check it.
  1843. # happily return 0. Find out about proper error states.
  1844. return 0;
  1845. }
  1846. }
  1847. 1;