3b8f7fc77aabac18256c1b218300a2190fd7151c
[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   my $action = 'add';
276
277   if ($::instance_conf->get_feature_experimental && 'oe.pl' eq $script) {
278     $script = 'controller.pl';
279     $action = 'Order/' . $action;
280   }
281
282   my $url = $self->url_for(
283     controller => $script,
284     action     => $action,
285     vc         => $db,
286     $db .'_id' => $self->{cv}->id,
287     $db        => $name,
288     type       => $::form->{type},
289     callback   => $::form->{callback},
290   );
291
292   print $::form->redirect_header($url);
293 }
294
295 sub action_save_and_ar_transaction {
296   my ($self) = @_;
297
298   $main::auth->assert('ar_transactions');
299
300   $self->_transaction('ar.pl');
301 }
302
303 sub action_save_and_ap_transaction {
304   my ($self) = @_;
305
306   $main::auth->assert('ap_transactions');
307
308   $self->_transaction('ap.pl');
309 }
310
311 sub action_save_and_invoice {
312   my ($self) = @_;
313
314   if ( $self->is_vendor() ) {
315     $::auth->assert('vendor_invoice_edit');
316   } else {
317     $::auth->assert('invoice_edit');
318   }
319
320   $::form->{type} = 'invoice';
321   $self->_transaction($self->is_vendor() ? 'ir.pl' : 'is.pl');
322 }
323
324 sub action_save_and_order {
325   my ($self) = @_;
326
327   if ( $self->is_vendor() ) {
328     $::auth->assert('purchase_order_edit');
329   } else {
330     $::auth->assert('sales_order_edit');
331   }
332
333   $::form->{type} = $self->is_vendor() ? 'purchase_order' : 'sales_order';
334   $self->_transaction('oe.pl');
335 }
336
337 sub action_save_and_rfq {
338   my ($self) = @_;
339
340   $::auth->assert('request_quotation_edit');
341
342   $::form->{type} = 'request_quotation';
343   $self->_transaction('oe.pl');
344 }
345
346 sub action_save_and_quotation {
347   my ($self) = @_;
348
349   $::auth->assert('sales_quotation_edit');
350
351   $::form->{type} = 'sales_quotation';
352   $self->_transaction('oe.pl');
353 }
354
355 sub action_delete {
356   my ($self) = @_;
357
358   my $db = $self->{cv}->db;
359
360   if( !$self->is_orphaned() ) {
361     $self->action_edit();
362   } else {
363
364     $db->with_transaction(sub {
365       $self->{cv}->delete(cascade => 1);
366
367       my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
368       SL::DB::History->new(
369         trans_id => $self->{cv}->id,
370         snumbers => $snumbers,
371         employee_id => SL::DB::Manager::Employee->current->id,
372         addition => 'DELETED',
373       )->save();
374     }) || die($db->error);
375
376     my $msg = $self->is_vendor() ? $::locale->text('Vendor deleted!') : $::locale->text('Customer deleted!');
377     $::form->redirect($msg);
378   }
379
380 }
381
382
383 sub action_delete_contact {
384   my ($self) = @_;
385
386   my $db = $self->{contact}->db;
387
388   if ( !$self->{contact}->cp_id ) {
389     SL::Helper::Flash::flash('error', $::locale->text('No contact selected to delete'));
390   } else {
391
392     $db->with_transaction(sub {
393       if ( $self->{contact}->used ) {
394         $self->{contact}->detach();
395         $self->{contact}->save();
396         SL::Helper::Flash::flash('info', $::locale->text('Contact is in use and was flagged invalid.'));
397       } else {
398         $self->{contact}->delete(cascade => 1);
399         SL::Helper::Flash::flash('info', $::locale->text('Contact deleted.'));
400       }
401
402       1;
403     }) || die($db->error);
404
405     $self->{contact} = $self->_new_contact_object;
406   }
407
408   $self->action_edit();
409 }
410
411 sub action_delete_shipto {
412   my ($self) = @_;
413
414   my $db = $self->{shipto}->db;
415
416   if ( !$self->{shipto}->shipto_id ) {
417     SL::Helper::Flash::flash('error', $::locale->text('No shipto selected to delete'));
418   } else {
419
420     $db->with_transaction(sub {
421       if ( $self->{shipto}->used ) {
422         $self->{shipto}->detach();
423         $self->{shipto}->save(cascade => 1);
424         SL::Helper::Flash::flash('info', $::locale->text('Shipto is in use and was flagged invalid.'));
425       } else {
426         $self->{shipto}->delete(cascade => 1);
427         SL::Helper::Flash::flash('info', $::locale->text('Shipto deleted.'));
428       }
429
430       1;
431     }) || die($db->error);
432
433     $self->{shipto} = SL::DB::Shipto->new();
434   }
435
436   $self->action_edit();
437 }
438
439
440 sub action_search {
441   my ($self) = @_;
442
443   my @url_params = (
444     controller => 'ct.pl',
445     action => 'search',
446     db => $self->is_vendor() ? 'vendor' : 'customer',
447   );
448
449   if ( $::form->{callback} ) {
450     push(@url_params, callback => $::form->{callback});
451   }
452
453   $self->redirect_to(@url_params);
454 }
455
456
457 sub action_search_contact {
458   my ($self) = @_;
459
460   my $url = 'ct.pl?action=search_contact&db=customer';
461
462   if ( $::form->{callback} ) {
463     $url .= '&callback='. $::form->escape($::form->{callback});
464   }
465
466   print $::form->redirect_header($url);
467 }
468
469
470 sub action_get_delivery {
471   my ($self) = @_;
472
473   $::auth->assert('sales_all_edit');
474
475   my $dbh = $::form->get_standard_dbh();
476
477   my ($arap, $db, $qty_sign);
478   if ( $self->is_vendor() ) {
479     $arap = 'ap';
480     $db = 'vendor';
481     $qty_sign = ' * -1 AS qty';
482   } else {
483     $arap = 'ar';
484     $db = 'customer';
485     $qty_sign = '';
486   }
487
488   my $where = ' WHERE 1=1';
489   my @values;
490
491   if ( !$self->is_vendor() && $::form->{shipto_id} && $::form->{shipto_id} ne 'all' ) {
492     $where .= " AND ${arap}.shipto_id = ?";
493     push(@values, $::form->{shipto_id});
494   } else {
495     $where .= " AND ${arap}.${db}_id = ?";
496     push(@values, $::form->{id});
497   }
498
499   if ( $::form->{delivery_from} ) {
500     $where .= " AND ${arap}.transdate >= ?";
501     push(@values, conv_date($::form->{delivery_from}));
502   }
503
504   if ( $::form->{delivery_to} ) {
505     $where .= " AND ${arap}.transdate <= ?";
506     push(@values, conv_date($::form->{delivery_to}));
507   }
508
509   my $query =
510     "SELECT
511        s.shiptoname,
512        i.qty ${qty_sign},
513        ${arap}.id,
514        ${arap}.transdate,
515        ${arap}.invnumber,
516        ${arap}.ordnumber,
517        i.description,
518        i.unit,
519        i.sellprice,
520        oe.id AS oe_id,
521        invoice
522      FROM ${arap}
523
524      LEFT JOIN shipto s
525       ON ". ($arap eq 'ar' ? '(ar.shipto_id = s.shipto_id) ' : '(ap.id = s.trans_id) ') ."
526
527      LEFT JOIN invoice i
528        ON ${arap}.id = i.trans_id
529
530      LEFT JOIN parts p
531        ON p.id = i.parts_id
532
533      LEFT JOIN oe
534        ON (oe.ordnumber = ${arap}.ordnumber AND NOT ${arap}.ordnumber = ''
535            AND ". ($arap eq 'ar' ? 'oe.customer_id IS NOT NULL' : 'oe.vendor_id IS NOT NULL') ." )
536
537      ${where}
538      ORDER BY ${arap}.transdate DESC LIMIT 15";
539
540   $self->{delivery} = selectall_hashref_query($::form, $dbh, $query, @values);
541
542   $self->render('customer_vendor/get_delivery', { layout => 0 });
543 }
544
545 sub action_ajaj_get_shipto {
546   my ($self) = @_;
547
548   my $data = {};
549   $data->{shipto} = {
550     map(
551       {
552         my $name = 'shipto'. $_;
553         $name => $self->{shipto}->$name;
554       }
555       qw(_id name department_1 department_2 street zipcode city gln country contact phone fax email)
556     )
557   };
558
559   $data->{shipto_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{shipto}->cvars_by_config);
560
561   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
562 }
563
564 sub action_ajaj_get_contact {
565   my ($self) = @_;
566
567   my $data;
568
569   $data->{contact} = {
570     map(
571       {
572         my $name = 'cp_'. $_;
573
574         if ( $_ eq 'birthday' && $self->{contact}->$name ) {
575           $name => $self->{contact}->$name->to_lxoffice;
576         } else {
577           $name => $self->{contact}->$name;
578         }
579       }
580       qw(
581         id gender abteilung title position givenname name email phone1 phone2 fax mobile1 mobile2
582         satphone satfax project street zipcode city privatphone privatemail birthday
583       )
584     )
585   };
586
587   $data->{contact_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{contact}->cvars_by_config);
588
589   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
590 }
591
592 sub action_ajaj_autocomplete {
593   my ($self, %params) = @_;
594
595   my ($model, $manager, $number, $matches);
596
597   # first see if this is customer or vendor picking
598   if ($::form->{type} eq 'customer') {
599      $model   = $self->customer_models;
600      $manager = 'SL::DB::Manager::Customer';
601      $number  = 'customernumber';
602   } elsif ($::form->{type} eq 'vendor')  {
603      $model   = $self->vendor_models;
604      $manager = 'SL::DB::Manager::Vendor';
605      $number  = 'vendornumber';
606   } else {
607      die "unknown type $::form->{type}";
608   }
609
610   # if someone types something, and hits enter, assume he entered the full name.
611   # if something matches, treat that as sole match
612   # unfortunately get_models can't do more than one per package atm, so we d it
613   # the oldfashioned way.
614   if ($::form->{prefer_exact}) {
615     my $exact_matches;
616     if (1 == scalar @{ $exact_matches = $manager->get_all(
617       query => [
618         obsolete => 0,
619         (salesman_id => SL::DB::Manager::Employee->current->id) x !$::auth->assert('customer_vendor_all_edit', 1),
620         or => [
621           name    => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
622           $number => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
623         ]
624       ],
625       limit => 2,
626     ) }) {
627       $matches = $exact_matches;
628     }
629   }
630
631   $matches //= $model->get;
632
633   my @hashes = map {
634    +{
635      value       => $_->displayable_name,
636      label       => $_->displayable_name,
637      id          => $_->id,
638      $number     => $_->$number,
639      name        => $_->name,
640      type        => $::form->{type},
641      cvars       => { map { ($_->config->name => { value => $_->value_as_text, is_valid => $_->is_valid }) } @{ $_->cvars_by_config } },
642     }
643   } @{ $matches };
644
645   $self->render(\ SL::JSON::to_json(\@hashes), { layout => 0, type => 'json', process => 0 });
646 }
647
648 sub action_test_page {
649   $_[0]->render('customer_vendor/test_page');
650 }
651
652 sub is_vendor {
653   return $::form->{db} eq 'vendor';
654 }
655
656 sub is_customer {
657   return $::form->{db} eq 'customer';
658 }
659
660 sub is_orphaned {
661   my ($self) = @_;
662
663   if ( defined($self->{_is_orphaned}) ) {
664     return $self->{_is_orphaned};
665   }
666
667   my $arap      = $self->is_vendor ? 'ap' : 'ar';
668   my $num_args  = 3;
669
670   my $cv = $self->is_vendor ? 'vendor' : 'customer';
671
672   my $query =
673    'SELECT a.id
674     FROM '. $arap .' AS a
675     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
676     WHERE ct.id = ?
677
678     UNION
679
680     SELECT a.id
681     FROM oe a
682     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
683     WHERE ct.id = ?
684
685     UNION
686
687     SELECT a.id
688     FROM delivery_orders a
689     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
690     WHERE ct.id = ?';
691
692
693   if ( $self->is_vendor ) {
694     $query .=
695      ' UNION
696       SELECT 1 FROM makemodel mm WHERE mm.make = ?';
697     $num_args++;
698   }
699
700   my ($dummy) = selectrow_query($::form, $::form->get_standard_dbh(), $query, (conv_i($self->{cv}->id)) x $num_args);
701
702   return $self->{_is_orphaned} = !$dummy;
703 }
704
705 sub _copy_form_to_cvars {
706   my ($self, %params) = @_;
707
708   foreach my $cvar (@{ $params{target}->cvars_by_config }) {
709     my $value = $params{source}->{$cvar->config->name};
710     $value    = $::form->parse_amount(\%::myconfig, $value) if $cvar->config->type eq 'number';
711
712     $cvar->value($value);
713   }
714 }
715
716 sub _instantiate_args {
717   my ($self) = @_;
718
719   my $curr_employee = SL::DB::Manager::Employee->current;
720
721   if ( $::form->{cv}->{id} ) {
722     if ( $self->is_vendor() ) {
723       $self->{cv} = SL::DB::Vendor->new(id => $::form->{cv}->{id})->load();
724     } else {
725       $self->{cv} = SL::DB::Customer->new(id => $::form->{cv}->{id})->load();
726     }
727   } else {
728     $self->{cv} = $self->_new_customer_vendor_object;
729   }
730   $self->{cv}->assign_attributes(%{$::form->{cv}});
731
732   if ( $self->is_customer() && $::form->{cv}->{taxincluded_checked} eq '' ) {
733     $self->{cv}->taxincluded_checked(undef);
734   }
735
736   $self->{cv}->hourly_rate($::instance_conf->get_customer_hourly_rate) if $self->is_customer && !$self->{cv}->hourly_rate;
737
738   if ( $::form->{note}->{id} ) {
739     $self->{note} = SL::DB::Note->new(id => $::form->{note}->{id})->load();
740     $self->{note_followup} = $self->{note}->follow_up;
741     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
742   } else {
743     $self->{note} = SL::DB::Note->new();
744     $self->{note_followup} = SL::DB::FollowUp->new();
745     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
746   }
747
748   $self->{note}->assign_attributes(%{$::form->{note}});
749   $self->{note}->created_by($curr_employee->id);
750   $self->{note}->trans_module('ct');
751
752   $self->{note_followup}->assign_attributes(%{$::form->{note_followup}});
753   $self->{note_followup}->note($self->{note});
754   $self->{note_followup}->created_by($curr_employee->id);
755
756   $self->{note_followup_link}->trans_type($self->is_vendor() ? 'vendor' : 'customer');
757   $self->{note_followup_link}->trans_info($self->{cv}->name);
758
759   if ( $::form->{shipto}->{shipto_id} ) {
760     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto}->{shipto_id})->load();
761   } else {
762     $self->{shipto} = SL::DB::Shipto->new();
763   }
764   $self->{shipto}->assign_attributes(%{$::form->{shipto}});
765   $self->{shipto}->module('CT');
766
767   if ( $::form->{contact}->{cp_id} ) {
768     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact}->{cp_id})->load();
769   } else {
770     $self->{contact} = $self->_new_contact_object;
771   }
772   $self->{contact}->assign_attributes(%{$::form->{contact}});
773
774   $self->_copy_form_to_cvars(target => $self->{cv},      source => $::form->{cv_cvars});
775   $self->_copy_form_to_cvars(target => $self->{contact}, source => $::form->{contact_cvars});
776   $self->_copy_form_to_cvars(target => $self->{shipto},  source => $::form->{shipto_cvars});
777 }
778
779 sub _load_customer_vendor {
780   my ($self) = @_;
781
782   if ( $self->is_vendor() ) {
783     $self->{cv} = SL::DB::Vendor->new(id => $::form->{id})->load();
784   } else {
785     $self->{cv} = SL::DB::Customer->new(id => $::form->{id})->load();
786   }
787
788   if ( $::form->{note_id} ) {
789     $self->{note} = SL::DB::Note->new(id => $::form->{note_id})->load();
790     $self->{note_followup} = $self->{note}->follow_up;
791     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
792   } else {
793     $self->{note} = SL::DB::Note->new();
794     $self->{note_followup} = SL::DB::FollowUp->new();
795     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
796   }
797
798   if ( $::form->{shipto_id} ) {
799     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto_id})->load();
800
801     if ( $self->{shipto}->trans_id != $self->{cv}->id ) {
802       die($::locale->text('Error'));
803     }
804   } else {
805     $self->{shipto} = SL::DB::Shipto->new();
806   }
807
808   if ( $::form->{contact_id} ) {
809     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact_id})->load();
810
811     if ( $self->{contact}->cp_cv_id != $self->{cv}->id ) {
812       die($::locale->text('Error'));
813     }
814   } else {
815     $self->{contact} = $self->_new_contact_object;
816   }
817 }
818
819 sub _check_customer_vendor_all_edit {
820   my ($self) = @_;
821
822   unless ($::auth->assert('customer_vendor_all_edit', 1)) {
823     die($::locale->text("You don't have the rights to edit this customer.") . "\n")
824       if $self->{cv}->is_customer and
825          SL::DB::Manager::Employee->current->id != $self->{cv}->salesman_id;
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_sorted(where => [ or => [ id       => $self->{cv}->payment_id,
911                                                                                                obsolete => 0 ] ]);
912
913   $self->{all_delivery_terms} = SL::DB::Manager::DeliveryTerm->get_all();
914
915   if ($self->{cv}->is_customer) {
916     $self->{all_pricegroups} = SL::DB::Manager::Pricegroup->get_all_sorted(query => [ or => [ id => $self->{cv}->pricegroup_id, obsolete => 0 ] ]);
917   }
918
919   $query =
920     'SELECT DISTINCT(cp_abteilung) AS department
921      FROM contacts
922      WHERE cp_abteilung IS NOT NULL AND cp_abteilung != \'\'
923      ORDER BY cp_abteilung';
924   $self->{all_departments} = [
925     map(
926       { $_->{department}; }
927       selectall_hashref_query($::form, $dbh, $query)
928     )
929   ];
930
931   $self->{contacts} = $self->{cv}->contacts;
932   $self->{contacts} ||= [];
933
934   $self->{shiptos} = $self->{cv}->shipto;
935   $self->{shiptos} ||= [];
936
937   $self->{notes} = SL::DB::Manager::Note->get_all(
938     query => [
939       trans_id => $self->{cv}->id,
940       trans_module => 'ct',
941     ],
942     with_objects => ['follow_up'],
943   );
944
945   $self->{template_args} ||= {};
946
947   $::request->{layout}->add_javascripts('kivi.CustomerVendor.js');
948   $::request->{layout}->add_javascripts('kivi.File.js');
949
950   $self->_setup_form_action_bar;
951 }
952
953 sub _setup_form_action_bar {
954   my ($self) = @_;
955
956   for my $bar ($::request->layout->get('actionbar')) {
957     $bar->add(
958       combobox => [
959         action => [
960           t8('Save'),
961           submit    => [ '#form', { action => "CustomerVendor/save" } ],
962           checks    => [ 'check_taxzone_and_ustid' ],
963           accesskey => 'enter',
964         ],
965         action => [
966           t8('Save and Close'),
967           submit => [ '#form', { action => "CustomerVendor/save_and_close" } ],
968           checks => [ 'check_taxzone_and_ustid' ],
969         ],
970       ], # end of combobox "Save"
971
972       combobox => [
973         action => [ t8('Workflow') ],
974         (action => [
975           t8('Save and AP Transaction'),
976           submit => [ '#form', { action => "CustomerVendor/save_and_ap_transaction" } ],
977           checks => [ 'check_taxzone_and_ustid' ],
978         ]) x !!$self->is_vendor,
979         (action => [
980           t8('Save and AR Transaction'),
981           submit => [ '#form', { action => "CustomerVendor/save_and_ar_transaction" } ],
982           checks => [ 'check_taxzone_and_ustid' ],
983         ]) x !$self->is_vendor,
984         action => [
985           t8('Save and Invoice'),
986           submit => [ '#form', { action => "CustomerVendor/save_and_invoice" } ],
987           checks => [ 'check_taxzone_and_ustid' ],
988         ],
989         action => [
990           t8('Save and Order'),
991           submit => [ '#form', { action => "CustomerVendor/save_and_order" } ],
992           checks => [ 'check_taxzone_and_ustid' ],
993         ],
994         (action => [
995           t8('Save and RFQ'),
996           submit => [ '#form', { action => "CustomerVendor/save_and_rfq" } ],
997           checks => [ 'check_taxzone_and_ustid' ],
998         ]) x !!$self->is_vendor,
999         (action => [
1000           t8('Save and Quotation'),
1001           submit => [ '#form', { action => "CustomerVendor/save_and_quotation" } ],
1002           checks => [ 'check_taxzone_and_ustid' ],
1003         ]) x !$self->is_vendor,
1004       ], # end of combobox "Workflow"
1005
1006       action => [
1007         t8('Delete'),
1008         submit   => [ '#form', { action => "CustomerVendor/delete" } ],
1009         confirm  => t8('Do you really want to delete this object?'),
1010         disabled => !$self->{cv}->id    ? t8('This object has not been saved yet.')
1011                   : !$self->is_orphaned ? t8('This object has already been used.')
1012                   :                       undef,
1013       ],
1014
1015       'separator',
1016
1017       action => [
1018         t8('History'),
1019         call     => [ 'kivi.CustomerVendor.showHistoryWindow', $self->{cv}->id ],
1020         disabled => !$self->{cv}->id ? t8('This object has not been saved yet.') : undef,
1021       ],
1022     );
1023   }
1024 }
1025
1026 sub _prepare_cvar_configs_for_ajaj {
1027   my ($self, $cvars) = @_;
1028
1029   return {
1030     map {
1031       my $cvar   = $_;
1032       my $result = { type => $cvar->config->type };
1033
1034       if ($cvar->config->type eq 'number') {
1035         $result->{value} = $::form->format_amount(\%::myconfig, $cvar->value, -2);
1036
1037       } elsif ($result->{type} eq 'date') {
1038         $result->{value} = $cvar->value ? $cvar->value->to_kivitendo : undef;
1039
1040       } elsif ($result->{type} =~ m{customer|vendor|part}) {
1041         my $object       = $cvar->value;
1042         my $method       = $result->{type} eq 'part' ? 'description' : 'name';
1043
1044         $result->{id}    = int($cvar->number_value) || undef;
1045         $result->{value} = $object ? $object->$method // '' : '';
1046
1047       } else {
1048         $result->{value} = $cvar->value;
1049       }
1050
1051       ( $cvar->config->name => $result )
1052
1053     } grep { $_->is_valid } @{ $cvars }
1054   };
1055 }
1056
1057 sub normalize_name {
1058   my ($self) = @_;
1059
1060   # check if feature is enabled (select normalize_vc_names from defaults)
1061   return unless ($::instance_conf->get_normalize_vc_names);
1062
1063   return unless $self->{cv};
1064   my $name = $self->{cv}->name;
1065   $name =~ s/\s+$//;
1066   $name =~ s/^\s+//;
1067   $name =~ s/\s+/ /g;
1068   $self->{cv}->name($name);
1069 }
1070
1071 sub home_address_for_google_maps {
1072   my ($self)  = @_;
1073
1074   my $address = $::instance_conf->get_address // '';
1075   $address    =~ s{^\s+|\s+$|\r+}{}g;
1076   $address    =~ s{\n+}{,}g;
1077   $address    =~ s{\s+}{ }g;
1078
1079   return $address;
1080 }
1081
1082 sub init_customer_models {
1083   my ($self) = @_;
1084
1085   SL::Controller::Helper::GetModels->new(
1086     controller   => $self,
1087     model        => 'Customer',
1088     sorted => {
1089       _default  => {
1090         by => 'customernumber',
1091         dir  => 1,
1092       },
1093       customernumber => t8('Customer Number'),
1094     },
1095     query => [
1096      ( salesman_id => SL::DB::Manager::Employee->current->id) x !$::auth->assert('customer_vendor_all_edit', 1),
1097     ],
1098   );
1099 }
1100
1101 sub init_vendor_models {
1102   my ($self) = @_;
1103
1104   SL::Controller::Helper::GetModels->new(
1105     controller => $self,
1106     model      => 'Vendor',
1107     sorted => {
1108       _default  => {
1109         by => 'vendornumber',
1110         dir  => 1,
1111       },
1112       vendornumber => t8('Vendor Number'),
1113     },
1114   );
1115 }
1116
1117 sub _new_customer_vendor_object {
1118   my ($self) = @_;
1119
1120   my $class  = 'SL::DB::' . ($self->is_vendor ? 'Vendor' : 'Customer');
1121   return $class->new(
1122     contacts         => [],
1123     shipto           => [],
1124     custom_variables => [],
1125   );
1126 }
1127
1128 sub _new_contact_object {
1129   my ($self) = @_;
1130
1131   return SL::DB::Contact->new(custom_variables => []);
1132 }
1133
1134 1;