summaryrefslogtreecommitdiff
path: root/bin/contact-upgrade-fix-multiple
blob: f5d68fc01dc67db80ac7d3db8cb6623aec1b41a1 (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
#!/usr/bin/perl

use FS::UID qw(adminsuidsetup);
use FS::cust_main_invoice;
use FS::Record qw(qsearch qsearchs dbh);
use FS::cust_main;
use Date::Parse 'str2time';
use strict;

my $usage = "usage: contact-upgrade-fix-multiple <user> <upgrade date>\n";

my $user = shift or die $usage;
adminsuidsetup($user);
local $FS::UID::AutoCommit = 0;

my $date = shift;
my $timestamp = str2time($date) or die $usage;
# safety
die "upgrade date is before the 4.0 release, must be incorrect.\n$usage"
  if $timestamp < 1455609600;

my $search = {
  'table'     => 'h_cust_main_invoice',
  'hashref'   => {
    'history_date'    => { op => '>=', value => $timestamp },
    'history_action'  => 'delete',
    'dest'            => { op => '!=', value => 'POST' },
  }
};

# find deleted cust_main_invoice records
my %custnum_dest;
foreach my $deleted (qsearch $search) {
  my $custnum = $deleted->custnum;
  push @{ $custnum_dest{$custnum} ||= [] }, $deleted->dest;
}

# find those customers
while (my ($custnum, $dests) = each(%custnum_dest)) {
  my $cust_main = FS::cust_main->by_key($custnum);
  # filter out the email(s) that the customer already has
  my @curr_dest = $cust_main->invoicing_list_email;
  my @new_dest = @curr_dest;
  print "cust#$custnum\n";
  foreach my $email ( @$dests ) {
    print "      $email: ";
    if ( grep { $_ eq $email } @curr_dest ) {
      print "skipped.\n";
      next;
    }
    print "appending.\n";
    push @new_dest, $email;
  }
  my $error = $cust_main->replace( invoicing_list => \@new_dest );
  die $error if $error;
}

dbh->commit;
print "Done.\n";