OrderCreate.php 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  1. <?php
  2. namespace addons\shopro\service\order;
  3. use think\Db;
  4. use addons\shopro\service\goods\GoodsService;
  5. use addons\shopro\service\pay\PayOper;
  6. use addons\shopro\exception\ShoproException;
  7. use addons\shopro\facade\Activity as ActivityFacade;
  8. use app\admin\model\shopro\goods\Goods;
  9. use app\admin\model\shopro\order\Order;
  10. use app\admin\model\shopro\order\OrderItem;
  11. use app\admin\model\shopro\order\Address as OrderAddress;
  12. use app\admin\model\shopro\order\Invoice as OrderInvoice;
  13. use app\admin\model\shopro\dispatch\Dispatch;
  14. use app\admin\model\shopro\user\Coupon;
  15. use app\admin\model\shopro\user\Address as UserAddress;
  16. use app\admin\model\shopro\user\Invoice as UserInvoice;
  17. use addons\shopro\service\StockSale;
  18. use app\common\model\Wallet;
  19. class OrderCreate
  20. {
  21. protected $user = null;
  22. /**
  23. * 订单类型
  24. */
  25. protected $order_type = 'goods';
  26. /**
  27. * 是否需要收货地址,自动发货商品不需要选
  28. */
  29. protected $need_address = 1;
  30. /**
  31. * 用户选择的收货地址 id
  32. */
  33. protected $address_id = 0;
  34. /**
  35. * 选择的收货地址信息
  36. */
  37. protected $userAddress = null;
  38. /**
  39. * 货到付款的状态
  40. */
  41. protected $offline_status = 'none';
  42. /**
  43. * 当前参与的活动
  44. */
  45. protected $activity_id = 0;
  46. /**
  47. * 用户选择的开票信息
  48. */
  49. protected $invoice_id = 0;
  50. /**
  51. * 用户选择的优惠券 id
  52. */
  53. protected $coupon_id = 0;
  54. /**
  55. * 用户备注
  56. */
  57. protected $remark = 0;
  58. /**
  59. * 余额抵扣(余额和 微信|支付宝,混合支付时使用了)
  60. */
  61. protected $money = 0;
  62. /**
  63. * 善豆抵扣(余额和 微信|支付宝,混合支付时使用了)
  64. */
  65. protected $bean = 0;
  66. /**
  67. * 发票配置
  68. */
  69. protected $invoiceConfig = [];
  70. /**
  71. * 类型,create:创建订单,calc:计算费用
  72. */
  73. protected $calc_type = 'create';
  74. protected $goodsList = [];
  75. protected $msg = null;
  76. protected $activity = [
  77. 'activity' => null, // 当前订单参与的活动
  78. 'promos' => [], // 当前订单可能参与的促销(每个商品所涉及的促销的集合)
  79. 'promo_infos' => [], // 当前订单实际参与的促销
  80. ];
  81. /**
  82. * 订单相关费用
  83. */
  84. protected $orderData = [
  85. 'goods_original_amount' => '0', // 商品原始总价
  86. 'goods_old_amount' => '0', // 商品不参与活动时的总价
  87. 'goods_amount' => '0', // 商品总价
  88. 'goods_bean_amount' => '0', // 商品善豆可抵扣总价
  89. 'coupon_discount_fee' => '0', // 优惠券优惠金额
  90. 'promo_discount_fee' => 0, // 当前促销优惠总金额 (包含满包邮的邮费)
  91. 'total_discount_fee' => 0, // 当前订单,总优惠金额(优惠券 + 活动优惠)
  92. 'coupon' => null, // 所使用的优惠券
  93. 'coupon_goods_ids' => [],
  94. 'dispatch_amount' => '0', // 运费总价
  95. 'real_dispatch_amount' => '0', // 免邮减免之后的运费总价,不做计算使用
  96. 'score_amount' => 0, // 订单总积分
  97. 'free_shipping_goods_ids' => [], // 满额包邮商品 ids
  98. 'dispatch_infos' => [], // 当前订单商品按照配送方式分组
  99. 'order_amount' => 0, // 订单总费用
  100. 'pay_fee' => 0 // 应支付总金额 (减去优惠之后的)
  101. ];
  102. /**
  103. * 活动(拼团,秒杀) 和 促销(满减,满折),是否可以同时存在
  104. */
  105. protected $activity_promos = false;
  106. public function __construct($params)
  107. {
  108. $this->user = auth_user();
  109. $this->calcParams($params);
  110. }
  111. /**
  112. * 获取请求参数,初始化,并设置默认值
  113. *
  114. * @param array $params
  115. * @return array
  116. */
  117. public function calcParams($params)
  118. {
  119. $this->order_type = $params['order_type'] ?? 'goods';
  120. $this->activity_id = $params['activity_id'] ?? 0;
  121. // $groupon_id = $groupon_id ?? 0; // 拼团的 团 id
  122. // $buy_type = $buy_type ?? 'alone'; // 拼团的 购买方式: alone=单独购买,groupon=开团
  123. // $this->goodsList = $params['goods_list'] ?? [];
  124. $this->goodsList = $params['goods_list'] ? json_decode(htmlspecialchars_decode($params['goods_list']),true) : [];
  125. $this->address_id = $params['address_id'] ?? 0;
  126. $this->invoice_id = $params['invoice_id'] ?? 0;//发票
  127. $this->coupon_id = $params['coupon_id'] ?? 0;//单张优惠券,优惠券只能与活动叠加
  128. $this->remark = $params['remark'] ?? '';
  129. $this->money = (isset($params['money']) && $params['money'] > 0) ? $params['money'] : 0;
  130. $this->bean = (isset($params['bean']) && $params['bean'] > 0) ? $params['bean'] : 0;
  131. // 获取商品信息
  132. $this->goodsListInit();
  133. }
  134. public function goodsListInit()
  135. {
  136. foreach ($this->goodsList as $key => &$buyInfo) {
  137. $goods_sku_price_id = $buyInfo['goods_sku_price_id'];
  138. if ($this->order_type == 'score') {
  139. $goods = $this->getGoodsService()->score()->show()->where('id', $buyInfo['goods_id'])->findOrFail();
  140. } else {
  141. // 暂时保存当前商品要获取的活动的 id
  142. session('goods-activity_id:' . $buyInfo['goods_id'], $this->activity_id); //设置商品活动id的session
  143. $goods = $this->getGoodsService()->activity($this->activity_id)->show()->where('id', $buyInfo['goods_id'])->findOrFail();
  144. if ($this->activity_id) {
  145. if (!$this->activity['activity'] = $goods->activity) {
  146. $this->exception('活动不存在', true);
  147. }
  148. if ($this->activity['activity']['status'] != 'ing') {
  149. $this->exception('活动' . $this->activity['activity']['status_text']);
  150. }
  151. }
  152. if ($this->isCalcPromos()&& isset($goods['promos']) && $goods['promos']) {
  153. $this->activity['promos'] = array_merge($this->activity['promos'], $goods['promos']);
  154. }
  155. }
  156. $skuPrices = $goods['new_sku_prices'];
  157. foreach ($skuPrices as $key => $skuPrice) {
  158. if ($skuPrice['id'] == $goods_sku_price_id && $skuPrice['status'] == 'up') {
  159. $buyInfo['current_sku_price'] = $skuPrice; // 当前购买规格
  160. break;
  161. }
  162. }
  163. if (!isset($buyInfo['current_sku_price']) || !$buyInfo['current_sku_price']) {
  164. $this->exception('商品规格不存在', true);
  165. }
  166. $buyInfo['dispatch_type'] = $goods['dispatch_type'] ?: 'express';
  167. $buyInfo['dispatch_type_text'] = $goods['dispatch_type_text'] ?? '';
  168. $buyInfo['goods'] = $goods;
  169. }
  170. }
  171. /**
  172. * 下单前检测,商品状态,秒杀,拼团活动状态,必要的选择项(比如下单收货地址),收货地址等
  173. *
  174. * @param array $params,请求参数
  175. * @return array
  176. */
  177. public function calcCheck()
  178. {
  179. $offline_num = 0; // 货到付款商品数量
  180. foreach ($this->goodsList as $key => &$buyInfo) {
  181. $goods = $buyInfo['goods'];
  182. $goods_sku_price_id = $buyInfo['goods_sku_price_id'];
  183. $goods_num = $buyInfo['goods_num'] ?? 1;
  184. // 最少购买一件
  185. $buyInfo['goods_num'] = intval($goods_num) < 1 ? 1 : intval($goods_num);
  186. if ($buyInfo['current_sku_price']['stock'] < $buyInfo['goods_num']) {
  187. $this->exception('商品 ' . $goods['title'] . ' 库存不足');
  188. }
  189. // 校验活动规则
  190. if ($this->activity['activity']) {
  191. try {
  192. $buyInfo = ActivityFacade::buyCheck($buyInfo, $this->activity['activity']);
  193. } catch (ShoproException $e) {
  194. $this->exception($e->getMessage());
  195. }
  196. }
  197. if ($buyInfo['goods']['is_offline']) {
  198. $offline_num ++;
  199. }
  200. $buyInfo['activity_type'] = $this->activity['activity']['type'] ?? null;
  201. }
  202. if (!count($this->goodsList)) {
  203. $this->exception('请选择要购买的商品');
  204. }
  205. if ($this->activity_id && count($this->goodsList) > 1) {
  206. $this->exception($this->activity['activity']['type_text'] . '必须单独购买');
  207. }
  208. if ($this->order_type == 'score' && count($this->goodsList) > 1) {
  209. $this->exception('积分商品必须单独购买');
  210. }
  211. // 判断是否支持货到付款
  212. if ($offline_num < count($this->goodsList)) {
  213. $this->offline_status = $offline_num == 0 ? 'none' : 'disabled';
  214. } else {
  215. $this->offline_status = 'enable';
  216. }
  217. // 判断是否有需要收货地址的商品,新版每个商品需要选择配送方式
  218. $dispatchTypes = array_column($this->goodsList, 'dispatch_type');
  219. // 配送方式为 快递 必须填写收货地址
  220. if (in_array('express', $dispatchTypes)) {
  221. // 用户收货地址
  222. if ($this->address_id) {
  223. $this->userAddress = UserAddress::where("user_id", $this->user->id)->find($this->address_id);
  224. }
  225. if (is_null($this->userAddress) && $this->calc_type == 'create') {
  226. $this->exception("请选择正确的收货地址");
  227. }
  228. } else {
  229. // 不需要收货地址
  230. $this->need_address = 0;
  231. }
  232. }
  233. /**
  234. * 计算订单各种费用
  235. *
  236. * @return array
  237. */
  238. public function calcAmount()
  239. {
  240. //dump($this->goodsList);
  241. // 计算商品金额
  242. foreach ($this->goodsList as $key => &$buyInfo) {
  243. $goods = $buyInfo['goods'];
  244. //dd(json_decode(json_encode($buyInfo),true));
  245. // 当前商品原始总价
  246. $current_goods_original_amount = bcmul($goods->original_price, $buyInfo['goods_num'], 2);
  247. $this->orderData['goods_original_amount'] = bcadd($this->orderData['goods_original_amount'], $current_goods_original_amount, 2);
  248. // 当前商品现在总价
  249. $current_goods_amount = bcmul($buyInfo['current_sku_price']->price, $buyInfo['goods_num'], 2);
  250. $this->orderData['goods_amount'] = bcadd($this->orderData['goods_amount'], $current_goods_amount, 2);
  251. //当前商品的善豆抵扣价,商品没有就拿分类
  252. $bean_rate = floatval($goods->bean_rate) > 0 ? $goods->bean_rate : 0;
  253. if($bean_rate == 0){
  254. $bean_rate = Db::name('shopro_category')->where('id',$goods->category_ids)->value('bean_rate');
  255. $bean_rate = floatval($bean_rate) > 0 ? $bean_rate : 0;
  256. }
  257. $current_goods_bean_amount = bcdiv(bcmul($current_goods_amount,$bean_rate,2),100,2);
  258. $this->orderData['goods_bean_amount'] = bcadd($this->orderData['goods_bean_amount'],$current_goods_bean_amount,2);
  259. // 当有活动时,计算作为普通商品时的商品总金额
  260. $current_goods_old_amount = $current_goods_amount;
  261. if ($this->activity['activity']) {
  262. $current_goods_old_amount = bcmul($buyInfo['current_sku_price']->old_price, $buyInfo['goods_num'], 2);
  263. }
  264. $this->orderData['goods_old_amount'] = bcadd($this->orderData['goods_old_amount'], $current_goods_old_amount, 2);
  265. // 当前商品所需积分
  266. $current_score_amount = 0;
  267. if ($this->order_type == 'score') { // 积分商城规格
  268. $current_score_amount = $buyInfo['current_sku_price']->score * $buyInfo['goods_num'];
  269. $this->orderData['score_amount'] = $this->orderData['score_amount'] + $current_score_amount;
  270. }
  271. // 当前商品总重量
  272. $current_weight = bcmul($buyInfo['current_sku_price']->weight, $buyInfo['goods_num'], 2);
  273. // 将计算好的属性记录下来,插入订单 item 表使用
  274. $buyInfo['goods_original_amount'] = $current_goods_original_amount; // 当前商品原始总金额(原价 * 数量)
  275. $buyInfo['goods_amount'] = $current_goods_amount; // 当前商品总金额(价格 * 数量)
  276. $buyInfo['goods_bean_amount'] = $current_goods_bean_amount; // 当前商品可抵扣最高总金额(当前商品总金额 * 比例)
  277. $buyInfo['score_amount'] = $current_score_amount; // 商品所需积分(积分商城)
  278. $buyInfo['weight'] = $current_weight; // 当前商品总重量
  279. $buyInfo['original_dispatch_amount'] = 0; // 当前商品运费(未判断活动的,并且也未合并相同运费模板商品的原始运费)
  280. $buyInfo['dispatch_amount'] = 0; // 当前商品运费,按照运费模板合并相同商品的真实运费)
  281. $buyInfo['dispatch_id'] = 0; // 商品运费模板,如果有活动,并且活动包邮,这里是 0
  282. $buyInfo['promo_types'] = []; // 商品参与的营销类型
  283. $buyInfo['dispatch_discount_fee'] = 0; // 初始化每个商品运费优惠金额
  284. $buyInfo['promo_discount_fee'] = 0; // 初始化每个商品的促销优惠金额(这里不包含运费优惠,实际 order_item 上是包含的)
  285. $buyInfo['coupon_discount_fee'] = 0; // 初始化每个商品的优惠券优惠金额
  286. // 商品的配送模板 id
  287. $current_dispatch_id = $goods['dispatch_id'];
  288. // 获取快递配送数据
  289. if ($buyInfo['dispatch_type'] == 'express'
  290. && (!$this->activity['activity'] // 没有活动
  291. || (
  292. $this->activity['activity'] // 有活动,并且(没有是否包邮字段,或者是不包邮)
  293. && (!isset($this->activity['activity']['rules']['is_free_shipping']) || !$this->activity['activity']['rules']['is_free_shipping'])
  294. )
  295. )
  296. ) {
  297. if ($this->userAddress) {
  298. if (!isset($this->orderData['dispatch_infos'][$goods['dispatch_id']]['finalExpress'])) {
  299. $finalExpress = $this->getDispatchExpress($buyInfo['dispatch_type'], $goods['dispatch_id']);
  300. } else {
  301. $finalExpress = $this->orderData['dispatch_infos'][$goods['dispatch_id']]['finalExpress'];
  302. }
  303. $current_original_dispatch_amount = $this->calcDispatch($finalExpress, [
  304. 'goods_num' => $buyInfo['goods_num'],
  305. 'weight' => $current_weight
  306. ]);
  307. $this->orderData['dispatch_infos'][$goods['dispatch_id']]['finalExpress'] = $finalExpress;
  308. $this->orderData['dispatch_infos'][$goods['dispatch_id']]['buyInfos'][] = $buyInfo;
  309. }
  310. $buyInfo['original_dispatch_amount'] = $current_original_dispatch_amount ?? 0; // 没选收货地址时默认为 0
  311. $buyInfo['dispatch_id'] = $current_dispatch_id;
  312. } else if ($buyInfo['dispatch_type'] == 'autosend') {
  313. $this->getDispatchAutosend($buyInfo['dispatch_type'], $goods['dispatch_id']);
  314. $buyInfo['dispatch_id'] = $current_dispatch_id;
  315. }
  316. }
  317. // 计算应付总运费,商品中同一种运费模板聚合进行计算运费,然后再按照运费模板规则,将运费加权平分到每个商品
  318. foreach ($this->orderData['dispatch_infos'] as $key => &$info) {
  319. $finalExpress = $info['finalExpress'];
  320. $buy_num = 0;
  321. $weight = 0;
  322. foreach ($info['buyInfos'] as $k => $infoInfo) {
  323. $buy_num += $infoInfo['goods_num'];
  324. $weight = bcadd($weight, $infoInfo['weight'], 2);
  325. }
  326. // 聚合原始运费
  327. $current_dispatch_amount = $this->calcDispatch($finalExpress, [
  328. 'goods_num' => $buy_num,
  329. 'weight' => $weight
  330. ]);
  331. $info['current_dispatch_amount'] = $current_dispatch_amount; // 记录当前运费模板下商品的运费
  332. // 将运费加权平分到当前运费模板中的每个商品
  333. if ($current_dispatch_amount) {
  334. $this->equalDispatch($current_dispatch_amount, $info['buyInfos'], [
  335. 'goods_num' => $buy_num,
  336. 'weight' => $weight,
  337. 'final_express' => $finalExpress
  338. ]);
  339. }
  340. $this->orderData['dispatch_amount'] = bcadd($this->orderData['dispatch_amount'], $current_dispatch_amount, 2);
  341. }
  342. }
  343. /**
  344. * 计算商品的优惠促销
  345. *
  346. * @return void
  347. */
  348. public function calcDiscount() {
  349. // 过滤重复促销
  350. $promos = [];
  351. foreach ($this->activity['promos'] as $promo) {
  352. if (!isset($promos[$promo['id']])) {
  353. $promos[$promo['id']] = $promo;
  354. }
  355. }
  356. // 将购买的商品,按照促销分类
  357. foreach ($this->goodsList as $buyInfo) {
  358. $goods = $buyInfo['goods'];
  359. unset($buyInfo['goods']);
  360. if (isset($goods['promos']) && $goods['promos']) {
  361. foreach ($goods['promos'] as $promo) {
  362. $promos[$promo['id']]['goods'][] = $buyInfo;
  363. }
  364. }
  365. }
  366. // 计算各个促销是否满足
  367. foreach ($promos as $key => $promo) {
  368. if (!isset($promo['goods'])) {
  369. // 促销没有商品,直接 next
  370. continue;
  371. }
  372. $promoInfo = ActivityFacade::getPromoInfo($promo, [
  373. 'userAddress' => $this->userAddress
  374. ]);
  375. if ($promoInfo) {
  376. if (in_array($promo['type'], ['full_reduce', 'full_discount'])) {
  377. // 这里目前只计算,满减,满折
  378. $this->orderData['promo_discount_fee'] = bcadd($this->orderData['promo_discount_fee'], $promoInfo['promo_discount_money'], 2);
  379. // 将当前优惠平分到参与该促销的商品上
  380. foreach ($this->goodsList as &$buyInfo) {
  381. if (in_array($buyInfo['goods_id'], $promoInfo['goods_ids'])) {
  382. $scale = bcdiv($buyInfo['goods_amount'], $promoInfo['promo_goods_amount'], 6);
  383. // 当前商品,当前促销分配的优惠金额
  384. $current_promo_discount_fee = round(bcmul($promoInfo['promo_discount_money'], $scale, 3), 2);
  385. $buyInfo['promo_discount_fee'] = bcadd($buyInfo['promo_discount_fee'], $current_promo_discount_fee, 2); // 当前商品参与所有活动累计分配的优惠金额
  386. }
  387. }
  388. }
  389. if ($promo['type'] == 'free_shipping') {
  390. // 满包邮涉及到的商品
  391. $this->orderData['free_shipping_goods_ids'] = array_merge($this->orderData['free_shipping_goods_ids'], $promoInfo['goods_ids']);
  392. }
  393. $this->activity['promo_infos'][] = $promoInfo;
  394. }
  395. }
  396. // 计算实际应付总运费
  397. if ($this->orderData['free_shipping_goods_ids']) {
  398. // first:简单计算方式,谁包邮,就把 buyinfo 上的 dispatch_amount 计算为运费优惠
  399. $promo_dispatch_discount_fee = 0;
  400. foreach ($this->goodsList as $key => &$buyInfo) {
  401. if (in_array($buyInfo['goods_id'], $this->orderData['free_shipping_goods_ids'])) {
  402. // 商品运费优惠金额就是 当前商品的运费
  403. $buyInfo['dispatch_discount_fee'] = $buyInfo['dispatch_amount'];
  404. $promo_dispatch_discount_fee = bcadd($promo_dispatch_discount_fee, $buyInfo['dispatch_amount'], 2);
  405. }
  406. }
  407. // 真实运费 = 总运费,减去总包邮优惠
  408. $this->orderData['real_dispatch_amount'] = bcsub($this->orderData['dispatch_amount'], $promo_dispatch_discount_fee, 2);
  409. $this->orderData['promo_discount_fee'] = bcadd($this->orderData['promo_discount_fee'], $promo_dispatch_discount_fee, 2);
  410. // second:复杂计算方式,一个运费模板中多个商品只有一个包邮时,包邮优惠重新计算,而不是直接使用 dispatch_amount
  411. // foreach ($this->orderData['dispatch_infos'] as $key => $info) {
  412. // $finalExpress = $info['finalExpress'];
  413. // $total_buy_num = 0; // 总购买数量
  414. // $total_weight = 0; // 总购买重量
  415. // $buy_num = 0; // 不包邮购买数量
  416. // $weight = 0; // 不包邮购买重量
  417. // $currentGoodsIds = array_column($info['buyInfos'], 'goods_id');
  418. // $currentFreeGoodsIds = array_intersect($this->orderData['free_shipping_goods_ids'], $currentGoodsIds); // 当前配送模板中的包邮商品
  419. // $noFreeGoodsIds = array_diff($currentGoodsIds, $currentFreeGoodsIds); // 当前配送模板中的不包邮商品
  420. // foreach ($info['buyInfos'] as $k => $dispatchBuyInfo) {
  421. // $total_buy_num += $dispatchBuyInfo['goods_num'];
  422. // $total_weight = bcadd($total_weight, $dispatchBuyInfo['weight'], 2);
  423. // if (!in_array($dispatchBuyInfo['goods_id'], $this->orderData['free_shipping_goods_ids'])) {
  424. // // 不是包邮商品 累加
  425. // $buy_num += $dispatchBuyInfo['goods_num'];
  426. // $weight = bcadd($weight, $dispatchBuyInfo['weight'], 2);
  427. // }
  428. // }
  429. // if ($currentFreeGoodsIds && $noFreeGoodsIds) {
  430. // // 有免邮商品,也有非免邮商品,重新计算除包邮优惠后的运费
  431. // $current_dispatch_amount = $this->calcDispatch($finalExpress, [
  432. // 'goods_num' => $buy_num,
  433. // 'weight' => $weight
  434. // ]);
  435. // // 模板总运费优惠金额
  436. // $current_discount_dispatch_amount = bcsub($info['current_dispatch_amount'], $current_dispatch_amount, 2);
  437. // if ($current_discount_dispatch_amount > 0) {
  438. // // 将优惠金额按照运费模板平均分配
  439. // $this->equalDispatchDiscount($currentFreeGoodsIds, $current_discount_dispatch_amount, [
  440. // 'goods_num' => bcsub($total_buy_num, $buy_num), // 包邮购买数量
  441. // 'weight' => bcsub($total_weight, $weight, 2), // 包邮购买重量
  442. // 'final_express' => $finalExpress
  443. // ]);
  444. // // 将新的运费加权平均到每个 item 上
  445. // $this->equalDispatch($current_dispatch_amount, $noFreeGoodsIds, [
  446. // 'goods_num' => $buy_num,
  447. // 'weight' => $weight,
  448. // 'final_express' => $finalExpress
  449. // ]);
  450. // }
  451. // } elseif ($currentFreeGoodsIds) {
  452. // // 全部包邮了,将邮费优惠按件数或者重量分配了
  453. // $current_discount_dispatch_amount = $info['current_dispatch_amount'];
  454. // if ($current_discount_dispatch_amount > 0) {
  455. // // 每个商品运费优惠,就是 dispatch_amount
  456. // $this->allDispatchDiscount($currentFreeGoodsIds);
  457. // }
  458. // $current_dispatch_amount = 0;
  459. // } else {
  460. // // 全部不包邮,每个商品的 dispatch_discount_fee 为初始值,不需要处理每个商品分配到的运费优惠
  461. // $current_dispatch_amount = $info['current_dispatch_amount'];
  462. // }
  463. // $this->orderData['real_dispatch_amount'] = bcadd($this->orderData['real_dispatch_amount'], $current_dispatch_amount, 2);
  464. // }
  465. // // 包邮活动优惠的总费用
  466. // $promo_dispatch_discount_fee = bcsub($this->orderData['dispatch_amount'], $this->orderData['real_dispatch_amount'], 2);
  467. // $this->orderData['promo_discount_fee'] = bcadd($this->orderData['promo_discount_fee'], $promo_dispatch_discount_fee, 2);
  468. // second:复杂计算方式结束
  469. }
  470. // 将每个商品对应的 activity_type 放入 goods_list 中的 promo_types 中,重新计算真实的包邮优惠
  471. foreach ($this->activity['promo_infos'] as &$info) {
  472. // 寻找商品id 等于 $goods_id 的所有商品,存在同一个商品,购买多个规格的情况
  473. foreach ($this->goodsList as &$buyInfo) {
  474. if (in_array($buyInfo['goods_id'], $info['goods_ids'])) {
  475. if (!in_array($info['activity_type'], $buyInfo['promo_types'])) {
  476. $buyInfo['promo_types'][] = $info['activity_type'];
  477. }
  478. if ($info['activity_type'] == 'free_shipping') {
  479. // 重新计算运费真实优惠
  480. $info['promo_discount_money'] = bcadd($info['promo_discount_money'], $buyInfo['dispatch_discount_fee'], 2);
  481. }
  482. }
  483. }
  484. }
  485. }
  486. /**
  487. * 计算优惠券的优惠
  488. *
  489. * @return void
  490. */
  491. public function calcCoupon()
  492. {
  493. // 获取优惠券
  494. $this->orderData['coupon'] = $this->getCoupon($this->coupon_id);
  495. if ($this->orderData['coupon']) {
  496. $this->orderData['coupon_discount_fee'] = $this->orderData['coupon']['coupon_money']; // 获取优惠券时计算的金额
  497. $this->orderData['coupon_goods_ids'] = $this->orderData['coupon']['goods_ids']; // 获取优惠券时参与的商品
  498. // 将当前优惠券优惠金额平分到使用优惠券的商品上
  499. foreach ($this->goodsList as &$buyInfo) {
  500. if (in_array($buyInfo['goods_id'], $this->orderData['coupon_goods_ids'])) {
  501. $scale = bcdiv($buyInfo['goods_amount'], $this->orderData['coupon']['goods_amount'], 6);
  502. // 当前商品,当前活动分配的优惠金额
  503. $current_coupon_discount_fee = round(bcmul($this->orderData['coupon_discount_fee'], $scale, 3), 2);
  504. $buyInfo['coupon_discount_fee'] = bcadd($buyInfo['coupon_discount_fee'], $current_coupon_discount_fee, 2); // 当前商品可用优惠券的累计优惠金额
  505. }
  506. }
  507. } else {
  508. $this->exception('优惠券不可用');
  509. }
  510. }
  511. /**
  512. * 获取用户的优惠券列表,可用和不可用的做区分
  513. *
  514. * @return array
  515. */
  516. public function getCoupons($calc_type = 'coupons')
  517. {
  518. $this->calc_type = $calc_type;
  519. // 检查是否可下单
  520. $this->calcCheck();
  521. // 计算订单各种费用
  522. $this->calcAmount();
  523. // 用户可用优惠券列表
  524. // 这里使用的with,没法用 coupon表的减免金额做排序,可能需要重新写
  525. $coupons = Coupon::with('coupon')->where('user_id', $this->user->id)->canUse()->select();
  526. $cannot_use = [];
  527. $can_use = [];
  528. foreach ($coupons as $key => $coupon) {
  529. $result = $this->checkCoupon($coupon);
  530. if (isset($result['can_use']) && $result['can_use']) {
  531. $can_use[] = $coupon;
  532. } else {
  533. $coupon->cannot_use_msg = $result['cannot_use_msg'];
  534. $cannot_use[] = $coupon;
  535. }
  536. }
  537. return compact('can_use', 'cannot_use');
  538. }
  539. public function getCoupon($coupon_id)
  540. {
  541. // 选用的优惠券
  542. $coupon = Coupon::with('coupon')->where('user_id', $this->user->id)->canUse()->find($coupon_id);
  543. if ($coupon) {
  544. $result = $this->checkCoupon($coupon);
  545. return (isset($result['can_use']) && $result['can_use']) ? $coupon : null;
  546. }
  547. return null;
  548. }
  549. /**
  550. * 检测用户优惠券是否可用
  551. *
  552. * @param array|object $coupon
  553. * @param string $type
  554. * @return array|object
  555. */
  556. private function checkCoupon($coupon)
  557. {
  558. $can_use = true;
  559. $cannot_use_msg = '';
  560. // (积分或者活动 并且 优惠券不支持优惠叠加)
  561. if (($this->order_type == 'score' || $this->activity_id) && !$coupon->is_double_discount) {
  562. $can_use = false;
  563. $cannot_use_msg = '优惠券不可与活动叠加';
  564. return compact('can_use', 'cannot_use_msg');
  565. }
  566. $goods_amount = 0;
  567. $goodsIds = []; // 符合优惠券规则的 商品 ids
  568. if ($coupon->use_scope == 'all_use') {
  569. // 计算商品总金额
  570. foreach ($this->goodsList as $buyInfo) {
  571. $goods_amount = bcadd($goods_amount, $buyInfo['goods_amount'], 2);
  572. $goodsIds[] = $buyInfo['goods_id'];
  573. }
  574. } elseif ($coupon->use_scope == 'goods') {
  575. // 计算指定商品的总金额是否满足
  576. foreach ($this->goodsList as $buyInfo) {
  577. if (in_array($buyInfo['goods_id'], explode(',', $coupon->items))) {
  578. $goods_amount = bcadd($goods_amount, $buyInfo['goods_amount'], 2);
  579. $goodsIds[] = $buyInfo['goods_id'];
  580. }
  581. }
  582. } elseif ($coupon->use_scope == 'disabled_goods') {
  583. // 计算非指定的商品的总金额是否满足
  584. foreach ($this->goodsList as $buyInfo) {
  585. if (!in_array($buyInfo['goods_id'], explode(',', $coupon->items))) {
  586. $goods_amount = bcadd($goods_amount, $buyInfo['goods_amount'], 2);
  587. $goodsIds[] = $buyInfo['goods_id'];
  588. }
  589. }
  590. } elseif ($coupon->use_scope == 'category') {
  591. // 计算指定分类的商品的总金额
  592. foreach ($this->goodsList as $buyInfo) {
  593. // 取分类交集
  594. if (array_intersect(explode(',', $buyInfo['goods']['category_ids']), explode(',', $coupon->items))) {
  595. $goods_amount = bcadd($goods_amount, $buyInfo['goods_amount'], 2);
  596. $goodsIds[] = $buyInfo['goods_id'];
  597. }
  598. }
  599. }
  600. if ($coupon->enough <= $goods_amount) {
  601. $coupon['coupon_money'] = $coupon->amount;
  602. $coupon['goods_amount'] = $goods_amount; // 参与优惠券的商品的总金额
  603. $coupon['goods_ids'] = $goodsIds;
  604. if ($coupon->type == 'discount') {
  605. $scale = bcmul($coupon->amount, 0.1, 3);
  606. $scale = $scale > 1 ? 1 : ($scale < 0 ? 0 : $scale);
  607. $coupon_money = bcmul(bcsub(1, $scale, 3), $goods_amount, 2);
  608. // 优惠金额最大为 coupon->max_amount;
  609. $coupon['coupon_money'] = $coupon->max_amount && $coupon_money > $coupon->max_amount ? $coupon->max_amount : $coupon_money;
  610. }
  611. $coupons[] = $coupon;
  612. } else {
  613. $can_use = false;
  614. if ($goods_amount > 0) {
  615. $cannot_use_msg = '商品金额不满足优惠券门槛';
  616. } else {
  617. $cannot_use_msg = '优惠券不支持该商品';
  618. }
  619. }
  620. return compact('can_use', 'cannot_use_msg');
  621. }
  622. /**
  623. * 获取匹配的配送规则
  624. *
  625. * @param string $dispatch_type
  626. * @param integer $dispatch_id
  627. * @return array
  628. */
  629. public function getDispatchExpress($dispatch_type, $dispatch_id)
  630. {
  631. // 物流快递
  632. $dispatch = Dispatch::with('express')->show()->where('type', $dispatch_type)->where('id', $dispatch_id)->find();
  633. if (!$dispatch) {
  634. $this->exception('配送方式不存在', true);
  635. }
  636. $finalExpress = null;
  637. foreach ($dispatch->express as $key => $express) {
  638. if (strpos($express->district_ids, strval($this->userAddress->district_id)) !== false) {
  639. $finalExpress = $express;
  640. break;
  641. }
  642. if (strpos($express->city_ids, strval($this->userAddress->city_id)) !== false) {
  643. $finalExpress = $express;
  644. break;
  645. }
  646. if (strpos($express->province_ids, strval($this->userAddress->province_id)) !== false) {
  647. $finalExpress = $express;
  648. break;
  649. }
  650. }
  651. if (empty($finalExpress)) {
  652. $this->exception('当前地区不在配送范围');
  653. }
  654. return $finalExpress;
  655. }
  656. /**
  657. * 获取匹配的配送规则
  658. *
  659. * @param string $dispatch_type
  660. * @param integer $dispatch_id
  661. * @return array
  662. */
  663. public function getDispatchAutosend($dispatch_type, $dispatch_id)
  664. {
  665. // 物流快递
  666. $dispatch = Dispatch::with(['autosend'])->show()->where('type', $dispatch_type)->where('id', $dispatch_id)->find();
  667. if (!$dispatch) {
  668. $this->exception('配送方式不存在', true);
  669. }
  670. return $dispatch;
  671. }
  672. public function calcDispatch($finalExpress, $data)
  673. {
  674. if (empty($finalExpress)) {
  675. // 没有找到 finalExpress,比如商品不在配送范围,直接返回 0
  676. return 0;
  677. }
  678. // 初始费用
  679. $dispatch_amount = $finalExpress->first_price;
  680. if ($finalExpress['type'] == 'number') {
  681. // 按件计算
  682. if ($finalExpress->additional_num && $finalExpress->additional_price) {
  683. // 首件之后剩余件数
  684. $surplus_num = $data['goods_num'] - $finalExpress->first_num;
  685. // 多出的计量
  686. $additional_mul = ceil(($surplus_num / $finalExpress->additional_num));
  687. if ($additional_mul > 0) {
  688. $additional_dispatch_amount = bcmul($additional_mul, $finalExpress->additional_price, 2);
  689. $dispatch_amount = bcadd($dispatch_amount, $additional_dispatch_amount, 2);
  690. }
  691. }
  692. } else {
  693. // 按重量计算
  694. if ($finalExpress->additional_num && $finalExpress->additional_price) {
  695. // 首重之后剩余重量
  696. $surplus_num = $data['weight'] - $finalExpress->first_num;
  697. // 多出的计量
  698. $additional_mul = ceil(($surplus_num / $finalExpress->additional_num));
  699. if ($additional_mul > 0) {
  700. $additional_dispatch_amount = bcmul($additional_mul, $finalExpress->additional_price, 2);
  701. $dispatch_amount = bcadd($dispatch_amount, $additional_dispatch_amount, 2);
  702. }
  703. }
  704. }
  705. return $dispatch_amount;
  706. }
  707. /**
  708. * 加权平均每个包邮商品,应该分配的优惠(一个运费模板中的商品,部分包邮,部分不包邮,要重新计算)
  709. *
  710. * @param [type] $currentFreeGoodsIds
  711. * @param [type] $current_dispatch_amount
  712. * @param array $data
  713. * @return void
  714. */
  715. public function equalDispatchDiscount($currentFreeGoodsIds, $dispatch_discount_amount, $data = [])
  716. {
  717. $goods_num = $data['goods_num'];
  718. $weight = $data['weight'];
  719. $finalExpress = $data['final_express']; // 这里肯定有,否则走不到这个方法
  720. foreach ($this->goodsList as $key => &$buyInfo) {
  721. if (in_array($buyInfo['goods_id'], $currentFreeGoodsIds)) {
  722. $scale = 0; // 重量或者数量计算比例
  723. if ($finalExpress['type'] == 'number') {
  724. // 按件
  725. if (floatval($goods_num)) { // 字符串 0.00 是 true, 这里转下类型在判断
  726. $scale = bcdiv($buyInfo['goods_num'], $goods_num, 6);
  727. }
  728. $current_dispatch_discount_fee = round(bcmul($dispatch_discount_amount, $scale, 3), 2);
  729. } else {
  730. // 按重量
  731. if (floatval($weight)) {
  732. $current_weight = bcmul($buyInfo['current_sku_price']->weight, $buyInfo['goods_num'], 2);
  733. $scale = bcdiv($current_weight, $weight, 6);
  734. }
  735. $current_dispatch_discount_fee = round(bcmul($dispatch_discount_amount, $scale, 3), 2);
  736. }
  737. // 每个商品分配到的包邮优惠金额, 和订单 item 上的dispatch_fee 不一样,因为 剩余运费又重新计算了,这个优惠没有 dispatch_fee 大
  738. $buyInfo['dispatch_discount_fee'] = $current_dispatch_discount_fee;
  739. }
  740. }
  741. }
  742. /**
  743. * 同一运费模板额所有商品都包邮了,不需要重新计算,优惠金额就是 dispatch_amount
  744. *
  745. * @param [type] $currentFreeGoodsIds
  746. * @param [type] $current_dispatch_amount
  747. * @param array $data
  748. * @return void
  749. */
  750. public function allDispatchDiscount($currentFreeGoodsIds)
  751. {
  752. foreach ($this->goodsList as $key => &$buyInfo) {
  753. if (in_array($buyInfo['goods_id'], $currentFreeGoodsIds)) {
  754. // 每个商品分配到的包邮优惠金额, 和订单 item 上的dispatch_fee 不一样,因为 剩余运费又重新计算了,这个优惠没有 dispatch_fee 大
  755. $buyInfo['dispatch_discount_fee'] = $buyInfo['dispatch_amount'];
  756. }
  757. }
  758. }
  759. /**
  760. * 加权平分同一运费模板下商品实际应付运费
  761. *
  762. * @param float $dispatch_amount
  763. * @param array $currentBuyInfos
  764. * @param array $data
  765. * @return void
  766. */
  767. private function equalDispatch($dispatch_amount, $currentBuyInfos, $data)
  768. {
  769. $goods_num = $data['goods_num'];
  770. $weight = $data['weight'];
  771. $finalExpress = $data['final_express'];
  772. // 当前运费模板中的商品 Ids
  773. $goodsIds = array_column($currentBuyInfos, 'goods_id');
  774. foreach ($this->goodsList as $key => &$buyInfo) {
  775. if (in_array($buyInfo['goods_id'], $goodsIds)) {
  776. $scale = 0; // 重量或者数量计算比例
  777. if ($finalExpress['type'] == 'number') {
  778. // 按件
  779. if ($goods_num) { // 字符串 0.00 是 true, 这里转下类型在判断
  780. $scale = bcdiv($buyInfo['goods_num'], $goods_num, 6);
  781. }
  782. $current_dispatch_amount = round(bcmul($dispatch_amount, $scale, 3), 2);
  783. } else {
  784. // 按重量
  785. if (floatval($weight)) {
  786. $scale = bcdiv($buyInfo['weight'], $weight, 6);
  787. }
  788. $current_dispatch_amount = round(bcmul($dispatch_amount, $scale, 3), 2);
  789. }
  790. $buyInfo['dispatch_amount'] = $current_dispatch_amount; // 每个商品分配到的实际应支付运费
  791. }
  792. }
  793. }
  794. public function calcReturn() {
  795. $invoiceConfig = sheep_config('shop.order.invoice');
  796. $this->invoiceConfig = [
  797. 'status' => $invoiceConfig['status'] && $this->orderData['pay_fee'] ? 1 : 0, // 可开具发票状态,
  798. 'amount_type' => $invoiceConfig['amount_type'] ?? 'pay_fee',
  799. 'user_invoice' => null
  800. ];
  801. if ($this->invoiceConfig['status'] && $this->invoice_id) {
  802. // 获取用户发票信息
  803. $this->invoiceConfig['user_invoice'] = UserInvoice::where('user_id', $this->user->id)->find($this->invoice_id);
  804. if (!$this->invoiceConfig['user_invoice']) {
  805. $this->exception('请选择正确的发票信息');
  806. }
  807. }
  808. //善豆抵扣不能高于善豆余额
  809. $user_bean = (new Wallet())->getWalletBak($this->user->id,'bean');
  810. $this->orderData['goods_bean_amount'] = $this->orderData['goods_bean_amount'] > $user_bean ? $user_bean : $this->orderData['goods_bean_amount'];
  811. //$temp_remain_pay_fee = bcsub($this->orderData['pay_fee'], $this->money, 2);
  812. $this->bean = $this->bean > $this->orderData['goods_bean_amount'] ? $this->orderData['goods_bean_amount'] : $this->bean;
  813. $temp_remain_pay_fee = bcsub($this->orderData['pay_fee'], $this->bean, 2);
  814. $result = [
  815. 'goods_original_amount' => $this->orderData['goods_original_amount'],
  816. 'goods_old_amount' => $this->orderData['goods_old_amount'],
  817. 'goods_amount' => $this->orderData['goods_amount'],
  818. 'goods_bean_amount' => $this->orderData['goods_bean_amount'], //最大可抵扣善豆
  819. 'user_bean_amount' => $user_bean, //用户善豆余额
  820. 'min_bean_amount' => config('site.shopro_min_bean_amount'), //最小可使用善豆数量
  821. 'dispatch_amount' => $this->orderData['dispatch_amount'],
  822. 'real_dispatch_amount' => $this->orderData['real_dispatch_amount'],
  823. 'order_amount' => $this->orderData['order_amount'],
  824. 'pay_fee' => $this->orderData['pay_fee'],
  825. 'temp_remain_pay_fee' => $temp_remain_pay_fee >= 0 ? $temp_remain_pay_fee : 0, // 临时剩余应支付金额,订单确认页面显示
  826. 'total_discount_fee' => $this->orderData['total_discount_fee'],
  827. 'coupon_discount_fee' => $this->orderData['coupon_discount_fee'],
  828. 'promo_discount_fee' => $this->orderData['promo_discount_fee'], // 包含包邮的运费优惠
  829. 'money' => $this->money, // 余额支付部分
  830. 'bean' => $this->bean, // 善豆支付部分
  831. "invoice_amount" => $this->orderData[$this->invoiceConfig['amount_type']] // 可开票金额
  832. ];
  833. // 处理小数点保留两位小数
  834. foreach ($result as $key => $amount) {
  835. $result[$key] = number_format($amount, 2, '.', '');
  836. }
  837. // 合并不需要处理小数点的
  838. $result = array_merge($result, [
  839. 'activity_id' => $this->activity['activity']['id'] ?? 0,
  840. 'activity_type' => $this->activity['activity']['type'] ?? null,
  841. 'activity_title' => $this->activity['activity']['title'] ?? null,
  842. 'promo_types' => array_column($this->activity['promo_infos'], 'activity_type'),
  843. 'score_amount' => $this->orderData['score_amount'],
  844. 'goods_list' => $this->goodsList,
  845. 'promo_infos' => $this->activity['promo_infos'],
  846. "invoice_status" => $this->invoiceConfig['status'], // 发票可开状态
  847. "invoice_amount_type" => $this->invoiceConfig['amount_type'], // 发票金额类型
  848. "need_address" => $this->need_address,
  849. "offline_status" => $this->offline_status,
  850. ]);
  851. // 如果是下单,合并 优惠券, 收货地址
  852. if ($this->calc_type == 'create') {
  853. $result = array_merge($result, [
  854. "coupon" => $this->orderData['coupon'],
  855. "user_address" => $this->userAddress
  856. ]);
  857. } else {
  858. $result = array_merge($result, ['msg' => $this->msg]);
  859. }
  860. return $result;
  861. }
  862. /**
  863. * 计算订单
  864. *
  865. * @return void
  866. */
  867. public function calc($calc_type = 'calc')
  868. {
  869. $this->calc_type = $calc_type;
  870. // 检查系统必要条件
  871. check_env(['bcmath', 'queue']);
  872. // 检查是否可下单
  873. $this->calcCheck();
  874. // 计算订单各种费用
  875. $this->calcAmount();
  876. // 计算订单各种优惠(promo 等)
  877. if ($this->isCalcPromos()) { // 判断是否参与优惠
  878. $this->calcDiscount();
  879. }
  880. // 计算优惠券费用
  881. if ($this->coupon_id) {
  882. $this->calcCoupon();
  883. }
  884. // 订单应付金额
  885. $this->orderData['order_amount'] = bcadd($this->orderData['goods_amount'], $this->orderData['dispatch_amount'], 2);
  886. $this->orderData['total_discount_fee'] = bcadd($this->orderData['coupon_discount_fee'], $this->orderData['promo_discount_fee'], 2);
  887. $this->orderData['pay_fee'] = bcsub($this->orderData['order_amount'], $this->orderData['total_discount_fee'], 2);
  888. $this->orderData['pay_fee'] = $this->orderData['pay_fee'] < 0 ? 0 : $this->orderData['pay_fee'];
  889. return $this->calcReturn();
  890. }
  891. public function create($result)
  892. {
  893. $stockSale = new StockSale();
  894. try {
  895. // 如果失败,被扣除的库存,退回
  896. $order = $this->createOrder($result);
  897. $stockSale->successDelHashKey();
  898. } catch (\Exception $e) {
  899. $message = $e->getMessage();
  900. if ($e instanceof \think\exception\HttpResponseException) {
  901. $data = $e->getResponse()->getData();
  902. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  903. }
  904. // 下单失败,检测并返还锁定的库存
  905. $stockSale->faildStockUnLock();
  906. error_stop($message);
  907. }
  908. // 重新获取订单
  909. $order = Order::with('items')->where('id', $order->id)->find();
  910. $pay_money = floatval($result['money']);
  911. if ($order->status == Order::STATUS_UNPAID && $pay_money > 0) {
  912. // 如果订单未支付,并且使用了余额混合支付 (支付失败,不影响订单状态)
  913. $order = Db::transaction(function () use ($order, $pay_money) {
  914. $payOper = new PayOper();
  915. // 余额支付,并判断是否直接支付成功了
  916. $order = $payOper->money($order, $pay_money, 'order');
  917. return $order;
  918. });
  919. }
  920. return $order;
  921. }
  922. private function createOrder($result)
  923. {
  924. $order = Db::transaction(function () use ($result) {
  925. $orderData['type'] = $this->order_type;
  926. $orderData['order_sn'] = get_sn($this->user->id);
  927. $orderData['user_id'] = $this->user->id;
  928. $orderData['activity_id'] = $result['activity_id'];
  929. $orderData['activity_type'] = $result['activity_type'];
  930. $orderData['promo_types'] = join(',', $result['promo_types']);
  931. $orderData['goods_original_amount'] = $result['goods_original_amount'];
  932. $orderData['goods_amount'] = $result['goods_amount'];
  933. $orderData['goods_bean_amount'] = $result['goods_bean_amount'];
  934. $orderData['dispatch_amount'] = $result['dispatch_amount'];
  935. $orderData['remark'] = $this->remark;
  936. $orderData['order_amount'] = $result['order_amount'];
  937. $orderData['score_amount'] = $result['score_amount'];
  938. $orderData['pay_fee'] = $result['pay_fee'];
  939. $orderData['original_pay_fee'] = $result['pay_fee']; // 记录支付总金额,后面可能会订单改价
  940. $orderData['remain_pay_fee'] = $result['pay_fee']; // 这里还是显示应支付总金额,扣除动作放到实际支付时
  941. $orderData['total_discount_fee'] = $result['total_discount_fee'];
  942. $orderData['coupon_discount_fee'] = $result['coupon_discount_fee'];
  943. $orderData['promo_discount_fee'] = $result['promo_discount_fee'];
  944. $orderData['coupon_id'] = $result['coupon'] ? $result['coupon']['id'] : 0;
  945. $orderData['status'] = Order::STATUS_UNPAID;
  946. $orderData['platform'] = request()->header('platform');
  947. //直播间id
  948. $orderData['room_id'] = 0;
  949. $orderData['room_log_id'] = 0;
  950. $room_log_id = request()->param('room_log_id',0);
  951. if($room_log_id){
  952. $room_id = Db::name('live_room_log')->where('id',$room_log_id)->value('room_id');
  953. if($room_id){
  954. $orderData['room_id'] = $room_id;
  955. $orderData['room_log_id'] = $room_log_id;
  956. }
  957. }
  958. $ext = $result['promo_infos'] ? ['promo_infos' => $result['promo_infos']] : []; // 促销活动信息
  959. if ($this->activity['activity']) {
  960. $rules = $this->activity['activity']['rules'];
  961. $ext['refund_type'] = $rules['refund_type'] ?? 'back'; // 退款方式,(目前主要针对拼团失败自动退款)
  962. }
  963. $ext['real_dispatch_amount'] = $result['real_dispatch_amount']; // 真实运费,剪掉运费优惠金额
  964. $goods_discount_amount = bcsub($result['goods_old_amount'], $result['goods_amount'], 2); // 如果参与活动时商品总价的优惠费用
  965. $ext['activity_discount_amount'] = $goods_discount_amount > 0 ? $goods_discount_amount : 0; // 如果参与活动时的优惠费用
  966. if ($result['activity_id']) {
  967. $ext['activity_type'] = $result['activity_type'];
  968. $ext['activity_title'] = $result['activity_title'];
  969. }
  970. $ext['offline_status'] = $result['offline_status'];
  971. $ext['need_address'] = $result['need_address']; // 后台判断是否有 编辑收货地址按钮
  972. $orderData['ext'] = $ext;
  973. // 发票开具状态
  974. $invoice_status = 0; // 没有申请
  975. if ($result['invoice_status'] && $this->invoice_id) {
  976. // 可开具,并且申请了
  977. $invoice_status = 1;
  978. } else if ($result['invoice_status'] == 0) {
  979. // 不可开具
  980. $invoice_status = -1;
  981. }
  982. $orderData['invoice_status'] = $invoice_status; // 可开具发票,并且申请了
  983. // 订单创建前
  984. $hookData = [
  985. 'params' => $result,
  986. 'order_data' => $orderData
  987. ];
  988. \think\Hook::listen('order_create_before', $hookData);
  989. $order = new Order();
  990. $order->save($orderData);
  991. // 添加收货地址信息
  992. if ($result['user_address']) {
  993. $this->createOrderAddress($order, $result);
  994. }
  995. // 添加发票信息
  996. if ($invoice_status == 1) {
  997. $this->createOrderInvoice($order, $result);
  998. }
  999. // 将优惠券使用掉
  1000. if ($result['coupon']) {
  1001. $result['coupon']->use_order_id = $order->id;
  1002. $result['coupon']->use_time = time();
  1003. $result['coupon']->allowField(true)->save();
  1004. }
  1005. // 添加 订单 item
  1006. foreach ($result['goods_list'] as $key => $buyInfo) {
  1007. $goods = $buyInfo['goods'];
  1008. $current_sku_price = $buyInfo['current_sku_price'];
  1009. $orderItem = new OrderItem();
  1010. $orderItem->order_id = $order->id;
  1011. $orderItem->user_id = $this->user->id;
  1012. $orderItem->goods_id = $buyInfo['goods_id'];
  1013. $orderItem->goods_type = $goods['type'];
  1014. $orderItem->goods_sku_price_id = $buyInfo['goods_sku_price_id'];
  1015. $orderItem->activity_id = $result['activity_id']; // 商品当前参与的活动 id
  1016. $orderItem->activity_type = $result['activity_type']; // 商品当前的活动类型
  1017. $orderItem->promo_types = join(',', $buyInfo['promo_types']); // 商品当前的活动类型
  1018. // 当前商品规格对应的 活动下对应商品规格的 id
  1019. $orderItem->item_goods_sku_price_id = isset($current_sku_price['item_goods_sku_price']) ?
  1020. $current_sku_price['item_goods_sku_price']['id'] : 0;
  1021. $orderItem->goods_sku_text = is_array($current_sku_price->goods_sku_text) ? join(',', $current_sku_price->goods_sku_text) : '';
  1022. $orderItem->goods_title = $goods->title;
  1023. $orderItem->goods_image = empty($current_sku_price->image) ? $goods->image : $current_sku_price->image;
  1024. $orderItem->goods_original_price = $goods->original_price;
  1025. $orderItem->goods_price = $current_sku_price->price;
  1026. $orderItem->goods_num = $buyInfo['goods_num'] ?? 1;
  1027. $orderItem->goods_weight = $current_sku_price->weight;
  1028. $orderItem->discount_fee = bcadd(bcadd($buyInfo['promo_discount_fee'], $buyInfo['coupon_discount_fee'], 2), $buyInfo['dispatch_discount_fee'], 2); // 当前商品所享受的折扣 (promo_discount_fee + coupon_discount_fee + dispatch_discount_fee)
  1029. $pay_fee = bcsub($buyInfo['goods_amount'], bcadd($buyInfo['promo_discount_fee'], $buyInfo['coupon_discount_fee'], 2), 2); // 商品总金额(不算运费),减去(活动优惠(不包含包邮优惠) + 优惠券优惠)
  1030. $orderItem->pay_fee = $pay_fee; // 平均计算单件商品不算运费,算折扣时候的金额
  1031. $orderItem->dispatch_status = 0;
  1032. $orderItem->dispatch_fee = $buyInfo['dispatch_amount']; // 运费模板中商品自动合并后的加权平均运费,没有扣除包邮优惠
  1033. $orderItem->dispatch_type = $buyInfo['dispatch_type'];
  1034. $orderItem->dispatch_id = $buyInfo['dispatch_id'] ? $buyInfo['dispatch_id'] : 0;
  1035. $orderItem->aftersale_status = 0;
  1036. $orderItem->comment_status = 0;
  1037. $orderItem->refund_status = 0;
  1038. $orderItem->room_id = $orderData['room_id'];
  1039. $orderItem->room_log_id = $orderData['room_log_id'];
  1040. $ext = [
  1041. 'original_dispatch_amount' => $buyInfo['original_dispatch_amount'], // 原始运费总金额(未判断活动的,并且也未合并相同运费模板商品的原始运费)
  1042. 'promo_discount_fee' => bcadd($buyInfo['promo_discount_fee'], $buyInfo['dispatch_discount_fee'], 2), // 促销优惠,包含满包邮
  1043. 'dispatch_discount_fee' => $buyInfo['dispatch_discount_fee'], // 包邮优惠,已经包含在 promo_discount_fee
  1044. 'coupon_discount_fee' => $buyInfo['coupon_discount_fee'], // 优惠券优惠
  1045. 'activity_sku_price_ext' => $current_sku_price['ext'] ?? [], // 活动规格 ext,保存备用
  1046. 'ladder' => $buyInfo['ladder'] ?? [], // (阶梯拼团仅有)阶梯拼团,当前购买的阶梯
  1047. ];
  1048. if (isset($buyInfo['is_commission'])) {
  1049. $ext['is_commission'] = $buyInfo['is_commission'];
  1050. }
  1051. $orderItem->ext = $ext;
  1052. $orderItem->save();
  1053. }
  1054. // 订单创建后
  1055. $hookData = [
  1056. 'order' => $order,
  1057. 'activity' => $this->activity['activity'],
  1058. ];
  1059. \think\Hook::listen('order_create_after', $hookData);
  1060. return $order;
  1061. });
  1062. return $order;
  1063. }
  1064. /**
  1065. * 添加收货地址信息
  1066. *
  1067. * @param \think\Model $order
  1068. * @param array $result
  1069. * @return void
  1070. */
  1071. private function createOrderAddress($order, $result)
  1072. {
  1073. // 保存收货地址
  1074. $orderAddress = new OrderAddress();
  1075. $orderAddress->order_id = $order->id;
  1076. $orderAddress->user_id = $this->user->id;
  1077. $orderAddress->consignee = $result['user_address']->consignee;
  1078. $orderAddress->mobile = $result['user_address']->mobile;
  1079. $orderAddress->province_name = $result['user_address']->province_name;
  1080. $orderAddress->city_name = $result['user_address']->city_name;
  1081. $orderAddress->district_name = $result['user_address']->district_name;
  1082. $orderAddress->address = $result['user_address']->address;
  1083. $orderAddress->province_id = $result['user_address']->province_id;
  1084. $orderAddress->city_id = $result['user_address']->city_id;
  1085. $orderAddress->district_id = $result['user_address']->district_id;
  1086. $orderAddress->save();
  1087. }
  1088. /**
  1089. * 添加发票信息
  1090. *
  1091. * @param \think\Model $order
  1092. * @param array $result
  1093. * @return void
  1094. */
  1095. private function createOrderInvoice($order, $result)
  1096. {
  1097. $userInvoice = $this->invoiceConfig['user_invoice'];
  1098. // 保存收货地址
  1099. $orderInvoice = new OrderInvoice();
  1100. $orderInvoice->type = $userInvoice->type;
  1101. $orderInvoice->order_id = $order->id;
  1102. $orderInvoice->user_id = $userInvoice->user_id;
  1103. $orderInvoice->name = $userInvoice->name;
  1104. $orderInvoice->tax_no = $userInvoice->tax_no;
  1105. $orderInvoice->address = $userInvoice->address;
  1106. $orderInvoice->mobile = $userInvoice->mobile;
  1107. $orderInvoice->bank_name = $userInvoice->bank_name;
  1108. $orderInvoice->bank_no = $userInvoice->bank_no;
  1109. $orderInvoice->amount = $result['invoice_amount'];
  1110. $orderInvoice->status = 'unpaid';
  1111. $orderInvoice->save();
  1112. }
  1113. /**
  1114. * 判断并处理异常
  1115. *
  1116. * @param string $msg 处理结果
  1117. * @param boolean $force 是否强制抛出异常
  1118. * @return boolean
  1119. */
  1120. private function exception($msg, $force = false)
  1121. {
  1122. if ($this->calc_type == 'create' || $force) {
  1123. // 如果是创建订单,或者强制抛出异常
  1124. error_stop($msg);
  1125. } else {
  1126. // 预下单,记录第一条错误信息
  1127. if (!$this->msg) {
  1128. $this->msg = $msg;
  1129. }
  1130. }
  1131. return false;
  1132. }
  1133. /**
  1134. * 获取商品服务实例
  1135. *
  1136. * @return GoodsService
  1137. */
  1138. private function getGoodsService()
  1139. {
  1140. // 实例化商品服务
  1141. return new GoodsService(function ($goods, $service) {
  1142. // $goods->sku_prices;
  1143. // 这个写法没用,只要判断 promos 还是会获取 promos
  1144. // if (!$this->activity_id) {
  1145. // // 可能要参与的营销活动
  1146. // $goods->promos = $goods->promos;
  1147. // }
  1148. return $goods;
  1149. });
  1150. }
  1151. /**
  1152. * 是否计算促销
  1153. *
  1154. * @return bool
  1155. */
  1156. private function isCalcPromos()
  1157. {
  1158. if ($this->order_type == 'score') {
  1159. return false; // 积分商品不能参与促销
  1160. } else if ($this->activity_id) {
  1161. if ($this->activity_promos) {
  1162. // 活动与促销共存
  1163. return true;
  1164. } else {
  1165. // 参与活动,不能在参与促销
  1166. return false;
  1167. }
  1168. } else {
  1169. return true;
  1170. }
  1171. }
  1172. }