Kundenstammdaten: Lieferadresse speichern, wenn beliebiges Feld gesetzt
[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::Controller::Helper::GetModels;
13
14 use SL::DB::Customer;
15 use SL::DB::Vendor;
16 use SL::DB::Business;
17 use SL::DB::Employee;
18 use SL::DB::Language;
19 use SL::DB::TaxZone;
20 use SL::DB::Note;
21 use SL::DB::PaymentTerm;
22 use SL::DB::Pricegroup;
23 use SL::DB::Contact;
24 use SL::DB::FollowUp;
25 use SL::DB::FollowUpLink;
26 use SL::DB::History;
27 use SL::DB::Currency;
28
29 use Rose::Object::MakeMethods::Generic (
30   'scalar --get_set_init' => [ qw(customer_models vendor_models) ],
31 );
32
33 # safety
34 __PACKAGE__->run_before(
35   sub {
36     $::auth->assert('customer_vendor_edit');
37   }
38 );
39 __PACKAGE__->run_before(
40   '_instantiate_args',
41   only => [
42     'save',
43     'save_and_ap_transaction',
44     'save_and_ar_transaction',
45     'save_and_close',
46     'save_and_invoice',
47     'save_and_order',
48     'save_and_quotation',
49     'save_and_rfq',
50     'delete',
51     'delete_contact',
52     'delete_shipto',
53   ]
54 );
55
56 __PACKAGE__->run_before(
57   '_load_customer_vendor',
58   only => [
59     'edit',
60     'show',
61     'update',
62     'ajaj_get_shipto',
63     'ajaj_get_contact',
64   ]
65 );
66
67 # make sure this comes after _load_customer_vendor
68 __PACKAGE__->run_before(
69   '_check_customer_vendor_all_edit',
70   only => [
71     'edit',
72     'show',
73     'update',
74     'delete',
75     'save',
76     'save_and_ap_transaction',
77     'save_and_ar_transaction',
78     'save_and_close',
79     'save_and_invoice',
80     'save_and_order',
81     'save_and_quotation',
82     'save_and_rfq',
83     'delete',
84     'delete_contact',
85     'delete_shipto',
86   ]
87 );
88
89 __PACKAGE__->run_before(
90   '_create_customer_vendor',
91   only => [
92     'add',
93   ]
94 );
95
96 __PACKAGE__->run_before('normalize_name');
97
98
99 sub action_add {
100   my ($self) = @_;
101
102   $self->_pre_render();
103   $self->{cv}->assign_attributes(hourly_rate => $::instance_conf->get_customer_hourly_rate) if $self->{cv}->is_customer;
104   $self->render(
105     'customer_vendor/form',
106     title => ($self->is_vendor() ? $::locale->text('Add Vendor') : $::locale->text('Add Customer')),
107     %{$self->{template_args}}
108   );
109 }
110
111 sub action_edit {
112   my ($self) = @_;
113
114   $self->_pre_render();
115   $self->render(
116     'customer_vendor/form',
117     title => ($self->is_vendor() ? $::locale->text('Edit Vendor') : $::locale->text('Edit Customer')),
118     %{$self->{template_args}}
119   );
120 }
121
122 sub action_show {
123   my ($self) = @_;
124
125   if ($::request->type eq 'json') {
126     my $cv_hash;
127     if (!$self->{cv}) {
128       # TODO error
129     } else {
130       $cv_hash          = $self->{cv}->as_tree;
131       $cv_hash->{cvars} = $self->{cv}->cvar_as_hashref;
132     }
133
134     $self->render(\ SL::JSON::to_json($cv_hash), { layout => 0, type => 'json', process => 0 });
135   }
136 }
137
138 sub _save {
139   my ($self) = @_;
140
141   my @errors = $self->{cv}->validate;
142   if (@errors) {
143     flash('error', @errors);
144     $self->_pre_render();
145     $self->render(
146       'customer_vendor/form',
147       title => ($self->is_vendor() ? t8('Edit Vendor') : t8('Edit Customer')),
148       %{$self->{template_args}}
149     );
150     $::dispatcher->end_request;
151   }
152
153   my $db = $self->{cv}->db;
154
155   $db->do_transaction(sub {
156     my $cvs_by_nr;
157     if ( $self->is_vendor() ) {
158       if ( $self->{cv}->vendornumber ) {
159         $cvs_by_nr = SL::DB::Manager::Vendor->get_all(query => [vendornumber => $self->{cv}->vendornumber]);
160       }
161     } else {
162       if ( $self->{cv}->customernumber ) {
163         $cvs_by_nr = SL::DB::Manager::Customer->get_all(query => [customernumber => $self->{cv}->customernumber]);
164       }
165     }
166
167     foreach my $entry (@{$cvs_by_nr}) {
168       if( $entry->id != $self->{cv}->id ) {
169         my $msg =
170           $self->is_vendor() ? $::locale->text('This vendor number is already in use.') : $::locale->text('This customer number is already in use.');
171
172         $::form->error($msg);
173       }
174     }
175
176     $self->{cv}->save(cascade => 1);
177
178     $self->{contact}->cp_cv_id($self->{cv}->id);
179     if( $self->{contact}->cp_name ne '' || $self->{contact}->cp_givenname ne '' ) {
180       $self->{contact}->save(cascade => 1);
181     }
182
183     if( $self->{note}->subject ne '' && $self->{note}->body ne '' ) {
184
185       if ( !$self->{note_followup}->follow_up_date ) {
186         $::form->error($::locale->text('Date missing!'));
187       }
188
189       $self->{note}->trans_id($self->{cv}->id);
190       $self->{note}->save();
191
192       $self->{note_followup}->save();
193
194       $self->{note_followup_link}->follow_up_id($self->{note_followup}->id);
195       $self->{note_followup_link}->trans_id($self->{cv}->id);
196       $self->{note_followup_link}->save();
197
198       SL::Helper::Flash::flash_later('info', $::locale->text('Follow-Up saved.'));
199     }
200
201     $self->{shipto}->trans_id($self->{cv}->id);
202     if(any { $self->{shipto}->$_ ne '' } qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax shiptoemail)) {
203       $self->{shipto}->save(cascade => 1);
204     }
205
206     my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
207     SL::DB::History->new(
208       trans_id => $self->{cv}->id,
209       snumbers => $snumbers,
210       employee_id => SL::DB::Manager::Employee->current->id,
211       addition => 'SAVED',
212     )->save();
213
214     if ( $::form->{delete_notes} ) {
215       foreach my $note_id (@{ $::form->{delete_notes} }) {
216         my $note = SL::DB::Note->new(id => $note_id)->load();
217         if ( $note->follow_up ) {
218           if ( $note->follow_up->follow_up_link ) {
219             $note->follow_up->follow_up_link->delete(cascade => 'delete');
220           }
221           $note->follow_up->delete(cascade => 'delete');
222         }
223         $note->delete(cascade => 'delete');
224       }
225     }
226   }) || die($db->error);
227
228 }
229
230 sub action_save {
231   my ($self) = @_;
232
233   $self->_save();
234
235   my @redirect_params = (
236     action => 'edit',
237     id     => $self->{cv}->id,
238     db     => ($self->is_vendor() ? 'vendor' : 'customer'),
239   );
240
241   if ( $self->{contact}->cp_id ) {
242     push(@redirect_params, contact_id => $self->{contact}->cp_id);
243   }
244
245   if ( $self->{shipto}->shipto_id ) {
246     push(@redirect_params, shipto_id => $self->{shipto}->shipto_id);
247   }
248
249   $self->redirect_to(@redirect_params);
250 }
251
252 sub action_save_and_close {
253   my ($self) = @_;
254
255   $self->_save();
256
257   my $msg = $self->is_vendor() ? $::locale->text('Vendor saved') : $::locale->text('Customer saved');
258   $::form->redirect($msg);
259 }
260
261 sub _transaction {
262   my ($self, $script) = @_;
263
264   $::auth->assert('general_ledger         | invoice_edit         | vendor_invoice_edit | ' .
265                  ' request_quotation_edit | sales_quotation_edit | sales_order_edit    | purchase_order_edit');
266
267   $self->_save();
268
269   my $name = $::form->escape($self->{cv}->name, 1);
270   my $db = $self->is_vendor() ? 'vendor' : 'customer';
271
272   my $url = $self->url_for(
273     controller => $script,
274     action     => 'add',
275     vc         => $db,
276     $db .'_id' => $self->{cv}->id,
277     $db        => $name,
278     type       => $::form->{type},
279     callback   => $::form->{callback},
280   );
281
282   print $::form->redirect_header($url);
283 }
284
285 sub action_save_and_ar_transaction {
286   my ($self) = @_;
287
288   $main::auth->assert('general_ledger');
289
290   $self->_transaction('ar.pl');
291 }
292
293 sub action_save_and_ap_transaction {
294   my ($self) = @_;
295
296   $main::auth->assert('general_ledger');
297
298   $self->_transaction('ap.pl');
299 }
300
301 sub action_save_and_invoice {
302   my ($self) = @_;
303
304   if ( $self->is_vendor() ) {
305     $::auth->assert('vendor_invoice_edit');
306   } else {
307     $::auth->assert('invoice_edit');
308   }
309
310   $::form->{type} = 'invoice';
311   $self->_transaction($self->is_vendor() ? 'ir.pl' : 'is.pl');
312 }
313
314 sub action_save_and_order {
315   my ($self) = @_;
316
317   if ( $self->is_vendor() ) {
318     $::auth->assert('purchase_order_edit');
319   } else {
320     $::auth->assert('sales_order_edit');
321   }
322
323   $::form->{type} = $self->is_vendor() ? 'purchase_order' : 'sales_order';
324   $self->_transaction('oe.pl');
325 }
326
327 sub action_save_and_rfq {
328   my ($self) = @_;
329
330   $::auth->assert('request_quotation_edit');
331
332   $::form->{type} = 'request_quotation';
333   $self->_transaction('oe.pl');
334 }
335
336 sub action_save_and_quotation {
337   my ($self) = @_;
338
339   $::auth->assert('sales_quotation_edit');
340
341   $::form->{type} = 'sales_quotation';
342   $self->_transaction('oe.pl');
343 }
344
345 sub action_delete {
346   my ($self) = @_;
347
348   my $db = $self->{cv}->db;
349
350   if( !$self->is_orphaned() ) {
351     $self->action_edit();
352   } else {
353
354     $db->do_transaction(sub {
355       $self->{cv}->delete(cascade => 1);
356
357       my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
358       SL::DB::History->new(
359         trans_id => $self->{cv}->id,
360         snumbers => $snumbers,
361         employee_id => SL::DB::Manager::Employee->current->id,
362         addition => 'DELETED',
363       )->save();
364     }) || die($db->error);
365
366     my $msg = $self->is_vendor() ? $::locale->text('Vendor deleted!') : $::locale->text('Customer deleted!');
367     $::form->redirect($msg);
368   }
369
370 }
371
372
373 sub action_delete_contact {
374   my ($self) = @_;
375
376   my $db = $self->{contact}->db;
377
378   if ( !$self->{contact}->cp_id ) {
379     SL::Helper::Flash::flash('error', $::locale->text('No contact selected to delete'));
380   } else {
381
382     $db->do_transaction(sub {
383       if ( $self->{contact}->used ) {
384         $self->{contact}->detach();
385         $self->{contact}->save();
386         SL::Helper::Flash::flash('info', $::locale->text('Contact is in use and was flagged invalid.'));
387       } else {
388         $self->{contact}->delete(cascade => 1);
389         SL::Helper::Flash::flash('info', $::locale->text('Contact deleted.'));
390       }
391     }) || die($db->error);
392
393     $self->{contact} = $self->_new_contact_object;
394   }
395
396   $self->action_edit();
397 }
398
399 sub action_delete_shipto {
400   my ($self) = @_;
401
402   my $db = $self->{shipto}->db;
403
404   if ( !$self->{shipto}->shipto_id ) {
405     SL::Helper::Flash::flash('error', $::locale->text('No shipto selected to delete'));
406   } else {
407
408     $db->do_transaction(sub {
409       if ( $self->{shipto}->used ) {
410         $self->{shipto}->detach();
411         $self->{shipto}->save(cascade => 1);
412         SL::Helper::Flash::flash('info', $::locale->text('Shipto is in use and was flagged invalid.'));
413       } else {
414         $self->{shipto}->delete(cascade => 1);
415         SL::Helper::Flash::flash('info', $::locale->text('Shipto deleted.'));
416       }
417     }) || die($db->error);
418
419     $self->{shipto} = SL::DB::Shipto->new();
420   }
421
422   $self->action_edit();
423 }
424
425
426 sub action_search {
427   my ($self) = @_;
428
429   my @url_params = (
430     controller => 'ct.pl',
431     action => 'search',
432     db => $self->is_vendor() ? 'vendor' : 'customer',
433   );
434
435   if ( $::form->{callback} ) {
436     push(@url_params, callback => $::form->{callback});
437   }
438
439   $self->redirect_to(@url_params);
440 }
441
442
443 sub action_search_contact {
444   my ($self) = @_;
445
446   my $url = 'ct.pl?action=search_contact&db=customer';
447
448   if ( $::form->{callback} ) {
449     $url .= '&callback='. $::form->escape($::form->{callback});
450   }
451
452   print $::form->redirect_header($url);
453 }
454
455
456 sub action_get_delivery {
457   my ($self) = @_;
458
459   $::auth->assert('sales_all_edit');
460
461   my $dbh = $::form->get_standard_dbh();
462
463   my ($arap, $db, $qty_sign);
464   if ( $self->is_vendor() ) {
465     $arap = 'ap';
466     $db = 'vendor';
467     $qty_sign = ' * -1 AS qty';
468   } else {
469     $arap = 'ar';
470     $db = 'customer';
471     $qty_sign = '';
472   }
473
474   my $where = ' WHERE 1=1';
475   my @values;
476
477   if ( !$self->is_vendor() && $::form->{shipto_id} && $::form->{shipto_id} ne 'all' ) {
478     $where .= " AND ${arap}.shipto_id = ?";
479     push(@values, $::form->{shipto_id});
480   } else {
481     $where .= " AND ${arap}.${db}_id = ?";
482     push(@values, $::form->{id});
483   }
484
485   if ( $::form->{delivery_from} ) {
486     $where .= " AND ${arap}.transdate >= ?";
487     push(@values, conv_date($::form->{delivery_from}));
488   }
489
490   if ( $::form->{delivery_to} ) {
491     $where .= " AND ${arap}.transdate <= ?";
492     push(@values, conv_date($::form->{delivery_to}));
493   }
494
495   my $query =
496     "SELECT
497        s.shiptoname,
498        i.qty ${qty_sign},
499        ${arap}.id,
500        ${arap}.transdate,
501        ${arap}.invnumber,
502        ${arap}.ordnumber,
503        i.description,
504        i.unit,
505        i.sellprice,
506        oe.id AS oe_id,
507        invoice
508      FROM ${arap}
509
510      LEFT JOIN shipto s
511       ON ". ($arap eq 'ar' ? '(ar.shipto_id = s.shipto_id) ' : '(ap.id = s.trans_id) ') ."
512
513      LEFT JOIN invoice i
514        ON ${arap}.id = i.trans_id
515
516      LEFT JOIN parts p
517        ON p.id = i.parts_id
518
519      LEFT JOIN oe
520        ON (oe.ordnumber = ${arap}.ordnumber AND NOT ${arap}.ordnumber = ''
521            AND ". ($arap eq 'ar' ? 'oe.customer_id IS NOT NULL' : 'oe.vendor_id IS NOT NULL') ." )
522
523      ${where}
524      ORDER BY ${arap}.transdate DESC LIMIT 15";
525
526   $self->{delivery} = selectall_hashref_query($::form, $dbh, $query, @values);
527
528   $self->render('customer_vendor/get_delivery', { layout => 0 });
529 }
530
531 sub action_ajaj_get_shipto {
532   my ($self) = @_;
533
534   my $data = {};
535   $data->{shipto} = {
536     map(
537       {
538         my $name = 'shipto'. $_;
539         $name => $self->{shipto}->$name;
540       }
541       qw(_id name department_1 department_2 street zipcode city gln country contact phone fax email)
542     )
543   };
544
545   $data->{shipto_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{shipto}->cvars_by_config);
546
547   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
548 }
549
550 sub action_ajaj_get_contact {
551   my ($self) = @_;
552
553   my $data;
554
555   $data->{contact} = {
556     map(
557       {
558         my $name = 'cp_'. $_;
559
560         if ( $_ eq 'birthday' && $self->{contact}->$name ) {
561           $name => $self->{contact}->$name->to_lxoffice;
562         } else {
563           $name => $self->{contact}->$name;
564         }
565       }
566       qw(
567         id gender abteilung title position givenname name email phone1 phone2 fax mobile1 mobile2
568         satphone satfax project street zipcode city privatphone privatemail birthday
569       )
570     )
571   };
572
573   $data->{contact_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{contact}->cvars_by_config);
574
575   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
576 }
577
578 sub action_ajaj_autocomplete {
579   my ($self, %params) = @_;
580
581   my ($model, $manager, $number, $matches);
582
583   # first see if this is customer or vendor picking
584   if ($::form->{type} eq 'customer') {
585      $model   = $self->customer_models;
586      $manager = 'SL::DB::Manager::Customer';
587      $number  = 'customernumber';
588   } elsif ($::form->{type} eq 'vendor')  {
589      $model   = $self->vendor_models;
590      $manager = 'SL::DB::Manager::Vendor';
591      $number  = 'vendornumber';
592   } else {
593      die "unknown type $::form->{type}";
594   }
595
596   # if someone types something, and hits enter, assume he entered the full name.
597   # if something matches, treat that as sole match
598   # unfortunately get_models can't do more than one per package atm, so we d it
599   # the oldfashioned way.
600   if ($::form->{prefer_exact}) {
601     my $exact_matches;
602     if (1 == scalar @{ $exact_matches = $manager->get_all(
603       query => [
604         obsolete => 0,
605         (salesman_id => SL::DB::Manager::Employee->current->id) x !$::auth->assert('customer_vendor_all_edit', 1),
606         or => [
607           name    => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
608           $number => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
609         ]
610       ],
611       limit => 2,
612     ) }) {
613       $matches = $exact_matches;
614     }
615   }
616
617   $matches //= $model->get;
618
619   my @hashes = map {
620    +{
621      value       => $_->displayable_name,
622      label       => $_->displayable_name,
623      id          => $_->id,
624      $number     => $_->$number,
625      name        => $_->name,
626      type        => $::form->{type},
627      cvars       => { map { ($_->config->name => { value => $_->value_as_text, is_valid => $_->is_valid }) } @{ $_->cvars_by_config } },
628     }
629   } @{ $matches };
630
631   $self->render(\ SL::JSON::to_json(\@hashes), { layout => 0, type => 'json', process => 0 });
632 }
633
634 sub action_test_page {
635   $::request->{layout}->add_javascripts('autocomplete_customer.js');
636   $_[0]->render('customer_vendor/test_page');
637 }
638
639 sub is_vendor {
640   return $::form->{db} eq 'vendor';
641 }
642
643 sub is_customer {
644   return $::form->{db} eq 'customer';
645 }
646
647 sub is_orphaned {
648   my ($self) = @_;
649
650   if ( defined($self->{_is_orphaned}) ) {
651     return $self->{_is_orphaned};
652   }
653
654   my $arap      = $self->is_vendor ? 'ap' : 'ar';
655   my $num_args  = 3;
656
657   my $cv = $self->is_vendor ? 'vendor' : 'customer';
658
659   my $query =
660    'SELECT a.id
661     FROM '. $arap .' AS a
662     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
663     WHERE ct.id = ?
664
665     UNION
666
667     SELECT a.id
668     FROM oe a
669     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
670     WHERE ct.id = ?
671
672     UNION
673
674     SELECT a.id
675     FROM delivery_orders a
676     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
677     WHERE ct.id = ?';
678
679
680   if ( $self->is_vendor ) {
681     $query .=
682      ' UNION
683       SELECT 1 FROM makemodel mm WHERE mm.make = ?';
684     $num_args++;
685   }
686
687   my ($dummy) = selectrow_query($::form, $::form->get_standard_dbh(), $query, (conv_i($self->{cv}->id)) x $num_args);
688
689   return $self->{_is_orphaned} = !$dummy;
690 }
691
692 sub _copy_form_to_cvars {
693   my ($self, %params) = @_;
694
695   foreach my $cvar (@{ $params{target}->cvars_by_config }) {
696     my $value = $params{source}->{$cvar->config->name};
697     $value    = $::form->parse_amount(\%::myconfig, $value) if $cvar->config->type eq 'number';
698
699     $cvar->value($value);
700   }
701 }
702
703 sub _instantiate_args {
704   my ($self) = @_;
705
706   my $curr_employee = SL::DB::Manager::Employee->current;
707
708   if ( $::form->{cv}->{id} ) {
709     if ( $self->is_vendor() ) {
710       $self->{cv} = SL::DB::Vendor->new(id => $::form->{cv}->{id})->load();
711     } else {
712       $self->{cv} = SL::DB::Customer->new(id => $::form->{cv}->{id})->load();
713     }
714   } else {
715     $self->{cv} = $self->_new_customer_vendor_object;
716   }
717   $self->{cv}->assign_attributes(%{$::form->{cv}});
718
719   if ( $self->is_customer() && $::form->{cv}->{taxincluded_checked} eq '' ) {
720     $self->{cv}->taxincluded_checked(undef);
721   }
722
723   $self->{cv}->hourly_rate($::instance_conf->get_customer_hourly_rate) if $self->is_customer && !$self->{cv}->hourly_rate;
724
725   if ( $::form->{note}->{id} ) {
726     $self->{note} = SL::DB::Note->new(id => $::form->{note}->{id})->load();
727     $self->{note_followup} = $self->{note}->follow_up;
728     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
729   } else {
730     $self->{note} = SL::DB::Note->new();
731     $self->{note_followup} = SL::DB::FollowUp->new();
732     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
733   }
734
735   $self->{note}->assign_attributes(%{$::form->{note}});
736   $self->{note}->created_by($curr_employee->id);
737   $self->{note}->trans_module('ct');
738
739   $self->{note_followup}->assign_attributes(%{$::form->{note_followup}});
740   $self->{note_followup}->note($self->{note});
741   $self->{note_followup}->created_by($curr_employee->id);
742
743   $self->{note_followup_link}->trans_type($self->is_vendor() ? 'vendor' : 'customer');
744   $self->{note_followup_link}->trans_info($self->{cv}->name);
745
746   if ( $::form->{shipto}->{shipto_id} ) {
747     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto}->{shipto_id})->load();
748   } else {
749     $self->{shipto} = SL::DB::Shipto->new();
750   }
751   $self->{shipto}->assign_attributes(%{$::form->{shipto}});
752   $self->{shipto}->module('CT');
753
754   if ( $::form->{contact}->{cp_id} ) {
755     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact}->{cp_id})->load();
756   } else {
757     $self->{contact} = $self->_new_contact_object;
758   }
759   $self->{contact}->assign_attributes(%{$::form->{contact}});
760
761   $self->_copy_form_to_cvars(target => $self->{cv},      source => $::form->{cv_cvars});
762   $self->_copy_form_to_cvars(target => $self->{contact}, source => $::form->{contact_cvars});
763   $self->_copy_form_to_cvars(target => $self->{shipto},  source => $::form->{shipto_cvars});
764 }
765
766 sub _load_customer_vendor {
767   my ($self) = @_;
768
769   if ( $self->is_vendor() ) {
770     $self->{cv} = SL::DB::Vendor->new(id => $::form->{id})->load();
771   } else {
772     $self->{cv} = SL::DB::Customer->new(id => $::form->{id})->load();
773   }
774
775   if ( $::form->{note_id} ) {
776     $self->{note} = SL::DB::Note->new(id => $::form->{note_id})->load();
777     $self->{note_followup} = $self->{note}->follow_up;
778     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
779   } else {
780     $self->{note} = SL::DB::Note->new();
781     $self->{note_followup} = SL::DB::FollowUp->new();
782     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
783   }
784
785   if ( $::form->{shipto_id} ) {
786     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto_id})->load();
787
788     if ( $self->{shipto}->trans_id != $self->{cv}->id ) {
789       die($::locale->text('Error'));
790     }
791   } else {
792     $self->{shipto} = SL::DB::Shipto->new();
793   }
794
795   if ( $::form->{contact_id} ) {
796     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact_id})->load();
797
798     if ( $self->{contact}->cp_cv_id != $self->{cv}->id ) {
799       die($::locale->text('Error'));
800     }
801   } else {
802     $self->{contact} = $self->_new_contact_object;
803   }
804 }
805
806 sub _check_customer_vendor_all_edit {
807   my ($self) = @_;
808
809   unless ($::auth->assert('customer_vendor_all_edit', 1)) {
810     die($::locale->text("You don't have the rights to edit this customer.") . "\n")
811       if $self->{cv}->is_customer and
812          SL::DB::Manager::Employee->current->id != $self->{cv}->salesman_id;
813   };
814 };
815
816 sub _create_customer_vendor {
817   my ($self) = @_;
818
819   $self->{cv} = $self->_new_customer_vendor_object;
820   $self->{cv}->currency_id($::instance_conf->get_currency_id());
821
822   $self->{note} = SL::DB::Note->new();
823
824   $self->{note_followup} = SL::DB::FollowUp->new();
825
826   $self->{shipto} = SL::DB::Shipto->new();
827
828   $self->{contact} = $self->_new_contact_object;
829 }
830
831 sub _pre_render {
832   my ($self) = @_;
833
834   my $dbh = $::form->get_standard_dbh();
835
836   my $query;
837
838   $self->{all_business} = SL::DB::Manager::Business->get_all();
839
840   $self->{all_employees} = SL::DB::Manager::Employee->get_all(query => [ deleted => 0 ]);
841
842   $query =
843     'SELECT DISTINCT(greeting)
844      FROM customer
845      WHERE greeting IS NOT NULL AND greeting != \'\'
846      UNION
847        SELECT DISTINCT(greeting)
848        FROM vendor
849        WHERE greeting IS NOT NULL AND greeting != \'\'
850      ORDER BY greeting';
851   $self->{all_greetings} = [
852     map(
853       { $_->{greeting}; }
854       selectall_hashref_query($::form, $dbh, $query)
855     )
856   ];
857
858   $query =
859     'SELECT DISTINCT(cp_title) AS title
860      FROM contacts
861      WHERE cp_title IS NOT NULL AND cp_title != \'\'
862      ORDER BY cp_title';
863   $self->{all_titles} = [
864     map(
865       { $_->{title}; }
866       selectall_hashref_query($::form, $dbh, $query)
867     )
868   ];
869
870   $self->{all_currencies} = SL::DB::Manager::Currency->get_all();
871
872   $self->{all_languages} = SL::DB::Manager::Language->get_all();
873
874   $self->{all_taxzones} = SL::DB::Manager::TaxZone->get_all_sorted();
875
876   if ( $::instance_conf->get_vertreter() ) {
877     $query =
878       'SELECT id
879        FROM business
880        WHERE salesman';
881     my $business_ids = [
882       map(
883         { $_->{id}; }
884         selectall_hashref_query($::form, $dbh, $query)
885       )
886     ];
887
888     if ( $business_ids->[0] ) {
889       $self->{all_salesman_customers} = SL::DB::Manager::Customer->get_all(query => [business_id => $business_ids]);
890     } else {
891       $self->{all_salesman_customers} = [];
892     }
893   } else {
894     $self->{all_salesmen} = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $self->{cv}->salesman_id,  deleted => 0 ] ]);
895   }
896
897   $self->{all_payment_terms} = SL::DB::Manager::PaymentTerm->get_all();
898
899   $self->{all_delivery_terms} = SL::DB::Manager::DeliveryTerm->get_all();
900
901   $self->{all_pricegroups} = SL::DB::Manager::Pricegroup->get_all();
902
903   $query =
904     'SELECT DISTINCT(cp_abteilung) AS department
905      FROM contacts
906      WHERE cp_abteilung IS NOT NULL AND cp_abteilung != \'\'
907      ORDER BY cp_abteilung';
908   $self->{all_departments} = [
909     map(
910       { $_->{department}; }
911       selectall_hashref_query($::form, $dbh, $query)
912     )
913   ];
914
915   $self->{contacts} = $self->{cv}->contacts;
916   $self->{contacts} ||= [];
917
918   $self->{shiptos} = $self->{cv}->shipto;
919   $self->{shiptos} ||= [];
920
921   $self->{notes} = SL::DB::Manager::Note->get_all(
922     query => [
923       trans_id => $self->{cv}->id,
924       trans_module => 'ct',
925     ],
926     with_objects => ['follow_up'],
927   );
928
929   $self->{template_args} ||= {};
930
931   $::request->{layout}->add_javascripts('autocomplete_customer.js');
932   $::request->{layout}->add_javascripts('kivi.CustomerVendor.js');
933 }
934
935 sub _prepare_cvar_configs_for_ajaj {
936   my ($self, $cvars) = @_;
937
938   return {
939     map {
940       my $cvar   = $_;
941       my $result = { type => $cvar->config->type };
942
943       if ($cvar->config->type eq 'number') {
944         $result->{value} = $::form->format_amount(\%::myconfig, $cvar->value, -2);
945
946       } elsif ($result->{type} eq 'date') {
947         $result->{value} = $cvar->value ? $cvar->value->to_kivitendo : undef;
948
949       } elsif ($result->{type} =~ m{customer|vendor|part}) {
950         my $object       = $cvar->value;
951         my $method       = $result->{type} eq 'part' ? 'description' : 'name';
952
953         $result->{id}    = int($cvar->number_value) || undef;
954         $result->{value} = $object ? $object->$method // '' : '';
955
956       } else {
957         $result->{value} = $cvar->value;
958       }
959
960       ( $cvar->config->name => $result )
961
962     } grep { $_->is_valid } @{ $cvars }
963   };
964 }
965
966 sub normalize_name {
967   my ($self) = @_;
968
969   # check if feature is enabled (select normalize_vc_names from defaults)
970   return unless ($::instance_conf->get_normalize_vc_names);
971
972   return unless $self->{cv};
973   my $name = $self->{cv}->name;
974   $name =~ s/\s+$//;
975   $name =~ s/^\s+//;
976   $name =~ s/\s+/ /g;
977   $self->{cv}->name($name);
978 }
979
980 sub home_address_for_google_maps {
981   my ($self)  = @_;
982
983   my $address = $::instance_conf->get_address // '';
984   $address    =~ s{^\s+|\s+$|\r+}{}g;
985   $address    =~ s{\n+}{,}g;
986   $address    =~ s{\s+}{ }g;
987
988   return $address;
989 }
990
991 sub init_customer_models {
992   my ($self) = @_;
993
994   SL::Controller::Helper::GetModels->new(
995     controller   => $self,
996     model        => 'Customer',
997     sorted => {
998       _default  => {
999         by => 'customernumber',
1000         dir  => 1,
1001       },
1002       customernumber => t8('Customer Number'),
1003     },
1004     query => [
1005      ( salesman_id => SL::DB::Manager::Employee->current->id) x !$::auth->assert('customer_vendor_all_edit', 1),
1006     ],
1007   );
1008 }
1009
1010 sub init_vendor_models {
1011   my ($self) = @_;
1012
1013   SL::Controller::Helper::GetModels->new(
1014     controller => $self,
1015     model      => 'Vendor',
1016     sorted => {
1017       _default  => {
1018         by => 'vendornumber',
1019         dir  => 1,
1020       },
1021       vendornumber => t8('Vendor Number'),
1022     },
1023   );
1024 }
1025
1026 sub _new_customer_vendor_object {
1027   my ($self) = @_;
1028
1029   my $class  = 'SL::DB::' . ($self->is_vendor ? 'Vendor' : 'Customer');
1030   return $class->new(
1031     contacts         => [],
1032     shipto           => [],
1033     custom_variables => [],
1034   );
1035 }
1036
1037 sub _new_contact_object {
1038   my ($self) = @_;
1039
1040   return SL::DB::Contact->new(custom_variables => []);
1041 }
1042
1043 1;