OrderLogic.php 63 KB

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