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