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