avoid creating contacts that duplicate other contact emails, #73708
[freeside.git] / bin / create-billing-contacts-v3
1 #!/usr/bin/perl
2
3 use strict;
4 use FS::Misc::Getopt;
5 use FS::Record qw(qsearchs qsearch dbh);
6 use FS::cust_main;
7 use FS::cust_main_invoice;
8 use FS::contact;
9
10 our %opt;
11 getopts('c:'); # contact classname
12
13 $FS::UID::AutoCommit = 0;
14
15 my $error;
16
17 my $classnum = '';
18 if ( $opt{c} ) {
19   my $class = qsearchs('contact_class', { classname => $opt{c} });
20   if (!$class) {
21     $class = FS::contact_class->new({ classname => $opt{c} });
22     $error = $class->insert;
23     die $error if $error;
24   }
25   $classnum = $class->classnum;
26 }
27
28 # Find all invoice destinations that are email addresses, except those where
29 # there is already a contact with that email address.
30 my @invoice_dests = qsearch({
31   select    => 'cust_main_invoice.*',
32   table     => 'cust_main_invoice',
33   hashref   => { 'dest' => { op=>'!=', value=>'POST' } },
34   addl_from => ' LEFT JOIN contact_email ON
35      (cust_main_invoice.dest    = contact_email.emailaddress)',
36   extra_sql => ' AND contact_email.contactnum IS NULL',
37 });
38 print "Found email destinations: ".scalar(@invoice_dests)."\n";
39 my %email_used;
40   
41 foreach my $invoice_dest (@invoice_dests) {
42   my $cust_main = $invoice_dest->cust_main;
43   my $last = $cust_main->get('last');
44   my $first = $cust_main->get('first');
45   my $email = $invoice_dest->dest;
46   print "$first $last <$email>\n";
47   if (exists $email_used{$email}) {
48     print "-- in use by cust#$email_used{$email}\n";
49     next;
50   }
51   $email_used{$email} = $cust_main->custnum;
52
53   my $contact = qsearchs('contact', {
54     'custnum' => $invoice_dest->custnum,
55     'last'    => $last,
56     'first'   => $first,
57   });
58   if ($contact) {
59     my $contact_email = FS::contact_email->new({
60       'contactnum'    => $contact->contactnum,
61       'emailaddress'  => $email
62     });
63     $error = $contact_email->insert;
64     die "inserting contact email: $error\n" if $error;
65   } else {
66     # use the 'emailaddress' param here so that send_reset_email will
67     # work right
68     $contact = FS::contact->new({
69       'custnum'     => $invoice_dest->custnum,
70       'locationnum' => $cust_main->bill_locationnum,
71       'last'        => $last,
72       'first'       => $first,
73       'classnum'    => $classnum,
74       'selfservice_access' => 'Y',
75       'emailaddress'  => $email,
76       '_password'   => '',
77       '_password_encoding' => '',
78     });
79     $error = $contact->insert;
80     die "inserting contact: $error\n" if $error;
81   }
82 }
83 dbh->commit;
84 print "Finished!\n";
85