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