Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
Plugin — Discount Rules Provider
Purpose
Create, modify, and review GrandNode discount rule plugins that implement IDiscountProvider and one or more IDiscountRule classes.
When To Use
Use this skill when building a new discount requirement rule, adding a rule type to an existing plugin, changing rule validation logic, building a rule configuration UI, or reviewing discount rule correctness.
When Not To Use
Do not use this skill for discount domain entity management, pricing calculation, or general plugin infrastructure; combine with plugin-module when foundational setup is needed.
Inputs Required
- Repository root.
- The condition the rule validates (e.g., customer group, minimum spend, product ownership).
- Whether the rule needs admin configuration per discount instance.
- What data the rule needs at validation time (customer, cart, store, etc.).
Instructions
Mandatory Rules
Provider and Rule Interfaces
- Implement
IDiscountProviderfromGrand.Business.Core.Interfaces.Catalog.Discounts. This extendsIProviderrequiringConfigurationUrl,SystemName,FriendlyName,Priority,LimitedToStores,LimitedToGroups. - Implement
IDiscountProvider.GetRequirementRules()to return allIDiscountRuleinstances this plugin provides. - For each rule type, create a class implementing
IDiscountRule:
| Member | Requirement |
|---|---|
string SystemName |
Unique identifier in the format "{PluginSystemName}.{RuleName}", e.g. "DiscountRules.Standard.MustBeAssignedToCustomerGroup". |
string FriendlyName |
Human-readable rule name shown in the admin discount editor. |
Task<DiscountRuleValidationResult> CheckRequirement(request) |
Validation logic. Return result.IsValid = true on pass; set result.UserError when the rule fails and you want a customer-facing message. |
string GetConfigurationUrl(discountId, requirementId) |
Return the URL of the rule's admin configuration page. Format: "/{ControllerName}/Configure/?discountId={discountId}&discountRequirementId={requirementId}". Return "" if the rule needs no configuration. |
- Keep
CheckRequirementidempotent and side-effect free — it is called on every cart recalculation. - Read rule configuration from
request.DiscountRule.Metadata(a string stored perDiscountRuleinstance). Parse the format you write during configuration (plain string, ID, JSON, etc.).
DiscountRuleValidationRequest (key fields)
Discount Discount { get; } // the discount being validated
DiscountRule DiscountRule { get; } // the rule instance (carries Metadata)
Customer Customer { get; } // current customer
Store Store { get; } // current store
Admin Configuration Controller
- Create a storefront-accessible controller (no
[Area("Admin")]) for each rule that requires configuration. The route must matchGetConfigurationUrl. - The controller renders a configuration form that saves the chosen value (customer group ID, amount, product ID, etc.) back to
DiscountRule.Metadatavia the discount service. - Inject
IDiscountServiceto load and update theDiscountRuleentity during save. - Protect the configuration controller with
[AuthorizeAdmin]since it is accessed from the admin discount edit page via an iframe or popup. Use[Area("Admin")]when it is admin-routed; omit the area when it is accessed from the public route prefix (follow the nearest existing rule controller pattern).
DI Registration
- Register the provider and all rule classes in
StartupApplication.ConfigureServices:
Inject the rule instances into the provider constructor and return them fromservices.AddScoped<IDiscountProvider, YourDiscountProvider>(); services.AddScoped<YourRule1>(); services.AddScoped<YourRule2>();GetRequirementRules().
Project Structure
- Use
Microsoft.NET.Sdk.Razorwhen configuration views are present;Microsoft.NET.Sdkotherwise. - Set output path to
..\..\Web\Grand.Web\Plugins\{SystemName}\. - Mark all GrandNode project references
Private="false". - Include
logo.jpgwithCopyToOutputDirectory = Always.
Manifest, Defaults, Settings
- Define
[assembly: PluginInfo(...)]withGroup = "Discount rules". - Define a
Defaultsclass withProviderSystemName,FriendlyName(resource key), and system names for each rule type. - Plugin-level
ISettingsis only needed when the plugin itself has shared configuration across all rule instances. Per-instance rule config goes inDiscountRule.Metadata.
Startup and Install
- In
Install(): register localization keys for the plugin and each rule'sFriendlyName. Callbase.Install()last. - In
Uninstall(): remove resource keys. Callbase.Uninstall()last. If the plugin owns no settings,DeleteSettingis not needed.
Recommendations
- Prefer
DiscountRules.Standardas the template — it bundles multiple rules in one plugin, showing the full pattern. - Prefer storing a single domain ID (group ID, product ID) as
Metadatafor simple rules rather than serializing complex objects. - Prefer returning an empty
UserErrorwhen the rule fails silently (cart recalculation); populate it only when the customer should see an explanation. - Prefer early-return
result.IsValid = falsewith no error for cases where the customer simply doesn't meet the condition yet (e.g., not enough spend).
Key Contracts
IDiscountProvider
IList<IDiscountRule> GetRequirementRules();
// + all IProvider members: ConfigurationUrl, SystemName, FriendlyName, Priority, LimitedToStores, LimitedToGroups
IDiscountRule
string SystemName { get; }
string FriendlyName { get; }
Task<DiscountRuleValidationResult> CheckRequirement(DiscountRuleValidationRequest request);
string GetConfigurationUrl(string discountId, string discountRequirementId);
DiscountRuleValidationResult
public bool IsValid { get; set; }
public string UserError { get; set; } // shown to customer; empty = silent fail
DiscountRule entity (key fields used by rules)
public string DiscountRequirementRuleSystemName { get; set; } // matches IDiscountRule.SystemName
public string Metadata { get; set; } // rule-specific config (group ID, amount, etc.)
Discount entity (key fields relevant to rules)
public bool RequiresCouponCode { get; set; }
public bool IsCumulative { get; set; }
public int DiscountLimitationId { get; set; }
public ICollection<DiscountRule> DiscountRules { get; set; }
File Locations
| Concern | Path |
|---|---|
| IDiscountProvider | src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountProvider.cs |
| IDiscountRule | src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountRule.cs |
| DiscountRuleValidationRequest | src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationRequest.cs |
| DiscountRuleValidationResult | src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationResult.cs |
| Discount entity | src/Core/Grand.Domain/Discounts/Discount.cs |
| DiscountRule entity | src/Core/Grand.Domain/Discounts/DiscountRule.cs |
| IDiscountService | src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountService.cs |
| Example — multiple rules | src/Plugins/DiscountRules.Standard/ |
Validation Checklist
-
IDiscountProviderandIProvidermembers all implemented. -
GetRequirementRules()returns all rule instances. - Each
IDiscountRulehas a globally uniqueSystemName. -
CheckRequirementis side-effect free and reads config fromrequest.DiscountRule.Metadata. -
GetConfigurationUrlreturns a URL matching the configuration controller route, or""for rules with no config. - Each rule class registered in DI individually via
AddScoped<YourRule>(). - Provider registered with
AddScoped<IDiscountProvider, ...>. - Output path set to
Grand.Web/Plugins/{SystemName}/. -
Installregisters resource keys;Uninstallremoves them.
Examples
Example 1: Customer Group Rule
CheckRequirement reads request.DiscountRule.Metadata as a customer group ID and checks request.Customer.Groups.Contains(groupId). Configuration controller shows a dropdown of customer groups and saves the selected ID to DiscountRule.Metadata.
Example 2: Minimum Spend Rule
CheckRequirement reads a minimum amount from Metadata, retrieves the customer's order history total via IOrderService, and returns IsValid = true when the total meets or exceeds the threshold.
Example 3: Has Specific Product in Cart Rule
CheckRequirement reads a product ID from Metadata, iterates the customer's current cart items (accessible via cart session or passed context), and returns IsValid = true when the product is found.
Example 4: Multiple Rules in One Plugin
Pattern from DiscountRules.Standard: define CustomerGroupDiscountRule, HadSpentAmountDiscountRule, HasAllProductsDiscountRule, HasOneProductDiscountRule, ShoppingCartDiscountRule as separate classes. Register each with AddScoped<T>(). Inject all into DiscountProvider constructor and return them from GetRequirementRules().