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