b1c75f879f43fd124b4c179af5d501d8392697ba
[kivitendo-erp.git] / SL / PriceSource / Pricegroup.pm
1 package SL::PriceSource::Pricegroup;
2
3 use strict;
4 use parent qw(SL::PriceSource::Base);
5
6 use SL::PriceSource::Price;
7 use SL::Locale::String;
8 use List::UtilsBy qw(min_by);
9 use List::Util qw(first);
10
11 sub name { 'pricegroup' }
12
13 sub description { t8('Pricegroup') }
14
15 sub available_prices {
16   my ($self, %params) = @_;
17
18   my $item = $self->record_item;
19
20   my $prices = SL::DB::Manager::Price->get_all(
21     query        => [ parts_id => $item->parts_id, price => { gt => 0 } ],
22     with_objects => 'pricegroup',
23     order_by     => 'pricegroun.id',
24   );
25
26   return () unless @$prices;
27
28   return map {
29     $self->make_price($_);
30   } @$prices;
31 }
32
33 sub price_from_source {
34   my ($self, $source, $spec) = @_;
35
36   my $price = SL::DB::Manager::Price->find_by(id => $spec);
37
38   return $self->make_price($price);
39 }
40
41 sub best_price {
42   my ($self, %params) = @_;
43
44   my @prices    = $self->availabe_prices;
45   my $customer  = $self->record->customer;
46   my $min_price = min_by { $_->price } @prices;
47
48   return $min_price if !$customer || !$customer->cv_klass;
49
50   my $best_price = first { $_->spec == $customer->cv_class } @prices;
51
52   return $best_price || $min_price;
53 }
54
55 sub make_price {
56   my ($self, $price_obj) = @_;
57
58   SL::PriceSource::Price->new(
59     price        => $price_obj->price,
60     spec         => $price_obj->id,
61     description  => $price_obj->pricegroup->pricegroup,
62     price_source => $self,
63   )
64 }
65
66 1;