Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .ai/skills/scheduled-task.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ public class ScheduleTask : BaseEntity
| `GenerateSitemapXmlTask` | `"Generate sitemap XML file"` | 10080 min | false |
| `EndAuctionsTask` | `"End of the auctions"` | 60 min | false |
| `CancelOrderScheduledTask` | `"Cancel unpaid and pending orders"` | 1440 min | false |
| `PaymentDueReminderScheduleTask` | `"Payment due reminders"` | 1440 min | true (added disabled by the upgrade) |
| `DeleteOidcSessionsScheduleTask` | `"Delete OpenID Connect sessions"` | 1440 min | true |

## Expected Output
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using Grand.Business.Core.Queries.Checkout.Orders;
using Grand.Business.Core.Extensions;
using Grand.Business.Core.Queries.Checkout.Orders;
using Grand.Data;
using Grand.Domain;
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using Grand.Mediator;

namespace Grand.Business.Checkout.Queries.Handlers.Orders;
Expand Down Expand Up @@ -104,11 +104,7 @@ public async Task<IPagedList<Order>> Handle(GetOrderQuery request, CancellationT
if (request.OverdueOnly)
{
var today = DateTime.UtcNow.Date;
query = query.Where(o => o.PaymentDueDateUtc != null && o.PaymentDueDateUtc < today &&
o.OrderStatusId != (int)OrderStatusSystem.Cancelled &&
(o.PaymentStatusId == PaymentStatus.Pending ||
o.PaymentStatusId == PaymentStatus.Authorized ||
o.PaymentStatusId == PaymentStatus.PartiallyPaid));
query = query.Where(PaymentExtensions.UnpaidOnCredit).Where(o => o.PaymentDueDateUtc < today);
}

query = query.Where(o => !o.Deleted);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Utilities.Checkout;
using Grand.Data;
using Grand.Domain.Customers;
using Grand.Domain.Orders;
using Grand.Domain.Payments;

namespace Grand.Business.Checkout.Services.Orders;

Expand Down Expand Up @@ -37,14 +37,8 @@ public CompanyCreditService(IRepository<Order> orderRepository, ICustomerService
/// </summary>
private IQueryable<Order> UnpaidCreditOrders(string companyOwnerId)
{
return _orderRepository.Table.Where(o =>
o.OwnerId == companyOwnerId &&
o.PaymentDueDateUtc != null &&
!o.Deleted &&
o.OrderStatusId != (int)OrderStatusSystem.Cancelled &&
(o.PaymentStatusId == PaymentStatus.Pending ||
o.PaymentStatusId == PaymentStatus.Authorized ||
o.PaymentStatusId == PaymentStatus.PartiallyPaid));
return _orderRepository.Table.Where(o => o.OwnerId == companyOwnerId)
.Where(PaymentExtensions.UnpaidOnCredit);
}

#endregion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,38 @@ public virtual async Task UpdateOrder(Order order)
await _mediator.EntityUpdated(order);
}

/// <summary>
/// Updates the purchase order number and the payment due date of an order
/// </summary>
/// <param name="order">The order</param>
/// <param name="purchaseOrderNumber">Purchase order number</param>
/// <param name="paymentDueDateUtc">Payment due date (a calendar day, UTC), or null when the order is paid at once</param>
public virtual async Task UpdatePaymentTerms(Order order, string purchaseOrderNumber, DateTime? paymentDueDateUtc)
{
ArgumentNullException.ThrowIfNull(order);

//only these fields: a payment or a reminder saved meanwhile must not be overwritten
var update = UpdateBuilder<Order>.Create()
.Set(x => x.PurchaseOrderNumber, purchaseOrderNumber)
.Set(x => x.PaymentDueDateUtc, paymentDueDateUtc);

//a new due date is a new term: the customer is reminded of it and told when it passes. Compared in UTC,
//because LiteDB reads a stored date back in local time
if (order.PaymentDueDateUtc?.ToUniversalTime() != paymentDueDateUtc?.ToUniversalTime())
{
update.Set(x => x.PaymentReminderSentOnUtc, null).Set(x => x.PaymentOverdueNoticeSentOnUtc, null);
order.PaymentReminderSentOnUtc = null;
order.PaymentOverdueNoticeSentOnUtc = null;
}

order.PurchaseOrderNumber = purchaseOrderNumber;
order.PaymentDueDateUtc = paymentDueDateUtc;
await _orderRepository.UpdateOneAsync(x => x.Id == order.Id, update);

//event notification
await _mediator.EntityUpdated(order);
}

/// <summary>
/// Cancel UnPaid Orders and has pending status
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Common.Configuration;
using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Data;
using Grand.Domain.Orders;
using Grand.Infrastructure.Extensions;
using Grand.Mediator;
using Microsoft.Extensions.Logging;
using System.Linq.Expressions;

namespace Grand.Business.Checkout.Services.Orders;

/// <summary>
/// Payment reminder service
/// </summary>
public class PaymentReminderService(
IRepository<Order> orderRepository,
IStoreService storeService,
ISettingService settingService,
ICustomerService customerService,
IOrderService orderService,
IOrderMessageProviderService orderMessageProviderService,
IMediator mediator,
ILogger<PaymentReminderService> logger) : IPaymentReminderService
{
public async Task SendPaymentReminders(DateTime utcNow, CancellationToken cancellationToken = default)
{
//the due date is a calendar day, as in PaymentExtensions.IsPaymentOverdue: due today is not overdue yet
var today = utcNow.Date;
foreach (var store in await storeService.GetAllStores())
{
cancellationToken.ThrowIfCancellationRequested();

//the overdue notices first: an order that is overdue already is not reminded that it falls due
var overdue = await UnpaidOrderIds(store.Id, o =>
o.PaymentDueDateUtc < today && o.PaymentOverdueNoticeSentOnUtc == null, cancellationToken);
foreach (var orderId in overdue)
await Notify(orderId, true, utcNow, cancellationToken);

var orderSettings = await settingService.LoadSetting<OrderSettings>(store.Id);
//bounded as in the settings validator: a value stored past it must not stop the run for every store
var daysBefore = Math.Clamp(orderSettings.PaymentReminderDaysBefore, 0,
OrderSettings.MaxPaymentReminderDaysBefore);
var lastDueDate = today.AddDays(daysBefore);
var dueSoon = await UnpaidOrderIds(store.Id, o =>
o.PaymentDueDateUtc >= today && o.PaymentDueDateUtc <= lastDueDate &&
o.PaymentReminderSentOnUtc == null, cancellationToken);
foreach (var orderId in dueSoon)
await Notify(orderId, false, utcNow, cancellationToken);
}
}

/// <summary>
/// Ids of the store's orders bought on credit and not paid yet: an existing shop may hold many of them, so each
/// order is loaded only when its e-mail is sent
/// </summary>
private Task<IList<string>> UnpaidOrderIds(string storeId, Expression<Func<Order, bool>> filter,
CancellationToken cancellationToken)
{
return orderRepository.ToListAsync(orderRepository.Table
.Where(o => o.StoreId == storeId)
.Where(PaymentExtensions.UnpaidOnCredit)
.Where(filter)
.Select(o => o.Id), cancellationToken);
}

private async Task Notify(string orderId, bool overdue, DateTime utcNow, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var order = await orderRepository.GetByIdAsync(orderId);
if (order == null)
return;

var customer = await customerService.GetCustomerById(order.CustomerId);
var queued = overdue
? await orderMessageProviderService.SendPaymentOverdueCustomerMessage(order, customer,
order.CustomerLanguageId)
: await orderMessageProviderService.SendPaymentDueReminderCustomerMessage(order, customer,
order.CustomerLanguageId);

//marked also when an inactive template, or one not meant for this store, queued nothing: switching it
//on later does not mail every order that fell due meanwhile. A field update, not the whole order: a
//payment saved meanwhile must not be overwritten
if (overdue)
{
order.PaymentOverdueNoticeSentOnUtc = utcNow;
await orderRepository.UpdateField(order.Id, x => x.PaymentOverdueNoticeSentOnUtc, utcNow);
}
else
{
order.PaymentReminderSentOnUtc = utcNow;
await orderRepository.UpdateField(order.Id, x => x.PaymentReminderSentOnUtc, utcNow);
}

await mediator.EntityUpdated(order);

if (queued > 0)
await orderService.InsertOrderNote(new OrderNote {
Note = overdue ? "Payment overdue e-mail sent" : "Payment due reminder e-mail sent",
DisplayToCustomer = false,
OrderId = order.Id
});
}
catch (Exception ex)
{
//not marked when the e-mail could not be queued: the next run tries again
logger.LogError(ex, "Payment reminder for order {OrderId} failed", orderId);
}
Comment on lines +109 to +113
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ private static void RegisterOrdersService(IServiceCollection serviceCollection)
serviceCollection.AddScoped<ICheckoutClaimService, CheckoutClaimService>();
serviceCollection.AddScoped<IOrderPlacementRuleProvider, OrderApprovalLimitRuleProvider>();
serviceCollection.AddScoped<ICompanyCreditService, CompanyCreditService>();
serviceCollection.AddScoped<IPaymentReminderService, PaymentReminderService>();
serviceCollection.AddScoped<ILoyaltyPointsService, LoyaltyPointsService>();
serviceCollection.AddScoped<IShoppingCartService, ShoppingCartService>();
serviceCollection.AddScoped<IShoppingCartValidator, ShoppingCartValidator>();
Expand Down
22 changes: 16 additions & 6 deletions src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using System.Linq.Expressions;

namespace Grand.Business.Core.Extensions;

Expand All @@ -9,6 +10,20 @@ namespace Grand.Business.Core.Extensions;
/// </summary>
public static class PaymentExtensions
{
/// <summary>
/// Orders bought on credit and not paid yet: not deleted, not cancelled and with the payment still open. A query
/// filter, so the reminders, the company credit and the overdue order list all count the same orders
/// </summary>
public static readonly Expression<Func<Order, bool>> UnpaidOnCredit = o =>
o.PaymentDueDateUtc != null &&
!o.Deleted &&
o.OrderStatusId != (int)OrderStatusSystem.Cancelled &&
(o.PaymentStatusId == PaymentStatus.Pending ||
o.PaymentStatusId == PaymentStatus.Authorized ||
o.PaymentStatusId == PaymentStatus.PartiallyPaid);

private static readonly Func<Order, bool> IsUnpaidOnCredit = UnpaidOnCredit.Compile();

/// <summary>
/// Is payment method active?
/// </summary>
Expand Down Expand Up @@ -63,11 +78,6 @@ public static bool IsPaymentOverdue(this Order order, DateTime utcNow)
{
ArgumentNullException.ThrowIfNull(order);

return order.PaymentDueDateUtc.HasValue &&
order.PaymentDueDateUtc.Value < utcNow.Date &&
!order.Deleted &&
order.OrderStatusId != (int)OrderStatusSystem.Cancelled &&
order.PaymentStatusId is PaymentStatus.Pending or PaymentStatus.Authorized
or PaymentStatus.PartiallyPaid;
return IsUnpaidOnCredit(order) && order.PaymentDueDateUtc!.Value < utcNow.Date;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,15 @@ Task<IPagedList<Order>> SearchOrders(string storeId = "",
/// <param name="order">The order</param>
Task UpdateOrder(Order order);

/// <summary>
/// Updates the purchase order number and the payment due date of an order. A new due date is a new term: the
/// payment reminder and the overdue notice are sent again
/// </summary>
/// <param name="order">The order</param>
/// <param name="purchaseOrderNumber">Purchase order number</param>
/// <param name="paymentDueDateUtc">Payment due date (a calendar day, UTC), or null when the order is paid at once</param>
Task UpdatePaymentTerms(Order order, string purchaseOrderNumber, DateTime? paymentDueDateUtc);

#endregion

#region Order notes
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace Grand.Business.Core.Interfaces.Checkout.Orders;

/// <summary>
/// E-mails the customers of orders bought on credit: once before the payment falls due, once when it is overdue
/// </summary>
public interface IPaymentReminderService
{
/// <summary>
/// Sends the reminders and overdue notices not sent yet. Each order gets each e-mail once, until its due date
/// changes; an order already overdue gets only the overdue notice
/// </summary>
/// <param name="utcNow">Current date and time in UTC</param>
/// <param name="cancellationToken">Cancellation token, checked between orders</param>
Task SendPaymentReminders(DateTime utcNow, CancellationToken cancellationToken = default);
}
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,24 @@ Task<int> SendOrderCompletedCustomerMessage(Order order, Customer customer, stri
/// <returns>Queued email identifier</returns>
Task<int> SendOrderRefundedCustomerMessage(Order order, double refundedAmount, string languageId);

/// <summary>
/// Reminds a customer that the payment of an order bought on credit falls due
/// </summary>
/// <param name="order">Order</param>
/// <param name="customer">Customer</param>
/// <param name="languageId">Message language identifier</param>
/// <returns>Queued email identifier</returns>
Task<int> SendPaymentDueReminderCustomerMessage(Order order, Customer customer, string languageId);

/// <summary>
/// Tells a customer that the payment of an order bought on credit is overdue
/// </summary>
/// <param name="order">Order</param>
/// <param name="customer">Customer</param>
/// <param name="languageId">Message language identifier</param>
/// <returns>Queued email identifier</returns>
Task<int> SendPaymentOverdueCustomerMessage(Order order, Customer customer, string languageId);

/// <summary>
/// Sends a new order note added notification to a customer
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ public static class MessageTemplateNames
public const string SendOrderCompletedCustomerMessage = "OrderCompleted.CustomerNotification";
public const string SendOrderCancelledCustomerMessage = "OrderCancelled.CustomerNotification";
public const string SendOrderRefundedCustomerMessage = "OrderRefunded.CustomerNotification";
public const string SendPaymentDueReminderCustomerMessage = "OrderPaymentDue.CustomerNotification";
public const string SendPaymentOverdueCustomerMessage = "OrderPaymentOverdue.CustomerNotification";

public const string SendOrderPlacedVendorMessage = "OrderPlaced.VendorNotification";
public const string SendOrderPaidVendorMessage = "OrderPaid.VendorNotification";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,34 @@ public virtual async Task<int> SendOrderRefundedCustomerMessage(Order order, dou
languageId, refundedAmount: refundedAmount);
}

/// <summary>
/// Reminds a customer that the payment of an order bought on credit falls due
/// </summary>
/// <param name="order">Order</param>
/// <param name="customer">Customer</param>
/// <param name="languageId">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public virtual async Task<int> SendPaymentDueReminderCustomerMessage(Order order, Customer customer,
string languageId)
{
return await SendOrderCustomerMessage(MessageTemplateNames.SendPaymentDueReminderCustomerMessage, order,
customer, languageId);
}

/// <summary>
/// Tells a customer that the payment of an order bought on credit is overdue
/// </summary>
/// <param name="order">Order</param>
/// <param name="customer">Customer</param>
/// <param name="languageId">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public virtual async Task<int> SendPaymentOverdueCustomerMessage(Order order, Customer customer,
string languageId)
{
return await SendOrderCustomerMessage(MessageTemplateNames.SendPaymentOverdueCustomerMessage, order,
customer, languageId);
}

/// <summary>
/// Sends an order notification with an invoice to a customer
/// </summary>
Expand Down
10 changes: 10 additions & 0 deletions src/Core/Grand.Domain/Orders/Order.cs
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,16 @@ public class Order : BaseEntity
/// </summary>
public DateTime? PaymentDueDateUtc { get; set; }

/// <summary>
/// Gets or sets when the customer was reminded that the payment falls due; cleared when the due date changes
/// </summary>
public DateTime? PaymentReminderSentOnUtc { get; set; }

/// <summary>
/// Gets or sets when the customer was told that the payment is overdue; cleared when the due date changes
/// </summary>
public DateTime? PaymentOverdueNoticeSentOnUtc { get; set; }

/// <summary>
/// Gets or sets the refunded amount
/// </summary>
Expand Down
Loading
Loading