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