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