Artikel-Klassifizierung
[kivitendo-erp.git] / SL / Controller / CsvImport / Part.pm
1 package SL::Controller::CsvImport::Part;
2
3 use strict;
4
5 use SL::Helper::Csv;
6
7 use SL::DBUtils;
8 use SL::DB::Buchungsgruppe;
9 use SL::DB::CustomVariable;
10 use SL::DB::CustomVariableConfig;
11 use SL::DB::PartsGroup;
12 use SL::DB::PaymentTerm;
13 use SL::DB::PriceFactor;
14 use SL::DB::Pricegroup;
15 use SL::DB::Price;
16 use SL::DB::Translation;
17 use SL::DB::Unit;
18
19 use List::MoreUtils qw(none);
20
21 use parent qw(SL::Controller::CsvImport::Base);
22
23 use Rose::Object::MakeMethods::Generic
24 (
25  scalar                  => [ qw(table makemodel_columns) ],
26  'scalar --get_set_init' => [ qw(bg_by settings parts_by price_factors_by classification_by units_by partsgroups_by
27                                  warehouses_by bins_by
28                                  translation_columns all_pricegroups) ],
29 );
30
31 sub set_profile_defaults {
32   my ($self) = @_;
33
34   my $bugru = SL::DB::Manager::Buchungsgruppe->find_by(description => { like => 'Standard%19%' });
35
36   $self->controller->profile->_set_defaults(
37                        sellprice_places          => 2,
38                        sellprice_adjustment      => 0,
39                        sellprice_adjustment_type => 'percent',
40                        article_number_policy     => 'update_prices',
41                        shoparticle_if_missing    => '0',
42                        part_type                 => 'part',
43                        part_classification       => 0,
44                        default_buchungsgruppe    => ($bugru ? $bugru->id : undef),
45                        apply_buchungsgruppe      => 'all',
46                       );
47 };
48
49
50 sub init_class {
51   my ($self) = @_;
52   $self->class('SL::DB::Part');
53 }
54
55 sub init_bg_by {
56   my ($self) = @_;
57
58   my $all_bg = SL::DB::Manager::Buchungsgruppe->get_all;
59   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_bg } } ) } qw(id description) };
60 }
61
62 sub init_classification_by {
63   my ($self) = @_;
64   my $all_classifications = SL::DB::Manager::PartClassification->get_all;
65   $_->abbreviation($::locale->text($_->abbreviation)) for @{ $all_classifications };
66   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_classifications } } ) } qw(id abbreviation) };
67 }
68
69 sub init_price_factors_by {
70   my ($self) = @_;
71
72   my $all_price_factors = SL::DB::Manager::PriceFactor->get_all;
73   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_price_factors } } ) } qw(id description) };
74 }
75
76 sub init_partsgroups_by {
77   my ($self) = @_;
78
79   my $all_partsgroups = SL::DB::Manager::PartsGroup->get_all;
80   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_partsgroups } } ) } qw(id partsgroup) };
81 }
82
83 sub init_units_by {
84   my ($self) = @_;
85
86   my $all_units = SL::DB::Manager::Unit->get_all;
87   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_units } } ) } qw(name) };
88 }
89
90 sub init_bins_by {
91   my ($self) = @_;
92
93   my $all_bins = SL::DB::Manager::Bin->get_all;
94   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_bins } } ) } qw(id description) };
95 }
96
97 sub init_warehouses_by {
98   my ($self) = @_;
99
100   my $all_warehouses = SL::DB::Manager::Warehouse->get_all;
101   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_warehouses } } ) } qw(id description) };
102 }
103
104
105 sub init_parts_by {
106   my ($self) = @_;
107
108 #  my $parts_by = { id         => { map { ( $_->id => $_ ) } grep { !$_->part_type = 'assembly' } @{ $self->existing_objects } },
109 #                   partnumber => { part    => { },
110 #                                   service => { } } };
111 #
112 #  foreach my $part (@{ $self->existing_objects }) {
113 #    next if $part->part_type eq 'assembly';
114 #    $parts_by->{partnumber}->{ $part->type }->{ $part->partnumber } = $part;
115 #  }
116
117   my $parts_by = {};
118   my $sth = prepare_execute_query($::form, SL::DB::Object->new->db->dbh, 'SELECT partnumber FROM parts');
119   while (my ($partnumber) = $sth->fetchrow_array()) {
120     $parts_by->{partnumber}{$partnumber} = 1;
121   }
122
123   return $parts_by;
124 }
125
126 sub init_all_pricegroups {
127   my ($self) = @_;
128
129   return SL::DB::Manager::Pricegroup->get_all_sorted;
130 }
131
132 sub init_settings {
133   my ($self) = @_;
134
135   return { map { ( $_ => $self->controller->profile->get($_) ) } qw(apply_buchungsgruppe default_buchungsgruppe article_number_policy
136                                                                     sellprice_places sellprice_adjustment sellprice_adjustment_type
137                                                                     shoparticle_if_missing part_type classification_id default_unit) };
138 }
139
140 sub init_all_cvar_configs {
141   my ($self) = @_;
142
143   return SL::DB::Manager::CustomVariableConfig->get_all(where => [ module => 'IC' ]);
144 }
145
146 sub init_translation_columns {
147   my ($self) = @_;
148
149   return [ map { ("description_" . $_->article_code, "notes_" . $_->article_code) } (@{ $self->all_languages }) ];
150 }
151
152 sub check_objects {
153   my ($self) = @_;
154
155   return unless @{ $self->controller->data };
156
157   $self->controller->track_progress(phase => 'building data', progress => 0);
158
159   $self->makemodel_columns({});
160
161   my $i = 0;
162   my $num_data = scalar @{ $self->controller->data };
163   foreach my $entry (@{ $self->controller->data }) {
164     $self->controller->track_progress(progress => $i/$num_data * 100) if $i % 100 == 0;
165
166     $self->check_buchungsgruppe($entry);
167     $self->check_part_type($entry);
168     $self->check_unit($entry);
169     $self->check_price_factor($entry);
170     $self->check_payment($entry);
171     $self->check_partsgroup($entry);
172     $self->check_warehouse_and_bin($entry);
173     $self->handle_pricegroups($entry);
174     $self->check_existing($entry) unless @{ $entry->{errors} };
175     $self->handle_prices($entry) if $self->settings->{sellprice_adjustment};
176     $self->handle_shoparticle($entry);
177     $self->handle_translations($entry);
178     $self->handle_cvars($entry);
179     $self->handle_makemodel($entry);
180     $self->set_various_fields($entry);
181   } continue {
182     $i++;
183   }
184
185   $self->add_columns(qw(part_type classification_id)) if $self->settings->{part_type} eq 'mixed';
186   $self->add_columns(qw(buchungsgruppen_id unit));
187   $self->add_columns(map { "${_}_id" } grep { exists $self->controller->data->[0]->{raw_data}->{$_} } qw (price_factor payment partsgroup warehouse bin));
188   $self->add_columns(qw(shop)) if $self->settings->{shoparticle_if_missing};
189   $self->add_cvar_raw_data_columns;
190   map { $self->add_raw_data_columns("pricegroup_${_}") if exists $self->controller->data->[0]->{raw_data}->{"pricegroup_$_"} } (1..scalar(@{ $self->all_pricegroups }));
191   map { $self->add_raw_data_columns($_) if exists $self->controller->data->[0]->{raw_data}->{$_} } @{ $self->translation_columns };
192   map { $self->add_raw_data_columns("make_${_}", "model_${_}", "lastcost_${_}") } sort { $a <=> $b } keys %{ $self->makemodel_columns };
193 }
194
195 sub get_duplicate_check_fields {
196   return {
197     partnumber => {
198       label     => $::locale->text('Part Number'),
199       default   => 0
200     },
201
202     description => {
203       label     => $::locale->text('Description'),
204       default   => 1,
205       maker     => sub {
206         my $desc = shift->description;
207         $desc =~ s/[\s,\.\-]//g;
208         return $desc;
209       }
210     },
211   };
212 }
213
214 sub check_buchungsgruppe {
215   my ($self, $entry) = @_;
216
217   my $object = $entry->{object};
218
219   # Check Buchungsgruppe
220
221   # Store and verify default ID.
222   my $default_id = $self->settings->{default_buchungsgruppe};
223   $default_id    = undef unless $self->bg_by->{id}->{ $default_id };
224
225   # 1. Use default ID if enforced.
226   if ($default_id && ($self->settings->{apply_buchungsgruppe} eq 'all')) {
227     $object->buchungsgruppen_id($default_id);
228     push @{ $entry->{information} }, $::locale->text('Use default booking group because setting is \'all\'');
229   }
230
231   # 2. Use supplied ID if valid
232   $object->buchungsgruppen_id(undef) if $object->buchungsgruppen_id && !$self->bg_by->{id}->{ $object->buchungsgruppen_id };
233
234   # 3. Look up name if supplied.
235   if (!$object->buchungsgruppen_id && $entry->{raw_data}->{buchungsgruppe}) {
236     my $bg = $self->bg_by->{description}->{ $entry->{raw_data}->{buchungsgruppe} };
237     $object->buchungsgruppen_id($bg->id) if $bg;
238   }
239
240   # 4. Use default ID if not valid.
241   if (!$object->buchungsgruppen_id && $default_id && ($self->settings->{apply_buchungsgruppe} eq 'missing')) {
242     $object->buchungsgruppen_id($default_id) ;
243     $entry->{buch_information} = $::locale->text('Use default booking group because wanted is missing');
244   }
245   return 1 if $object->buchungsgruppen_id;
246   $entry->{buch_error} =  $::locale->text('Error: booking group missing or invalid');
247   return 0;
248 }
249
250 sub _part_is_used {
251   my ($self, $part) = @_;
252
253   my $query =
254       qq|SELECT COUNT(parts_id) FROM invoice where parts_id = ?
255          UNION
256          SELECT COUNT(parts_id) FROM assembly where parts_id = ?
257          UNION
258          SELECT COUNT(parts_id) FROM orderitems where parts_id = ?
259         |;
260   foreach my $ref (selectall_hashref_query($::form, $part->db->dbh, $query, $part->id, $part->id, $part->id)) {
261     return 1 if $ref->{count} != 0;
262   }
263   return 0;
264 }
265
266 sub check_existing {
267   my ($self, $entry) = @_;
268
269   my $object = $entry->{object};
270   my $raw = $entry->{raw_data};
271
272   if ($object->partnumber && $self->parts_by->{partnumber}{$object->partnumber}) {
273     $entry->{part} = SL::DB::Manager::Part->get_first( query => [ partnumber => $object->partnumber ], limit => 1,
274       with_objects => [ 'translations', 'custom_variables' ], multi_many_ok => 1
275     );
276     if ( !$entry->{part} ) {
277         $entry->{part} = SL::DB::Manager::Part->get_first( query => [ partnumber => $object->partnumber ], limit => 1,
278           with_objects => [ 'translations' ], multi_many_ok => 1
279         );
280     }
281   }
282
283   if ($entry->{part}) {
284     if ($entry->{part}->part_type ne $object->part_type ) {
285       push(@{$entry->{errors}}, $::locale->text('Skipping due to existing entry in database with different type'));
286       return;
287     }
288     if ( $entry->{part}->unit ne $object->unit ) {
289       if ( $entry->{part}->onhand != 0 || $self->_part_is_used($entry->{part})) {
290         push(@{$entry->{errors}}, $::locale->text('Skipping due to existing entry with different unit'));
291         return;
292       }
293     }
294   }
295
296   if ($self->settings->{article_number_policy} eq 'update_prices_sn' || $self->settings->{article_number_policy} eq 'update_parts_sn') {
297     if (!$entry->{part}) {
298       push(@{$entry->{errors}}, $::locale->text('Skipping non-existent article'));
299       return;
300     }
301   }
302
303   ## checking also doubles in csv !!
304   foreach my $csventry (@{ $self->controller->data }) {
305     if ( $entry != $csventry && $object->partnumber eq $csventry->{object}->partnumber ) {
306       if ( $csventry->{doublechecked} ) {
307         push(@{$entry->{errors}}, $::locale->text('Skipping due to same partnumber in csv file'));
308         return;
309       }
310     }
311   }
312   $entry->{doublechecked} = 1;
313
314   if ($entry->{part}) {
315     if ($self->settings->{article_number_policy} eq 'update_prices' || $self->settings->{article_number_policy} eq 'update_prices_sn') {
316       map { $entry->{part}->$_( $object->$_ ) if defined $object->$_ } qw(sellprice listprice lastcost);
317
318       # merge prices
319       my %prices_by_pricegroup_id = map { $_->pricegroup->id => $_ } $entry->{part}->prices, $object->prices;
320       $entry->{part}->prices(grep { $_ } map { $prices_by_pricegroup_id{$_->id} } @{ $self->all_pricegroups });
321
322       push @{ $entry->{information} }, $::locale->text('Updating prices of existing entry in database');
323       $entry->{object_to_save} = $entry->{part};
324     } elsif ( $self->settings->{article_number_policy} eq 'update_parts' || $self->settings->{article_number_policy} eq 'update_parts_sn') {
325
326       # Update parts table
327       # copy only the data which is not explicit copied by  "methods"
328
329       map { $entry->{part}->$_( $object->$_ ) if defined $object->$_ }  qw(description notes weight ean rop image
330                                                                            drawing ve gv
331                                                                            unit
332                                                                            has_sernumber not_discountable obsolete
333                                                                            payment_id
334                                                                            sellprice listprice lastcost);
335
336       if (defined $raw->{"sellprice"} || defined $raw->{"listprice"} || defined $raw->{"lastcost"}) {
337         # merge prices
338         my %prices_by_pricegroup_id = map { $_->pricegroup->id => $_ } $entry->{part}->prices, $object->prices;
339         $entry->{part}->prices(grep { $_ } map { $prices_by_pricegroup_id{$_->id} } @{ $self->all_pricegroups });
340       }
341
342       # Update translation
343       my @translations;
344       push @translations, $entry->{part}->translations;
345       foreach my $language (@{ $self->all_languages }) {
346         my $desc;
347         $desc = $raw->{"description_". $language->article_code}  if defined $raw->{"description_". $language->article_code};
348         my $notes;
349         $notes = $raw->{"notes_". $language->article_code}  if defined $raw->{"notes_". $language->article_code};
350         next unless $desc || $notes;
351
352         push @translations, SL::DB::Translation->new(language_id     => $language->id,
353                                                      translation     => $desc,
354                                                      longdescription => $notes);
355       }
356       $entry->{part}->translations(\@translations) if @translations;
357
358       # Update cvars
359       my %type_to_column = ( text      => 'text_value',
360                              textfield => 'text_value',
361                              select    => 'text_value',
362                              date      => 'timestamp_value_as_date',
363                              timestamp => 'timestamp_value_as_date',
364                              number    => 'number_value_as_number',
365                              bool      => 'bool_value' );
366       my @cvars;
367       push @cvars, $entry->{part}->custom_variables;
368       foreach my $config (@{ $self->all_cvar_configs }) {
369         next unless exists $raw->{ "cvar_" . $config->name };
370         my $value  = $raw->{ "cvar_" . $config->name };
371         my $column = $type_to_column{ $config->type } || die "Program logic error: unknown custom variable storage type";
372         push @cvars, SL::DB::CustomVariable->new(config_id => $config->id, $column => $value, sub_module => '');
373       }
374       $entry->{part}->custom_variables(\@cvars) if @cvars;
375
376       # save Part Update
377       push @{ $entry->{information} }, $::locale->text('Updating data of existing entry in database');
378
379       $entry->{object_to_save} = $entry->{part};
380       # copy all other data via "methods"
381       my $methods        = $self->controller->headers->{methods};
382       $entry->{object_to_save}->$_( $entry->{object}->$_ ) for @{ $methods }, keys %{ $self->clone_methods };
383
384     } elsif ( $self->settings->{article_number_policy} eq 'skip' ) {
385       push(@{$entry->{errors}}, $::locale->text('Skipping due to existing entry in database')) if ( $entry->{part} );
386     } else {
387       #$object->partnumber('####');
388     }
389   } else {
390     # set error or info from buch if part not exists
391     push @{ $entry->{information} }, $entry->{buch_information} if $entry->{buch_information};
392     push @{ $entry->{errors} }, $entry->{buch_error} if $entry->{buch_error};
393   }
394 }
395
396 sub handle_prices {
397   my ($self, $entry) = @_;
398
399   foreach my $column (qw(sellprice)) {
400     my $object     = $entry->{object_to_save} || $entry->{object};
401     my $adjustment = $self->settings->{sellprice_adjustment};
402     my $value      = $object->$column;
403
404     $value = $self->settings->{sellprice_adjustment_type} eq 'percent' ? $value * (100 + $adjustment) / 100 : $value + $adjustment;
405     $object->$column($::form->round_amount($value, $self->settings->{sellprice_places}));
406   }
407 }
408
409 sub handle_shoparticle {
410   my ($self, $entry) = @_;
411
412   $entry->{object}->shop(1) if $self->settings->{shoparticle_if_missing} && !$self->controller->headers->{used}->{shop};
413 }
414
415 sub check_part_type {
416   my ($self, $entry) = @_;
417
418   # TODO: assemblies or assortments can't be imported
419
420   # my $bg = $self->bg_by->{id}->{ $entry->{object}->buchungsgruppen_id };
421   # $bg  ||= SL::DB::Buchungsgruppe->new(inventory_accno_id => 1); # does this case ever occur?
422
423   my $part_type = $self->settings->{part_type};
424   if ($part_type eq 'mixed' && $entry->{raw_data}->{part_type}) {
425     $part_type = $entry->{raw_data}->{part_type} =~ m/^p/i     ? 'part'
426                : $entry->{raw_data}->{part_type} =~ m/^s/i     ? 'service'
427                : $entry->{raw_data}->{part_type} =~ m/^assem/i ? 'assembly'
428                : $entry->{raw_data}->{part_type} =~ m/^assor/i ? 'assortment'
429                :                                                 $self->settings->{part_type};
430   }
431   my $classification_id = $self->settings->{classification_id};
432
433   if ( $entry->{raw_data}->{pclass} && length($entry->{raw_data}->{pclass}) >= 2 ) {
434     my $abbr1 = substr($entry->{raw_data}->{pclass},0,1);
435     my $abbr2 = substr($entry->{raw_data}->{pclass},1);
436
437     if ( $self->classification_by->{abbreviation}->{$abbr2} ) {
438       my $tmp_classification_id = $self->classification_by->{abbreviation}->{$abbr2}->id;
439       $classification_id = $tmp_classification_id if $tmp_classification_id;
440     }
441     if ($part_type eq 'mixed') {
442       $part_type = $abbr1 eq $::locale->text('Part (typeabbreviation)') ? 'part'
443         : $abbr1 eq $::locale->text('Service (typeabbreviation)')       ? 'service'
444         : $abbr1 eq $::locale->text('Assembly (typeabbreviation)')      ? 'assembly'
445         : $abbr1 eq $::locale->text('Assortment (typeabbreviation)')    ? 'assortment'
446         :                                                                 undef;
447     }
448   }
449
450   # when saving income_accno_id or expense_accno_id use ids from the selected
451   # $bg according to the default tax_zone (the one with the highest sort
452   # order).  Alternatively one could use the ids from defaults, but they might
453   # not all be set.
454   # Only use existing bg
455
456   # $entry->{object}->income_accno_id( $bg->income_accno_id( SL::DB::Manager::TaxZone->get_default->id ) );
457
458   # if ($part_type eq 'part' || $part_type eq 'service') {
459   #   $entry->{object}->expense_accno_id( $bg->expense_accno_id( SL::DB::Manager::TaxZone->get_default->id ) );
460   # }
461
462   # if ($part_type eq 'part') {
463   #   $entry->{object}->inventory_accno_id( $bg->inventory_accno_id );
464   # }
465
466   if (none { $_ eq $part_type } qw(part service assembly assortment)) {
467     push @{ $entry->{errors} }, $::locale->text('Error: Invalid part type');
468     return 0;
469   }
470
471   $entry->{object}->part_type($part_type);
472   $entry->{object}->classification_id( $classification_id );
473
474   return 1;
475 }
476
477 sub check_price_factor {
478   my ($self, $entry) = @_;
479
480   my $object = $entry->{object};
481
482   # Check whether or not price factor ID is valid.
483   if ($object->price_factor_id && !$self->price_factors_by->{id}->{ $object->price_factor_id }) {
484     push @{ $entry->{errors} }, $::locale->text('Error: Invalid price factor');
485     return 0;
486   }
487
488   # Map name to ID if given.
489   if (!$object->price_factor_id && $entry->{raw_data}->{price_factor}) {
490     my $pf = $self->price_factors_by->{description}->{ $entry->{raw_data}->{price_factor} };
491
492     if (!$pf) {
493       push @{ $entry->{errors} }, $::locale->text('Error: Invalid price factor');
494       return 0;
495     }
496
497     $object->price_factor_id($pf->id);
498     $self->clone_methods->{price_factor_id} = 1;
499   }
500
501   return 1;
502 }
503
504 sub check_warehouse_and_bin {
505   my ($self, $entry) = @_;
506
507   my $object = $entry->{object};
508
509   # Check whether or not warehouse id is valid.
510   if ($object->warehouse_id && !$self->warehouses_by->{id}->{ $object->warehouse_id }) {
511     push @{ $entry->{errors} }, $::locale->text('Error: Invalid warehouse id');
512     return 0;
513   }
514   # Map name to ID if given.
515   if (!$object->warehouse_id && $entry->{raw_data}->{warehouse}) {
516     my $wh = $self->warehouses_by->{description}->{ $entry->{raw_data}->{warehouse} };
517
518     if (!$wh) {
519       push @{ $entry->{errors} }, $::locale->text('Error: Invalid warehouse name #1',$entry->{raw_data}->{warehouse});
520       return 0;
521     }
522
523     $object->warehouse_id($wh->id);
524   }
525   $self->clone_methods->{warehouse_id} = 1;
526
527   # Check whether or not bin id is valid.
528   if ($object->bin_id && !$self->bins_by->{id}->{ $object->bin_id }) {
529     push @{ $entry->{errors} }, $::locale->text('Error: Invalid bin id');
530     return 0;
531   }
532   # Map name to ID if given.
533   if ($object->warehouse_id && !$object->bin_id && $entry->{raw_data}->{bin}) {
534     my $bin = $self->bins_by->{description}->{ $entry->{raw_data}->{bin} };
535
536     if (!$bin) {
537       push @{ $entry->{errors} }, $::locale->text('Error: Invalid bin name #1',$entry->{raw_data}->{bin});
538       return 0;
539     }
540
541     $object->bin_id($bin->id);
542   }
543   $self->clone_methods->{bin_id} = 1;
544
545   if ($object->warehouse_id && $object->bin_id ) {
546     my $bin = $self->bins_by->{id}->{ $object->bin_id };
547     if ( $bin->warehouse_id != $object->warehouse_id ) {
548       push @{ $entry->{errors} }, $::locale->text('Error: Bin #1 is not from warehouse #2',
549                                                   $self->bins_by->{id}->{$object->bin_id}->description,
550                                                   $self->warehouses_by->{id}->{ $object->warehouse_id }->description);
551       return 0;
552     }
553   }
554   return 1;
555 }
556
557 sub check_partsgroup {
558   my ($self, $entry) = @_;
559
560   my $object = $entry->{object};
561
562   # Check whether or not part group ID is valid.
563   if ($object->partsgroup_id && !$self->partsgroups_by->{id}->{ $object->partsgroup_id }) {
564     push @{ $entry->{errors} }, $::locale->text('Error: Invalid parts group');
565     return 0;
566   }
567
568   # Map name to ID if given.
569   if (!$object->partsgroup_id && $entry->{raw_data}->{partsgroup}) {
570     my $pg = $self->partsgroups_by->{partsgroup}->{ $entry->{raw_data}->{partsgroup} };
571
572     if (!$pg) {
573       push @{ $entry->{errors} }, $::locale->text('Error: Invalid parts group');
574       return 0;
575     }
576
577     $object->partsgroup_id($pg->id);
578   }
579   # register payment_id for method copying later
580   $self->clone_methods->{partsgroup_id} = 1;
581
582   return 1;
583 }
584
585 sub check_unit {
586   my ($self, $entry) = @_;
587
588   my $object = $entry->{object};
589
590   $object->unit($self->settings->{default_unit}) unless $object->unit;
591
592   # Check whether or unit is valid.
593   if (!$self->units_by->{name}->{ $object->unit }) {
594     push @{ $entry->{errors} }, $::locale->text('Error: Unit missing or invalid');
595     return 0;
596   }
597
598   return 1;
599 }
600
601 sub handle_translations {
602   my ($self, $entry) = @_;
603
604   my @translations;
605   foreach my $language (@{ $self->all_languages }) {
606     my ($desc, $notes) = @{ $entry->{raw_data} }{ "description_" . $language->article_code, "notes_" . $language->article_code };
607     next unless $desc || $notes;
608
609     push @translations, SL::DB::Translation->new(language_id     => $language->id,
610                                                  translation     => $desc,
611                                                  longdescription => $notes);
612   }
613
614   $entry->{object}->translations(\@translations);
615 }
616
617 sub handle_pricegroups {
618   my ($self, $entry) = @_;
619
620   my @prices;
621   my $idx = 0;
622   foreach my $pricegroup (@{ $self->all_pricegroups }) {
623     $idx++;
624     my $sellprice = $entry->{raw_data}->{"pricegroup_${idx}"};
625     next if $sellprice eq '';
626
627     push @prices, SL::DB::Price->new(pricegroup_id => $pricegroup->id,
628                                      price         => $::form->parse_amount(\%::myconfig, $sellprice));
629   }
630
631   $entry->{object}->prices(\@prices);
632 }
633
634 sub handle_makemodel {
635   my ($self, $entry) = @_;
636   my $object = $entry->{object};
637   my $found_any;
638
639   my @makemodels;
640   foreach my $idx (sort map { substr $_, 5 } grep { m/^make_\d+$/ && $entry->{raw_data}->{$_} } keys %{ $entry->{raw_data} }) {
641     my $vendor = $entry->{raw_data}->{"make_${idx}"};
642     $vendor    = $self->vc_by->{id}->               { $vendor }
643               || $self->vc_by->{number}->{vendors}->{ $vendor }
644               || $self->vc_by->{name}->  {vendors}->{ $vendor };
645
646     if (ref($vendor) ne 'SL::DB::Vendor') {
647       push @{ $entry->{errors} }, $::locale->text('Error: Invalid vendor in column make_#1', $idx);
648
649     } else {
650       $found_any = 1;
651       push @makemodels, SL::DB::MakeModel->new(make               => $vendor->id,
652                                                model              => $entry->{raw_data}->{"model_${idx}"},
653                                                lastcost_as_number => $entry->{raw_data}->{"lastcost_${idx}"});
654
655       $self->makemodel_columns->{$idx}    = 1;
656       $entry->{raw_data}->{"make_${idx}"} = $vendor->name;
657     }
658   }
659
660   $object->makemodels(\@makemodels);
661   $object->makemodel(scalar(@makemodels) ? 1 : 0);
662
663   if ( !$entry->{part} || $self->settings->{article_number_policy} ne 'update_prices' ) {
664     return;
665   }
666
667   my %old_makemodels_by_mm = map { $_->make . $; . $_->model => $_ } $entry->{part}->makemodels;
668   my @new_makemodels;
669
670   foreach my $makemodel ($object->makemodels()) {
671     my $makemodel_orig = $old_makemodels_by_mm{$makemodel->make,$makemodel->model};
672     $found_any = 1;
673
674     if ($makemodel_orig) {
675       $makemodel_orig->model($makemodel->model);
676       $makemodel_orig->lastcost($makemodel->lastcost);
677
678     } else {
679       push @new_makemodels, $makemodel;
680     }
681   }
682
683   $entry->{part}->makemodels([ $entry->{part}->makemodels, @new_makemodels ]) if @new_makemodels;
684
685   # reindex makemodels
686   my $i = 0;
687   $_->sortorder(++$i) for @{ $entry->{part}->makemodels };
688
689   $self->save_with_cascade(1) if $found_any;
690 }
691
692 sub set_various_fields {
693   my ($self, $entry) = @_;
694
695   $entry->{object}->priceupdate(DateTime->now_local);
696 }
697
698 sub init_profile {
699   my ($self) = @_;
700
701   my $profile = $self->SUPER::init_profile;
702   delete @{$profile}{qw(bom makemodel priceupdate stockable type)};
703
704   $profile->{"pricegroup_$_"} = '' for 1 .. scalar @{ $_[0]->all_pricegroups };
705
706   return $profile;
707 }
708
709 sub save_objects {
710   my ($self, %params) = @_;
711
712   my $with_number    = [ grep { $_->{object}->partnumber ne '####' } @{ $self->controller->data } ];
713   my $without_number = [ grep { $_->{object}->partnumber eq '####' } @{ $self->controller->data } ];
714
715   map { $_->{object}->partnumber('') } @{ $without_number };
716
717   $self->SUPER::save_objects(data => $with_number);
718   $self->SUPER::save_objects(data => $without_number);
719 }
720
721 sub setup_displayable_columns {
722   my ($self) = @_;
723
724   $self->SUPER::setup_displayable_columns;
725   $self->add_cvar_columns_to_displayable_columns;
726
727   $self->add_displayable_columns({ name => 'bin_id',             description => $::locale->text('Bin (database ID)')                                    },
728                                  { name => 'bin',                description => $::locale->text('Bin (name)')                                           },
729                                  { name => 'buchungsgruppen_id', description => $::locale->text('Booking group (database ID)')                          },
730                                  { name => 'buchungsgruppe',     description => $::locale->text('Booking group (name)')                                 },
731                                  { name => 'description',        description => $::locale->text('Description')                                          },
732                                  { name => 'drawing',            description => $::locale->text('Drawing')                                              },
733                                  { name => 'ean',                description => $::locale->text('EAN')                                                  },
734                                  { name => 'formel',             description => $::locale->text('Formula')                                              },
735                                  { name => 'gv',                 description => $::locale->text('Business Volume')                                      },
736                                  { name => 'has_sernumber',      description => $::locale->text('Has serial number')                                    },
737                                  { name => 'image',              description => $::locale->text('Image')                                                },
738                                  { name => 'lastcost',           description => $::locale->text('Last Cost')                                            },
739                                  { name => 'listprice',          description => $::locale->text('List Price')                                           },
740                                  { name => 'make_X',             description => $::locale->text('Make (vendor\'s database ID, number or name; with X being a number)') . ' [1]' },
741                                  { name => 'microfiche',         description => $::locale->text('Microfiche')                                           },
742                                  { name => 'model_X',            description => $::locale->text('Model (with X being a number)') . ' [1]'               },
743                                  { name => 'lastcost_X',         description => $::locale->text('Lastcost (with X being a number)') . ' [1]'            },
744                                  { name => 'not_discountable',   description => $::locale->text('Not Discountable')                                     },
745                                  { name => 'notes',              description => $::locale->text('Notes')                                                },
746                                  { name => 'obsolete',           description => $::locale->text('Obsolete')                                             },
747                                  { name => 'onhand',             description => $::locale->text('On Hand') . ' [2]'                                     },
748                                  { name => 'partnumber',         description => $::locale->text('Part Number')                                          },
749                                  { name => 'partsgroup_id',      description => $::locale->text('Partsgroup (database ID)')                             },
750                                  { name => 'partsgroup',         description => $::locale->text('Partsgroup (name)')                                    },
751                                  { name => 'part_classification',description => $::locale->text('Article classification')  . ' [3]'                     },
752                                  { name => 'payment_id',         description => $::locale->text('Payment terms (database ID)')                          },
753                                  { name => 'payment',            description => $::locale->text('Payment terms (name)')                                 },
754                                  { name => 'price_factor_id',    description => $::locale->text('Price factor (database ID)')                           },
755                                  { name => 'price_factor',       description => $::locale->text('Price factor (name)')                                  },
756                                  { name => 'rop',                description => $::locale->text('ROP')                                                  },
757                                  { name => 'sellprice',          description => $::locale->text('Sellprice')                                            },
758                                  { name => 'shop',               description => $::locale->text('Shop article')                                         },
759                                  { name => 'type',               description => $::locale->text('Article type')  . ' [3]'                               },
760                                  { name => 'unit',               description => $::locale->text('Unit (if missing or empty default unit will be used)') },
761                                  { name => 've',                 description => $::locale->text('Verrechnungseinheit')                                  },
762                                  { name => 'warehouse_id',       description => $::locale->text('Warehouse (database ID)')                              },
763                                  { name => 'warehouse',          description => $::locale->text('Warehouse (name)')                                     },
764                                  { name => 'weight',             description => $::locale->text('Weight')                                               },
765                                 );
766
767   foreach my $language (@{ $self->all_languages }) {
768     $self->add_displayable_columns({ name        => 'description_' . $language->article_code,
769                                      description => $::locale->text('Description (translation for #1)', $language->description) },
770                                    { name        => 'notes_' . $language->article_code,
771                                      description => $::locale->text('Notes (translation for #1)', $language->description) });
772   }
773
774   my $idx = 0;
775   foreach my $pricegroup (@{ $self->all_pricegroups }) {
776     $idx++;
777     $self->add_displayable_columns({ name        => 'pricegroup_' . $idx,
778                                      description => $::locale->text("Sellprice for price group '#1'", $pricegroup->pricegroup) });
779   }
780 }
781
782 1;