Merge branch 'rb-wiederkehrende-rechnungen' into 263
[kivitendo-erp.git] / SL / DB / PeriodicInvoicesConfig.pm
1 package SL::DB::PeriodicInvoicesConfig;
2
3 use strict;
4
5 use Readonly;
6
7 use SL::DB::MetaSetup::PeriodicInvoicesConfig;
8
9 __PACKAGE__->meta->add_relationships(
10   order        => {
11     type       => 'one to one',
12     class      => 'SL::DB::Order',
13     column_map => { oe_id => 'id' },
14   },
15 );
16
17 __PACKAGE__->meta->initialize;
18
19 # Creates get_all, get_all_count, get_all_iterator, delete_all and update_all.
20 __PACKAGE__->meta->make_manager_class;
21
22 Readonly our @PERIODICITIES  => qw(m q f b y);
23 Readonly our %PERIOD_LENGTHS => ( m => 1, q => 3, f => 4, b => 6, y => 12 );
24
25 sub get_period_length {
26   my $self = shift;
27   return $PERIOD_LENGTHS{ $self->periodicity } || 1;
28 }
29
30 sub _log_msg {
31   $::lxdebug->message(LXDebug->DEBUG1(), join('', @_));
32 }
33
34 sub handle_automatic_extension {
35   my $self = shift;
36
37   _log_msg("HAE for " . $self->id . "\n");
38   # Don't extend configs that have been terminated. There's nothing to
39   # extend if there's no end date.
40   return if $self->terminated || !$self->end_date;
41
42   my $today    = DateTime->now_local;
43   my $end_date = $self->end_date;
44
45   _log_msg("today $today end_date $end_date\n");
46
47   # The end date has not been reached yet, therefore no extension is
48   # needed.
49   return if $today <= $end_date;
50
51   # The end date has been reached. If no automatic extension has been
52   # set then terminate the config and return.
53   if (!$self->extend_automatically_by) {
54     _log_msg("setting inactive\n");
55     $self->active(0);
56     $self->save;
57     return;
58   }
59
60   # Add the automatic extension period to the new end date as long as
61   # the new end date is in the past. Then save it and get out.
62   $end_date->add(months => $self->extend_automatically_by) while $today > $end_date;
63   _log_msg("new end date $end_date\n");
64
65   $self->end_date($end_date);
66   $self->save;
67
68   return $end_date;
69 }
70
71 sub get_previous_invoice_date {
72   my $self  = shift;
73
74   my $query = <<SQL;
75     SELECT MAX(ar.transdate)
76     FROM periodic_invoices
77     LEFT JOIN ar ON (ar.id = periodic_invoices.ar_id)
78     WHERE periodic_invoices.config_id = ?
79 SQL
80
81   my ($max_transdate) = $self->dbh->selectrow_array($query, undef, $self->id);
82
83   return undef unless $max_transdate;
84   return ref $max_transdate ? $max_transdate : $self->db->parse_date($max_transdate);
85 }
86
87 1;