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