1 package SL::PriceSource::PriceRules;
4 use parent qw(SL::PriceSource::Base);
6 use SL::PriceSource::Price;
7 use SL::PriceSource::Discount;
8 use SL::Locale::String;
10 use List::UtilsBy qw(min_by max_by);
12 sub name { 'price_rules' }
14 sub description { t8('Price Rule') }
17 my ($self, %params) = @_;
19 $self->{available} ||= SL::DB::Manager::PriceRule->get_all_matching(record => $self->record, record_item => $self->record_item);
22 sub available_price_rules {
23 my $rules = $_[0]->available_rules;
24 grep { $_->price_type != SL::DB::Manager::PriceRule::PRICE_DISCOUNT() } @$rules
27 sub available_discount_rules {
28 my $rules = $_[0]->available_rules;
29 grep { $_->price_type == SL::DB::Manager::PriceRule::PRICE_DISCOUNT() } @$rules
32 sub available_prices {
33 my ($self, %params) = @_;
35 map { $self->make_price_from_rule($_) } $self->available_price_rules;
38 sub available_discounts {
39 my ($self, %params) = @_;
41 map { $self->make_discount_from_rule($_) } $self->available_discount_rules;
44 sub price_from_source {
45 my ($self, $source, $spec) = @_;
47 my $rule = SL::DB::Manager::PriceRule->find_by(id => $spec);
48 if ($rule->price_type == SL::DB::Manager::PriceRule::PRICE_DISCOUNT()) {
49 return $self->make_discount_from_rule($rule);
51 return $self->make_price_from_rule($rule);
58 my @rules = $self->available_price_rules;
62 my @max_prio = max_by { $_->priority } @rules;
63 my $min_price = min_by { $self->price_for_rule($_) } @max_prio;
65 $self->make_price_from_rule($min_price);
71 my @rules = $self->available_discount_rules;
75 my @max_prio = max_by { $_->priority } @rules;
76 my $max_discount = max_by { $_->discount } @max_prio;
78 $self->make_discount_from_rule($max_discount);
82 my ($self, $rule) = @_;
83 $rule->price_type != SL::DB::Manager::PriceRule::PRICE_NEW()
84 ? (1 - $rule->reduction / 100) * ($rule->is_sales ? $self->part->sellprice : $self->part->lastcost)
88 sub make_price_from_rule {
89 my ($self, $rule) = @_;
91 SL::PriceSource::Price->new(
92 price => $self->price_for_rule($rule),
94 description => $rule->name,
95 price_source => $self,
96 (invalid => t8('This Price Rule is no longer valid'))x!!$rule->obsolete,
100 sub make_discount_from_rule {
101 my ($self, $rule) = @_;
103 SL::PriceSource::Discount->new(
104 discount => $rule->discount / 100,
106 description => $rule->name,
107 price_source => $self,
108 (invalid => t8('This Price Rule is no longer valid'))x!!$rule->obsolete,