3e6ad82175197331c69c014fcdacd18a5e06e90e
[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} = SL::DB::Contact->new();
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       {
548         if ( $_->config->type eq 'number' ) {
549           $_->config->name => $::form->format_amount(\%::myconfig, $_->value, -2);
550         } else {
551           $_->config->name => $_->value;
552         }
553       }
554       grep(
555         { $_->is_valid; }
556         @{$self->{contact}->cvars_by_config}
557       )
558     )
559   };
560
561   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
562 }
563
564 sub action_ajaj_autocomplete {
565   my ($self, %params) = @_;
566
567   my ($model, $manager, $number, $matches);
568
569   # first see if this is customer or vendor picking
570   if ($::form->{type} eq 'customer') {
571      $model   = $self->customer_models;
572      $manager = 'SL::DB::Manager::Customer';
573      $number  = 'customernumber';
574   } elsif ($::form->{type} eq 'vendor')  {
575      $model   = $self->vendor_models;
576      $manager = 'SL::DB::Manager::Vendor';
577      $number  = 'vendornumber';
578   } else {
579      die "unknown type $::form->{type}";
580   }
581
582   # if someone types something, and hits enter, assume he entered the full name.
583   # if something matches, treat that as sole match
584   # unfortunately get_models can't do more than one per package atm, so we d it
585   # the oldfashioned way.
586   if ($::form->{prefer_exact}) {
587     my $exact_matches;
588     if (1 == scalar @{ $exact_matches = $manager->get_all(
589       query => [
590         obsolete => 0,
591         or => [
592           name    => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
593           $number => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
594         ]
595       ],
596       limit => 2,
597     ) }) {
598       $matches = $exact_matches;
599     }
600   }
601
602   $matches //= $model->get;
603
604   my @hashes = map {
605    +{
606      value       => $_->name,
607      label       => $_->displayable_name,
608      id          => $_->id,
609      $number     => $_->$number,
610      name        => $_->name,
611      type        => $::form->{type},
612      cvars       => { map { ($_->config->name => { value => $_->value_as_text, is_valid => $_->is_valid }) } @{ $_->cvars_by_config } },
613     }
614   } @{ $matches };
615
616   $self->render(\ SL::JSON::to_json(\@hashes), { layout => 0, type => 'json', process => 0 });
617 }
618
619 sub action_test_page {
620   $::request->{layout}->add_javascripts('autocomplete_customer.js');
621   $_[0]->render('customer_vendor/test_page');
622 }
623
624 sub is_vendor {
625   return $::form->{db} eq 'vendor';
626 }
627
628 sub is_customer {
629   return $::form->{db} eq 'customer';
630 }
631
632 sub is_orphaned {
633   my ($self) = @_;
634
635   if ( defined($self->{_is_orphaned}) ) {
636     return $self->{_is_orphaned};
637   }
638
639   my $arap      = $self->is_vendor ? 'ap' : 'ar';
640   my $num_args  = 2;
641
642   my $cv = $self->is_vendor ? 'vendor' : 'customer';
643
644   my $query =
645    'SELECT a.id
646     FROM '. $arap .' AS a
647     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
648     WHERE ct.id = ?
649
650     UNION
651
652     SELECT a.id
653     FROM oe a
654     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
655     WHERE ct.id = ?';
656
657
658   if ( $self->is_vendor ) {
659     $query .=
660      ' UNION
661       SELECT 1 FROM makemodel mm WHERE mm.make = ?';
662     $num_args++;
663   }
664
665   my ($dummy) = selectrow_query($::form, $::form->get_standard_dbh(), $query, (conv_i($self->{cv}->id)) x $num_args);
666
667   return $self->{_is_orphaned} = !$dummy;
668 }
669
670 sub _instantiate_args {
671   my ($self) = @_;
672
673   my $curr_employee = SL::DB::Manager::Employee->current;
674
675   if ( $::form->{cv}->{id} ) {
676     if ( $self->is_vendor() ) {
677       $self->{cv} = SL::DB::Vendor->new(id => $::form->{cv}->{id})->load();
678     } else {
679       $self->{cv} = SL::DB::Customer->new(id => $::form->{cv}->{id})->load();
680     }
681   } else {
682     if ( $self->is_vendor() ) {
683       $self->{cv} = SL::DB::Vendor->new();
684     } else {
685       $self->{cv} = SL::DB::Customer->new();
686     }
687   }
688   $self->{cv}->assign_attributes(%{$::form->{cv}});
689
690   if ( $self->is_customer() && $::form->{cv}->{taxincluded_checked} eq '' ) {
691     $self->{cv}->taxincluded_checked(undef);
692   }
693
694   $self->{cv}->hourly_rate($::instance_conf->get_customer_hourly_rate) if $self->is_customer && !$self->{cv}->hourly_rate;
695
696   foreach my $cvar (@{$self->{cv}->cvars_by_config()}) {
697     my $value = $::form->{cv_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   if ( $::form->{note}->{id} ) {
707     $self->{note} = SL::DB::Note->new(id => $::form->{note}->{id})->load();
708     $self->{note_followup} = $self->{note}->follow_up;
709     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
710   } else {
711     $self->{note} = SL::DB::Note->new();
712     $self->{note_followup} = SL::DB::FollowUp->new();
713     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
714   }
715
716   $self->{note}->assign_attributes(%{$::form->{note}});
717   $self->{note}->created_by($curr_employee->id);
718   $self->{note}->trans_module('ct');
719
720   $self->{note_followup}->assign_attributes(%{$::form->{note_followup}});
721   $self->{note_followup}->note($self->{note});
722   $self->{note_followup}->created_by($curr_employee->id);
723
724   $self->{note_followup_link}->trans_type($self->is_vendor() ? 'vendor' : 'customer');
725   $self->{note_followup_link}->trans_info($self->{cv}->name);
726
727   if ( $::form->{shipto}->{shipto_id} ) {
728     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto}->{shipto_id})->load();
729   } else {
730     $self->{shipto} = SL::DB::Shipto->new();
731   }
732   $self->{shipto}->assign_attributes(%{$::form->{shipto}});
733   $self->{shipto}->module('CT');
734
735   if ( $::form->{contact}->{cp_id} ) {
736     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact}->{cp_id})->load();
737   } else {
738     $self->{contact} = SL::DB::Contact->new();
739   }
740   $self->{contact}->assign_attributes(%{$::form->{contact}});
741
742   foreach my $cvar (@{$self->{contact}->cvars_by_config()}) {
743     my $value = $::form->{contact_cvars}->{$cvar->config->name};
744
745     if ( $cvar->config->type eq 'number' ) {
746       $value = $::form->parse_amount(\%::myconfig, $value);
747     }
748
749     $cvar->value($value);
750   }
751 }
752
753 sub _load_customer_vendor {
754   my ($self) = @_;
755
756   if ( $self->is_vendor() ) {
757     $self->{cv} = SL::DB::Vendor->new(id => $::form->{id})->load();
758   } else {
759     $self->{cv} = SL::DB::Customer->new(id => $::form->{id})->load();
760   }
761
762   if ( $::form->{note_id} ) {
763     $self->{note} = SL::DB::Note->new(id => $::form->{note_id})->load();
764     $self->{note_followup} = $self->{note}->follow_up;
765     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
766   } else {
767     $self->{note} = SL::DB::Note->new();
768     $self->{note_followup} = SL::DB::FollowUp->new();
769     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
770   }
771
772   if ( $::form->{shipto_id} ) {
773     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto_id})->load();
774
775     if ( $self->{shipto}->trans_id != $self->{cv}->id ) {
776       die($::locale->text('Error'));
777     }
778   } else {
779     $self->{shipto} = SL::DB::Shipto->new();
780   }
781
782   if ( $::form->{contact_id} ) {
783     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact_id})->load();
784
785     if ( $self->{contact}->cp_cv_id != $self->{cv}->id ) {
786       die($::locale->text('Error'));
787     }
788   } else {
789     $self->{contact} = SL::DB::Contact->new();
790   }
791 }
792
793 sub _create_customer_vendor {
794   my ($self) = @_;
795
796   if ( $self->is_vendor() ) {
797     $self->{cv} = SL::DB::Vendor->new();
798   } else {
799     $self->{cv} = SL::DB::Customer->new();
800   }
801   $self->{cv}->currency_id($::instance_conf->get_currency_id());
802
803   $self->{note} = SL::DB::Note->new();
804
805   $self->{note_followup} = SL::DB::FollowUp->new();
806
807   $self->{shipto} = SL::DB::Shipto->new();
808
809   $self->{contact} = SL::DB::Contact->new();
810 }
811
812 sub _pre_render {
813   my ($self) = @_;
814
815   my $dbh = $::form->get_standard_dbh();
816
817   my $query;
818
819   $self->{all_business} = SL::DB::Manager::Business->get_all();
820
821   $self->{all_employees} = SL::DB::Manager::Employee->get_all(query => [ deleted => 0 ]);
822
823   $query =
824     'SELECT DISTINCT(greeting)
825      FROM customer
826      WHERE greeting IS NOT NULL AND greeting != \'\'
827      UNION
828        SELECT DISTINCT(greeting)
829        FROM vendor
830        WHERE greeting IS NOT NULL AND greeting != \'\'
831      ORDER BY greeting';
832   $self->{all_greetings} = [
833     map(
834       { $_->{greeting}; }
835       selectall_hashref_query($::form, $dbh, $query)
836     )
837   ];
838
839   $query =
840     'SELECT DISTINCT(cp_title) AS title
841      FROM contacts
842      WHERE cp_title IS NOT NULL AND cp_title != \'\'
843      ORDER BY cp_title';
844   $self->{all_titles} = [
845     map(
846       { $_->{title}; }
847       selectall_hashref_query($::form, $dbh, $query)
848     )
849   ];
850
851   $self->{all_currencies} = SL::DB::Manager::Currency->get_all();
852
853   $self->{all_languages} = SL::DB::Manager::Language->get_all();
854
855   $self->{all_taxzones} = SL::DB::Manager::TaxZone->get_all_sorted();
856
857   if ( $::instance_conf->get_vertreter() ) {
858     $query =
859       'SELECT id
860        FROM business
861        WHERE salesman';
862     my $business_ids = [
863       map(
864         { $_->{id}; }
865         selectall_hashref_query($::form, $dbh, $query)
866       )
867     ];
868
869     if ( $business_ids->[0] ) {
870       $self->{all_salesman_customers} = SL::DB::Manager::Customer->get_all(query => [business_id => $business_ids]);
871     } else {
872       $self->{all_salesman_customers} = [];
873     }
874   } else {
875     $self->{all_salesmen} = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $self->{cv}->salesman_id,  deleted => 0 ] ]);
876   }
877
878   $self->{all_payment_terms} = SL::DB::Manager::PaymentTerm->get_all();
879
880   $self->{all_delivery_terms} = SL::DB::Manager::DeliveryTerm->get_all();
881
882   $self->{all_pricegroups} = SL::DB::Manager::Pricegroup->get_all();
883
884   $query =
885     'SELECT DISTINCT(cp_abteilung) AS department
886      FROM contacts
887      WHERE cp_abteilung IS NOT NULL AND cp_abteilung != \'\'
888      ORDER BY cp_abteilung';
889   $self->{all_departments} = [
890     map(
891       { $_->{department}; }
892       selectall_hashref_query($::form, $dbh, $query)
893     )
894   ];
895
896   $self->{contacts} = $self->{cv}->contacts;
897   $self->{contacts} ||= [];
898
899   $self->{shiptos} = $self->{cv}->shipto;
900   $self->{shiptos} ||= [];
901
902   $self->{notes} = SL::DB::Manager::Note->get_all(
903     query => [
904       trans_id => $self->{cv}->id,
905       trans_module => 'ct',
906     ],
907     with_objects => ['follow_up'],
908   );
909
910   $self->{template_args} ||= {};
911
912   $::request->{layout}->add_javascripts('autocomplete_customer.js');
913   $::request->{layout}->add_javascripts('kivi.CustomerVendor.js');
914 }
915
916 sub normalize_name {
917   my ($self) = @_;
918
919   # check if feature is enabled (select normalize_vc_names from defaults)
920   return unless ($::instance_conf->get_normalize_vc_names);
921
922   return unless $self->{cv};
923   my $name = $self->{cv}->name;
924   $name =~ s/\s+$//;
925   $name =~ s/^\s+//;
926   $name =~ s/\s+/ /g;
927   $self->{cv}->name($name);
928 }
929
930 sub home_address_for_google_maps {
931   my ($self)  = @_;
932
933   my $address = $::instance_conf->get_address // '';
934   $address    =~ s{^\s+|\s+$|\r+}{}g;
935   $address    =~ s{\n+}{,}g;
936   $address    =~ s{\s+}{ }g;
937
938   return $address;
939 }
940
941 sub init_customer_models {
942   my ($self) = @_;
943
944   SL::Controller::Helper::GetModels->new(
945     controller   => $self,
946     model        => 'Customer',
947     sorted => {
948       _default  => {
949         by => 'name',
950         dir  => 1,
951       },
952       name  => t8('Name'),
953     },
954   );
955 }
956
957 sub init_vendor_models {
958   my ($self) = @_;
959
960   SL::Controller::Helper::GetModels->new(
961     controller => $self,
962     model      => 'Vendor',
963     sorted => {
964       _default  => {
965         by => 'name',
966         dir  => 1,
967       },
968       name  => t8('Name'),
969     },
970   );
971 }
972
973 1;