GDPDU: DATEV-ähnlicher Buchungsexport Rohversion
[kivitendo-erp.git] / SL / Controller / FinancialControllingReport.pm
1 package SL::Controller::FinancialControllingReport;
2
3 use strict;
4 use parent qw(SL::Controller::Base);
5
6 use List::Util qw(max min sum);
7
8 use SL::DB::Order;
9 use SL::DB::ProjectType;
10 use SL::Controller::Helper::GetModels;
11 use SL::Controller::Helper::ReportGenerator;
12 use SL::Locale::String;
13
14 use Rose::Object::MakeMethods::Generic (
15   scalar                  => [ qw(orders) ],
16   'scalar --get_set_init' => [ qw(project_types models) ],
17 );
18
19 __PACKAGE__->run_before(sub { $::auth->assert('sales_order_edit'); });
20
21 my %sort_columns = (
22   ordnumber               => t8('Order'),
23   customer                => t8('Customer'),
24   transaction_description => t8('Transaction description'),
25   globalprojectnumber     => t8('Project'),
26   globalproject_type      => t8('Project Type'),
27 );
28
29 sub action_list {
30   my ($self) = @_;
31
32   $self->make_filter_summary;
33
34   $self->prepare_report;
35
36   $self->orders($self->models->get);
37
38   $self->calculate_data;
39
40   $self->list_objects;
41 }
42
43 # private functions
44
45 sub prepare_report {
46   my ($self)      = @_;
47
48   my $report      = SL::ReportGenerator->new(\%::myconfig, $::form);
49   $self->{report} = $report;
50
51   my @columns     = qw(customer globalprojectnumber globalproject_type transaction_description ordnumber net_amount delivered_amount delivered_amount_p billed_amount billed_amount_p paid_amount paid_amount_p
52                        billable_amount billable_amount_p other_amount);
53   my @sortable    = qw(ordnumber transdate customer globalprojectnumber globalproject_type transaction_description );
54   $self->{number_columns} = [ qw(net_amount billed_amount billed_amount_p delivered_amount delivered_amount_p paid_amount paid_amount_p other_amount billable_amount billable_amount_p) ];
55
56   my %column_defs           = (
57     net_amount              => { text     => $::locale->text('Order amount')                                             },
58     billed_amount           => { text     => $::locale->text('Billed amount')                                            },
59     billed_amount_p         => { text     => $::locale->text('%')                                                        },
60     delivered_amount        => { text     => $::locale->text('Delivered amount')                                         },
61     delivered_amount_p      => { text     => $::locale->text('%')                                                        },
62     paid_amount             => { text     => $::locale->text('Paid amount')                                              },
63     paid_amount_p           => { text     => $::locale->text('%')                                                        },
64     billable_amount         => { text     => $::locale->text('Billable amount')                                          },
65     billable_amount_p       => { text     => $::locale->text('%')                                                        },
66     other_amount            => { text     => $::locale->text('Billed extra expenses')                                    },
67     transaction_description => { text     => $::locale->text('Transaction description')                                  },
68     ordnumber               => { obj_link => sub { $self->link_to($_[0])                                              }  },
69     customer                => {      sub => sub { $_[0]->customer->name                                              },
70                                  obj_link => sub { $self->link_to($_[0]->customer)                                    }  },
71     globalprojectnumber     => {      sub => sub { $_[0]->globalproject_id ? $_[0]->globalproject->projectnumber : '' },
72                                  obj_link => sub { $self->link_to($_[0]->globalproject)                               }  },
73     globalproject_type      => { text     => $::locale->text('Project type'),
74                                  sub      => sub { $_[0]->globalproject_id ? $_[0]->globalproject->project_type->description : '' }  },
75   );
76
77   $column_defs{$_}->{text} ||= $::locale->text( $self->models->get_sort_spec->{$_}->{title} ) for keys %column_defs;
78   $column_defs{$_}->{align}  = 'right'                                                        for @{ $self->{number_columns} };
79
80   $report->set_options(
81     std_column_visibility => 1,
82     controller_class      => 'FinancialControllingReport',
83     output_format         => 'HTML',
84     top_info_text         => $::locale->text('Financial controlling report for open sales orders'),
85     title                 => $::locale->text('Financial Controlling Report'),
86     allow_pdf_export      => 1,
87     allow_csv_export      => 1,
88   );
89   $report->set_columns(%column_defs);
90   $report->set_column_order(@columns);
91   $report->set_export_options(qw(list filter));
92   $report->set_options_from_form;
93   $self->models->disable_plugin('paginated') if $report->{options}{output_format} =~ /^(pdf|csv)$/i;
94   $self->models->finalize;
95   $self->models->set_report_generator_sort_options(report => $report, sortable_columns => \@sortable);
96   $report->set_options(
97     raw_top_info_text     => $self->render('financial_controlling_report/report_top',    { output => 0 }),
98     raw_bottom_info_text  => $self->render('financial_controlling_report/report_bottom', { output => 0 }, models => $self->models),
99   );
100 }
101
102 sub calculate_data {
103   my ($self) = @_;
104
105   foreach my $order (@{ $self->orders }) {
106     my @delivery_orders = @{ $order->linked_records(direction => 'to', to => 'DeliveryOrder', via => 'Order', query => [ '!customer_id' => undef ]) };
107     my @invoices        = @{ $order->linked_records(direction => 'to', to => 'Invoice',       via => [ 'Order', 'DeliveryOrder' ])                  };
108
109     @invoices = (
110       grep({ !$_->storno_id } @invoices),
111       map({ @{ $_->storno_invoices } } grep { $_->storno && !$_->storno_id } @invoices),
112     );
113
114     $order->{delivered_amount}  = sum(map { $self->sum_relevant_items(order => $order, other => $_, by_order => 1)    } @delivery_orders) // 0;
115     $order->{billed_amount}     = sum(map { $self->sum_relevant_items(order => $order, other => $_)                   } @invoices)        // 0;
116     $order->{paid_amount}       = sum(map { $_->paid * $_->netamount / (($_->amount * 1) || ($_->netamount * 1) || 1) } @invoices)        // 0;
117     my $billed_amount           = sum(map { $_->netamount                                                             } @invoices)        // 0;
118     $order->{other_amount}      = $billed_amount             - $order->{billed_amount};
119     $order->{billable_amount}   = $order->{delivered_amount} - $order->{billed_amount};
120
121     if ($order->periodic_invoices_config) {
122       $order->{net_amount} = $self->calculate_periodic_invoices_order_netamount($order);
123
124     } else {
125       $order->{net_amount} = $order->netamount;
126     }
127
128     foreach (qw(delivered billed paid billable)) {
129       $order->{"${_}_amount_p"} = $order->{net_amount} * 1 ? $order->{"${_}_amount"} * 100 / $order->{net_amount} : undef;
130     }
131   }
132 }
133
134 sub calculate_periodic_invoices_order_netamount {
135   my ($self, $order) = @_;
136
137   my $year       = DateTime->today_local->year;
138   my $year_start = DateTime->new_local(day =>  1, month =>  1, year => $year);
139   my $year_end   = DateTime->new_local(day => 31, month => 12, year => $year);
140
141   my $cfg        = $order->periodic_invoices_config;
142   my $period_len = $cfg->get_billing_period_length;
143   my $num_months = 0;
144   my $cur_date   = $cfg->start_date->clone;
145   my $end_date   = $cfg->terminated ? $cfg->end_date : undef;
146   $end_date    //= $year_end;
147   $end_date      = min $end_date, $year_end;
148
149   while ($cur_date <= $end_date) {
150     $num_months += $period_len if $cur_date >= $year_start;
151     $cur_date->add(months => $period_len);
152   }
153
154   return $num_months * $order->netamount / $order->periodic_invoices_config->get_order_value_period_length;
155 }
156
157 sub sum_items {
158   my ($self, %params) = @_;
159
160   my %vals;
161
162   foreach my $item (@{ $params{obj}->items }) {
163     my $key  = $item->parts_id;
164     $key    .= ':' . $item->serialnumber if $item->serialnumber;
165
166     $vals{$key}            ||= { parts_id => $item->parts_id, serialnumber => $item->serialnumber, amount => 0, base_qty => 0 };
167     $vals{$key}->{amount}   += $item->qty * $item->sellprice * (1 - $item->discount) / (($item->price_factor * 1) || 1);
168     $vals{$key}->{base_qty} += $item->qty * $item->unit_obj->base_factor;
169   }
170
171   return \%vals;
172 }
173
174 sub sum_relevant_items {
175   my ($self, %params) = @_;
176
177   $params{order}->{amounts_by_parts_id} ||= $self->sum_items(obj => $params{order});
178   my $sums                                = $self->sum_items(obj => $params{other});
179   my $total                               = 0;
180
181   foreach my $item (grep { $params{order}->{amounts_by_parts_id}->{ $_->{parts_id} } } values %{ $sums }) {
182     my $key = $item->{parts_id};
183
184     if ($params{by_order}) {
185       $key           .= ':' . $item->{serialnumber};
186       my $order_item  = $params{order}->{amounts_by_parts_id}->{ $key } || $params{order}->{amounts_by_parts_id}->{ $item->{parts_id} };
187
188       if ($order_item && $order_item->{base_qty}) {
189         $total += $order_item->{amount} * $item->{base_qty} / $order_item->{base_qty};
190         next;
191       }
192     }
193
194     $total += $item->{amount};
195   }
196
197   return $total;
198 }
199
200 sub list_objects {
201   my ($self)      = @_;
202   my $modify_data = sub {
203     my ($data) = @_;
204     $data->{$_}->{data} = defined $data->{$_}->{data} ? int($data->{$_}->{data}) : ''  for grep {  m/_p$/ } @{ $self->{number_columns} };
205     $data->{$_}->{data} = $::form->format_amount(\%::myconfig, $data->{$_}->{data}, 2) for grep { !m/_p$/ } @{ $self->{number_columns} };
206   };
207
208   return $self->report_generator_list_objects(report => $self->{report}, objects => $self->orders, data_callback => $modify_data);
209 }
210
211 sub make_filter_summary {
212   my ($self) = @_;
213
214   my $filter = $::form->{filter} || {};
215   my @filter_strings;
216
217   my @filters = (
218     [ $filter->{"ordnumber:substr::ilike"},                $::locale->text('Number')                                          ],
219     [ $filter->{"transdate:date::ge"},                     $::locale->text('Order Date') . " " . $::locale->text('From Date') ],
220     [ $filter->{"transdate:date::le"},                     $::locale->text('Order Date') . " " . $::locale->text('To Date')   ],
221     [ $filter->{customer}{"name:substr::ilike"},           $::locale->text('Customer')                                        ],
222     [ $filter->{customer}{"customernumber:substr::ilike"}, $::locale->text('Customer Number')                                 ],
223   );
224
225   $self->{filter_summary} = join ', ', @filter_strings;
226 }
227
228 sub init_project_types { SL::DB::Manager::ProjectType->get_all_sorted }
229
230 sub init_models {
231   my ($self) = @_;
232
233   SL::Controller::Helper::GetModels->new(
234     controller   => $self,
235     model        => 'Order',
236     sorted       => {
237       _default     => {
238         by           => 'globalprojectnumber',
239         dir          => 1,
240       },
241       %sort_columns,
242     },
243     query => [
244       SL::DB::Manager::Order->type_filter('sales_order'),
245       '!closed' => 1,
246       (salesman_id => SL::DB::Manager::Employee->current->id) x !$::auth->assert('sales_all_edit', 1),
247       or        => [
248         globalproject_id => undef,
249         and              => [
250           'globalproject.active' => 1,
251           'globalproject.valid'  => 1,
252         ]],
253       # keine WR
254       # oder aber (WR aktiv und (kein enddatum oder enddatum noch nicht Ã¼berschritten))
255       or => [
256         'periodic_invoices_config.id' => undef,
257         # and => [
258           'periodic_invoices_config.active' => 1,
259         #   or => [
260         #     'periodic_invoices_config.end_date' => undef,
261         #     'periodic_invoices_config.end_date' => { le => DateTime->today_local },
262         # ]
263         # ]
264       ],
265     ],
266     with_objects => [ 'customer', 'globalproject', 'globalproject.project_type', 'periodic_invoices_config' ],
267   );
268 }
269
270 sub link_to {
271   my ($self, $object, %params) = @_;
272
273   return unless $object;
274   my $action = $params{action} || 'edit';
275
276   if ($object->isa('SL::DB::Order')) {
277     my $type = $object->type;
278     my $id   = $object->id;
279
280     return "oe.pl?action=$action&type=$type&vc=customer&id=$id";
281   }
282   if ($object->isa('SL::DB::Customer')) {
283     my $id     = $object->id;
284     return "controller.pl?action=CustomerVendor/$action&id=$id";
285   }
286   if ($object->isa('SL::DB::Project')) {
287     my $id     = $object->id;
288     return "controller.pl?action=Project/$action&id=$id";
289   }
290 }
291
292 1;