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