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