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