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