Skip to content

Commit e30736d

Browse files
author
support
committed
Trade credit, PO number and payment due date for company accounts
Company accounts can pay by invoice on trade credit, and every order can carry the buyer's purchase order number and, when bought on credit, a payment due date. - Customer: CreditLimit and PaymentTermDays on the company owner; a sub-account buys on its owner's credit. Set in Admin and in the Store panel, with validation and the outstanding amount shown on the account. - Order: PurchaseOrderNumber and PaymentDueDateUtc. ICompanyCreditService sums what a company owes (unpaid orders bought on credit, in the primary currency); an order is overdue once its due date has passed. - Checkout: OrderSettings.PurchaseOrderNumberMode (disabled, optional, required) asks for the PO number at the confirm step. The number is shown on the storefront, in Admin, Store and Vendor, on the PDF invoice and as an e-mail token, always encoded. - Order lists in Admin and Store filter by PO number and overdue payments. - Payments.OnAccount plugin ("Pay by invoice"): offered while the cart subtotal fits the available credit, checked again on the exact amount when the order is placed, so a hidden method posted anyway is refused. It sets the due date through ProcessPaymentResult.PaymentDueDateUtc. - Orders bought on credit are left out of the unpaid-order cancellation. - Migration and installer add the OwnerId_PaymentDueDateUtc order index. Known limits: the credit limit is soft (two orders placed at the same moment can overrun it), the term counts from placement, there are no payment reminders yet, and PO number and due date cannot be edited in the back office.
1 parent c7757af commit e30736d

81 files changed

Lines changed: 2518 additions & 15 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎GrandNode.slnx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
<Project Path="src/Plugins/ExchangeRate.McExchange/ExchangeRate.McExchange.csproj" />
4343
<Project Path="src/Plugins/Payments.BrainTree/Payments.BrainTree.csproj" />
4444
<Project Path="src/Plugins/Payments.CashOnDelivery/Payments.CashOnDelivery.csproj" />
45+
<Project Path="src/Plugins/Payments.OnAccount/Payments.OnAccount.csproj" />
4546
<Project Path="src/Plugins/Payments.StripeCheckout/Payments.StripeCheckout.csproj" />
4647
<Project Path="src/Plugins/Shipping.ByWeight/Shipping.ByWeight.csproj" />
4748
<Project Path="src/Plugins/Shipping.FixedRateShipping/Shipping.FixedRateShipping.csproj" />

‎src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,17 @@ public async Task<PlaceOrderResult> Handle(PlaceOrderCommand command, Cancellati
169169
if (result.Errors.Any())
170170
return result;
171171

172+
//the buyer's purchase order number is checked before any payment is taken
173+
details.PurchaseOrderNumber = PurchaseOrderNumberRules.Normalize(command.PurchaseOrderNumber,
174+
_orderSettings.PurchaseOrderNumberMode);
175+
var purchaseOrderNumberError = PurchaseOrderNumberRules.Validate(details.PurchaseOrderNumber,
176+
_orderSettings.PurchaseOrderNumberMode);
177+
if (purchaseOrderNumberError != null)
178+
{
179+
result.AddError(_translationService.GetResource(purchaseOrderNumberError, command.Language.Id));
180+
return result;
181+
}
182+
172183
//an order over the customer's limit is placed awaiting an approval, with an allowed payment method only
173184
var approval = await _orderApprovalService.RequiresApproval(details.Cart, details.Context);
174185
details.ApprovalRequired = approval.Required;
@@ -922,6 +933,7 @@ protected virtual Order PrepareOrderHeader(PaymentTransaction paymentTransaction
922933
StoreId = paymentTransaction.StoreId,
923934
OrderGuid = paymentTransaction.OrderGuid,
924935
Code = paymentTransaction.OrderCode,
936+
PurchaseOrderNumber = details.PurchaseOrderNumber,
925937
CustomerId = details.Customer.Id,
926938
OwnerId = string.IsNullOrEmpty(details.Customer.OwnerId) ? details.Customer.Id : details.Customer.OwnerId,
927939
SeId = details.Customer.SeId,
@@ -957,6 +969,7 @@ protected virtual Order PrepareOrderHeader(PaymentTransaction paymentTransaction
957969
PaymentStatusId = paymentStatus,
958970
PaidAmount = processPaymentResult.PaidAmount,
959971
PaidDateUtc = processPaymentResult.PaidAmount > 0 ? DateTime.UtcNow : null,
972+
PaymentDueDateUtc = processPaymentResult.PaymentDueDateUtc,
960973
BillingAddress = details.BillingAddress,
961974
ShippingAddress = details.ShippingAddress,
962975
ShippingStatusId = details.ShippingStatus,

‎src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using Grand.Data;
33
using Grand.Domain;
44
using Grand.Domain.Orders;
5+
using Grand.Domain.Payments;
56
using Grand.Mediator;
67

78
namespace Grand.Business.Checkout.Queries.Handlers.Orders;
@@ -92,6 +93,23 @@ public async Task<IPagedList<Order>> Handle(GetOrderQuery request, CancellationT
9293
if (!string.IsNullOrEmpty(request.OrderTagId))
9394
query = query.Where(o => o.OrderTags.Any(y => y == request.OrderTagId));
9495

96+
if (!string.IsNullOrWhiteSpace(request.PurchaseOrderNumber))
97+
{
98+
var purchaseOrderNumber = request.PurchaseOrderNumber.Trim();
99+
query = query.Where(o => o.PurchaseOrderNumber == purchaseOrderNumber);
100+
}
101+
102+
//the same rule as PaymentExtensions.IsPaymentOverdue
103+
if (request.OverdueOnly)
104+
{
105+
var today = DateTime.UtcNow.Date;
106+
query = query.Where(o => o.PaymentDueDateUtc != null && o.PaymentDueDateUtc < today &&
107+
o.OrderStatusId != (int)OrderStatusSystem.Cancelled &&
108+
(o.PaymentStatusId == PaymentStatus.Pending ||
109+
o.PaymentStatusId == PaymentStatus.Authorized ||
110+
o.PaymentStatusId == PaymentStatus.PartiallyPaid));
111+
}
112+
95113
query = query.Where(o => !o.Deleted);
96114
query = query.OrderByDescending(o => o.CreatedOnUtc);
97115

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
using Grand.Business.Core.Interfaces.Checkout.Orders;
2+
using Grand.Business.Core.Interfaces.Customers;
3+
using Grand.Business.Core.Utilities.Checkout;
4+
using Grand.Data;
5+
using Grand.Domain.Customers;
6+
using Grand.Domain.Orders;
7+
using Grand.Domain.Payments;
8+
9+
namespace Grand.Business.Checkout.Services.Orders;
10+
11+
/// <summary>
12+
/// Company credit service
13+
/// </summary>
14+
public class CompanyCreditService : ICompanyCreditService
15+
{
16+
#region Ctor
17+
18+
public CompanyCreditService(IRepository<Order> orderRepository, ICustomerService customerService)
19+
{
20+
_orderRepository = orderRepository;
21+
_customerService = customerService;
22+
}
23+
24+
#endregion
25+
26+
#region Fields
27+
28+
private readonly IRepository<Order> _orderRepository;
29+
private readonly ICustomerService _customerService;
30+
31+
#endregion
32+
33+
#region Utilities
34+
35+
/// <summary>
36+
/// Gets the company's orders bought on credit that are not paid yet
37+
/// </summary>
38+
private IQueryable<Order> UnpaidCreditOrders(string companyOwnerId)
39+
{
40+
return _orderRepository.Table.Where(o =>
41+
o.OwnerId == companyOwnerId &&
42+
o.PaymentDueDateUtc != null &&
43+
!o.Deleted &&
44+
o.OrderStatusId != (int)OrderStatusSystem.Cancelled &&
45+
(o.PaymentStatusId == PaymentStatus.Pending ||
46+
o.PaymentStatusId == PaymentStatus.Authorized ||
47+
o.PaymentStatusId == PaymentStatus.PartiallyPaid));
48+
}
49+
50+
#endregion
51+
52+
#region Methods
53+
54+
public virtual async Task<CompanyCredit> GetCompanyCredit(Customer customer)
55+
{
56+
ArgumentNullException.ThrowIfNull(customer);
57+
58+
var companyOwnerId = OrderApprovalRules.CompanyId(customer);
59+
var owner = string.IsNullOrEmpty(customer.OwnerId)
60+
? customer
61+
: await _customerService.GetCustomerById(customer.OwnerId);
62+
63+
if (owner is not { Active: true, Deleted: false } ||
64+
!owner.CreditLimit.HasValue || !owner.PaymentTermDays.HasValue)
65+
return CompanyCredit.None(companyOwnerId);
66+
67+
var outstanding = await GetOutstandingAmount(companyOwnerId);
68+
var hasOverdue = await HasOverdue(companyOwnerId, DateTime.UtcNow);
69+
70+
return new CompanyCredit(companyOwnerId, owner.CreditLimit, owner.PaymentTermDays, outstanding,
71+
hasOverdue);
72+
}
73+
74+
public virtual async Task<double> GetOutstandingAmount(string companyOwnerId)
75+
{
76+
if (string.IsNullOrEmpty(companyOwnerId))
77+
return 0;
78+
79+
var query = UnpaidCreditOrders(companyOwnerId)
80+
.Select(o => new { o.OrderTotal, o.PaidAmount, o.CurrencyRate });
81+
var orders = await _orderRepository.ToListAsync(query);
82+
83+
// the same conversion to the primary currency as the order reports use
84+
return orders.Sum(o => (o.OrderTotal - o.PaidAmount) / (o.CurrencyRate > 0 ? o.CurrencyRate : 1));
85+
}
86+
87+
public virtual async Task<bool> HasOverdue(string companyOwnerId, DateTime utcNow)
88+
{
89+
if (string.IsNullOrEmpty(companyOwnerId))
90+
return false;
91+
92+
//the due date is a calendar day: overdue once it has passed, as in PaymentExtensions.IsPaymentOverdue
93+
var today = utcNow.Date;
94+
return await _orderRepository.AnyAsync(
95+
UnpaidCreditOrders(companyOwnerId).Where(o => o.PaymentDueDateUtc < today));
96+
}
97+
98+
#endregion
99+
}

‎src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,8 @@ public virtual async Task<IPagedList<Order>> SearchOrders(string storeId = "",
182182
DateTime? createdFromUtc = null, DateTime? createdToUtc = null,
183183
int? os = null, PaymentStatus? ps = null, ShippingStatus? ss = null,
184184
string billingEmail = null, string billingLastName = "", string orderGuid = null,
185-
string orderCode = null, int pageIndex = 0, int pageSize = int.MaxValue, string orderTagId = "")
185+
string orderCode = null, int pageIndex = 0, int pageSize = int.MaxValue, string orderTagId = "",
186+
string purchaseOrderNumber = null, bool overdueOnly = false)
186187
{
187188
var queryModel = new GetOrderQuery {
188189
AffiliateId = affiliateId,
@@ -206,7 +207,9 @@ public virtual async Task<IPagedList<Order>> SearchOrders(string storeId = "",
206207
WarehouseId = warehouseId,
207208
OrderTagId = orderTagId,
208209
OwnerId = ownerId,
209-
SalesEmployeeId = salesEmployeeId
210+
SalesEmployeeId = salesEmployeeId,
211+
PurchaseOrderNumber = purchaseOrderNumber,
212+
OverdueOnly = overdueOnly
210213
};
211214
return await _mediator.Send(queryModel);
212215
}
@@ -266,7 +269,9 @@ public virtual async Task UpdateOrder(Order order)
266269
public async Task CancelExpiredOrders(DateTime expirationDateUtc, CancellationToken cancellationToken = default)
267270
{
268271
var orders = _orderRepository.Table
272+
//an order bought on credit is unpaid on purpose until its due date, not an abandoned payment
269273
.Where(o => o.CreatedOnUtc < expirationDateUtc && o.PaymentStatusId == PaymentStatus.Pending &&
274+
o.PaymentDueDateUtc == null &&
270275
o.OrderStatusId == (int)OrderStatusSystem.Pending &&
271276
(o.ShippingStatusId == ShippingStatus.Pending
272277
|| o.ShippingStatusId == ShippingStatus.ShippingNotRequired))

‎src/Business/Grand.Business.Checkout/Startup/StartupApplication.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ private static void RegisterOrdersService(IServiceCollection serviceCollection)
5151
serviceCollection.AddScoped<ILoyaltyPointsCalculationService, LoyaltyPointsCalculationService>();
5252
serviceCollection.AddScoped<IMerchandiseReturnService, MerchandiseReturnService>();
5353
serviceCollection.AddScoped<IOrderApprovalService, OrderApprovalService>();
54+
serviceCollection.AddScoped<ICompanyCreditService, CompanyCreditService>();
5455
serviceCollection.AddScoped<ILoyaltyPointsService, LoyaltyPointsService>();
5556
serviceCollection.AddScoped<IShoppingCartService, ShoppingCartService>();
5657
serviceCollection.AddScoped<IShoppingCartValidator, ShoppingCartValidator>();

‎src/Business/Grand.Business.Common/Services/Pdf/PdfService.cs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ private async Task ComposeOrder(PdfComposer pdf, Order order, string vendorId, b
174174
await _mediator.Publish(paymentLines);
175175
billing = await AddressCell(order.BillingAddress, "PDFInvoice", "PDFInvoice.BillingInformation", lang,
176176
Format("PDFInvoice.PaymentMethod", lang, paymentMethod.GetPaymentMethodName(order)),
177-
paymentLines.Lines.Select(PdfHtmlText.ToPlainText));
177+
paymentLines.Lines.Select(PdfHtmlText.ToPlainText).Concat(PaymentTermsLines(order, lang)));
178178
}
179179

180180
var shipping = order.ShippingAddress == null
@@ -398,6 +398,15 @@ private async Task<byte[]> LoadLogo()
398398
}
399399
}
400400

401+
//the PO number is the buyer's own text, printed as typed; the due date is a calendar date
402+
private IEnumerable<string> PaymentTermsLines(Order order, string lang)
403+
{
404+
if (!string.IsNullOrEmpty(order.PurchaseOrderNumber))
405+
yield return Format("PDFInvoice.PurchaseOrderNumber", lang, order.PurchaseOrderNumber);
406+
if (order.PaymentDueDateUtc.HasValue)
407+
yield return Format("PDFInvoice.PaymentDueDate", lang, order.PaymentDueDateUtc.Value.ToString("yyyy-MM-dd"));
408+
}
409+
401410
private string Format(string resourceKey, string lang, object value)
402411
{
403412
return string.Format(_translationService.GetResource(resourceKey, lang), value);

‎src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceOrderCommand.cs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,9 @@ public class PlaceOrderCommand : IRequest<PlaceOrderResult>
2727
/// Staff member who places the order while impersonating the customer, if any
2828
/// </summary>
2929
public Customer OriginalCustomerIfImpersonated { get; set; }
30+
31+
/// <summary>
32+
/// Buyer's own purchase order number, if any
33+
/// </summary>
34+
public string PurchaseOrderNumber { get; set; }
3035
}

‎src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,24 @@ public static string GetPaymentMethodName(this IPaymentProvider paymentMethod, O
5050

5151
return string.IsNullOrEmpty(name) ? order.PaymentMethodSystemName : name;
5252
}
53+
54+
/// <summary>
55+
/// Gets a value indicating whether the payment of an order bought on credit is overdue: the order is not
56+
/// cancelled, not paid yet and its due date has passed. The due date is a calendar day (UTC), so the
57+
/// payment becomes overdue the day after it.
58+
/// </summary>
59+
/// <param name="order">Order</param>
60+
/// <param name="utcNow">Current date and time in UTC</param>
61+
/// <returns>Result</returns>
62+
public static bool IsPaymentOverdue(this Order order, DateTime utcNow)
63+
{
64+
ArgumentNullException.ThrowIfNull(order);
65+
66+
return order.PaymentDueDateUtc.HasValue &&
67+
order.PaymentDueDateUtc.Value < utcNow.Date &&
68+
!order.Deleted &&
69+
order.OrderStatusId != (int)OrderStatusSystem.Cancelled &&
70+
order.PaymentStatusId is PaymentStatus.Pending or PaymentStatus.Authorized
71+
or PaymentStatus.PartiallyPaid;
72+
}
5373
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
using Grand.Business.Core.Utilities.Checkout;
2+
using Grand.Domain.Customers;
3+
4+
namespace Grand.Business.Core.Interfaces.Checkout.Orders;
5+
6+
/// <summary>
7+
/// Trade credit of company accounts: the limit and term set on the company owner, and what the company owes
8+
/// on orders bought on credit
9+
/// </summary>
10+
public interface ICompanyCreditService
11+
{
12+
/// <summary>
13+
/// Gets the trade credit the customer buys with: the customer's own for a company owner, the owner's for
14+
/// a sub-account. The credit is disabled when the owner is missing, deleted or inactive.
15+
/// </summary>
16+
/// <param name="customer">Customer</param>
17+
Task<CompanyCredit> GetCompanyCredit(Customer customer);
18+
19+
/// <summary>
20+
/// Gets the unpaid amount of the company's orders bought on credit, in the primary store currency
21+
/// </summary>
22+
/// <param name="companyOwnerId">Identifier of the company owner</param>
23+
Task<double> GetOutstandingAmount(string companyOwnerId);
24+
25+
/// <summary>
26+
/// Gets a value indicating whether any of the company's orders bought on credit is past its due date
27+
/// (the due date is a calendar day: an order due today is not overdue yet)
28+
/// </summary>
29+
/// <param name="companyOwnerId">Identifier of the company owner</param>
30+
/// <param name="utcNow">Current date and time in UTC</param>
31+
Task<bool> HasOverdue(string companyOwnerId, DateTime utcNow);
32+
}

0 commit comments

Comments
 (0)