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