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