Código
Basado en el Reloj de Cobranza que diseñé en Totalplay
Motor de enrutamiento de cobranza
Un millón de cuentas por ciclo, en paralelo y escalado horizontalmente.
14 archivos710 líneas de código 12/12 pruebas
using CollectionRouter.Domain;
namespace CollectionRouter.Rules;
/// <summary>
/// Reglas de enrutamiento como función pura: misma cuenta + mismo ciclo = misma decisión.
/// Al no tener estado ni E/S, se pueden ejecutar en paralelo sin bloqueos y probar sin infraestructura.
/// </summary>
public static class RoutingRules
{
public static RoutingDecision Route(Account account, string cycleId)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentException.ThrowIfNullOrWhiteSpace(cycleId);
// 1. Exclusiones: nunca se gestiona una cuenta en disputa o con promesa vigente.
if (account.IsDisputed)
return Decide(account, cycleId, Stage.Hold, ContactChannel.None, 0, "Cuenta en disputa");
if (account.HasActivePaymentPromise)
return Decide(account, cycleId, Stage.Hold, ContactChannel.None, 0, "Promesa de pago vigente");
// 2. Etapa por días de atraso.
var stage = account.DaysPastDue switch
{
<= 0 => Stage.Preventive,
<= 30 => Stage.Early,
<= 90 => Stage.Late,
_ => Stage.PreLegal,
};
// 3. Canal: se escala cuando los canales automáticos ya no responden.
var channel = (stage, account.Segment, account.FailedContactsThisCycle) switch
{
(Stage.PreLegal, _, _) => ContactChannel.SpecializedAgent,
(_, Segment.Enterprise, _) => ContactChannel.SpecializedAgent,
(Stage.Preventive, _, _) => ContactChannel.Sms,
(Stage.Early, _, < 2) => ContactChannel.Sms,
(Stage.Early, _, < 4) => ContactChannel.Ivr,
(Stage.Late, _, < 2) => ContactChannel.Ivr,
_ => ContactChannel.Agent,
};
// 4. Prioridad (0-100): monto y antigüedad pesan más que el segmento.
var amountScore = (int)Math.Min(50m, account.PastDueAmount / 200m);
var ageScore = Math.Min(40, account.DaysPastDue / 3);
var segmentScore = account.Segment == Segment.Enterprise ? 10 : 0;
var priority = Math.Clamp(amountScore + ageScore + segmentScore, 0, 100);
return Decide(account, cycleId, stage, channel, priority,
$"{account.DaysPastDue} días de atraso, {account.FailedContactsThisCycle} contactos fallidos");
}
private static RoutingDecision Decide(Account a, string cycleId, Stage stage, ContactChannel channel, int priority, string reason) =>
new(a.Id, cycleId, stage, channel, priority, reason);
}