2024-12-04
将分散在多个 Controller 中的配送报价逻辑封装到统一的工具类中,提高代码复用性和可维护性。
common/components/delivery/helpers/DeliveryQuoteUtil.phpcommon/components/delivery/helpers/核心方法:
DeliveryQuoteUtil::getDeliveryQuote($params)
功能特性:
common/components/delivery/helpers/DeliveryQuoteUtil_USAGE.mdcommon/components/delivery/helpers/app-hd/controllers/PurchaseController.php修改位置:第 573-660 行
修改前(84 行代码):
// 复杂的内联逻辑:
// - 计算重量
// - 构建订单数据
// - 调用 DispatchService
// - 格式化报价
// - 重试逻辑
// - 免费配送规则判断
修改后(30 行代码):
// 简洁的工具类调用
try {
$quoteResult = DeliveryQuoteUtil::getDeliveryQuote([
'productList' => $productList,
'deliveryPlatform' => $post['deliveryPlatform'],
'ghsInfo' => $ghsInfo,
'custom' => $custom,
'order' => [
'orderSn' => $orderSn,
'itemTotalAmount' => $post['itemTotalAmount'] ?? 0,
'remark' => $post['remark'] ?? '',
],
'mainId' => $this->mainId,
'productCount' => $productCount,
]);
$sendCost = $quoteResult['sendCost'];
$sendDistance = $quoteResult['sendDistance'];
} catch (\Exception $e) {
util::fail($e->getMessage());
}
代码减少:54 行(减少 64%)
DeliveryQuoteUtil.php 一个文件以下位置可以使用新的工具类替换现有逻辑:
app-hd/controllers/PurchaseController.php 第 577-660 行app-mall/controllers/OrderController.php 第 374 行附近DispatchService 和 getAllPlatformPrice 找到)引入命名空间
use common\components\delivery\helpers\DeliveryQuoteUtil;
调用方法
try {
$quoteResult = DeliveryQuoteUtil::getDeliveryQuote([
'productList' => $productList,
'deliveryPlatform' => 'shansong',
'ghsInfo' => ['mainId' => xxx, 'shopId' => xxx],
'custom' => $customObject,
'order' => ['orderSn' => xxx, 'itemTotalAmount' => xxx, 'remark' => xxx],
'mainId' => $this->mainId,
'productCount' => $count,
]);
$sendCost = $quoteResult['sendCost'];
$sendDistance = $quoteResult['sendDistance'];
} catch (\Exception $e) {
util::fail($e->getMessage());
}
参见:common/components/delivery/helpers/DeliveryQuoteUtil_USAGE.md
重量计算
bcmul 和 bcadd 精确计算订单数据构建
平台报价调用
DispatchServicegetAllPlatformPrice 获取报价重试机制
免费配送规则
异常处理
// 测试正常报价
testGetDeliveryQuote_Success()
// 测试免费配送规则
testGetDeliveryQuote_FreeDelivery()
// 测试参数验证
testGetDeliveryQuote_InvalidParams()
// 测试重试机制
testGetDeliveryQuote_Retry()
DispatchService 的集成ShopClass、ShopExtClass 的集成app-mall/controllers/OrderController.php 中的配送报价逻辑DispatchService::getAllPlatformPrice 的地方并迁移try-catch 捕获异常sendCost 和 sendDistancesendCost 是元,sendDistance 是米如有问题或建议,请联系开发团队。