2e5a9e9ab05558bbc1605e6b80610b915493a267
[kivitendo-erp.git] / SL / Controller / CsvImport / DeliveryOrder.pm
1 package SL::Controller::CsvImport::DeliveryOrder;
2
3
4 use strict;
5
6 use List::Util qw(first);
7 use List::MoreUtils qw(any none uniq);
8 use DateTime;
9
10 use SL::Controller::CsvImport::Helper::Consistency;
11 use SL::DB::DeliveryOrder;
12 use SL::DB::DeliveryOrder::TypeData qw(:types);
13 use SL::DB::DeliveryOrderItem;
14 use SL::DB::DeliveryOrderItemsStock;
15 use SL::DB::Part;
16 use SL::DB::PaymentTerm;
17 use SL::DB::Contact;
18 use SL::DB::PriceFactor;
19 use SL::DB::Pricegroup;
20 use SL::DB::Shipto;
21 use SL::DB::Unit;
22 use SL::DB::Inventory;
23 use SL::DB::TransferType;
24 use SL::DBUtils;
25 use SL::Helper::ShippedQty;
26 use SL::PriceSource;
27 use SL::TransNumber;
28 use SL::Util qw(trim);
29
30 use parent qw(SL::Controller::CsvImport::BaseMulti);
31
32
33 use Rose::Object::MakeMethods::Generic
34 (
35  'scalar --get_set_init' => [ qw(settings languages_by all_parts parts_by part_counts_by
36                                  contacts_by ct_shiptos_by
37                                  price_factors_by pricegroups_by units_by
38                                  warehouses_by bins_by transfer_types_by) ],
39 );
40
41
42 sub init_class {
43   my ($self) = @_;
44   $self->class(['SL::DB::DeliveryOrder', 'SL::DB::DeliveryOrderItem', 'SL::DB::DeliveryOrderItemsStock']);
45 }
46
47 sub set_profile_defaults {
48   my ($self) = @_;
49
50   $self->controller->profile->_set_defaults(
51     order_column         => $::locale->text('DeliveryOrder'),
52     item_column          => $::locale->text('OrderItem'),
53     stock_column         => $::locale->text('StockInfo'),
54     ignore_faulty_positions => 0,
55   );
56 };
57
58 sub init_settings {
59   my ($self) = @_;
60
61   return { map { ( $_ => $self->controller->profile->get($_) ) } qw(order_column item_column stock_column ignore_faulty_positions) };
62 }
63
64 sub init_cvar_configs_by {
65   my ($self) = @_;
66
67   my $item_cvar_configs = SL::DB::Manager::CustomVariableConfig->get_all(where => [ module => 'IC' ]);
68   $item_cvar_configs = [grep { $_->has_flag('editable') } @{ $item_cvar_configs }];
69
70   my $ccb;
71   $ccb->{class}->{$self->class->[0]}        = [];
72   $ccb->{class}->{$self->class->[1]}        = $item_cvar_configs;
73   $ccb->{class}->{$self->class->[2]}        = [];
74   $ccb->{row_ident}->{$self->_order_column} = [];
75   $ccb->{row_ident}->{$self->_item_column}  = $item_cvar_configs;
76   $ccb->{row_ident}->{$self->_stock_column} = [];
77
78   return $ccb;
79 }
80
81 sub init_profile {
82   my ($self) = @_;
83
84   my $profile = $self->SUPER::init_profile;
85
86   # SUPER::init_profile sets row_ident to the translated class name
87   # overwrite it with the user specified settings
88   foreach my $p (@{ $profile }) {
89     $p->{row_ident} = $self->_order_column if $p->{class} eq $self->class->[0];
90     $p->{row_ident} = $self->_item_column  if $p->{class} eq $self->class->[1];
91     $p->{row_ident} = $self->_stock_column if $p->{class} eq $self->class->[2];
92   }
93
94   foreach my $p (@{ $profile }) {
95     my $prof = $p->{profile};
96     if ($p->{row_ident} eq $self->_order_column) {
97       # no need to handle
98       delete @{$prof}{qw(oreqnumber)};
99     }
100     if ($p->{row_ident} eq $self->_item_column) {
101       # no need to handle
102       delete @{$prof}{qw(delivery_order_id)};
103     }
104     if ($p->{row_ident} eq $self->_stock_column) {
105       # no need to handle
106       delete @{$prof}{qw(delivery_order_item_id)};
107       delete @{$prof}{qw(bestbefore)} if !$::instance_conf->get_show_bestbefore;
108     }
109   }
110
111   return $profile;
112 }
113
114 sub init_existing_objects {
115   my ($self) = @_;
116
117   # only use objects of main class (the first one)
118   eval "require " . $self->class->[0];
119   $self->existing_objects($self->manager_class->[0]->get_all);
120 }
121
122 sub get_duplicate_check_fields {
123   return {
124     donumber => {
125       label     => $::locale->text('Delivery Order Number'),
126       default   => 1,
127       std_check => 1,
128       maker     => sub {
129         my ($object, $worker) = @_;
130         return if ref $object ne $worker->class->[0];
131         return $object->donumber;
132       },
133     },
134   };
135 }
136
137 sub check_std_duplicates {
138   my $self = shift;
139
140   my $duplicates = {};
141
142   my $all_fields = $self->get_duplicate_check_fields();
143
144   foreach my $key (keys(%{ $all_fields })) {
145     if ( $self->controller->profile->get('duplicates_'. $key) && (!exists($all_fields->{$key}->{std_check}) || $all_fields->{$key}->{std_check} )  ) {
146       $duplicates->{$key} = {};
147     }
148   }
149
150   my @duplicates_keys = keys(%{ $duplicates });
151
152   if ( !scalar(@duplicates_keys) ) {
153     return;
154   }
155
156   if ( $self->controller->profile->get('duplicates') eq 'check_db' ) {
157     foreach my $object (@{ $self->existing_objects }) {
158       foreach my $key (@duplicates_keys) {
159         my $value = exists($all_fields->{$key}->{maker}) ? $all_fields->{$key}->{maker}->($object, $self) : $object->$key;
160         $duplicates->{$key}->{$value} = 'db';
161       }
162     }
163   }
164
165   # only check order rows
166   foreach my $entry (@{ $self->controller->data }) {
167     if ($entry->{raw_data}->{datatype} ne $self->_order_column) {
168       next;
169     }
170     if ( @{ $entry->{errors} } ) {
171       next;
172     }
173
174     my $object = $entry->{object};
175
176     foreach my $key (@duplicates_keys) {
177       my $value = exists($all_fields->{$key}->{maker}) ? $all_fields->{$key}->{maker}->($object, $self) : $object->$key;
178
179       if ( exists($duplicates->{$key}->{$value}) ) {
180         push(@{ $entry->{errors} }, $duplicates->{$key}->{$value} eq 'db' ? $::locale->text('Duplicate in database') : $::locale->text('Duplicate in CSV file'));
181         last;
182       } else {
183         $duplicates->{$key}->{$value} = 'csv';
184       }
185
186     }
187   }
188 }
189
190 sub setup_displayable_columns {
191   my ($self) = @_;
192
193   $self->SUPER::setup_displayable_columns;
194
195   $self->add_cvar_columns_to_displayable_columns($self->_order_column);
196
197   $self->add_displayable_columns($self->_order_column,
198                                  { name => 'datatype',                description => $self->_order_column . ' [1]'                            },
199                                  { name => 'closed',                  description => $::locale->text('Closed')                                },
200                                  { name => 'contact',                 description => $::locale->text('Contact Person (name)')                 },
201                                  { name => 'cp_id',                   description => $::locale->text('Contact Person (database ID)')          },
202                                  { name => 'currency',                description => $::locale->text('Currency')                              },
203                                  { name => 'currency_id',             description => $::locale->text('Currency (database ID)')                },
204                                  { name => 'customer',                description => $::locale->text('Customer (name)')                       },
205                                  { name => 'customernumber',          description => $::locale->text('Customer Number')                       },
206                                  { name => 'customer_id',             description => $::locale->text('Customer (database ID)')                },
207                                  { name => 'cusordnumber',            description => $::locale->text('Customer Order Number')                 },
208                                  { name => 'delivered',               description => $::locale->text('Delivered')                             },
209                                  { name => 'delivery_term',           description => $::locale->text('Delivery terms (name)')                 },
210                                  { name => 'delivery_term_id',        description => $::locale->text('Delivery terms (database ID)')          },
211                                  { name => 'department_id',           description => $::locale->text('Department (database ID)')              },
212                                  { name => 'department',              description => $::locale->text('Department (description)')              },
213                                  { name => 'donumber',                description => $::locale->text('Delivery Order Number')                 },
214                                  { name => 'employee_id',             description => $::locale->text('Employee (database ID)')                },
215                                  { name => 'globalproject',           description => $::locale->text('Document Project (description)')        },
216                                  { name => 'globalprojectnumber',     description => $::locale->text('Document Project (number)')             },
217                                  { name => 'globalproject_id',        description => $::locale->text('Document Project (database ID)')        },
218                                  { name => 'intnotes',                description => $::locale->text('Internal Notes')                        },
219                                  { name => 'language',                description => $::locale->text('Language (name)')                       },
220                                  { name => 'language_id',             description => $::locale->text('Language (database ID)')                },
221                                  { name => 'notes',                   description => $::locale->text('Notes')                                 },
222                                  { name => 'order_type',              description => $::locale->text('Delivery Order Type')                   },
223                                  { name => 'ordnumber',               description => $::locale->text('Order Number')                          },
224                                  { name => 'payment',                 description => $::locale->text('Payment terms (name)')                  },
225                                  { name => 'payment_id',              description => $::locale->text('Payment terms (database ID)')           },
226                                  { name => 'reqdate',                 description => $::locale->text('Reqdate')                               },
227                                  { name => 'salesman_id',             description => $::locale->text('Salesman (database ID)')                },
228                                  { name => 'shippingpoint',           description => $::locale->text('Shipping Point')                        },
229                                  { name => 'shipvia',                 description => $::locale->text('Ship via')                              },
230                                  { name => 'shipto_id',               description => $::locale->text('Ship to (database ID)')                 },
231                                  { name => 'taxincluded',             description => $::locale->text('Tax Included')                          },
232                                  { name => 'taxzone',                 description => $::locale->text('Tax zone (description)')                },
233                                  { name => 'taxzone_id',              description => $::locale->text('Tax zone (database ID)')                },
234                                  { name => 'transaction_description', description => $::locale->text('Transaction description')               },
235                                  { name => 'transdate',               description => $::locale->text('Order Date')                            },
236                                  { name => 'vendor',                  description => $::locale->text('Vendor (name)')                         },
237                                  { name => 'vendornumber',            description => $::locale->text('Vendor Number')                         },
238                                  { name => 'vendor_id',               description => $::locale->text('Vendor (database ID)')                  },
239                                 );
240
241   $self->add_cvar_columns_to_displayable_columns($self->_item_column);
242
243   $self->add_displayable_columns($self->_item_column,
244                                  { name => 'datatype',        description => $self->_item_column . ' [1]'                  },
245                                  { name => 'cusordnumber',    description => $::locale->text('Customer Order Number')      },
246                                  { name => 'description',     description => $::locale->text('Description')                },
247                                  { name => 'discount',        description => $::locale->text('Discount')                   },
248                                  { name => 'lastcost',        description => $::locale->text('Lastcost')                   },
249                                  { name => 'longdescription', description => $::locale->text('Long Description')           },
250                                  { name => 'ordnumber',       description => $::locale->text('Order Number')               },
251                                  { name => 'partnumber',      description => $::locale->text('Part Number')                },
252                                  { name => 'parts_id',        description => $::locale->text('Part (database ID)')         },
253                                  { name => 'position',        description => $::locale->text('position')                   },
254                                  { name => 'price_factor',    description => $::locale->text('Price factor (name)')        },
255                                  { name => 'price_factor_id', description => $::locale->text('Price factor (database ID)') },
256                                  { name => 'pricegroup',      description => $::locale->text('Price group (name)')         },
257                                  { name => 'pricegroup_id',   description => $::locale->text('Price group (database ID)')  },
258                                  { name => 'project',         description => $::locale->text('Project (description)')      },
259                                  { name => 'projectnumber',   description => $::locale->text('Project (number)')           },
260                                  { name => 'project_id',      description => $::locale->text('Project (database ID)')      },
261                                  { name => 'qty',             description => $::locale->text('Quantity')                   },
262                                  { name => 'reqdate',         description => $::locale->text('Reqdate')                    },
263                                  { name => 'sellprice',       description => $::locale->text('Sellprice')                  },
264                                  { name => 'serialnumber',    description => $::locale->text('Serial No.')                 },
265                                  { name => 'transdate',       description => $::locale->text('Order Date')                 },
266                                  { name => 'unit',            description => $::locale->text('Unit')                       },
267                                 );
268
269   $self->add_cvar_columns_to_displayable_columns($self->_stock_column);
270
271   $self->add_displayable_columns($self->_stock_column,
272                                  { name => 'datatype',     description => $self->_stock_column . ' [1]'              },
273                                  { name => 'warehouse',    description => $::locale->text('Warehouse')               },
274                                  { name => 'warehouse_id', description => $::locale->text('Warehouse (database ID)') },
275                                  { name => 'bin',          description => $::locale->text('Bin')                     },
276                                  { name => 'bin_id',       description => $::locale->text('Bin (database ID)')       },
277                                  { name => 'chargenumber', description => $::locale->text('Charge number')           },
278                                  { name => 'qty',          description => $::locale->text('Quantity')                },
279                                  { name => 'unit',         description => $::locale->text('Unit')                    },
280                                 );
281   if ($::instance_conf->get_show_bestbefore) {
282     $self->add_displayable_columns($self->_stock_column,
283                                    { name => 'bestbefore', description => $::locale->text('Best Before') });
284   }
285 }
286
287
288 sub init_languages_by {
289   my ($self) = @_;
290
291   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $self->all_languages } } ) } qw(id description article_code) };
292 }
293
294 sub init_all_parts {
295   my ($self) = @_;
296
297   return SL::DB::Manager::Part->get_all(where => [or => [ obsolete => 0, obsolete => undef ]]);
298 }
299
300 sub init_parts_by {
301   my ($self) = @_;
302
303   return { map { my $col = $_; ( $col => { map { ( trim($_->$col) => $_ ) } @{ $self->all_parts } } ) } qw(id partnumber ean description) };
304 }
305
306 sub init_part_counts_by {
307   my ($self) = @_;
308
309   my $part_counts_by;
310
311   $part_counts_by->{ean}->        {trim($_->ean)}++         for @{ $self->all_parts };
312   $part_counts_by->{description}->{trim($_->description)}++ for @{ $self->all_parts };
313
314   return $part_counts_by;
315 }
316
317 sub init_contacts_by {
318   my ($self) = @_;
319
320   my $all_contacts = SL::DB::Manager::Contact->get_all;
321
322   my $cby;
323   # by customer/vendor id  _and_  contact person id
324   $cby->{'cp_cv_id+cp_id'}   = { map { ( $_->cp_cv_id . '+' . $_->cp_id   => $_ ) } @{ $all_contacts } };
325   # by customer/vendor id  _and_  contact person name
326   $cby->{'cp_cv_id+cp_name'} = { map { ( $_->cp_cv_id . '+' . $_->cp_name => $_ ) } @{ $all_contacts } };
327
328   return $cby;
329 }
330
331 sub init_ct_shiptos_by {
332   my ($self) = @_;
333
334   my $all_ct_shiptos = SL::DB::Manager::Shipto->get_all(query => [module => 'CT']);
335
336   my $sby;
337   # by trans_id  _and_  shipto_id
338   $sby->{'trans_id+shipto_id'} = { map { ( $_->trans_id . '+' . $_->shipto_id => $_ ) } @{ $all_ct_shiptos } };
339
340   return $sby;
341 }
342
343 sub init_price_factors_by {
344   my ($self) = @_;
345
346   my $all_price_factors = SL::DB::Manager::PriceFactor->get_all;
347   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_price_factors } } ) } qw(id description) };
348 }
349
350 sub init_pricegroups_by {
351   my ($self) = @_;
352
353   my $all_pricegroups = SL::DB::Manager::Pricegroup->get_all;
354   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_pricegroups } } ) } qw(id pricegroup) };
355 }
356
357 sub init_units_by {
358   my ($self) = @_;
359
360   my $all_units = SL::DB::Manager::Unit->get_all;
361   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_units } } ) } qw(name) };
362 }
363
364 sub init_warehouses_by {
365   my ($self) = @_;
366
367   my $all_warehouses = SL::DB::Manager::Warehouse->get_all(query => [ or => [ invalid => 0, invalid => undef ]]);
368   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_warehouses } } ) } qw(id description) };
369 }
370
371 sub init_bins_by {
372   my ($self) = @_;
373
374   my $all_bins = SL::DB::Manager::Bin->get_all();
375   my $bins_by;
376   $bins_by->{_wh_id_and_id_ident()}          = { map { ( _wh_id_and_id_maker($_->warehouse_id, $_->id)                   => $_ ) } @{ $all_bins } };
377   $bins_by->{_wh_id_and_description_ident()} = { map { ( _wh_id_and_description_maker($_->warehouse_id, $_->description) => $_ ) } @{ $all_bins } };
378
379   return $bins_by;
380 }
381
382 sub init_transfer_types_by {
383   my ($self) = @_;
384
385   my $all_transfer_types = SL::DB::Manager::TransferType->get_all();
386   my $transfer_types_by;
387   $transfer_types_by->{_transfer_type_dir_and_description_ident()} = {
388     map { ( _transfer_type_dir_and_description_maker($_->direction, $_->description) => $_ ) } @{ $all_transfer_types }
389   };
390
391   return $transfer_types_by;
392 }
393
394 sub check_objects {
395   my ($self) = @_;
396
397   $self->controller->track_progress(phase => 'building data', progress => 0);
398
399   my $i = 0;
400   my $num_data = scalar @{ $self->controller->data };
401   my $order_entry;
402   my $item_entry;
403   foreach my $entry (@{ $self->controller->data }) {
404     $self->controller->track_progress(progress => $i/$num_data * 100) if $i % 100 == 0;
405
406     $entry->{info_data}->{datatype} = $entry->{raw_data}->{datatype};
407
408     if ($entry->{raw_data}->{datatype} eq $self->_order_column) {
409       $self->handle_order($entry);
410       $order_entry = $entry;
411     } elsif ($entry->{raw_data}->{datatype} eq $self->_item_column && $entry->{object}->can('part')) {
412       $self->handle_item($entry, $order_entry);
413       $item_entry = $entry;
414     } elsif ($entry->{raw_data}->{datatype} eq $self->_stock_column) {
415       $self->handle_stock($entry, $item_entry, $order_entry);
416       push @{ $order_entry->{errors} }, $::locale->text('Error: Stock problem') if scalar(@{$entry->{errors}}) > 0;
417     } else {
418       $order_entry = undef;
419       $item_entry  = undef;
420     }
421
422     $self->handle_cvars($entry, sub_module => 'delivery_order_items');
423
424   } continue {
425     $i++;
426   }
427
428   $self->add_info_columns($self->_order_column,
429                           { header => $::locale->text('Data type'), method => 'datatype' });
430   $self->add_info_columns($self->_item_column,
431                           { header => $::locale->text('Data type'), method => 'datatype' });
432   $self->add_info_columns($self->_stock_column,
433                           { header => $::locale->text('Data type'), method => 'datatype' });
434
435   $self->add_info_columns($self->_order_column,
436                           { header => $::locale->text('Customer/Vendor'), method => 'vc_name' });
437   # Todo: access via ->[0] ok? Better: search first order column and use this
438   $self->add_columns($self->_order_column,
439                      map { "${_}_id" } grep { exists $self->controller->data->[0]->{raw_data}->{$_} } qw(payment delivery_term language department globalproject taxzone cp currency));
440   $self->add_columns($self->_order_column, 'globalproject_id') if exists $self->controller->data->[0]->{raw_data}->{globalprojectnumber};
441   $self->add_columns($self->_order_column, 'cp_id')            if exists $self->controller->data->[0]->{raw_data}->{contact};
442
443   $self->add_info_columns($self->_item_column,
444                           { header => $::locale->text('Part Number'), method => 'partnumber' });
445   # Todo: access via ->[1] ok? Better: search first item column and use this
446   $self->add_columns($self->_item_column,
447                      map { "${_}_id" } grep { exists $self->controller->data->[1]->{raw_data}->{$_} } qw(project price_factor pricegroup));
448   $self->add_columns($self->_item_column, 'project_id') if exists $self->controller->data->[1]->{raw_data}->{projectnumber};
449
450   $self->add_cvar_raw_data_columns();
451
452
453   # Check overall qtys for sales delivery orders, because they are
454   # stocked out in the end and a stock underrun can occure.
455   # Todo: let it work even with bestbefore turned off.
456   $order_entry = undef;
457   $item_entry  = undef;
458   my %wanted_qtys_by_part_wh_bin_charge_bestbefore;
459   my %stock_entries_with_part_wh_bin_charge_bestbefore;
460   my %order_entries_with_part_wh_bin_charge_bestbefore;
461   foreach my $entry (@{ $self->controller->data }) {
462     if ($entry->{raw_data}->{datatype} eq $self->_order_column) {
463       if (scalar(@{ $entry->{errors} }) || !$entry->{object}->is_sales) {
464         $order_entry = undef;
465         $item_entry  = undef;
466         next;
467       }
468       $order_entry = $entry;
469
470     } elsif (defined $order_entry && $entry->{raw_data}->{datatype} eq $self->_item_column) {
471       if (scalar(@{ $entry->{errors} })) {
472         $item_entry = undef;
473         next;
474       }
475       $item_entry = $entry;
476
477     } elsif (defined $item_entry && $entry->{raw_data}->{datatype} eq $self->_stock_column) {
478       my $object = $entry->{object};
479       my $key = join('+',
480                      $item_entry->{object}->parts_id,
481                      $object->warehouse_id,
482                      $object->bin_id,
483                      $object->chargenumber,
484                      $object->bestbefore);
485       $wanted_qtys_by_part_wh_bin_charge_bestbefore{$key} += $object->qty;
486       push @{$order_entries_with_part_wh_bin_charge_bestbefore{$key}}, $order_entry;
487       push @{$stock_entries_with_part_wh_bin_charge_bestbefore{$key}}, $entry;
488     }
489   }
490
491   foreach my $key (keys %wanted_qtys_by_part_wh_bin_charge_bestbefore) {
492     my ($parts_id, $wh_id, $bin_id, $chargenumber, $bestbefore) = split '\+', $key;
493     my $qty = $self->get_stocked_qty($parts_id, $wh_id, $bin_id, $chargenumber, $bestbefore);
494     if ($wanted_qtys_by_part_wh_bin_charge_bestbefore{$key} > $qty) {
495
496       foreach my $stock_entry (@{ $stock_entries_with_part_wh_bin_charge_bestbefore{$key} }) {
497         push @{ $stock_entry->{errors} }, $::locale->text('Error: Stocking out would result in stock underrun');
498       }
499
500       foreach my $order_entry (uniq @{ $order_entries_with_part_wh_bin_charge_bestbefore{$key} }) {
501         my $part            = $self->parts_by->{id}->{$parts_id}->displayable_name;
502         my $stock           = $self->bins_by->{_wh_id_and_id_ident()}->{_wh_id_and_id_maker($wh_id, $bin_id)}->full_description;
503         my $bestbefore_obj  = $::locale->parse_date_to_object($bestbefore, dateformat=>'yyyy-mm-dd');
504         my $bestbefore_text = $bestbefore_obj? $::locale->parse_date_to_object($bestbefore_obj, dateformat=>'yyyy-mm-dd')->to_kivitendo: '-';
505         my $wanted_qty      = $wanted_qtys_by_part_wh_bin_charge_bestbefore{$key};
506         my $details_text    = sprintf('%s (%s / %s / %s): %s > %s',
507                                       $part,
508                                       $stock,
509                                       $chargenumber,
510                                       $bestbefore_text,
511                                       $::form->format_amount(\%::myconfig, $wanted_qty,  2),
512                                       $::form->format_amount(\%::myconfig, $qty, 2));
513         push @{ $order_entry->{errors} }, $::locale->text('Error: Stocking out would result in stock underrun: #1', $details_text);
514       }
515
516     }
517   }
518
519 }
520
521 sub handle_order {
522   my ($self, $entry) = @_;
523
524   my $object = $entry->{object};
525
526   $object->orderitems([]);
527
528   $self->handle_order_sources($entry);
529   my $first_source_order = $object->{source_orders}->[0];
530
531   my $vc_obj;
532   if (any { $entry->{raw_data}->{$_} } qw(customer customernumber customer_id)) {
533     $self->check_vc($entry, 'customer_id');
534     $vc_obj = SL::DB::Customer->new(id => $object->customer_id)->load if $object->customer_id;
535
536   } elsif (any { $entry->{raw_data}->{$_} } qw(vendor vendornumber vendor_id)) {
537     $self->check_vc($entry, 'vendor_id');
538     $vc_obj = SL::DB::Vendor->new(id => $object->vendor_id)->load if $object->vendor_id;
539
540   } else {
541     # customer / vendor from (first) source order if not given
542     if ($first_source_order) {
543       if ($first_source_order->customer) {
544         $vc_obj = $first_source_order->customer;
545         $object->customer($first_source_order->customer);
546       } elsif ($first_source_order->vendor) {
547         $vc_obj = $first_source_order->vendor;
548         $object->vendor($first_source_order->vendor);
549       }
550     }
551   }
552
553   if (!$vc_obj) {
554     push @{ $entry->{errors} }, $::locale->text('Error: Customer/vendor missing');
555   }
556
557   $self->handle_type($entry);
558   $self->check_contact($entry);
559   $self->check_language($entry);
560   $self->check_payment($entry);
561   $self->check_delivery_term($entry);
562   $self->check_department($entry);
563   $self->check_project($entry, global => 1);
564   $self->check_ct_shipto($entry);
565   $self->check_taxzone($entry);
566   $self->check_currency($entry, take_default => 0);
567
568   # copy from (first) source order if not given
569   # if no source order, then copy some values from customer/vendor
570   if ($first_source_order) {
571     foreach (qw(cusordnumber notes intnotes shippingpoint shipvia
572                 transaction_description currency_id delivery_term_id
573                 department_id language_id payment_id globalproject_id shipto_id
574                 taxzone_id)) {
575       $object->$_($first_source_order->$_) unless $object->$_;
576     }
577   } elsif ($vc_obj) {
578     foreach (qw(currency_id delivery_term_id language_id payment_id taxzone_id)) {
579       $object->$_($vc_obj->$_) unless $object->$_;
580     }
581     $object->intnotes($vc_obj->notes) unless $object->intnotes;
582   }
583
584   $self->handle_salesman($entry);
585   $self->handle_employee($entry);
586 }
587
588 sub handle_item {
589   my ($self, $entry, $order_entry) = @_;
590
591   return unless $order_entry;
592
593   my $order_obj = $order_entry->{object};
594   my $object    = $entry->{object};
595   $object->delivery_order_stock_entries([]);
596
597   if (!$self->check_part($entry)) {
598     if ($self->controller->profile->get('ignore_faulty_positions')) {
599       push @{ $order_entry->{information} }, $::locale->text('Warning: Faulty position ignored');
600     } else {
601       push @{ $order_entry->{errors} }, $::locale->text('Error: Faulty position in this delivery order');
602     }
603     return;
604   }
605
606   $order_obj->add_items($object);
607
608   my $part_obj = SL::DB::Part->new(id => $object->parts_id)->load;
609
610   $self->handle_item_source($entry, $order_entry);
611   $object->position($object->{source_item}->position) if $object->{source_item};
612
613   $self->handle_unit($entry);
614
615   # copy from part if not given
616   $object->description($part_obj->description) unless $object->description;
617   $object->longdescription($part_obj->notes)   unless $object->longdescription;
618   $object->lastcost($part_obj->lastcost)       unless defined $object->lastcost;
619
620   $self->check_project($entry, global => 0);
621   $self->check_price_factor($entry);
622   $self->check_pricegroup($entry);
623
624   $self->handle_sellprice($entry, $order_entry);
625   $self->handle_discount($entry, $order_entry);
626
627   push @{ $order_entry->{errors} }, $::locale->text('Error: Faulty position in this delivery order') if scalar(@{$entry->{errors}}) > 0;
628 }
629
630 sub handle_stock {
631   my ($self, $entry, $item_entry, $order_entry) = @_;
632
633   return unless $item_entry;
634
635   my $item_obj  = $item_entry->{object};
636   return unless $item_obj->part;
637
638   my $order_obj = $order_entry->{object};
639   my $object    = $entry->{object};
640
641   $item_obj->add_delivery_order_stock_entries($object);
642
643   $self->check_warehouse($entry);
644   $self->check_bin($entry);
645
646   $self->handle_unit($entry, $item_obj->part);
647
648   # check if enough is stocked
649   # not necessary, because overall stock underrun is checked later
650   # if ($order_obj->is_sales) {
651   #   my $stocked_qty = $self->get_stocked_qty($item_obj->parts_id,
652   #                                            $object->warehouse_id,
653   #                                            $object->bin_id,
654   #                                            $object->chargenumber,
655   #                                            $object->bestbefore);
656   #   if ($stocked_qty < $object->qty) {
657   #     push @{ $entry->{errors} }, $::locale->text('Error: Not enough parts in stock');
658   #   }
659   # }
660
661   my ($stock_info_entry, $part) = @_;
662
663   # Todo: option: should stock?
664   if (1) {
665     my $tt_key = $order_obj->is_sales
666                ? _transfer_type_dir_and_description_maker('out', 'shipped')
667                : _transfer_type_dir_and_description_maker('in', 'stock');
668     my $trans_type_id = $self->transfer_types_by->{_transfer_type_dir_and_description_ident()}{$tt_key}->id;
669
670     my $qty = $order_obj->is_sales ? -1*($object->qty) : $object->qty;
671     my $inventory = SL::DB::Inventory->new(
672       parts_id      => $item_obj->parts_id,
673       warehouse_id  => $object->warehouse_id,
674       bin_id        => $object->bin_id,
675       trans_type_id => $trans_type_id,
676       qty           => $qty,
677       chargenumber  => $object->chargenumber,
678       employee_id   => $order_obj->employee_id,
679       shippingdate  => ($order_obj->reqdate || DateTime->today_local),
680       comment       => $order_obj->transaction_description,
681       project_id    => ($order_obj->globalproject_id || $item_obj->project_id),
682     );
683     $inventory->bestbefore($object->bestbefore) if $::instance_conf->get_show_bestbefore;
684     $object->{inventory_obj} = $inventory;
685     $order_obj->delivered(1);
686   }
687 }
688
689 sub handle_type {
690   my ($self, $entry) = @_;
691
692   if (!exists $entry->{raw_data}->{order_type}) {
693     # if no type is present - set to sales delivery order or purchase delivery
694     # order depending on is_sales or customer/vendor
695
696     $entry->{object}->order_type(
697       $entry->{object}->customer_id  ? SALES_DELIVERY_ORDER_TYPE :
698       $entry->{object}->vendor_id    ? PURCHASE_DELIVERY_ORDER_TYPE :
699       $entry->{raw_data}->{is_sales} ? SALES_DELIVERY_ORDER_TYPE :
700                                        PURCHASE_DELIVERY_ORDER_TYPE
701     );
702   }
703 }
704
705 sub handle_order_sources {
706   my ($self, $entry) = @_;
707
708   my $record = $entry->{object};
709
710   $record->{source_orders} = [];
711   return $record->{source_orders} if !$record->ordnumber;
712
713   my @order_numbers = split ' ', $record->ordnumber;
714
715   my $orders = SL::DB::Manager::Order->get_all(where => [ordnumber => \@order_numbers]);
716
717   if (scalar @$orders == 0) {
718     push @{ $entry->{errors} }, $::locale->text('Error: Source order not found');
719   } elsif (scalar @$orders > 1) {
720     push @{ $entry->{errors} }, $::locale->text('Error: More than one source order found');
721   }
722
723   foreach my $order (@$orders) {
724     $self->{remaining_source_qtys_by_item_id} = { map { $_->id => $_->qty } @{ $order->items } };
725   }
726
727   $record->{source_orders} = $orders;
728 }
729
730 sub handle_item_source {
731   my ($self, $entry, $record_entry) = @_;
732
733   my $item   = $entry->{object};
734   my $record = $record_entry->{object};
735
736   return if !@{ $record->{source_orders} };
737
738   # Todo: units?
739
740   foreach my $order (@{ $record->{source_orders} }) {
741     # First: Excact matches and source order position is still complete.
742     $item->{source_item} = first {
743          $item->parts_id                                     == $_->parts_id
744       && $item->qty                                          == $_->qty
745       && $self->{remaining_source_qtys_by_item_id}->{$_->id} == $_->qty
746     } @{ $order->items_sorted };
747     if ($item->{source_item}) {
748       $self->{remaining_source_qtys_by_item_id}->{$item->{source_item}->id} -= $item->qty;
749       last;
750     }
751
752     # Second: Smallest remaining order qty greater or equal delivery order qty.
753     $item->{source_item} = first {
754          $item->parts_id                                     == $_->parts_id
755       && $self->{remaining_source_qtys_by_item_id}->{$_->id} >= $item->qty
756     } sort { $self->{remaining_source_qtys_by_item_id}->{$a->id} <=> $self->{remaining_source_qtys_by_item_id}->{$b->id} } @{ $order->items_sorted };
757     if ($item->{source_item}) {
758       $self->{remaining_source_qtys_by_item_id}->{$item->{source_item}->id} -= $item->qty;
759       last;
760     }
761
762     # Last: Overdelivery?
763     # $item->{source_item} = first {
764     #      $item->parts_id == $_->parts_id
765     # } @{ $order->items_sorted };
766     # if ($item->{source_item}) {
767     #   $self->{remaining_source_qtys_by_item_id}->{$item->{source_item}->id} -= $item->qty;
768     #   last;
769     # }
770   }
771 }
772
773 sub handle_unit {
774   my ($self, $entry, $part) = @_;
775
776   my $object = $entry->{object};
777
778   $part ||= $object->part;
779
780   # Set unit from part if not given.
781   if (!$object->unit) {
782     $object->unit($part->unit);
783     return 1;
784   }
785
786   # Check whether or not unit is valid.
787   if ($object->unit && !$self->units_by->{name}->{ $object->unit }) {
788     push @{ $entry->{errors} }, $::locale->text('Error: Invalid unit');
789     return 0;
790   }
791
792   # Check whether unit is convertible to parts unit
793   if (none { $object->unit eq $_ } map { $_->name } @{ $part->unit_obj->convertible_units }) {
794     push @{ $entry->{errors} }, $::locale->text('Error: Invalid unit');
795     return 0;
796   }
797
798   return 1;
799 }
800
801 sub handle_sellprice {
802   my ($self, $entry, $record_entry) = @_;
803
804   my $item   = $entry->{object};
805   my $record = $record_entry->{object};
806
807   return if !$record->customervendor;
808
809   # If sellprice is given, set price source to pricegroup if given or to none.
810   if (exists $entry->{raw_data}->{sellprice}) {
811     my $price_source      = SL::PriceSource->new(record_item => $item, record => $record);
812     my $price_source_spec = $item->pricegroup_id ? 'pricegroup' . '/' . $item->pricegroup_id : '';
813     my $price             = $price_source->price_from_source($price_source_spec);
814     $item->active_price_source($price->source);
815
816   } else {
817
818     if ($item->{source_item}) {
819       # Set sellprice from source order item if not given. Convert with respect to unit.
820       my $sellprice = $item->{source_item}->sellprice;
821       if ($item->unit ne $item->{source_item}->unit) {
822         $sellprice = $item->unit_obj->convert_to($sellprice, $item->{source_item}->unit_obj);
823       }
824       $item->sellprice($sellprice);
825       $item->active_price_source($item->{source_item}->active_price_source);
826
827     } else {
828       # Set sellprice the best price of price source
829       my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
830       my $price        = $price_source->best_price;
831       if ($price) {
832         $item->sellprice($price->price);
833         $item->active_price_source($price->source);
834       } else {
835         $item->sellprice(0);
836         $item->active_price_source($price_source->price_from_source('')->source);
837       }
838     }
839   }
840 }
841
842 sub handle_discount {
843   my ($self, $entry, $record_entry) = @_;
844
845   my $item   = $entry->{object};
846   my $record = $record_entry->{object};
847
848   return if !$record->customervendor;
849
850   # If discount is given, set discount to none.
851   if (exists $entry->{raw_data}->{discount}) {
852     my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
853     my $discount     = $price_source->price_from_source('');
854     $item->active_discount_source($discount->source);
855
856   } else {
857
858     if ($item->{source_item}) {
859       # Set discount from source order item if not given.
860       $item->discount($item->{source_item}->discount);
861       $item->active_discount_source($item->{source_item}->active_discount_source);
862
863     } else {
864       # Set discount the best discount of price source
865       my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
866       my $discount     = $price_source->best_discount;
867       if ($discount) {
868         $item->discount($discount->discount);
869         $item->active_discount_source($discount->source);
870       } else {
871         $item->discount(0);
872         $item->active_discount_source($price_source->discount_from_source('')->source);
873       }
874     }
875   }
876 }
877
878 sub check_contact {
879   my ($self, $entry) = @_;
880
881   my $object = $entry->{object};
882
883   my $cp_cv_id = $object->customer_id || $object->vendor_id;
884   return 0 unless $cp_cv_id;
885
886   # Check whether or not contact ID is valid.
887   if ($object->cp_id && !$self->contacts_by->{'cp_cv_id+cp_id'}->{ $cp_cv_id . '+' . $object->cp_id }) {
888     push @{ $entry->{errors} }, $::locale->text('Error: Invalid contact');
889     return 0;
890   }
891
892   # Map name to ID if given.
893   if (!$object->cp_id && $entry->{raw_data}->{contact}) {
894     my $cp = $self->contacts_by->{'cp_cv_id+cp_name'}->{ $cp_cv_id . '+' . $entry->{raw_data}->{contact} };
895     if (!$cp) {
896       push @{ $entry->{errors} }, $::locale->text('Error: Invalid contact');
897       return 0;
898     }
899
900     $object->cp_id($cp->cp_id);
901   }
902
903   if ($object->cp_id) {
904     $entry->{info_data}->{contact} = $self->contacts_by->{'cp_cv_id+cp_id'}->{ $cp_cv_id . '+' . $object->cp_id }->cp_name;
905   }
906
907   return 1;
908 }
909
910 sub check_language {
911   my ($self, $entry) = @_;
912
913   my $object = $entry->{object};
914
915   # Check whether or not language ID is valid.
916   if ($object->language_id && !$self->languages_by->{id}->{ $object->language_id }) {
917     push @{ $entry->{errors} }, $::locale->text('Error: Invalid language');
918     return 0;
919   }
920
921   # Map name to ID if given.
922   if (!$object->language_id && $entry->{raw_data}->{language}) {
923     my $language = $self->languages_by->{description}->{  $entry->{raw_data}->{language} }
924                 || $self->languages_by->{article_code}->{ $entry->{raw_data}->{language} };
925
926     if (!$language) {
927       push @{ $entry->{errors} }, $::locale->text('Error: Invalid language');
928       return 0;
929     }
930
931     $object->language_id($language->id);
932   }
933
934   if ($object->language_id) {
935     $entry->{info_data}->{language} = $self->languages_by->{id}->{ $object->language_id }->description;
936   }
937
938   return 1;
939 }
940
941 sub check_ct_shipto {
942   my ($self, $entry) = @_;
943
944   my $object = $entry->{object};
945
946   my $trans_id = $object->customer_id || $object->vendor_id;
947   return 0 unless $trans_id;
948
949   # Check whether or not shipto ID is valid.
950   if ($object->shipto_id && !$self->ct_shiptos_by->{'trans_id+shipto_id'}->{ $trans_id . '+' . $object->shipto_id }) {
951     push @{ $entry->{errors} }, $::locale->text('Error: Invalid shipto');
952     return 0;
953   }
954
955   return 1;
956 }
957
958 sub check_part {
959   my ($self, $entry) = @_;
960
961   my $object = $entry->{object};
962   my $is_ambiguous;
963
964   # Check whether or not part ID is valid.
965   if ($object->parts_id && !$self->parts_by->{id}->{ $object->parts_id }) {
966     push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
967     return 0;
968   }
969
970   # Map number to ID if given.
971   if (!$object->parts_id && $entry->{raw_data}->{partnumber}) {
972     my $part = $self->parts_by->{partnumber}->{ trim($entry->{raw_data}->{partnumber}) };
973     if (!$part) {
974       push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
975       return 0;
976     }
977
978     $object->parts_id($part->id);
979   }
980
981   # Map description to ID if given.
982   if (!$object->parts_id && $entry->{raw_data}->{description}) {
983     my $part = $self->parts_by->{description}->{ trim($entry->{raw_data}->{description}) };
984     if (!$part) {
985       push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
986       return 0;
987     }
988
989     if ($self->part_counts_by->{description}->{ trim($entry->{raw_data}->{description}) } > 1) {
990       $is_ambiguous = 1;
991     } else {
992       $object->parts_id($part->id);
993     }
994   }
995
996   # Map ean to ID if given.
997   if (!$object->parts_id && $entry->{raw_data}->{ean}) {
998     my $part = $self->parts_by->{ean}->{ trim($entry->{raw_data}->{ean}) };
999     if (!$part) {
1000       push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
1001       return 0;
1002     }
1003
1004     if ($self->part_counts_by->{ean}->{ trim($entry->{raw_data}->{ean}) } > 1) {
1005       $is_ambiguous = 1;
1006     } else {
1007       $object->parts_id($part->id);
1008     }
1009   }
1010
1011   if ($object->parts_id) {
1012     $entry->{info_data}->{partnumber} = $self->parts_by->{id}->{ $object->parts_id }->partnumber;
1013   } else {
1014     if ($is_ambiguous) {
1015       push @{ $entry->{errors} }, $::locale->text('Error: Part is ambiguous');
1016     } else {
1017       push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
1018     }
1019     return 0;
1020   }
1021
1022   return 1;
1023 }
1024
1025 sub check_price_factor {
1026   my ($self, $entry) = @_;
1027
1028   my $object = $entry->{object};
1029
1030   # Check whether or not price_factor ID is valid.
1031   if ($object->price_factor_id && !$self->price_factors_by->{id}->{ $object->price_factor_id }) {
1032     push @{ $entry->{errors} }, $::locale->text('Error: Invalid price factor');
1033     return 0;
1034   }
1035
1036   # Map description to ID if given.
1037   if (!$object->price_factor_id && $entry->{raw_data}->{price_factor}) {
1038     my $price_factor = $self->price_factors_by->{description}->{ $entry->{raw_data}->{price_factor} };
1039     if (!$price_factor) {
1040       push @{ $entry->{errors} }, $::locale->text('Error: Invalid price factor');
1041       return 0;
1042     }
1043
1044     $object->price_factor_id($price_factor->id);
1045   }
1046
1047   return 1;
1048 }
1049
1050 sub check_pricegroup {
1051   my ($self, $entry) = @_;
1052
1053   my $object = $entry->{object};
1054
1055   # Check whether or not pricegroup ID is valid.
1056   if ($object->pricegroup_id && !$self->pricegroups_by->{id}->{ $object->pricegroup_id }) {
1057     push @{ $entry->{errors} }, $::locale->text('Error: Invalid price group');
1058     return 0;
1059   }
1060
1061   # Map pricegroup to ID if given.
1062   if (!$object->pricegroup_id && $entry->{raw_data}->{pricegroup}) {
1063     my $pricegroup = $self->pricegroups_by->{pricegroup}->{ $entry->{raw_data}->{pricegroup} };
1064     if (!$pricegroup) {
1065       push @{ $entry->{errors} }, $::locale->text('Error: Invalid price group');
1066       return 0;
1067     }
1068
1069     $object->pricegroup_id($pricegroup->id);
1070   }
1071
1072   return 1;
1073 }
1074
1075 sub check_warehouse {
1076   my ($self, $entry) = @_;
1077
1078   my $object = $entry->{object};
1079
1080   # Check whether or not warehouse ID is valid.
1081   if ($object->warehouse_id && !$self->warehouses_by->{id}->{ $object->warehouse_id }) {
1082     push @{ $entry->{errors} }, $::locale->text('Error: Invalid warehouse');
1083     return 0;
1084   }
1085
1086   # Map description to ID if given.
1087   if (!$object->warehouse_id && $entry->{raw_data}->{warehouse}) {
1088     my $wh = $self->warehouses_by->{description}->{ $entry->{raw_data}->{warehouse} };
1089     if (!$wh) {
1090       push @{ $entry->{errors} }, $::locale->text('Error: Invalid warehouse');
1091       return 0;
1092     }
1093
1094     $object->warehouse_id($wh->id);
1095   }
1096
1097   if ($object->warehouse_id) {
1098     $entry->{info_data}->{warehouse} = $self->warehouses_by->{id}->{ $object->warehouse_id }->description;
1099   } else {
1100     push @{ $entry->{errors} }, $::locale->text('Error: Warehouse not found');
1101     return 0;
1102   }
1103
1104   return 1;
1105 }
1106
1107 # Check bin for given warehouse, so check_warehouse must be called first.
1108 sub check_bin {
1109   my ($self, $entry) = @_;
1110
1111   my $object = $entry->{object};
1112
1113   # Check whether or not bin ID is valid.
1114   if ($object->bin_id && !$self->bins_by->{_wh_id_and_id_ident()}->{ _wh_id_and_id_maker($object->warehouse_id, $object->bin_id) }) {
1115     push @{ $entry->{errors} }, $::locale->text('Error: Invalid bin');
1116     return 0;
1117   }
1118
1119   # Map description to ID if given.
1120   if (!$object->bin_id && $entry->{raw_data}->{bin}) {
1121     my $bin = $self->bins_by->{_wh_id_and_description_ident()}->{ _wh_id_and_description_maker($object->warehouse_id, $entry->{raw_data}->{bin}) };
1122     if (!$bin) {
1123       push @{ $entry->{errors} }, $::locale->text('Error: Invalid bin');
1124       return 0;
1125     }
1126
1127     $object->bin_id($bin->id);
1128   }
1129
1130   if ($object->bin_id) {
1131     $entry->{info_data}->{bin} = $self->bins_by->{_wh_id_and_id_ident()}->{ _wh_id_and_id_maker($object->warehouse_id, $object->bin_id) }->description;
1132   } else {
1133     push @{ $entry->{errors} }, $::locale->text('Error: Bin not found');
1134     return 0;
1135   }
1136
1137   return 1;
1138 }
1139
1140 sub save_additions {
1141   my ($self, $object) = @_;
1142
1143   # record links
1144   my $orders = delete $object->{source_orders};
1145
1146   if (scalar(@$orders)) {
1147
1148     $_->link_to_record($object) for @$orders;
1149
1150     foreach my $item (@{ $object->items }) {
1151       my $orderitem = delete $item->{source_item};
1152       $orderitem->link_to_record($item) if $orderitem;
1153     }
1154   }
1155
1156   # delivery order for all positions created?
1157   if (scalar(@$orders)) {
1158     SL::Helper::ShippedQty->new->calculate($orders)->write_to_objects;
1159     $_->update_attributes(delivered => $_->delivered) for @{ $orders };
1160   }
1161
1162   # inventory (or use WH->transfer?)
1163   foreach my $item (@{ $object->items }) {
1164     foreach my $stock_info (@{ $item->delivery_order_stock_entries }) {
1165       my $inventory  = delete $stock_info->{inventory_obj};
1166       next if !$inventory;
1167       my ($trans_id) = selectrow_query($::form, $object->db->dbh, qq|SELECT nextval('id')|);
1168       $inventory->trans_id($trans_id);
1169       $inventory->oe_id($object->id);
1170       $inventory->delivery_order_items_stock_id($stock_info->id);
1171       $inventory->save;
1172     }
1173   }
1174 }
1175
1176 sub save_objects {
1177   my ($self, %params) = @_;
1178
1179   # Collect orders without errors to save.
1180   my $entries_to_save = [];
1181   foreach my $entry (@{ $self->controller->data }) {
1182     next if $entry->{raw_data}->{datatype} ne $self->_order_column;
1183     next if @{ $entry->{errors} };
1184
1185     push @{ $entries_to_save }, $entry;
1186   }
1187
1188   $self->SUPER::save_objects(data => $entries_to_save);
1189 }
1190
1191 sub get_stocked_qty {
1192   my ($self, $parts_id, $wh_id, $bin_id, $chargenumber, $bestbefore) = @_;
1193
1194   my $key = join '+', $parts_id, $wh_id, $bin_id, $chargenumber, $bestbefore;
1195   return $self->{stocked_qty}->{$key} if exists $self->{stocked_qty}->{$key};
1196
1197   my $bestbefore_filter  = '';
1198   my $bestbefore_val_cnt = 0;
1199   if ($::instance_conf->get_show_bestbefore) {
1200     $bestbefore_filter  = ($bestbefore) ? 'AND bestbefore = ?' : 'AND bestbefore IS NULL';
1201     $bestbefore_val_cnt = ($bestbefore) ? 1                    : 0;
1202   }
1203
1204   my $query = <<SQL;
1205     SELECT sum(qty) FROM inventory
1206       WHERE parts_id = ? AND warehouse_id = ? AND bin_id = ? AND chargenumber = ? $bestbefore_filter
1207       GROUP BY warehouse_id, bin_id, chargenumber
1208 SQL
1209
1210   my @values = ($parts_id,
1211                 $wh_id,
1212                 $bin_id,
1213                 $chargenumber);
1214   push @values, $bestbefore if $bestbefore_val_cnt;
1215
1216   my $dbh = $self->controller->data->[0]{object}->db->dbh;
1217   my ($stocked_qty) = selectrow_query($::form, $dbh, $query, @values);
1218
1219   $self->{stocked_qty}->{$key} = $stocked_qty;
1220   return $stocked_qty;
1221 }
1222
1223 sub _wh_id_and_description_ident {
1224   return 'wh_id+description';
1225 }
1226
1227 sub _wh_id_and_description_maker {
1228   return join '+', $_[0], $_[1]
1229 }
1230
1231 sub _wh_id_and_id_ident {
1232   return 'wh_id+id';
1233 }
1234
1235 sub _wh_id_and_id_maker {
1236   return join '+', $_[0], $_[1]
1237 }
1238
1239 sub _transfer_type_dir_and_description_ident {
1240   return 'dir+description';
1241 }
1242
1243 sub _transfer_type_dir_and_description_maker {
1244   return join '+', $_[0], $_[1]
1245 }
1246
1247 sub _order_column {
1248   $_[0]->settings->{'order_column'}
1249 }
1250
1251 sub _item_column {
1252   $_[0]->settings->{'item_column'}
1253 }
1254
1255 sub _stock_column {
1256   $_[0]->settings->{'stock_column'}
1257 }
1258
1259 1;