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