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