'When a CourseEnrollment object calls its unenroll method, this function checks to see if that unenrollment
occurred in a verified certificate that was within the refund deadline.  If so, it actually performs the
refund.
Returns the refunded certificate on a successful refund; else, it returns nothing.'

@receiver(UNENROLL_DONE)
def refund_cert_callback(sender, course_enrollment=None, skip_refund=False, **kwargs):

    if ((not course_enrollment.refundable()) or skip_refund):
        return
    target_certs = CertificateItem.objects.filter(course_id=course_enrollment.course_id, user_id=course_enrollment.user, status='purchased', mode='verified')
    try:
        target_cert = target_certs[0]
    except IndexError:
        log.warning(u'Matching    CertificateItem    not    found    while    trying    to    refund.    User    %s,    Course    %s', course_enrollment.user, course_enrollment.course_id)
        return
    target_cert.status = 'refunded'
    target_cert.refund_requested_time = datetime.now(pytz.utc)
    target_cert.save()
    target_cert.order.refund()
    order_number = target_cert.order_id
    subject = _('[Refund]    User-Requested    Refund')
    message = 'User    {user}    ({user_email})    has    requested    a    refund    on    Order    #{order_number}.'.format(user=course_enrollment.user, user_email=course_enrollment.user.email, order_number=order_number)
    to_email = [settings.PAYMENT_SUPPORT_EMAIL]
    from_email = configuration_helpers.get_value('payment_support_email', settings.PAYMENT_SUPPORT_EMAIL)
    try:
        send_mail(subject, message, from_email, to_email, fail_silently=False)
    except Exception as exception:
        err_str = 'Failed    sending    email    to    billing    to    request    a    refund    for    verified    certificate    (User    {user},    Course    {course},    CourseEnrollmentID    {ce_id},    Order    #{order})\n{exception}'
        log.error(err_str.format(user=course_enrollment.user, course=course_enrollment.course_id, ce_id=course_enrollment.id, order=order_number, exception=exception))
    return target_cert
