6d7aaa908ba19481eb1aaabd7de9808f5cacb2ae
[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 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));
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()
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_linked_items {
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     SELECT id FROM (
175       SELECT oi.qty, oi.id, SUM(doi.qty) AS doi_qty
176       FROM orderitems oi, oe, record_links rl, delivery_order_items doi
177       WHERE
178         oe.id = oi.trans_id AND
179         oe.${vc}_id IS NOT NULL AND
180         (oe.quotation = 'f' OR oe.quotation IS NULL) AND
181         NOT oe.closed AND
182         $oe_owner
183         doi.id = rl.to_id AND
184         rl.from_table = 'orderitems'AND
185         rl.to_table   = 'delivery_order_items' AND
186         rl.from_id = oi.id
187       GROUP BY oi.id
188     ) linked
189     WHERE qty > doi_qty
190
191     UNION ALL
192
193     -- 2. since the join over record_links fails for items not in any delivery order
194     --    retrieve those without record_links at all
195     SELECT oi.id FROM orderitems oi, oe
196     WHERE
197       oe.id = oi.trans_id AND
198       oe.${vc}_id IS NOT NULL AND
199       (oe.quotation = 'f' OR oe.quotation IS NULL) AND
200       NOT oe.closed AND
201       $oe_owner
202       NOT EXISTS (
203         SELECT from_id
204         FROM record_links rl
205         WHERE
206           rl.from_table = 'orderitems' AND
207           rl.to_table = 'delivery_order_items' AND
208           rl.from_id = oi.id
209       )
210
211   " ], # make emacs happy again: " ]
212   ]
213 }
214
215 sub init_models {
216   my ($self) = @_;
217   my $vc     = $self->vc;
218
219   my $query = $self->delivery_plan_query_linked_items;
220
221   SL::Controller::Helper::GetModels->new(
222     controller   => $self,
223     model        => 'OrderItem',
224     sorted       => {
225       _default     => {
226         by           => 'reqdate',
227         dir          => 1,
228       },
229       %sort_columns,
230     },
231     query        => $query,
232     with_objects => [ 'order', "order.$vc", 'part' ],
233     additional_url_params => { vc => $vc },
234   );
235 }
236
237 sub init_all_edit_right {
238   return $_[0]->vc eq 'customer' ? $::auth->assert('sales_all_edit', 1) : $::auth->assert('purchase_all_edit', 1);
239 }
240 sub init_vc {
241   return $::form->{vc} if ($::form->{vc} eq 'customer' || $::form->{vc} eq 'vendor') || croak "self (DeliveryPlan) has no vc defined";
242 }
243
244 sub init_all_employees {
245   return SL::DB::Manager::Employee->get_all_sorted;
246 }
247 sub init_all_businesses {
248   return SL::DB::Manager::Business->get_all_sorted;
249 }
250 sub init_all_departments {
251   return SL::DB::Manager::Department->get_all_sorted;
252 }
253 sub link_to {
254   my ($self, $object, %params) = @_;
255
256   return unless $object;
257   my $action = $params{action} || 'edit';
258
259   if ($object->isa('SL::DB::Order')) {
260     my $type   = $object->type;
261     my $vc     = $object->is_sales ? 'customer' : 'vendor';
262     my $id     = $object->id;
263
264     if ($::instance_conf->get_feature_experimental_order) {
265       return "controller.pl?action=Order/$action&type=$type&id=$id";
266     } else {
267       return "oe.pl?action=$action&type=$type&vc=$vc&id=$id";
268     }
269   }
270   if ($object->isa('SL::DB::Part')) {
271     my $id     = $object->id;
272     return "controller.pl?action=Part/$action&part.id=$id";
273   }
274   if ($object->isa('SL::DB::Customer')) {
275     my $id     = $object->id;
276     return "controller.pl?action=CustomerVendor/$action&id=$id&db=customer";
277   }
278 }
279
280 sub setup_list_action_bar {
281   my ($self, %params) = @_;
282
283   for my $bar ($::request->layout->get('actionbar')) {
284     $bar->add(
285       action => [
286         t8('Update'),
287         submit    => [ '#filter_form', { action => 'DeliveryPlan/list' } ],
288         accesskey => 'enter',
289       ],
290     );
291   }
292 }
293
294 1;