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