test action
[kivitendo-erp.git] / SL / Controller / CsvImport / Inventory.pm
1 package SL::Controller::CsvImport::Inventory;
2
3
4 use strict;
5
6 use SL::Helper::Csv;
7 use SL::Helper::DateTime;
8
9 use SL::DBUtils;
10 use SL::DB::Inventory;
11 use SL::DB::Part;
12 use SL::DB::Warehouse;
13 use SL::DB::Bin;
14 use SL::DB::TransferType;
15 use SL::DB::Employee;
16
17 use parent qw(SL::Controller::CsvImport::Base);
18
19
20 use Rose::Object::MakeMethods::Generic
21 (
22  'scalar --get_set_init' => [ qw(settings parts_by warehouses_by bins_by) ],
23 );
24
25
26 sub init_class {
27   my ($self) = @_;
28   $self->class('SL::DB::Inventory');
29 }
30
31 sub set_profile_defaults {
32 };
33
34 sub init_profile {
35   my ($self) = @_;
36
37   my $profile = $self->SUPER::init_profile;
38   delete @{$profile}{qw(trans_id oe_id delivery_order_items_stock_id trans_type_id project_id)};
39   delete @{$profile}{qw(bestbefore)}    if !$::instance_conf->get_show_bestbefore;
40
41   return $profile;
42 }
43
44 sub init_settings {
45   my ($self) = @_;
46
47   return { map { ( $_ => $self->controller->profile->get($_) ) } qw(warehouse apply_warehouse
48                                                                     bin       apply_bin
49                                                                     comment   apply_comment) };
50 }
51
52 sub init_parts_by {
53   my ($self) = @_;
54
55   my $all_parts = SL::DB::Manager::Part->get_all;
56   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_parts } } ) } qw(id partnumber ean description) };
57 }
58
59 sub init_warehouses_by {
60   my ($self) = @_;
61
62   my $all_warehouses = SL::DB::Manager::Warehouse->get_all(query => [ or => [ invalid => 0, invalid => undef ]]);
63   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_warehouses } } ) } qw(id description) };
64 }
65
66 sub init_bins_by {
67   my ($self) = @_;
68
69   my $all_bins = SL::DB::Manager::Bin->get_all();
70   my $bins_by;
71   $bins_by->{_wh_id_and_id_ident()}          = { map { ( _wh_id_and_id_maker($_->warehouse_id, $_->id)                   => $_ ) } @{ $all_bins } };
72   $bins_by->{_wh_id_and_description_ident()} = { map { ( _wh_id_and_description_maker($_->warehouse_id, $_->description) => $_ ) } @{ $all_bins } };
73
74   return $bins_by;
75 }
76
77 sub check_objects {
78   my ($self) = @_;
79
80   $self->controller->track_progress(phase => 'building data', progress => 0);
81
82   my $i = 0;
83   my $num_data = scalar @{ $self->controller->data };
84   foreach my $entry (@{ $self->controller->data }) {
85     $self->controller->track_progress(progress => $i/$num_data * 100) if $i % 100 == 0;
86
87     $self->check_warehouse($entry);
88     $self->check_bin($entry);
89     $self->check_part($entry);
90     $self->check_qty($entry)            unless scalar @{ $entry->{errors} };
91     $self->handle_comment($entry);
92     $self->handle_employee($entry);
93     $self->handle_transfer_type($entry) unless scalar @{ $entry->{errors} };
94     $self->handle_shippingdate($entry);
95   } continue {
96     $i++;
97   }
98
99   $self->add_info_columns(qw(warehouse bin partnumber employee target_qty));
100 }
101
102 sub setup_displayable_columns {
103   my ($self) = @_;
104
105   $self->SUPER::setup_displayable_columns;
106
107   $self->add_displayable_columns({ name => 'bin',          description => $::locale->text('Bin')                     },
108                                  { name => 'bin_id',       description => $::locale->text('Bin (database ID)')       },
109                                  { name => 'chargenumber', description => $::locale->text('Charge number')           },
110                                  { name => 'comment',      description => $::locale->text('Comment')                 },
111                                  { name => 'employee_id',  description => $::locale->text('Employee (database ID)')  },
112                                  { name => 'partnumber',   description => $::locale->text('Part Number')             },
113                                  { name => 'parts_id',     description => $::locale->text('Part (database ID)')      },
114                                  { name => 'qty',          description => $::locale->text('qty (to transfer)')       },
115                                  { name => 'shippingdate', description => $::locale->text('Shipping date')           },
116                                  { name => 'target_qty',   description => $::locale->text('Target Qty')              },
117                                  { name => 'warehouse',    description => $::locale->text('Warehouse')               },
118                                  { name => 'warehouse_id', description => $::locale->text('Warehouse (database ID)') },
119                                 );
120   if ($::instance_conf->get_show_bestbefore) {
121     $self->add_displayable_columns({ name => 'bestbefore', description => $::locale->text('Best Before') });
122   }
123 }
124
125 sub check_warehouse {
126   my ($self, $entry) = @_;
127
128   my $object = $entry->{object};
129
130   # If warehouse from front-end is enforced for all transfers, use this, if valid.
131   if ($self->settings->{apply_warehouse} eq 'all') {
132     $object->warehouse_id(undef);
133     my $wh = $self->warehouses_by->{description}->{ $self->settings->{warehouse} };
134     if (!$wh) {
135       push @{ $entry->{errors} }, $::locale->text('Error: Invalid warehouse');
136       return 0;
137     }
138
139     $object->warehouse_id($wh->id);
140   }
141
142   # If warehouse from front-end is enforced for transfers with missing warehouse, use this, if valid.
143   if (    $self->settings->{apply_warehouse} eq 'missing'
144        && ! $object->warehouse_id
145        && ! $entry->{raw_data}->{warehouse} ) {
146     my $wh = $self->warehouses_by->{description}->{ $self->settings->{warehouse} };
147     if (!$wh) {
148       push @{ $entry->{errors} }, $::locale->text('Error: Invalid warehouse');
149       return 0;
150     }
151
152     $object->warehouse_id($wh->id);
153   }
154
155   # Check whether or not warehouse ID is valid.
156   if ($object->warehouse_id && !$self->warehouses_by->{id}->{ $object->warehouse_id }) {
157     push @{ $entry->{errors} }, $::locale->text('Error: Invalid warehouse');
158     return 0;
159   }
160
161   # Map description to ID if given.
162   if (!$object->warehouse_id && $entry->{raw_data}->{warehouse}) {
163     my $wh = $self->warehouses_by->{description}->{ $entry->{raw_data}->{warehouse} };
164     if (!$wh) {
165       push @{ $entry->{errors} }, $::locale->text('Error: Invalid warehouse');
166       return 0;
167     }
168
169     $object->warehouse_id($wh->id);
170   }
171
172   if ($object->warehouse_id) {
173     $entry->{info_data}->{warehouse} = $self->warehouses_by->{id}->{ $object->warehouse_id }->description;
174   } else {
175     push @{ $entry->{errors} }, $::locale->text('Error: Warehouse not found');
176     return 0;
177   }
178
179   return 1;
180 }
181
182 # Check bin for given warehouse, so check_warehouse must be called first.
183 sub check_bin {
184   my ($self, $entry) = @_;
185
186   my $object = $entry->{object};
187
188   # If bin from front-end is enforced for all transfers, use this, if valid.
189   if ($self->settings->{apply_bin} eq 'all') {
190     $object->bin_id(undef);
191     my $bin = $self->bins_by->{_wh_id_and_description_ident()}->{ _wh_id_and_description_maker($object->warehouse_id, $self->settings->{bin}) };
192     if (!$bin) {
193       push @{ $entry->{errors} }, $::locale->text('Error: Invalid bin');
194       return 0;
195     }
196
197     $object->bin_id($bin->id);
198   }
199
200   # If bin from front-end is enforced for transfers with missing bin, use this, if valid.
201   if (    $self->settings->{apply_bin} eq 'missing'
202        && ! $object->bin_id
203        && ! $entry->{raw_data}->{bin} ) {
204     my $bin = $self->bins_by->{_wh_id_and_description_ident()}->{ _wh_id_and_description_maker($object->warehouse_id, $self->settings->{bin}) };
205     if (!$bin) {
206       push @{ $entry->{errors} }, $::locale->text('Error: Invalid bin');
207       return 0;
208     }
209
210     $object->bin_id($bin->id);
211   }
212
213   # Check whether or not bin ID is valid.
214   if ($object->bin_id && !$self->bins_by->{_wh_id_and_id_ident()}->{ _wh_id_and_id_maker($object->warehouse_id, $object->bin_id) }) {
215     push @{ $entry->{errors} }, $::locale->text('Error: Invalid bin');
216     return 0;
217   }
218
219   # Map description to ID if given.
220   if (!$object->bin_id && $entry->{raw_data}->{bin}) {
221     my $bin = $self->bins_by->{_wh_id_and_description_ident()}->{ _wh_id_and_description_maker($object->warehouse_id, $entry->{raw_data}->{bin}) };
222     if (!$bin) {
223       push @{ $entry->{errors} }, $::locale->text('Error: Invalid bin');
224       return 0;
225     }
226
227     $object->bin_id($bin->id);
228   }
229
230   if ($object->bin_id) {
231     $entry->{info_data}->{bin} = $self->bins_by->{_wh_id_and_id_ident()}->{ _wh_id_and_id_maker($object->warehouse_id, $object->bin_id) }->description;
232   } else {
233     push @{ $entry->{errors} }, $::locale->text('Error: Bin not found');
234     return 0;
235   }
236
237   return 1;
238 }
239
240 sub check_part {
241   my ($self, $entry) = @_;
242
243   my $object = $entry->{object};
244
245   # Check whether or not part ID is valid.
246   if ($object->parts_id && !$self->parts_by->{id}->{ $object->parts_id }) {
247     push @{ $entry->{errors} }, $::locale->text('Error: Invalid part');
248     return 0;
249   }
250
251   # Map number to ID if given.
252   if (!$object->parts_id && $entry->{raw_data}->{partnumber}) {
253     my $part = $self->parts_by->{partnumber}->{ $entry->{raw_data}->{partnumber} };
254     if (!$part) {
255       push @{ $entry->{errors} }, $::locale->text('Error: Invalid part');
256       return 0;
257     }
258
259     $object->parts_id($part->id);
260   }
261
262   if ($object->parts_id) {
263     $entry->{info_data}->{partnumber} = $self->parts_by->{id}->{ $object->parts_id }->partnumber;
264   } else {
265     push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
266     return 0;
267   }
268
269   return 1;
270 }
271
272 # This imports inventories when target_qty is given, transfers else.
273 # So we get the actual qty in stock and transfer the difference in case of
274 # a given target_qty
275 sub check_qty{
276   my ($self, $entry) = @_;
277
278   my $object = $entry->{object};
279
280   if (! exists $entry->{raw_data}->{target_qty} && ! exists $entry->{raw_data}->{qty}) {
281     push @{ $entry->{errors} }, $::locale->text('Error: A quantity or a target quantity must be given.');
282     return 0;
283   }
284
285   if (exists $entry->{raw_data}->{target_qty} && exists $entry->{raw_data}->{qty}) {
286     push @{ $entry->{errors} }, $::locale->text('Error: A quantity and a target quantity could not be given both.');
287     return 0;
288   }
289
290   if (exists $entry->{raw_data}->{target_qty} && ($entry->{raw_data}->{target_qty} * 1) < 0) {
291     push @{ $entry->{errors} }, $::locale->text('Error: A negative target quantity is not allowed.');
292     return 0;
293   }
294
295   # Actual quantity is read from stock or is the result of transfers for the
296   # same part, warehouse, bin, chargenumber and bestbefore date (if
297   # show_bestbefore is enabled) done before.
298   my $key = join '+', $object->parts_id, $object->warehouse_id, $object->bin_id, $object->chargenumber;
299   $key   .= join '+', $key, $object->bestbefore    if $::instance_conf->get_show_bestbefore;
300
301   if (!exists $self->{resulting_quantities}->{$key}) {
302     $self->{resulting_quantities}->{$key} = _get_stocked_qty($object);
303   }
304   my $actual_qty = $self->{resulting_quantities}->{$key};
305
306   if (exists $entry->{raw_data}->{target_qty}) {
307     my $target_qty = $entry->{raw_data}->{target_qty} * 1;
308
309     $object->qty($target_qty - $actual_qty);
310     $self->add_columns(qw(qty));
311   }
312
313   if ($object->qty == 0) {
314     push @{ $entry->{errors} }, $::locale->text('Error: Quantity to transfer is zero.');
315     return 0;
316   }
317
318   # Check if resulting quantity is below zero.
319   if ( ($actual_qty + $object->qty) < 0 ) {
320     push @{ $entry->{errors} }, $::locale->text('Error: Transfer would result in a negative target quantity.');
321     return 0;
322   }
323
324   $self->{resulting_quantities}->{$key} += $object->qty;
325   $entry->{info_data}->{target_qty} = $self->{resulting_quantities}->{$key};
326
327   return 1;
328 }
329
330 sub handle_comment {
331   my ($self, $entry) = @_;
332
333   my $object = $entry->{object};
334
335   # If comment from front-end is enforced for all transfers, use this, if valid.
336   if ($self->settings->{apply_comment} eq 'all') {
337     $object->comment($self->settings->{comment});
338   }
339
340   # If comment from front-end is enforced for transfers with missing comment, use this, if valid.
341   if ($self->settings->{apply_comment} eq 'missing' && ! $object->comment) {
342     $object->comment($self->settings->{comment});
343   }
344
345   return;
346 }
347
348 sub handle_transfer_type  {
349   my ($self, $entry) = @_;
350
351   my $object = $entry->{object};
352
353   my $transfer_type = SL::DB::Manager::TransferType->find_by(description => 'correction',
354                                                              direction   => ($object->qty > 0)? 'in': 'out');
355   $object->trans_type($transfer_type);
356
357   return;
358 }
359
360 # ToDo: employee by name
361 sub handle_employee {
362   my ($self, $entry) = @_;
363
364   my $object = $entry->{object};
365
366   # employee from front end if not given
367   if (!$object->employee_id) {
368     $object->employee_id($self->controller->{employee_id})
369   }
370
371   # employee from login if not given
372   if (!$object->employee_id) {
373     $object->employee_id(SL::DB::Manager::Employee->find_by(login => $::myconfig{login})->id);
374   }
375
376   if ($object->employee_id) {
377     $entry->{info_data}->{employee} = $object->employee->name;
378   }
379
380 }
381
382 sub handle_shippingdate {
383   my ($self, $entry) = @_;
384
385   my $object = $entry->{object};
386
387   if (!$object->shippingdate) {
388     $object->shippingdate(DateTime->today_local);
389   }
390 }
391
392 sub save_objects {
393   my ($self, %params) = @_;
394
395   my $data = $params{data} || $self->controller->data;
396
397   foreach my $entry (@{ $data }) {
398     my ($trans_id) = selectrow_query($::form,$entry->{object}->db->dbh, qq|SELECT nextval('id')|);
399     $entry->{object}->trans_id($trans_id);
400   }
401
402   $self->SUPER::save_objects(%params);
403 }
404
405 sub _get_stocked_qty {
406   my ($object) = @_;
407
408   my $bestbefore_filter  = '';
409   my $bestbefore_val_cnt = 0;
410   if ($::instance_conf->get_show_bestbefore) {
411     $bestbefore_filter  = ($object->bestbefore) ? 'AND bestbefore = ?' : 'AND bestbefore IS NULL';
412     $bestbefore_val_cnt = ($object->bestbefore) ? 1                    : 0;
413   }
414
415   my $query = <<SQL;
416     SELECT sum(qty) FROM inventory
417       WHERE parts_id = ? AND warehouse_id = ? AND bin_id = ? AND chargenumber = ? $bestbefore_filter
418       GROUP BY warehouse_id, bin_id, chargenumber
419 SQL
420
421   my @values = ($object->parts_id,
422                 $object->warehouse_id,
423                 $object->bin_id,
424                 $object->chargenumber);
425   push @values, $object->bestbefore if $bestbefore_val_cnt;
426
427   my ($stocked_qty) = selectrow_query($::form, $object->db->dbh, $query, @values);
428
429   return $stocked_qty;
430 }
431
432 sub _wh_id_and_description_ident {
433   return 'wh_id+description';
434 }
435
436 sub _wh_id_and_description_maker {
437   return join '+', $_[0], $_[1]
438 }
439
440 sub _wh_id_and_id_ident {
441   return 'wh_id+id';
442 }
443
444 sub _wh_id_and_id_maker {
445   return join '+', $_[0], $_[1]
446 }
447
448 1;