Finanzübersicht: Neue Spalte »Kosten« analog zu BWA-Kosten
[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::DBUtils;
15 use SL::Controller::Helper::ReportGenerator;
16 use SL::Locale::String;
17
18 use Rose::Object::MakeMethods::Generic (
19   scalar                  => [ qw(report number_columns year current_year objects subtotals_per_quarter salesman_id) ],
20   'scalar --get_set_init' => [ qw(employees types data show_costs) ],
21 );
22
23 __PACKAGE__->run_before(sub { $::auth->assert('report'); });
24
25 sub action_list {
26   my ($self) = @_;
27
28   $self->$_($::form->{$_}) for qw(subtotals_per_quarter salesman_id);
29
30   $self->get_objects;
31   $self->calculate_one_time_data;
32   $self->calculate_periodic_invoices;
33   $self->calculate_costs if $self->show_costs;
34   $self->prepare_report;
35   $self->list_data;
36 }
37
38 # private functions
39
40 sub prepare_report {
41   my ($self)      = @_;
42
43   $self->report(SL::ReportGenerator->new(\%::myconfig, $::form));
44
45   my @columns = (qw(year quarter month), @{ $self->types });
46
47   $self->number_columns([ grep { !m/^(?:month|year|quarter)$/ } @columns ]);
48
49   my %column_defs          = (
50     month                  => { text => t8('Month')                  },
51     year                   => { text => t8('Year')                   },
52     quarter                => { text => t8('Quarter')                },
53     sales_quotations       => { text => t8('Sales Quotations')       },
54     sales_orders           => { text => t8('Sales Orders Advance')   },
55     sales_orders_per_inv   => { text => t8('Total Sales Orders Value') },
56     sales_invoices         => { text => t8('Invoices')               },
57     requests_for_quotation => { text => t8('Requests for Quotation') },
58     purchase_orders        => { text => t8('Purchase Orders')        },
59     purchase_invoices      => { text => t8('Purchase Invoices')      },
60     costs                  => { text => t8('Costs')                  },
61   );
62
63   $column_defs{$_}->{align} = 'right' for @columns;
64
65   $self->report->set_options(
66     std_column_visibility => 1,
67     controller_class      => 'FinancialOverview',
68     output_format         => 'HTML',
69     raw_top_info_text     => $self->render('financial_overview/report_top', { output => 0 }, YEARS_TO_LIST => [ reverse(($self->current_year - 10)..($self->current_year + 5)) ]),
70     title                 => t8('Financial overview for #1', $self->year),
71     allow_pdf_export      => 1,
72     allow_csv_export      => 1,
73   );
74   $self->report->set_columns(%column_defs);
75   $self->report->set_column_order(@columns);
76   $self->report->set_export_options(qw(list year subtotals_per_quarter salesman_id));
77   $self->report->set_options_from_form;
78 }
79
80 sub get_objects {
81   my ($self) = @_;
82
83   $self->current_year(DateTime->today->year);
84   $self->year($::form->{year} || DateTime->today->year);
85
86   my $start       = DateTime->new(year => $self->year, month => 1, day => 1);
87   my $end         = DateTime->new(year => $self->year, month => 12, day => 31);
88
89   my @f_date      = (transdate => { ge => $start }, transdate => { le => $end });
90   my @f_salesman  = $self->salesman_id ? (salesman_id => $self->salesman_id) : ();
91
92   $self->objects({
93     sales_quotations       => SL::DB::Manager::Order->get_all(          where => [ and => [ @f_date, @f_salesman, SL::DB::Manager::Order->type_filter('sales_quotation')   ]]),
94     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) ]),
95     sales_orders_per_inv   => [],
96     requests_for_quotation => SL::DB::Manager::Order->get_all(          where => [ and => [ @f_date, @f_salesman, SL::DB::Manager::Order->type_filter('request_quotation') ]]),
97     purchase_orders        => SL::DB::Manager::Order->get_all(          where => [ and => [ @f_date, @f_salesman, SL::DB::Manager::Order->type_filter('purchase_order')    ]]),
98     sales_invoices         => SL::DB::Manager::Invoice->get_all(        where => [ and => [ @f_date, @f_salesman, ]]),
99     purchase_invoices      => SL::DB::Manager::PurchaseInvoice->get_all(where => [ and =>  \@f_date ]),
100     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) ]),
101   });
102
103   $self->objects->{sales_orders} = [ grep { !$_->periodic_invoices_config || !$_->periodic_invoices_config->active } @{ $self->objects->{sales_orders} } ];
104 }
105
106 sub init_show_costs { $::instance_conf->get_profit_determination eq 'balance' }
107
108 sub init_types {
109   my ($self) = @_;
110   my @types  = qw(sales_quotations sales_orders sales_orders_per_inv sales_invoices requests_for_quotation purchase_orders purchase_invoices);
111   push @types, 'costs' if $self->show_costs;
112
113   return \@types;
114 }
115
116 sub init_data {
117   my ($self) = @_;
118
119   my %data  = (
120     year    => [ ($self->year) x 12                   ],
121     month   => [ (1..12)                              ],
122     quarter => [ (1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4) ],
123     map {
124       $_ => {
125         months   => [ (0) x 12 ],
126         quarters => [ (0) x  4 ],
127         year     => 0,
128       }
129     } @{ $self->types },
130   );
131
132   return \%data;
133 }
134
135 sub calculate_one_time_data {
136   my ($self) = @_;
137
138   foreach my $type (@{ $self->types }) {
139     my $src_object_type = $type eq 'sales_orders_per_inv' ? 'sales_orders' : $type;
140     foreach my $object (@{ $self->objects->{ $src_object_type } || [] }) {
141       my $month                              = $object->transdate->month - 1;
142       my $tdata                              = $self->data->{$type};
143
144       $tdata->{months}->[$month]            += $object->netamount;
145       $tdata->{quarters}->[int($month / 3)] += $object->netamount;
146       $tdata->{year}                        += $object->netamount;
147     }
148   }
149 }
150
151 sub calculate_periodic_invoices {
152   my ($self)     = @_;
153
154   my $start_date = DateTime->new(year => $self->year, month =>  1, day =>  1, time_zone => $::locale->get_local_time_zone);
155   my $end_date   = DateTime->new(year => $self->year, month => 12, day => 31, time_zone => $::locale->get_local_time_zone);
156
157   $self->calculate_one_periodic_invoice(config => $_, start_date => $start_date, end_date => $end_date) for @{ $self->objects->{periodic_invoices_cfg} };
158 }
159
160 sub calculate_one_periodic_invoice {
161   my ($self, %params) = @_;
162
163   # Calculate sales order advance
164   my $net  = $params{config}->order->netamount * $params{config}->get_billing_period_length / $params{config}->get_order_value_period_length;
165   my $sord = $self->data->{sales_orders};
166
167   foreach my $date ($params{config}->calculate_invoice_dates(start_date => $params{start_date}, end_date => $params{end_date}, past_dates => 1)) {
168     $sord->{months  }->[ $date->month   - 1 ] += $net;
169     $sord->{quarters}->[ $date->quarter - 1 ] += $net;
170     $sord->{year}                             += $net;
171   }
172
173   # Calculate total sales order value
174   my $date = $params{config}->order->transdate;
175   return if $date->year != $params{start_date}->year;
176
177   $net                                       = $params{config}->order->netamount;
178   $sord                                      = $self->data->{sales_orders_per_inv};
179   $sord->{months  }->[ $date->month   - 1 ] += $net;
180   $sord->{quarters}->[ $date->quarter - 1 ] += $net;
181   $sord->{year}                             += $net;
182 }
183
184 sub calculate_costs {
185   my ($self) = @_;
186
187   # Relevante BWA-Positionen für Kosten:
188   #  4 – Mat./Wareneinkauf
189   # 10 – Personalkosten
190   # 11 – Raumkosten
191   # 12 – Betriebl.Steuern
192   # 13 – Versicherungsbeiträge
193   # 14 – KFZ-Kosten ohne Steuern
194   # 15 – Werbe-/Reisekosten
195   # 16 – Kosten Warenabgabe
196   # 17 – Abschreibungen
197   # 18 – Reparatur/Instandhaltung
198   # 20 – Sonstige Kosten
199   my $query = <<SQL;
200     SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount,
201       EXTRACT(month FROM ac.transdate) AS month
202     FROM acc_trans ac
203     LEFT JOIN chart c ON (c.id = ac.chart_id)
204     WHERE (c.pos_bwa IN (4, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20))
205       AND (ac.transdate >= ?)
206       AND (ac.transdate <  ?)
207     GROUP BY month
208 SQL
209
210   my @args = (
211     DateTime->new_local(day => 1, month => 1, year => $self->year)->to_kivitendo,
212     DateTime->new_local(day => 1, month => 1, year => $self->year + 1)->to_kivitendo,
213   );
214
215   my @results = selectall_hashref_query($::form, SL::DB::AccTransaction->new->db->dbh, $query, @args);
216   foreach my $row (@results) {
217     my $month                              = $row->{month} - 1;
218     my $tdata                              = $self->data->{costs};
219
220     $tdata->{months}->[$month]            += $row->{amount};
221     $tdata->{quarters}->[int($month / 3)] += $row->{amount};
222     $tdata->{year}                        += $row->{amount};
223   }
224 }
225
226 sub list_data {
227   my ($self)           = @_;
228
229   my @visible_columns  = $self->report->get_visible_columns;
230   my @type_columns     = @{ $self->types };
231   my @non_type_columns = grep { my $c = $_; none { $c eq $_ } @type_columns } @visible_columns;
232
233   for my $month (1..12) {
234     my %data  = (
235       map({ ($_ => { data => $self->data->{$_}->[$month - 1]                                                    }) } @non_type_columns),
236       map({ ($_ => { data => $::form->format_amount(\%::myconfig, $self->data->{$_}->{months}->[$month - 1], 2) }) } @type_columns    ),
237     );
238
239     $self->report->add_data(\%data);
240
241     if ($self->subtotals_per_quarter && (($month % 3) == 0)) {
242       my %subtotal =  (
243         year       => { data => $self->year },
244         month      => { data => $::locale->text('Total') },
245         map { ($_ => { data => $::form->format_amount(\%::myconfig, $self->data->{$_}->{quarters}->[int(($month - 1) / 3)], 2) }) } @type_columns,
246       );
247
248       $subtotal{$_}->{class} = 'listsubtotal' for @visible_columns;
249
250       $self->report->add_data(\%subtotal);
251     }
252   }
253
254   my %data  =  (
255     year    => { data => $self->year },
256     quarter => { data => $::locale->text('Total') },
257     map { ($_ => { data => $::form->format_amount(\%::myconfig, $self->data->{$_}->{year}, 2) }) } @type_columns,
258   );
259
260   $data{$_}->{class} = 'listtotal' for @visible_columns;
261
262   $self->report->add_data(\%data);
263
264   return $self->report->generate_with_headers;
265 }
266
267 sub init_employees { SL::DB::Manager::Employee->get_all_sorted }
268
269 1;