OrderLogic.php 62 KB

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