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::DeliveryOrder::TypeData qw(:types);
13 use SL::DB::DeliveryOrderItem;
14 use SL::DB::DeliveryOrderItemsStock;
16 use SL::DB::PaymentTerm;
18 use SL::DB::PriceFactor;
19 use SL::DB::Pricegroup;
22 use SL::DB::Inventory;
23 use SL::DB::TransferType;
25 use SL::Helper::ShippedQty;
28 use SL::Util qw(trim);
30 use parent qw(SL::Controller::CsvImport::BaseMulti);
33 use Rose::Object::MakeMethods::Generic
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) ],
44 $self->class(['SL::DB::DeliveryOrder', 'SL::DB::DeliveryOrderItem', 'SL::DB::DeliveryOrderItemsStock']);
47 sub set_profile_defaults {
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,
61 return { map { ( $_ => $self->controller->profile->get($_) ) } qw(order_column item_column stock_column ignore_faulty_positions) };
64 sub init_cvar_configs_by {
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 }];
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} = [];
84 my $profile = $self->SUPER::init_profile;
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];
94 foreach my $p (@{ $profile }) {
95 my $prof = $p->{profile};
96 if ($p->{row_ident} eq $self->_order_column) {
98 delete @{$prof}{qw(oreqnumber)};
100 if ($p->{row_ident} eq $self->_item_column) {
102 delete @{$prof}{qw(delivery_order_id)};
104 if ($p->{row_ident} eq $self->_stock_column) {
106 delete @{$prof}{qw(delivery_order_item_id)};
107 delete @{$prof}{qw(bestbefore)} if !$::instance_conf->get_show_bestbefore;
114 sub init_existing_objects {
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);
122 sub get_duplicate_check_fields {
125 label => $::locale->text('Delivery Order Number'),
129 my ($object, $worker) = @_;
130 return if ref $object ne $worker->class->[0];
131 return $object->donumber;
137 sub check_std_duplicates {
142 my $all_fields = $self->get_duplicate_check_fields();
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} = {};
150 my @duplicates_keys = keys(%{ $duplicates });
152 if ( !scalar(@duplicates_keys) ) {
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';
165 # only check order rows
166 foreach my $entry (@{ $self->controller->data }) {
167 if ($entry->{raw_data}->{datatype} ne $self->_order_column) {
170 if ( @{ $entry->{errors} } ) {
174 my $object = $entry->{object};
176 foreach my $key (@duplicates_keys) {
177 my $value = exists($all_fields->{$key}->{maker}) ? $all_fields->{$key}->{maker}->($object, $self) : $object->$key;
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'));
183 $duplicates->{$key}->{$value} = 'csv';
190 sub setup_displayable_columns {
193 $self->SUPER::setup_displayable_columns;
195 $self->add_cvar_columns_to_displayable_columns($self->_order_column);
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)') },
241 $self->add_cvar_columns_to_displayable_columns($self->_item_column);
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') },
269 $self->add_cvar_columns_to_displayable_columns($self->_stock_column);
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') },
281 if ($::instance_conf->get_show_bestbefore) {
282 $self->add_displayable_columns($self->_stock_column,
283 { name => 'bestbefore', description => $::locale->text('Best Before') });
288 sub init_languages_by {
291 return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $self->all_languages } } ) } qw(id description article_code) };
297 return SL::DB::Manager::Part->get_all(where => [or => [ obsolete => 0, obsolete => undef ]]);
303 return { map { my $col = $_; ( $col => { map { ( trim($_->$col) => $_ ) } @{ $self->all_parts } } ) } qw(id partnumber ean description) };
306 sub init_part_counts_by {
311 $part_counts_by->{ean}-> {trim($_->ean)}++ for @{ $self->all_parts };
312 $part_counts_by->{description}->{trim($_->description)}++ for @{ $self->all_parts };
314 return $part_counts_by;
317 sub init_contacts_by {
320 my $all_contacts = SL::DB::Manager::Contact->get_all;
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 } };
331 sub init_ct_shiptos_by {
334 my $all_ct_shiptos = SL::DB::Manager::Shipto->get_all(query => [module => 'CT']);
337 # by trans_id _and_ shipto_id
338 $sby->{'trans_id+shipto_id'} = { map { ( $_->trans_id . '+' . $_->shipto_id => $_ ) } @{ $all_ct_shiptos } };
343 sub init_price_factors_by {
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) };
350 sub init_pricegroups_by {
353 my $all_pricegroups = SL::DB::Manager::Pricegroup->get_all;
354 return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_pricegroups } } ) } qw(id pricegroup) };
360 my $all_units = SL::DB::Manager::Unit->get_all;
361 return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_units } } ) } qw(name) };
364 sub init_warehouses_by {
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) };
374 my $all_bins = SL::DB::Manager::Bin->get_all();
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 } };
382 sub init_transfer_types_by {
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 }
391 return $transfer_types_by;
397 $self->controller->track_progress(phase => 'building data', progress => 0);
400 my $num_data = scalar @{ $self->controller->data };
403 foreach my $entry (@{ $self->controller->data }) {
404 $self->controller->track_progress(progress => $i/$num_data * 100) if $i % 100 == 0;
406 $entry->{info_data}->{datatype} = $entry->{raw_data}->{datatype};
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;
418 $order_entry = undef;
422 $self->handle_cvars($entry, sub_module => 'delivery_order_items');
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' });
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};
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};
450 $self->add_cvar_raw_data_columns();
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;
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;
468 $order_entry = $entry;
470 } elsif (defined $order_entry && $entry->{raw_data}->{datatype} eq $self->_item_column) {
471 if (scalar(@{ $entry->{errors} })) {
475 $item_entry = $entry;
477 } elsif (defined $item_entry && $entry->{raw_data}->{datatype} eq $self->_stock_column) {
478 my $object = $entry->{object};
480 $item_entry->{object}->parts_id,
481 $object->warehouse_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;
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) {
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');
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',
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);
522 my ($self, $entry) = @_;
524 my $object = $entry->{object};
526 $object->orderitems([]);
528 $self->handle_order_sources($entry);
529 my $first_source_order = $object->{source_orders}->[0];
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;
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;
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);
554 push @{ $entry->{errors} }, $::locale->text('Error: Customer/vendor missing');
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);
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
575 $object->$_($first_source_order->$_) unless $object->$_;
578 foreach (qw(currency_id delivery_term_id language_id payment_id taxzone_id)) {
579 $object->$_($vc_obj->$_) unless $object->$_;
581 $object->intnotes($vc_obj->notes) unless $object->intnotes;
584 $self->handle_salesman($entry);
585 $self->handle_employee($entry);
589 my ($self, $entry, $order_entry) = @_;
591 return unless $order_entry;
593 my $order_obj = $order_entry->{object};
594 my $object = $entry->{object};
595 $object->delivery_order_stock_entries([]);
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');
601 push @{ $order_entry->{errors} }, $::locale->text('Error: Faulty position in this delivery order');
606 $order_obj->add_items($object);
608 my $part_obj = SL::DB::Part->new(id => $object->parts_id)->load;
610 $self->handle_item_source($entry, $order_entry);
611 $object->position($object->{source_item}->position) if $object->{source_item};
613 $self->handle_unit($entry);
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;
620 $self->check_project($entry, global => 0);
621 $self->check_price_factor($entry);
622 $self->check_pricegroup($entry);
624 $self->handle_sellprice($entry, $order_entry);
625 $self->handle_discount($entry, $order_entry);
627 push @{ $order_entry->{errors} }, $::locale->text('Error: Faulty position in this delivery order') if scalar(@{$entry->{errors}}) > 0;
631 my ($self, $entry, $item_entry, $order_entry) = @_;
633 return unless $item_entry;
635 my $item_obj = $item_entry->{object};
636 return unless $item_obj->part;
638 my $order_obj = $order_entry->{object};
639 my $object = $entry->{object};
641 $item_obj->add_delivery_order_stock_entries($object);
643 $self->check_warehouse($entry);
644 $self->check_bin($entry);
646 $self->handle_unit($entry, $item_obj->part);
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,
654 # $object->chargenumber,
655 # $object->bestbefore);
656 # if ($stocked_qty < $object->qty) {
657 # push @{ $entry->{errors} }, $::locale->text('Error: Not enough parts in stock');
661 my ($stock_info_entry, $part) = @_;
663 # Todo: option: should stock?
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;
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,
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),
683 $inventory->bestbefore($object->bestbefore) if $::instance_conf->get_show_bestbefore;
684 $object->{inventory_obj} = $inventory;
685 $order_obj->delivered(1);
690 my ($self, $entry) = @_;
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
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
705 sub handle_order_sources {
706 my ($self, $entry) = @_;
708 my $record = $entry->{object};
710 $record->{source_orders} = [];
711 return $record->{source_orders} if !$record->ordnumber;
713 my @order_numbers = split ' ', $record->ordnumber;
715 my $orders = SL::DB::Manager::Order->get_all(where => [ordnumber => \@order_numbers]);
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');
723 foreach my $order (@$orders) {
724 $self->{remaining_source_qtys_by_item_id} = { map { $_->id => $_->qty } @{ $order->items } };
727 $record->{source_orders} = $orders;
730 sub handle_item_source {
731 my ($self, $entry, $record_entry) = @_;
733 my $item = $entry->{object};
734 my $record = $record_entry->{object};
736 return if !@{ $record->{source_orders} };
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;
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;
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;
774 my ($self, $entry, $part) = @_;
776 my $object = $entry->{object};
778 $part ||= $object->part;
780 # Set unit from part if not given.
781 if (!$object->unit) {
782 $object->unit($part->unit);
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');
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');
801 sub handle_sellprice {
802 my ($self, $entry, $record_entry) = @_;
804 my $item = $entry->{object};
805 my $record = $record_entry->{object};
807 return if !$record->customervendor;
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);
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);
824 $item->sellprice($sellprice);
825 $item->active_price_source($item->{source_item}->active_price_source);
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;
832 $item->sellprice($price->price);
833 $item->active_price_source($price->source);
836 $item->active_price_source($price_source->price_from_source('')->source);
842 sub handle_discount {
843 my ($self, $entry, $record_entry) = @_;
845 my $item = $entry->{object};
846 my $record = $record_entry->{object};
848 return if !$record->customervendor;
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);
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);
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;
868 $item->discount($discount->discount);
869 $item->active_discount_source($discount->source);
872 $item->active_discount_source($price_source->discount_from_source('')->source);
879 my ($self, $entry) = @_;
881 my $object = $entry->{object};
883 my $cp_cv_id = $object->customer_id || $object->vendor_id;
884 return 0 unless $cp_cv_id;
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');
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} };
896 push @{ $entry->{errors} }, $::locale->text('Error: Invalid contact');
900 $object->cp_id($cp->cp_id);
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;
911 my ($self, $entry) = @_;
913 my $object = $entry->{object};
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');
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} };
927 push @{ $entry->{errors} }, $::locale->text('Error: Invalid language');
931 $object->language_id($language->id);
934 if ($object->language_id) {
935 $entry->{info_data}->{language} = $self->languages_by->{id}->{ $object->language_id }->description;
941 sub check_ct_shipto {
942 my ($self, $entry) = @_;
944 my $object = $entry->{object};
946 my $trans_id = $object->customer_id || $object->vendor_id;
947 return 0 unless $trans_id;
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');
959 my ($self, $entry) = @_;
961 my $object = $entry->{object};
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');
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}) };
974 push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
978 $object->parts_id($part->id);
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}) };
985 push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
989 if ($self->part_counts_by->{description}->{ trim($entry->{raw_data}->{description}) } > 1) {
992 $object->parts_id($part->id);
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}) };
1000 push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
1004 if ($self->part_counts_by->{ean}->{ trim($entry->{raw_data}->{ean}) } > 1) {
1007 $object->parts_id($part->id);
1011 if ($object->parts_id) {
1012 $entry->{info_data}->{partnumber} = $self->parts_by->{id}->{ $object->parts_id }->partnumber;
1014 if ($is_ambiguous) {
1015 push @{ $entry->{errors} }, $::locale->text('Error: Part is ambiguous');
1017 push @{ $entry->{errors} }, $::locale->text('Error: Part not found');
1025 sub check_price_factor {
1026 my ($self, $entry) = @_;
1028 my $object = $entry->{object};
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');
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');
1044 $object->price_factor_id($price_factor->id);
1050 sub check_pricegroup {
1051 my ($self, $entry) = @_;
1053 my $object = $entry->{object};
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');
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} };
1065 push @{ $entry->{errors} }, $::locale->text('Error: Invalid price group');
1069 $object->pricegroup_id($pricegroup->id);
1075 sub check_warehouse {
1076 my ($self, $entry) = @_;
1078 my $object = $entry->{object};
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');
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} };
1090 push @{ $entry->{errors} }, $::locale->text('Error: Invalid warehouse');
1094 $object->warehouse_id($wh->id);
1097 if ($object->warehouse_id) {
1098 $entry->{info_data}->{warehouse} = $self->warehouses_by->{id}->{ $object->warehouse_id }->description;
1100 push @{ $entry->{errors} }, $::locale->text('Error: Warehouse not found');
1107 # Check bin for given warehouse, so check_warehouse must be called first.
1109 my ($self, $entry) = @_;
1111 my $object = $entry->{object};
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');
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}) };
1123 push @{ $entry->{errors} }, $::locale->text('Error: Invalid bin');
1127 $object->bin_id($bin->id);
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;
1133 push @{ $entry->{errors} }, $::locale->text('Error: Bin not found');
1140 sub save_additions {
1141 my ($self, $object) = @_;
1144 my $orders = delete $object->{source_orders};
1146 if (scalar(@$orders)) {
1148 $_->link_to_record($object) for @$orders;
1150 foreach my $item (@{ $object->items }) {
1151 my $orderitem = delete $item->{source_item};
1152 $orderitem->link_to_record($item) if $orderitem;
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 };
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);
1177 my ($self, %params) = @_;
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} };
1185 push @{ $entries_to_save }, $entry;
1188 $self->SUPER::save_objects(data => $entries_to_save);
1191 sub get_stocked_qty {
1192 my ($self, $parts_id, $wh_id, $bin_id, $chargenumber, $bestbefore) = @_;
1194 my $key = join '+', $parts_id, $wh_id, $bin_id, $chargenumber, $bestbefore;
1195 return $self->{stocked_qty}->{$key} if exists $self->{stocked_qty}->{$key};
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;
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
1210 my @values = ($parts_id,
1214 push @values, $bestbefore if $bestbefore_val_cnt;
1216 my $dbh = $self->controller->data->[0]{object}->db->dbh;
1217 my ($stocked_qty) = selectrow_query($::form, $dbh, $query, @values);
1219 $self->{stocked_qty}->{$key} = $stocked_qty;
1220 return $stocked_qty;
1223 sub _wh_id_and_description_ident {
1224 return 'wh_id+description';
1227 sub _wh_id_and_description_maker {
1228 return join '+', $_[0], $_[1]
1231 sub _wh_id_and_id_ident {
1235 sub _wh_id_and_id_maker {
1236 return join '+', $_[0], $_[1]
1239 sub _transfer_type_dir_and_description_ident {
1240 return 'dir+description';
1243 sub _transfer_type_dir_and_description_maker {
1244 return join '+', $_[0], $_[1]
1248 $_[0]->settings->{'order_column'}
1252 $_[0]->settings->{'item_column'}
1256 $_[0]->settings->{'stock_column'}