Refactoring
[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(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   netamount               => t8('Order amount'),
28 );
29
30 sub action_list {
31   my ($self) = @_;
32
33   $self->project_types(SL::DB::Manager::ProjectType->get_all_sorted);
34
35   $self->make_filter_summary;
36
37   $self->prepare_report;
38
39   $self->{orders} = $self->models->get;
40
41   $self->calculate_data;
42
43   $self->list_objects;
44 }
45
46 # private functions
47
48 sub prepare_report {
49   my ($self)      = @_;
50
51   my $report      = SL::ReportGenerator->new(\%::myconfig, $::form);
52   $self->{report} = $report;
53
54   my @columns     = qw(customer globalprojectnumber globalproject_type ordnumber netamount delivered_amount delivered_amount_p billed_amount billed_amount_p paid_amount paid_amount_p
55                        billable_amount billable_amount_p other_amount);
56   my @sortable    = qw(ordnumber transdate customer netamount globalprojectnumber globalproject_type);
57   $self->{number_columns} = [ qw(netamount billed_amount billed_amount_p delivered_amount delivered_amount_p paid_amount paid_amount_p other_amount billable_amount billable_amount_p) ];
58
59   my %column_defs           = (
60     netamount               => {                                                                                         },
61     billed_amount           => { text     => $::locale->text('Billed amount')                                            },
62     billed_amount_p         => { text     => $::locale->text('%')                                                        },
63     delivered_amount        => { text     => $::locale->text('Delivered amount')                                         },
64     delivered_amount_p      => { text     => $::locale->text('%')                                                        },
65     paid_amount             => { text     => $::locale->text('Paid amount')                                              },
66     paid_amount_p           => { text     => $::locale->text('%')                                                        },
67     billable_amount         => { text     => $::locale->text('Billable amount')                                          },
68     billable_amount_p       => { text     => $::locale->text('%')                                                        },
69     other_amount            => { text     => $::locale->text('Billed extra expenses')                                    },
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   map { $column_defs{$_}->{text} ||= $::locale->text( $self->models->get_sort_spec->{$_}->{title} ) } keys %column_defs;
80   map { $column_defs{$_}->{align} = 'right' } @{ $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     foreach (qw(delivered billed paid billable)) {
124       $order->{"${_}_amount_p"} = $order->netamount * 1 ? $order->{"${_}_amount"} * 100 / $order->netamount : undef;
125     }
126   }
127 }
128
129 sub sum_items {
130   my ($self, %params) = @_;
131
132   my %vals;
133
134   foreach my $item (@{ $params{obj}->items }) {
135     my $key  = $item->parts_id;
136     $key    .= ':' . $item->serialnumber if $item->serialnumber;
137
138     $vals{$key}            ||= { parts_id => $item->parts_id, serialnumber => $item->serialnumber, amount => 0, base_qty => 0 };
139     $vals{$key}->{amount}   += $item->qty * $item->sellprice * (1 - $item->discount) / (($item->price_factor * 1) || 1);
140     $vals{$key}->{base_qty} += $item->qty * $item->unit_obj->base_factor;
141   }
142
143   return \%vals;
144 }
145
146 sub sum_relevant_items {
147   my ($self, %params) = @_;
148
149   $params{order}->{amounts_by_parts_id} ||= $self->sum_items(obj => $params{order});
150   my $sums                                = $self->sum_items(obj => $params{other});
151   my $total                               = 0;
152
153   foreach my $item (grep { $params{order}->{amounts_by_parts_id}->{ $_->{parts_id} } } values %{ $sums }) {
154     my $key = $item->{parts_id};
155
156     if ($params{by_order}) {
157       $key           .= ':' . $item->{serialnumber};
158       my $order_item  = $params{order}->{amounts_by_parts_id}->{ $key } || $params{order}->{amounts_by_parts_id}->{ $item->{parts_id} };
159
160       if ($order_item && $order_item->{base_qty}) {
161         $total += $order_item->{amount} * $item->{base_qty} / $order_item->{base_qty};
162         next;
163       }
164     }
165
166     $total += $item->{amount};
167   }
168
169   return $total;
170 }
171
172 sub list_objects {
173   my ($self)      = @_;
174   my $modify_data = sub {
175     my ($data) = @_;
176     map { $data->{$_}->{data} = defined $data->{$_}->{data} ? int($data->{$_}->{data}) : ''  } grep {  m/_p$/ } @{ $self->{number_columns} };
177     map { $data->{$_}->{data} = $::form->format_amount(\%::myconfig, $data->{$_}->{data}, 2) } grep { !m/_p$/ } @{ $self->{number_columns} };
178   };
179
180   return $self->report_generator_list_objects(report => $self->{report}, objects => $self->{orders}, data_callback => $modify_data);
181 }
182
183 sub make_filter_summary {
184   my ($self) = @_;
185
186   my $filter = $::form->{filter} || {};
187   my @filter_strings;
188
189   my @filters = (
190     [ $filter->{"ordnumber:substr::ilike"},                $::locale->text('Number')                                          ],
191     [ $filter->{"transdate:date::ge"},                     $::locale->text('Order Date') . " " . $::locale->text('From Date') ],
192     [ $filter->{"transdate:date::le"},                     $::locale->text('Order Date') . " " . $::locale->text('To Date')   ],
193     [ $filter->{customer}{"name:substr::ilike"},           $::locale->text('Customer')                                        ],
194     [ $filter->{customer}{"customernumber:substr::ilike"}, $::locale->text('Customer Number')                                 ],
195   );
196
197   $self->{filter_summary} = join ', ', @filter_strings;
198 }
199
200 sub init_models {
201   my ($self) = @_;
202
203   SL::Controller::Helper::GetModels->new(
204     controller   => $self,
205     model        => 'Order',
206     sorted       => {
207       _default     => {
208         by           => 'globalprojectnumber',
209         dir          => 1,
210       },
211       %sort_columns,
212     },
213     query => [
214       SL::DB::Manager::Order->type_filter('sales_order'),
215       '!closed' => 1,
216       or        => [
217         globalproject_id => undef,
218         and              => [
219           'globalproject.active' => 1,
220           'globalproject.valid'  => 1,
221         ]],
222     ],
223     with_objects => [ 'customer', 'globalproject', 'globalproject.project_type' ],
224   );
225 }
226
227 sub link_to {
228   my ($self, $object, %params) = @_;
229
230   return unless $object;
231   my $action = $params{action} || 'edit';
232
233   if ($object->isa('SL::DB::Order')) {
234     my $type = $object->type;
235     my $id   = $object->id;
236
237     return "oe.pl?action=$action&type=$type&vc=customer&id=$id";
238   }
239   if ($object->isa('SL::DB::Customer')) {
240     my $id     = $object->id;
241     return "ct.pl?action=$action&id=$id&db=customer";
242   }
243   if ($object->isa('SL::DB::Project')) {
244     my $id     = $object->id;
245     return "controller.pl?action=Project/$action&id=$id";
246   }
247 }
248
249 1;