Merge branch 'master' of vc.linet-services.de:public/lx-office-erp
[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_${_}") } sort { $a <=> $b } keys %{ $self->makemodel_columns };
133 }
134
135 sub check_duplicates {
136   my ($self, %params) = @_;
137
138   my $normalizer = sub { my $name = $_[0]; $name =~ s/[\s,\.\-]//g; return $name; };
139   my $name_maker = sub { return $normalizer->($_[0]->description) };
140
141   my %by_name;
142   if ('check_db' eq $self->controller->profile->get('duplicates')) {
143     %by_name = map { ( $name_maker->($_) => 'db' ) } @{ $self->existing_objects };
144   }
145
146   foreach my $entry (@{ $self->controller->data }) {
147     next if @{ $entry->{errors} };
148
149     my $name = $name_maker->($entry->{object});
150
151     if (!$by_name{ $name }) {
152       $by_name{ $name } = 'csv';
153
154     } else {
155       push @{ $entry->{errors} }, $by_name{ $name } eq 'db' ? $::locale->text('Duplicate in database') : $::locale->text('Duplicate in CSV file');
156     }
157   }
158 }
159
160 sub check_buchungsgruppe {
161   my ($self, $entry) = @_;
162
163   my $object = $entry->{object};
164
165   # Check Buchungsgruppe
166
167   # Store and verify default ID.
168   my $default_id = $self->settings->{default_buchungsgruppe};
169   $default_id    = undef unless $self->bg_by->{id}->{ $default_id };
170
171   # 1. Use default ID if enforced.
172   $object->buchungsgruppen_id($default_id) if $default_id && ($self->settings->{apply_buchungsgruppe} eq 'all');
173
174   # 2. Use supplied ID if valid
175   $object->buchungsgruppen_id(undef) if $object->buchungsgruppen_id && !$self->bg_by->{id}->{ $object->buchungsgruppen_id };
176
177   # 3. Look up name if supplied.
178   if (!$object->buchungsgruppen_id) {
179     my $bg = $self->bg_by->{description}->{ $entry->{raw_data}->{buchungsgruppe} };
180     $object->buchungsgruppen_id($bg->id) if $bg;
181   }
182
183   # 4. Use default ID if not valid.
184   $object->buchungsgruppen_id($default_id) if !$object->buchungsgruppen_id && $default_id && ($self->settings->{apply_buchungsgruppe} eq 'missing');
185
186   return 1 if $object->buchungsgruppen_id;
187
188   push @{ $entry->{errors} }, $::locale->text('Error: Buchungsgruppe missing or invalid');
189   return 0;
190 }
191
192 sub check_existing {
193   my ($self, $entry) = @_;
194
195   my $object = $entry->{object};
196
197   $entry->{part} = $self->parts_by->{partnumber}->{ $object->type }->{ $object->partnumber };
198
199   if ($self->settings->{article_number_policy} eq 'update_prices') {
200     if ($entry->{part}) {
201       map { $entry->{part}->$_( $object->$_ ) } qw(sellprice listprice lastcost prices);
202       push @{ $entry->{information} }, $::locale->text('Updating prices of existing entry in database');
203       $entry->{object_to_save} = $entry->{part};
204     }
205
206   } else {
207     $object->partnumber('####') if $entry->{part};
208   }
209 }
210
211 sub handle_prices {
212   my ($self, $entry) = @_;
213
214   foreach my $column (qw(sellprice listprice lastcost)) {
215     next unless $self->controller->headers->{used}->{ $column };
216
217     my $adjustment = $self->settings->{sellprice_adjustment};
218     my $value      = $entry->{object}->$column;
219
220     $value = $self->settings->{sellprice_adjustment_type} eq 'percent' ? $value * (100 + $adjustment) / 100 : $value + $adjustment;
221     $entry->{object}->$column($::form->round_amount($value, $self->settings->{sellprice_places}));
222   }
223 }
224
225 sub handle_shoparticle {
226   my ($self, $entry) = @_;
227
228   $entry->{object}->shop(1) if $self->settings->{shoparticle_if_missing} && !$self->controller->headers->{used}->{shop};
229 }
230
231 sub check_type {
232   my ($self, $entry) = @_;
233
234   my $bg = $self->bg_by->{id}->{ $entry->{object}->buchungsgruppen_id };
235   $bg  ||= SL::DB::Buchungsgruppe->new(inventory_accno_id => 1, income_accno_id_0 => 1, expense_accno_id_0 => 1);
236
237   my $type = $self->settings->{parts_type};
238   if ($type eq 'mixed') {
239     $type = $entry->{raw_data}->{type} =~ m/^p/i ? 'part'
240           : $entry->{raw_data}->{type} =~ m/^s/i ? 'service'
241           :                                        undef;
242   }
243
244   $entry->{object}->income_accno_id(  $bg->income_accno_id_0 );
245   $entry->{object}->expense_accno_id( $bg->expense_accno_id_0 );
246
247   if ($type eq 'part') {
248     $entry->{object}->inventory_accno_id( $bg->inventory_accno_id );
249
250   } elsif ($type ne 'service') {
251     push @{ $entry->{errors} }, $::locale->text('Error: Invalid part type');
252     return 0;
253   }
254
255   return 1;
256 }
257
258 sub check_price_factor {
259   my ($self, $entry) = @_;
260
261   my $object = $entry->{object};
262
263   # Check whether or not price factor ID is valid.
264   if ($object->price_factor_id && !$self->price_factors_by->{id}->{ $object->price_factor_id }) {
265     push @{ $entry->{errors} }, $::locale->text('Error: Invalid price factor');
266     return 0;
267   }
268
269   # Map name to ID if given.
270   if (!$object->price_factor_id && $entry->{raw_data}->{price_factor}) {
271     my $pf = $self->price_factors_by->{description}->{ $entry->{raw_data}->{price_factor} };
272
273     if (!$pf) {
274       push @{ $entry->{errors} }, $::locale->text('Error: Invalid price factor');
275       return 0;
276     }
277
278     $object->price_factor_id($pf->id);
279   }
280
281   return 1;
282 }
283
284 sub check_partsgroup {
285   my ($self, $entry) = @_;
286
287   my $object = $entry->{object};
288
289   # Check whether or not part group ID is valid.
290   if ($object->partsgroup_id && !$self->partsgroups_by->{id}->{ $object->partsgroup_id }) {
291     push @{ $entry->{errors} }, $::locale->text('Error: Invalid parts group');
292     return 0;
293   }
294
295   # Map name to ID if given.
296   if (!$object->partsgroup_id && $entry->{raw_data}->{partsgroup}) {
297     my $pg = $self->partsgroups_by->{partsgroup}->{ $entry->{raw_data}->{partsgroup} };
298
299     if (!$pg) {
300       push @{ $entry->{errors} }, $::locale->text('Error: Invalid parts group');
301       return 0;
302     }
303
304     $object->partsgroup_id($pg->id);
305   }
306
307   return 1;
308 }
309
310 sub check_unit {
311   my ($self, $entry) = @_;
312
313   my $object = $entry->{object};
314
315   $object->unit($self->settings->{default_unit}) unless $object->unit;
316
317   # Check whether or unit is valid.
318   if (!$self->units_by->{name}->{ $object->unit }) {
319     push @{ $entry->{errors} }, $::locale->text('Error: Unit missing or invalid');
320     return 0;
321   }
322
323   return 1;
324 }
325
326 sub handle_translations {
327   my ($self, $entry) = @_;
328
329   my @translations;
330   foreach my $language (@{ $self->all_languages }) {
331     my ($desc, $notes) = @{ $entry->{raw_data} }{ "description_" . $language->article_code, "notes_" . $language->article_code };
332     next unless $desc || $notes;
333
334     push @translations, SL::DB::Translation->new(language_id     => $language->id,
335                                                  translation     => $desc,
336                                                  longdescription => $notes);
337   }
338
339   $entry->{object}->translations(\@translations);
340 }
341
342 sub handle_pricegroups {
343   my ($self, $entry) = @_;
344
345   my @prices;
346   my $idx = 0;
347   foreach my $pricegroup (@{ $self->all_pricegroups }) {
348     $idx++;
349     my $sellprice = $entry->{raw_data}->{"pricegroup_${idx}"};
350     next if $sellprice eq '';
351
352     push @prices, SL::DB::Price->new(pricegroup_id => $pricegroup->id,
353                                      price         => $::form->parse_amount(\%::myconfig, $sellprice));
354   }
355
356   $entry->{object}->prices(\@prices);
357 }
358
359 sub handle_makemodel {
360   my ($self, $entry) = @_;
361
362   my @makemodels;
363   foreach my $idx (map { substr $_, 5 } grep { m/^make_\d+$/ && $entry->{raw_data}->{$_} } keys %{ $entry->{raw_data} }) {
364     my $vendor = $entry->{raw_data}->{"make_${idx}"};
365     $vendor    = $self->vc_by->{id}->               { $vendor }
366               || $self->vc_by->{number}->{vendors}->{ $vendor }
367               || $self->vc_by->{name}->  {vendors}->{ $vendor };
368
369     if (ref($vendor) ne 'SL::DB::Vendor') {
370       push @{ $entry->{errors} }, $::locale->text('Error: Invalid vendor in column make_#1', $idx);
371
372     } else {
373       push @makemodels, SL::DB::MakeModel->new(make  => $vendor->id,
374                                                model => $entry->{raw_data}->{"model_${idx}"});
375       $self->makemodel_columns->{$idx}    = 1;
376       $entry->{raw_data}->{"make_${idx}"} = $vendor->name;
377     }
378   }
379
380   $entry->{object}->makemodels(\@makemodels);
381   $entry->{object}->makemodel(scalar(@makemodels) ? 1 : 0);
382 }
383
384 sub set_various_fields {
385   my ($self, $entry) = @_;
386
387   $entry->{object}->priceupdate(DateTime->now_local);
388 }
389
390 sub init_profile {
391   my ($self) = @_;
392
393   my $profile = $self->SUPER::init_profile;
394   delete @{$profile}{qw(alternate assembly bom expense_accno_id income_accno_id inventory_accno_id makemodel priceupdate stockable type)};
395
396   return $profile;
397 }
398
399 sub save_objects {
400   my ($self, %params) = @_;
401
402   my $with_number    = [ grep { $_->{object}->partnumber ne '####' } @{ $self->controller->data } ];
403   my $without_number = [ grep { $_->{object}->partnumber eq '####' } @{ $self->controller->data } ];
404
405   map { $_->{object}->partnumber('') } @{ $without_number };
406
407   $self->SUPER::save_objects(data => $with_number);
408   $self->SUPER::save_objects(data => $without_number);
409 }
410
411 sub setup_displayable_columns {
412   my ($self) = @_;
413
414   $self->SUPER::setup_displayable_columns;
415   $self->add_cvar_columns_to_displayable_columns;
416
417   $self->add_displayable_columns({ name => 'bin',                description => $::locale->text('Bin')                                                  },
418                                  { name => 'buchungsgruppen_id', description => $::locale->text('Buchungsgruppe (database ID)')                         },
419                                  { name => 'buchungsgruppe',     description => $::locale->text('Buchungsgruppe (name)')                                },
420                                  { name => 'description',        description => $::locale->text('Description')                                          },
421                                  { name => 'drawing',            description => $::locale->text('Drawing')                                              },
422                                  { name => 'ean',                description => $::locale->text('EAN')                                                  },
423                                  { name => 'formel',             description => $::locale->text('Formula')                                              },
424                                  { name => 'gv',                 description => $::locale->text('Business Volume')                                      },
425                                  { name => 'has_sernumber',      description => $::locale->text('Has serial number')                                    },
426                                  { name => 'image',              description => $::locale->text('Image')                                                },
427                                  { name => 'lastcost',           description => $::locale->text('Last Cost')                                            },
428                                  { name => 'listprice',          description => $::locale->text('List Price')                                           },
429                                  { name => 'make_X',             description => $::locale->text('Make (with X being a number)')                         },
430                                  { name => 'microfiche',         description => $::locale->text('Microfiche')                                           },
431                                  { name => 'model_X',            description => $::locale->text('Model (with X being a number)')                        },
432                                  { name => 'not_discountable',   description => $::locale->text('Not Discountable')                                     },
433                                  { name => 'notes',              description => $::locale->text('Notes')                                                },
434                                  { name => 'obsolete',           description => $::locale->text('Obsolete')                                             },
435                                  { name => 'onhand',             description => $::locale->text('On Hand')                                              },
436                                  { name => 'partnumber',         description => $::locale->text('Part Number')                                          },
437                                  { name => 'partsgroup_id',      description => $::locale->text('Partsgroup (database ID)')                             },
438                                  { name => 'partsgroup',         description => $::locale->text('Partsgroup (name)')                                    },
439                                  { name => 'payment_id',         description => $::locale->text('Payment terms (database ID)')                          },
440                                  { name => 'payment',            description => $::locale->text('Payment terms (name)')                                 },
441                                  { name => 'price_factor_id',    description => $::locale->text('Price factor (database ID)')                           },
442                                  { name => 'price_factor',       description => $::locale->text('Price factor (name)')                                  },
443                                  { name => 'rop',                description => $::locale->text('ROP')                                                  },
444                                  { name => 'sellprice',          description => $::locale->text('Sellprice')                                            },
445                                  { name => 'shop',               description => $::locale->text('Shopartikel')                                          },
446                                  { name => 'type',               description => $::locale->text('Article type (see below)')                             },
447                                  { name => 'unit',               description => $::locale->text('Unit (if missing or empty default unit will be used)') },
448                                  { name => 've',                 description => $::locale->text('Verrechnungseinheit')                                  },
449                                  { name => 'weight',             description => $::locale->text('Weight')                                               },
450                                 );
451
452   foreach my $language (@{ $self->all_languages }) {
453     $self->add_displayable_columns({ name        => 'description_' . $language->article_code,
454                                      description => $::locale->text('Description (translation for #1)', $language->description) },
455                                    { name        => 'notes_' . $language->article_code,
456                                      description => $::locale->text('Notes (translation for #1)', $language->description) });
457   }
458
459   my $idx = 0;
460   foreach my $pricegroup (@{ $self->all_pricegroups }) {
461     $idx++;
462     $self->add_displayable_columns({ name        => 'pricegroup_' . $idx,
463                                      description => $::locale->text("Sellprice for price group '#1'", $pricegroup->pricegroup) });
464   }
465 }
466
467 1;