denny/ShinyCMS

View on GitHub
bin/dev-tools/fix-mail-recipients

Summary

Maintainability
Test Coverage
#!/usr/bin/env perl

# ===================================================================
# File:        bin/dev-tools/fix-mail-recipients
# Project:    ShinyCMS
# Purpose:    Fix duplicates in mail_recipient table
# Author:    Denny de la Haye <2019@denny.me>
# 
# ShinyCMS is free software; you can redistribute it and/or modify it
# under the terms of either the GPL 2.0 or the Artistic License 2.0
# ===================================================================

use strict;
use warnings;

# Load local helper script for fetching schema
use FindBin qw( $Bin );
use lib "$Bin/../lib";
require 'helpers.pl';  ## no critic

my $schema = get_schema();


my @mail_recipients = $schema->resultset( 'MailRecipient' )->all;

my %emails;
foreach my $mr ( @mail_recipients ) {
    my $email = $mr->email;
    $email =~ s/[<>]//g;
    $emails{ $email }++;
}

foreach my $email ( keys %emails ) {
    my $mail_recipients = $schema->resultset( 'MailRecipient' )->search(
        {
            email => { -like => '%'.$email.'%' },
        },
        {
            order_by => 'id',
        }
    );
    
    next if $mail_recipients->count == 1;
    warn $email if $mail_recipients->count == 0;    # shouldn't happen?!
    
    my $mr_id = $mail_recipients->first->id;
    
    while ( my $mr = $mail_recipients->next ) {
        my $list_recipients = $mr->list_recipients;
        $list_recipients->update({ recipient => $mr_id });
    }

    $mail_recipients->search({ id => { '!=' => $mr_id } })->delete;
}