一、前言

上一篇我们已经确立的购买上下文和销售上下文的交互方式,传送门在此:https://zacharyfan.com/archives/147.html,本篇我们来实现售价上下文的具体细节。

二、明确业务细节

电商市场越来越成熟,竞争也越来越激烈,影响客户流量的关键因素之一就是价格,运营的主要打法之一也是价格,所以是商品价格是一个在电商中很重要的一环。

正因为如此也让促销演变的越来越复杂,那么如何在编码上花点心思来尽可能的降低业务的复杂化带来的影响和提高可扩展性来拥抱变化就变得很重要了。

先从最简单的开始,我浏览了某东的促销,先把影响价格相关的几个促销找出来,暂时得出以下几个结论(这里又要提一下,我们实际工作中应在开始编码之前要做的就是和领域专家讨论促销的细节):

  1. 满减:可以多个商品共同参与,汇总金额达到某个阈值之后减免 XX 金额。

  2. 多买优惠(方式 1):可以多个商品共同参与,汇总购买数量达到一定数量得到 X 折的优惠。

  3. 多买优惠(方式 2):可以多个商品共同参与,汇总购买数量达到一定数量减免最便宜的 X 件商品。

  4. 限时折扣:直接商品的购买金额被修改到指定值。

  5. 满减促销的金额满足点以优惠后价格为准,比如该商品既有限时折扣又有满减,则使用限时折扣的价格来计算金额满足点。

  6. 优惠券是在之上的规则计算之后得出的金额基础下计算金额满足点。

  7. 每一个商品的满减 + 多买优惠仅能参与一种。并且相同促销商品在购物车中商品展示的方式是在一组中。

三、建模

根据上面的业务描述先找到其中的几个领域对象,然后在做一些适当的抽象,得出下面的 UML 图:

7 实现售价上下文 - 图1

四、实现

建模完之后下面的事情就容易了,先梳理一下我们的业务处理顺序:

  1. 根据购买上下文传入的购物车信息获取产品的相关促销。

  2. 先处理单品促销。

  3. 最后处理多商品共同参与的促销。

梳理的过程中发现,为了能够实现满减和多买优惠促销仅能参与一个,所以需要再购买上下文和售价上下文之间传递购物项时增加一个参数选择的促销唯一标识 (SelectedMultiProductsPromotionId)。

随后根据上面业务处理顺序,发现整个处理的链路比较长,那么这里我决定定义一个值对象来承载整个处理的过程。如下:

  1. public class BoughtProduct
  2. {
  3. private readonly List<PromotionRule> _promotionRules = new List<PromotionRule>();
  4. public string ProductId { get; private set; }
  5. public int Quantity { get; private set; }
  6. public decimal UnitPrice { get; private set; }
  7. public decimal ReducePrice { get; private set; }
  8. public decimal DiscountedUnitPrice
  9. {
  10. get { return UnitPrice - ReducePrice; }
  11. }
  12. public decimal TotalDiscountedPrice
  13. {
  14. get { return DiscountedUnitPrice * Quantity; }
  15. }
  16. public ReadOnlyCollection<ISingleProductPromotion> InSingleProductPromotionRules
  17. {
  18. get { return _promotionRules.OfType<ISingleProductPromotion>().ToList().AsReadOnly(); }
  19. }
  20. public IMultiProductsPromotion InMultiProductPromotionRule { get; private set; }
  21. public BoughtProduct(string productId, int quantity, decimal unitPrice, decimal reducePrice, IEnumerable<PromotionRule> promotionRules, string selectedMultiProdcutsPromotionId)
  22. {
  23. if (string.IsNullOrWhiteSpace(productId))
  24. throw new ArgumentException("productId不能为null或者空字符串", "productId");
  25. if (quantity <= 0)
  26. throw new ArgumentException("quantity不能小于等于0", "quantity");
  27. if (unitPrice < 0)
  28. throw new ArgumentException("unitPrice不能小于0", "unitPrice");
  29. if (reducePrice < 0)
  30. throw new ArgumentException("reducePrice不能小于0", "reducePrice");
  31. this.ProductId = productId;
  32. this.Quantity = quantity;
  33. this.UnitPrice = unitPrice;
  34. this.ReducePrice = reducePrice;
  35. if (promotionRules != null)
  36. {
  37. this._promotionRules.AddRange(promotionRules);
  38. var multiProductsPromotions = this._promotionRules.OfType<IMultiProductsPromotion>().ToList();
  39. if (multiProductsPromotions.Count > 0)
  40. {
  41. var selectedMultiProductsPromotionRule = multiProductsPromotions.SingleOrDefault(ent => ((PromotionRule)ent).PromotoinId == selectedMultiProdcutsPromotionId);
  42. InMultiProductPromotionRule = selectedMultiProductsPromotionRule ?? multiProductsPromotions.First();
  43. }
  44. }
  45. }
  46. public BoughtProduct ChangeReducePrice(decimal reducePrice)
  47. {
  48. if (reducePrice < 0)
  49. throw new ArgumentException("result.ReducePrice不能小于0");
  50. var selectedMultiProdcutsPromotionId = this.InMultiProductPromotionRule == null
  51. ? null
  52. : ((PromotionRule) this.InMultiProductPromotionRule).PromotoinId;
  53. return new BoughtProduct(this.ProductId, this.Quantity, this.UnitPrice, reducePrice, this._promotionRules, selectedMultiProdcutsPromotionId);
  54. }
  55. }

需要注意一下,值对象的不可变性,所以这里的 ChangeReducePrice 方法返回的是一个新的 BoughtProduct 对象。

另外这次我们的例子比较简单,单品促销只有 1 种。理论上单品促销是支持叠加参与的,所以这里的单品促销设计了一个集合来存放。

下面的代码是处理单品促销的代码:

  1. foreach (var promotionRule in singleProductPromotionRules)
  2. {
  3. var tempReducePrice = ((PromotionRuleLimitTimeDiscount)promotionRule).CalculateReducePrice(productId, unitPrice, DateTime.Now);
  4. if (unitPrice - reducePrice <= tempReducePrice)
  5. {
  6. reducePrice = unitPrice;
  7. }
  8. else
  9. {
  10. reducePrice += tempReducePrice;
  11. }
  12. }

这里也可以考虑把它重构成一个领域服务来合并同一个商品多个单品促销计算结果。

整个应用服务的代码如下:

  1. public class CalculateSalePriceService : ICalculateSalePriceService
  2. {
  3. private static readonly MergeSingleProductPromotionForOneProductDomainService _mergeSingleProductPromotionForOneProductDomainService = new MergeSingleProductPromotionForOneProductDomainService();
  4. public CalculatedCartDTO Calculate(CartRequest cart)
  5. {
  6. List<BoughtProduct> boughtProducts = new List<BoughtProduct>();
  7. foreach (var cartItemRequest in cart.CartItems)
  8. {
  9. var promotionRules = DomainRegistry.PromotionRepository().GetListByContainsProductId(cartItemRequest.ProductId);
  10. var boughtProduct = new BoughtProduct(cartItemRequest.ProductId, cartItemRequest.Quantity, cartItemRequest.UnitPrice, 0, promotionRules, cartItemRequest.SelectedMultiProductsPromotionId);
  11. boughtProducts.Add(boughtProduct);
  12. }
  13. #region 处理单品促销
  14. foreach (var boughtProduct in boughtProducts.ToList())
  15. {
  16. var calculateResult = _mergeSingleProductPromotionForOneProductDomainService.Merge(boughtProduct.ProductId, boughtProduct.DiscountedUnitPrice, boughtProduct.InSingleProductPromotionRules);
  17. var newBoughtProduct = boughtProduct.ChangeReducePrice(calculateResult);
  18. boughtProducts.Remove(boughtProduct);
  19. boughtProducts.Add(newBoughtProduct);
  20. }
  21. #endregion
  22. #region 处理多商品促销&构造DTO模型
  23. List<CalculatedFullGroupDTO> fullGroupDtos = new List<CalculatedFullGroupDTO>();
  24. foreach (var groupedPromotoinId in boughtProducts.Where(ent => ent.InMultiProductPromotionRule != null).GroupBy(ent => ((PromotionRule)ent.InMultiProductPromotionRule).PromotoinId))
  25. {
  26. var multiProdcutsReducePricePromotion = (IMultiProdcutsReducePricePromotion)groupedPromotoinId.First().InMultiProductPromotionRule;
  27. var products = groupedPromotoinId.ToList();
  28. if (multiProdcutsReducePricePromotion == null)
  29. continue;
  30. var reducePrice = multiProdcutsReducePricePromotion.CalculateReducePrice(products);
  31. fullGroupDtos.Add(new CalculatedFullGroupDTO
  32. {
  33. CalculatedCartItems = products.Select(ent => ent.ToDTO()).ToArray(),
  34. ReducePrice = reducePrice,
  35. MultiProductsPromotionId = groupedPromotoinId.Key
  36. });
  37. }
  38. #endregion
  39. return new CalculatedCartDTO
  40. {
  41. CalculatedCartItems = boughtProducts.Where(ent => fullGroupDtos.SelectMany(e => e.CalculatedCartItems).All(e => e.ProductId != ent.ProductId))
  42. .Select(ent => ent.ToDTO()).ToArray(),
  43. CalculatedFullGroups = fullGroupDtos.ToArray(),
  44. CartId = cart.CartId
  45. };
  46. }
  47. }

五、结语

这里的设计没有考虑促销规则的冲突问题,如果做的话把它放在创建促销规则的时候进行约束即可。

本文的源码地址:https://github.com/ZacharyFan/DDDDemo/tree/Demo7


原创文章,转载请注明本文链接: https://zacharyfan.com/archives/154.html

关于作者:张帆(Zachary,个人微信号:Zachary-ZF)。坚持用心打磨每一篇高质量原创。欢迎扫描二维码~

7 实现售价上下文 - 图2

定期发表原创内容:架构设计丨分布式系统丨产品丨运营丨一些思考。

如果你是初级程序员,想提升但不知道如何下手。又或者做程序员多年,陷入了一些瓶颈想拓宽一下视野。欢迎关注我的公众号「跨界架构师」,回复「技术」,送你一份我长期收集和整理的思维导图。

如果你是运营,面对不断变化的市场束手无策。又或者想了解主流的运营策略,以丰富自己的 “仓库”。欢迎关注我的公众号「跨界架构师」,回复「运营」,送你一份我长期收集和整理的思维导图。
https://zacharyfan.com/archives/154.html