CsvImport: Parts: CVars von handle_cvars behandeln lassen.
[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) unless $entry->{dont_handle_cvars};
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       $entry->{dont_handle_cvars} = 1;
325     } elsif ( $self->settings->{article_number_policy} eq 'update_parts' || $self->settings->{article_number_policy} eq 'update_parts_sn') {
326
327       # Update parts table
328       # copy only the data which is not explicit copied by  "methods"
329
330       map { $entry->{part}->$_( $object->$_ ) if defined $object->$_ }  qw(description notes weight ean rop image
331                                                                            drawing ve gv
332                                                                            unit
333                                                                            has_sernumber not_discountable obsolete
334                                                                            payment_id
335                                                                            sellprice listprice lastcost);
336
337       if (defined $raw->{"sellprice"} || defined $raw->{"listprice"} || defined $raw->{"lastcost"}) {
338         # merge prices
339         my %prices_by_pricegroup_id = map { $_->pricegroup->id => $_ } $entry->{part}->prices, $object->prices;
340         $entry->{part}->prices(grep { $_ } map { $prices_by_pricegroup_id{$_->id} } @{ $self->all_pricegroups });
341       }
342
343       # Update translation
344       my @translations;
345       push @translations, $entry->{part}->translations;
346       foreach my $language (@{ $self->all_languages }) {
347         my $desc;
348         $desc = $raw->{"description_". $language->article_code}  if defined $raw->{"description_". $language->article_code};
349         my $notes;
350         $notes = $raw->{"notes_". $language->article_code}  if defined $raw->{"notes_". $language->article_code};
351         next unless $desc || $notes;
352
353         push @translations, SL::DB::Translation->new(language_id     => $language->id,
354                                                      translation     => $desc,
355                                                      longdescription => $notes);
356       }
357       $entry->{part}->translations(\@translations) if @translations;
358
359       # save Part Update
360       push @{ $entry->{information} }, $::locale->text('Updating data of existing entry in database');
361
362       $entry->{object_to_save} = $entry->{part};
363       # copy all other data via "methods"
364       my $methods        = $self->controller->headers->{methods};
365       $entry->{object_to_save}->$_( $entry->{object}->$_ ) for @{ $methods }, keys %{ $self->clone_methods };
366
367     } elsif ( $self->settings->{article_number_policy} eq 'skip' ) {
368       push(@{$entry->{errors}}, $::locale->text('Skipping due to existing entry in database')) if ( $entry->{part} );
369     } else {
370       #$object->partnumber('####');
371     }
372   } else {
373     # set error or info from buch if part not exists
374     push @{ $entry->{information} }, $entry->{buch_information} if $entry->{buch_information};
375     push @{ $entry->{errors} }, $entry->{buch_error} if $entry->{buch_error};
376   }
377 }
378
379 sub handle_prices {
380   my ($self, $entry) = @_;
381
382   foreach my $column (qw(sellprice)) {
383     my $object     = $entry->{object_to_save} || $entry->{object};
384     my $adjustment = $self->settings->{sellprice_adjustment};
385     my $value      = $object->$column;
386
387     $value = $self->settings->{sellprice_adjustment_type} eq 'percent' ? $value * (100 + $adjustment) / 100 : $value + $adjustment;
388     $object->$column($::form->round_amount($value, $self->settings->{sellprice_places}));
389   }
390 }
391
392 sub handle_shoparticle {
393   my ($self, $entry) = @_;
394
395   $entry->{object}->shop(1) if $self->settings->{shoparticle_if_missing} && !$self->controller->headers->{used}->{shop};
396 }
397
398 sub check_part_type {
399   my ($self, $entry) = @_;
400
401   # TODO: assemblies or assortments can't be imported
402
403   # my $bg = $self->bg_by->{id}->{ $entry->{object}->buchungsgruppen_id };
404   # $bg  ||= SL::DB::Buchungsgruppe->new(inventory_accno_id => 1); # does this case ever occur?
405
406   my $part_type = $self->settings->{part_type};
407   if ($part_type eq 'mixed' && $entry->{raw_data}->{part_type}) {
408     $part_type = $entry->{raw_data}->{part_type} =~ m/^p/i     ? 'part'
409                : $entry->{raw_data}->{part_type} =~ m/^s/i     ? 'service'
410                : $entry->{raw_data}->{part_type} =~ m/^assem/i ? 'assembly'
411                : $entry->{raw_data}->{part_type} =~ m/^assor/i ? 'assortment'
412                :                                                 $self->settings->{part_type};
413   }
414   my $classification_id = $self->settings->{classification_id};
415
416   if ( $entry->{raw_data}->{pclass} && length($entry->{raw_data}->{pclass}) >= 2 ) {
417     my $abbr1 = substr($entry->{raw_data}->{pclass},0,1);
418     my $abbr2 = substr($entry->{raw_data}->{pclass},1);
419
420     if ( $self->classification_by->{abbreviation}->{$abbr2} ) {
421       my $tmp_classification_id = $self->classification_by->{abbreviation}->{$abbr2}->id;
422       $classification_id = $tmp_classification_id if $tmp_classification_id;
423     }
424     if ($part_type eq 'mixed') {
425       $part_type = $abbr1 eq $::locale->text('Part (typeabbreviation)') ? 'part'
426         : $abbr1 eq $::locale->text('Service (typeabbreviation)')       ? 'service'
427         : $abbr1 eq $::locale->text('Assembly (typeabbreviation)')      ? 'assembly'
428         : $abbr1 eq $::locale->text('Assortment (typeabbreviation)')    ? 'assortment'
429         :                                                                 undef;
430     }
431   }
432
433   # when saving income_accno_id or expense_accno_id use ids from the selected
434   # $bg according to the default tax_zone (the one with the highest sort
435   # order).  Alternatively one could use the ids from defaults, but they might
436   # not all be set.
437   # Only use existing bg
438
439   # $entry->{object}->income_accno_id( $bg->income_accno_id( SL::DB::Manager::TaxZone->get_default->id ) );
440
441   # if ($part_type eq 'part' || $part_type eq 'service') {
442   #   $entry->{object}->expense_accno_id( $bg->expense_accno_id( SL::DB::Manager::TaxZone->get_default->id ) );
443   # }
444
445   # if ($part_type eq 'part') {
446   #   $entry->{object}->inventory_accno_id( $bg->inventory_accno_id );
447   # }
448
449   if (none { $_ eq $part_type } qw(part service assembly assortment)) {
450     push @{ $entry->{errors} }, $::locale->text('Error: Invalid part type');
451     return 0;
452   }
453
454   $entry->{object}->part_type($part_type);
455   $entry->{object}->classification_id( $classification_id );
456
457   return 1;
458 }
459
460 sub check_price_factor {
461   my ($self, $entry) = @_;
462
463   my $object = $entry->{object};
464
465   # Check whether or not price factor ID is valid.
466   if ($object->price_factor_id && !$self->price_factors_by->{id}->{ $object->price_factor_id }) {
467     push @{ $entry->{errors} }, $::locale->text('Error: Invalid price factor');
468     return 0;
469   }
470
471   # Map name to ID if given.
472   if (!$object->price_factor_id && $entry->{raw_data}->{price_factor}) {
473     my $pf = $self->price_factors_by->{description}->{ $entry->{raw_data}->{price_factor} };
474
475     if (!$pf) {
476       push @{ $entry->{errors} }, $::locale->text('Error: Invalid price factor');
477       return 0;
478     }
479
480     $object->price_factor_id($pf->id);
481     $self->clone_methods->{price_factor_id} = 1;
482   }
483
484   return 1;
485 }
486
487 sub check_warehouse_and_bin {
488   my ($self, $entry) = @_;
489
490   my $object = $entry->{object};
491
492   # Check whether or not warehouse id is valid.
493   if ($object->warehouse_id && !$self->warehouses_by->{id}->{ $object->warehouse_id }) {
494     push @{ $entry->{errors} }, $::locale->text('Error: Invalid warehouse id');
495     return 0;
496   }
497   # Map name to ID if given.
498   if (!$object->warehouse_id && $entry->{raw_data}->{warehouse}) {
499     my $wh = $self->warehouses_by->{description}->{ $entry->{raw_data}->{warehouse} };
500
501     if (!$wh) {
502       push @{ $entry->{errors} }, $::locale->text('Error: Invalid warehouse name #1',$entry->{raw_data}->{warehouse});
503       return 0;
504     }
505
506     $object->warehouse_id($wh->id);
507   }
508   $self->clone_methods->{warehouse_id} = 1;
509
510   # Check whether or not bin id is valid.
511   if ($object->bin_id && !$self->bins_by->{id}->{ $object->bin_id }) {
512     push @{ $entry->{errors} }, $::locale->text('Error: Invalid bin id');
513     return 0;
514   }
515   # Map name to ID if given.
516   if ($object->warehouse_id && !$object->bin_id && $entry->{raw_data}->{bin}) {
517     my $bin = $self->bins_by->{description}->{ $entry->{raw_data}->{bin} };
518
519     if (!$bin) {
520       push @{ $entry->{errors} }, $::locale->text('Error: Invalid bin name #1',$entry->{raw_data}->{bin});
521       return 0;
522     }
523
524     $object->bin_id($bin->id);
525   }
526   $self->clone_methods->{bin_id} = 1;
527
528   if ($object->warehouse_id && $object->bin_id ) {
529     my $bin = $self->bins_by->{id}->{ $object->bin_id };
530     if ( $bin->warehouse_id != $object->warehouse_id ) {
531       push @{ $entry->{errors} }, $::locale->text('Error: Bin #1 is not from warehouse #2',
532                                                   $self->bins_by->{id}->{$object->bin_id}->description,
533                                                   $self->warehouses_by->{id}->{ $object->warehouse_id }->description);
534       return 0;
535     }
536   }
537   return 1;
538 }
539
540 sub check_partsgroup {
541   my ($self, $entry) = @_;
542
543   my $object = $entry->{object};
544
545   # Check whether or not part group ID is valid.
546   if ($object->partsgroup_id && !$self->partsgroups_by->{id}->{ $object->partsgroup_id }) {
547     push @{ $entry->{errors} }, $::locale->text('Error: Invalid parts group id #1', $object->partsgroup_id);
548     return 0;
549   }
550
551   # Map name to ID if given.
552   if (!$object->partsgroup_id && $entry->{raw_data}->{partsgroup}) {
553     my $pg = $self->partsgroups_by->{partsgroup}->{ $entry->{raw_data}->{partsgroup} };
554
555     if (!$pg) {
556       push @{ $entry->{errors} }, $::locale->text('Error: Invalid parts group name #1',  $entry->{raw_data}->{partsgroup});
557       return 0;
558     }
559
560     $object->partsgroup_id($pg->id);
561   }
562   # register payment_id for method copying later
563   $self->clone_methods->{partsgroup_id} = 1;
564
565   return 1;
566 }
567
568 sub check_unit {
569   my ($self, $entry) = @_;
570
571   my $object = $entry->{object};
572
573   $object->unit($self->settings->{default_unit}) unless $object->unit;
574
575   # Check whether or unit is valid.
576   if (!$self->units_by->{name}->{ $object->unit }) {
577     push @{ $entry->{errors} }, $::locale->text('Error: Unit missing or invalid');
578     return 0;
579   }
580
581   return 1;
582 }
583
584 sub handle_translations {
585   my ($self, $entry) = @_;
586
587   my @translations;
588   foreach my $language (@{ $self->all_languages }) {
589     my ($desc, $notes) = @{ $entry->{raw_data} }{ "description_" . $language->article_code, "notes_" . $language->article_code };
590     next unless $desc || $notes;
591
592     push @translations, SL::DB::Translation->new(language_id     => $language->id,
593                                                  translation     => $desc,
594                                                  longdescription => $notes);
595   }
596
597   $entry->{object}->translations(\@translations);
598 }
599
600 sub handle_pricegroups {
601   my ($self, $entry) = @_;
602
603   my @prices;
604   my $idx = 0;
605   foreach my $pricegroup (@{ $self->all_pricegroups }) {
606     $idx++;
607     my $sellprice = $entry->{raw_data}->{"pricegroup_${idx}"};
608     next if ($sellprice // '') eq '';
609
610     push @prices, SL::DB::Price->new(pricegroup_id => $pricegroup->id,
611                                      price         => $::form->parse_amount(\%::myconfig, $sellprice));
612   }
613
614   $entry->{object}->prices(\@prices);
615 }
616
617 sub handle_makemodel {
618   my ($self, $entry) = @_;
619   my $object = $entry->{object};
620   my $found_any;
621
622   my @makemodels;
623   foreach my $idx (sort map { substr $_, 5 } grep { m/^make_\d+$/ && $entry->{raw_data}->{$_} } keys %{ $entry->{raw_data} }) {
624     my $vendor = $entry->{raw_data}->{"make_${idx}"};
625     $vendor    = $self->vc_by->{id}->               { $vendor }
626               || $self->vc_by->{number}->{vendors}->{ $vendor }
627               || $self->vc_by->{name}->  {vendors}->{ $vendor };
628
629     if (ref($vendor) ne 'SL::DB::Vendor') {
630       push @{ $entry->{errors} }, $::locale->text('Error: Invalid vendor in column make_#1', $idx);
631
632     } else {
633       $found_any = 1;
634       push @makemodels, SL::DB::MakeModel->new(make               => $vendor->id,
635                                                model              => $entry->{raw_data}->{"model_${idx}"},
636                                                lastcost_as_number => $entry->{raw_data}->{"lastcost_${idx}"});
637
638       $self->makemodel_columns->{$idx}    = 1;
639       $entry->{raw_data}->{"make_${idx}"} = $vendor->name;
640     }
641   }
642
643   $object->makemodels(\@makemodels);
644   $object->makemodel(scalar(@makemodels) ? 1 : 0);
645
646   if ( !$entry->{part} || $self->settings->{article_number_policy} ne 'update_prices' ) {
647     return;
648   }
649
650   my %old_makemodels_by_mm = map { $_->make . $; . $_->model => $_ } $entry->{part}->makemodels;
651   my @new_makemodels;
652
653   foreach my $makemodel (@{ $object->makemodels_sorted }) {
654     my $makemodel_orig = $old_makemodels_by_mm{$makemodel->make,$makemodel->model};
655     $found_any = 1;
656
657     if ($makemodel_orig) {
658       $makemodel_orig->model($makemodel->model);
659       $makemodel_orig->lastcost($makemodel->lastcost);
660
661     } else {
662       push @new_makemodels, $makemodel;
663     }
664   }
665
666   $entry->{part}->makemodels([ @{$entry->{part}->makemodels_sorted}, @new_makemodels ]) if @new_makemodels;
667
668   # reindex makemodels
669   my $i = 0;
670   $_->sortorder(++$i) for @{ $entry->{part}->makemodels_sorted };
671
672   $self->save_with_cascade(1) if $found_any;
673 }
674
675 sub set_various_fields {
676   my ($self, $entry) = @_;
677
678   my $object = $entry->{object_to_save} || $entry->{object};
679
680   $object->priceupdate(DateTime->now_local);
681 }
682
683 sub init_profile {
684   my ($self) = @_;
685
686   my $profile = $self->SUPER::init_profile;
687   delete @{$profile}{qw(bom makemodel priceupdate stockable type)};
688
689   $profile->{"pricegroup_$_"} = '' for 1 .. scalar @{ $_[0]->all_pricegroups };
690
691   return $profile;
692 }
693
694 sub save_objects {
695   my ($self, %params) = @_;
696
697   my $with_number    = [ grep { $_->{object}->partnumber ne '####' } @{ $self->controller->data } ];
698   my $without_number = [ grep { $_->{object}->partnumber eq '####' } @{ $self->controller->data } ];
699
700   map { $_->{object}->partnumber('') } @{ $without_number };
701   $self->SUPER::save_objects(data => $with_number);
702   $self->SUPER::save_objects(data => $without_number);
703 }
704
705 sub setup_displayable_columns {
706   my ($self) = @_;
707
708   $self->SUPER::setup_displayable_columns;
709   $self->add_cvar_columns_to_displayable_columns;
710
711   $self->add_displayable_columns({ name => 'bin_id',             description => $::locale->text('Bin (database ID)')                                    },
712                                  { name => 'bin',                description => $::locale->text('Bin (name)')                                           },
713                                  { name => 'buchungsgruppen_id', description => $::locale->text('Booking group (database ID)')                          },
714                                  { name => 'buchungsgruppe',     description => $::locale->text('Booking group (name)')                                 },
715                                  { name => 'description',        description => $::locale->text('Description')                                          },
716                                  { name => 'drawing',            description => $::locale->text('Drawing')                                              },
717                                  { name => 'ean',                description => $::locale->text('EAN')                                                  },
718                                  { name => 'formel',             description => $::locale->text('Formula')                                              },
719                                  { name => 'gv',                 description => $::locale->text('Business Volume')                                      },
720                                  { name => 'has_sernumber',      description => $::locale->text('Has serial number')                                    },
721                                  { name => 'image',              description => $::locale->text('Image')                                                },
722                                  { name => 'lastcost',           description => $::locale->text('Last Cost')                                            },
723                                  { name => 'listprice',          description => $::locale->text('List Price')                                           },
724                                  { name => 'make_X',             description => $::locale->text('Make (vendor\'s database ID, number or name; with X being a number)') . ' [1]' },
725                                  { name => 'microfiche',         description => $::locale->text('Microfiche')                                           },
726                                  { name => 'model_X',            description => $::locale->text('Model (with X being a number)') . ' [1]'               },
727                                  { name => 'lastcost_X',         description => $::locale->text('Lastcost (with X being a number)') . ' [1]'            },
728                                  { name => 'not_discountable',   description => $::locale->text('Not Discountable')                                     },
729                                  { name => 'notes',              description => $::locale->text('Notes')                                                },
730                                  { name => 'obsolete',           description => $::locale->text('Obsolete')                                             },
731                                  { name => 'onhand',             description => $::locale->text('On Hand') . ' [2]'                                     },
732                                  { name => 'partnumber',         description => $::locale->text('Part Number')                                          },
733                                  { name => 'partsgroup_id',      description => $::locale->text('Partsgroup (database ID)')                             },
734                                  { name => 'partsgroup',         description => $::locale->text('Partsgroup (name)')                                    },
735                                  { name => 'part_classification',description => $::locale->text('Article classification')  . ' [3]'                     },
736                                  { name => 'payment_id',         description => $::locale->text('Payment terms (database ID)')                          },
737                                  { name => 'payment',            description => $::locale->text('Payment terms (name)')                                 },
738                                  { name => 'price_factor_id',    description => $::locale->text('Price factor (database ID)')                           },
739                                  { name => 'price_factor',       description => $::locale->text('Price factor (name)')                                  },
740                                  { name => 'rop',                description => $::locale->text('ROP')                                                  },
741                                  { name => 'sellprice',          description => $::locale->text('Sellprice')                                            },
742                                  { name => 'shop',               description => $::locale->text('Shop article')                                         },
743                                  { name => 'type',               description => $::locale->text('Article type')  . ' [3]'                               },
744                                  { name => 'unit',               description => $::locale->text('Unit (if missing or empty default unit will be used)') },
745                                  { name => 've',                 description => $::locale->text('Verrechnungseinheit')                                  },
746                                  { name => 'warehouse_id',       description => $::locale->text('Warehouse (database ID)')                              },
747                                  { name => 'warehouse',          description => $::locale->text('Warehouse (name)')                                     },
748                                  { name => 'weight',             description => $::locale->text('Weight')                                               },
749                                 );
750
751   foreach my $language (@{ $self->all_languages }) {
752     $self->add_displayable_columns({ name        => 'description_' . $language->article_code,
753                                      description => $::locale->text('Description (translation for #1)', $language->description) },
754                                    { name        => 'notes_' . $language->article_code,
755                                      description => $::locale->text('Notes (translation for #1)', $language->description) });
756   }
757
758   my $idx = 0;
759   foreach my $pricegroup (@{ $self->all_pricegroups }) {
760     $idx++;
761     $self->add_displayable_columns({ name        => 'pricegroup_' . $idx,
762                                      description => $::locale->text("Sellprice for price group '#1'", $pricegroup->pricegroup) });
763   }
764 }
765
766 1;