summaryrefslogtreecommitdiff
path: root/bin/create-billing-contacts-v3
blob: c8ccd59baa44d924cd180c4a43e9a0fccf94ce11 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/perl

use strict;
use FS::Misc::Getopt;
use FS::Record qw(qsearchs qsearch dbh);
use FS::cust_main;
use FS::cust_main_invoice;
use FS::contact;

our %opt;
getopts('c:'); # contact classname

$FS::UID::AutoCommit = 0;

my $error;

my $classnum = '';
if ( $opt{c} ) {
  my $class = qsearchs('contact_class', { classname => $opt{c} });
  if (!$class) {
    $class = FS::contact_class->new({ classname => $opt{c} });
    $error = $class->insert;
    die $error if $error;
  }
  $classnum = $class->classnum;
}

# Find all invoice destinations that are email addresses, except those where
# there is already a contact with that email address.
my @invoice_dests = qsearch({
  select    => 'cust_main_invoice.*',
  table     => 'cust_main_invoice',
  hashref   => { 'dest' => { op=>'!=', value=>'POST' } },
  addl_from => ' LEFT JOIN contact_email ON
     (cust_main_invoice.dest    = contact_email.emailaddress)',
  extra_sql => ' AND contact_email.contactnum IS NULL',
});
print "Found email destinations: ".scalar(@invoice_dests)."\n";
my %email_used;
  
foreach my $invoice_dest (@invoice_dests) {
  my $cust_main = $invoice_dest->cust_main
    or next; #cust_main_invoice.custnum points to non-existant customer?
             #will need to be fixed before v4 upgrade, but this can still run..
  my $last = $cust_main->get('last');
  my $first = $cust_main->get('first');
  my $email = $invoice_dest->dest;
  print "$first $last <$email>\n";
  if (exists $email_used{$email}) {
    print "-- in use by cust#$email_used{$email}\n";
    next;
  }
  $email_used{$email} = $cust_main->custnum;

  my $contact = qsearchs('contact', {
    'custnum' => $invoice_dest->custnum,
    'last'    => $last,
    'first'   => $first,
  });
  if ($contact) {
    my $contact_email = FS::contact_email->new({
      'contactnum'    => $contact->contactnum,
      'emailaddress'  => $email
    });
    $error = $contact_email->insert;
    die "inserting contact email: $error\n" if $error;
  } else {
    # use the 'emailaddress' param here so that send_reset_email will
    # work right
    $contact = FS::contact->new({
      'custnum'     => $invoice_dest->custnum,
      'locationnum' => $cust_main->bill_locationnum,
      'last'        => $last,
      'first'       => $first,
      'classnum'    => $classnum,
      'selfservice_access' => 'Y',
      'emailaddress'  => $email,
      '_password'   => '',
      '_password_encoding' => '',
    });
    $error = $contact->insert;
    die "inserting contact: $error\n" if $error;
  }
}
dbh->commit;
print "Finished!\n";