CsvImport: Makemodels feiner granulieren.
[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                                  translation_columns all_pricegroups) ],
28 );
29
30 sub init_class {
31   my ($self) = @_;
32   $self->class('SL::DB::Part');
33 }
34
35 sub init_bg_by {
36   my ($self) = @_;
37
38   my $all_bg = SL::DB::Manager::Buchungsgruppe->get_all;
39   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_bg } } ) } qw(id description) };
40 }
41
42 sub init_price_factors_by {
43   my ($self) = @_;
44
45   my $all_price_factors = SL::DB::Manager::PriceFactor->get_all;
46   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_price_factors } } ) } qw(id description) };
47 }
48
49 sub init_partsgroups_by {
50   my ($self) = @_;
51
52   my $all_partsgroups = SL::DB::Manager::PartsGroup->get_all;
53   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_partsgroups } } ) } qw(id partsgroup) };
54 }
55
56 sub init_units_by {
57   my ($self) = @_;
58
59   my $all_units = SL::DB::Manager::Unit->get_all;
60   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $all_units } } ) } qw(name) };
61 }
62
63 sub init_parts_by {
64   my ($self) = @_;
65
66 #  my $parts_by = { id         => { map { ( $_->id => $_ ) } grep { !$_->assembly } @{ $self->existing_objects } },
67 #                   partnumber => { part    => { },
68 #                                   service => { } } };
69 #
70 #  foreach my $part (@{ $self->existing_objects }) {
71 #    next if $part->assembly;
72 #    $parts_by->{partnumber}->{ $part->type }->{ $part->partnumber } = $part;
73 #  }
74
75   my $parts_by = {};
76   my $sth = prepare_execute_query($::form, $::form->get_standard_dbh, 'SELECT partnumber FROM parts');
77   while (my ($partnumber) = $sth->fetchrow_array()) {
78     $parts_by->{partnumber}{$partnumber} = 1;
79   }
80
81   return $parts_by;
82 }
83
84 sub init_all_pricegroups {
85   my ($self) = @_;
86
87   return SL::DB::Manager::Pricegroup->get_all(sort => 'id');
88 }
89
90 sub init_settings {
91   my ($self) = @_;
92
93   return { map { ( $_ => $self->controller->profile->get($_) ) } qw(apply_buchungsgruppe default_buchungsgruppe article_number_policy
94                                                                     sellprice_places sellprice_adjustment sellprice_adjustment_type
95                                                                     shoparticle_if_missing parts_type default_unit) };
96 }
97
98 sub init_all_cvar_configs {
99   my ($self) = @_;
100
101   return SL::DB::Manager::CustomVariableConfig->get_all(where => [ module => 'IC' ]);
102 }
103
104 sub init_translation_columns {
105   my ($self) = @_;
106
107   return [ map { ("description_" . $_->article_code, "notes_" . $_->article_code) } (@{ $self->all_languages }) ];
108 }
109
110 sub check_objects {
111   my ($self) = @_;
112
113   return unless @{ $self->controller->data };
114
115   $self->controller->track_progress(phase => 'building data', progress => 0);
116
117   $self->makemodel_columns({});
118
119   my $i;
120   my $num_data = scalar @{ $self->controller->data };
121   foreach my $entry (@{ $self->controller->data }) {
122     $self->controller->track_progress(progress => $i/$num_data * 100) if $i % 100 == 0;
123
124     $self->check_buchungsgruppe($entry);
125     $self->check_type($entry);
126     $self->check_unit($entry);
127     $self->check_price_factor($entry);
128     $self->check_payment($entry);
129     $self->check_partsgroup($entry);
130     $self->handle_pricegroups($entry);
131     $self->check_existing($entry) unless @{ $entry->{errors} };
132     $self->handle_prices($entry) if $self->settings->{sellprice_adjustment};
133     $self->handle_shoparticle($entry);
134     $self->handle_translations($entry);
135     $self->handle_cvars($entry);
136     $self->handle_makemodel($entry);
137     $self->set_various_fields($entry);
138   } continue {
139     $i++;
140   }
141
142   $self->add_columns(qw(type)) if $self->settings->{parts_type} eq 'mixed';
143   $self->add_columns(qw(buchungsgruppen_id unit));
144   $self->add_columns(map { "${_}_id" } grep { exists $self->controller->data->[0]->{raw_data}->{$_} } qw (price_factor payment partsgroup));
145   $self->add_columns(qw(shop)) if $self->settings->{shoparticle_if_missing};
146   $self->add_cvar_raw_data_columns;
147   map { $self->add_raw_data_columns("pricegroup_${_}") if exists $self->controller->data->[0]->{raw_data}->{"pricegroup_$_"} } (1..scalar(@{ $self->all_pricegroups }));
148   map { $self->add_raw_data_columns($_) if exists $self->controller->data->[0]->{raw_data}->{$_} } @{ $self->translation_columns };
149   map { $self->add_raw_data_columns("make_${_}", "model_${_}", "lastcost_${_}") } sort { $a <=> $b } keys %{ $self->makemodel_columns };
150 }
151
152 sub get_duplicate_check_fields {
153   return {
154     partnumber => {
155       label     => $::locale->text('Part Number'),
156       default   => 0
157     },
158
159     description => {
160       label     => $::locale->text('Description'),
161       default   => 1,
162       maker     => sub {
163         my $desc = shift->description;
164         $desc =~ s/[\s,\.\-]//g;
165         return $desc;
166       }
167     },
168   };
169 }
170
171 sub check_buchungsgruppe {
172   my ($self, $entry) = @_;
173
174   my $object = $entry->{object};
175
176   # Check Buchungsgruppe
177
178   # Store and verify default ID.
179   my $default_id = $self->settings->{default_buchungsgruppe};
180   $default_id    = undef unless $self->bg_by->{id}->{ $default_id };
181
182   # 1. Use default ID if enforced.
183   $object->buchungsgruppen_id($default_id) if $default_id && ($self->settings->{apply_buchungsgruppe} eq 'all');
184
185   # 2. Use supplied ID if valid
186   $object->buchungsgruppen_id(undef) if $object->buchungsgruppen_id && !$self->bg_by->{id}->{ $object->buchungsgruppen_id };
187
188   # 3. Look up name if supplied.
189   if (!$object->buchungsgruppen_id) {
190     my $bg = $self->bg_by->{description}->{ $entry->{raw_data}->{buchungsgruppe} };
191     $object->buchungsgruppen_id($bg->id) if $bg;
192   }
193
194   # 4. Use default ID if not valid.
195   $object->buchungsgruppen_id($default_id) if !$object->buchungsgruppen_id && $default_id && ($self->settings->{apply_buchungsgruppe} eq 'missing');
196
197   return 1 if $object->buchungsgruppen_id;
198
199   push @{ $entry->{errors} }, $::locale->text('Error: Buchungsgruppe missing or invalid');
200   return 0;
201 }
202
203 sub check_existing {
204   my ($self, $entry) = @_;
205
206   my $object = $entry->{object};
207
208   if ($object->partnumber && $self->parts_by->{partnumber}{$object->partnumber}) {
209     $entry->{part} = SL::DB::Manager::Part->find_by(partnumber => $object->partnumber);
210   }
211
212   if ($entry->{part}) {
213     if ($self->settings->{article_number_policy} eq 'update_prices') {
214       if ($self->settings->{parts_type} eq 'mixed' && $entry->{part}->type ne $object->type) {
215         push(@{$entry->{errors}}, $::locale->text('Skipping due to existing entry in database with different type'));
216       } else {
217         map { $entry->{part}->$_( $object->$_ ) if defined $object->$_ } qw(sellprice listprice lastcost);
218
219         # merge prices
220         my %prices_by_pricegroup_id = map { $_->pricegroup->id => $_ } $entry->{part}->prices, $object->prices;
221         $entry->{part}->prices(grep { $_ } map { $prices_by_pricegroup_id{$_->id} } @{ $self->all_pricegroups });
222
223         push @{ $entry->{information} }, $::locale->text('Updating prices of existing entry in database');
224         $entry->{object_to_save} = $entry->{part};
225       }
226     } elsif ( $self->settings->{article_number_policy} eq 'skip' ) {
227       push(@{$entry->{errors}}, $::locale->text('Skipping due to existing entry in database'));
228
229     } else {
230       $object->partnumber('####');
231       push(@{$entry->{errors}}, $::locale->text('Skipping, for assemblies are not importable (yet)')) if $object->type eq 'assembly';
232     }
233   } else {
234     push(@{$entry->{errors}}, $::locale->text('Skipping, for assemblies are not importable (yet)')) if $object->type eq 'assembly';
235   }
236 }
237
238 sub handle_prices {
239   my ($self, $entry) = @_;
240
241   foreach my $column (qw(sellprice)) {
242     my $object     = $entry->{object_to_save} || $entry->{object};
243     my $adjustment = $self->settings->{sellprice_adjustment};
244     my $value      = $object->$column;
245
246     $value = $self->settings->{sellprice_adjustment_type} eq 'percent' ? $value * (100 + $adjustment) / 100 : $value + $adjustment;
247     $object->$column($::form->round_amount($value, $self->settings->{sellprice_places}));
248   }
249 }
250
251 sub handle_shoparticle {
252   my ($self, $entry) = @_;
253
254   $entry->{object}->shop(1) if $self->settings->{shoparticle_if_missing} && !$self->controller->headers->{used}->{shop};
255 }
256
257 sub check_type {
258   my ($self, $entry) = @_;
259
260   my $bg = $self->bg_by->{id}->{ $entry->{object}->buchungsgruppen_id };
261   $bg  ||= SL::DB::Buchungsgruppe->new(inventory_accno_id => 1); # does this case ever occur?
262
263   my $type = $self->settings->{parts_type};
264   if ($type eq 'mixed') {
265     $type = $entry->{raw_data}->{type} =~ m/^p/i ? 'part'
266           : $entry->{raw_data}->{type} =~ m/^s/i ? 'service'
267           : $entry->{raw_data}->{type} =~ m/^a/i ? 'assembly'
268           :                                        undef;
269   }
270
271   $entry->{object}->assembly($type eq 'assembly');
272
273   # when saving income_accno_id or expense_accno_id use ids from the selected
274   # $bg according to the default tax_zone (the one with the highest sort
275   # order).  Alternatively one could use the ids from defaults, but they might
276   # not all be set.
277
278   $entry->{object}->income_accno_id( $bg->income_accno_id( SL::DB::Manager::TaxZone->get_default->id ) );
279
280   if ($type eq 'part' || $type eq 'service') {
281     $entry->{object}->expense_accno_id( $bg->expense_accno_id( SL::DB::Manager::TaxZone->get_default->id ) );
282   }
283
284   if ($type eq 'part') {
285     $entry->{object}->inventory_accno_id( $bg->inventory_accno_id );
286   }
287
288   if (none { $_ eq $type } qw(part service assembly)) {
289     push @{ $entry->{errors} }, $::locale->text('Error: Invalid part type');
290     return 0;
291   }
292
293   return 1;
294 }
295
296 sub check_price_factor {
297   my ($self, $entry) = @_;
298
299   my $object = $entry->{object};
300
301   # Check whether or not price factor ID is valid.
302   if ($object->price_factor_id && !$self->price_factors_by->{id}->{ $object->price_factor_id }) {
303     push @{ $entry->{errors} }, $::locale->text('Error: Invalid price factor');
304     return 0;
305   }
306
307   # Map name to ID if given.
308   if (!$object->price_factor_id && $entry->{raw_data}->{price_factor}) {
309     my $pf = $self->price_factors_by->{description}->{ $entry->{raw_data}->{price_factor} };
310
311     if (!$pf) {
312       push @{ $entry->{errors} }, $::locale->text('Error: Invalid price factor');
313       return 0;
314     }
315
316     $object->price_factor_id($pf->id);
317   }
318
319   return 1;
320 }
321
322 sub check_partsgroup {
323   my ($self, $entry) = @_;
324
325   my $object = $entry->{object};
326
327   # Check whether or not part group ID is valid.
328   if ($object->partsgroup_id && !$self->partsgroups_by->{id}->{ $object->partsgroup_id }) {
329     push @{ $entry->{errors} }, $::locale->text('Error: Invalid parts group');
330     return 0;
331   }
332
333   # Map name to ID if given.
334   if (!$object->partsgroup_id && $entry->{raw_data}->{partsgroup}) {
335     my $pg = $self->partsgroups_by->{partsgroup}->{ $entry->{raw_data}->{partsgroup} };
336
337     if (!$pg) {
338       push @{ $entry->{errors} }, $::locale->text('Error: Invalid parts group');
339       return 0;
340     }
341
342     $object->partsgroup_id($pg->id);
343   }
344
345   return 1;
346 }
347
348 sub check_unit {
349   my ($self, $entry) = @_;
350
351   my $object = $entry->{object};
352
353   $object->unit($self->settings->{default_unit}) unless $object->unit;
354
355   # Check whether or unit is valid.
356   if (!$self->units_by->{name}->{ $object->unit }) {
357     push @{ $entry->{errors} }, $::locale->text('Error: Unit missing or invalid');
358     return 0;
359   }
360
361   return 1;
362 }
363
364 sub handle_translations {
365   my ($self, $entry) = @_;
366
367   my @translations;
368   foreach my $language (@{ $self->all_languages }) {
369     my ($desc, $notes) = @{ $entry->{raw_data} }{ "description_" . $language->article_code, "notes_" . $language->article_code };
370     next unless $desc || $notes;
371
372     push @translations, SL::DB::Translation->new(language_id     => $language->id,
373                                                  translation     => $desc,
374                                                  longdescription => $notes);
375   }
376
377   $entry->{object}->translations(\@translations);
378 }
379
380 sub handle_pricegroups {
381   my ($self, $entry) = @_;
382
383   my @prices;
384   my $idx = 0;
385   foreach my $pricegroup (@{ $self->all_pricegroups }) {
386     $idx++;
387     my $sellprice = $entry->{raw_data}->{"pricegroup_${idx}"};
388     next if $sellprice eq '';
389
390     push @prices, SL::DB::Price->new(pricegroup_id => $pricegroup->id,
391                                      price         => $::form->parse_amount(\%::myconfig, $sellprice));
392   }
393
394   $entry->{object}->prices(\@prices);
395 }
396
397 sub handle_makemodel {
398   my ($self, $entry) = @_;
399   my $object = $entry->{object};
400   my $found_any;
401
402   my @makemodels;
403   foreach my $idx (sort map { substr $_, 5 } grep { m/^make_\d+$/ && $entry->{raw_data}->{$_} } keys %{ $entry->{raw_data} }) {
404     my $vendor = $entry->{raw_data}->{"make_${idx}"};
405     $vendor    = $self->vc_by->{id}->               { $vendor }
406               || $self->vc_by->{number}->{vendors}->{ $vendor }
407               || $self->vc_by->{name}->  {vendors}->{ $vendor };
408
409     if (ref($vendor) ne 'SL::DB::Vendor') {
410       push @{ $entry->{errors} }, $::locale->text('Error: Invalid vendor in column make_#1', $idx);
411
412     } else {
413       $found_any = 1;
414       push @makemodels, SL::DB::MakeModel->new(make               => $vendor->id,
415                                                model              => $entry->{raw_data}->{"model_${idx}"},
416                                                lastcost_as_number => $entry->{raw_data}->{"lastcost_${idx}"});
417
418       $self->makemodel_columns->{$idx}    = 1;
419       $entry->{raw_data}->{"make_${idx}"} = $vendor->name;
420     }
421   }
422
423   $object->makemodels(\@makemodels);
424   $object->makemodel(scalar(@makemodels) ? 1 : 0);
425
426   if ( !$entry->{part} || $self->settings->{article_number_policy} ne 'update_prices' ) {
427     return;
428   }
429
430   my %old_makemodels_by_mm = map { $_->make . $; . $_->model => $_ } $entry->{part}->makemodels;
431
432   foreach my $makemodel ($object->makemodels()) {
433     my $makemodel_orig = $old_makemodels_by_mm{$makemodel->make,$makemodel->model};
434     $found_any = 1;
435
436     if ($makemodel_orig) {
437       $makemodel_orig->model($makemodel->model);
438       $makemodel_orig->lastcost($makemodel->lastcost);
439
440     } else {
441       $entry->{part}->add_makemodels($makemodel);
442     }
443   }
444
445   # reindex makemodels
446   my $i = 0;
447   $_->sortorder(++$i) for @{ $entry->{part}->makemodels };
448
449   $self->save_with_cascade(1) if $found_any;
450 }
451
452 sub set_various_fields {
453   my ($self, $entry) = @_;
454
455   $entry->{object}->priceupdate(DateTime->now_local);
456 }
457
458 sub init_profile {
459   my ($self) = @_;
460
461   my $profile = $self->SUPER::init_profile;
462   delete @{$profile}{qw(alternate assembly bom expense_accno_id income_accno_id inventory_accno_id makemodel priceupdate stockable type)};
463
464   $profile->{"pricegroup_$_"} = '' for 1 .. scalar @{ $_[0]->all_pricegroups };
465
466   return $profile;
467 }
468
469 sub save_objects {
470   my ($self, %params) = @_;
471
472   my $with_number    = [ grep { $_->{object}->partnumber ne '####' } @{ $self->controller->data } ];
473   my $without_number = [ grep { $_->{object}->partnumber eq '####' } @{ $self->controller->data } ];
474
475   map { $_->{object}->partnumber('') } @{ $without_number };
476
477   $self->SUPER::save_objects(data => $with_number);
478   $self->SUPER::save_objects(data => $without_number);
479 }
480
481 sub setup_displayable_columns {
482   my ($self) = @_;
483
484   $self->SUPER::setup_displayable_columns;
485   $self->add_cvar_columns_to_displayable_columns;
486
487   $self->add_displayable_columns({ name => 'bin',                description => $::locale->text('Bin')                                                  },
488                                  { name => 'buchungsgruppen_id', description => $::locale->text('Buchungsgruppe (database ID)')                         },
489                                  { name => 'buchungsgruppe',     description => $::locale->text('Buchungsgruppe (name)')                                },
490                                  { name => 'description',        description => $::locale->text('Description')                                          },
491                                  { name => 'drawing',            description => $::locale->text('Drawing')                                              },
492                                  { name => 'ean',                description => $::locale->text('EAN')                                                  },
493                                  { name => 'formel',             description => $::locale->text('Formula')                                              },
494                                  { name => 'gv',                 description => $::locale->text('Business Volume')                                      },
495                                  { name => 'has_sernumber',      description => $::locale->text('Has serial number')                                    },
496                                  { name => 'image',              description => $::locale->text('Image')                                                },
497                                  { name => 'lastcost',           description => $::locale->text('Last Cost')                                            },
498                                  { name => 'listprice',          description => $::locale->text('List Price')                                           },
499                                  { name => 'make_X',             description => $::locale->text('Make (vendor\'s database ID, number or name; with X being a number)') . ' [1]' },
500                                  { name => 'microfiche',         description => $::locale->text('Microfiche')                                           },
501                                  { name => 'model_X',            description => $::locale->text('Model (with X being a number)') . ' [1]'               },
502                                  { name => 'lastcost_X',         description => $::locale->text('Lastcost (with X being a number)') . ' [1]'            },
503                                  { name => 'not_discountable',   description => $::locale->text('Not Discountable')                                     },
504                                  { name => 'notes',              description => $::locale->text('Notes')                                                },
505                                  { name => 'obsolete',           description => $::locale->text('Obsolete')                                             },
506                                  { name => 'onhand',             description => $::locale->text('On Hand') . ' [2]'                                     },
507                                  { name => 'partnumber',         description => $::locale->text('Part Number')                                          },
508                                  { name => 'partsgroup_id',      description => $::locale->text('Partsgroup (database ID)')                             },
509                                  { name => 'partsgroup',         description => $::locale->text('Partsgroup (name)')                                    },
510                                  { name => 'payment_id',         description => $::locale->text('Payment terms (database ID)')                          },
511                                  { name => 'payment',            description => $::locale->text('Payment terms (name)')                                 },
512                                  { name => 'price_factor_id',    description => $::locale->text('Price factor (database ID)')                           },
513                                  { name => 'price_factor',       description => $::locale->text('Price factor (name)')                                  },
514                                  { name => 'rop',                description => $::locale->text('ROP')                                                  },
515                                  { name => 'sellprice',          description => $::locale->text('Sellprice')                                            },
516                                  { name => 'shop',               description => $::locale->text('Shopartikel')                                          },
517                                  { name => 'type',               description => $::locale->text('Article type')  . ' [3]'                             },
518                                  { name => 'unit',               description => $::locale->text('Unit (if missing or empty default unit will be used)') },
519                                  { name => 've',                 description => $::locale->text('Verrechnungseinheit')                                  },
520                                  { name => 'weight',             description => $::locale->text('Weight')                                               },
521                                 );
522
523   foreach my $language (@{ $self->all_languages }) {
524     $self->add_displayable_columns({ name        => 'description_' . $language->article_code,
525                                      description => $::locale->text('Description (translation for #1)', $language->description) },
526                                    { name        => 'notes_' . $language->article_code,
527                                      description => $::locale->text('Notes (translation for #1)', $language->description) });
528   }
529
530   my $idx = 0;
531   foreach my $pricegroup (@{ $self->all_pricegroups }) {
532     $idx++;
533     $self->add_displayable_columns({ name        => 'pricegroup_' . $idx,
534                                      description => $::locale->text("Sellprice for price group '#1'", $pricegroup->pricegroup) });
535   }
536 }
537
538 1;