FreeShippingMarketing.php 20 KB

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