Merge branch 'b-3.6.1' of ../kivitendo-erp_20220811
[kivitendo-erp.git] / SL / Controller / TopQuickSearch / Contact.pm
1 package SL::Controller::TopQuickSearch::Contact;
2
3 use strict;
4 use parent qw(SL::Controller::TopQuickSearch::Base);
5
6 use SL::Controller::CustomerVendor;
7 use SL::DB::Vendor;
8 use SL::DBUtils qw(selectfirst_array_query like);
9 use SL::Locale::String qw(t8);
10
11 sub auth { undef }
12
13 sub name { 'contact' }
14
15 sub description_config { t8('Contact') }
16
17 sub description_field { t8('Contacts') }
18
19 sub query_autocomplete {
20   my ($self) = @_;
21
22   my $cv_query = <<SQL;
23     SELECT id FROM customer
24     WHERE (obsolete IS NULL)
25        OR (obsolete = FALSE)
26
27     UNION
28
29     SELECT id FROM vendor
30     WHERE (obsolete IS NULL)
31        OR (obsolete = FALSE)
32 SQL
33
34   my $result = SL::DB::Manager::Contact->get_all(
35     query => [
36       or => [
37         cp_name      => { ilike => like($::form->{term}) },
38         cp_givenname => { ilike => like($::form->{term}) },
39         cp_email     => { ilike => like($::form->{term}) },
40       ],
41       cp_cv_id => [ \$cv_query ],
42     ],
43     limit => 10,
44     sort_by => 'cp_name',
45   );
46
47   return [
48     map {
49      value       => $_->full_name,
50      label       => $_->full_name,
51      id          => $_->cp_id,
52     }, @$result
53   ];
54 }
55
56 sub select_autocomplete {
57   my ($self) = @_;
58
59   my $contact = SL::DB::Manager::Contact->find_by(cp_id => $::form->{id});
60
61   SL::Controller::CustomerVendor->new->url_for(action => 'edit', id => $contact->cp_cv_id, contact_id => $contact->cp_id, db => db_for_contact($contact), fragment => 'contacts');
62 }
63
64 sub do_search {
65   my ($self) = @_;
66
67   my $results = $self->query_autocomplete;
68
69   if (@$results != 1) {
70     return SL::Controller::CustomerVendor->new->url_for(
71       controller      => 'ct.pl',
72       action          => 'list_contacts',
73       'filter.status' => 'active',
74       search_term     => $::form->{term},
75     );
76   } else {
77     $::form->{id} = $results->[0]{id};
78     return $self->select_autocomplete;
79   }
80 }
81
82
83 sub db_for_contact {
84   my ($contact) = @_;
85
86   my ($customer, $vendor) = selectfirst_array_query($::form, $::form->get_standard_dbh, <<SQL, ($contact->cp_cv_id)x2);
87     SELECT (SELECT COUNT(id) FROM customer WHERE id = ?), (SELECT COUNT(id) FROM vendor WHERE id = ?);
88 SQL
89
90   die 'Contact is orphaned, cannot link to it'         if !$customer && !$vendor;
91
92   $customer ? 'customer' : 'vendor';
93 }
94
95 # TODO: multi search
96
97 1;