add condition_sql optimization to "Customer does not have uncancelled package of...
[freeside.git] / bin / contact-upgrade-fix-multiple
1 #!/usr/bin/perl
2
3 use FS::UID qw(adminsuidsetup);
4 use FS::cust_main_invoice;
5 use FS::Record qw(qsearch qsearchs dbh);
6 use FS::cust_main;
7 use Date::Parse 'str2time';
8 use strict;
9
10 my $usage = "usage: contact-upgrade-fix-multiple <user> <upgrade date>\n";
11
12 my $user = shift or die $usage;
13 adminsuidsetup($user);
14 local $FS::UID::AutoCommit = 0;
15
16 my $date = shift;
17 my $timestamp = str2time($date) or die $usage;
18 # safety
19 die "upgrade date is before the 4.0 release, must be incorrect.\n$usage"
20   if $timestamp < 1455609600;
21
22 my $search = {
23   'table'     => 'h_cust_main_invoice',
24   'hashref'   => {
25     'history_date'    => { op => '>=', value => $timestamp },
26     'history_action'  => 'delete',
27     'dest'            => { op => '!=', value => 'POST' },
28   }
29 };
30
31 # find deleted cust_main_invoice records
32 my %custnum_dest;
33 foreach my $deleted (qsearch $search) {
34   my $custnum = $deleted->custnum;
35   push @{ $custnum_dest{$custnum} ||= [] }, $deleted->dest;
36 }
37
38 # find those customers
39 while (my ($custnum, $dests) = each(%custnum_dest)) {
40   my $cust_main = FS::cust_main->by_key($custnum);
41   # filter out the email(s) that the customer already has
42   my @curr_dest = $cust_main->invoicing_list_email;
43   my @new_dest = @curr_dest;
44   print "cust#$custnum\n";
45   foreach my $email ( @$dests ) {
46     print "      $email: ";
47     if ( grep { $_ eq $email } @curr_dest ) {
48       print "skipped.\n";
49       next;
50     }
51     print "appending.\n";
52     push @new_dest, $email;
53   }
54   my $error = $cust_main->replace( invoicing_list => \@new_dest );
55   die $error if $error;
56 }
57
58 dbh->commit;
59 print "Done.\n";
60