trailing whitespaces entfernt
[kivitendo-erp.git] / SL / Controller / DeliveryPlan.pm
1 package SL::Controller::DeliveryPlan;
2
3 use strict;
4 use parent qw(SL::Controller::Base);
5
6 use Clone qw(clone);
7 use SL::DB::OrderItem;
8 use SL::DB::Business;
9 use SL::Controller::Helper::GetModels;
10 use SL::Controller::Helper::ReportGenerator;
11 use SL::Locale::String;
12 use SL::AM;
13 use SL::DBUtils ();
14 use Carp;
15
16 use Rose::Object::MakeMethods::Generic (
17   scalar => [ qw(db_args flat_filter) ],
18   'scalar --get_set_init' => [ qw(models all_edit_right mode vc all_employees all_businesses) ],
19 );
20
21 __PACKAGE__->run_before(sub { $::auth->assert('delivery_plan'); });
22
23 my %sort_columns = (
24   reqdate           => t8('Reqdate'),
25   description       => t8('Description'),
26   partnumber        => t8('Part Number'),
27   qty               => t8('Qty'),
28   unit              => t8('Unit'),
29   shipped_qty       => t8('shipped'),
30   delivered_qty     => t8('transferred in / out'),
31   not_shipped_qty   => t8('not shipped'),
32   ordnumber         => t8('Order'),
33   customer          => t8('Customer'),
34   vendor            => t8('Vendor'),
35   value_of_goods    => t8('Value of transferred goods'),
36 );
37
38
39 sub action_list {
40   my ($self) = @_;
41   $self->make_filter_summary;
42   $self->prepare_report;
43
44   my $orderitems = $self->models->get;
45
46   $self->calc_qtys($orderitems);
47   $self->report_generator_list_objects(report => $self->{report}, objects => $orderitems);
48 }
49
50 # private functions
51 #
52 sub prepare_report {
53   my ($self)      = @_;
54
55   my $vc          = $self->vc;
56   my $mode        = $self->mode;
57   my $report      = SL::ReportGenerator->new(\%::myconfig, $::form);
58   my $csv_option  = $::form->{report_generator_output_format};
59   $self->{report} = $report;
60
61   my @columns     = qw(reqdate customer vendor ordnumber partnumber description qty shipped_qty not_shipped_qty delivered_qty value_of_goods);
62
63   my @sortable    = qw(reqdate customer vendor ordnumber partnumber description);
64   my $rp_csv_mod  = ($csv_option eq 'CSV' && $mode eq 'delivery_value_report') ? 1 : '';
65
66   my %column_defs = (
67     reqdate           => {      sub => sub { $_[0]->reqdate_as_date || $_[0]->order->reqdate_as_date                         } },
68     description       => {      sub => sub { $_[0]->description                                                              },
69                            obj_link => sub { $self->link_to($_[0]->part)                                                     } },
70     partnumber        => {      sub => sub { $_[0]->part->partnumber                                                         },
71                            obj_link => sub { $self->link_to($_[0]->part)                                                     } },
72     qty               => {      sub => sub { $_[0]->qty_as_number .
73                                              ($rp_csv_mod ? '' : ' ' .  $_[0]->unit)                                         } },
74     unit              => {      sub => sub {  $_[0]->unit                                                                    },
75                             visible => $rp_csv_mod                                                                           },
76     shipped_qty       => {      sub => sub { $::form->format_amount(\%::myconfig, $_[0]{shipped_qty}, 2) .
77                                              ($rp_csv_mod ? '' : ' ' .  $_[0]->unit)                                         } },
78     not_shipped_qty   => {      sub => sub { $::form->format_amount(\%::myconfig, $_[0]->qty - $_[0]{shipped_qty}, 2) .
79                                              ($rp_csv_mod ? '' : ' ' .  $_[0]->unit)                                         } },
80     delivered_qty     => {      sub => sub { $::form->format_amount(\%::myconfig, $_[0]{delivered_qty}, 2) .
81                                              ($rp_csv_mod ? '' : ' ' .  $_[0]->unit)                                         } },
82     ordnumber         => {      sub => sub { $_[0]->order->ordnumber                                                         },
83                            obj_link => sub { $self->link_to($_[0]->order)                                                    } },
84     vendor            => {      sub => sub { $_[0]->order->vendor->name                                                      },
85                             visible => $vc eq 'vendor',
86                            obj_link => sub { $self->link_to($_[0]->order->vendor)                                            } },
87     customer          => {      sub => sub { $_[0]->order->customer->name                                                    },
88                             visible => $vc eq 'customer',
89                            obj_link => sub { $self->link_to($_[0]->order->customer)                                          } },
90     value_of_goods    => {      sub => sub { $::form->format_amount(\%::myconfig, $_[0]->value_of_goods, 2) . ' ' . $_[0]->taxincluded },
91                             visible => $::auth->assert('sales_order_edit', 1) && $mode eq 'delivery_value_report' &&   $::instance_conf->get_delivery_plan_show_value_of_goods, },
92   );
93
94   $column_defs{$_}->{text} = $sort_columns{$_} for keys %column_defs;
95
96   $report->set_options(
97     std_column_visibility => 1,
98     controller_class      => 'DeliveryPlan',
99     output_format         => 'HTML',
100     top_info_text         => ($vc eq 'customer') ?  (($mode eq 'delivery_plan') ? $::locale->text('Delivery Plan for currently outstanding sales orders') :
101                                                    $::locale->text('Delivery Value Report for currently open sales orders')) :
102                                                    ($mode eq 'delivery_value_report') ? $::locale->text('Delivery Value Report for currently outstanding purchase orders') :
103                                                    $::locale->text('Delivery Plan for currently outstanding purchase orders'),
104     title                 => ($mode eq 'delivery_plan') ? $::locale->text('Delivery Plan') : $::locale->text('Delivery Value Report'),
105     allow_pdf_export      => 1,
106     allow_csv_export      => 1,
107   );
108   $report->set_columns(%column_defs);
109   $report->set_column_order(@columns);
110   $report->set_export_options(qw(list filter vc mode));
111   $report->set_options_from_form;
112   $self->models->disable_plugin('paginated') if $report->{options}{output_format} =~ /^(pdf|csv)$/i;
113   $self->models->finalize; # for filter laundering
114   $self->models->set_report_generator_sort_options(report => $report, sortable_columns => \@sortable);
115   $report->set_options(
116     raw_top_info_text     => $self->render('delivery_plan/report_top',    { output => 0 }),
117     raw_bottom_info_text  => $self->render('delivery_plan/report_bottom', { output => 0 }, models => $self->models),
118   );
119 }
120
121 sub calc_qtys {
122   my ($self, $orderitems) = @_;
123   # using $orderitem->shipped_qty 40 times is far too slow. need to do it manually
124   #
125   my %orderitems_by_id = map { $_->id => $_ } @$orderitems;
126
127   my $query = <<SQL;
128     SELECT oi.id, doi.qty, doi.qty, doi.unit, doe.delivered
129     FROM record_links rl
130     INNER JOIN delivery_order_items doi ON (doi.delivery_order_id = rl.to_id)
131     INNER JOIN delivery_orders doe ON (doe.id = rl.to_id)
132     INNER JOIN orderitems oi ON (oi.trans_id = rl.from_id)
133     WHERE rl.from_table = 'oe'
134       AND rl.to_table   = 'delivery_orders'
135       AND oi.parts_id   = doi.parts_id
136       AND oi.id IN (@{[ join ', ', ("?")x @$orderitems ]})
137 SQL
138
139   my $result = SL::DBUtils::selectall_hashref_query($::form, $::form->get_standard_dbh, $query, map { $_->id } @$orderitems);
140
141   for my $row (@$result) {
142     my $item = $orderitems_by_id{ $row->{id} };
143     $item->{shipped_qty}   ||= 0;
144     $item->{delivered_qty} ||= 0;
145     $item->{shipped_qty}    += AM->convert_unit($row->{unit} => $item->unit) * $row->{qty};
146     $item->{delivered_qty}  += AM->convert_unit($row->{unit} => $item->unit) * $row->{qty} if $row->{delivered};
147   }
148 }
149
150 sub make_filter_summary {
151   my ($self) = @_;
152   my $vc     = $self->vc;
153   my $mode   = $self->mode;
154   my ($business, $employee);
155
156   my $filter = $::form->{filter} || {};
157   my @filter_strings;
158
159   $business = SL::DB::Business->new(id => $filter->{order}{customer}{"business_id"})->load->description if $filter->{order}{customer}{"business_id"};
160   $employee = SL::DB::Employee->new(id => $filter->{order}{employee_id})->load->name if $filter->{order}{employee_id};
161
162   my @filters = (
163     [ $filter->{order}{"ordnumber:substr::ilike"},                    $::locale->text('Number')                                             ],
164     [ $filter->{order}{globalproject}{"projectnumber:substr::ilike"}, $::locale->text('Document Project Number')                            ],
165     [ $filter->{part}{"partnumber:substr::ilike"},                    $::locale->text('Part Number')                                        ],
166     [ $filter->{"description:substr::ilike"},                         $::locale->text('Part Description')                                   ],
167     [ $filter->{"reqdate:date::ge"},                                  $::locale->text('Delivery Date') . " " . $::locale->text('From Date') ],
168     [ $filter->{"reqdate:date::le"},                                  $::locale->text('Delivery Date') . " " . $::locale->text('To Date')   ],
169     [ $filter->{"qty:number"},                                        $::locale->text('Quantity')                                           ],
170     [ $filter->{order}{vendor}{"name:substr::ilike"},                 $::locale->text('Vendor')                                             ],
171     [ $filter->{order}{vendor}{"vendornumber:substr::ilike"},         $::locale->text('Vendor Number')                                      ],
172     [ $filter->{order}{customer}{"name:substr::ilike"},               $::locale->text('Customer')                                           ],
173     [ $filter->{order}{customer}{"customernumber:substr::ilike"},     $::locale->text('Customer Number')                                    ],
174     [ $business,                                                      $::locale->text('Customer type')                                      ],
175     [ $employee,                                                      $::locale->text('Employee')                                           ],
176   );
177
178   my %flags = (
179     part     => $::locale->text('Parts'),
180     service  => $::locale->text('Services'),
181     assembly => $::locale->text('Assemblies'),
182   );
183   my @flags = map { $flags{$_} } @{ $filter->{part}{type} || [] };
184
185   for (@flags) {
186     push @filter_strings, $_ if $_;
187   }
188   for (@filters) {
189     push @filter_strings, "$_->[1]: $_->[0]" if $_->[0];
190   }
191
192   $self->{filter_summary} = join ', ', @filter_strings;
193 }
194
195 sub delivery_plan_query {
196   my ($self) = @_;
197   my $vc     = $self->vc;
198   my $mode   = $self->mode;
199   my $employee_id = SL::DB::Manager::Employee->current->id;
200   my $oe_owner = $_[0]->all_edit_right ? '' : " oe.employee_id = $employee_id AND";
201   # check delivered state for delivery_orders (transferred out) if enabled
202   # OR if we are delivery_value_report mode
203   my $filter_delivered = ($::instance_conf->get_delivery_plan_calculate_transferred_do ||
204                           $mode eq 'delivery_value_report' ) ?
205                           "AND (SELECT delivered from delivery_orders where id = doi.delivery_order_id)" : '';
206   # Show ALL open orders in delivery_value_report mode
207   my $comment_show_all_open_orders = ($mode eq 'delivery_value_report' ) ? "-- " : "";
208   [
209   "order.${vc}_id" => { gt => 0 },
210   'order.closed' => 0,
211   or => [ 'order.quotation' => 0, 'order.quotation' => undef ],
212
213   # filter by shipped_qty < qty, read from innermost to outermost
214   'id' => [ \"
215     -- 3. resolve the desired information about those
216     SELECT oi.id FROM (
217       -- 2. slice only part, orderitem and both quantities from it
218       SELECT parts_id, trans_id, qty, SUM(doi_qty) AS doi_qty FROM (
219         -- 1. join orderitems and deliverorder items via record_links.
220         --    also add customer data to filter for sales_orders
221         SELECT oi.parts_id, oi.trans_id, oi.id, oi.qty, doi.qty AS doi_qty
222         FROM orderitems oi, oe, record_links rl, delivery_order_items doi
223         WHERE
224           oe.id = oi.trans_id AND
225           oe.${vc}_id IS NOT NULL AND
226           (oe.quotation = 'f' OR oe.quotation IS NULL) AND
227           NOT oe.closed AND
228           $oe_owner
229           rl.from_id = oe.id AND
230           rl.from_id = oi.trans_id AND
231           oe.id = oi.trans_id AND
232           rl.from_table = 'oe' AND
233           rl.to_table = 'delivery_orders' AND
234           rl.to_id = doi.delivery_order_id AND
235           oi.parts_id = doi.parts_id
236           $filter_delivered
237       ) tuples GROUP BY parts_id, trans_id, qty
238     ) partials
239     LEFT JOIN orderitems oi ON partials.parts_id = oi.parts_id AND partials.trans_id = oi.trans_id
240     WHERE oi.qty > doi_qty
241
242     UNION ALL
243
244     -- 4. since the join over record_links fails for sales_orders without any delivery order
245     --    retrieve those without record_links at all
246     SELECT oi.id FROM orderitems oi, oe
247     WHERE
248       oe.id = oi.trans_id AND
249       oe.${vc}_id IS NOT NULL AND
250       (oe.quotation = 'f' OR oe.quotation IS NULL) AND
251       NOT oe.closed AND
252       $oe_owner
253       oi.trans_id NOT IN (
254         SELECT from_id
255         FROM record_links rl
256         WHERE
257           rl.from_table ='oe' AND
258           rl.to_table = 'delivery_orders'
259       )
260
261     UNION ALL
262
263     -- 5. now for the really nasty cases.
264     --    If someone partially delivered an order in several delivery orders,
265     --    there will be lots of record_links (4 doesn't catch those) but those
266     --    won't have matching part_ids in delivery_order_items, so 1-3 can't
267     --    find anything
268     --    In this case aggreg record_links - delivery_order - delivery_order_items
269     --    slice only oe.id, parts_id and sum of of qty
270     --    left join that onto orderitems to get matching qtys in doi while retaining
271     --    entrys without matches and then throw out those without record_links
272     --    TODO: join this and 1-3 into a general case
273                   -- need debug info? uncomment these:
274     SELECT oi.id  -- ,oi.trans_id, oi.parts_id, coalesce(sum, 0), agg.parts_id
275     FROM orderitems oi LEFT JOIN (
276       SELECT rl.from_id as oid, doi.parts_id, sum(doi.qty) FROM (
277         SELECT from_id, to_id
278         FROM record_links rl
279         LEFT JOIN oe ON oe.id = from_id
280         WHERE
281           rl.from_table = 'oe' AND
282           rl.to_table = 'delivery_orders' AND
283
284           oe.${vc}_id IS NOT NULL AND
285           $oe_owner
286           (oe.quotation = 'f' OR oe.quotation IS NULL) AND NOT oe.closed
287       ) rl
288       LEFT JOIN delivery_order_items doi ON (rl.to_id = doi.delivery_order_id)
289       WHERE 1 = 1
290       $filter_delivered
291       GROUP BY rl.from_id, doi.parts_id
292     ) agg ON (agg.oid = oi.trans_id AND agg.parts_id = oi.parts_id)
293     LEFT JOIN oe ON oe.id = oi.trans_id
294     WHERE
295       EXISTS (
296         SELECT to_id
297         FROM record_links rl
298         WHERE oi.trans_id = rl.from_id AND rl.from_table = 'oe' AND rl.to_table = 'delivery_orders'
299       ) AND
300       $comment_show_all_open_orders coalesce(sum, 0) < oi.qty AND
301       oe.${vc}_id IS NOT NULL AND
302       $oe_owner
303       (oe.quotation = 'f' OR oe.quotation IS NULL) AND NOT oe.closed
304   " ],
305   ]
306 }
307
308 sub init_models {
309   my ($self) = @_;
310   my $vc     = $self->vc;
311   my $mode   = $self->mode;
312   SL::Controller::Helper::GetModels->new(
313     controller            => $self,
314     model                 => 'OrderItem',
315     sorted                => {
316       _default              => {
317         by                    => 'reqdate',
318         dir                   => 1,
319       },
320       %sort_columns,
321     },
322     query                 => $self->delivery_plan_query,
323     with_objects          => [ 'order', "order.$vc", 'part' ],
324     additional_url_params => { vc => $vc, mode => $mode},
325   );
326 }
327
328 sub init_all_edit_right {
329   $::auth->assert('sales_all_edit', 1)
330 }
331 sub init_vc {
332   return $::form->{vc} if ($::form->{vc} eq 'customer' || $::form->{vc} eq 'vendor') || croak "self (DeliveryPlan) has no vc defined";
333 }
334 sub init_mode {
335   return $::form->{mode} if ($::form->{mode} eq 'delivery_value_report' || $::form->{mode} eq 'delivery_plan') || croak "self (DeliveryPlan) has no mode defined";
336 }
337
338 sub init_all_employees {
339   return SL::DB::Manager::Employee->get_all_sorted;
340 }
341 sub init_all_businesses {
342   return SL::DB::Manager::Business->get_all_sorted;
343 }
344 sub link_to {
345   my ($self, $object, %params) = @_;
346
347   return unless $object;
348   my $action = $params{action} || 'edit';
349
350   if ($object->isa('SL::DB::Order')) {
351     my $type   = $object->type;
352     my $vc     = $object->is_sales ? 'customer' : 'vendor';
353     my $id     = $object->id;
354
355     return "oe.pl?action=$action&type=$type&vc=$vc&id=$id";
356   }
357   if ($object->isa('SL::DB::Part')) {
358     my $id     = $object->id;
359     return "ic.pl?action=$action&id=$id";
360   }
361   if ($object->isa('SL::DB::Customer')) {
362     my $id     = $object->id;
363     return "controller.pl?action=CustomerVendor/$action&id=$id&db=customer";
364   }
365 }
366
367 1;