OrderCreate.php 56 KB

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