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