v3: prevent CARD/CHEK customers from inadvertantly going off auto-pay making an early...
[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     or next; #cust_main_invoice.custnum points to non-existant customer?
44              #will need to be fixed before v4 upgrade, but this can still run..
45   my $last = $cust_main->get('last');
46   my $first = $cust_main->get('first');
47   my $email = $invoice_dest->dest;
48   print "$first $last <$email>\n";
49   if (exists $email_used{$email}) {
50     print "-- in use by cust#$email_used{$email}\n";
51     next;
52   }
53   $email_used{$email} = $cust_main->custnum;
54
55   my $contact = qsearchs('contact', {
56     'custnum' => $invoice_dest->custnum,
57     'last'    => $last,
58     'first'   => $first,
59   });
60   if ($contact) {
61     my $contact_email = FS::contact_email->new({
62       'contactnum'    => $contact->contactnum,
63       'emailaddress'  => $email
64     });
65     $error = $contact_email->insert;
66     die "inserting contact email: $error\n" if $error;
67   } else {
68     # use the 'emailaddress' param here so that send_reset_email will
69     # work right
70     $contact = FS::contact->new({
71       'custnum'     => $invoice_dest->custnum,
72       'locationnum' => $cust_main->bill_locationnum,
73       'last'        => $last,
74       'first'       => $first,
75       'classnum'    => $classnum,
76       'selfservice_access' => 'Y',
77       'emailaddress'  => $email,
78       '_password'   => '',
79       '_password_encoding' => '',
80     });
81     $error = $contact->insert;
82     die "inserting contact: $error\n" if $error;
83   }
84 }
85 dbh->commit;
86 print "Finished!\n";
87