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