35b81f859431397a6d988629e4787b34a285ea5b
[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,
29 # except those where the customer already has a contact with that
30 # email address.
31 my @invoice_dests = qsearch({
32   select    => 'cust_main_invoice.*',
33   table     => 'cust_main_invoice',
34   hashref   => { 'dest' => { op=>'!=', value=>'POST' } },
35   addl_from => ' LEFT JOIN (contact JOIN contact_email USING (contactnum)) ON
36     (cust_main_invoice.custnum = contact.custnum AND
37      cust_main_invoice.dest    = contact_email.emailaddress)',
38   extra_sql => ' AND contact.contactnum IS NULL',
39 });
40 print "Found email destinations: ".scalar(@invoice_dests)."\n";
41   
42 foreach my $invoice_dest (@invoice_dests) {
43   my $cust_main = $invoice_dest->cust_main;
44   my $last = $cust_main->get('last');
45   my $first = $cust_main->get('first');
46   my $email = $invoice_dest->dest;
47   print "$first $last <$email>\n";
48
49   my $contact = qsearchs('contact', {
50     'custnum' => $invoice_dest->custnum,
51     'last'    => $last,
52     'first'   => $first,
53   });
54   if ($contact) {
55     my $contact_email = FS::contact_email->new({
56       'contactnum'    => $contact->contactnum,
57       'emailaddress'  => $email
58     });
59     $error = $contact_email->insert;
60     die "inserting contact email: $error\n" if $error;
61   } else {
62     # use the 'emailaddress' param here so that send_reset_email will
63     # work right
64     $contact = FS::contact->new({
65       'custnum'     => $invoice_dest->custnum,
66       'locationnum' => $cust_main->bill_locationnum,
67       'last'        => $last,
68       'first'       => $first,
69       'classnum'    => $classnum,
70       'selfservice_access' => 'Y',
71       'emailaddress'  => $email,
72       '_password'   => '',
73       '_password_encoding' => '',
74     });
75     $error = $contact->insert;
76     die "inserting contact: $error\n" if $error;
77   }
78 }
79 dbh->commit;
80 print "Finished!\n";
81