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