OrderLogic.php 62 KB

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