OrderLogic.php 63 KB

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