OrderLogic.php 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LikeShop有特色的全开源社交分销电商系统
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 商业用途务必购买系统授权,以免引起不必要的法律纠纷
  7. // | 禁止对系统程序代码以任何目的,任何形式的再发布
  8. // | 微信公众号:好象科技
  9. // | 访问官网:http://www.likemarket.net
  10. // | 访问社区:http://bbs.likemarket.net
  11. // | 访问手册:http://doc.likemarket.net
  12. // | 好象科技开发团队 版权所有 拥有最终解释权
  13. // +----------------------------------------------------------------------
  14. // | Author: LikeShopTeam-段誉
  15. // +----------------------------------------------------------------------
  16. namespace app\shopapi\logic\Order;
  17. use app\common\enum\AfterSaleEnum;
  18. use app\common\enum\AfterSaleLogEnum;
  19. use app\common\enum\BargainEnum;
  20. use app\common\enum\CouponEnum;
  21. use app\common\enum\DeliveryEnum;
  22. use app\common\enum\FreeShippingEnum;
  23. use app\common\enum\GoodsEnum;
  24. use app\common\enum\OrderEnum;
  25. use app\common\enum\OrderLogEnum;
  26. use app\common\enum\PayEnum;
  27. use app\common\enum\PresellEnum;
  28. use app\common\enum\TeamEnum;
  29. use app\common\enum\YesNoEnum;
  30. use app\common\logic\CommonPresellLogic;
  31. use app\common\logic\DiscountLogic;
  32. use app\common\model\AddressLibrary;
  33. use app\common\model\AfterSale;
  34. use app\common\model\AfterSaleGoods;
  35. use app\common\model\BargainInitiate;
  36. use app\common\model\Cart;
  37. use app\common\model\CouponList;
  38. use app\common\model\Delivery;
  39. use app\common\model\Express;
  40. use app\common\model\FreeShipping;
  41. use app\common\model\FreeShippingOrder;
  42. use app\common\model\Goods;
  43. use app\common\model\GoodsItem;
  44. use app\common\model\LuckyDrawRecord;
  45. use app\common\model\Order;
  46. use app\common\model\OrderGoods;
  47. use app\common\model\OrderLog;
  48. use app\common\model\PresellGoodsItem;
  49. use app\common\model\Region;
  50. use app\common\model\SeckillGoodsItem;
  51. use app\common\model\SelffetchShop;
  52. use app\common\model\TeamActivity;
  53. use app\common\model\TeamFound;
  54. use app\common\model\TeamGoods;
  55. use app\common\model\TeamGoodsItem;
  56. use app\common\model\TeamJoin;
  57. use app\common\model\User;
  58. use app\common\logic\BaseLogic;
  59. use app\common\model\UserAddress;
  60. use app\common\service\after_sale\AfterSaleService;
  61. use app\common\service\ConfigService;
  62. use app\common\service\FileService;
  63. use app\shopapi\logic\BargainLogic;
  64. use app\shopapi\logic\TeamLogic;
  65. use expressage\Kd100;
  66. use expressage\Kdniao;
  67. use think\Exception;
  68. use think\facade\Db;
  69. use think\facade\Validate;
  70. /**
  71. * 订单逻辑
  72. * Class OrderLogic
  73. * @package app\shopapi\logic
  74. */
  75. class OrderLogic extends BaseLogic
  76. {
  77. /**
  78. * 下单用户
  79. * @var
  80. */
  81. protected static $user;
  82. /**
  83. * 订单类型
  84. * @var int
  85. */
  86. protected static $OrderType = OrderEnum::NORMAL_ORDER;
  87. /**
  88. * 订单数量
  89. * @var int
  90. */
  91. protected static $totalNum = 0;
  92. /**
  93. * 订单金额
  94. * @var array
  95. */
  96. protected static $orderPrice = [
  97. 'total_goods_price' => 0,//订单商品金额
  98. 'express_price' => 0,//运费
  99. 'total_amount' => 0,//订单金额
  100. 'order_amount' => 0,//订单实付金额
  101. 'discount_amount' => 0,//优惠金额
  102. 'member_amount' => 0,//会员折扣价
  103. 'total_goods_original_price' => 0,//订单商品原价总价
  104. ];
  105. /**
  106. * 失效商品列表
  107. * @var array
  108. */
  109. protected static array $disabledGoods = [];
  110. /**
  111. * @notes 当前下单用户
  112. * @param $userId
  113. * @return array
  114. * @author 段誉
  115. * @date 2021/7/23 15:52
  116. */
  117. public static function setOrderUser($userId)
  118. {
  119. self::$user = User::findOrEmpty($userId)->toArray();
  120. return self::$user;
  121. }
  122. /**
  123. * @notes 订单结算详情
  124. * @param $params
  125. * @return array|bool
  126. * @author 段誉
  127. * @date 2021/7/23 15:52
  128. */
  129. public static function settlement($params)
  130. {
  131. try {
  132. //设置订单类型
  133. self::$OrderType = $params['order_type'];
  134. //设置用户信息
  135. $user = self::setOrderUser($params['user_id']);
  136. //设置用户地址
  137. $userAddress = UserAddress::getOneAddress($params['user_id'], $params['address_id'] ?? 0);
  138. //获取商品信息
  139. $goodsLists = self::getOrderGoodsData($params);
  140. //判断是否需要地址
  141. $is_address = 1;
  142. foreach ($goodsLists as $goods) {
  143. //非虚拟商品必填地址
  144. if ($goods['type'] != GoodsEnum::GOODS_VIRTUAL) {
  145. break;
  146. }
  147. $is_address = $goods['is_address'];
  148. }
  149. if ($is_address == 0) {
  150. $userAddress = [];
  151. }
  152. outFileLog($goodsLists,'freight','$goodsLists');
  153. //计算运费(自提订单不需要运费)
  154. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) {
  155. self::$orderPrice['express_price'] = 0;
  156. } else {
  157. $area_flag = ConfigService::get('shop', 'area_flag');
  158. if($area_flag==1){
  159. // $express_data = FreightLogic::calculateFreight($goodsLists, $userAddress);
  160. $new_express_price = self::getNewExpressPrice($goodsLists,$userAddress);
  161. self::$orderPrice['express_price'] = 33;
  162. }else{
  163. $express_data = FreightLogic::calculateFreight($goodsLists, $userAddress);
  164. self::$orderPrice['express_price'] = $express_data['express_price'];
  165. $goodsLists = $express_data['goods'];
  166. }
  167. }
  168. // 普通订单、虚拟订单可使用优惠券
  169. if (!empty($params['coupon_list_id']) && in_array(self::$OrderType, [OrderEnum::NORMAL_ORDER, OrderEnum::VIRTUAL_ORDER])) {
  170. $discountData = OrderCouponLogic::calculateCouponDiscount($goodsLists, $params['coupon_list_id']);
  171. self::$orderPrice['discount_amount'] = $discountData['discount'];
  172. self::$orderPrice['order_amount'] -= $discountData['discount'];
  173. $goodsLists = $discountData['goods'];
  174. }
  175. // 订单金额
  176. self::$orderPrice['total_amount'] += self::$orderPrice['express_price'];
  177. //订单应付金额
  178. self::$orderPrice['order_amount'] += self::$orderPrice['express_price'];
  179. $result = [
  180. 'terminal' => $params['terminal'],
  181. 'delivery_type' => intval($params['delivery_type']),
  182. 'delivery_type_desc' => DeliveryEnum::getDeliveryTypeDesc($params['delivery_type']),
  183. 'cart_id' => $params['cart_id'] ?? [],
  184. 'order_type' => self::$OrderType,
  185. 'coupon_list_id' => intval($params['coupon_list_id'] ?? 0),
  186. 'total_num' => self::$totalNum,
  187. 'total_goods_price' => bcadd(0, self::$orderPrice['total_goods_price'], 2),
  188. 'total_amount' => bcadd(0, self::$orderPrice['total_amount'], 2),
  189. 'order_amount' => bcadd(0, self::$orderPrice['order_amount'], 2),
  190. 'discount_amount' => bcadd(0, self::$orderPrice['discount_amount'], 2),
  191. 'member_amount' => bcadd(0, self::$orderPrice['member_amount'],2),
  192. 'express_price' => bcadd(0, self::$orderPrice['express_price'], 2),
  193. 'total_goods_original_price' => bcadd(0, self::$orderPrice['total_goods_original_price'], 2),
  194. 'user_id' => $user['id'],
  195. 'user_money' => $user['user_money'],
  196. 'user_remark' => $params['user_remark'] ?? '',
  197. 'address' => $userAddress,
  198. 'goods' => $goodsLists,
  199. 'goods_disabled' => static::$disabledGoods,
  200. 'selffetch_shop_id' => $params['selffetch_shop_id'] ?? '',
  201. 'selffetch_info' => [],
  202. 'contact' => $params['contact'] ?? '',
  203. 'mobile' => $params['mobile'] ?? '',
  204. 'is_address' => $is_address,
  205. 'draw_record_id' => $params['draw_record_id'] ?? 0,
  206. ];
  207. //门店自提显示上次提货人信息
  208. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) {
  209. $selffetch_info = Order::where(['user_id' => $user['id'], 'delivery_type' => DeliveryEnum::SELF_DELIVERY])
  210. ->field('address,selffetch_shop_id')
  211. ->order('id desc')
  212. ->findOrEmpty()->toArray();
  213. //上一次提货人
  214. if ($selffetch_info) {
  215. $selffetch_field = [
  216. 'id', 'name', 'image', 'contact', 'mobile',
  217. 'province', 'city', 'district', 'longitude', 'address', 'latitude',
  218. 'business_start_time', 'business_end_time', 'weekdays', 'remark',
  219. 'status',
  220. ];
  221. $result['selffetch_info'] = [
  222. 'selffetch_shop_id' => $selffetch_info['selffetch_shop_id'] ?? '',
  223. 'contact' => $selffetch_info['address']->contact ?? '',
  224. 'mobile' => $selffetch_info['address']->mobile ?? '',
  225. 'selffetch_shop' => SelffetchShop::where('status', 1)
  226. ->field($selffetch_field)
  227. ->append([ 'detailed_address' ])
  228. ->find($selffetch_info['selffetch_shop_id'] ?? 0),
  229. ];
  230. }
  231. }
  232. // 营销活动附加参数: 秒杀、拼团、砍价
  233. switch ($params['order_type']) {
  234. // 拼团
  235. case OrderEnum::TEAM_ORDER:
  236. $result['team_id'] = $params['team_id'];
  237. $result['found_id'] = $params['found_id'] ?? null;
  238. $teamFound = (new TeamFound())
  239. ->where(['id' => $result['found_id'], 'user_id' => $params['user_id']])
  240. ->findOrEmpty();
  241. if (!$teamFound->isEmpty()) {
  242. self::$error = '不允许参与自己开的团';
  243. return false;
  244. }
  245. break;
  246. // 秒杀
  247. case OrderEnum::SECKILL_ORDER:
  248. $result['seckill_id'] = $params['seckill_id'];
  249. break;
  250. // 砍价
  251. case OrderEnum::BARGAIN_ORDER:
  252. $result['initiate_id'] = $params['initiate_id'];
  253. break;
  254. // 预售
  255. case OrderEnum::PRESELL_ORDER:
  256. $result['presell_id'] = $params['presell_id'];
  257. break;
  258. // 抽奖
  259. case OrderEnum::DRAW_ORDER:
  260. //订单金额等于运费
  261. $result['order_amount'] = $result['express_price'];
  262. $result['total_amount'] = $result['express_price'];
  263. break;
  264. }
  265. // 判断是否符合包邮活动条件
  266. if (self::isFreeShipping($result)) {
  267. $result['order_amount'] = $result['order_amount'] - $result['express_price'];
  268. $result['total_amount'] = $result['total_amount'] - $result['express_price'];
  269. $result['express_price'] = 0;
  270. // 商品的运费也清0
  271. foreach ($goodsLists as &$goodsList) {
  272. $goodsList['express_price'] = 0;
  273. $goodsList['express_money'] = 0;
  274. }
  275. $result['goods'] = $goodsLists;
  276. }
  277. $result['total_goods_price'] = bcadd($result['total_goods_price'], 0, 2);
  278. $result['total_amount'] = bcadd($result['total_amount'], 0, 2);
  279. $result['order_amount'] = bcadd($result['order_amount'], 0, 2);
  280. $result['discount_amount'] = bcadd($result['discount_amount'], 0, 2);
  281. $result['member_amount'] = bcadd($result['member_amount'], 0, 2);
  282. $result['express_price'] = bcadd($result['express_price'], 0, 2);
  283. $result['total_goods_original_price'] = bcadd($result['total_goods_original_price'], 0, 2);
  284. return $result;
  285. } catch (\Exception $e) {
  286. self::$error = $e->getMessage();
  287. return false;
  288. }
  289. }
  290. public static function getNewExpressPrice($goods,$address){
  291. return 13;
  292. }
  293. /**
  294. * @notes 是否符合包邮活动条件
  295. */
  296. public static function isFreeShipping(&$params) {
  297. $params['is_free_shipping'] = false;
  298. if (empty($params['address'])) {
  299. return false;
  300. }
  301. // 获取当前时间进行中的包邮活动
  302. $activity = FreeShipping::where([
  303. ['start_time', '<=', time()],
  304. ['end_time', '>', time()],
  305. ['status', '=', FreeShippingEnum::ING],
  306. ])->find();
  307. if (!$activity) {
  308. // 没有包邮活动
  309. return false;
  310. }
  311. if ($activity->getData('condition_type') == FreeShippingEnum::BY_AMOUNT) {
  312. // 去除优惠金额
  313. $threshold = $params['total_goods_price'] - $params['discount_amount'];
  314. } else {
  315. $threshold = $params['total_num'];
  316. }
  317. $nationThreshold = 0;
  318. foreach($activity->region as $item) {
  319. if ($item->region_id == "100000") {
  320. // 全国区域留在最后判断
  321. $nationThreshold = $item->threshold;
  322. continue;
  323. }
  324. if (strpos($item->region_id, $params['address']->district_id) !== false) {
  325. if ($threshold >= $item->threshold) {
  326. $params['is_free_shipping'] = true;
  327. $params['free_shipping_id'] = $activity->id;
  328. return true;
  329. } else {
  330. return false;
  331. }
  332. }
  333. if (strpos($item->region_id, $params['address']->city_id) !== false) {
  334. if ($threshold >= $item->threshold) {
  335. $params['is_free_shipping'] = true;
  336. $params['free_shipping_id'] = $activity->id;
  337. return true;
  338. } else {
  339. return false;
  340. }
  341. }
  342. if (strpos($item->region_id, $params['address']->province_id) !== false) {
  343. if ($threshold >= $item->threshold) {
  344. $params['is_free_shipping'] = true;
  345. $params['free_shipping_id'] = $activity->id;
  346. return true;
  347. } else {
  348. return false;
  349. }
  350. }
  351. }
  352. if ($threshold >= $nationThreshold) {
  353. $params['is_free_shipping'] = true;
  354. $params['free_shipping_id'] = $activity->id;
  355. return true;
  356. }
  357. return false;
  358. }
  359. /**
  360. * @notes 提交订单前验证
  361. * @param $params
  362. * @throws \Exception
  363. * @author 段誉
  364. * @date 2021/7/23 15:53
  365. */
  366. public static function submitBeforeCheck($params)
  367. {
  368. // 商品检测
  369. if (empty($params['goods'])) {
  370. throw new \Exception('提交的商品已不能购买,请重新选择商品');
  371. }
  372. //配送方式为快递配送时,检测地址
  373. if (empty($params['address']) && $params['delivery_type'] == DeliveryEnum::EXPRESS_DELIVERY && $params['is_address'] == 1) {
  374. throw new \Exception('请选择收货地址');
  375. }
  376. //配送方式为门店自提时
  377. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY && empty($params['selffetch_shop_id'])) {
  378. throw new \Exception('自提门店不能为空');
  379. }
  380. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY && !empty($params['selffetch_shop_id'])) {
  381. $selffetch_shop = SelffetchShop::where('id', $params['selffetch_shop_id'])->findOrEmpty();
  382. if ($selffetch_shop->isEmpty()) {
  383. throw new \Exception('自提门店不存在');
  384. }
  385. }
  386. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY && empty($params['contact'])) {
  387. throw new \Exception('取货人不能为空');
  388. }
  389. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY && empty($params['mobile'])) {
  390. throw new \Exception('联系电话不能为空');
  391. }
  392. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY && !Validate::mobile($params['mobile'])) {
  393. throw new \Exception('联系电话格式不正确');
  394. }
  395. // 校验商品数量
  396. $limit_arr = [];
  397. foreach ($params['goods'] as $goods) {
  398. if ($goods['goods_num'] <= 0) {
  399. throw new \Exception('请选择商品' . ($goods['goods_name'] ?? '') . '数量');
  400. }
  401. $limit_arr[$goods['goods_id']]['goods_num'] = ($limit_arr[$goods['goods_id']]['goods_num'] ?? 0) + $goods['goods_num'];
  402. $limit_arr[$goods['goods_id']]['limit_type'] = $goods['limit_type'];
  403. $limit_arr[$goods['goods_id']]['limit_value'] = $goods['limit_value'];
  404. $limit_arr[$goods['goods_id']]['goods_name'] = $goods['goods_name'];
  405. $limit_arr[$goods['goods_id']]['goods_id'] = $goods['goods_id'];
  406. }
  407. //校验限购商品
  408. foreach ($limit_arr as $limit_val) {
  409. if (static::isOutBuyNum($limit_val, $limit_val['goods_num'], $params['user_id'])) {
  410. throw new \Exception('商品:' . ($limit_val['goods_name'] ?? '') . ' 超过限购数量');
  411. }
  412. }
  413. //验证订单商品是否支持对应的配送方式
  414. $is_express = ConfigService::get('delivery_type', 'is_express', 1);
  415. $is_selffetch = ConfigService::get('delivery_type', 'is_selffetch', 0);
  416. $item_ids = implode(',', array_column($params['goods'], 'item_id'));
  417. $goods_ids = implode(',', GoodsItem::where('id', 'in', $item_ids)->column('goods_id'));
  418. $goods = Goods::where('id', 'in', $goods_ids)->select();
  419. $goods_name = [];
  420. //门店自提
  421. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) {
  422. if ($is_selffetch == 0) {
  423. throw new \Exception('系统未开启门店自提配送方式');
  424. }
  425. foreach ($goods as $val) {
  426. //虚拟商品不支持门店自提
  427. if (GoodsEnum::GOODS_VIRTUAL == $val['type']) {
  428. throw new \Exception($val['name'] . '不支持门店自提');
  429. }
  430. if ($val['is_selffetch'] == 0) {
  431. $goods_name[] = $val['name'];
  432. }
  433. }
  434. } elseif ($params['delivery_type'] == DeliveryEnum::EXPRESS_DELIVERY) { //快递配送
  435. if ($is_express == 0) {
  436. throw new \Exception('系统未开启快递配送方式');
  437. }
  438. foreach ($goods as $val) {
  439. //实物商品且不支持物流
  440. if ($val['is_express'] == 0 && GoodsEnum::GOODS_REALITY == $val['type']) {
  441. $goods_name[] = $val['name'];
  442. }
  443. }
  444. }
  445. if (!empty($goods_name)) {
  446. throw new \Exception(implode('、', $goods_name) . '不支持' . DeliveryEnum::getDeliveryTypeDesc($params['delivery_type']) . ',请重新选择配送方式');
  447. }
  448. }
  449. /**
  450. * @notes 提交订单
  451. * @param $params
  452. * @return array|bool
  453. * @author 段誉
  454. * @date 2021/7/23 15:53
  455. */
  456. public static function submitOrder($params)
  457. {
  458. Db::startTrans();
  459. try {
  460. //提交前验证
  461. self::submitBeforeCheck($params);
  462. //删除购物车
  463. self::delCartByOrder($params);
  464. //下单扣除库存
  465. self::decStock($params['goods']);
  466. //判断PC端邀请人信息是否存在。不存在的话需要相伴i的那个邀请人才能下单
  467. if($params['terminal'] ==4){
  468. if(!self::$user['inviter_id']){
  469. self::$error = '您未绑定推荐码,请联系商店管理员绑定推荐码后再次下单!';
  470. return false;
  471. }
  472. }
  473. //提交订单
  474. $order = self::addOrder($params, self::$user['id']);
  475. //下单增加商品销量
  476. self::incSale($params['goods']);
  477. //有使用优惠券时更新coupon_list
  478. if ($params['coupon_list_id'] > 0) {
  479. self::handleCouponByOrder($params['coupon_list_id'], $order['id']);
  480. }
  481. // 营销活动下单后的操作
  482. switch ($params['order_type']) {
  483. // 拼团
  484. case OrderEnum::TEAM_ORDER:
  485. self::teamAfter($params, $order);
  486. break;
  487. // 秒杀
  488. case OrderEnum::SECKILL_ORDER:
  489. self::seckillAfter($params, $order);
  490. break;
  491. // 砍价
  492. case OrderEnum::BARGAIN_ORDER:
  493. self::bargainAfter($params, $order);
  494. break;
  495. // 预售
  496. case OrderEnum::PRESELL_ORDER:
  497. self::presellAfter($params, $order);
  498. break;
  499. }
  500. // 判断是否为包邮活动订单
  501. if ($params['is_free_shipping']) {
  502. FreeShippingOrder::create([
  503. 'free_shpping_id' => $params['free_shipping_id'],
  504. 'order_id' => $order['id'],
  505. 'amount' => $order['order_amount']
  506. ]);
  507. }
  508. //订单日志
  509. (new OrderLog())->record([
  510. 'type' => OrderLogEnum::TYPE_USER,
  511. 'channel' => OrderLogEnum::USER_ADD_ORDER,
  512. 'order_id' => $order['id'],
  513. 'operator_id' => self::$user['id'],
  514. ]);
  515. //抽奖记录结算
  516. LuckyDrawRecord::update([
  517. 'id' => $params['draw_record_id'] ?? 0,
  518. 'is_send' => YesNoEnum::YES,
  519. 'send_time' => time(),
  520. ]);
  521. //提交事务
  522. Db::commit();
  523. return ['order_id' => $order['id'], 'type' => 'order'];
  524. } catch (\Exception $e) {
  525. Db::rollback();
  526. self::$error = $e->getMessage();
  527. return false;
  528. }
  529. }
  530. /**
  531. * @notes 更新订单优惠券状态
  532. * @param $coupon_list_id
  533. * @param $order_id
  534. * @throws \think\db\exception\DataNotFoundException
  535. * @throws \think\db\exception\DbException
  536. * @throws \think\db\exception\ModelNotFoundException
  537. * @author ljj
  538. * @date 2021/9/14 11:39 上午
  539. */
  540. public static function handleCouponByOrder($coupon_list_id, $order_id)
  541. {
  542. $coupon_list = CouponList::find($coupon_list_id);
  543. $coupon_list->order_id = $order_id;
  544. $coupon_list->status = CouponEnum::USE_STATUS_OK;
  545. $coupon_list->use_time = time();
  546. $coupon_list->update_time = time();
  547. $coupon_list->save();
  548. }
  549. /**
  550. * @notes 扣减库存
  551. * @param $goodLists
  552. * @throws \Exception
  553. * @author 段誉
  554. * @date 2021/8/9 17:47
  555. */
  556. public static function decStock($goodLists)
  557. {
  558. foreach ($goodLists as $goods) {
  559. $goodsItem = GoodsItem::where(['id' => $goods['item_id']])->findOrEmpty()->toArray();
  560. if ($goodsItem['stock'] < $goods['goods_num']) {
  561. throw new \Exception('商品库存不足');
  562. }
  563. //更新商品总库存
  564. Goods::update(['total_stock' => ['dec', $goods['goods_num']]], ['id' => $goods['goods_id']]);
  565. //更新规格库存
  566. GoodsItem::update(['stock' => ['dec', $goods['goods_num']]], ['id' => $goods['item_id']]);
  567. }
  568. }
  569. /**
  570. * @notes 下单增加销量
  571. * @param $goodLists
  572. * @throws \Exception
  573. * @author ljj
  574. * @date 2021/9/22 5:30 下午
  575. */
  576. public static function incSale($goodLists)
  577. {
  578. foreach ($goodLists as $goods) {
  579. Goods::update(['sales_num' => ['inc', $goods['goods_num']]], ['id' => $goods['goods_id']]);
  580. }
  581. }
  582. /**
  583. * @notes 删除购物车(购物车下单情况)
  584. * @param $params
  585. * @author 段誉
  586. * @date 2021/7/23 15:54
  587. */
  588. public static function delCartByOrder($params)
  589. {
  590. if (!empty($params['cart_id'])) {
  591. Cart::where(['id' => $params['cart_id'], 'user_id' => self::$user['id']])->delete();
  592. }
  593. }
  594. /**
  595. * @notes 添加订单
  596. * @param $params
  597. * @param $user_id
  598. * @author 段誉
  599. * @date 2021/8/9 17:42
  600. */
  601. public static function addOrder($params, $user_id)
  602. {
  603. $order = Order::create([
  604. 'sn' => generate_sn((new Order()), 'sn'),
  605. 'order_type' => $params['order_type'],
  606. 'user_id' => $user_id,
  607. 'order_terminal' => $params['terminal'],
  608. 'coupon_list_id' => $params['coupon_list_id'],
  609. 'total_num' => $params['total_num'],
  610. 'total_amount' => $params['total_amount'],
  611. 'goods_price' => $params['total_goods_price'],
  612. 'order_amount' => $params['order_amount'],
  613. 'express_price' => $params['express_price'],
  614. 'discount_amount' => $params['discount_amount'],
  615. 'member_amount' => $params['member_amount'],
  616. 'user_remark' => $params['user_remark'],
  617. 'address' => [
  618. 'contact' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? $params['contact'] : ($params['address']['contact'] ?? ''),
  619. 'province' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? '' : ($params['address']['province_id'] ?? ''),
  620. 'city' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? '' : ($params['address']['city_id'] ?? ''),
  621. 'district' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? '' : ($params['address']['district_id'] ?? ''),
  622. 'address' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? '' : ($params['address']['address'] ?? ''),
  623. 'mobile' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? $params['mobile'] : ($params['address']['mobile'] ?? ''),
  624. ],
  625. 'delivery_type' => OrderEnum::VIRTUAL_ORDER == $params['order_type'] ? DeliveryEnum::DELIVERY_VIRTUAL : $params['delivery_type'],
  626. 'pickup_code' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? create_number_sn((new Order()), 'pickup_code', 6) : null,
  627. 'selffetch_shop_id' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? $params['selffetch_shop_id'] : 0,
  628. 'draw_record_id' => $params['draw_record_id'] ?? 0,
  629. ]);
  630. $goodsData = [];
  631. foreach ($params['goods'] as $goods) {
  632. //商品实付价格
  633. $totalPayPrice = $goods['sub_price'] - ($goods['discount_price'] ?? 0) + ($goods['express_price'] ?? 0);
  634. $totalPayPrice = $totalPayPrice <= 0 ? 0 : $totalPayPrice;
  635. $goodsData[] = [
  636. 'order_id' => $order['id'],
  637. 'goods_id' => $goods['goods_id'],
  638. 'item_id' => $goods['item_id'],
  639. 'goods_name' => $goods['goods_name'],
  640. 'goods_num' => $goods['goods_num'],
  641. 'goods_price' => $goods['sell_price'],//商品价格单价(未扣减优惠和积分价格)
  642. 'total_price' => $goods['sub_price'],
  643. 'total_pay_price' => $totalPayPrice,//实际支付商品金额(扣除优惠金额、加上运费)
  644. 'spec_value_ids' => $goods['spec_value_ids'],
  645. 'discount_price' => $goods['discount_price'] ?? 0,//优惠券优惠金额
  646. 'original_price' => $goods['original_price'] ?? 0,//商品原始价格
  647. 'member_price' => $goods['member_price'] ?? 0,//商品会员价格
  648. 'goods_snap' => $goods,
  649. 'express_price' => $goods['express_price'] ?? 0,//运费
  650. ];
  651. }
  652. (new OrderGoods())->saveAll($goodsData);
  653. return $order;
  654. }
  655. /**
  656. * @notes 商品信息
  657. * @param $params
  658. * @return array
  659. * @author 段誉
  660. * @date 2021/7/23 15:54
  661. */
  662. public static function getOrderGoodsData($params)
  663. {
  664. // 购物车下单
  665. if ($params['source'] == 'cart') {
  666. $params['goods'] = Cart::where([
  667. ['id', 'in', $params['cart_id']],
  668. ['user_id', '=', $params['user_id']],
  669. ])->field('item_id,goods_id,goods_num')->select()->toArray();
  670. }
  671. // 砍价商品信息提取
  672. if ($params['order_type'] == OrderEnum::BARGAIN_ORDER) {
  673. $params['goods'] = self::initiateGoods($params);
  674. }
  675. $itemIds = array_column($params['goods'], 'item_id');
  676. $field = [
  677. 'gi.id', 'gi.id' => 'item_id', 'gi.image' => 'item_image',
  678. 'gi.spec_value_str', 'spec_value_ids', 'gi.sell_price',
  679. 'gi.volume', 'gi.stock', 'gi.weight', 'gi.bar_code', 'g.id' => 'goods_id',
  680. 'g.name' => 'goods_name', 'g.type', 'g.status', 'g.delete_time', 'g.image',
  681. 'g.express_type', 'g.express_money', 'g.express_template_id',
  682. 'g.is_express', 'g.is_selffetch', 'g.is_express', 'g.is_virtualdelivery',
  683. 'g.after_pay', 'g.after_delivery', 'g.delivery_content', 'g.delivery_type','g.delivery_template_id',
  684. 'g.code', 'g.is_address', 'g.limit_type', 'g.limit_value'
  685. ];
  686. $goodsData = (new Goods())->alias('g')
  687. ->join('goods_item gi', 'gi.goods_id = g.id')
  688. ->with([ 'goods_category_index2', 'delivery_template' ])
  689. ->where('gi.id', 'in', $itemIds)
  690. ->field($field)
  691. ->select()->toArray();
  692. $goodsData = array_column($goodsData, null, 'id');
  693. //处理图片路径
  694. foreach ($goodsData as &$val) {
  695. $val['item_image'] = trim($val['item_image']) ? FileService::getFileUrl($val['item_image']) : '';
  696. }
  697. return self::getOrderGoodsLists($params, $goodsData);
  698. }
  699. /**
  700. * @notes 结算商品列表
  701. * @param $goods
  702. * @param $goodsData
  703. * @return array
  704. * @author 段誉
  705. * @date 2021/7/23 15:55
  706. */
  707. public static function getOrderGoodsLists($params, $goodsData)
  708. {
  709. $goods = $params['goods'];
  710. $goodsIds = array_column($goodsData, 'goods_id');
  711. $levelGoodsItem = DiscountLogic::getGoodsDiscount(self::$user['id'], $goodsIds);
  712. $goodsLists = [];
  713. foreach ($goods as $k => $item) {
  714. //删除没找到商品信息的商品
  715. if (!isset($goodsData[$item['item_id']])) {
  716. unset($goods[$k]);
  717. static::$disabledGoods[] = [
  718. 'msg' => '找不到商品',
  719. 'goods' => $goodsData[$item['item_id']] ?? [],
  720. ];
  721. continue;
  722. }
  723. //组装商品数据
  724. $goodsInfo = $goodsData[$item['item_id']];
  725. $goodsInfo['goods_num'] = intval($item['goods_num'] ?? 0);
  726. //记录原价
  727. $goodsInfo['original_price'] = $goodsInfo['sell_price'];
  728. $goodsInfo['sub_price'] = round($goodsInfo['sell_price'] * $item['goods_num'], 2);
  729. //当前商品是否被删除或下架
  730. if ($goodsInfo['delete_time'] > 0 || $goodsInfo['status'] != 1) {
  731. unset($goods[$k]);
  732. static::$disabledGoods[] = [
  733. 'msg' => '商品不能购买',
  734. 'goods' => $goodsInfo,
  735. ];
  736. continue;
  737. }
  738. //当前库存是否足够
  739. if ($item['goods_num'] > $goodsInfo['stock']) {
  740. unset($goods[$k]);
  741. static::$disabledGoods[] = [
  742. 'msg' => '商品库存不足',
  743. 'goods' => $goodsInfo,
  744. ];
  745. continue;
  746. }
  747. // 是否限购
  748. if (static::isOutBuyNum($goodsInfo, $item['goods_num'], $params['user_id'])) {
  749. unset($goods[$k]);
  750. static::$disabledGoods[] = [
  751. 'msg' => '超过购买限制',
  752. 'goods' => $goodsInfo,
  753. ];
  754. continue;
  755. }
  756. $goodsInfo['member_price'] = 0;
  757. if(in_array(self::$OrderType,[OrderEnum::NORMAL_ORDER,OrderEnum::VIRTUAL_ORDER])){
  758. //会员折扣
  759. $goodsInfo['member_price'] = $levelGoodsItem[$goodsInfo['goods_id']][$goodsInfo['item_id']]['discount_price'] ?? '';
  760. }
  761. // 获取不同订单类型的规格单价
  762. $goodsInfo['sell_price'] = self::getSellPrice($params, $goodsInfo);
  763. $goodsInfo['sub_price'] = round($goodsInfo['sell_price'] * $item['goods_num'], 2);
  764. $goodsInfo['total_original_price'] = round($goodsInfo['original_price'] * $goodsInfo['goods_num'], 2);//商品原价合计
  765. $goodsLists[] = $goodsInfo;
  766. self::$totalNum += $item['goods_num'];
  767. self::$orderPrice['total_goods_price'] += $goodsInfo['sub_price'];
  768. //普通商品,计算折扣金额
  769. if(in_array(self::$OrderType,[OrderEnum::NORMAL_ORDER,OrderEnum::VIRTUAL_ORDER])){
  770. $memberAmount = round(($goodsInfo['original_price'] - $goodsInfo['sell_price']) * $item['goods_num'],2);
  771. self::$orderPrice['member_amount'] += $memberAmount;
  772. }
  773. //订单商品原价总价
  774. self::$orderPrice['total_goods_original_price'] += $goodsInfo['total_original_price'];
  775. }
  776. //订单金额
  777. self::$orderPrice['total_amount'] = self::$orderPrice['total_goods_price'] + self::$orderPrice['member_amount'];
  778. //订单应付金额
  779. self::$orderPrice['order_amount'] = self::$orderPrice['total_goods_price'];
  780. return $goodsLists;
  781. }
  782. /**
  783. * @notes 是否超出 购买限制
  784. * @param $goods
  785. * @param $num
  786. * @param $userId
  787. * @return bool
  788. * @author lbzy
  789. * @datetime 2023-08-16 15:13:47
  790. */
  791. static function isOutBuyNum($goods, $num, $userId) : bool
  792. {
  793. if ($goods['limit_type'] == GoodsEnum::LIMIT_TYPE_USER) {
  794. $order_goods_num = OrderGoods::alias('og')
  795. ->join('order o', 'o.id = og.order_id')
  796. ->where([
  797. 'og.goods_id'=>$goods['goods_id'],
  798. 'o.order_status'=>[
  799. OrderEnum::STATUS_WAIT_PAY,
  800. OrderEnum::STATUS_WAIT_DELIVERY,
  801. OrderEnum::STATUS_WAIT_RECEIVE,
  802. OrderEnum::STATUS_FINISH
  803. ],
  804. 'o.user_id' => $userId,
  805. 'o.order_type' => [ OrderEnum::NORMAL_ORDER, OrderEnum::VIRTUAL_ORDER] ]
  806. )
  807. ->sum('og.goods_num');
  808. return ($order_goods_num + $goods['goods_num']) > $goods['limit_value'];
  809. }
  810. if ($goods['limit_type'] == GoodsEnum::LIMIT_TYPE_ORDER) {
  811. return $num > $goods['limit_value'];
  812. }
  813. return false;
  814. }
  815. /**
  816. * @notes 订单详情
  817. * @param $params
  818. * @return array
  819. * @author 段誉
  820. * @date 2021/8/2 20:59
  821. */
  822. public static function getDetail($params)
  823. {
  824. $result = (new Order())->with(['order_goods' => function ($query) {
  825. $query->field([
  826. 'id', 'order_id', 'goods_id', 'item_id', 'goods_snap', 'original_price',
  827. 'goods_name', 'goods_price', 'goods_num', 'total_price', 'total_pay_price', 'express_price', 'change_price', 'discount_price', 'discount_price'=>'coupon_discount', 'member_price', 'integral_price'
  828. ])->append(['goods_image', 'spec_value_str','original_price'])->hidden(['goods_snap']);
  829. }])
  830. ->where(['id' => $params['id'], 'user_id' => $params['user_id']])
  831. ->append(['btn', 'delivery_address', 'cancel_unpaid_orders_time', 'show_pickup_code'])
  832. ->hidden(['user_id', 'order_terminal', 'delete_time', 'update_time'])
  833. ->findOrEmpty()->toArray();
  834. //订单类型
  835. $result['order_type_desc'] = ($result['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? '自提订单' : OrderEnum::getOrderTypeDesc($result['order_type']);
  836. //订单状态描述
  837. $result['order_status_desc'] = ($result['order_status'] == OrderEnum::STATUS_WAIT_DELIVERY && $result['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? '待取货' : OrderEnum::getOrderStatusDesc($result['order_status']);
  838. if ($result['order_type'] == OrderEnum::TEAM_ORDER && $result['is_team_success'] != TeamEnum::TEAM_FOUND_SUCCESS) {
  839. $result['order_status_desc'] = ($result['order_status'] == OrderEnum::STATUS_WAIT_DELIVERY) ? TeamEnum::getStatusDesc($result['is_team_success']) : OrderEnum::getOrderStatusDesc($result['order_status']);
  840. }
  841. // 预售信息
  842. if ($result['order_type'] == OrderEnum::PRESELL_ORDER) {
  843. $result['presell'] = CommonPresellLogic::orderInfo($result);
  844. }
  845. //自提门店
  846. $result['selffetch_shop'] = SelffetchShop::where('id', $result['selffetch_shop_id'])
  847. ->append(['detailed_address'])
  848. ->hidden([ 'create_time', 'update_time', 'delete_time' ])
  849. ->find();
  850. //地址 省市区分隔开
  851. $result['address']->province = Region::where('id', $result['address']->province)->value('name');
  852. $result['address']->city = Region::where('id', $result['address']->city)->value('name');
  853. $result['address']->district = Region::where('id', $result['address']->district)->value('name');
  854. //订单商品原价总价
  855. $result['total_original_price'] = 0;
  856. //订单商品售后按钮处理
  857. foreach ($result['order_goods'] as &$goods) {
  858. $goods['after_sale_btn'] = 0;//售后按钮关闭
  859. $after_sale = AfterSale::where(['order_goods_id' => $goods['id'], 'order_id' => $params['id']])->findOrEmpty();
  860. $after_sale_goods = AfterSaleGoods::where(['order_goods_id' => $goods['id'], 'after_sale_id' => $after_sale['id']])->findOrEmpty();
  861. $goods['after_sale_id'] = $after_sale_goods['id'] ?? 0;
  862. if ($result['order_status'] == OrderEnum::STATUS_FINISH && $result['after_sale_deadline'] > time() && $after_sale->isEmpty()) {
  863. $goods['after_sale_btn'] = 1;//售后按钮开启
  864. }
  865. if ($result['order_status'] == OrderEnum::STATUS_FINISH && $result['after_sale_deadline'] > time() && $after_sale['status'] == AfterSaleEnum::STATUS_ING) {
  866. $goods['after_sale_btn'] = 2;//售后中
  867. }
  868. if ($result['order_status'] == OrderEnum::STATUS_FINISH && $result['after_sale_deadline'] > time() && $after_sale['status'] == AfterSaleEnum::STATUS_SUCCESS) {
  869. $goods['after_sale_btn'] = 3;//售后成功
  870. }
  871. if ($result['order_status'] == OrderEnum::STATUS_FINISH && $result['after_sale_deadline'] > time() && $after_sale['status'] == AfterSaleEnum::STATUS_FAIL) {
  872. $goods['after_sale_btn'] = 4;//售后失败
  873. }
  874. //批量下单后,过了取消订单的时间,可对其中一件商品进行退款操作
  875. if (in_array($result['order_status'],[OrderEnum::STATUS_WAIT_DELIVERY,OrderEnum::STATUS_WAIT_RECEIVE])) {
  876. $ableCancelOrder = ConfigService::get('transaction', 'cancel_unshipped_orders');
  877. if ($ableCancelOrder == YesNoEnum::NO) {
  878. $goods['after_sale_btn'] = 1;//售后按钮开启
  879. }
  880. if ($ableCancelOrder == YesNoEnum::YES) {
  881. $configTime = ConfigService::get('transaction', 'cancel_unshipped_orders_times');
  882. $ableCancelTime = strtotime($result['pay_time']) + ($configTime * 60);
  883. if (time() > $ableCancelTime) {
  884. $goods['after_sale_btn'] = 1;//售后按钮开启
  885. }
  886. }
  887. if (isset($after_sale['status']) && $after_sale['status'] == AfterSaleEnum::STATUS_ING) {
  888. $goods['after_sale_btn'] = 2;//售后中
  889. }
  890. if (isset($after_sale['status']) && $after_sale['status'] == AfterSaleEnum::STATUS_SUCCESS) {
  891. $goods['after_sale_btn'] = 3;//售后成功
  892. }
  893. if (isset($after_sale['status']) && $after_sale['status'] == AfterSaleEnum::STATUS_FAIL) {
  894. $goods['after_sale_btn'] = 4;//售后失败
  895. }
  896. }
  897. //商品原价总价
  898. $goods['total_original_price'] = $goods['original_price'] * $goods['goods_num'];
  899. $result['total_original_price'] += $goods['original_price'] * $goods['goods_num'];
  900. //会员价优惠
  901. $goods['member_discount'] = 0;
  902. if($goods['member_price'] > 0){
  903. $goods['member_discount'] = round(($goods['original_price'] - $goods['member_price']) * $goods['goods_num'],2);
  904. }
  905. // unset($goods['member_price']);
  906. //积分优惠
  907. $goods['integral_discount'] = round($goods['integral_price'] * $goods['goods_num'],2);
  908. // unset($goods['integral_price']);
  909. //售后状态
  910. $goods['after_sale_status_desc'] = '无售后';
  911. if (!$after_sale->isEmpty()) {
  912. $goods['after_sale_status_desc'] = AfterSaleEnum::getStatusDesc($after_sale->status);
  913. }
  914. //订单商品总的优惠
  915. $goods['total_discount'] = round($goods['member_discount']+ $goods['coupon_discount'] +$goods['integral_discount'],2);
  916. }
  917. //订单商品原价总价
  918. $result['total_original_price'] = round($result['total_original_price'],2);
  919. //订单总优惠金额
  920. $result['total_discount'] = $result['discount_amount'] + $result['member_amount'] + $result['integral_amount'];
  921. // unset($result['discount_amount']);unset($result['member_amount']);unset($result['integral_amount']);
  922. //商品详情屏蔽查看内容按钮
  923. $result['btn']['content_btn'] = OrderEnum::BTN_HIDE;
  924. return $result;
  925. }
  926. static function wxReceiveDetail($id, $user_id)
  927. {
  928. $order = Order::where('id', $id)->where('user_id', $user_id)->findOrEmpty()->toArray();
  929. return [
  930. 'transaction_id' => $order['transaction_id'] ?? '',
  931. ];
  932. }
  933. /**
  934. * @notes 取消订单
  935. * @param $params
  936. * @return bool
  937. * @author 段誉
  938. * @date 2021/8/2 15:08
  939. */
  940. public static function cancelOrder($params)
  941. {
  942. Db::startTrans();
  943. try {
  944. $order = (new Order())->getUserOrderById($params['id'], $params['user_id']);
  945. // 如果是拼团订单特别处理
  946. if ($order['order_type'] == OrderEnum::TEAM_ORDER) {
  947. TeamLogic::signFailTeam($order['id']);
  948. } else {
  949. //处于已支付状态的发起整单售后
  950. if ($order['pay_status'] == PayEnum::ISPAID) {
  951. AfterSaleService::orderRefund([
  952. 'order_id' => $params['id'],
  953. 'scene' => AfterSaleLogEnum::BUYER_CANCEL_ORDER
  954. ]);
  955. }
  956. //更新订单为已关闭
  957. Order::update([
  958. 'order_status' => OrderEnum::STATUS_CLOSE,
  959. 'cancel_time' => time()
  960. ], ['id' => $order['id']]);
  961. $returnInventory = ConfigService::get('transaction', 'return_inventory');
  962. if ($returnInventory) {
  963. // 需退还库存
  964. AfterSaleService::returnInventory(['order_id' => $order['id']]);
  965. }
  966. $returnCoupon = ConfigService::get('transaction', 'return_coupon');
  967. if ($returnCoupon) {
  968. // 需退还优惠券
  969. AfterSaleService::returnCoupon($order);
  970. }
  971. //订单日志
  972. (new OrderLog())->record([
  973. 'type' => OrderLogEnum::TYPE_USER,
  974. 'channel' => OrderLogEnum::USER_CANCEL_ORDER,
  975. 'order_id' => $params['id'],
  976. 'operator_id' => $params['user_id'],
  977. ]);
  978. }
  979. Db::commit();
  980. return true;
  981. } catch (\Exception $e) {
  982. Db::rollback();
  983. self::$error = $e->getMessage();
  984. return false;
  985. }
  986. }
  987. /**
  988. * @notes 确认订单
  989. * @param $params
  990. * @author 段誉
  991. * @date 2021/8/2 14:59
  992. */
  993. public static function confirmOrder($params)
  994. {
  995. //更新订单状态
  996. Order::update([
  997. 'order_status' => OrderEnum::STATUS_FINISH,
  998. 'confirm_take_time' => time(),
  999. 'after_sale_deadline' => self::getAfterSaleDeadline(), //售后截止时间
  1000. ], ['id' => $params['id'], 'user_id' => $params['user_id']]);
  1001. //订单日志
  1002. (new OrderLog())->record([
  1003. 'type' => OrderLogEnum::TYPE_USER,
  1004. 'channel' => OrderLogEnum::USER_CONFIRM_ORDER,
  1005. 'order_id' => $params['id'],
  1006. 'operator_id' => $params['user_id']
  1007. ]);
  1008. }
  1009. /**
  1010. * @notes 获取当前售后
  1011. * @return float|int
  1012. * @author 段誉
  1013. * @date 2021/8/2 17:02
  1014. */
  1015. public static function getAfterSaleDeadline()
  1016. {
  1017. //是否关闭维权
  1018. $afterSale = ConfigService::get('transaction', 'after_sales');
  1019. //可维权时间
  1020. $afterSaleDays = ConfigService::get('transaction', 'after_sales_days');
  1021. if ($afterSale == YesNoEnum::NO) {
  1022. $afterSaleDeadline = time();
  1023. } else {
  1024. $afterSaleDeadline = ($afterSaleDays * 24 * 60 * 60) + time();
  1025. }
  1026. return $afterSaleDeadline;
  1027. }
  1028. /**
  1029. * @notes 查看物流
  1030. * @param $params
  1031. * @return array[]
  1032. * @author ljj
  1033. * @date 2021/8/13 6:07 下午
  1034. */
  1035. public static function orderTraces($params)
  1036. {
  1037. //订单信息
  1038. $order = Order::field('id,sn,pay_time,address,order_type,express_status,order_status')
  1039. ->append(['delivery_address'])
  1040. ->where('id',$params['id'])
  1041. ->find()
  1042. ->toArray();
  1043. //物流配置
  1044. $express_type = ConfigService::get('logistics_config', 'express_type', '');
  1045. $express_bird = unserialize(ConfigService::get('logistics_config', 'express_bird', ''));
  1046. $express_hundred = unserialize(ConfigService::get('logistics_config', 'express_hundred', ''));
  1047. $parcelInfo = Delivery::field('id,order_id,order_goods_info,express_name,express_id,invoice_no,send_type,remark,create_time,delivery_address_info,return_address_info')
  1048. ->where(['order_id'=>$order['id']])
  1049. ->append(['send_type_desc'])
  1050. ->select()->toArray();
  1051. foreach ($parcelInfo as $key=>$parcel) {
  1052. //查询物流信息
  1053. $logisticsInfo = [];
  1054. if ($parcel['send_type'] == DeliveryEnum::NO_EXPRESS) {
  1055. $logisticsInfo['traces'] = ['无需物流'];
  1056. } else {
  1057. if (empty($express_type)) {
  1058. $logisticsInfo['traces'] = ['暂无物流信息'];
  1059. }
  1060. //快递配置设置为快递鸟时
  1061. if($express_type === 'express_bird') {
  1062. $expressage = (new Kdniao($express_bird['ebussiness_id'], $express_bird['app_key']));
  1063. $express_field = 'codebird';
  1064. } elseif($express_type === 'express_hundred') {
  1065. $expressage = (new Kd100($express_hundred['customer'], $express_hundred['app_key']));
  1066. $express_field = 'code100';
  1067. }
  1068. //快递编码
  1069. $express_code = Express::where('id',$parcel['express_id'])->value($express_field);
  1070. //获取物流轨迹
  1071. if (in_array(strtolower($express_code), [ 'sf', 'shunfeng' ])) {
  1072. if ($express_type === 'express_bird') {
  1073. $expressage->logistics($express_code, $parcel['invoice_no'], substr($order['address']->mobile, -4));
  1074. } else {
  1075. $expressage->logistics($express_code, $parcel['invoice_no'], $order['address']->mobile);
  1076. }
  1077. }else {
  1078. $expressage->logistics($express_code, $parcel['invoice_no']);
  1079. }
  1080. $logisticsInfo['traces'] = $expressage->logisticsFormat();
  1081. if ($logisticsInfo['traces'] == false) {
  1082. $logisticsInfo['traces'] = ['暂无物流信息'];
  1083. } else {
  1084. foreach ($logisticsInfo['traces'] as &$item) {
  1085. $item = array_values(array_unique($item));
  1086. }
  1087. }
  1088. }
  1089. $parcelInfo[$key]['logistics_info'] = $logisticsInfo;
  1090. $parcelInfo[$key]['express_icon'] = Express::where('id',$parcel['express_id'])->value('icon');
  1091. }
  1092. $deliveryAddressInfo = !empty($parcelInfo[0]['delivery_address_info']) ? json_decode($parcelInfo[0]['delivery_address_info'],true) : '';
  1093. $returnAddressInfo = !empty($parcelInfo[0]['return_address_info']) ? json_decode($parcelInfo[0]['return_address_info'],true) : '';
  1094. //待发货商品
  1095. $waitDeliveryGoods = OrderGoods::where(['order_id'=>$order['id'],'express_status'=>[DeliveryEnum::NOT_SHIPPED,DeliveryEnum::PART_SHIPPED]])
  1096. ->field('id,goods_name,goods_num,goods_price,delivery_num,goods_snap')
  1097. ->append(['spec_value_str','goods_image'])
  1098. ->hidden(['goods_snap'])->select()->toArray();
  1099. foreach ($waitDeliveryGoods as $key=>$goods) {
  1100. $afterSale = AfterSale::where(['order_goods_id'=>$goods['id'],'status'=>AfterSaleEnum::STATUS_SUCCESS])->findOrEmpty();
  1101. if (!$afterSale->isEmpty()) {
  1102. unset($waitDeliveryGoods[$key]);
  1103. }
  1104. }
  1105. $waitDeliveryGoods = empty($waitDeliveryGoods) ? [] : array_values($waitDeliveryGoods);
  1106. return [
  1107. 'order_id' => $order['id'],
  1108. 'order_sn' => $order['sn'],
  1109. 'order_type' => $order['order_type'],
  1110. 'order_status' => $order['order_status'],
  1111. 'express_status' => $order['express_status'],
  1112. 'pay_time' => $order['pay_time'],
  1113. 'receipt_address_info' => [
  1114. 'addresss' => $order['delivery_address'],
  1115. 'contact' => $order['address']->contact,
  1116. 'mobile' => $order['address']->mobile,
  1117. ],
  1118. 'delivery_address_info' => [
  1119. 'addresss' => $deliveryAddressInfo['complete_address'] ?? '',
  1120. 'contact' => $deliveryAddressInfo['contact'] ?? '',
  1121. 'mobile' => $deliveryAddressInfo['mobile'] ?? '',
  1122. ],
  1123. 'return_address_info' => [
  1124. 'addresss' => $returnAddressInfo['complete_address'] ?? '',
  1125. 'contact' => $returnAddressInfo['contact'] ?? '',
  1126. 'mobile' => $returnAddressInfo['mobile'] ?? '',
  1127. ],
  1128. 'remark' => $parcelInfo[0]['remark'],
  1129. 'parcel_info' => $parcelInfo,
  1130. 'wait_delivery_goods' => $waitDeliveryGoods
  1131. ];
  1132. }
  1133. /**
  1134. * @notes 获取配送方式
  1135. * @return array
  1136. * @author ljj
  1137. * @date 2021/8/27 2:32 下午
  1138. */
  1139. public function getDeliveryType()
  1140. {
  1141. return [
  1142. 'express' => [
  1143. 'is_express' => ConfigService::get('delivery_type', 'is_express', 1),
  1144. 'express_name' => ConfigService::get('delivery_type', 'express_name', '快递发货'),
  1145. ],
  1146. 'selffetch' => [
  1147. 'is_selffetch' => ConfigService::get('delivery_type', 'is_selffetch', 0),
  1148. 'selffetch_name' => ConfigService::get('delivery_type', 'selffetch_name', '上门自提'),
  1149. ],
  1150. ];
  1151. }
  1152. /**
  1153. * @notes 删除订单
  1154. * @param $params
  1155. * @return bool
  1156. * @author ljj
  1157. * @date 2021/8/31 2:38 下午
  1158. */
  1159. public function del($params)
  1160. {
  1161. return Order::destroy($params['id']);
  1162. }
  1163. /**
  1164. * @notes 提取砍价商品信息
  1165. * @param $params
  1166. * @return array
  1167. * @author Tab
  1168. * @date 2021/10/9 11:13
  1169. */
  1170. public static function initiateGoods($params)
  1171. {
  1172. $bargainInitiate = BargainInitiate::findOrEmpty($params['initiate_id'])->toArray();
  1173. // 返回二维数组
  1174. return [
  1175. [
  1176. 'item_id' => $bargainInitiate['goods_snapshot']['item_id'],
  1177. 'goods_num' => $bargainInitiate['goods_snapshot']['goods_num'],
  1178. ]
  1179. ];
  1180. }
  1181. /**
  1182. * @notes 获取不同类型订单的规格单价
  1183. * @param $params
  1184. * @author Tab
  1185. * @date 2021/10/9 11:23
  1186. */
  1187. public static function getSellPrice($params, $goodsInfo)
  1188. {
  1189. switch ($params['order_type']) {
  1190. // 普通订单 虚拟订单 抽奖订单
  1191. case OrderEnum::VIRTUAL_ORDER:
  1192. case OrderEnum::NORMAL_ORDER:
  1193. case OrderEnum::DRAW_ORDER:
  1194. return self::getGoodsSellPrice($goodsInfo);
  1195. // 拼团订单
  1196. case OrderEnum::TEAM_ORDER:
  1197. return self::getTeamActivityPrice($params);
  1198. // 秒杀订单
  1199. case OrderEnum::SECKILL_ORDER:
  1200. return self::getSeckillActivityPrice($params);
  1201. // 砍价订单
  1202. case OrderEnum::BARGAIN_ORDER:
  1203. return self::getBargainActivityPrice($params);
  1204. // 预售订单
  1205. case OrderEnum::PRESELL_ORDER:
  1206. return self::getPresellActivityPrice($params);
  1207. }
  1208. }
  1209. /**
  1210. * @notes 获取预售价
  1211. * @param $params
  1212. * @return mixed
  1213. * @author lbzy
  1214. * @datetime 2024-04-26 16:33:58
  1215. */
  1216. static function getPresellActivityPrice($params)
  1217. {
  1218. return PresellGoodsItem::alias('pgi')
  1219. ->where('pgi.item_id', $params['goods'][0]['item_id'])
  1220. ->where('pgi.presell_id', $params['presell_id'])
  1221. ->value('price');
  1222. }
  1223. /**
  1224. * @notes 获取商品售价
  1225. * @param $params
  1226. * @return mixed
  1227. * @author cjhao
  1228. * @date 2022/5/7 18:40
  1229. */
  1230. public static function getGoodsSellPrice($params)
  1231. {
  1232. //会员价允许为零
  1233. if($params['member_price'] >= 0 && $params['member_price'] <= $params['sell_price']){
  1234. return $params['member_price'];
  1235. }
  1236. return $params['sell_price'];
  1237. }
  1238. /**
  1239. * @notes 获取砍价活动价格
  1240. * @param $params
  1241. * @return mixed|void
  1242. * @author Tab
  1243. * @date 2021/10/9 11:30
  1244. */
  1245. public static function getBargainActivityPrice($params)
  1246. {
  1247. $bargainInitiate = BargainInitiate::findOrEmpty($params['initiate_id'])->toArray();
  1248. // 任意金额可购买
  1249. if ($params['buy_condition'] == 'random') {
  1250. return $bargainInitiate['current_price'];
  1251. }
  1252. // 底价购买
  1253. if ($params['buy_condition'] == 'floor') {
  1254. return $bargainInitiate['floor_price'];
  1255. }
  1256. }
  1257. /**
  1258. * @notes 获取秒杀活动价格
  1259. * @param $params
  1260. * @return mixed
  1261. * @author Tab
  1262. * @date 2021/10/9 16:00
  1263. */
  1264. public static function getSeckillActivityPrice($params)
  1265. {
  1266. return SeckillGoodsItem::where([
  1267. 'seckill_id' => $params['seckill_id'],
  1268. 'item_id' => $params['goods'][0]['item_id'],
  1269. ])->value('seckill_price');
  1270. }
  1271. /**
  1272. * @notes 获取拼团活动价格
  1273. * @param $params
  1274. * @author Tab
  1275. * @date 2021/10/9 16:31
  1276. */
  1277. public static function getTeamActivityPrice($params)
  1278. {
  1279. return TeamGoodsItem::where([
  1280. 'team_id' => $params['team_id'],
  1281. 'item_id' => $params['goods'][0]['item_id'],
  1282. ])->value('team_price');
  1283. }
  1284. /**
  1285. * @notes 砍价下单后的操作
  1286. * @param $params
  1287. * @param $order
  1288. * @author Tab
  1289. * @date 2021/10/9 11:52
  1290. */
  1291. public static function bargainAfter($params, $order)
  1292. {
  1293. // 更新砍价记录
  1294. $bargainInitiate = BargainInitiate::findOrEmpty($params['initiate_id']);
  1295. $bargainInitiate->order_id = $order['id'];
  1296. // 标识砍价成功避免任意金额可下单的情况用户继续发起帮助砍价
  1297. $bargainInitiate->status = BargainEnum::STATUS_SUCCESS;
  1298. $bargainInitiate->save();
  1299. }
  1300. /**
  1301. * @notes 拼团下单后的操作
  1302. * @param $params
  1303. * @param $order
  1304. * @author Tab
  1305. * @date 2021/10/9 16:35
  1306. */
  1307. public static function teamAfter($params, $order)
  1308. {
  1309. $time = time();
  1310. $news_found_id = null;
  1311. $teamActivity = TeamActivity::findOrEmpty($params['team_id'])->toArray();
  1312. $teamGoods = TeamGoods::where([
  1313. 'team_id' => $params['team_id'],
  1314. 'goods_id' => $params['goods'][0]['goods_id'],
  1315. ])->findOrEmpty()->toArray();
  1316. $teamGoodsItem = TeamGoodsItem::where([
  1317. 'team_id' => $params['team_id'],
  1318. 'item_id' => $params['goods'][0]['item_id'],
  1319. ])->findOrEmpty()->toArray();
  1320. $goodsSnap = $teamGoods['goods_snap'];
  1321. $itemSnap = $teamGoodsItem['item_snap'];
  1322. $goodsInfo = [
  1323. 'id' => intval($params['goods'][0]['goods_id']),
  1324. 'item_id' => intval($params['goods'][0]['item_id']),
  1325. 'spec_value_ids' => $params['goods'][0]['spec_value_ids'],
  1326. 'name' => $goodsSnap['name'],
  1327. 'image' => $itemSnap['image'] ? FileService::getFileUrl($itemSnap['image']) : FileService::getFileUrl($goodsSnap['image']),
  1328. 'spec_value_str' => $itemSnap['spec_value_str'],
  1329. 'cost_price' => $teamGoodsItem['sell_price'],
  1330. 'sell_price' => $teamGoodsItem['team_price'],
  1331. 'total_price' => round($teamGoodsItem['team_price'] * $params['goods'][0]['goods_num'], 2),
  1332. 'count' => intval($params['goods'][0]['goods_num']),
  1333. 'goods_snap' => $goodsSnap,
  1334. ];
  1335. // 开团
  1336. if (!isset($params['found_id']) || empty($params['found_id'])) {
  1337. $found = TeamFound::create([
  1338. 'found_sn' => generate_sn((new TeamFound()), 'found_sn'),
  1339. 'team_id' => $params['team_id'],
  1340. 'user_id' => $params['user_id'],
  1341. 'order_id' => $order['id'],
  1342. 'people' => $teamActivity['people_num'],
  1343. 'join' => 0,
  1344. 'status' => 0,
  1345. 'goods_snap' => json_encode([
  1346. 'id' => $params['goods'][0]['goods_id'],
  1347. 'name' => $params['goods'][0]['goods_name'],
  1348. 'image' => $params['goods'][0]['image']
  1349. ], JSON_UNESCAPED_UNICODE),
  1350. 'kaituan_time' => $time,
  1351. 'invalid_time' => ($teamActivity['effective_time'] * 60) + time()
  1352. ]);
  1353. $news_found_id = $found['id'];
  1354. }
  1355. // 参团
  1356. TeamJoin::create([
  1357. 'join_sn' => generate_sn((new TeamJoin()), 'join_sn'),
  1358. 'team_id' => $params['team_id'],
  1359. 'found_id' => $news_found_id ?: $params['found_id'],
  1360. 'identity' => $news_found_id ? 1 : 2,
  1361. 'user_id' => $params['user_id'],
  1362. 'order_id' => $order['id'],
  1363. 'status' => 0,
  1364. 'team_snap' => json_encode($teamActivity, JSON_UNESCAPED_UNICODE),
  1365. 'goods_snap' => json_encode($goodsInfo, JSON_UNESCAPED_UNICODE),
  1366. 'invalid_time' => ($teamActivity['effective_time'] * 60) + time(),
  1367. 'create_time' => $time,
  1368. 'update_time' => $time
  1369. ]);
  1370. // 更新数据
  1371. TeamFound::update(['join' => ['inc', 1]], ['id' => $news_found_id ?: $params['found_id']]);
  1372. TeamActivity::update(['partake_number' => ['inc', 1]], ['id' => $params['team_id']]);
  1373. Order::update(['team_found_id' => $news_found_id ?: $params['found_id']], ['id' => $order['id']]);
  1374. }
  1375. /**
  1376. * @notes 秒杀下单后操作
  1377. * @param $params
  1378. * @param $order
  1379. * @author Tab
  1380. * @date 2021/10/13 14:49
  1381. */
  1382. public static function seckillAfter($params, $order)
  1383. {
  1384. Order::update([
  1385. 'id' => $order['id'],
  1386. 'seckill_id' => $params['seckill_id']
  1387. ]);
  1388. }
  1389. /**
  1390. * @notes 预售下单后操作
  1391. * @param $params
  1392. * @param $order
  1393. * @return void
  1394. * @author lbzy
  1395. * @datetime 2024-04-26 16:43:00
  1396. */
  1397. static function presellAfter($params, $order)
  1398. {
  1399. Order::update([
  1400. 'id' => $order['id'],
  1401. 'presell_id' => $params['presell_id']
  1402. ]);
  1403. }
  1404. }