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