epic-ts
[kivitendo-erp.git] / SL / Controller / FinancialOverview.pm
1 package SL::Controller::FinancialOverview;
2
3 use strict;
4 use parent qw(SL::Controller::Base);
5
6 use List::MoreUtils qw(none);
7 use List::Util qw(min);
8
9 use SL::DB::Employee;
10 use SL::DB::Invoice;
11 use SL::DB::Order;
12 use SL::DB::PeriodicInvoicesConfig;
13 use SL::DB::PurchaseInvoice;
14 use SL::Controller::Helper::ReportGenerator;
15 use SL::Locale::String;
16
17 use Rose::Object::MakeMethods::Generic (
18   scalar                  => [ qw(report number_columns year current_year objects subtotals_per_quarter salesman_id) ],
19   'scalar --get_set_init' => [ qw(employees types data) ],
20 );
21
22 __PACKAGE__->run_before(sub { $::auth->assert('report'); });
23
24 sub action_list {
25   my ($self) = @_;
26
27   $self->$_($::form->{$_}) for qw(subtotals_per_quarter salesman_id);
28
29   $self->get_objects;
30   $self->calculate_one_time_data;
31   $self->calculate_periodic_invoices;
32   $self->prepare_report;
33   $self->list_data;
34 }
35
36 # private functions
37
38 sub prepare_report {
39   my ($self)      = @_;
40
41   $self->report(SL::ReportGenerator->new(\%::myconfig, $::form));
42
43   my @columns = (qw(year quarter month), @{ $self->types });
44
45   $self->number_columns([ grep { !m/^(?:month|year|quarter)$/ } @columns ]);
46
47   my %column_defs          = (
48     month                  => { text => t8('Month')                  },
49     year                   => { text => t8('Year')                   },
50     quarter                => { text => t8('Quarter')                },
51     sales_quotations       => { text => t8('Sales Quotations')       },
52     sales_orders           => { text => t8('Sales Orders Advance')   },
53     sales_orders_per_inv   => { text => t8('Total Sales Orders Value') },
54     sales_invoices         => { text => t8('Invoices')               },
55     requests_for_quotation => { text => t8('Requests for Quotation') },
56     purchase_orders        => { text => t8('Purchase Orders')        },
57     purchase_invoices      => { text => t8('Purchase Invoices')      },
58   );
59
60   $column_defs{$_}->{align} = 'right' for @columns;
61
62   $self->report->set_options(
63     std_column_visibility => 1,
64     controller_class      => 'FinancialOverview',
65     output_format         => 'HTML',
66     raw_top_info_text     => $self->render('financial_overview/report_top', { output => 0 }, YEARS_TO_LIST => [ reverse(($self->current_year - 10)..($self->current_year + 5)) ]),
67     title                 => t8('Financial overview for #1', $self->year),
68     allow_pdf_export      => 1,
69     allow_csv_export      => 1,
70   );
71   $self->report->set_columns(%column_defs);
72   $self->report->set_column_order(@columns);
73   $self->report->set_export_options(qw(list year subtotals_per_quarter salesman_id));
74   $self->report->set_options_from_form;
75 }
76
77 sub get_objects {
78   my ($self) = @_;
79
80   $self->current_year(DateTime->today->year);
81   $self->year($::form->{year} || DateTime->today->year);
82
83   my $start       = DateTime->new(year => $self->year, month => 1, day => 1);
84   my $end         = DateTime->new(year => $self->year, month => 12, day => 31);
85
86   my @f_date      = (transdate => { ge => $start }, transdate => { le => $end });
87   my @f_salesman  = $self->salesman_id ? (salesman_id => $self->salesman_id) : ();
88
89   $self->objects({
90     sales_quotations       => SL::DB::Manager::Order->get_all(          where => [ and => [ @f_date, @f_salesman, SL::DB::Manager::Order->type_filter('sales_quotation')   ]]),
91     sales_orders           => SL::DB::Manager::Order->get_all(          where => [ and => [ @f_date, @f_salesman, SL::DB::Manager::Order->type_filter('sales_order')       ]], with_objects => [ qw(periodic_invoices_config) ]),
92     sales_orders_per_inv   => [],
93     requests_for_quotation => SL::DB::Manager::Order->get_all(          where => [ and => [ @f_date, @f_salesman, SL::DB::Manager::Order->type_filter('request_quotation') ]]),
94     purchase_orders        => SL::DB::Manager::Order->get_all(          where => [ and => [ @f_date, @f_salesman, SL::DB::Manager::Order->type_filter('purchase_order')    ]]),
95     sales_invoices         => SL::DB::Manager::Invoice->get_all(        where => [ and => [ @f_date, @f_salesman, ]]),
96     purchase_invoices      => SL::DB::Manager::PurchaseInvoice->get_all(where => [ and =>  \@f_date ]),
97     periodic_invoices_cfg  => SL::DB::Manager::PeriodicInvoicesConfig->get_all(where => [ active => 1, $self->salesman_id ? ('order.salesman_id' => $self->salesman_id) : () ], with_objects => [ qw(order) ]),
98   });
99
100   $self->objects->{sales_orders} = [ grep { !$_->periodic_invoices_config || !$_->periodic_invoices_config->active } @{ $self->objects->{sales_orders} } ];
101 }
102
103 sub init_types { [ qw(sales_quotations sales_orders sales_orders_per_inv sales_invoices requests_for_quotation purchase_orders purchase_invoices) ] }
104
105 sub init_data {
106   my ($self) = @_;
107
108   my %data  = (
109     year    => [ ($self->year) x 12                   ],
110     month   => [ (1..12)                              ],
111     quarter => [ (1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4) ],
112     map {
113       $_ => {
114         months   => [ (0) x 12 ],
115         quarters => [ (0) x  4 ],
116         year     => 0,
117       }
118     } @{ $self->types },
119   );
120
121   return \%data;
122 }
123
124 sub calculate_one_time_data {
125   my ($self) = @_;
126
127   foreach my $type (@{ $self->types }) {
128     my $src_object_type = $type eq 'sales_orders_per_inv' ? 'sales_orders' : $type;
129     foreach my $object (@{ $self->objects->{ $src_object_type } }) {
130       my $month                              = $object->transdate->month - 1;
131       my $tdata                              = $self->data->{$type};
132
133       $tdata->{months}->[$month]            += $object->netamount;
134       $tdata->{quarters}->[int($month / 3)] += $object->netamount;
135       $tdata->{year}                        += $object->netamount;
136     }
137   }
138 }
139
140 sub calculate_periodic_invoices {
141   my ($self)     = @_;
142
143   my $start_date = DateTime->new(year => $self->year, month =>  1, day =>  1, time_zone => $::locale->get_local_time_zone);
144   my $end_date   = DateTime->new(year => $self->year, month => 12, day => 31, time_zone => $::locale->get_local_time_zone);
145
146   $self->calculate_one_periodic_invoice(config => $_, start_date => $start_date, end_date => $end_date) for @{ $self->objects->{periodic_invoices_cfg} };
147 }
148
149 sub calculate_one_periodic_invoice {
150   my ($self, %params) = @_;
151
152   # Calculate sales order advance
153   my $net  = $params{config}->order->netamount * $params{config}->get_billing_period_length / $params{config}->get_order_value_period_length;
154   my $sord = $self->data->{sales_orders};
155
156   foreach my $date ($params{config}->calculate_invoice_dates(start_date => $params{start_date}, end_date => $params{end_date}, past_dates => 1)) {
157     $sord->{months  }->[ $date->month   - 1 ] += $net;
158     $sord->{quarters}->[ $date->quarter - 1 ] += $net;
159     $sord->{year}                             += $net;
160   }
161
162   # Calculate total sales order value
163   my $date = $params{config}->order->transdate;
164   return if $date->year != $params{start_date}->year;
165
166   $net                                       = $params{config}->order->netamount;
167   $sord                                      = $self->data->{sales_orders_per_inv};
168   $sord->{months  }->[ $date->month   - 1 ] += $net;
169   $sord->{quarters}->[ $date->quarter - 1 ] += $net;
170   $sord->{year}                             += $net;
171 }
172
173 sub list_data {
174   my ($self)           = @_;
175
176   my @visible_columns  = $self->report->get_visible_columns;
177   my @type_columns     = @{ $self->types };
178   my @non_type_columns = grep { my $c = $_; none { $c eq $_ } @type_columns } @visible_columns;
179
180   for my $month (1..12) {
181     my %data  = (
182       map({ ($_ => { data => $self->data->{$_}->[$month - 1]                                                    }) } @non_type_columns),
183       map({ ($_ => { data => $::form->format_amount(\%::myconfig, $self->data->{$_}->{months}->[$month - 1], 2) }) } @type_columns    ),
184     );
185
186     $self->report->add_data(\%data);
187
188     if ($self->subtotals_per_quarter && (($month % 3) == 0)) {
189       my %subtotal =  (
190         year       => { data => $self->year },
191         month      => { data => $::locale->text('Total') },
192         map { ($_ => { data => $::form->format_amount(\%::myconfig, $self->data->{$_}->{quarters}->[int(($month - 1) / 3)], 2) }) } @type_columns,
193       );
194
195       $subtotal{$_}->{class} = 'listsubtotal' for @visible_columns;
196
197       $self->report->add_data(\%subtotal);
198     }
199   }
200
201   my %data  =  (
202     year    => { data => $self->year },
203     quarter => { data => $::locale->text('Total') },
204     map { ($_ => { data => $::form->format_amount(\%::myconfig, $self->data->{$_}->{year}, 2) }) } @type_columns,
205   );
206
207   $data{$_}->{class} = 'listtotal' for @visible_columns;
208
209   $self->report->add_data(\%data);
210
211   return $self->report->generate_with_headers;
212 }
213
214 sub init_employees { SL::DB::Manager::Employee->get_all_sorted }
215
216 1;