Merge branch 'master' of github.com:kivitendo/kivitendo-erp
[kivitendo-erp.git] / SL / DB / PaymentTerm.pm
1 package SL::DB::PaymentTerm;
2
3 use strict;
4
5 use SL::DB::MetaSetup::PaymentTerm;
6 use SL::DB::Manager::PaymentTerm;
7 use SL::DB::Helper::ActsAsList;
8 use SL::DB::Helper::TranslatedAttributes;
9
10 __PACKAGE__->meta->initialize;
11
12 sub validate {
13   my ($self) = @_;
14
15   my @errors;
16   push @errors, $::locale->text('The description is missing.')      if !$self->description;
17   push @errors, $::locale->text('The long description is missing.') if !$self->description_long;
18
19   return @errors;
20 }
21
22 sub calc_date {
23   my ($self, %params) = @_;
24
25   my $reference_date  = $params{reference_date} || DateTime->today_local;
26   $reference_date     = DateTime->from_kivitendo($reference_date) unless ref($reference_date) eq 'DateTime';
27
28   my $terms           = ($params{terms} // 'net') eq 'discount' ? 'terms_skonto' : 'terms_netto';
29   my $date            = $reference_date->add(days => $self->$terms);
30
31   my $dow             = $date->day_of_week;
32   $date               = $date->add(days => 8 - $dow) if $dow > 5;
33
34   return $date;
35 }
36
37 1;
38 __END__
39
40 =pod
41
42 =encoding utf8
43
44 =head1 NAME
45
46 SL::DB::PaymentTerm - Rose model for the payment_terms table
47
48 =head1 SYNOPSIS
49
50   my $terms             = SL::DB::PaymentTerm->new(id => $::form->{payment_id})->load;
51   my $due_date_net      = $erms->calc_date(terms => 'net');      # uses terms_netto
52   my $due_date_discount = $erms->calc_date(terms => 'discount'); # uses terms_skonto
53
54 =head1 FUNCTIONS
55
56 =over 4
57
58 =item C<calc_date [%params]>
59
60 Calculates and returns a due date as an instance of L<DateTime> by
61 adding one of C<$self>'s terms fields. Note that the resulting date
62 will be the following Monday if the result falls on a weekend.
63
64 C<%params> can contain the following parameters:
65
66 =over 4
67
68 =item C<reference_date>
69
70 The reference date from which the due date will be calculated. Can be
71 either an instance of L<DateTime> or a scalar in which case the scalar
72 is parsed via L<DateTime/from_kivitendo>.
73
74 Defaults to the current date if unset.
75
76 =item C<terms>
77
78 Can be either C<net> or C<discount>. For C<net> the number of days to
79 add to the reference date are C<$self-E<gt>terms_netto>. For
80 C<discount> C<$self-E<gt>terms_skonto> is used.
81
82 Defaults to C<net> if unset.
83
84 =back
85
86 =item C<validate>
87
88 Validates before saving and returns an array of human-readable error
89 messages in case of an error.
90
91 =back
92
93 =head1 BUGS
94
95 Nothing here yet.
96
97 =head1 AUTHOR
98
99 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
100
101 =cut