def record_payin_transfer_reversal(
    db, pt_id, remote_id, amount, payin_refund_id=None, ctime=None
):
    """Record a transfer reversal.

    Args:
        pt_id (int): the ID of the reversed transfer in our database
        remote_id (int): the ID of the reversal in the payment processor's database
        amount (Money): the reversal amount, must be less or equal to the transfer amount
        payin_refund_id (int): the ID of the associated payin refund in our database
        ctime (datetime): when the refund was initiated

    Returns:
        Record: the row inserted in the `payin_transfer_reversals` table

    """
    return db.one("""
        INSERT INTO payin_transfer_reversals
               (payin_transfer, remote_id, amount, payin_refund,
                ctime)
        VALUES (%(pt_id)s, %(remote_id)s, %(amount)s, %(payin_refund_id)s,
                coalesce(%(ctime)s, current_timestamp))
   ON CONFLICT (payin_transfer, remote_id) DO UPDATE
           SET amount = excluded.amount
             , payin_refund = excluded.payin_refund
     RETURNING *
    """, locals())