描述在促销引擎中实现阶梯折扣的插件写法
解读
国内电商、政务采购平台、B2B 门户常要求“阶梯价”——买得越多折扣越大,且需支持多货币、多客户角色、限时叠加优惠券。
面试官想确认三件事:
- 是否熟悉 Drupal Commerce 的 Price Resolver、Adjustment 与 Promotion 体系;
- 能否用 Symfony 事件驱动思想把“阶梯规则”做成可插拔、可导出的配置实体;
- 是否具备性能与合规意识(缓存、事务、审计日志、国内发票含税价)。
因此,答案要给出“配置实体 + 条件插件 + 调整器”三段式代码骨架,并说明如何与国产支付、ERP 对接。
知识点
- Drupal 8/9/10 插件系统(Plugin API、Annotation)
- Commerce Promotion、Commerce Adjustment、Price Resolver 优先级链
- 配置实体(ConfigEntity)与内容实体(ContentEntity)差异
- 条件插件(ConditionPluginBase)的 evaluate() 上下文
- 事件订阅器(EventSubscriber)拦截 OrderRefresh 事件
- 国内价税分离要求:含税价存储、不含税价参与折扣计算
- BigPipe/动态缓存标签:promotion_list、order_total
- 单元测试:CommerceKernelTestBase + PromotionTestTrait
- CI 合规:phpstan-drupal、phpcs Drupal 标准、git pre-commit
答案
-
定义阶梯规则配置实体
文件:src/Entity/SteppedDiscount.php
使用 @ConfigEntityType 注解,字段:- steps:序列化数组 [[qty=>5,rate=>0.95],[qty=>10,rate=>0.9]]
- customerRoles:角色数组,支持“政企大客户”等国内角色
- enabledSkus:SKU 白名单,空表示全部
- start/end:DrupalDateTime,支持“618”“双11”精确到秒
实现 Exportable/Importable,方便运维在阿里云 DTS 中同步。
-
创建条件插件
文件:src/Plugin/Commerce/PromotionCondition/SteppedDiscountCondition.php
继承 ConditionPluginBase,核心逻辑:
public function evaluate(PromotionInterface order) {
this->getConfiguration();
config['stepped_discount_id']);
// 国内发票价税分离:数量按“计税数量”字段,非原始 qty
item) => order->getItems())
);
entity->getSteps() as step) { if (totalQty >= step['qty']) { matched = true;
step['rate']; // 保存到对象属性供调整器使用
}
}
return $matched;
}
注意:evaluate 里不打折,只返回布尔,保证条件复用。 -
创建调整器(OrderProcessor)
文件:src/Plugin/Commerce/OrderProcessor/SteppedDiscountProcessor.php
标签:@CommerceOrderProcessor(priority=60, applies=“commerce_order”)
public function process(OrderInterface order) { foreach (order->getItems() as item) { promotions = item->getPurchasedEntity(), promotions as promotion) { condition = condition && promotion, order)) { rate = original = adjusted = rate);
// 国内合规:折扣行必须可追踪,Adjustment 类型设为“阶梯折扣”
rate)*100]),
'amount' => original),
'source_id' => $promotion->id(),
'included' => FALSE, // 价外税
]));
}
}
}
}
优先级设为 60,确保在 tax 模块之后、coupon 之前,防止优惠券重复折上折。 -
缓存与性能
在插件上追加 cache contexts:user.roles、products.quantity;
为每个阶梯规则生成 cache tag:config:stepped_discount.{id},运营后台修改后自动刷新订单页。
若平台日单量超 20W,可开启 Redis 与 Commerce Cache 模块,把可用 promotions 预加载到内存。 -
配置导出与合规审计
使用 drush cex 导出 stepped_discount 配置,纳入 Git;
在模块中实现 EventSubscriber 监听 OrderPaid 事件,写入国内审计表:- 订单号、折扣金额(含税)、折扣率、客户统一社会信用代码;
- 数据通过 OpenAPI 推送到金蝶/用友,方便财务开票。
-
自动化测试
tests/src/Kernel/SteppedDiscountTest.php
构造三个场景:- 普通用户买 8 件,无折扣;
- 政企用户买 8 件,打 95 折;
- 政企用户买 12 件,打 9 折;
断言 order->getTotalPrice() 与预期金额差值小于 0.01;
同时检查 adjustment 标签能被国内发票模块识别。
拓展思考
- 若阶梯规则需按“金额”而非“数量”判定,可把 evaluate 中的 order->getSubtotalPrice()->getNumber(),并新增 cache context:order.total,注意防止循环依赖。
- 当平台做“区域限购”时,可再叠加一个自定义条件插件(如 CityCondition),利用国内 IP 库或收货地址解析,实现“华东政企客户专享阶梯价”。
- 为了支持“秒杀”高并发,可将阶梯规则序列化到 Redis Hash,并用 Lua 脚本保证“查询规则 + 扣减库存”原子性,Drupal 端仅负责下单后校验,避免重复折抵。
- 如果客户要求“阶梯折扣与优惠券可叠加但上限 80%”,可在 OrderProcessor 末尾加一守护逻辑:累计 adjustment 绝对值超过 20% 时,按比率缩减,确保财务合规。