epic-s6ts
[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 $query = [ parts_id => $item->parts_id, price => { gt => 0 } ];
24
25   # add a pricegroup_filter for obsolete pricegroups, unless part of an
26   # existing pricegroup where that pricegroup was actually used.
27   if ( $self->record->id and $item->active_price_source =~ m/^pricegroup/ ) {
28     my ($pricegroup_id) = $item->active_price_source =~ m/^pricegroup\/(\d+)$/;
29     push(@{$query}, or => [ 'pricegroup.obsolete' => 0, 'pricegroup_id' => $pricegroup_id ]);
30   } else {
31     push(@{$query}, 'pricegroup.obsolete' => 0);
32   }
33
34   my $prices = SL::DB::Manager::Price->get_all(
35     query        => $query,
36     with_objects => 'pricegroup',
37     sort_by      => 'pricegroup.sortkey',
38   );
39
40   return () unless @$prices;
41
42   return map {
43     $self->make_price($_);
44   } @$prices;
45 }
46
47 sub available_discounts { }
48
49 sub price_from_source {
50   my ($self, $source, $spec) = @_;
51
52   my $price = SL::DB::Manager::Price->find_by(pricegroup_id => $spec, parts_id => $self->part->id);
53
54   if (!$price) {
55     return SL::PriceSource::Price->new(
56       price_source => $self,
57       missing      => t8('Could not find an entry for this part in the pricegroup.'),
58     );
59   }
60
61   return $self->make_price($price);
62 }
63
64 sub discount_from_source { }
65
66 sub best_price {
67   my ($self, %params) = @_;
68
69   return () unless $self->record->is_sales;
70
71   my @prices    = $self->available_prices;
72   my $customer  = $self->record->customer;
73
74   return () if !$customer || !$customer->pricegroup_id;
75
76   my $best_price = first { $_->spec == $customer->pricegroup_id } @prices;
77
78   return $best_price || ();
79 }
80
81 sub best_discount { }
82
83 sub make_price {
84   my ($self, $price_obj) = @_;
85
86   SL::PriceSource::Price->new(
87     price        => $price_obj->price,
88     spec         => $price_obj->pricegroup->id,
89     description  => $price_obj->pricegroup->pricegroup,
90     price_source => $self,
91   )
92 }
93
94 1;