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