1 package SL::Controller::CsvImport::DeliveryOrder;
6 use List::Util qw(first);
7 use List::MoreUtils qw(any none uniq);
10 use SL::Controller::CsvImport::Helper::Consistency;
11 use SL::DB::DeliveryOrder;
12 use SL::DB::DeliveryOrderItem;
13 use SL::DB::DeliveryOrderItemsStock;
15 use SL::DB::PaymentTerm;
17 use SL::DB::PriceFactor;
18 use SL::DB::Pricegroup;
21 use SL::DB::Inventory;
22 use SL::DB::TransferType;
24 use SL::Helper::ShippedQty;
27 use SL::Util qw(trim);
29 use parent qw(SL::Controller::CsvImport::BaseMulti);
32 use Rose::Object::MakeMethods::Generic
34 'scalar --get_set_init' => [ qw(settings languages_by all_parts parts_by part_counts_by
35 contacts_by ct_shiptos_by
36 price_factors_by pricegroups_by units_by
37 warehouses_by bins_by transfer_types_by) ],
43 $self->class(['SL::DB::DeliveryOrder', 'SL::DB::DeliveryOrderItem', 'SL::DB::DeliveryOrderItemsStock']);
46 sub set_profile_defaults {
49 $self->controller->profile->_set_defaults(
50 order_column => $::locale->text('DeliveryOrder'),
51 item_column => $::locale->text('OrderItem'),
52 stock_column => $::locale->text('StockInfo'),
53 ignore_faulty_positions => 0,
60 return { map { ( $_ => $self->controller->profile->get($_) ) } qw(order_column item_column stock_column ignore_faulty_positions) };
63 sub init_cvar_configs_by {
66 my $item_cvar_configs = SL::DB::Manager::CustomVariableConfig->get_all(where => [ module => 'IC' ]);
67 $item_cvar_configs = [grep { $_->has_flag('editable') } @{ $item_cvar_configs }];
70 $ccb->{class}->{$self->class->[0]} = [];
71 $ccb->{class}->{$self->class->[1]} = $item_cvar_configs;
72 $ccb->{class}->{$self->class->[2]} = [];
73 $ccb->{row_ident}->{$self->_order_column} = [];
74 $ccb->{row_ident}->{$self->_item_column} = $item_cvar_configs;
75 $ccb->{row_ident}->{$self->_stock_column} = [];
83 my $profile = $self->SUPER::init_profile;
85 # SUPER::init_profile sets row_ident to the translated class name
86 # overwrite it with the user specified settings
87 foreach my $p (@{ $profile }) {
88 $p->{row_ident} = $self->_order_column if $p->{class} eq $self->class->[0];
89 $p->{row_ident} = $self->_item_column if $p->{class} eq $self->class->[1];
90 $p->{row_ident} = $self->_stock_column if $p->{class} eq $self->class->[2];
93 foreach my $p (@{ $profile }) {
94 my $prof = $p->{profile};
95 if ($p->{row_ident} eq $self->_order_column) {
97 delete @{$prof}{qw(oreqnumber)};
99 if ($p->{row_ident} eq $self->_item_column) {
101 delete @{$prof}{qw(delivery_order_id)};
103 if ($p->{row_ident} eq $self->_stock_column) {
105 delete @{$prof}{qw(delivery_order_item_id)};
106 delete @{$prof}{qw(bestbefore)} if !$::instance_conf->get_show_bestbefore;
113 sub init_existing_objects {
116 # only use objects of main class (the first one)
117 eval "require " . $self->class->[0];
118 $self->existing_objects($self->manager_class->[0]->get_all);
121 sub get_duplicate_check_fields {
124 label => $::locale->text('Delivery Order Number'),
128 my ($object, $worker) = @_;
129 return if ref $object ne $worker->class->[0];
130 return $object->donumber;
136 sub check_std_duplicates {
141 my $all_fields = $self->get_duplicate_check_fields();
143 foreach my $key (keys(%{ $all_fields })) {
144 if ( $self->controller->profile->get('duplicates_'. $key) && (!exists($all_fields->{$key}->{std_check}) || $all_fields->{$key}->{std_check} ) ) {
145 $duplicates->{$key} = {};
149 my @duplicates_keys = keys(%{ $duplicates });
151 if ( !scalar(@duplicates_keys) ) {
155 if ( $self->controller->profile->get('duplicates') eq 'check_db' ) {
156 foreach my $object (@{ $self->existing_objects }) {
157 foreach my $key (@duplicates_keys) {
158 my $value = exists($all_fields->{$key}->{maker}) ? $all_fields->{$key}->{maker}->($object, $self) : $object->$key;
159 $duplicates->{$key}->{$value} = 'db';
164 # only check order rows
165 foreach my $entry (@{ $self->controller->data }) {
166 if ($entry->{raw_data}->{datatype} ne $self->_order_column) {
169 if ( @{ $entry->{errors} } ) {
173 my $object = $entry->{object};
175 foreach my $key (@duplicates_keys) {
176 my $value = exists($all_fields->{$key}->{maker}) ? $all_fields->{$key}->{maker}->($object, $self) : $object->$key;
178 if ( exists($duplicates->{$key}->{$value}) ) {
179 push(@{ $entry->{errors} }, $duplicates->{$key}->{$value} eq 'db' ? $::locale->text('Duplicate in database') : $::locale->text('Duplicate in CSV file'));
182 $duplicates->{$key}->{$value} = 'csv';
189 sub setup_displayable_columns {
192 $self->SUPER::setup_displayable_columns;
194 $self->add_cvar_columns_to_displayable_columns($self->_order_column);
196 $self->add_displayable_columns($self->_order_column,
197 { name => 'datatype', description => $self->_order_column . ' [1]' },
198 { name => 'closed', description => $::locale->text('Closed') },
199 { name => 'contact', description => $::locale->text('Contact Person (name)') },
200 { name => 'cp_id', description => $::locale->text('Contact Person (database ID)') },
201 { name => 'currency', description => $::locale->text('Currency') },
202 { name => 'currency_id', description => $::locale->text('Currency (database ID)') },
203 { name => 'customer', description => $::locale->text('Customer (name)') },
204 { name => 'customernumber', description => $::locale->text('Customer Number') },
205 { name => 'customer_id', description => $::locale->text('Customer (database ID)') },
206 { name => 'cusordnumber', description => $::locale->text('Customer Order Number') },
207 { name => 'delivered', description => $::locale->text('Delivered') },
208 { name => 'delivery_term', description => $::locale->text('Delivery terms (name)') },
209 { name => 'delivery_term_id', description => $::locale->text('Delivery terms (database ID)') },
210 { name => 'department_id', description => $::locale->text('Department (database ID)') },
211 { name => 'department', description => $::locale->text('Department (description)') },
212 { name => 'donumber', description => $::locale->text('Delivery Order Number') },
213 { name => 'employee_id', description => $::locale->text('Employee (database ID)') },
214 { name => 'globalproject', description => $::locale->text('Document Project (description)') },
215 { name => 'globalprojectnumber', description => $::locale->text('Document Project (number)') },
216 { name => 'globalproject_id', description => $::locale->text('Document Project (database ID)') },
217 { name => 'intnotes', description => $::locale->text('Internal Notes') },
218 { name => 'is_sales', description => $::locale->text('Is sales') },
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 => 'ordnumber', description => $::locale->text('Order Number') },
223 { name => 'payment', description => $::locale->text('Payment terms (name)') },
224 { name => 'payment_id', description => $::locale->text('Payment terms (database ID)') },
225 { name => 'reqdate', description => $::locale->text('Reqdate') },
226 { name => 'salesman_id', description => $::locale->text('Salesman (database ID)') },
227 { name => 'shippingpoint', description => $::locale->text('Shipping Point') },
228 { name => 'shipvia', description => $::locale->text('Ship via') },
229 { name => 'shipto_id', description => $::locale->text('Ship to (database ID)') },
230 { name => 'taxincluded', description => $::locale->text('Tax Included') },
231 { name => 'taxzone', description => $::locale->text('Tax zone (description)') },
232 { name => 'taxzone_id', description => $::locale->text('Tax zone (database ID)') },
233 { name => 'transaction_description', description => $::locale->text('Transaction description') },
234 { name => 'transdate', description => $::locale->text('Order Date') },
235 { name => 'vendor', description => $::locale->text('Vendor (name)') },
236 { name => 'vendornumber', description => $::locale->text('Vendor Number') },
237 { name => 'vendor_id', description => $::locale->text('Vendor (database ID)') },
240 $self->add_cvar_columns_to_displayable_columns($self->_item_column);
242 $self->add_displayable_columns($self->_item_column,
243 { name => 'datatype', description => $self->_item_column . ' [1]' },
244 { name => 'cusordnumber', description => $::locale->text('Customer Order Number') },
245 { name => 'description', description => $::locale->text('Description') },
246 { name => 'discount', description => $::locale->text('Discount') },
247 { name => 'lastcost', description => $::locale->text('Lastcost') },
248 { name => 'longdescription', description => $::locale->text('Long Description') },
249 { name => 'ordnumber', description => $::locale->text('Order Number') },
250 { name => 'partnumber', description => $::locale->text('Part Number') },
251 { name => 'parts_id', description => $::locale->text('Part (database ID)') },
252 { name => 'position', description => $::locale->text('position') },
253 { name => 'price_factor', description => $::locale->text('Price factor (name)') },
254 { name => 'price_factor_id', description => $::locale->text('Price factor (database ID)') },
255 { name => 'pricegroup', description => $::locale->text('Price group (name)') },
256 { name => 'pricegroup_id', description => $::locale->text('Price group (database ID)') },
257 { name => 'project', description => $::locale->text('Project (description)') },
258 { name => 'projectnumber', description => $::locale->text('Project (number)') },
259 { name => 'project_id', description => $::locale->text('Project (database ID)') },
260 { name => 'qty', description => $::locale->text('Quantity') },
261 { name => 'reqdate', description => $::locale->text('Reqdate') },
262 { name => 'sellprice', description => $::locale->text('Sellprice') },
263 { name => 'serialnumber', description => $::locale->text('Serial No.') },
264 { name => 'transdate', description => $::locale->text('Order Date') },
265 { name => 'unit', description => $::locale->text('Unit') },
268 $self->add_cvar_columns_to_displayable_columns($self->_stock_column);
270 $self->add_displayable_columns($self->_stock_column,
271 { name => 'datatype', description => $self->_stock_column . ' [1]' },
272 { name => 'warehouse', description => $::locale->text('Warehouse') },
273 { name => 'warehouse_id', description => $::locale->text('Warehouse (database ID)') },
274 { name => 'bin', description => $::locale->text('Bin') },
275 { name => 'bin_id', description => $::locale->text('Bin (database ID)') },
276 { name => 'chargenumber', description => $::locale->text('Charge number') },
277 { name => 'qty', description => $::locale->text('Quantity') },
278 { name => 'unit', description => $::locale->text('Unit') },
280 if ($::instance_conf->get_show_bestbefore) {
281 $self->add_displayable_columns($self->_stock_column,
282 { name => 'bestbefore', description => $::locale->text('Best Before') });
287 sub init_languages_by {
290 return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $self->all_languages } } ) } qw(id description article_code) };
296 return SL::DB::Manager::Part->get_all(where => [or => [ obsolete => 0, obsolete => undef ]]);
302 return { map { my $col = $_; ( $col => { map { ( trim($_->$col) => $_ ) } @{ $self->all_parts } } ) } qw(id partnumber ean description) };
305 sub init_part_counts_by {
310 $part_counts_by->{ean}-> {trim($_->ean)}++ for @{ $self->all_parts };
311 $part_counts_by->{description}->{trim($_->description)}++ for @{ $self->all_parts };
313 return $part_counts_by;
316 sub init_contacts_by {
319 my $all_contacts = SL::DB::Manager::Contact->get_all;
322 # by customer/vendor id _and_ contact person id
323 $cby->{'cp_cv_id+cp_id'} = { map { ( $_->cp_cv_id . '+' . $_->cp_id => $_ ) } @{ $all_contacts } };
324 # by customer/vendor id _and_ contact person name
325 $cby->{'cp_cv_id+cp_name'} = { map { ( $_->cp_cv_id . '+' . $_->cp_name => $_ ) } @{ $all_contacts } };
330 sub init_ct_shiptos_by {
333 my $all_ct_shiptos = SL::DB::Manager::Shipto->get_all(query => [module => 'CT']);
336 # by trans_id _and_ shipto_id
337 $sby->{'trans_id+shipto_id'} = { map { ( $_->trans_id . '+' . $_->shipto_id => $_ ) } @{ $all_ct_shiptos } };
342 sub init_price_factors_by {
345 my $all_price_factors = SL::DB::Manager::PriceFactor->get_all;
346 return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_price_factors } } ) } qw(id description) };
349 sub init_pricegroups_by {
352 my $all_pricegroups = SL::DB::Manager::Pricegroup->get_all;
353 return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_pricegroups } } ) } qw(id pricegroup) };
359 my $all_units = SL::DB::Manager::Unit->get_all;
360 return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_units } } ) } qw(name) };
363 sub init_warehouses_by {
366 my $all_warehouses = SL::DB::Manager::Warehouse->get_all(query => [ or => [ invalid => 0, invalid => undef ]]);
367 return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_warehouses } } ) } qw(id description) };
373 my $all_bins = SL::DB::Manager::Bin->get_all();
375 $bins_by->{_wh_id_and_id_ident()} = { map { ( _wh_id_and_id_maker($_->warehouse_id, $_->id) => $_ ) } @{ $all_bins } };
376 $bins_by->{_wh_id_and_description_ident()} = { map { ( _wh_id_and_description_maker($_->warehouse_id, $_->description) => $_ ) } @{ $all_bins } };
381 sub init_transfer_types_by {
384 my $all_transfer_types = SL::DB::Manager::TransferType->get_all();
385 my $transfer_types_by;
386 $transfer_types_by->{_transfer_type_dir_and_description_ident()} = {
387 map { ( _transfer_type_dir_and_description_maker($_->direction, $_->description) => $_ ) } @{ $all_transfer_types }
390 return $transfer_types_by;
396 $self->controller->track_progress(phase => 'building data', progress => 0);
399 my $num_data = scalar @{ $self->controller->data };
402 foreach my $entry (@{ $self->controller->data }) {
403 $self->controller->track_progress(progress => $i/$num_data * 100) if $i % 100 == 0;
405 $entry->{info_data}->{datatype} = $entry->{raw_data}->{datatype};
407 if ($entry->{raw_data}->{datatype} eq $self->_order_column) {
408 $self->handle_order($entry);
409 $order_entry = $entry;
410 } elsif ($entry->{raw_data}->{datatype} eq $self->_item_column && $entry->{object}->can('part')) {
411 $self->handle_item($entry, $order_entry);
412 $item_entry = $entry;
413 } elsif ($entry->{raw_data}->{datatype} eq $self->_stock_column) {
414 $self->handle_stock($entry, $item_entry, $order_entry);
415 push @{ $order_entry->{errors} }, $::locale->text('Error: Stock problem') if scalar(@{$entry->{errors}}) > 0;
417 $order_entry = undef;
421 $self->handle_cvars($entry, sub_module => 'delivery_order_items');
427 $self->add_info_columns($self->_order_column,
428 { header => $::locale->text('Data type'), method => 'datatype' });
429 $self->add_info_columns($self->_item_column,
430 { header => $::locale->text('Data type'), method => 'datatype' });
431 $self->add_info_columns($self->_stock_column,
432 { header => $::locale->text('Data type'), method => 'datatype' });
434 $self->add_info_columns($self->_order_column,
435 { header => $::locale->text('Customer/Vendor'), method => 'vc_name' });
436 # Todo: access via ->[0] ok? Better: search first order column and use this
437 $self->add_columns($self->_order_column,
438 map { "${_}_id" } grep { exists $self->controller->data->[0]->{raw_data}->{$_} } qw(payment delivery_term language department globalproject taxzone cp currency));
439 $self->add_columns($self->_order_column, 'globalproject_id') if exists $self->controller->data->[0]->{raw_data}->{globalprojectnumber};
440 $self->add_columns($self->_order_column, 'cp_id') if exists $self->controller->data->[0]->{raw_data}->{contact};
442 $self->add_info_columns($self->_item_column,
443 { header => $::locale->text('Part Number'), method => 'partnumber' });
444 # Todo: access via ->[1] ok? Better: search first item column and use this
445 $self->add_columns($self->_item_column,
446 map { "${_}_id" } grep { exists $self->controller->data->[1]->{raw_data}->{$_} } qw(project price_factor pricegroup));
447 $self->add_columns($self->_item_column, 'project_id') if exists $self->controller->data->[1]->{raw_data}->{projectnumber};
449 $self->add_cvar_raw_data_columns();
452 # Check overall qtys for sales delivery orders, because they are
453 # stocked out in the end and a stock underrun can occure.
454 # Todo: let it work even with bestbefore turned off.
455 $order_entry = undef;
457 my %wanted_qtys_by_part_wh_bin_charge_bestbefore;
458 my %stock_entries_with_part_wh_bin_charge_bestbefore;
459 my %order_entries_with_part_wh_bin_charge_bestbefore;
460 foreach my $entry (@{ $self->controller->data }) {
461 if ($entry->{raw_data}->{datatype} eq $self->_order_column) {
462 if (scalar(@{ $entry->{errors} }) || !$entry->{object}->is_sales) {
463 $order_entry = undef;
467 $order_entry = $entry;
469 } elsif (defined $order_entry && $entry->{raw_data}->{datatype} eq $self->_item_column) {
470 if (scalar(@{ $entry->{errors} })) {
474 $item_entry = $entry;
476 } elsif (defined $item_entry && $entry->{raw_data}->{datatype} eq $self->_stock_column) {
477 my $object = $entry->{object};
479 $item_entry->{object}->parts_id,
480 $object->warehouse_id,
482 $object->chargenumber,
483 $object->bestbefore);
484 $wanted_qtys_by_part_wh_bin_charge_bestbefore{$key} += $object->qty;
485 push @{$order_entries_with_part_wh_bin_charge_bestbefore{$key}}, $order_entry;
486 push @{$stock_entries_with_part_wh_bin_charge_bestbefore{$key}}, $entry;
490 foreach my $key (keys %wanted_qtys_by_part_wh_bin_charge_bestbefore) {
491 my ($parts_id, $wh_id, $bin_id, $chargenumber, $bestbefore) = split '\+', $key;
492 my $qty = $self->get_stocked_qty($parts_id, $wh_id, $bin_id, $chargenumber, $bestbefore);
493 if ($wanted_qtys_by_part_wh_bin_charge_bestbefore{$key} > $qty) {
495 foreach my $stock_entry (@{ $stock_entries_with_part_wh_bin_charge_bestbefore{$key} }) {
496 push @{ $stock_entry->{errors} }, $::locale->text('Error: Stocking out would result in stock underrun');
499 foreach my $order_entry (uniq @{ $order_entries_with_part_wh_bin_charge_bestbefore{$key} }) {
500 my $part = $self->parts_by->{id}->{$parts_id}->displayable_name;
501 my $stock = $self->bins_by->{_wh_id_and_id_ident()}->{_wh_id_and_id_maker($wh_id, $bin_id)}->full_description;
502 my $bestbefore_obj = $::locale->parse_date_to_object($bestbefore, dateformat=>'yyyy-mm-dd');
503 my $bestbefore_text = $bestbefore_obj? $::locale->parse_date_to_object($bestbefore_obj, dateformat=>'yyyy-mm-dd')->to_kivitendo: '-';
504 my $wanted_qty = $wanted_qtys_by_part_wh_bin_charge_bestbefore{$key};
505 my $details_text = sprintf('%s (%s / %s / %s): %s > %s',
510 $::form->format_amount(\%::myconfig, $wanted_qty, 2),
511 $::form->format_amount(\%::myconfig, $qty, 2));
512 push @{ $order_entry->{errors} }, $::locale->text('Error: Stocking out would result in stock underrun: #1', $details_text);
521 my ($self, $entry) = @_;
523 my $object = $entry->{object};
525 $object->orderitems([]);
527 $self->handle_order_sources($entry);
528 my $first_source_order = $object->{source_orders}->[0];
531 if (any { $entry->{raw_data}->{$_} } qw(customer customernumber customer_id)) {
532 $self->check_vc($entry, 'customer_id');
533 $vc_obj = SL::DB::Customer->new(id => $object->customer_id)->load if $object->customer_id;
535 } elsif (any { $entry->{raw_data}->{$_} } qw(vendor vendornumber vendor_id)) {
536 $self->check_vc($entry, 'vendor_id');
537 $vc_obj = SL::DB::Vendor->new(id => $object->vendor_id)->load if $object->vendor_id;
540 # customer / vendor from (first) source order if not given
541 if ($first_source_order) {
542 if ($first_source_order->customer) {
543 $vc_obj = $first_source_order->customer;
544 $object->customer($first_source_order->customer);
545 } elsif ($first_source_order->vendor) {
546 $vc_obj = $first_source_order->vendor;
547 $object->vendor($first_source_order->vendor);
553 push @{ $entry->{errors} }, $::locale->text('Error: Customer/vendor missing');
556 $self->handle_is_sales($entry);
557 $self->check_contact($entry);
558 $self->check_language($entry);
559 $self->check_payment($entry);
560 $self->check_delivery_term($entry);
561 $self->check_department($entry);
562 $self->check_project($entry, global => 1);
563 $self->check_ct_shipto($entry);
564 $self->check_taxzone($entry);
565 $self->check_currency($entry, take_default => 0);
567 # copy from (first) source order if not given
568 # if no source order, then copy some values from customer/vendor
569 if ($first_source_order) {
570 foreach (qw(cusordnumber notes intnotes shippingpoint shipvia
571 transaction_description currency_id delivery_term_id
572 department_id language_id payment_id globalproject_id shipto_id
574 $object->$_($first_source_order->$_) unless $object->$_;
577 foreach (qw(currency_id delivery_term_id language_id payment_id taxzone_id)) {
578 $object->$_($vc_obj->$_) unless $object->$_;
580 $object->intnotes($vc_obj->notes) unless $object->intnotes;
583 $self->handle_salesman($entry);
584 $self->handle_employee($entry);
588 my ($self, $entry, $order_entry) = @_;
590 return unless $order_entry;
592 my $order_obj = $order_entry->{object};
593 my $object = $entry->{object};
594 $object->delivery_order_stock_entries([]);
596 if (!$self->check_part($entry)) {
597 if ($self->controller->profile->get('ignore_faulty_positions')) {
598 push @{ $order_entry->{information} }, $::locale->text('Warning: Faulty position ignored');
600 push @{ $order_entry->{errors} }, $::locale->text('Error: Faulty position in this delivery order');
605 $order_obj->add_items($object);
607 my $part_obj = SL::DB::Part->new(id => $object->parts_id)->load;
609 $self->handle_item_source($entry, $order_entry);
610 $object->position($object->{source_item}->position) if $object->{source_item};
612 $self->handle_unit($entry);
614 # copy from part if not given
615 $object->description($part_obj->description) unless $object->description;
616 $object->longdescription($part_obj->notes) unless $object->longdescription;
617 $object->lastcost($part_obj->lastcost) unless defined $object->lastcost;
619 $self->check_project($entry, global => 0);
620 $self->check_price_factor($entry);
621 $self->check_pricegroup($entry);
623 $self->handle_sellprice($entry, $order_entry);
624 $self->handle_discount($entry, $order_entry);
626 push @{ $order_entry->{errors} }, $::locale->text('Error: Faulty position in this delivery order') if scalar(@{$entry->{errors}}) > 0;
630 my ($self, $entry, $item_entry, $order_entry) = @_;
632 return unless $item_entry;
634 my $item_obj = $item_entry->{object};
635 return unless $item_obj->part;
637 my $order_obj = $order_entry->{object};
638 my $object = $entry->{object};
640 $item_obj->add_delivery_order_stock_entries($object);
642 $self->check_warehouse($entry);
643 $self->check_bin($entry);
645 $self->handle_unit($entry, $item_obj->part);
647 # check if enough is stocked
648 # not necessary, because overall stock underrun is checked later
649 # if ($order_obj->is_sales) {
650 # my $stocked_qty = $self->get_stocked_qty($item_obj->parts_id,
651 # $object->warehouse_id,
653 # $object->chargenumber,
654 # $object->bestbefore);
655 # if ($stocked_qty < $object->qty) {
656 # push @{ $entry->{errors} }, $::locale->text('Error: Not enough parts in stock');
660 my ($stock_info_entry, $part) = @_;
662 # Todo: option: should stock?
664 my $tt_key = $order_obj->is_sales
665 ? _transfer_type_dir_and_description_maker('out', 'shipped')
666 : _transfer_type_dir_and_description_maker('in', 'stock');
667 my $trans_type_id = $self->transfer_types_by->{_transfer_type_dir_and_description_ident()}{$tt_key}->id;
669 my $qty = $order_obj->is_sales ? -1*($object->qty) : $object->qty;
670 my $inventory = SL::DB::Inventory->new(
671 parts_id => $item_obj->parts_id,
672 warehouse_id => $object->warehouse_id,
673 bin_id => $object->bin_id,
674 trans_type_id => $trans_type_id,
676 chargenumber => $object->chargenumber,
677 employee_id => $order_obj->employee_id,
678 shippingdate => ($order_obj->reqdate || DateTime->today_local),
679 comment => $order_obj->transaction_description,
680 project_id => ($order_obj->globalproject_id || $item_obj->project_id),
682 $inventory->bestbefore($object->bestbefore) if $::instance_conf->get_show_bestbefore;
683 $object->{inventory_obj} = $inventory;
684 $order_obj->delivered(1);
688 sub handle_is_sales {
689 my ($self, $entry) = @_;
691 if (!exists $entry->{raw_data}->{is_sales}) {
692 $entry->{object}->is_sales(!!$entry->{object}->customer_id);
696 sub handle_order_sources {
697 my ($self, $entry) = @_;
699 my $record = $entry->{object};
701 $record->{source_orders} = [];
702 return $record->{source_orders} if !$record->ordnumber;
704 my @order_numbers = split ' ', $record->ordnumber;
706 my $orders = SL::DB::Manager::Order->get_all(where => [ordnumber => \@order_numbers]);
708 if (scalar @$orders == 0) {
709 push @{ $entry->{errors} }, $::locale->text('Error: Source order not found');
710 } elsif (scalar @$orders > 1) {
711 push @{ $entry->{errors} }, $::locale->text('Error: More than one source order found');
714 foreach my $order (@$orders) {
715 $self->{remaining_source_qtys_by_item_id} = { map { $_->id => $_->qty } @{ $order->items } };
718 $record->{source_orders} = $orders;
721 sub handle_item_source {
722 my ($self, $entry, $record_entry) = @_;
724 my $item = $entry->{object};
725 my $record = $record_entry->{object};
727 return if !@{ $record->{source_orders} };
731 foreach my $order (@{ $record->{source_orders} }) {
732 # First: Excact matches and source order position is still complete.
733 $item->{source_item} = first {
734 $item->parts_id == $_->parts_id
735 && $item->qty == $_->qty
736 && $self->{remaining_source_qtys_by_item_id}->{$_->id} == $_->qty
737 } @{ $order->items_sorted };
738 if ($item->{source_item}) {
739 $self->{remaining_source_qtys_by_item_id}->{$item->{source_item}->id} -= $item->qty;
743 # Second: Smallest remaining order qty greater or equal delivery order qty.
744 $item->{source_item} = first {
745 $item->parts_id == $_->parts_id
746 && $self->{remaining_source_qtys_by_item_id}->{$_->id} >= $item->qty
747 } sort { $self->{remaining_source_qtys_by_item_id}->{$a->id} <=> $self->{remaining_source_qtys_by_item_id}->{$b->id} } @{ $order->items_sorted };
748 if ($item->{source_item}) {
749 $self->{remaining_source_qtys_by_item_id}->{$item->{source_item}->id} -= $item->qty;
753 # Last: Overdelivery?
754 # $item->{source_item} = first {
755 # $item->parts_id == $_->parts_id
756 # } @{ $order->items_sorted };
757 # if ($item->{source_item}) {
758 # $self->{remaining_source_qtys_by_item_id}->{$item->{source_item}->id} -= $item->qty;
765 my ($self, $entry, $part) = @_;
767 my $object = $entry->{object};
769 $part ||= $object->part;
771 # Set unit from part if not given.
772 if (!$object->unit) {
773 $object->unit($part->unit);
777 # Check whether or not unit is valid.
778 if ($object->unit && !$self->units_by->{name}->{ $object->unit }) {
779 push @{ $entry->{errors} }, $::locale->text('Error: Invalid unit');
783 # Check whether unit is convertible to parts unit
784 if (none { $object->unit eq $_ } map { $_->name } @{ $part->unit_obj->convertible_units }) {
785 push @{ $entry->{errors} }, $::locale->text('Error: Invalid unit');
792 sub handle_sellprice {
793 my ($self, $entry, $record_entry) = @_;
795 my $item = $entry->{object};
796 my $record = $record_entry->{object};
798 return if !$record->customervendor;
800 # If sellprice is given, set price source to pricegroup if given or to none.
801 if (exists $entry->{raw_data}->{sellprice}) {
802 my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
803 my $price_source_spec = $item->pricegroup_id ? 'pricegroup' . '/' . $item->pricegroup_id : '';
804 my $price = $price_source->price_from_source($price_source_spec);
805 $item->active_price_source($price->source);
809 if ($item->{source_item}) {
810 # Set sellprice from source order item if not given. Convert with respect to unit.
811 my $sellprice = $item->{source_item}->sellprice;
812 if ($item->unit ne $item->{source_item}->unit) {
813 $sellprice = $item->unit_obj->convert_to($sellprice, $item->{source_item}->unit_obj);
815 $item->sellprice($sellprice);
816 $item->active_price_source($item->{source_item}->active_price_source);
819 # Set sellprice the best price of price source
820 my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
821 my $price = $price_source->best_price;
823 $item->sellprice($price->price);
824 $item->active_price_source($price->source);
827 $item->active_price_source($price_source->price_from_source('')->source);
833 sub handle_discount {
834 my ($self, $entry, $record_entry) = @_;
836 my $item = $entry->{object};
837 my $record = $record_entry->{object};
839 return if !$record->customervendor;
841 # If discount is given, set discount to none.
842 if (exists $entry->{raw_data}->{discount}) {
843 my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
844 my $discount = $price_source->price_from_source('');
845 $item->active_discount_source($discount->source);
849 if ($item->{source_item}) {
850 # Set discount from source order item if not given.
851 $item->discount($item->{source_item}->discount);
852 $item->active_discount_source($item->{source_item}->active_discount_source);
855 # Set discount the best discount of price source
856 my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
857 my $discount = $price_source->best_discount;
859 $item->discount($discount->discount);
860 $item->active_discount_source($discount->source);
863 $item->active_discount_source($price_source->discount_from_source('')->source);
870 my ($self, $entry) = @_;
872 my $object = $entry->{object};
874 my $cp_cv_id = $object->customer_id || $object->vendor_id;
875 return 0 unless $cp_cv_id;
877 # Check whether or not contact ID is valid.
878 if ($object->cp_id && !$self->contacts_by->{'cp_cv_id+cp_id'}->{ $cp_cv_id . '+' . $object->cp_id }) {
879 push @{ $entry->{errors} }, $::locale->text('Error: Invalid contact');
883 # Map name to ID if given.
884 if (!$object->cp_id && $entry->{raw_data}->{contact}) {
885 my $cp = $self->contacts_by->{'cp_cv_id+cp_name'}->{ $cp_cv_id . '+' . $entry->{raw_data}->{contact} };
887 push @{ $entry->{errors} }, $::locale->text('Error: Invalid contact');
891 $object->cp_id($cp->cp_id);
894 if ($object->cp_id) {
895 $entry->{info_data}->{contact} = $self->contacts_by->{'cp_cv_id+cp_id'}->{ $cp_cv_id . '+' . $object->cp_id }->cp_name;
902 my ($self, $entry) = @_;
904 my $object = $entry->{object};
906 # Check whether or not language ID is valid.
907 if ($object->language_id && !$self->languages_by->{id}->{ $object->language_id }) {
908 push @{ $entry->{errors} }, $::locale->text('Error: Invalid language');
912 # Map name to ID if given.
913 if (!$object->language_id && $entry->{raw_data}->{language}) {
914 my $language = $self->languages_by->{description}->{ $entry->{raw_data}->{language} }
915 || $self->languages_by->{article_code}->{ $entry->{raw_data}->{language} };
918 push @{ $entry->{errors} }, $::locale->text('Error: Invalid language');
922 $object->language_id($language->id);
925 if ($object->language_id) {
926 $entry->{info_data}->{language} = $self->languages_by->{id}->{ $object->language_id }->description;
932 sub check_ct_shipto {
933 my ($self, $entry) = @_;
935 my $object = $entry->{object};
937 my $trans_id = $object->customer_id || $object->vendor_id;
938 return 0 unless $trans_id;
940 # Check whether or not shipto ID is valid.
941 if ($object->shipto_id && !$self->ct_shiptos_by->{'trans_id+shipto_id'}->{ $trans_id . '+' . $object->shipto_id }) {
942 push @{ $entry->{errors} }, $::locale->text('Error: Invalid shipto');
950 my ($self, $entry) = @_;
952 my $object = $entry->{object};
955 # Check whether or not part ID is valid.
956 if ($object->parts_id && !$self->parts_by->{id}->{ $object->parts_id }) {
957 push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
961 # Map number to ID if given.
962 if (!$object->parts_id && $entry->{raw_data}->{partnumber}) {
963 my $part = $self->parts_by->{partnumber}->{ trim($entry->{raw_data}->{partnumber}) };
965 push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
969 $object->parts_id($part->id);
972 # Map description to ID if given.
973 if (!$object->parts_id && $entry->{raw_data}->{description}) {
974 my $part = $self->parts_by->{description}->{ trim($entry->{raw_data}->{description}) };
976 push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
980 if ($self->part_counts_by->{description}->{ trim($entry->{raw_data}->{description}) } > 1) {
983 $object->parts_id($part->id);
987 # Map ean to ID if given.
988 if (!$object->parts_id && $entry->{raw_data}->{ean}) {
989 my $part = $self->parts_by->{ean}->{ trim($entry->{raw_data}->{ean}) };
991 push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
995 if ($self->part_counts_by->{ean}->{ trim($entry->{raw_data}->{ean}) } > 1) {
998 $object->parts_id($part->id);
1002 if ($object->parts_id) {
1003 $entry->{info_data}->{partnumber} = $self->parts_by->{id}->{ $object->parts_id }->partnumber;
1005 if ($is_ambiguous) {
1006 push @{ $entry->{errors} }, $::locale->text('Error: Part is ambiguous');
1008 push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
1016 sub check_price_factor {
1017 my ($self, $entry) = @_;
1019 my $object = $entry->{object};
1021 # Check whether or not price_factor ID is valid.
1022 if ($object->price_factor_id && !$self->price_factors_by->{id}->{ $object->price_factor_id }) {
1023 push @{ $entry->{errors} }, $::locale->text('Error: Invalid price factor');
1027 # Map description to ID if given.
1028 if (!$object->price_factor_id && $entry->{raw_data}->{price_factor}) {
1029 my $price_factor = $self->price_factors_by->{description}->{ $entry->{raw_data}->{price_factor} };
1030 if (!$price_factor) {
1031 push @{ $entry->{errors} }, $::locale->text('Error: Invalid price factor');
1035 $object->price_factor_id($price_factor->id);
1041 sub check_pricegroup {
1042 my ($self, $entry) = @_;
1044 my $object = $entry->{object};
1046 # Check whether or not pricegroup ID is valid.
1047 if ($object->pricegroup_id && !$self->pricegroups_by->{id}->{ $object->pricegroup_id }) {
1048 push @{ $entry->{errors} }, $::locale->text('Error: Invalid price group');
1052 # Map pricegroup to ID if given.
1053 if (!$object->pricegroup_id && $entry->{raw_data}->{pricegroup}) {
1054 my $pricegroup = $self->pricegroups_by->{pricegroup}->{ $entry->{raw_data}->{pricegroup} };
1056 push @{ $entry->{errors} }, $::locale->text('Error: Invalid price group');
1060 $object->pricegroup_id($pricegroup->id);
1066 sub check_warehouse {
1067 my ($self, $entry) = @_;
1069 my $object = $entry->{object};
1071 # Check whether or not warehouse ID is valid.
1072 if ($object->warehouse_id && !$self->warehouses_by->{id}->{ $object->warehouse_id }) {
1073 push @{ $entry->{errors} }, $::locale->text('Error: Invalid warehouse');
1077 # Map description to ID if given.
1078 if (!$object->warehouse_id && $entry->{raw_data}->{warehouse}) {
1079 my $wh = $self->warehouses_by->{description}->{ $entry->{raw_data}->{warehouse} };
1081 push @{ $entry->{errors} }, $::locale->text('Error: Invalid warehouse');
1085 $object->warehouse_id($wh->id);
1088 if ($object->warehouse_id) {
1089 $entry->{info_data}->{warehouse} = $self->warehouses_by->{id}->{ $object->warehouse_id }->description;
1091 push @{ $entry->{errors} }, $::locale->text('Error: Warehouse not found');
1098 # Check bin for given warehouse, so check_warehouse must be called first.
1100 my ($self, $entry) = @_;
1102 my $object = $entry->{object};
1104 # Check whether or not bin ID is valid.
1105 if ($object->bin_id && !$self->bins_by->{_wh_id_and_id_ident()}->{ _wh_id_and_id_maker($object->warehouse_id, $object->bin_id) }) {
1106 push @{ $entry->{errors} }, $::locale->text('Error: Invalid bin');
1110 # Map description to ID if given.
1111 if (!$object->bin_id && $entry->{raw_data}->{bin}) {
1112 my $bin = $self->bins_by->{_wh_id_and_description_ident()}->{ _wh_id_and_description_maker($object->warehouse_id, $entry->{raw_data}->{bin}) };
1114 push @{ $entry->{errors} }, $::locale->text('Error: Invalid bin');
1118 $object->bin_id($bin->id);
1121 if ($object->bin_id) {
1122 $entry->{info_data}->{bin} = $self->bins_by->{_wh_id_and_id_ident()}->{ _wh_id_and_id_maker($object->warehouse_id, $object->bin_id) }->description;
1124 push @{ $entry->{errors} }, $::locale->text('Error: Bin not found');
1131 sub save_additions {
1132 my ($self, $object) = @_;
1135 my $orders = delete $object->{source_orders};
1137 if (scalar(@$orders)) {
1139 $_->link_to_record($object) for @$orders;
1141 foreach my $item (@{ $object->items }) {
1142 my $orderitem = delete $item->{source_item};
1143 $orderitem->link_to_record($item) if $orderitem;
1147 # delivery order for all positions created?
1148 if (scalar(@$orders)) {
1149 SL::Helper::ShippedQty->new->calculate($orders)->write_to_objects;
1150 $_->update_attributes(delivered => $_->delivered) for @{ $orders };
1153 # inventory (or use WH->transfer?)
1154 foreach my $item (@{ $object->items }) {
1155 foreach my $stock_info (@{ $item->delivery_order_stock_entries }) {
1156 my $inventory = delete $stock_info->{inventory_obj};
1157 next if !$inventory;
1158 my ($trans_id) = selectrow_query($::form, $object->db->dbh, qq|SELECT nextval('id')|);
1159 $inventory->trans_id($trans_id);
1160 $inventory->oe_id($object->id);
1161 $inventory->delivery_order_items_stock_id($stock_info->id);
1168 my ($self, %params) = @_;
1170 # Collect orders without errors to save.
1171 my $entries_to_save = [];
1172 foreach my $entry (@{ $self->controller->data }) {
1173 next if $entry->{raw_data}->{datatype} ne $self->_order_column;
1174 next if @{ $entry->{errors} };
1176 push @{ $entries_to_save }, $entry;
1179 $self->SUPER::save_objects(data => $entries_to_save);
1182 sub get_stocked_qty {
1183 my ($self, $parts_id, $wh_id, $bin_id, $chargenumber, $bestbefore) = @_;
1185 my $key = join '+', $parts_id, $wh_id, $bin_id, $chargenumber, $bestbefore;
1186 return $self->{stocked_qty}->{$key} if exists $self->{stocked_qty}->{$key};
1188 my $bestbefore_filter = '';
1189 my $bestbefore_val_cnt = 0;
1190 if ($::instance_conf->get_show_bestbefore) {
1191 $bestbefore_filter = ($bestbefore) ? 'AND bestbefore = ?' : 'AND bestbefore IS NULL';
1192 $bestbefore_val_cnt = ($bestbefore) ? 1 : 0;
1196 SELECT sum(qty) FROM inventory
1197 WHERE parts_id = ? AND warehouse_id = ? AND bin_id = ? AND chargenumber = ? $bestbefore_filter
1198 GROUP BY warehouse_id, bin_id, chargenumber
1201 my @values = ($parts_id,
1205 push @values, $bestbefore if $bestbefore_val_cnt;
1207 my $dbh = $self->controller->data->[0]{object}->db->dbh;
1208 my ($stocked_qty) = selectrow_query($::form, $dbh, $query, @values);
1210 $self->{stocked_qty}->{$key} = $stocked_qty;
1211 return $stocked_qty;
1214 sub _wh_id_and_description_ident {
1215 return 'wh_id+description';
1218 sub _wh_id_and_description_maker {
1219 return join '+', $_[0], $_[1]
1222 sub _wh_id_and_id_ident {
1226 sub _wh_id_and_id_maker {
1227 return join '+', $_[0], $_[1]
1230 sub _transfer_type_dir_and_description_ident {
1231 return 'dir+description';
1234 sub _transfer_type_dir_and_description_maker {
1235 return join '+', $_[0], $_[1]
1239 $_[0]->settings->{'order_column'}
1243 $_[0]->settings->{'item_column'}
1247 $_[0]->settings->{'stock_column'}