OrderCreate.php 63 KB

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