GoBD: Exportfehler an Benutzer ausgeben
[kivitendo-erp.git] / SL / Controller / GoBD.pm
1 package SL::Controller::GoBD;
2
3 use strict;
4
5 use parent qw(SL::Controller::Base);
6
7 use DateTime;
8 use SL::GoBD;
9 use SL::Locale::String qw(t8);
10 use SL::Helper::Flash;
11
12 use SL::DB::AccTransaction;
13
14 use Rose::Object::MakeMethods::Generic (
15   'scalar --get_set_init' => [ qw(from to) ],
16 );
17
18 __PACKAGE__->run_before('check_auth');
19
20 sub action_filter {
21   my ($self) = @_;
22
23   $self->from(DateTime->today->add(years => -1)->add(days => 1)) if !$self->from;
24   $self->to(DateTime->today)                                     if !$self->to;
25
26   $::request->layout->add_javascripts('kivi.GoBD.js');
27   $self->render('gobd/filter', current_year => DateTime->today->year, title => t8('GoBD Export'));
28 }
29
30 sub action_export {
31   my ($self) = @_;
32
33   if (!$self->check_inputs) {
34     $self->action_filter;
35     return;
36   }
37
38   my $filename;
39   my $gobd = SL::GoBD->new(
40     company    => $::instance_conf->get_company,
41     location   => $::instance_conf->get_address,
42     from       => $self->from,
43     to         => $self->to,
44   );
45
46   eval {
47     $filename = $gobd->generate_export;
48   } or do {
49     my $errors = $@;
50     flash('error', t8('The export failed because of malformed transactions. Please fix those before exporting.'));
51     flash('error', $_) for @$errors;
52
53     $self->action_filter;
54     return;
55   };
56
57   $self->send_file($filename, name => t8('gobd-#1-#2.zip', $self->from->ymd, $self->to->ymd), unlink => 1);
58 }
59
60 #--- other stuff
61
62 sub check_auth { $::auth->assert('report') }
63
64 sub check_inputs {
65   my ($self) = @_;
66
67   my $error = 0;
68
69   if ($::form->{method} eq 'year') {
70     if ($::form->{year}) {
71       $self->from(DateTime->new(year => $::form->{year}, month => 1,  day => 1));
72       $self->to(  DateTime->new(year => $::form->{year}, month => 12, day => 31));
73     } else {
74       $error = 1;
75       flash('error', t8('No year given for method year'));
76     }
77   } else {
78     if (!$::form->{from}) {
79       my $epoch = DateTime->new(day => 1, month => 1, year => 1900);
80       flash('info', t8('No start date given, setting to #1', $epoch->to_kivitendo));
81       $self->from($epoch);
82     }
83
84     if (!$::form->{to}) {
85       flash('info', t8('No end date given, setting to today'));
86       $self->to(DateTime->today);
87     }
88   }
89
90   !$error;
91 }
92
93 sub available_years {
94   my ($self) = @_;
95
96   my $first_trans = SL::DB::Manager::AccTransaction->get_first(sort_by => 'transdate', limit => 1);
97
98   return [] unless $first_trans;
99   return [ reverse $first_trans->transdate->year .. DateTime->today->year ];
100 }
101
102 sub init_from { DateTime->from_kivitendo($::form->{from}) }
103 sub init_to { DateTime->from_kivitendo($::form->{to}) }
104
105 1;