OrderCreate.php 62 KB

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