summaryrefslogtreecommitdiff
path: root/LedgerSMB/IS.pm
blob: 78819ea4a2bf6cfd82304c3c21d24ecce07fce63 (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_province 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. ( $null, $form->{employee_id} ) = split /--/, $form->{employee};
  672. unless ( $form->{employee_id} ) {
  673. ( $form->{employee}, $form->{employee_id} ) = $form->get_employee($dbh);
  674. }
  675. ( $null, $form->{department_id} ) = split( /--/, $form->{department} );
  676. $form->{department_id} *= 1;
  677. $query = qq|
  678. SELECT (SELECT value FROM defaults
  679. WHERE setting_key = 'fxgain_accno_id')
  680. AS fxgain_accno_id,
  681. (SELECT value FROM defaults
  682. WHERE setting_key = 'fxloss_accno_id')
  683. AS fxloss_accno_id|;
  684. my ( $fxgain_accno_id, $fxloss_accno_id ) = $dbh->selectrow_array($query);
  685. $query = qq|
  686. SELECT p.assembly, p.inventory_accno_id,
  687. p.income_accno_id, p.expense_accno_id, p.project_id
  688. FROM parts p
  689. WHERE p.id = ?|;
  690. my $pth = $dbh->prepare($query) || $form->dberror($query);
  691. if ( $form->{id} ) {
  692. $keepcleared = 1;
  693. $query = qq|SELECT id FROM ar WHERE id = ?|;
  694. $sth = $dbh->prepare($query);
  695. $sth->execute( $form->{id} );
  696. if ( $sth->fetchrow_array ) {
  697. &reverse_invoice( $dbh, $form );
  698. }
  699. else {
  700. $query = qq|INSERT INTO ar (id) VALUES (?)|;
  701. $sth = $dbh->prepare($query);
  702. $sth->execute( $form->{id} ) || $form->dberror($query);
  703. }
  704. }
  705. my $uid = localtime;
  706. $uid .= "$$";
  707. if ( !$form->{id} ) {
  708. $query = qq|
  709. INSERT INTO ar (invnumber, person_id)
  710. VALUES ('$uid', ?)|;
  711. $sth = $dbh->prepare($query);
  712. $sth->execute( $form->{employee_id} ) || $form->dberror($query);
  713. $query = qq|SELECT id FROM ar WHERE invnumber = '$uid'|;
  714. $sth = $dbh->prepare($query);
  715. $sth->execute || $form->dberror($query);
  716. ( $form->{id} ) = $sth->fetchrow_array;
  717. $sth->finish;
  718. @queries = $form->run_custom_queries( 'ar', 'INSERT' );
  719. }
  720. if ( $form->{currency} eq $form->{defaultcurrency} ) {
  721. $form->{exchangerate} = 1;
  722. }
  723. else {
  724. $exchangerate =
  725. $form->check_exchangerate( $myconfig, $form->{currency},
  726. $form->{transdate}, 'buy' );
  727. }
  728. $form->{exchangerate} =
  729. ($exchangerate)
  730. ? $exchangerate
  731. : $form->parse_amount( $myconfig, $form->{exchangerate} );
  732. my $i;
  733. my $item;
  734. my $allocated = 0;
  735. my $taxrate;
  736. my $tax;
  737. my $fxtax;
  738. my @taxaccounts;
  739. my $amount;
  740. my $grossamount;
  741. my $invamount = 0;
  742. my $invnetamount = 0;
  743. my $diff = 0;
  744. my $ml;
  745. my $invoice_id;
  746. my $ndx;
  747. for (keys %$form) {
  748. if (UNIVERSAL::isa( $form->{$_}, 'Math::BigFloat' )){
  749. $form->{$_} = $form->{$_}->bstr();
  750. }
  751. }
  752. foreach $i ( 1 .. $form->{rowcount} ) {
  753. $form->{"qty_$i"} = $form->parse_amount( $myconfig, $form->{"qty_$i"} );
  754. if ($form->{reverse}){
  755. $form->{"qty_$i"} *= -1;
  756. }
  757. if ( $form->{"qty_$i"} ) {
  758. $pth->execute( $form->{"id_$i"} );
  759. $ref = $pth->fetchrow_hashref(NAME_lc);
  760. for ( keys %$ref ) { $form->{"${_}_$i"} = $ref->{$_} }
  761. $pth->finish;
  762. # project
  763. if ( $form->{"projectnumber_$i"} ) {
  764. ( $null, $project_id ) = split /--/,
  765. $form->{"projectnumber_$i"};
  766. }
  767. $project_id = $form->{"project_id_$i"}
  768. if $form->{"project_id_$i"};
  769. # keep entered selling price
  770. my $fxsellprice =
  771. $form->parse_amount( $myconfig, $form->{"sellprice_$i"} );
  772. my ($dec) = ( $fxsellprice =~ /\.(\d+)/ );
  773. $dec = length $dec;
  774. my $decimalplaces = ( $dec > 2 ) ? $dec : 2;
  775. # undo discount formatting
  776. $form->{"discount_$i"} =
  777. $form->parse_amount( $myconfig, $form->{"discount_$i"} ) / 100;
  778. # deduct discount
  779. $form->{"sellprice_$i"} = $fxsellprice -
  780. $form->round_amount( $fxsellprice * $form->{"discount_$i"},
  781. $decimalplaces );
  782. # linetotal
  783. my $fxlinetotal =
  784. $form->round_amount( $form->{"sellprice_$i"} * $form->{"qty_$i"},
  785. 2 );
  786. $amount = $fxlinetotal * $form->{exchangerate};
  787. my $linetotal = $form->round_amount( $amount, 2 );
  788. $fxdiff += $amount - $linetotal;
  789. @taxaccounts = Tax::init_taxes(
  790. $form,
  791. $form->{"taxaccounts_$i"},
  792. $form->{"taxaccounts"}
  793. );
  794. $ml = 1;
  795. $tax = Math::BigFloat->bzero();
  796. $fxtax = Math::BigFloat->bzero();
  797. if ( $form->{taxincluded} ) {
  798. $tax += $amount =
  799. Tax::calculate_taxes( \@taxaccounts, $form, $linetotal, 1 );
  800. $form->{"sellprice_$i"} -= $amount / $form->{"qty_$i"};
  801. $fxtax +=
  802. Tax::calculate_taxes( \@taxaccounts, $form, $linetotal, 1 );
  803. }
  804. else {
  805. $tax += $amount =
  806. Tax::calculate_taxes( \@taxaccounts, $form, $linetotal, 0 );
  807. $fxtax +=
  808. Tax::calculate_taxes( \@taxaccounts, $form, $linetotal, 0 );
  809. }
  810. for (@taxaccounts) {
  811. $form->{acc_trans}{ $form->{id} }{ $_->account }{amount} +=
  812. $_->value;
  813. }
  814. $grossamount = $form->round_amount( $linetotal, 2 );
  815. if ( $form->{taxincluded} ) {
  816. $amount = $form->round_amount( $tax, 2 );
  817. $linetotal -= $form->round_amount( $tax - $diff, 2 );
  818. $diff = ( $amount - $tax );
  819. }
  820. # add linetotal to income
  821. $amount = $form->round_amount( $linetotal, 2 );
  822. push @{ $form->{acc_trans}{lineitems} },
  823. {
  824. chart_id => $form->{"income_accno_id_$i"},
  825. amount => $amount,
  826. fxgrossamount => $fxlinetotal + $fxtax,
  827. grossamount => $grossamount,
  828. project_id => $project_id
  829. };
  830. $ndx = $#{ @{ $form->{acc_trans}{lineitems} } };
  831. $form->{"sellprice_$i"} =
  832. $form->round_amount(
  833. $form->{"sellprice_$i"} * $form->{exchangerate},
  834. $decimalplaces );
  835. if ( $form->{"inventory_accno_id_$i"}
  836. || $form->{"assembly_$i"} )
  837. {
  838. if ( $form->{"assembly_$i"} ) {
  839. # If the assembly consists of all
  840. # services, we don't keep inventory,
  841. # so we should not update it
  842. $query = qq|
  843. SELECT sum(
  844. p.inventory_accno_id),
  845. p.assembly
  846. FROM parts p
  847. JOIN assembly a
  848. ON (a.parts_id = p.id)
  849. WHERE a.id = ?
  850. GROUP BY p.assembly|;
  851. $sth = $dbh->prepare($query);
  852. $sth->execute( $form->{"id_$i"} )
  853. || $form->dberror($query);
  854. my ( $inv, $assembly ) = $sth->fetchrow_array;
  855. $sth->finish;
  856. if ( $inv || $assembly ) {
  857. $form->update_balance(
  858. $dbh, "parts", "onhand",
  859. qq|id = | . qq|$form->{"id_$i"}|,
  860. $form->{"qty_$i"} * -1
  861. ) unless $form->{shipped};
  862. }
  863. &process_assembly( $dbh, $form, $form->{"id_$i"},
  864. $form->{"qty_$i"}, $project_id );
  865. }
  866. else {
  867. $form->update_balance(
  868. $dbh, "parts", "onhand",
  869. qq|id = $form->{"id_$i"}|,
  870. $form->{"qty_$i"} * -1
  871. ) unless $form->{shipped};
  872. $allocated = cogs(
  873. $dbh, $form,
  874. $form->{"id_$i"}, $form->{"qty_$i"},
  875. $project_id, $form->{"sellprice_$i"},
  876. );
  877. }
  878. }
  879. # save detail record in invoice table
  880. $query = qq|
  881. INSERT INTO invoice (description)
  882. VALUES ('$uid')|;
  883. $dbh->do($query) || $form->dberror($query);
  884. $query = qq|
  885. SELECT id FROM invoice
  886. WHERE description = '$uid'|;
  887. ($invoice_id) = $dbh->selectrow_array($query);
  888. unless ( $form->{"deliverydate_$i"} ) {
  889. undef $form->{"deliverydate_$i"};
  890. }
  891. $query = qq|
  892. UPDATE invoice
  893. SET trans_id = ?,
  894. parts_id = ?,
  895. description = ?,
  896. qty = ?,
  897. sellprice = ?,
  898. fxsellprice = ?,
  899. discount = ?,
  900. allocated = ?,
  901. unit = ?,
  902. deliverydate = ?,
  903. project_id = ?,
  904. serialnumber = ?,
  905. notes = ?
  906. WHERE id = ?|;
  907. $sth = $dbh->prepare($query);
  908. $sth->execute(
  909. $form->{id}, $form->{"id_$i"},
  910. $form->{"description_$i"}, $form->{"qty_$i"},
  911. $form->{"sellprice_$i"}, $fxsellprice,
  912. $form->{"discount_$i"}, $allocated,
  913. $form->{"unit_$i"}, $form->{"deliverydate_$i"},
  914. $project_id, $form->{"serialnumber_$i"},
  915. $form->{"notes_$i"},
  916. $invoice_id
  917. ) || $form->dberror($query);
  918. if (defined $form->{approved}) {
  919. $query = qq| UPDATE ar SET approved = ? WHERE id = ?|;
  920. $dbh->prepare($query)->execute($form->{approved}, $form->{id})
  921. || $form->dberror($query);
  922. if (!$form->{approved}){
  923. if (not defined $form->{batch_id}){
  924. $form->error($locale->text('Batch ID Missing'));
  925. }
  926. $query = qq|
  927. INSERT INTO voucher (batch_id, trans_id) VALUES (?, ?)|;
  928. $sth = $dbh->prepare($query);
  929. $sth->execute($form->{batch_id}, $form->{id}) ||
  930. $form->dberror($query);
  931. }
  932. }
  933. # add invoice_id
  934. $form->{acc_trans}{lineitems}[$ndx]->{invoice_id} = $invoice_id;
  935. }
  936. }
  937. $form->{paid} = 0;
  938. for $i ( 1 .. $form->{paidaccounts} ) {
  939. $form->{"paid_$i"} =
  940. $form->parse_amount( $myconfig, $form->{"paid_$i"} )->bstr();
  941. $form->{paid} += $form->{"paid_$i"};
  942. $form->{datepaid} = $form->{"datepaid_$i"}
  943. if ( $form->{"paid_$i"} );
  944. }
  945. # add lineitems + tax
  946. $amount = 0;
  947. $grossamount = 0;
  948. $fxgrossamount = 0;
  949. for ( @{ $form->{acc_trans}{lineitems} } ) {
  950. $amount += $_->{amount};
  951. $grossamount += $_->{grossamount};
  952. $fxgrossamount += $_->{fxgrossamount};
  953. }
  954. $invnetamount = $amount;
  955. $amount = 0;
  956. for ( split / /, $form->{taxaccounts} ) {
  957. $amount += $form->{acc_trans}{ $form->{id} }{$_}{amount} =
  958. $form->round_amount( $form->{acc_trans}{ $form->{id} }{$_}{amount},
  959. 2 );
  960. }
  961. $invamount = $invnetamount + $amount;
  962. $diff = 0;
  963. if ( $form->{taxincluded} ) {
  964. $diff = $form->round_amount( $grossamount - $invamount, 2 );
  965. $invamount += $diff;
  966. }
  967. $fxdiff = $form->round_amount( $fxdiff, 2 );
  968. $invnetamount += $fxdiff;
  969. $invamount += $fxdiff;
  970. if ( $form->round_amount( $form->{paid} - $fxgrossamount, 2 ) == 0 ) {
  971. $form->{paid} = $invamount;
  972. }
  973. else {
  974. $form->{paid} =
  975. $form->round_amount( $form->{paid} * $form->{exchangerate}, 2 );
  976. }
  977. foreach $ref ( sort { $b->{amount} <=> $a->{amount} }
  978. @{ $form->{acc_trans}{lineitems} } )
  979. {
  980. $amount = $ref->{amount} + $diff + $fxdiff;
  981. $query = qq|
  982. INSERT INTO acc_trans
  983. (trans_id, chart_id, amount,
  984. transdate, project_id, invoice_id)
  985. VALUES (?, ?, ?, ?, ?, ?)|;
  986. $sth = $dbh->prepare($query);
  987. $sth->execute( $form->{id}, $ref->{chart_id}, $amount,
  988. $form->{transdate}, $ref->{project_id}, $ref->{invoice_id} )
  989. || $form->dberror($query);
  990. $diff = 0;
  991. $fxdiff = 0;
  992. }
  993. $form->{receivables} = $invamount * -1;
  994. delete $form->{acc_trans}{lineitems};
  995. # update exchangerate
  996. if ( ( $form->{currency} ne $form->{defaultcurrency} ) && !$exchangerate ) {
  997. $form->update_exchangerate( $dbh, $form->{currency}, $form->{transdate},
  998. $form->{exchangerate}, 0 );
  999. }
  1000. # record receivable
  1001. if ( $form->{receivables} ) {
  1002. ($accno) = split /--/, $form->{AR};
  1003. $query = qq|
  1004. INSERT INTO acc_trans
  1005. (trans_id, chart_id, amount, transdate)
  1006. VALUES (?, (SELECT id FROM chart WHERE accno = ?),
  1007. ?, ?)|;
  1008. $sth = $dbh->prepare($query);
  1009. $sth->execute( $form->{id}, $accno, $form->{receivables},
  1010. $form->{transdate} )
  1011. || $form->dberror($query);
  1012. }
  1013. foreach my $trans_id ( keys %{ $form->{acc_trans} } ) {
  1014. foreach my $accno ( keys %{ $form->{acc_trans}{$trans_id} } ) {
  1015. $amount =
  1016. $form->round_amount(
  1017. $form->{acc_trans}{$trans_id}{$accno}{amount}, 2 );
  1018. if ($amount) {
  1019. $query = qq|
  1020. INSERT INTO acc_trans
  1021. (trans_id, chart_id, amount,
  1022. transdate)
  1023. VALUES (?, (SELECT id FROM chart
  1024. WHERE accno = ?),
  1025. ?, ?)|;
  1026. $sth = $dbh->prepare($query);
  1027. $sth->execute( $trans_id, $accno, $amount, $form->{transdate} )
  1028. || $form->dberror($query);
  1029. }
  1030. }
  1031. }
  1032. # if there is no amount but a payment record receivable
  1033. if ( $invamount == 0 ) {
  1034. $form->{receivables} = 1;
  1035. }
  1036. my $cleared = 0;
  1037. # record payments and offsetting AR
  1038. for $i ( 1 .. $form->{paidaccounts} ) {
  1039. if ( $form->{"paid_$i"} ) {
  1040. my ($accno) = split /--/, $form->{"AR_paid_$i"};
  1041. $form->{"datepaid_$i"} = $form->{transdate}
  1042. unless ( $form->{"datepaid_$i"} );
  1043. $form->{datepaid} = $form->{"datepaid_$i"};
  1044. $exchangerate = 0;
  1045. if ( $form->{currency} eq $form->{defaultcurrency} ) {
  1046. $form->{"exchangerate_$i"} = 1;
  1047. }
  1048. else {
  1049. $exchangerate =
  1050. $form->check_exchangerate( $myconfig, $form->{currency},
  1051. $form->{"datepaid_$i"}, 'buy' );
  1052. $form->{"exchangerate_$i"} =
  1053. ($exchangerate)
  1054. ? $exchangerate
  1055. : $form->parse_amount( $myconfig,
  1056. $form->{"exchangerate_$i"} );
  1057. }
  1058. # record AR
  1059. $amount =
  1060. $form->round_amount( $form->{"paid_$i"} * $form->{exchangerate},
  1061. 2 );
  1062. if ( $form->{receivables} ) {
  1063. $query = qq|
  1064. INSERT INTO acc_trans
  1065. (trans_id, chart_id, amount,
  1066. transdate)
  1067. VALUES (?, (SELECT id FROM chart
  1068. WHERE accno = ?),
  1069. ?, ?)|;
  1070. $sth = $dbh->prepare($query);
  1071. $sth->execute( $form->{id}, $form->{AR}, $amount,
  1072. $form->{"datepaid_$i"} )
  1073. || $form->dberror($query);
  1074. }
  1075. # record payment
  1076. $amount = $form->{"paid_$i"} * -1;
  1077. if ($keepcleared) {
  1078. $cleared = ( $form->{"cleared_$i"} ) ? 1 : 0;
  1079. }
  1080. $query = qq|
  1081. INSERT INTO acc_trans
  1082. (trans_id, chart_id, amount,
  1083. transdate, source, memo, cleared)
  1084. VALUES (?, (SELECT id FROM chart
  1085. WHERE accno = ?),
  1086. ?, ?, ?, ?, ?)|;
  1087. $sth = $dbh->prepare($query);
  1088. $sth->execute( $form->{id}, $accno, $amount, $form->{"datepaid_$i"},
  1089. $form->{"source_$i"}, $form->{"memo_$i"}, $cleared )
  1090. || $form->dberror($query);
  1091. # exchangerate difference
  1092. $amount = $form->round_amount(
  1093. (
  1094. $form->round_amount(
  1095. $form->{"paid_$i"} * $form->{"exchangerate_$i"} -
  1096. $form->{"paid_$i"},
  1097. 2
  1098. )
  1099. ) * -1,
  1100. 2
  1101. );
  1102. if ($amount) {
  1103. $query = qq|
  1104. INSERT INTO acc_trans
  1105. (trans_id, chart_id, amount,
  1106. transdate, source,
  1107. fx_transaction, cleared)
  1108. VALUES (?, (SELECT id FROM chart
  1109. WHERE accno = >),
  1110. ?, ?, ?, '1', ?)|;
  1111. $sth = $dbh->prepare($query);
  1112. $sth->execute( $form->{id}, $accno, $amount,
  1113. $form->{"datepaid_$i"},
  1114. $form->{"source_$i"}, $cleared )
  1115. || $form->dberror($query);
  1116. }
  1117. # gain/loss
  1118. $amount = $form->round_amount(
  1119. (
  1120. $form->round_amount(
  1121. $form->{"paid_$i"} * $form->{exchangerate}, 2 ) -
  1122. $form->round_amount(
  1123. $form->{"paid_$i"} * $form->{"exchangerate_$i"}, 2
  1124. )
  1125. ) * -1,
  1126. 2
  1127. );
  1128. if ($amount) {
  1129. my $accno_id =
  1130. ( $amount > 0 )
  1131. ? $fxgain_accno_id
  1132. : $fxloss_accno_id;
  1133. $query = qq|
  1134. INSERT INTO acc_trans (
  1135. trans_id, chart_id, amount,
  1136. transdate, fx_transaction,
  1137. cleared)
  1138. VALUES (?, ?, ?, ?, '1', ?)|;
  1139. $sth = $dbh->prepare($query);
  1140. $sth->execute( $form->{id}, $accno_id, $amount,
  1141. $form->{"datepaid_$i"}, $cleared )
  1142. || $form->dberror($query);
  1143. }
  1144. # update exchange rate
  1145. if ( ( $form->{currency} ne $form->{defaultcurrency} )
  1146. && !$exchangerate )
  1147. {
  1148. $form->update_exchangerate(
  1149. $dbh, $form->{currency},
  1150. $form->{"datepaid_$i"},
  1151. $form->{"exchangerate_$i"}, 0
  1152. );
  1153. }
  1154. }
  1155. }
  1156. # set values which could be empty to 0
  1157. $form->{terms} *= 1;
  1158. $form->{taxincluded} *= 1;
  1159. # save AR record
  1160. $query = qq|
  1161. UPDATE ar set
  1162. invnumber = ?,
  1163. ordnumber = ?,
  1164. quonumber = ?,
  1165. transdate = ?,
  1166. entity_id = ?,
  1167. amount = ?,
  1168. netamount = ?,
  1169. paid = ?,
  1170. datepaid = ?,
  1171. duedate = ?,
  1172. invoice = '1',
  1173. shippingpoint = ?,
  1174. shipvia = ?,
  1175. terms = ?,
  1176. notes = ?,
  1177. intnotes = ?,
  1178. taxincluded = ?,
  1179. curr = ?,
  1180. department_id = ?,
  1181. person_id = ?,
  1182. till = ?,
  1183. language_code = ?,
  1184. ponumber = ?
  1185. WHERE id = ?
  1186. |;
  1187. $sth = $dbh->prepare($query);
  1188. $sth->execute(
  1189. $form->{invnumber}, $form->{ordnumber},
  1190. $form->{quonumber}, $form->{transdate} || 'now',
  1191. $form->{customer_id}, $invamount,
  1192. $invnetamount, $form->{paid},
  1193. $form->{datepaid} || 'now', $form->{duedate} || 'now',
  1194. $form->{shippingpoint}, $form->{shipvia},
  1195. $form->{terms}, $form->{notes},
  1196. $form->{intnotes}, $form->{taxincluded},
  1197. $form->{currency}, $form->{department_id},
  1198. $form->{employee_id}, $form->{till},
  1199. $form->{language_code}, $form->{ponumber},
  1200. $form->{id}
  1201. ) || $form->dberror($query);
  1202. # add shipto
  1203. $form->{name} = $form->{customer};
  1204. $form->{name} =~ s/--$form->{customer_id}//;
  1205. $form->add_shipto( $dbh, $form->{id} );
  1206. # save printed, emailed and queued
  1207. $form->save_status($dbh);
  1208. my %audittrail = (
  1209. tablename => 'ar',
  1210. reference => $form->{invnumber},
  1211. formname => $form->{type},
  1212. action => 'posted',
  1213. id => $form->{id}
  1214. );
  1215. $form->audittrail( $dbh, "", \%audittrail );
  1216. $form->save_recurring( $dbh, $myconfig );
  1217. my $rc = $dbh->commit;
  1218. $rc;
  1219. }
  1220. sub process_assembly {
  1221. my ( $dbh2, $form, $id, $totalqty, $project_id ) = @_;
  1222. my $dbh = $form->{dbh};
  1223. my $query = qq|
  1224. SELECT a.parts_id, a.qty, p.assembly,
  1225. p.partnumber, p.description, p.unit,
  1226. p.inventory_accno_id, p.income_accno_id,
  1227. p.expense_accno_id
  1228. FROM assembly a
  1229. JOIN parts p ON (a.parts_id = p.id)
  1230. WHERE a.id = ?|;
  1231. my $sth = $dbh->prepare($query);
  1232. $sth->execute($id) || $form->dberror($query);
  1233. my $allocated;
  1234. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1235. $allocated = 0;
  1236. $ref->{inventory_accno_id} *= 1;
  1237. $ref->{expense_accno_id} *= 1;
  1238. # multiply by number of assemblies
  1239. $ref->{qty} *= $totalqty;
  1240. if ( $ref->{assembly} ) {
  1241. &process_assembly( $dbh, $form, $ref->{parts_id}, $ref->{qty},
  1242. $project_id );
  1243. next;
  1244. }
  1245. else {
  1246. if ( $ref->{inventory_accno_id} ) {
  1247. $allocated =
  1248. &cogs( $dbh, $form, $ref->{parts_id}, $ref->{qty},
  1249. $project_id );
  1250. }
  1251. }
  1252. $query = qq|
  1253. INSERT INTO invoice
  1254. (trans_id, description, parts_id, qty,
  1255. sellprice, fxsellprice, allocated,
  1256. assemblyitem, unit)
  1257. VALUES (?, ?, ?, ?, 0, 0, ?, 't', ?)|;
  1258. my $sth = $dbh->prepare($query);
  1259. $sth->execute( $form->{id}, $ref->{description}, $ref->{parts_id},
  1260. $ref->{qty}, $allocated, $ref->{unit} )
  1261. || $form->dberror($query);
  1262. }
  1263. $sth->finish;
  1264. }
  1265. sub cogs {
  1266. # This is nearly entirely rewritten since 1.2.8 based in part on the works
  1267. # of Victor Sterpu and Dieter Simader (see CONTRIBUTORS for more
  1268. # information). However, there are a number of areas where I have
  1269. # substantially rewritten the logic. This function is heavily annotated
  1270. # largely because COGS/invoices are still scheduled to be re-engineered in
  1271. # 1.4 so it is a good idea to have records of opinions in the code.-- CT
  1272. my ( $dbh2, $form, $id, $totalqty, $project_id, $sellprice) = @_;
  1273. my $dbh = $form->{dbh};
  1274. my $query;
  1275. my $allocated = 0;
  1276. if ($totalqty == 0) {
  1277. return 0;
  1278. }
  1279. elsif ($totalqty > 0) {
  1280. # If the quantity is positive, we do a standard FIFO COGS calculation.
  1281. # In this case, we are going to order the queue by transdate and trans_id
  1282. # as this is the best way of doing this perpetually. We don't want out
  1283. # of order entry to screw with the books. Of course if someone wants to
  1284. # implement LIFO, this would be the place to do it. -- CT
  1285. my $query = qq|
  1286. SELECT i.id, i.trans_id, i.qty, i.allocated, i.sellprice,
  1287. i.fxsellprice, p.inventory_accno_id,
  1288. p.expense_accno_id,
  1289. (i.qty * -1) - i.allocated AS available
  1290. FROM invoice i
  1291. JOIN parts p ON (i.parts_id = p.id)
  1292. JOIN ap a ON (i.trans_id = a.id)
  1293. WHERE i.parts_id = ? AND (i.qty + i.allocated) < 0
  1294. ORDER BY a.transdate, i.trans_id|;
  1295. my $sth = $dbh->prepare($query);
  1296. $sth->execute($id) || $form->dberror($query);
  1297. my $qty;
  1298. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1299. $form->db_parse_numeric(sth=>$sth, hashref=>$ref);
  1300. if ( $ref->{available} >= $totalqty ) {
  1301. $qty = $totalqty;
  1302. }
  1303. else {
  1304. $qty = $ref->{available};
  1305. }
  1306. $form->update_balance( $dbh, "invoice", "allocated",
  1307. qq|id = $ref->{id}|, $qty );
  1308. # total expenses and inventory
  1309. # sellprice is the cost of the item
  1310. my $linetotal = $form->round_amount($ref->{sellprice} * $qty, 2);
  1311. # add expense
  1312. push @{ $form->{acc_trans}{lineitems} },
  1313. {
  1314. chart_id => $ref->{expense_accno_id},
  1315. amount => $linetotal * -1,
  1316. project_id => $project_id,
  1317. invoice_id => $ref->{id}
  1318. };
  1319. # deduct inventory
  1320. push @{ $form->{acc_trans}{lineitems} },
  1321. {
  1322. chart_id => $ref->{inventory_accno_id},
  1323. amount => $linetotal,
  1324. project_id => $project_id,
  1325. invoice_id => $ref->{id}
  1326. };
  1327. # subtract from allocated
  1328. $allocated -= $qty;
  1329. last if ( ( $totalqty -= $qty ) <= 0 );
  1330. }
  1331. $sth->finish;
  1332. }
  1333. else {
  1334. # In this case, the quantity is negative. So we are looking at a
  1335. # reversing entry for partial COGS. The two workflows supported here
  1336. # are those involved in voiding an invoice or returning some items on it.
  1337. # If there are unallocated items for the current invoice at the end, we
  1338. # will throw an error until we have an understanding of other workflows
  1339. # that need to be supported. -- CT
  1340. #
  1341. # Note: Victor's original patch selected items to reverse based on
  1342. # sell price. This causes issues with restocking fees and the like so
  1343. # I am removing that restriction. This should be discussed more fully
  1344. # however. -- CT
  1345. $query = qq|
  1346. SELECT i.id, i.qty, i.allocated, a.transdate,
  1347. -1 * (i.allocated + i.qty) AS available,
  1348. p.expense_accno_id, p.inventory_accno_id
  1349. FROM invoice i
  1350. JOIN parts p ON (p.id = i.parts_id)
  1351. JOIN ar a ON (a.id = i.trans_id)
  1352. WHERE i.parts_id = ? AND (i.qty + i.allocated) > 0
  1353. ORDER BY transdate
  1354. |;
  1355. $sth = $dbh->prepare($query);
  1356. $sth->execute($id) || $form->dberror($query);
  1357. my $qty;
  1358. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1359. $form->db_parse_numeric(sth=>$sth, hashref => $ref);
  1360. if ($totalqty < $ref->{available}){
  1361. $qty = $ref->{available};
  1362. } else {
  1363. $qty = $totalqty;
  1364. }
  1365. # update allocated for sold item
  1366. $form->update_balance(
  1367. $dbh, "invoice", "allocated",
  1368. qq|id = $ref->{id}|, $qty
  1369. );
  1370. # Note: No COGS calculations on reversed short sale invoices.
  1371. # This merely prevents COGS calculations in the future agaisnt
  1372. # such short invoices. -- CT
  1373. $totalqty -= $qty;
  1374. $allocated -= $qty;
  1375. last if $totalqty == 0;
  1376. }
  1377. # If the total quantity is still less than zero, we must assume that
  1378. # this is just an invoice which has been voided or products returns
  1379. # but is not merely representing a voided short sale, and therefore
  1380. # we need to unallocate the items from AP. There has been some debate
  1381. # as to how to approach this, and I think it is safest to unallocate
  1382. # the most recently allocated AP items of the same type regardless of
  1383. # the relevant dates of the invoices. I can see cases where this
  1384. # might require adjustments, however. -- CT
  1385. if ($totalqty < 0){
  1386. $query = qq|
  1387. SELECT i.allocated, i.sellprice, p.inventory_accno_id,
  1388. p.expense_accno_id, i.id
  1389. FROM invoice i
  1390. JOIN parts p ON (i.parts_id = p.id)
  1391. JOIN ap a ON (i.trans_id = a.id)
  1392. WHERE allocated > 0
  1393. AND i.parts_id = ?
  1394. ORDER BY a.transdate DESC, a.id DESC
  1395. |;
  1396. my $sth = $dbh->prepare($query);
  1397. $sth->execute($id);
  1398. while (my $ref = $sth->fetchrow_hashref(NAME_lc)){
  1399. my $qty = $ref->{allocated} * -1;
  1400. $qty = ($qty < $totalqty) ? $totalqty : $qty;
  1401. my $linetotal = $qty*$ref->{sellprice};
  1402. push @{ $form->{acc_trans}{lineitems} },
  1403. {
  1404. chart_id => $ref->{expense_accno_id},
  1405. amount => $linetotal,
  1406. project_id => $project_id,
  1407. invoice_id => $ref->{id}
  1408. };
  1409. push @{ $form->{acc_trans}{lineitems} },
  1410. {
  1411. chart_id => $ref->{inventory_accno_id},
  1412. amount => -$linetotal,
  1413. project_id => $project_id,
  1414. invoice_id => $ref->{id}
  1415. };
  1416. $form->update_balance(
  1417. $dbh, "invoice", "allocated",
  1418. qq|id = $ref->{id}|, $qty
  1419. );
  1420. $totalqty -= $qty;
  1421. $allocated -= $qty;
  1422. last if $totalqty == 0;
  1423. }
  1424. }
  1425. # If we still have less than 0 total quantity, this is not a return
  1426. # or a void. Throw an error. If there are valid workflows that throw
  1427. # this error, they will require more work to address and will not work
  1428. # safely with the current system. -- CT
  1429. if ($totalqty < 0){
  1430. $form->error("Too many reversed items on an invoice");
  1431. }
  1432. elsif ($totalqty > 0){
  1433. $form->error("Unexpected and invalid quantity allocated.".
  1434. " Aborting.");
  1435. }
  1436. }
  1437. return $allocated;
  1438. }
  1439. sub reverse_invoice {
  1440. my ( $dbh2, $form ) = @_;
  1441. my $dbh = $form->{dbh};
  1442. my $query = qq|
  1443. SELECT id FROM ar
  1444. WHERE id = ?|;
  1445. my $sth;
  1446. $sth = $dbh->prepare($query);
  1447. $sth->execute( $form->{id} );
  1448. my ($id) = $sth->fetchrow_array;
  1449. return unless $id;
  1450. # reverse inventory items
  1451. my $query = qq|
  1452. SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly,
  1453. p.inventory_accno_id
  1454. FROM invoice i
  1455. JOIN parts p ON (i.parts_id = p.id)
  1456. WHERE i.trans_id = ?|;
  1457. my $sth = $dbh->prepare($query);
  1458. $sth->execute( $form->{id} ) || $form->dberror($query);
  1459. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1460. if ( $ref->{inventory_accno_id} || $ref->{assembly} ) {
  1461. # if the invoice item is not an assemblyitem
  1462. # adjust parts onhand
  1463. if ( !$ref->{assemblyitem} ) {
  1464. # adjust onhand in parts table
  1465. $form->update_balance( $dbh, "parts", "onhand",
  1466. qq|id = $ref->{parts_id}|,
  1467. $ref->{qty} );
  1468. }
  1469. # loop if it is an assembly
  1470. next if ( $ref->{assembly} );
  1471. # de-allocated purchases
  1472. $query = qq|
  1473. SELECT id, trans_id, allocated
  1474. FROM invoice
  1475. WHERE parts_id = ?
  1476. AND allocated > 0
  1477. ORDER BY trans_id DESC|;
  1478. my $sth = $dbh->prepare($query);
  1479. $sth->execute( $ref->{parts_id} )
  1480. || $form->dberror($query);
  1481. while ( my $inhref = $sth->fetchrow_hashref(NAME_lc) ) {
  1482. $qty = $ref->{qty};
  1483. if ( ( $ref->{qty} - $inhref->{allocated} ) > 0 ) {
  1484. $qty = $inhref->{allocated};
  1485. }
  1486. # update invoice
  1487. $form->update_balance( $dbh, "invoice", "allocated",
  1488. qq|id = $inhref->{id}|,
  1489. $qty * -1 );
  1490. last if ( ( $ref->{qty} -= $qty ) <= 0 );
  1491. }
  1492. $sth->finish;
  1493. }
  1494. }
  1495. $sth->finish;
  1496. # delete acc_trans
  1497. $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
  1498. $sth = $dbh->prepare($query);
  1499. $sth->execute( $form->{id} ) || $form->dberror($query);
  1500. # delete invoice entries
  1501. $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
  1502. $sth = $dbh->prepare($query);
  1503. $sth->execute( $form->{id} ) || $form->dberror($query);
  1504. $query = qq|DELETE FROM shipto WHERE trans_id = ?|;
  1505. $sth = $dbh->prepare($query);
  1506. $sth->execute( $form->{id} ) || $form->dberror($query);
  1507. $dbh->commit;
  1508. }
  1509. sub delete_invoice {
  1510. my ( $self, $myconfig, $form ) = @_;
  1511. my $dbh = $form->{dbh};
  1512. my $sth;
  1513. &reverse_invoice( $dbh, $form );
  1514. my %audittrail = (
  1515. tablename => 'ar',
  1516. reference => $form->{invnumber},
  1517. formname => $form->{type},
  1518. action => 'deleted',
  1519. id => $form->{id}
  1520. );
  1521. $form->audittrail( $dbh, "", \%audittrail );
  1522. # delete AR record
  1523. my $query = qq|DELETE FROM ar WHERE id = ?|;
  1524. $sth = $dbh->prepare($query);
  1525. $sth->execute( $form->{id} ) || $form->dberror($query);
  1526. # delete spool files
  1527. $query = qq|
  1528. SELECT spoolfile FROM status
  1529. WHERE trans_id = ? AND spoolfile IS NOT NULL|;
  1530. $sth = $dbh->prepare($query);
  1531. $sth->execute( $form->{id} ) || $form->dberror($query);
  1532. my $spoolfile;
  1533. my @spoolfiles = ();
  1534. while ( ($spoolfile) = $sth->fetchrow_array ) {
  1535. push @spoolfiles, $spoolfile;
  1536. }
  1537. $sth->finish;
  1538. # delete status entries
  1539. $query = qq|DELETE FROM status WHERE trans_id = ?|;
  1540. $sth = $dbh->prepare($query);
  1541. $sth->execute( $form->{id} ) || $form->dberror($query);
  1542. my $rc = $dbh->commit;
  1543. if ($rc) {
  1544. foreach $spoolfile (@spoolfiles) {
  1545. unlink "${LedgerSMB::Sysconfig::spool}/$spoolfile"
  1546. if $spoolfile;
  1547. }
  1548. }
  1549. $rc;
  1550. }
  1551. sub retrieve_invoice {
  1552. my ( $self, $myconfig, $form ) = @_;
  1553. my $dbh = $form->{dbh};
  1554. my $query;
  1555. if ( $form->{id} ) {
  1556. # get default accounts and last invoice number
  1557. $query = qq|
  1558. SELECT value AS currencies FROM defaults
  1559. WHERE setting_key = 'curr'|;
  1560. }
  1561. else {
  1562. $query = qq|
  1563. SELECT value AS currencies, current_date AS transdate
  1564. FROM defaults
  1565. WHERE setting_key = 'curr'|;
  1566. }
  1567. my $sth = $dbh->prepare($query);
  1568. $sth->execute || $form->dberror($query);
  1569. my $ref = $sth->fetchrow_hashref(NAME_lc);
  1570. for ( keys %$ref ) { $form->{$_} = $ref->{$_} }
  1571. $sth->finish;
  1572. if ( $form->{id} ) {
  1573. # retrieve invoice
  1574. $query = qq|
  1575. SELECT a.invnumber, a.ordnumber, a.quonumber,
  1576. a.transdate, a.paid,
  1577. a.shippingpoint, a.shipvia, a.terms, a.notes,
  1578. a.intnotes,
  1579. a.duedate, a.taxincluded, a.curr AS currency,
  1580. a.person_id, e.name AS employee, a.till,
  1581. a.entity_id, a.reverse,
  1582. a.language_code, a.ponumber,
  1583. a.on_hold
  1584. FROM ar a
  1585. LEFT JOIN employee em ON (em.entity_id = a.person_id)
  1586. INNER JOIN entity e ON e.id = em.entity_id
  1587. WHERE a.id = ?|;
  1588. $sth = $dbh->prepare($query);
  1589. $sth->execute( $form->{id} ) || $form->dberror($query);
  1590. $ref = $sth->fetchrow_hashref(NAME_lc);
  1591. $form->db_parse_numeric(sth=> $sth, hashref=>$ref_);
  1592. for ( keys %$ref ) { $form->{$_} = $ref->{$_} }
  1593. $sth->finish;
  1594. # get shipto
  1595. $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
  1596. $sth = $dbh->prepare($query);
  1597. $sth->execute( $form->{id} ) || $form->dberror($query);
  1598. $ref = $sth->fetchrow_hashref(NAME_lc);
  1599. for ( keys %$ref ) { $form->{$_} = $ref->{$_} }
  1600. $sth->finish;
  1601. # retrieve individual items
  1602. $query = qq|
  1603. SELECT i.description, i.qty, i.fxsellprice,
  1604. i.sellprice, i.discount, i.parts_id AS id,
  1605. i.unit, i.deliverydate, i.project_id,
  1606. pr.projectnumber, i.serialnumber, i.notes,
  1607. p.partnumber, p.assembly, p.bin,
  1608. pg.partsgroup, p.partsgroup_id,
  1609. p.partnumber AS sku, p.listprice, p.lastcost,
  1610. p.weight, p.onhand, p.inventory_accno_id,
  1611. p.income_accno_id, p.expense_accno_id,
  1612. t.description AS partsgrouptranslation
  1613. FROM invoice i
  1614. JOIN parts p ON (i.parts_id = p.id)
  1615. LEFT JOIN project pr ON (i.project_id = pr.id)
  1616. LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
  1617. LEFT JOIN translation t
  1618. ON (t.trans_id = p.partsgroup_id
  1619. AND t.language_code
  1620. = ?)
  1621. WHERE i.trans_id = ?
  1622. AND NOT i.assemblyitem = '1'
  1623. ORDER BY i.id|;
  1624. $sth = $dbh->prepare($query);
  1625. $sth->execute( $form->{language_code}, $form->{id} )
  1626. || $form->dberror($query);
  1627. # foreign currency
  1628. &exchangerate_defaults( $dbh, $form );
  1629. # query for price matrix
  1630. my $pmh = PriceMatrix::price_matrix_query( $dbh, $form );
  1631. # taxes
  1632. $query = qq|
  1633. SELECT c.accno
  1634. FROM chart c
  1635. JOIN partstax pt ON (pt.chart_id = c.id)
  1636. WHERE pt.parts_id = ?|;
  1637. my $tth = $dbh->prepare($query) || $form->dberror($query);
  1638. my $taxrate;
  1639. my $ptref;
  1640. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1641. $form->db_parse_numeric(sth=>$sth, hashref => $ref);
  1642. $ref->{qty} *= -1 if $form->{reverse};
  1643. my ($dec) = ( $ref->{fxsellprice} =~ /\.(\d+)/ );
  1644. $dec = length $dec;
  1645. my $decimalplaces = ( $dec > 2 ) ? $dec : 2;
  1646. $tth->execute( $ref->{id} );
  1647. $ref->{taxaccounts} = "";
  1648. $taxrate = 0;
  1649. while ( $ptref = $tth->fetchrow_hashref(NAME_lc) ) {
  1650. $ref->{taxaccounts} .= "$ptref->{accno} ";
  1651. $taxrate += $form->{"$ptref->{accno}_rate"};
  1652. }
  1653. $tth->finish;
  1654. chop $ref->{taxaccounts};
  1655. # price matrix
  1656. $ref->{sellprice} =
  1657. ( $ref->{fxsellprice} * $form->{ $form->{currency} } );
  1658. PriceMatrix::price_matrix( $pmh, $ref, $form->{transdate},
  1659. $decimalplaces, $form, $myconfig );
  1660. $ref->{sellprice} = $ref->{fxsellprice};
  1661. $ref->{partsgroup} = $ref->{partsgrouptranslation}
  1662. if $ref->{partsgrouptranslation};
  1663. push @{ $form->{invoice_details} }, $ref;
  1664. }
  1665. $sth->finish;
  1666. }
  1667. @queries = $form->run_custom_queries( 'ar', 'SELECT' );
  1668. my $rc = $dbh->commit;
  1669. $rc;
  1670. }
  1671. sub retrieve_item {
  1672. my ( $self, $myconfig, $form ) = @_;
  1673. my $dbh = $form->{dbh};
  1674. my $i = $form->{rowcount};
  1675. my $null;
  1676. my $var;
  1677. my $where = "WHERE p.obsolete = '0' AND NOT p.income_accno_id IS NULL";
  1678. if ( $form->{"partnumber_$i"} ne "" ) {
  1679. $var = $dbh->quote( $form->like( lc $form->{"partnumber_$i"} ) );
  1680. $where .= " AND lower(p.partnumber) LIKE $var";
  1681. }
  1682. if ( $form->{"description_$i"} ne "" ) {
  1683. $var = $dbh->quote( $form->like( lc $form->{"description_$i"} ) );
  1684. if ( $form->{language_code} ne "" ) {
  1685. $where .= " AND lower(t1.description) LIKE $var";
  1686. }
  1687. else {
  1688. $where .= " AND lower(p.description) LIKE $var";
  1689. }
  1690. }
  1691. if ( $form->{"partsgroup_$i"} ne "" ) {
  1692. ( $null, $var ) = split /--/, $form->{"partsgroup_$i"};
  1693. if ( ! $var ) {
  1694. # search by partsgroup, this is for the POS
  1695. $where .=
  1696. qq| AND pg.partsgroup = |
  1697. . $dbh->quote( $form->{"partsgroup_$i"} );
  1698. }
  1699. else {
  1700. $var = $dbh->quote($var);
  1701. $where .= qq| AND p.partsgroup_id = $var|;
  1702. }
  1703. }
  1704. if ( $form->{"description_$i"} ne "" ) {
  1705. $where .= " ORDER BY 3";
  1706. }
  1707. else {
  1708. $where .= " ORDER BY 2";
  1709. }
  1710. my $query = qq|
  1711. SELECT p.id, p.partnumber, p.description, p.sellprice,
  1712. p.listprice, p.lastcost, p.unit, p.assembly, p.bin,
  1713. p.onhand, p.notes, p.inventory_accno_id,
  1714. p.income_accno_id, p.expense_accno_id, pg.partsgroup,
  1715. p.partsgroup_id, p.partnumber AS sku, p.weight,
  1716. t1.description AS translation,
  1717. t2.description AS grouptranslation
  1718. FROM parts p
  1719. LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
  1720. LEFT JOIN translation t1
  1721. ON (t1.trans_id = p.id AND t1.language_code = ?)
  1722. LEFT JOIN translation t2
  1723. ON (t2.trans_id = p.partsgroup_id
  1724. AND t2.language_code = ?)
  1725. $where|;
  1726. my $sth = $dbh->prepare($query);
  1727. $sth->execute( $form->{language_code}, $form->{language_code} )
  1728. || $form->dberror($query);
  1729. my $ref;
  1730. my $ptref;
  1731. # setup exchange rates
  1732. &exchangerate_defaults( $dbh, $form );
  1733. # taxes
  1734. $query = qq|
  1735. SELECT c.accno
  1736. FROM chart c
  1737. JOIN partstax pt ON (c.id = pt.chart_id)
  1738. WHERE pt.parts_id = ?|;
  1739. my $tth = $dbh->prepare($query) || $form->dberror($query);
  1740. # price matrix
  1741. my $pmh = PriceMatrix::price_matrix_query( $dbh, $form );
  1742. my $transdate = $form->datetonum( $myconfig, $form->{transdate} );
  1743. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1744. $form->db_parse_numeric(sth => $sth, hashref => $ref);
  1745. my ($dec) = ( $ref->{sellprice} =~ /\.(\d+)/ );
  1746. $dec = length $dec;
  1747. my $decimalplaces = ( $dec > 2 ) ? $dec : 2;
  1748. # get taxes for part
  1749. $tth->execute( $ref->{id} );
  1750. $ref->{taxaccounts} = "";
  1751. while ( $ptref = $tth->fetchrow_hashref(NAME_lc) ) {
  1752. $ref->{taxaccounts} .= "$ptref->{accno} ";
  1753. }
  1754. $tth->finish;
  1755. chop $ref->{taxaccounts};
  1756. # get matrix
  1757. PriceMatrix::price_matrix( $pmh, $ref, $transdate, $decimalplaces,
  1758. $form, $myconfig );
  1759. $ref->{description} = $ref->{translation}
  1760. if $ref->{translation};
  1761. $ref->{partsgroup} = $ref->{grouptranslation}
  1762. if $ref->{grouptranslation};
  1763. push @{ $form->{item_list} }, $ref;
  1764. }
  1765. $sth->finish;
  1766. }
  1767. sub exchangerate_defaults {
  1768. my ( $dbh2, $form ) = @_;
  1769. $dbh = $form->{dbh};
  1770. my $var;
  1771. # get default currencies
  1772. my $query = qq|
  1773. SELECT substr(value,1,3), value FROM defaults
  1774. WHERE setting_key = 'curr'|;
  1775. my $eth = $dbh->prepare($query) || $form->dberror($query);
  1776. $eth->execute;
  1777. ( $form->{defaultcurrency}, $form->{currencies} ) = $eth->fetchrow_array;
  1778. $eth->finish;
  1779. $query = qq|
  1780. SELECT buy
  1781. FROM exchangerate
  1782. WHERE curr = ?
  1783. AND transdate = ?|;
  1784. my $eth1 = $dbh->prepare($query) || $form->dberror($query);
  1785. $query = qq/
  1786. SELECT max(transdate || ' ' || buy || ' ' || curr)
  1787. FROM exchangerate
  1788. WHERE curr = ?/;
  1789. my $eth2 = $dbh->prepare($query) || $form->dberror($query);
  1790. # get exchange rates for transdate or max
  1791. foreach $var ( split /:/, substr( $form->{currencies}, 4 ) ) {
  1792. $eth1->execute( $var, $form->{transdate} );
  1793. ( $form->{$var} ) = $eth1->fetchrow_array;
  1794. if ( !$form->{$var} ) {
  1795. $eth2->execute($var);
  1796. ( $form->{$var} ) = $eth2->fetchrow_array;
  1797. ( $null, $form->{$var} ) = split / /, $form->{$var};
  1798. $form->{$var} = 1 unless $form->{$var};
  1799. $eth2->finish;
  1800. }
  1801. $eth1->finish;
  1802. }
  1803. $form->{ $form->{currency} } = $form->{exchangerate}
  1804. if $form->{exchangerate};
  1805. $form->{ $form->{currency} } ||= 1;
  1806. $form->{ $form->{defaultcurrency} } = 1;
  1807. }
  1808. =pod
  1809. =cut
  1810. sub toggle_on_hold {
  1811. my $self = shift @_;
  1812. my $form = shift @_;
  1813. if ($form->{id}) { # it's an existing (.. probably) invoice.
  1814. my $dbh = $form->{dbh};
  1815. my $sth = $dbh->prepare("SELECT on_hold from ar where ar.id = ?");
  1816. $sth->execute($form->{id});
  1817. my $state = $sth->fetchrow_array;
  1818. my $sth;
  1819. my $n_s; # new state
  1820. if ($state[0] == 't') {
  1821. # Turn it off
  1822. $n_s = 'f';
  1823. } else {
  1824. $n_s = 't';
  1825. }
  1826. my $sth = $dbh->prepare("update ar set on_hold = ?::boolean where ar.id = ?");
  1827. my $code = $dbh->execute($ns, $form->{id});
  1828. return 1;
  1829. } else { # This shouldn't even be possible, but check for it anyway.
  1830. # Definitely, DEFINITELY check it.
  1831. # happily return 0. Find out about proper error states.
  1832. return 0;
  1833. }
  1834. }
  1835. 1;