-
Notifications
You must be signed in to change notification settings - Fork 2
/
CustomerRiskAssessor.cs
76 lines (65 loc) · 2.52 KB
/
CustomerRiskAssessor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using Codat.Demos.InvoiceFinancing.Api.Mappers;
using Codat.Demos.InvoiceFinancing.Api.Models;
using Codat.Lending;
using Codat.Lending.Models.Operations;
namespace Codat.Demos.InvoiceFinancing.Api.Services;
public interface ICustomerRiskAssessor
{
Task<CustomerRisk> AssessCustomerRisk(Guid companyId, Customer customer, IEnumerable<Invoice> unpaidInvoicesForCompany, decimal totalAmountDueForCompany);
}
public class CustomerRiskAssessor : ICustomerRiskAssessor
{
private readonly ICodatLending _codatLending;
public CustomerRiskAssessor(ICodatLending codatLending)
{
_codatLending = codatLending;
}
public async Task<CustomerRisk> AssessCustomerRisk(
Guid companyId,
Customer customer,
IEnumerable<Invoice> unpaidInvoicesForCompany,
decimal totalAmountDueForCompany
)
{
var customerPaidInvoices = await GetPaidInvoicesForCustomerAsync(companyId.ToString(), customer.Id);
if (customerPaidInvoices.Length < 2)
{
// Discard customers with fewer than 2 paid invoices (max risk)
return new CustomerRisk
{
CustomerId = customer.Id,
Risk = 1m
};
}
var customerUnpaidInvoices = unpaidInvoicesForCompany.Where(y => y.CustomerRef.Id == customer.Id).ToList();
var totalAmountDueForCustomer = customerUnpaidInvoices.Sum(y => y.AmountDue);
var risk = totalAmountDueForCustomer / totalAmountDueForCompany;
return new CustomerRisk
{
CustomerId = customer.Id,
Risk = risk
};
}
private async Task<Invoice[]> GetPaidInvoicesForCustomerAsync(string companyId, string customerId)
{
var invoices = new List<Invoice>();
var page = 1;
ListAccountingInvoicesResponse pagedResult;
do
{
pagedResult = await _codatLending.AccountsReceivable.Invoices.ListAsync(new()
{
CompanyId = companyId,
Query = $"status=paid&&customerRef.id={customerId}",
Page = page
});
if (!pagedResult.RawResponse.IsSuccessStatusCode)
{
continue;
}
invoices.AddRange(pagedResult.AccountingInvoices.Results.Select(InvoiceMapper.MapToDomainModel));
page++;
} while (pagedResult.AccountingInvoices.PageNumber * pagedResult.AccountingInvoices.PageSize < pagedResult.AccountingInvoices.TotalResults);
return invoices.ToArray();
}
}