f9e2515786c1e3b5de937ca154291d5105cb6344
[kivitendo-erp.git] / SL / Controller / CustomerVendor.pm
1 package SL::Controller::CustomerVendor;
2
3 use strict;
4 use parent qw(SL::Controller::Base);
5
6 use List::MoreUtils qw(any);
7
8 use SL::JSON;
9 use SL::DBUtils;
10 use SL::Helper::Flash;
11 use SL::Locale::String;
12 use SL::Util qw(trim);
13 use SL::VATIDNr;
14 use SL::Webdav;
15 use SL::ZUGFeRD;
16 use SL::Controller::Helper::GetModels;
17 use SL::Controller::Helper::ReportGenerator;
18 use SL::Controller::Helper::ParseFilter;
19
20 use SL::DB::Customer;
21 use SL::DB::Vendor;
22 use SL::DB::Business;
23 use SL::DB::ContactDepartment;
24 use SL::DB::ContactTitle;
25 use SL::DB::Employee;
26 use SL::DB::Greeting;
27 use SL::DB::Language;
28 use SL::DB::TaxZone;
29 use SL::DB::Note;
30 use SL::DB::PaymentTerm;
31 use SL::DB::Pricegroup;
32 use SL::DB::Price;
33 use SL::DB::Contact;
34 use SL::DB::FollowUp;
35 use SL::DB::FollowUpLink;
36 use SL::DB::History;
37 use SL::DB::Currency;
38 use SL::DB::Invoice;
39 use SL::DB::PurchaseInvoice;
40 use SL::DB::Order;
41
42 use Data::Dumper;
43
44 use Rose::Object::MakeMethods::Generic (
45   scalar                  => [ qw(user_has_edit_rights) ],
46   'scalar --get_set_init' => [ qw(customer_models vendor_models zugferd_settings) ],
47 );
48
49 # safety
50 __PACKAGE__->run_before(
51   '_instantiate_args',
52   only => [
53     'save',
54     'save_and_ap_transaction',
55     'save_and_ar_transaction',
56     'save_and_close',
57     'save_and_invoice',
58     'save_and_order',
59     'save_and_quotation',
60     'save_and_rfq',
61     'delete',
62     'delete_contact',
63     'delete_shipto',
64     'delete_additional_billing_address',
65   ]
66 );
67
68 __PACKAGE__->run_before(
69   '_load_customer_vendor',
70   only => [
71     'edit',
72     'show',
73     'update',
74     'ajaj_get_shipto',
75     'ajaj_get_additional_billing_address',
76     'ajaj_get_contact',
77     'ajax_list_prices',
78   ]
79 );
80
81 # make sure this comes after _load_customer_vendor
82 __PACKAGE__->run_before('_check_auth');
83
84 __PACKAGE__->run_before(
85   '_create_customer_vendor',
86   only => [
87     'add',
88   ]
89 );
90
91 __PACKAGE__->run_before('normalize_name');
92
93 my @ADDITIONAL_BILLING_ADDRESS_COLUMNS = qw(name department_1 department_2 contact street zipcode city country gln email phone fax default_address);
94
95 sub action_add {
96   my ($self) = @_;
97
98   $self->_pre_render();
99
100   if ($self->{cv}->is_customer) {
101     $self->{cv}->assign_attributes(hourly_rate => $::instance_conf->get_customer_hourly_rate);
102     $self->{cv}->salesman_id(SL::DB::Manager::Employee->current->id) if !$::auth->assert('customer_vendor_all_edit', 1);
103   }
104
105   $self->render(
106     'customer_vendor/form',
107     title => ($self->is_vendor() ? $::locale->text('Add Vendor') : $::locale->text('Add Customer')),
108     %{$self->{template_args}}
109   );
110 }
111
112 sub action_edit {
113   my ($self) = @_;
114
115   $self->_pre_render();
116   $self->render(
117     'customer_vendor/form',
118     title => ($self->is_vendor() ? $::locale->text('Edit Vendor') : $::locale->text('Edit Customer')),
119     %{$self->{template_args}}
120   );
121 }
122
123 sub action_show {
124   my ($self) = @_;
125
126   if ($::request->type eq 'json') {
127     my $cv_hash;
128     if (!$self->{cv}) {
129       # TODO error
130     } else {
131       $cv_hash          = $self->{cv}->as_tree;
132       $cv_hash->{cvars} = $self->{cv}->cvar_as_hashref;
133     }
134
135     $self->render(\ SL::JSON::to_json($cv_hash), { layout => 0, type => 'json', process => 0 });
136   }
137 }
138
139 sub _check_ustid_taxnumber_unique {
140   my ($self) = @_;
141
142   my %cfg;
143   if ($self->is_vendor()) {
144     %cfg = (should_check  => $::instance_conf->get_vendor_ustid_taxnummer_unique,
145             manager_class => 'SL::DB::Manager::Vendor',
146             err_ustid     => t8('A vendor with the same VAT ID already exists.'),
147             err_taxnumber => t8('A vendor with the same taxnumber already exists.'),
148     );
149
150   } elsif ($self->is_customer()) {
151     %cfg = (should_check  => $::instance_conf->get_customer_ustid_taxnummer_unique,
152             manager_class => 'SL::DB::Manager::Customer',
153             err_ustid     => t8('A customer with the same VAT ID already exists.'),
154             err_taxnumber => t8('A customer with the same taxnumber already exists.'),
155     );
156
157   } else {
158     return;
159   }
160
161   my @errors;
162
163   if ($cfg{should_check}) {
164     my $do_clean_taxnumber = sub { my $n = $_[0]; $n //= ''; $n =~ s{[[:space:].-]+}{}g; return $n};
165
166     my $clean_ustid     = SL::VATIDNr->clean($self->{cv}->ustid);
167     my $clean_taxnumber = $do_clean_taxnumber->($self->{cv}->taxnumber);
168
169     if (!($clean_ustid || $clean_taxnumber)) {
170       return t8('VAT ID and/or taxnumber must be given.');
171
172     } else {
173       my $clean_number = $clean_ustid;
174       if ($clean_number) {
175         my $entries = $cfg{manager_class}->get_all(query => ['!id' => $self->{cv}->id, '!ustid' => undef, '!ustid' => ''], select => ['ustid'], distinct => 1);
176         if (any { $clean_number eq SL::VATIDNr->clean($_->ustid) } @$entries) {
177           push @errors, $cfg{err_ustid};
178         }
179       }
180
181       $clean_number = $clean_taxnumber;
182       if ($clean_number) {
183         my $entries = $cfg{manager_class}->get_all(query => ['!id' => $self->{cv}->id, '!taxnumber' => undef, '!taxnumber' => ''], select => ['taxnumber'], distinct => 1);
184         if (any { $clean_number eq $do_clean_taxnumber->($_->taxnumber) } @$entries) {
185           push @errors, $cfg{err_taxnumber};
186         }
187       }
188     }
189   }
190
191   return join "\n", @errors if @errors;
192   return;
193 }
194
195 sub _save {
196   my ($self) = @_;
197
198   my @errors = $self->{cv}->validate;
199   if (@errors) {
200     flash('error', @errors);
201     $self->_pre_render();
202     $self->render(
203       'customer_vendor/form',
204       title => ($self->is_vendor() ? t8('Edit Vendor') : t8('Edit Customer')),
205       %{$self->{template_args}}
206     );
207     $::dispatcher->end_request;
208   }
209
210   $self->{cv}->greeting(trim $self->{cv}->greeting);
211   my $save_greeting           = $self->{cv}->greeting
212     && $::instance_conf->get_vc_greetings_use_textfield
213     && SL::DB::Manager::Greeting->get_all_count(where => [description => $self->{cv}->greeting]) == 0;
214
215   $self->{contact}->cp_title(trim($self->{contact}->cp_title));
216   my $save_contact_title      = $self->{contact}->cp_title
217     && $::instance_conf->get_contact_titles_use_textfield
218     && SL::DB::Manager::ContactTitle->get_all_count(where => [description => $self->{contact}->cp_title]) == 0;
219
220   $self->{contact}->cp_abteilung(trim($self->{contact}->cp_abteilung));
221   my $save_contact_department = $self->{contact}->cp_abteilung
222     && $::instance_conf->get_contact_departments_use_textfield
223     && SL::DB::Manager::ContactDepartment->get_all_count(where => [description => $self->{contact}->cp_abteilung]) == 0;
224
225   my $db = $self->{cv}->db;
226
227   $db->with_transaction(sub {
228     my $cvs_by_nr;
229     if ( $self->is_vendor() ) {
230       if ( $self->{cv}->vendornumber ) {
231         $cvs_by_nr = SL::DB::Manager::Vendor->get_all(query => [vendornumber => $self->{cv}->vendornumber]);
232       }
233     } else {
234       if ( $self->{cv}->customernumber ) {
235         $cvs_by_nr = SL::DB::Manager::Customer->get_all(query => [customernumber => $self->{cv}->customernumber]);
236       }
237     }
238
239     foreach my $entry (@{$cvs_by_nr}) {
240       if( $entry->id != $self->{cv}->id ) {
241         my $msg =
242           $self->is_vendor() ? $::locale->text('This vendor number is already in use.') : $::locale->text('This customer number is already in use.');
243
244         $::form->error($msg);
245       }
246     }
247
248     my $ustid_taxnumber_error = $self->_check_ustid_taxnumber_unique;
249     $::form->error($ustid_taxnumber_error) if $ustid_taxnumber_error;
250
251     $self->{cv}->save(cascade => 1);
252
253     SL::DB::Greeting->new(description => $self->{cv}->greeting)->save if $save_greeting;
254
255     $self->{contact}->cp_cv_id($self->{cv}->id);
256     if( $self->{contact}->cp_name ne '' || $self->{contact}->cp_givenname ne '' ) {
257       SL::DB::ContactTitle     ->new(description => $self->{contact}->cp_title)    ->save if $save_contact_title;
258       SL::DB::ContactDepartment->new(description => $self->{contact}->cp_abteilung)->save if $save_contact_department;
259
260       $self->{contact}->save(cascade => 1);
261     }
262
263     if( $self->{note}->subject ne '' && $self->{note}->body ne '' ) {
264
265       if ( !$self->{note_followup}->follow_up_date ) {
266         $::form->error($::locale->text('Date missing!'));
267       }
268
269       $self->{note}->trans_id($self->{cv}->id);
270       $self->{note}->save();
271
272       $self->{note_followup}->save();
273
274       $self->{note_followup_link}->follow_up_id($self->{note_followup}->id);
275       $self->{note_followup_link}->trans_id($self->{cv}->id);
276       $self->{note_followup_link}->save();
277
278       SL::Helper::Flash::flash_later('info', $::locale->text('Follow-Up saved.'));
279     }
280
281     $self->{shipto}->trans_id($self->{cv}->id);
282     if(any { $self->{shipto}->$_ ne '' } qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax shiptoemail)) {
283       $self->{shipto}->save(cascade => 1);
284     }
285
286     if ($self->is_customer && any { $self->{additional_billing_address}->$_ ne '' } grep { $_ ne 'default_address' } @ADDITIONAL_BILLING_ADDRESS_COLUMNS) {
287       $self->{additional_billing_address}->customer_id($self->{cv}->id);
288       $self->{additional_billing_address}->save(cascade => 1);
289
290       # Make sure only one address per customer has "default address" set.
291       if ($self->{additional_billing_address}->default_address) {
292         SL::DB::Manager::AdditionalBillingAddress->update_all(
293           set   => { default_address => 0, },
294           where => [
295             customer_id => $self->{cv}->id,
296             '!id'       => $self->{additional_billing_address}->id,
297           ]);
298       }
299     }
300
301     my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
302     SL::DB::History->new(
303       trans_id => $self->{cv}->id,
304       snumbers => $snumbers,
305       employee_id => SL::DB::Manager::Employee->current->id,
306       addition => 'SAVED',
307     )->save();
308
309     if ( $::form->{delete_notes} ) {
310       foreach my $note_id (@{ $::form->{delete_notes} }) {
311         my $note = SL::DB::Note->new(id => $note_id)->load();
312         if ( $note->follow_up ) {
313           if ( $note->follow_up->follow_up_link ) {
314             $note->follow_up->follow_up_link->delete(cascade => 'delete');
315           }
316           $note->follow_up->delete(cascade => 'delete');
317         }
318         $note->delete(cascade => 'delete');
319       }
320     }
321
322     1;
323   }) || die($db->error);
324
325 }
326
327 sub action_save {
328   my ($self) = @_;
329
330   $self->_save();
331
332   my @redirect_params = (
333     action => 'edit',
334     id     => $self->{cv}->id,
335     db     => ($self->is_vendor() ? 'vendor' : 'customer'),
336   );
337
338   if ( $self->{contact}->cp_id ) {
339     push(@redirect_params, contact_id => $self->{contact}->cp_id);
340   }
341
342   if ( $self->{shipto}->shipto_id ) {
343     push(@redirect_params, shipto_id => $self->{shipto}->shipto_id);
344   }
345
346   if ( $self->is_customer && $self->{additional_billing_address}->id ) {
347     push(@redirect_params, additional_billing_address_id => $self->{additional_billing_address}->id);
348   }
349
350   $self->redirect_to(@redirect_params);
351 }
352
353 sub action_save_and_close {
354   my ($self) = @_;
355
356   $self->_save();
357
358   my $msg = $self->is_vendor() ? $::locale->text('Vendor saved') : $::locale->text('Customer saved');
359   $::form->redirect($msg);
360 }
361
362 sub _transaction {
363   my ($self, $script) = @_;
364
365   $::auth->assert('gl_transactions | ap_transactions | ar_transactions'.
366                     '| invoice_edit         | vendor_invoice_edit | ' .
367                  ' request_quotation_edit | sales_quotation_edit | sales_order_edit    | purchase_order_edit');
368
369   $self->_save();
370
371   my $name = $::form->escape($self->{cv}->name, 1);
372   my $db = $self->is_vendor() ? 'vendor' : 'customer';
373   my $action = 'add';
374
375   if ($::instance_conf->get_feature_experimental_order && 'oe.pl' eq $script) {
376     $script = 'controller.pl';
377     $action = 'Order/' . $action;
378   }
379
380   my $url = $self->url_for(
381     controller => $script,
382     action     => $action,
383     vc         => $db,
384     $db .'_id' => $self->{cv}->id,
385     $db        => $name,
386     type       => $::form->{type},
387     callback   => $::form->{callback},
388   );
389
390   print $::form->redirect_header($url);
391 }
392
393 sub action_save_and_ar_transaction {
394   my ($self) = @_;
395
396   $main::auth->assert('ar_transactions');
397
398   $self->_transaction('ar.pl');
399 }
400
401 sub action_save_and_ap_transaction {
402   my ($self) = @_;
403
404   $main::auth->assert('ap_transactions');
405
406   $self->_transaction('ap.pl');
407 }
408
409 sub action_save_and_invoice {
410   my ($self) = @_;
411
412   if ( $self->is_vendor() ) {
413     $::auth->assert('vendor_invoice_edit');
414   } else {
415     $::auth->assert('invoice_edit');
416   }
417
418   $::form->{type} = 'invoice';
419   $self->_transaction($self->is_vendor() ? 'ir.pl' : 'is.pl');
420 }
421
422 sub action_save_and_order {
423   my ($self) = @_;
424
425   if ( $self->is_vendor() ) {
426     $::auth->assert('purchase_order_edit');
427   } else {
428     $::auth->assert('sales_order_edit');
429   }
430
431   $::form->{type} = $self->is_vendor() ? 'purchase_order' : 'sales_order';
432   $self->_transaction('oe.pl');
433 }
434
435 sub action_save_and_rfq {
436   my ($self) = @_;
437
438   $::auth->assert('request_quotation_edit');
439
440   $::form->{type} = 'request_quotation';
441   $self->_transaction('oe.pl');
442 }
443
444 sub action_save_and_quotation {
445   my ($self) = @_;
446
447   $::auth->assert('sales_quotation_edit');
448
449   $::form->{type} = 'sales_quotation';
450   $self->_transaction('oe.pl');
451 }
452
453 sub action_delete {
454   my ($self) = @_;
455
456   my $db = $self->{cv}->db;
457
458   if( !$self->is_orphaned() ) {
459     $self->action_edit();
460   } else {
461
462     $db->with_transaction(sub {
463       $self->{cv}->delete(cascade => 1);
464
465       my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
466       SL::DB::History->new(
467         trans_id => $self->{cv}->id,
468         snumbers => $snumbers,
469         employee_id => SL::DB::Manager::Employee->current->id,
470         addition => 'DELETED',
471       )->save();
472     }) || die($db->error);
473
474     my $msg = $self->is_vendor() ? $::locale->text('Vendor deleted!') : $::locale->text('Customer deleted!');
475     $::form->redirect($msg);
476   }
477
478 }
479
480
481 sub action_delete_contact {
482   my ($self) = @_;
483
484   my $db = $self->{contact}->db;
485
486   if ( !$self->{contact}->cp_id ) {
487     SL::Helper::Flash::flash('error', $::locale->text('No contact selected to delete'));
488   } else {
489
490     $db->with_transaction(sub {
491       if ( $self->{contact}->used ) {
492         $self->{contact}->detach();
493         $self->{contact}->save();
494         SL::Helper::Flash::flash('info', $::locale->text('Contact is in use and was flagged invalid.'));
495       } else {
496         $self->{contact}->delete(cascade => 1);
497         SL::Helper::Flash::flash('info', $::locale->text('Contact deleted.'));
498       }
499
500       1;
501     }) || die($db->error);
502
503     $self->{contact} = $self->_new_contact_object;
504   }
505
506   $self->action_edit();
507 }
508
509 sub action_delete_shipto {
510   my ($self) = @_;
511
512   my $db = $self->{shipto}->db;
513
514   if ( !$self->{shipto}->shipto_id ) {
515     SL::Helper::Flash::flash('error', $::locale->text('No shipto selected to delete'));
516   } else {
517
518     $db->with_transaction(sub {
519       if ( $self->{shipto}->used ) {
520         $self->{shipto}->detach();
521         $self->{shipto}->save(cascade => 1);
522         SL::Helper::Flash::flash('info', $::locale->text('Shipto is in use and was flagged invalid.'));
523       } else {
524         $self->{shipto}->delete(cascade => 1);
525         SL::Helper::Flash::flash('info', $::locale->text('Shipto deleted.'));
526       }
527
528       1;
529     }) || die($db->error);
530
531     $self->{shipto} = SL::DB::Shipto->new();
532   }
533
534   $self->action_edit();
535 }
536
537 sub action_delete_additional_billing_address {
538   my ($self) = @_;
539
540   my $db = $self->{additional_billing_address}->db;
541
542   if ( !$self->{additional_billing_address}->id ) {
543     SL::Helper::Flash::flash('error', $::locale->text('No address selected to delete'));
544   } else {
545     $db->with_transaction(sub {
546       if ( $self->{additional_billing_address}->used ) {
547         $self->{additional_billing_address}->detach;
548         $self->{additional_billing_address}->save(cascade => 1);
549         SL::Helper::Flash::flash('info', $::locale->text('Address is in use and was flagged invalid.'));
550       } else {
551         $self->{additional_billing_address}->delete(cascade => 1);
552         SL::Helper::Flash::flash('info', $::locale->text('Address deleted.'));
553       }
554
555       1;
556     }) || die($db->error);
557
558     $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new;
559   }
560
561   $self->action_edit;
562 }
563
564 sub action_search {
565   my ($self) = @_;
566
567   my @url_params = (
568     controller => 'ct.pl',
569     action => 'search',
570     db => $self->is_vendor() ? 'vendor' : 'customer',
571   );
572
573   if ( $::form->{callback} ) {
574     push(@url_params, callback => $::form->{callback});
575   }
576
577   $self->redirect_to(@url_params);
578 }
579
580
581 sub action_search_contact {
582   my ($self) = @_;
583
584   my $url = 'ct.pl?action=search_contact&db=customer';
585
586   if ( $::form->{callback} ) {
587     $url .= '&callback='. $::form->escape($::form->{callback});
588   }
589
590   print $::form->redirect_header($url);
591 }
592
593 sub action_get_delivery {
594   my ($self) = @_;
595
596   $::auth->assert('sales_all_edit')    if $self->is_customer();
597   $::auth->assert('purchase_all_edit') if $self->is_vendor();
598
599   my $dbh = $::form->get_standard_dbh();
600
601   my ($arap, $db, $qty_sign);
602   if ( $self->is_vendor() ) {
603     $arap = 'ap';
604     $db = 'vendor';
605     $qty_sign = ' * -1 AS qty';
606   } else {
607     $arap = 'ar';
608     $db = 'customer';
609     $qty_sign = '';
610   }
611
612   my $where = ' WHERE 1=1';
613   my @values;
614
615   if ( !$self->is_vendor() && $::form->{shipto_id} && $::form->{shipto_id} ne 'all' ) {
616     $where .= " AND ${arap}.shipto_id = ?";
617     push(@values, $::form->{shipto_id});
618   } else {
619     $where .= " AND ${arap}.${db}_id = ?";
620     push(@values, $::form->{id});
621   }
622
623   if ( $::form->{delivery_from} ) {
624     $where .= " AND ${arap}.transdate >= ?";
625     push(@values, conv_date($::form->{delivery_from}));
626   }
627
628   if ( $::form->{delivery_to} ) {
629     $where .= " AND ${arap}.transdate <= ?";
630     push(@values, conv_date($::form->{delivery_to}));
631   }
632
633   my $query =
634     "SELECT
635        s.shiptoname,
636        i.qty ${qty_sign},
637        ${arap}.id,
638        ${arap}.transdate,
639        ${arap}.invnumber,
640        ${arap}.ordnumber,
641        i.description,
642        i.unit,
643        i.sellprice,
644        oe.id AS oe_id,
645        invoice
646      FROM ${arap}
647
648      LEFT JOIN shipto s
649       ON ". ($arap eq 'ar' ? '(ar.shipto_id = s.shipto_id) ' : '(ap.id = s.trans_id) ') ."
650
651      LEFT JOIN invoice i
652        ON ${arap}.id = i.trans_id
653
654      LEFT JOIN parts p
655        ON p.id = i.parts_id
656
657      LEFT JOIN oe
658        ON (oe.ordnumber = ${arap}.ordnumber AND NOT ${arap}.ordnumber = ''
659            AND ". ($arap eq 'ar' ? 'oe.customer_id IS NOT NULL' : 'oe.vendor_id IS NOT NULL') ." )
660
661      ${where}
662      ORDER BY ${arap}.transdate DESC LIMIT 15";
663
664   $self->{delivery} = selectall_hashref_query($::form, $dbh, $query, @values);
665
666   $self->render('customer_vendor/get_delivery', { layout => 0 });
667 }
668
669 sub action_ajaj_get_shipto {
670   my ($self) = @_;
671
672   my $data = {};
673   $data->{shipto} = {
674     map(
675       {
676         my $name = 'shipto'. $_;
677         $name => $self->{shipto}->$name;
678       }
679       qw(_id name department_1 department_2 street zipcode city gln country contact phone fax email)
680     )
681   };
682
683   $data->{shipto_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{shipto}->cvars_by_config);
684
685   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
686 }
687
688 sub action_ajaj_get_additional_billing_address {
689   my ($self) = @_;
690
691   my $data = {
692     additional_billing_address => {
693       map { ($_ => $self->{additional_billing_address}->$_) } ('id', @ADDITIONAL_BILLING_ADDRESS_COLUMNS)
694     },
695   };
696
697   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
698 }
699
700 sub action_ajaj_get_contact {
701   my ($self) = @_;
702
703   my $data;
704
705   $data->{contact} = {
706     map(
707       {
708         my $name = 'cp_'. $_;
709
710         if ( $_ eq 'birthday' && $self->{contact}->$name ) {
711           $name => $self->{contact}->$name->to_lxoffice;
712         } else {
713           $name => $self->{contact}->$name;
714         }
715       }
716       qw(
717         id gender abteilung title position givenname name email phone1 phone2 fax mobile1 mobile2
718         satphone satfax project street zipcode city privatphone privatemail birthday main
719       )
720     )
721   };
722
723   $data->{contact_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{contact}->cvars_by_config);
724
725   # avoid two or more main_cp
726   my $has_main_cp = grep { $_->cp_main == 1 } @{ $self->{cv}->contacts };
727   $data->{contact}->{disable_cp_main} = 1 if ($has_main_cp && !$data->{contact}->{cp_main});
728
729   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
730 }
731
732 sub action_ajaj_autocomplete {
733   my ($self, %params) = @_;
734
735   my ($model, $manager, $number, $matches);
736
737   # first see if this is customer or vendor picking
738   if ($::form->{type} eq 'customer') {
739      $model   = $self->customer_models;
740      $manager = 'SL::DB::Manager::Customer';
741      $number  = 'customernumber';
742   } elsif ($::form->{type} eq 'vendor')  {
743      $model   = $self->vendor_models;
744      $manager = 'SL::DB::Manager::Vendor';
745      $number  = 'vendornumber';
746   } else {
747      die "unknown type $::form->{type}";
748   }
749
750   # if someone types something, and hits enter, assume he entered the full name.
751   # if something matches, treat that as the sole match
752   # unfortunately get_models can't do more than one per package atm, so we do it
753   # the oldfashioned way.
754   if ($::form->{prefer_exact}) {
755     my $exact_matches;
756     if (1 == scalar @{ $exact_matches = $manager->get_all(
757       query => [
758         obsolete => 0,
759         or => [
760           name    => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
761           $number => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
762         ]
763       ],
764       limit => 2,
765     ) }) {
766       $matches = $exact_matches;
767     }
768   }
769
770   $matches //= $model->get;
771
772   my @hashes = map {
773    +{
774      value       => $_->displayable_name,
775      label       => $_->displayable_name,
776      id          => $_->id,
777      $number     => $_->$number,
778      name        => $_->name,
779      type        => $::form->{type},
780      cvars       => { map { ($_->config->name => { value => $_->value_as_text, is_valid => $_->is_valid }) } @{ $_->cvars_by_config } },
781     }
782   } @{ $matches };
783
784   $self->render(\ SL::JSON::to_json(\@hashes), { layout => 0, type => 'json', process => 0 });
785 }
786
787 sub action_test_page {
788   $_[0]->render('customer_vendor/test_page');
789 }
790
791 sub action_ajax_list_prices {
792   my ($self, %params) = @_;
793
794   my $report   = SL::ReportGenerator->new(\%::myconfig, $::form);
795   my @columns  = qw(partnumber description price);
796   my @visible  = qw(partnumber description price);
797   my @sortable = qw(partnumber description price);
798
799   my %column_defs = (
800     partnumber  => { text => $::locale->text('Part Number'),      sub => sub { $_[0]->parts->partnumber  } },
801     description => { text => $::locale->text('Part Description'), sub => sub { $_[0]->parts->description } },
802     price       => { text => $::locale->text('Price'),            sub => sub { $::form->format_amount(\%::myconfig, $_[0]->price, 2) }, align => 'right' },
803   );
804
805   $::form->{sort_by}  ||= 'partnumber';
806   $::form->{sort_dir} //= 1;
807
808   for my $col (@sortable) {
809     $column_defs{$col}{link} = $self->url_for(
810       action   => 'ajax_list_prices',
811       callback => $::form->{callback},
812       db       => $::form->{db},
813       id       => $self->{cv}->id,
814       sort_by  => $col,
815       sort_dir => ($::form->{sort_by} eq $col ? 1 - $::form->{sort_dir} : $::form->{sort_dir})
816     );
817   }
818
819   map { $column_defs{$_}{visible} = 1 } @visible;
820
821   my $pricegroup;
822   $pricegroup = $self->{cv}->pricegroup->pricegroup if $self->{cv}->pricegroup;
823
824   $report->set_columns(%column_defs);
825   $report->set_column_order(@columns);
826   $report->set_options(allow_pdf_export => 0, allow_csv_export => 0);
827   $report->set_sort_indicator($::form->{sort_by}, $::form->{sort_dir});
828   $report->set_export_options(@{ $params{report_generator_export_options} || [] });
829   $report->set_options(
830     %{ $params{report_generator_options} || {} },
831     output_format        => 'HTML',
832     top_info_text        => $::locale->text('Pricegroup') . ': ' . $pricegroup,
833     title                => $::locale->text('Price List'),
834   );
835
836   my $sort_param = $::form->{sort_by} eq 'price'       ? 'price'             :
837                    $::form->{sort_by} eq 'description' ? 'parts.description' :
838                    'parts.partnumber';
839   $sort_param .= ' ' . ($::form->{sort_dir} ? 'ASC' : 'DESC');
840   my $prices = SL::DB::Manager::Price->get_all(where        => [ pricegroup_id => $self->{cv}->pricegroup_id ],
841                                                sort_by      => $sort_param,
842                                                with_objects => 'parts');
843
844   $self->report_generator_list_objects(report => $report, objects => $prices, layout => 0, header => 0);
845 }
846
847 sub is_vendor {
848   return $::form->{db} eq 'vendor';
849 }
850
851 sub is_customer {
852   return $::form->{db} eq 'customer';
853 }
854
855 sub is_orphaned {
856   my ($self) = @_;
857
858   if ( defined($self->{_is_orphaned}) ) {
859     return $self->{_is_orphaned};
860   }
861
862   my $arap      = $self->is_vendor ? 'ap' : 'ar';
863   my $num_args  = 3;
864
865   my $cv = $self->is_vendor ? 'vendor' : 'customer';
866
867   my $query =
868    'SELECT a.id
869     FROM '. $arap .' AS a
870     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
871     WHERE ct.id = ?
872
873     UNION
874
875     SELECT a.id
876     FROM oe a
877     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
878     WHERE ct.id = ?
879
880     UNION
881
882     SELECT a.id
883     FROM delivery_orders a
884     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
885     WHERE ct.id = ?';
886
887
888   if ( $self->is_vendor ) {
889     $query .=
890      ' UNION
891       SELECT 1 FROM makemodel mm WHERE mm.make = ?';
892     $num_args++;
893   }
894
895   my ($dummy) = selectrow_query($::form, $::form->get_standard_dbh(), $query, (conv_i($self->{cv}->id)) x $num_args);
896
897   return $self->{_is_orphaned} = !$dummy;
898 }
899
900 sub _copy_form_to_cvars {
901   my ($self, %params) = @_;
902
903   foreach my $cvar (@{ $params{target}->cvars_by_config }) {
904     my $value = $params{source}->{$cvar->config->name};
905     $value    = $::form->parse_amount(\%::myconfig, $value) if $cvar->config->type eq 'number';
906
907     $cvar->value($value);
908   }
909 }
910
911 sub _instantiate_args {
912   my ($self) = @_;
913
914   my $curr_employee = SL::DB::Manager::Employee->current;
915
916   if ( $::form->{cv}->{id} ) {
917     if ( $self->is_vendor() ) {
918       $self->{cv} = SL::DB::Vendor->new(id => $::form->{cv}->{id})->load();
919     } else {
920       $self->{cv} = SL::DB::Customer->new(id => $::form->{cv}->{id})->load();
921     }
922   } else {
923     $self->{cv} = $self->_new_customer_vendor_object;
924   }
925   $self->{cv}->assign_attributes(%{$::form->{cv}});
926
927   if ( $self->is_customer() && $::form->{cv}->{taxincluded_checked} eq '' ) {
928     $self->{cv}->taxincluded_checked(undef);
929   }
930
931   $self->{cv}->hourly_rate($::instance_conf->get_customer_hourly_rate) if $self->is_customer && !$self->{cv}->hourly_rate;
932
933   if ( $::form->{note}->{id} ) {
934     $self->{note} = SL::DB::Note->new(id => $::form->{note}->{id})->load();
935     $self->{note_followup} = $self->{note}->follow_up;
936     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
937   } else {
938     $self->{note} = SL::DB::Note->new();
939     $self->{note_followup} = SL::DB::FollowUp->new();
940     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
941   }
942
943   $self->{note}->assign_attributes(%{$::form->{note}});
944   $self->{note}->created_by($curr_employee->id);
945   $self->{note}->trans_module('ct');
946
947   $self->{note_followup}->assign_attributes(%{$::form->{note_followup}});
948   $self->{note_followup}->note($self->{note});
949   $self->{note_followup}->created_by($curr_employee->id);
950
951   $self->{note_followup_link}->trans_type($self->is_vendor() ? 'vendor' : 'customer');
952   $self->{note_followup_link}->trans_info($self->{cv}->name);
953
954   if ( $::form->{shipto}->{shipto_id} ) {
955     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto}->{shipto_id})->load();
956   } else {
957     $self->{shipto} = SL::DB::Shipto->new();
958   }
959   $self->{shipto}->assign_attributes(%{$::form->{shipto}});
960   $self->{shipto}->module('CT');
961
962   if ($self->is_customer) {
963     if ( $::form->{additional_billing_address}->{id} ) {
964       $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new(id => $::form->{additional_billing_address}->{id})->load;
965     } else {
966       $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new;
967     }
968     $self->{additional_billing_address}->assign_attributes(%{ $::form->{additional_billing_address} });
969   }
970
971   if ( $::form->{contact}->{cp_id} ) {
972     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact}->{cp_id})->load();
973   } else {
974     $self->{contact} = $self->_new_contact_object;
975   }
976   $self->{contact}->assign_attributes(%{$::form->{contact}});
977
978   $self->_copy_form_to_cvars(target => $self->{cv},      source => $::form->{cv_cvars});
979   $self->_copy_form_to_cvars(target => $self->{contact}, source => $::form->{contact_cvars});
980   $self->_copy_form_to_cvars(target => $self->{shipto},  source => $::form->{shipto_cvars});
981 }
982
983 sub _load_customer_vendor {
984   my ($self) = @_;
985
986   if ( $self->is_vendor() ) {
987     $self->{cv} = SL::DB::Vendor->new(id => $::form->{id})->load();
988   } else {
989     $self->{cv} = SL::DB::Customer->new(id => $::form->{id})->load();
990   }
991
992   if ( $::form->{note_id} ) {
993     $self->{note} = SL::DB::Note->new(id => $::form->{note_id})->load();
994     $self->{note_followup} = $self->{note}->follow_up;
995     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
996   } else {
997     $self->{note} = SL::DB::Note->new();
998     $self->{note_followup} = SL::DB::FollowUp->new();
999     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
1000   }
1001
1002   if ( $::form->{shipto_id} ) {
1003     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto_id})->load();
1004
1005     if ( $self->{shipto}->trans_id != $self->{cv}->id ) {
1006       die($::locale->text('Error'));
1007     }
1008   } else {
1009     $self->{shipto} = SL::DB::Shipto->new();
1010   }
1011
1012   if ($self->is_customer) {
1013     if ( $::form->{additional_billing_address_id} ) {
1014       $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new(id => $::form->{additional_billing_address_id})->load;
1015       die($::locale->text('Error')) if $self->{additional_billing_address}->customer_id != $self->{cv}->id;
1016
1017     } else {
1018       $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new;
1019     }
1020   }
1021
1022   if ( $::form->{contact_id} ) {
1023     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact_id})->load();
1024
1025     if ( $self->{contact}->cp_cv_id != $self->{cv}->id ) {
1026       die($::locale->text('Error'));
1027     }
1028   } else {
1029     $self->{contact} = $self->_new_contact_object;
1030   }
1031 }
1032
1033 sub _may_access_action {
1034   my ($self, $action)   = @_;
1035
1036   my $is_new            = !$self->{cv} || !$self->{cv}->id;
1037   my $is_own_customer   = !$is_new
1038                        && $self->{cv}->is_customer
1039                        && (SL::DB::Manager::Employee->current->id == $self->{cv}->salesman_id);
1040   my $has_edit_rights   = $::auth->assert('customer_vendor_all_edit', 1);
1041   $has_edit_rights    ||= $::auth->assert('customer_vendor_edit',     1) && ($is_new || $is_own_customer);
1042   my $needs_edit_rights = $action =~ m{^(?:add|save|delete|update)};
1043
1044   $self->user_has_edit_rights($has_edit_rights);
1045
1046   return 1 if $has_edit_rights;
1047   return 0 if $needs_edit_rights;
1048   return 1;
1049 }
1050
1051 sub _check_auth {
1052   my ($self, $action) = @_;
1053
1054   if (!$self->_may_access_action($action)) {
1055     $::auth->deny_access;
1056   }
1057 }
1058
1059 sub _create_customer_vendor {
1060   my ($self) = @_;
1061
1062   $self->{cv} = $self->_new_customer_vendor_object;
1063   $self->{cv}->currency_id($::instance_conf->get_currency_id());
1064
1065   $self->{note} = SL::DB::Note->new();
1066
1067   $self->{note_followup} = SL::DB::FollowUp->new();
1068
1069   $self->{shipto} = SL::DB::Shipto->new();
1070   $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new if $self->is_customer;
1071
1072   $self->{contact} = $self->_new_contact_object;
1073 }
1074
1075 sub _pre_render {
1076   my ($self) = @_;
1077
1078   my $dbh = $::form->get_standard_dbh();
1079
1080   my $query;
1081
1082   $self->{all_business} = SL::DB::Manager::Business->get_all();
1083
1084   $self->{all_employees} = SL::DB::Manager::Employee->get_all(query => [ deleted => 0 ]);
1085
1086   $self->{all_greetings} = SL::DB::Manager::Greeting->get_all_sorted();
1087   if ($self->{cv}->id && $self->{cv}->greeting && !grep {$self->{cv}->greeting eq $_->description} @{$self->{all_greetings}}) {
1088     unshift @{$self->{all_greetings}}, (SL::DB::Greeting->new(description => $self->{cv}->greeting));
1089   }
1090
1091   $self->{all_contact_titles} = SL::DB::Manager::ContactTitle->get_all_sorted();
1092   foreach my $contact (@{ $self->{cv}->contacts }) {
1093     if ($contact->cp_title && !grep {$contact->cp_title eq $_->description} @{$self->{all_contact_titles}}) {
1094       unshift @{$self->{all_contact_titles}}, (SL::DB::ContactTitle->new(description => $contact->cp_title));
1095     }
1096   }
1097
1098   $self->{all_contact_departments} = SL::DB::Manager::ContactDepartment->get_all_sorted();
1099   foreach my $contact (@{ $self->{cv}->contacts }) {
1100     if ($contact->cp_abteilung && !grep {$contact->cp_abteilung eq $_->description} @{$self->{all_contact_departments}}) {
1101       unshift @{$self->{all_contact_departments}}, (SL::DB::ContactDepartment->new(description => $contact->cp_abteilung));
1102     }
1103   }
1104
1105   $self->{all_currencies} = SL::DB::Manager::Currency->get_all();
1106
1107   $self->{all_languages} = SL::DB::Manager::Language->get_all();
1108
1109   $self->{all_taxzones} = SL::DB::Manager::TaxZone->get_all_sorted();
1110
1111   if ( $::instance_conf->get_vertreter() ) {
1112     $query =
1113       'SELECT id
1114        FROM business
1115        WHERE salesman';
1116     my $business_ids = [
1117       map(
1118         { $_->{id}; }
1119         selectall_hashref_query($::form, $dbh, $query)
1120       )
1121     ];
1122
1123     if ( $business_ids->[0] ) {
1124       $self->{all_salesman_customers} = SL::DB::Manager::Customer->get_all(query => [business_id => $business_ids]);
1125     } else {
1126       $self->{all_salesman_customers} = [];
1127     }
1128   } else {
1129     $self->{all_salesmen} = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $self->{cv}->salesman_id,  deleted => 0 ] ]);
1130   }
1131
1132   $self->{all_payment_terms} = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id       => $self->{cv}->payment_id,
1133                                                                                                obsolete => 0 ] ]);
1134
1135   $self->{all_delivery_terms} = SL::DB::Manager::DeliveryTerm->get_all();
1136
1137   if ($self->{cv}->is_customer) {
1138     $self->{all_pricegroups} = SL::DB::Manager::Pricegroup->get_all_sorted(query => [ or => [ id => $self->{cv}->pricegroup_id, obsolete => 0 ] ]);
1139   }
1140
1141   $self->{contacts} = $self->{cv}->contacts;
1142   $self->{contacts} ||= [];
1143
1144   $self->{shiptos} = $self->{cv}->shipto;
1145   $self->{shiptos} ||= [];
1146
1147   if ($self->is_customer) {
1148     $self->{additional_billing_addresses} = $self->{cv}->additional_billing_addresses;
1149     $self->{additional_billing_addresses} ||= [];
1150   }
1151
1152   $self->{notes} = SL::DB::Manager::Note->get_all(
1153     query => [
1154       trans_id => $self->{cv}->id,
1155       trans_module => 'ct',
1156     ],
1157     with_objects => ['follow_up'],
1158   );
1159
1160   if ( $self->is_vendor()) {
1161     $self->{open_items} = SL::DB::Manager::PurchaseInvoice->get_all_count(
1162       query => [
1163         vendor_id => $self->{cv}->id,
1164         paid => {lt_sql => 'amount'},
1165       ],
1166     );
1167   } else {
1168     $self->{open_items} = SL::DB::Manager::Invoice->get_all_count(
1169       query => [
1170         customer_id => $self->{cv}->id,
1171         paid => {lt_sql => 'amount'},
1172       ],
1173     );
1174   }
1175
1176   if ( $self->is_vendor() ) {
1177     $self->{open_orders} = SL::DB::Manager::Order->get_all_count(
1178       query => [
1179         vendor_id => $self->{cv}->id,
1180         closed => 'F',
1181       ],
1182     );
1183   } else {
1184     $self->{open_orders} = SL::DB::Manager::Order->get_all_count(
1185       query => [
1186         customer_id => $self->{cv}->id,
1187         closed => 'F',
1188       ],
1189     );
1190   }
1191
1192   if ($self->{cv}->number && $::instance_conf->get_webdav) {
1193     my $webdav = SL::Webdav->new(
1194       type     => $self->is_customer ? 'customer'
1195                 : $self->is_vendor   ? 'vendor'
1196                 : undef,
1197       number   => $self->{cv}->number,
1198     );
1199     my @all_objects = $webdav->get_all_objects;
1200     @{ $self->{template_args}->{WEBDAV} } = map { { name => $_->filename,
1201                                                     type => t8('File'),
1202                                                     link => File::Spec->catfile($_->full_filedescriptor),
1203                                                 } } @all_objects;
1204   }
1205
1206   $self->{template_args} ||= {};
1207
1208   $::request->{layout}->add_javascripts("$_.js") for qw (kivi.CustomerVendor kivi.File kivi.CustomerVendorTurnover ckeditor/ckeditor ckeditor/adapters/jquery);
1209
1210   $self->_setup_form_action_bar;
1211 }
1212
1213 sub _setup_form_action_bar {
1214   my ($self) = @_;
1215
1216   my $no_rights = $self->user_has_edit_rights ? undef
1217                 : $self->{cv}->is_customer    ? t8("You don't have the rights to edit this customer.")
1218                 :                               t8("You don't have the rights to edit this vendor.");
1219
1220   for my $bar ($::request->layout->get('actionbar')) {
1221     $bar->add(
1222       combobox => [
1223         action => [
1224           t8('Save'),
1225           submit    => [ '#form', { action => "CustomerVendor/save" } ],
1226           checks    => [ 'check_taxzone_and_ustid' ],
1227           accesskey => 'enter',
1228           disabled  => $no_rights,
1229         ],
1230         action => [
1231           t8('Save and Close'),
1232           submit => [ '#form', { action => "CustomerVendor/save_and_close" } ],
1233           checks => [ 'check_taxzone_and_ustid' ],
1234           disabled => $no_rights,
1235         ],
1236       ], # end of combobox "Save"
1237
1238       combobox => [
1239         action => [ t8('Workflow') ],
1240         (action => [
1241           t8('Save and AP Transaction'),
1242           submit => [ '#form', { action => "CustomerVendor/save_and_ap_transaction" } ],
1243           checks => [ 'check_taxzone_and_ustid' ],
1244           disabled => $no_rights,
1245         ]) x !!$self->is_vendor,
1246         (action => [
1247           t8('Save and AR Transaction'),
1248           submit => [ '#form', { action => "CustomerVendor/save_and_ar_transaction" } ],
1249           checks => [ 'check_taxzone_and_ustid' ],
1250           disabled => $no_rights,
1251         ]) x !$self->is_vendor,
1252         action => [
1253           t8('Save and Invoice'),
1254           submit => [ '#form', { action => "CustomerVendor/save_and_invoice" } ],
1255           checks => [ 'check_taxzone_and_ustid' ],
1256           disabled => $no_rights,
1257         ],
1258         action => [
1259           t8('Save and Order'),
1260           submit => [ '#form', { action => "CustomerVendor/save_and_order" } ],
1261           checks => [ 'check_taxzone_and_ustid' ],
1262           disabled => $no_rights,
1263         ],
1264         (action => [
1265           t8('Save and RFQ'),
1266           submit => [ '#form', { action => "CustomerVendor/save_and_rfq" } ],
1267           checks => [ 'check_taxzone_and_ustid' ],
1268           disabled => $no_rights,
1269         ]) x !!$self->is_vendor,
1270         (action => [
1271           t8('Save and Quotation'),
1272           submit => [ '#form', { action => "CustomerVendor/save_and_quotation" } ],
1273           checks => [ 'check_taxzone_and_ustid' ],
1274           disabled => $no_rights,
1275         ]) x !$self->is_vendor,
1276       ], # end of combobox "Workflow"
1277
1278       action => [
1279         t8('Delete'),
1280         submit   => [ '#form', { action => "CustomerVendor/delete" } ],
1281         confirm  => t8('Do you really want to delete this object?'),
1282         disabled => !$self->{cv}->id    ? t8('This object has not been saved yet.')
1283                   : !$self->is_orphaned ? t8('This object has already been used.')
1284                   :                       $no_rights,
1285       ],
1286
1287       'separator',
1288
1289       action => [
1290         t8('History'),
1291         call     => [ 'kivi.CustomerVendor.showHistoryWindow', $self->{cv}->id ],
1292         disabled => !$self->{cv}->id ? t8('This object has not been saved yet.') : undef,
1293       ],
1294     );
1295   }
1296 }
1297
1298 sub _prepare_cvar_configs_for_ajaj {
1299   my ($self, $cvars) = @_;
1300
1301   return {
1302     map {
1303       my $cvar   = $_;
1304       my $result = { type => $cvar->config->type };
1305
1306       if ($cvar->config->type eq 'number') {
1307         $result->{value} = $::form->format_amount(\%::myconfig, $cvar->value, -2);
1308
1309       } elsif ($result->{type} eq 'date') {
1310         $result->{value} = $cvar->value ? $cvar->value->to_kivitendo : undef;
1311
1312       } elsif ($result->{type} =~ m{customer|vendor|part}) {
1313         my $object       = $cvar->value;
1314         my $method       = $result->{type} eq 'part' ? 'description' : 'name';
1315
1316         $result->{id}    = int($cvar->number_value) || undef;
1317         $result->{value} = $object ? $object->$method // '' : '';
1318
1319       } else {
1320         $result->{value} = $cvar->value;
1321       }
1322
1323       ( $cvar->config->name => $result )
1324
1325     } grep { $_->is_valid } @{ $cvars }
1326   };
1327 }
1328
1329 sub normalize_name {
1330   my ($self) = @_;
1331
1332   # check if feature is enabled (select normalize_vc_names from defaults)
1333   return unless ($::instance_conf->get_normalize_vc_names);
1334
1335   return unless $self->{cv};
1336   my $name = $self->{cv}->name;
1337   $name =~ s/\s+$//;
1338   $name =~ s/^\s+//;
1339   $name =~ s/\s+/ /g;
1340   $self->{cv}->name($name);
1341 }
1342
1343 sub home_address_for_google_maps {
1344   my ($self)  = @_;
1345
1346   my $address = $::instance_conf->get_address // '';
1347   $address    =~ s{^\s+|\s+$|\r+}{}g;
1348   $address    =~ s{\n+}{,}g;
1349   $address    =~ s{\s+}{ }g;
1350
1351   return $address;
1352 }
1353
1354 sub init_customer_models {
1355   my ($self) = @_;
1356
1357   SL::Controller::Helper::GetModels->new(
1358     controller   => $self,
1359     model        => 'Customer',
1360     sorted => {
1361       _default  => {
1362         by => 'customernumber',
1363         dir  => 1,
1364       },
1365       customernumber => t8('Customer Number'),
1366     },
1367   );
1368 }
1369
1370 sub init_vendor_models {
1371   my ($self) = @_;
1372
1373   SL::Controller::Helper::GetModels->new(
1374     controller => $self,
1375     model      => 'Vendor',
1376     sorted => {
1377       _default  => {
1378         by => 'vendornumber',
1379         dir  => 1,
1380       },
1381       vendornumber => t8('Vendor Number'),
1382     },
1383   );
1384 }
1385
1386 sub init_zugferd_settings {
1387   return [
1388     [ -1, t8('Use settings from client configuration') ],
1389     @SL::ZUGFeRD::customer_settings,
1390   ],
1391 }
1392
1393 sub _new_customer_vendor_object {
1394   my ($self) = @_;
1395
1396   my $class  = 'SL::DB::' . ($self->is_vendor ? 'Vendor' : 'Customer');
1397   my $object = $class->new(
1398     contacts         => [],
1399     shipto           => [],
1400     custom_variables => [],
1401   );
1402
1403   $object->additional_billing_addresses([]) if $self->is_customer;
1404
1405   return $object;
1406 }
1407
1408 sub _new_contact_object {
1409   my ($self) = @_;
1410
1411   return SL::DB::Contact->new(custom_variables => []);
1412 }
1413
1414 1;