Leistungsdatum: Order-Controller
[kivitendo-erp.git] / SL / Controller / CsvImport / CustomerVendor.pm
1 package SL::Controller::CsvImport::CustomerVendor;
2
3 use strict;
4
5 use SL::Helper::Csv;
6 use SL::Controller::CsvImport::Helper::Consistency;
7 use SL::DB::Business;
8 use SL::DB::CustomVariable;
9 use SL::DB::CustomVariableConfig;
10 use SL::DB::Employee;
11 use SL::DB::PaymentTerm;
12 use SL::TransNumber;
13
14 use parent qw(SL::Controller::CsvImport::Base);
15
16 use Rose::Object::MakeMethods::Generic
17 (
18  'scalar --get_set_init' => [ qw(table languages_by businesses_by salesmen_by) ],
19 );
20
21 sub set_profile_defaults {
22   my ($self) = @_;
23   $self->controller->profile->_set_defaults(table => 'customer');
24 };
25
26 sub init_table {
27   my ($self) = @_;
28   $self->table($self->controller->profile->get('table') eq 'customer' ? 'customer' : 'vendor');
29 }
30
31 sub init_class {
32   my ($self) = @_;
33   $self->class('SL::DB::' . ucfirst($self->table));
34 }
35
36 sub init_all_cvar_configs {
37   my ($self) = @_;
38
39   return SL::DB::Manager::CustomVariableConfig->get_all(where => [ module => 'CT' ]);
40 }
41
42 sub init_businesses_by {
43   my ($self) = @_;
44
45   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ SL::DB::Manager::Business->get_all } } ) } qw(id description) };
46 }
47
48 sub init_languages_by {
49   my ($self) = @_;
50
51   return { map { my $col = $_; ( $col => { map { ( $_->$col => $_ ) } @{ $self->all_languages } } ) } qw(id description article_code) };
52 }
53
54 sub init_salesmen_by {
55   my ($self) = @_;
56
57   return { map { my $col = $_; ( $col => { map { ( lc($_->$col) => $_ ) } @{ SL::DB::Manager::Employee->get_all } } ) } qw(id name login) };
58 }
59
60 sub check_objects {
61   my ($self) = @_;
62
63   $self->controller->track_progress(phase => 'building data', progress => 0);
64
65   my $vc            = $self->controller->profile->get('table');
66   my $update_policy = $self->controller->profile->get('update_policy') || 'update_existing';
67   my $numbercolumn  = "${vc}number";
68   my %vcs_by_number = map { ( $_->$numbercolumn => $_ ) } @{ $self->existing_objects };
69   my $methods       = $self->controller->headers->{methods};
70
71   my $i;
72   my $num_data = scalar @{ $self->controller->data };
73   foreach my $entry (@{ $self->controller->data }) {
74     $self->controller->track_progress(progress => $i/$num_data * 100) if $i % 100 == 0;
75     my $object = $entry->{object};
76
77     $self->check_name($entry);
78     $self->check_language($entry);
79     $self->check_business($entry);
80     $self->check_payment($entry);
81     $self->check_delivery_term($entry);
82     $self->check_taxzone($entry,  take_default => 1);
83     $self->check_currency($entry, take_default => 1);
84     $self->check_salesman($entry);
85     $self->handle_cvars($entry);
86
87     next if @{ $entry->{errors} };
88
89     my @cleaned_fields = $self->clean_fields(qr{[\r\n]}, $object, qw(name department_1 department_2 street zipcode city country gln contact phone fax homepage email cc bcc
90                                                                      taxnumber account_number bank_code bank username greeting taxzone));
91
92     push @{ $entry->{information} }, $::locale->text('Illegal characters have been removed from the following fields: #1', join(', ', @cleaned_fields))
93       if @cleaned_fields;
94
95     my $existing_vc = $vcs_by_number{ $object->$numbercolumn };
96     if (!$existing_vc) {
97       $vcs_by_number{ $object->$numbercolumn } = $object if $object->$numbercolumn;
98
99     } elsif ($update_policy eq 'skip') {
100       push(@{$entry->{errors}}, $::locale->text('Skipping due to existing entry in database'));
101
102     } elsif ($update_policy eq 'update_existing') {
103       # Update existing customer/vendor records.
104       $entry->{object_to_save} = $existing_vc;
105
106       $existing_vc->$_( $entry->{object}->$_ ) for @{ $methods }, keys %{ $self->clone_methods };
107
108       $self->handle_cvars($entry);
109       $existing_vc->custom_variables($entry->{object}->custom_variables);
110
111       push @{ $entry->{information} }, $::locale->text('Updating existing entry in database');
112
113     } else {
114       $object->$numbercolumn('####');
115     }
116   } continue {
117     $i++;
118   }
119
120   $self->add_columns(map { "${_}_id" } grep { exists $self->controller->data->[0]->{raw_data}->{$_} } qw(language business payment delivery_term taxzone));
121   $self->add_cvar_raw_data_columns;
122 }
123
124 sub get_duplicate_check_fields {
125   return {
126     name => {
127       label     => $::locale->text('Customer Name'),
128       default   => 1,
129       maker     => sub {
130         my $name = shift->name;
131         $name =~ s/[\s,\.\-]//g;
132         return $name;
133       }
134     },
135   };
136 }
137
138 sub check_name {
139   my ($self, $entry) = @_;
140
141   my $name =  $entry->{object}->name;
142   $name    =~ s/^\s+//;
143   $name    =~ s/\s+$//;
144
145   return 1 if $name;
146
147   push @{ $entry->{errors} }, $::locale->text('Error: Name missing');
148   return 0;
149 }
150
151 sub check_language {
152   my ($self, $entry) = @_;
153
154   my $object = $entry->{object};
155
156   # Check whether or not language ID is valid.
157   if ($object->language_id && !$self->languages_by->{id}->{ $object->language_id }) {
158     push @{ $entry->{errors} }, $::locale->text('Error: Invalid language');
159     return 0;
160   }
161
162   # Map name to ID if given.
163   if (!$object->language_id && $entry->{raw_data}->{language}) {
164     my $language = $self->languages_by->{description}->{  $entry->{raw_data}->{language} }
165                 || $self->languages_by->{article_code}->{ $entry->{raw_data}->{language} };
166
167     if (!$language) {
168       push @{ $entry->{errors} }, $::locale->text('Error: Invalid language');
169       return 0;
170     }
171
172     $object->language_id($language->id);
173
174     # register language_id for method copying later
175     $self->clone_methods->{language_id} = 1;
176   }
177
178   return 1;
179 }
180
181 sub check_business {
182   my ($self, $entry) = @_;
183
184   my $object = $entry->{object};
185
186   # Check whether or not business ID is valid.
187   if ($object->business_id && !$self->businesses_by->{id}->{ $object->business_id }) {
188     push @{ $entry->{errors} }, $::locale->text('Error: Invalid business');
189     return 0;
190   }
191
192   # Map name to ID if given.
193   if (!$object->business_id && $entry->{raw_data}->{business}) {
194     my $business = $self->businesses_by->{description}->{ $entry->{raw_data}->{business} };
195
196     if (!$business) {
197       push @{ $entry->{errors} }, $::locale->text('Error: Invalid business');
198       return 0;
199     }
200
201     $object->business_id($business->id);
202
203     # register business_id for method copying later
204     $self->clone_methods->{business_id} = 1;
205   }
206
207   return 1;
208 }
209
210 sub check_salesman {
211   my ($self, $entry) = @_;
212
213   my $object = $entry->{object};
214
215   # Check whether or not salesman ID is valid.
216   if ($object->salesman_id && !$self->salesmen_by->{id}->{ $object->salesman_id }) {
217     push @{ $entry->{errors} }, $::locale->text('Error: Invalid salesman');
218     return 0;
219   }
220
221   # Map name to ID if given.
222   if (!$object->salesman_id && ($entry->{raw_data}->{salesman} || $entry->{raw_data}->{salesman_login})) {
223     my $salesman = $self->salesmen_by->{name} ->{ lc($entry->{raw_data}->{salesman}) }
224                 // $self->salesmen_by->{login}->{ lc($entry->{raw_data}->{salesman_login}) };
225
226     if (!$salesman) {
227       push @{ $entry->{errors} }, $::locale->text('Error: Invalid salesman');
228       return 0;
229     }
230
231     $object->salesman_id($salesman->id);
232
233     # register salesman_id for method copying later
234     $self->clone_methods->{salesman_id} = 1;
235   }
236
237   return 1;
238 }
239
240 sub save_objects {
241   my ($self, %params) = @_;
242
243   my $numbercolumn   = $self->table . 'number';
244   my $with_number    = [ grep { $_->{object}->$numbercolumn ne '####' } @{ $self->controller->data } ];
245   my $without_number = [ grep { $_->{object}->$numbercolumn eq '####' } @{ $self->controller->data } ];
246
247   foreach my $entry (@{$with_number}, @{$without_number}) {
248     my $object = $entry->{object};
249
250     my $number = SL::TransNumber->new(type        => $self->table(),
251                                       number      => $object->$numbercolumn(),
252                                       business_id => $object->business_id(),
253                                       save        => 1);
254
255     if ( $object->$numbercolumn eq '####' || !$number->is_unique() ) {
256       $object->$numbercolumn($number->create_unique());
257     }
258   }
259
260   $self->SUPER::save_objects(data => $with_number);
261   $self->SUPER::save_objects(data => $without_number);
262 }
263
264 sub init_profile {
265   my ($self) = @_;
266
267   my $profile = $self->SUPER::init_profile;
268   delete @{$profile}{qw(business datevexport language payment delivery_term taxincluded terms)};
269   delete @{$profile}{qw(salesman salesman_id salesman_login)} if $::instance_conf->get_vertreter;
270
271   return $profile;
272 }
273
274 sub setup_displayable_columns {
275   my ($self) = @_;
276
277   $self->SUPER::setup_displayable_columns;
278   $self->add_cvar_columns_to_displayable_columns;
279
280   $self->add_displayable_columns({ name => 'account_number',    description => $::locale->text('Account Number')                  },
281                                  { name => 'bank',              description => $::locale->text('Bank')                            },
282                                  { name => 'bank_code',         description => $::locale->text('Bank Code')                       },
283                                  { name => 'bcc',               description => $::locale->text('Bcc')                             },
284                                  { name => 'bic',               description => $::locale->text('BIC')                             },
285                                  { name => 'business_id',       description => $::locale->text('Business type (database ID)')     },
286                                  { name => 'business',          description => $::locale->text('Business type (name)')            },
287                                  { name => 'c_vendor_id',       description => $::locale->text('our vendor number at customer')   },
288                                  { name => 'cc',                description => $::locale->text('Cc')                              },
289                                  { name => 'city',              description => $::locale->text('City')                            },
290                                  { name => 'contact',           description => $::locale->text('Contact')                         },
291                                  { name => 'country',           description => $::locale->text('Country')                         },
292                                  { name => 'creditlimit',       description => $::locale->text('Credit Limit')                    },
293                                  { name => 'currency',          description => $::locale->text('Currency')                        },
294                                  { name => 'currency_id',       description => $::locale->text('Currency (database ID)')          },
295                                  { name => 'customernumber',    description => $::locale->text('Customer Number')                 },
296                                  { name => 'department_1',      description => $::locale->text('Department 1')                    },
297                                  { name => 'department_2',      description => $::locale->text('Department 2')                    },
298                                  { name => 'delivery_term_id',  description => $::locale->text('Delivery terms (database ID)')    },
299                                  { name => 'delivery_term',     description => $::locale->text('Delivery terms (name)')           },
300                                  { name => 'direct_debit',      description => $::locale->text('direct debit')                    },
301                                  { name => 'discount',          description => $::locale->text('Discount')                        },
302                                  { name => 'email',             description => $::locale->text('E-mail')                          },
303                                  { name => 'fax',               description => $::locale->text('Fax')                             },
304                                  { name => 'gln',               description => $::locale->text('GLN')                             },
305                                  { name => 'greeting',          description => $::locale->text('Greeting')                        },
306                                  { name => 'homepage',          description => $::locale->text('Homepage')                        },
307                                  { name => 'iban',              description => $::locale->text('IBAN')                            },
308                                  { name => 'pricegroup_id',     description => $::locale->text('Price group (database ID)')       },
309                                  { name => 'language_id',       description => $::locale->text('Language (database ID)')          },
310                                  { name => 'language',          description => $::locale->text('Language (name)')                 },
311                                  { name => 'name',              description => $::locale->text('Name')                            },
312                                  { name => 'notes',             description => $::locale->text('Notes')                           },
313                                  { name => 'obsolete',          description => $::locale->text('Obsolete')                        },
314                                  { name => 'payment_id',        description => $::locale->text('Payment terms (database ID)')     },
315                                  { name => 'payment',           description => $::locale->text('Payment terms (name)')            },
316                                  { name => 'phone',             description => $::locale->text('Phone')                           },
317                                  { name => 'street',            description => $::locale->text('Street')                          },
318                                  { name => 'taxnumber',         description => $::locale->text('Tax Number / SSN')                },
319                                  { name => 'taxzone',           description => $::locale->text('Tax zone (description)')          },
320                                  { name => 'taxzone_id',        description => $::locale->text('Tax zone (database ID)')          },
321                                  { name => 'user_password',     description => $::locale->text('Password')                        },
322                                  { name => 'username',          description => $::locale->text('Username')                        },
323                                  { name => 'ustid',             description => $::locale->text('sales tax identification number') },
324                                  { name => 'zipcode',           description => $::locale->text('Zipcode')                         },
325                                 );
326
327   if (!$::instance_conf->get_vertreter) {
328     $self->add_displayable_columns({ name => 'salesman',       description => $::locale->text('Salesman') },
329                                    { name => 'salesman_id',    description => $::locale->text('Salesman (database ID)') },
330                                    { name => 'salesman_login', description => $::locale->text('Salesman (login)') });
331   }
332 }
333
334 # TODO:
335 # salesman_id -- Kunden mit Typ 'Verkäufer', falls Vertreter-Modus an ist, ansonsten Employees
336
337 1;