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