FreeShippingMarketing.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. <?php
  2. namespace addons\ValetOrder\common\logic\order;
  3. use common\enums\GoodsTypeEnum;
  4. use common\enums\ShippingTypeEnum;
  5. use common\enums\StatusEnum;
  6. use common\logic\order\marketing\BaseMarketing;
  7. use common\models\goods\FreeShippingRules;
  8. use common\models\goods\FreightRules;
  9. use common\models\goods\Goods;
  10. use common\models\goods\GoodsAttr;
  11. use common\models\user\UserAddress;
  12. use Yii;
  13. use yii\helpers\Json;
  14. /**
  15. * 运费减免计算
  16. * @Author bing
  17. * @DateTime 2021-09-27 19:07:32
  18. * @copyright: Copyright (c) 2020 广东七件事集团
  19. */
  20. class FreeShippingMarketing extends BaseMarketing{
  21. public function execute( $form){}
  22. /**
  23. * 计算运费
  24. * @Author: lun
  25. * @DateTime: 2021/10/6 0006 10:37
  26. * @Copyright: copyright (c) 2021 广东七件事集团
  27. * @param $item
  28. * @param $form
  29. * @param $extra
  30. * @return mixed
  31. */
  32. public static function compute($item, &$form, &$extra)
  33. {
  34. $order_goods_num = array_sum(array_column($item['goods'], 'num'));
  35. if (isset($form->data['shipping_type']) && $form->data['shipping_type']==ShippingTypeEnum::PICKUP){
  36. return $item;
  37. }
  38. // 获取用户收货地址信息
  39. if (empty($extra['address'])) {
  40. $address = UserAddress::getOne([['id' => $form['address_id']], ['user_id' => $form->process_extra_data['valet_order_origin_user_id'] ?? $form['user_id']]], true);
  41. $extra['address'] = $address;
  42. } else {
  43. $address = $extra['address'];
  44. }
  45. // 收货地址
  46. if(empty($address)){
  47. $address['province_id'] = $address['city_id'] = $address['district_id'] = $address['town_id'] = $address['community_id'] = 0;
  48. $address['province'] = $address['city'] = $address['district'] = $address['town'] = $address['community'] = $address['detail'] = $address['name'] = $address['mobile'] ='';
  49. }
  50. // 收货地址
  51. $item['mch_order_info']['province'] = $address['province_id'];
  52. $item['mch_order_info']['city'] = $address['city_id'];
  53. $item['mch_order_info']['area'] = $address['district_id'];
  54. $item['mch_order_info']['town'] = $address['town_id'];
  55. $item['mch_order_info']['community'] = $address['community_id'];
  56. $item['mch_order_info']['region_name'] = $address['province'] .' '. $address['city'] .' '. $address['district'].' '.$address['town'].' '.$address['community'];
  57. $item['mch_order_info']['address'] = $address['detail'];
  58. $item['mch_order_info']['receiver_name'] = $address['name'];
  59. $item['mch_order_info']['mobile'] = $address['mobile'];
  60. $shipping_fee = 0;// 订单总运费初始化
  61. $group_order_fee = 0;// 单个商户订单运费
  62. $is_free = false;// 是否免邮
  63. $compute_shipping = [];// 运费计算,配合运费规则compute_type == 2使用
  64. // 获取包邮地区
  65. $feeShippingRules = FreeShippingRules::getFreeShippingRulesArea($item['mch_order_info']['mall_id'], $item['mch_order_info']['mch_id']);
  66. // 获取运费模板
  67. $freightRules = FreightRules::getFreightRulesArea($item['mch_order_info']['mall_id'], $item['mch_order_info']['mch_id']);
  68. // 包邮计算
  69. foreach ($feeShippingRules as $fee) {
  70. if ($fee['rule_type'] == 1) {
  71. // 如果包邮金额<=购买商品金额 || 包邮件数<=购买商品件数,并且地区符合收货地址则免邮
  72. if (($fee['money'] <= $item['mch_order_info']['goods_price'] || $fee['num'] <= $order_goods_num) && self::isInArea($address, $fee['district_ids'])) {
  73. $is_free = true;
  74. continue;
  75. }
  76. } else {
  77. // 如果包邮金额<=购买商品金额 && 包邮件数<=购买商品件数,并且地区符合收货地址则免邮
  78. if (($fee['money'] <= $item['mch_order_info']['goods_price'] && $fee['num'] <= $order_goods_num) && self::isInArea($address, $fee['district_ids'])) {
  79. $is_free = true;
  80. continue;
  81. }
  82. }
  83. }
  84. // 不免邮处理
  85. if ($is_free == false) {
  86. list($shipping_fee, $group_order_fee) = self::getFreightRules($item, $form, $freightRules, $address, $compute_shipping);
  87. // 按同件商品运费计算
  88. if ($compute_shipping) {
  89. $shop_fee_assignment = self::shopFeeAssignment($compute_shipping);
  90. $shipping_fee += $shop_fee_assignment['shipping_fee'] ?? 0;
  91. $group_order_fee += $shop_fee_assignment['group_order_fee'] ?? 0;
  92. }
  93. // 单个商户订单运费计算
  94. $item['mch_order_info']['shipping_type'] = $form['data']['shipping_type'] ?? ShippingTypeEnum::LOGISTICS;
  95. $item['mch_order_info']['shipping_money'] = bcmul($group_order_fee, 1, 2);
  96. }
  97. // 运费赋值
  98. $item['mch_order_info']['pay_money'] = $item['mch_order_info']['pay_money'] + $shipping_fee;
  99. $prev_shipping_fee = $form->marketing['deduct']['shipping_fee']['money'] ?? 0;
  100. $form->marketing['deduct']['shipping_fee'] = ['name' => '运费', 'money' => bcadd($prev_shipping_fee, $group_order_fee, 2)];
  101. return $item;
  102. }
  103. private static function getFreightRules($item, $form, $freightRules, $address, &$compute_shipping)
  104. {
  105. // 阶梯价格情况下 存储哪个运费模板已经计算了价格(因为如果是开启了阶梯,并且是同一个模板来计算的话只拿一次价格)
  106. $groupOrderFee = 0;
  107. $shippingFee = 0;
  108. // 校验输入数据完整性
  109. if (empty($item['goods']) || empty($form['sku'])) {
  110. return [$groupOrderFee, $shippingFee];
  111. }
  112. // 获取所有商品ID
  113. $goodsIds = array_column($item['goods'], 'goods_id');
  114. // 批量查询虚拟商品信息
  115. $virtualGoodsIds = Goods::find()
  116. ->select('id')
  117. ->where([
  118. 'status' => StatusEnum::ENABLED,
  119. 'goods_type' => GoodsTypeEnum::GoodsTypeVirtual,
  120. 'id' => $goodsIds
  121. ])
  122. ->column();
  123. $goodsAttr = GoodsAttr::find()->where(['goods_id' => $goodsIds, 'status' => StatusEnum::ENABLED])->indexBy('id')->asArray()->all();
  124. $calculatedFreight = [];
  125. $freightValue = self::getFreightValue($item['goods'], $form, $freightRules, $goodsAttr);
  126. foreach ($item['goods'] as $good_id => $good) {
  127. // 跳过虚拟商品
  128. if (in_array($good_id, $virtualGoodsIds)) {
  129. continue;
  130. }
  131. // 获取SKU属性
  132. $formAttr = $form['sku'][$good_id]['goods'];
  133. if (empty($formAttr)) continue;
  134. foreach ($good['goods_details'] as $detail) {
  135. // 跳过非物流方式的商品
  136. if (!in_array(ShippingTypeEnum::LOGISTICS, explode(',', $formAttr['freight_type']))) continue;
  137. // 免邮规则:数量达到免邮条件
  138. if ($formAttr['free_shipping_num'] > 0 && $detail['num'] >= $formAttr['free_shipping_num']) continue;
  139. // 邮规则:金额达到免邮条件
  140. if ($formAttr['free_shipping_money']> 0 && $detail['goods_price'] >= $formAttr['free_shipping_money']) continue;
  141. // 运费规则计算
  142. if ($formAttr['freight_rules_type'] == 1) { // 运费模版
  143. // 根据商品id获取对应的规则
  144. $thisRules = $freightRules[$formAttr['freight_id']] ?? [];
  145. if (empty($thisRules)) {
  146. continue; // 规则无效时跳过
  147. }
  148. $shippingList = self::shippingDateMinute($detail, $thisRules, $address, $goodsAttr, $formAttr, $good, $form, $freightValue, $calculatedFreight, $compute_shipping);
  149. if (!empty($shippingList)) {
  150. $groupOrderFee += $shippingList[0];
  151. $shippingFee += $shippingList[1];
  152. }
  153. } else { // 自定义运费
  154. if (!empty($formAttr['shipping_fee'])) {
  155. $groupOrderFee += $formAttr['shipping_fee'];
  156. $shippingFee += $formAttr['shipping_fee'];
  157. }
  158. }
  159. }
  160. }
  161. return [$groupOrderFee, $shippingFee];
  162. }
  163. /**
  164. * @param $detail
  165. * @param $thisRules
  166. * @param $address
  167. * @param $goodsAttr
  168. * @param $formAttr
  169. * @param $goods
  170. * @param $form
  171. * @param $freightValue
  172. * @param $calculatedFreight
  173. * @param $compute_shipping
  174. * @return array|int[]
  175. */
  176. private static function shippingDateMinute($detail, $thisRules, $address, $goodsAttr, $formAttr, $goods, &$form, $freightValue, &$calculatedFreight, &$compute_shipping)
  177. {
  178. // 初始化运费变量
  179. $groupOrderFee = 0;
  180. $shippingFee = 0;
  181. // 检查规则是否存在
  182. if (empty($thisRules['rule']) || !is_array($thisRules['rule'])) {
  183. return [$shippingFee, $groupOrderFee];
  184. }
  185. foreach ($thisRules['rule'] as $rule) {
  186. // 获取模版对应区域id
  187. $areArrIds = array_column($rule['list'], 'id');
  188. // 判断当前收货地址是否在模版区域中
  189. if (!self::isInArea($address, $areArrIds)) continue;
  190. // 判断是否开启阶梯
  191. if (!empty($rule['is_enable_ladder_condition']) && !empty($rule['ladder_condition'])) {
  192. // 根据商品计算方式来决定使用哪个字段来确定唯一值
  193. switch ($thisRules['compute_type']) {
  194. case 1: // 按不同商品计算
  195. $calculatedFreightKey = $detail['goods_attr_id'];
  196. break;
  197. case 2: // 按同件商品计算
  198. $calculatedFreightKey = $formAttr['freight_id'];
  199. break;
  200. }
  201. if (isset($calculatedFreightKey)) {
  202. if (!empty($calculatedFreight[$thisRules['compute_type']][$calculatedFreightKey])) {
  203. continue;
  204. }
  205. // 验证是否满足阶梯
  206. $computeLadderCondition = self::computeLadderCondition(
  207. $freightValue,
  208. $detail,
  209. $formAttr,
  210. $thisRules['type'],
  211. $thisRules['compute_type'],
  212. $rule,
  213. $form
  214. );
  215. if ($computeLadderCondition['is_success']) {
  216. $groupOrderFee += $computeLadderCondition['money'];
  217. $shippingFee += $computeLadderCondition['money'];
  218. $calculatedFreight[$thisRules['compute_type']][$calculatedFreightKey] = true;
  219. continue;
  220. }
  221. }
  222. }
  223. // 判断是否设置首重
  224. if (empty($rule['first'])) {
  225. return [0, 0];
  226. }
  227. // 计算首重金额
  228. if ($thisRules['compute_type'] == 1) {
  229. if (($thisRules['type'] == 1 && $goodsAttr[$detail['goods_attr_id']]['weight'] > 0) || ($thisRules['type'] == 2)) {
  230. $firstPrice = $rule['firstPrice'] ?? 0;
  231. $groupOrderFee += $firstPrice; // 订单运费
  232. $shippingFee += $firstPrice; // 首重运费
  233. }
  234. }
  235. // 判断是否设置续重
  236. if (empty($rule['second']) && $thisRules['compute_type'] != 2) continue;
  237. if ($thisRules['type'] == 1) { // 计重量
  238. // 获取当前商品重量
  239. $newNumWeight = $detail['num'] * $goodsAttr[$detail['goods_attr_id']]['weight'];
  240. } else { // 计件
  241. $newNumWeight = $detail['num'];
  242. }
  243. if ($thisRules['compute_type'] == 2) {
  244. self::getShopFee($thisRules['id'], $thisRules['type'], $rule, $newNumWeight, $compute_shipping);
  245. continue;
  246. }
  247. $newRenewed = $newNumWeight - $rule['first'];
  248. $secondPrice = $rule['secondPrice'] ?? 0;
  249. if ($newRenewed <= 0 || !is_numeric($secondPrice)) continue;
  250. $renewedFee = (double)bcmul(ceil($newRenewed / $rule['second']), $secondPrice, 2);
  251. $groupOrderFee += $renewedFee;
  252. $shippingFee += $renewedFee;
  253. }
  254. return [$shippingFee, $groupOrderFee];
  255. }
  256. /**
  257. * 判断收货地址是否在地区中
  258. * @Author: lun
  259. * @DateTime: 2021/9/30 0030 14:45
  260. * @Copyright: copyright (c) 2021 广东七件事集团
  261. * @param $address
  262. * @param $areaArr
  263. * @return bool
  264. */
  265. private static function isInArea($address, $areaArr)
  266. {
  267. $return = false;
  268. if(in_array($address['province_id'], $areaArr) || in_array($address['city_id'], $areaArr) || in_array($address['district_id'], $areaArr)) $return = true;
  269. return $return;
  270. }
  271. /**
  272. * 运费模板为:按同件商品计算
  273. * 目的:不同商品使用不同的模板情况下的混合计算,主要算出:首件/重 + 续件/重 运费费用
  274. * @Author: lun
  275. * @DateTime: 2023/8/12 0012 17:11
  276. * @Copyright: copyright (c) 2021 广东七件事集团
  277. * @param $rule_id
  278. * @param $rule
  279. * @param $goods_weight_or_num
  280. * @param array $data
  281. */
  282. private static function getShopFee($rule_id, $type, $rule, $goods_weight_or_num, &$data = [])
  283. {
  284. $data[$rule_id]['total_weight_or_num'] = empty($data[$rule_id]['total_weight_or_num']) ? $goods_weight_or_num : $data[$rule_id]['total_weight_or_num'] + $goods_weight_or_num;
  285. if (empty($data[$rule_id]['first_fee'])) $data[$rule_id]['first_fee'] = $rule['firstPrice'];// 首重/件 费用
  286. if (empty($data[$rule_id]['group_first_fee'])) $data[$rule_id]['group_first_fee'] = $rule['firstPrice'];// 首重/件 费用
  287. if (empty($data[$rule_id]['first_weight_or_num'])) $data[$rule_id]['first_weight_or_num'] = $rule['first'];// 同模板商品首重
  288. if (empty($data[$rule_id]['renew_price'])) $data[$rule_id]['renew_price'] = 0;// 续重/件 费用
  289. $surplus_weight_or_num = $data[$rule_id]['total_weight_or_num'] - $data[$rule_id]['first_weight_or_num'];// 总重量/总数量 - 首重/件 = 续重/件
  290. // 续重/件运费 = (剩余重量 / 续件重量)[向上取整] * 续重费用 [向下取整]
  291. if($surplus_weight_or_num > 0 && isset($rule['second']) && $rule['second'] > 0) {
  292. if ($type == 2) {// 按件计费
  293. $fee = $rule['secondPrice'] * floor($surplus_weight_or_num / $rule['second']);
  294. } else {// 按重计费
  295. $fee = floor(ceil($surplus_weight_or_num / $rule['second']) * $rule['secondPrice']);
  296. }
  297. $data[$rule_id]['renew_price'] = $fee;// 每次都覆盖之前的值,为了重新算出最后的续重/件费用
  298. }
  299. }
  300. /**
  301. * 将计算好的不同运费模板运费加起来
  302. * @Author: lun
  303. * @DateTime: 2023/8/12 0012 17:13
  304. * @Copyright: copyright (c) 2021 广东七件事集团
  305. * @param $shopFeeList
  306. * @return array
  307. */
  308. private static function shopFeeAssignment($shopFeeList)
  309. {
  310. $shop_fee = 0;
  311. $group_order_fee = 0;
  312. foreach ($shopFeeList as $item) {
  313. $shop_fee += $item['first_fee'] + $item['renew_price'];
  314. $group_order_fee += $item['group_first_fee'] + $item['renew_price'];
  315. }
  316. return ['shipping_fee' => $shop_fee, 'group_order_fee' => $group_order_fee];
  317. }
  318. /**
  319. * 计算阶梯价格
  320. *
  321. * @param array $freightValue
  322. * @param array $good
  323. * @param int $type
  324. * @param int $computeType
  325. * @param array $rule
  326. * @param $form
  327. *
  328. * @return array
  329. */
  330. private static function computeLadderCondition(
  331. array $freightValue,
  332. array $detail,
  333. array $formAttr,
  334. int $type,
  335. int $computeType,
  336. array $rule,
  337. $form
  338. ): array
  339. {
  340. $res = ['is_success' => false, 'money' => 0];
  341. !isset($freightValue[$computeType]) && $freightValue[$computeType] = [];
  342. // 如果是按重,则需要转为kg
  343. if ($type == 1) {
  344. foreach ($freightValue[$computeType] as &$value) {
  345. $value = bcdiv($value, 1000, 2);
  346. }
  347. }
  348. switch ($computeType) {
  349. case 1: // 按不同商品计算
  350. $goodsId = $detail['goods_attr_id'];
  351. $resValue = $freightValue[$computeType][$goodsId] ?? 0;
  352. break;
  353. case 2: // 按同件商品计算
  354. $freightId = $formAttr['freight_id'];
  355. $resValue = $freightValue[$computeType][$freightId] ?? 0;
  356. break;
  357. default:
  358. return $res;
  359. }
  360. $checkLadderConditionRes = self::checkLadderCondition($rule['ladder_condition'], $resValue);
  361. if ($checkLadderConditionRes['res']) {
  362. $res['is_success'] = true;
  363. $res['money'] = $checkLadderConditionRes['money'];
  364. }
  365. return $res;
  366. }
  367. /**
  368. * @param array $ladderCondition
  369. * @param $value
  370. *
  371. * @return array
  372. */
  373. protected static function checkLadderCondition(array $ladderCondition, $value): array
  374. {
  375. // 根据$ladderCondition的condition_value字段按从大到小排序
  376. usort($ladderCondition, function ($a, $b) {
  377. return $b['condition_value'] <=> $a['condition_value'];
  378. });
  379. foreach ($ladderCondition as $condition) {
  380. if ($value >= $condition['condition_value']) {
  381. return ['res' => true, 'money' => $condition['money']];
  382. }
  383. }
  384. return ['res' => false];
  385. }
  386. /**
  387. * 按计费方式和计算方式将值归类
  388. *
  389. * @param $goods
  390. * @param $form
  391. * @param $freightRules
  392. *
  393. * @return array
  394. */
  395. private static function getFreightValue($goods, $form, $freightRules, $goodsAttr): array
  396. {
  397. $freightValue = [];
  398. // 把相同运费模板的商品合并,根据选择的计费方式
  399. // 如果是按相同商品计算时,就需要保存选择了当前模板的商品
  400. foreach ($goods as $good_id => $good) {
  401. $freightId = $form['sku'][$good_id]['goods']['freight_id'];
  402. // 获取SKU属性
  403. $formAttr = $form['sku'][$good_id]['goods'];
  404. if (empty($formAttr)) continue;
  405. // 过滤掉没有自定义运费模版商品
  406. if ($formAttr['freight_rules_type'] != 1) continue;
  407. // 根据商品id获取对应的规则
  408. $thisRules = $freightRules[$freightId] ?? [];
  409. if (empty($thisRules)) {
  410. continue;
  411. }
  412. // 因为同一个商品不同规格是按照不同商品计算
  413. foreach ($good['goods_details'] as $detail) {
  414. if ($thisRules['type'] == 1) { // 按重计费
  415. $new_num_weight = $goodsAttr[$detail['goods_attr_id']]['weight'] * $detail['num'];
  416. } else { // 按件计费
  417. $new_num_weight = $detail['num'];
  418. }
  419. if (empty($new_num_weight)) continue;
  420. switch ($thisRules['compute_type']) {
  421. case 1: // 按照不同商品计算(取商品规格计算)
  422. !isset($freightValue[$thisRules['compute_type']][$detail['goods_attr_id']]) && $freightValue[$thisRules['compute_type']][$detail['goods_attr_id']] = 0;
  423. $freightValue[$thisRules['compute_type']][$detail['goods_attr_id']] += $new_num_weight;
  424. break;
  425. case 2: // 按同件商品计算 (取商品模版)
  426. !isset($freightValue[$thisRules['compute_type']][$freightId]) && $freightValue[$thisRules['compute_type']][$freightId] = 0;
  427. $freightValue[$thisRules['compute_type']][$freightId] += $new_num_weight;
  428. break;
  429. }
  430. }
  431. }
  432. return $freightValue;
  433. }
  434. }