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