6408300b13a4de5d1260cb768c69207ea89a8d00
[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::DB::Price;
8 use SL::Locale::String;
9 use List::UtilsBy qw(min_by);
10 use List::Util qw(first);
11
12 sub name { 'pricegroup' }
13
14 sub description { t8('Pricegroup') }
15
16 sub available_prices {
17   my ($self, %params) = @_;
18
19   return () unless $self->record->is_sales;
20
21   my $item = $self->record_item;
22
23   my $prices = SL::DB::Manager::Price->get_all(
24     query        => [ parts_id => $item->parts_id, price => { gt => 0 } ],
25     with_objects => 'pricegroup',
26     order_by     => 'pricegroup.id',
27   );
28
29   return () unless @$prices;
30
31   return map {
32     $self->make_price($_);
33   } @$prices;
34 }
35
36 sub available_discounts { }
37
38 sub price_from_source {
39   my ($self, $source, $spec) = @_;
40
41   my $price = SL::DB::Manager::Price->find_by(pricegroup_id => $spec, parts_id => $self->part->id);
42
43   # TODO: if someone deletes the prices entry, this fails. add a fallback
44   return $self->make_price($price);
45 }
46
47 sub discount_from_source { }
48
49 sub best_price {
50   my ($self, %params) = @_;
51
52   return () unless $self->record->is_sales;
53
54   my @prices    = $self->available_prices;
55   my $customer  = $self->record->customer;
56
57   return () if !$customer || !$customer->klass;
58
59   my $best_price = first { $_->spec == $customer->klass } @prices;
60
61   return $best_price || ();
62 }
63
64 sub best_discount { }
65
66 sub make_price {
67   my ($self, $price_obj) = @_;
68
69   SL::PriceSource::Price->new(
70     price        => $price_obj->price,
71     spec         => $price_obj->pricegroup->id,
72     description  => $price_obj->pricegroup->pricegroup,
73     price_source => $self,
74   )
75 }
76
77 1;