+ ##
+ # contacts
+ ##
+ if (keys %{ $params->{'contacts'} }) {
+ my $contact_params = $params->{'contacts'};
+
+ if ($contact_params->{'contacts_firstname'} || $contact_params->{'contacts_lastname'}) {
+ my $first_query = " AND contact.first = '" . $contact_params->{'contacts_firstname'} . "'"
+ unless !$contact_params->{'contacts_firstname'};
+ my $last_query = " AND contact.last = '" . $contact_params->{'contacts_lastname'} . "'"
+ unless !$contact_params->{'contacts_lastname'};
+ push @where,
+ "EXISTS ( SELECT 1 FROM contact
+ JOIN cust_contact USING (contactnum)
+ WHERE cust_contact.custnum = cust_main.custnum
+ $first_query $last_query
+ ) ";
+ }
+
+ if ($contact_params->{'contacts_email'}) {
+ push @where,
+ "EXISTS ( SELECT 1 FROM contact_email
+ JOIN cust_contact USING (contactnum)
+ WHERE cust_contact.custnum = cust_main.custnum
+ AND contact_email.emailaddress = '" . $contact_params->{'contacts_email'} . "'
+ ) ";
+ }
+
+ if ( grep { /^contacts_phonetypenum(\d+)$/ } keys %{ $contact_params } ) {
+ my $phone_query;
+ foreach my $phone ( grep { /^contacts_phonetypenum(\d+)$/ } keys %{ $contact_params } ) {
+ $phone =~ /^contacts_phonetypenum(\d+)$/ or die "No phone type num $1 from $phone";
+ my $phonetypenum = $1;
+ (my $num = $contact_params->{$phone}) =~ s/\W//g;
+ if ( $num =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { $contact_params->{$phone} = "$1$2$3"; }
+ $phone_query .= " AND ( contact_phone.phonetypenum = '".$phonetypenum."' AND contact_phone.phonenum = '" . $contact_params->{$phone} . "' )"
+ unless !$contact_params->{$phone};
+ }
+ push @where,
+ "EXISTS ( SELECT 1 FROM contact_phone
+ JOIN cust_contact USING (contactnum)
+ WHERE cust_contact.custnum = cust_main.custnum
+ $phone_query
+ ) ";
+ }
+ }
+
+