ShopOrderModel.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. <?php
  2. namespace app\common\model;
  3. use app\common\model\ShopGoodsModel as Goods;
  4. use app\common\model\UserModel as User;
  5. use app\common\model\UserMoneyModel as UserMoney;
  6. use app\api\services\ExpressServices;
  7. use jobs\ShopOrderJob;
  8. use mysql_xdevapi\Result;
  9. use services\CacheServices;
  10. use think\db\concern\ResultOperation;
  11. use think\Exception;
  12. use think\facade\Db;
  13. use think\Model;
  14. use app\common\model\ShopOrderGoodsModel as OrderGoods;
  15. use app\common\model\ShopOrderShippingModel as OrderShipping;
  16. use jobs\ShopBonusJob;
  17. use utils\Json;
  18. use utils\Queue;
  19. class ShopOrderModel extends Model
  20. {
  21. protected $name = 'shop_order';
  22. const waitPay = 0; //待支付
  23. const waitDelivery = 1; //待发货
  24. const doneDelivery = 2; //已发货
  25. const doneOrder = 3; //交易完成
  26. const cancelOrder = 4; //已取消
  27. /**
  28. * @return \think\model\relation\HasMany
  29. * 关联订单商品
  30. */
  31. public function withOrderGoods ()
  32. {
  33. return self::hasMany(OrderGoods::class, 'order_id', 'order_id')->field('goods_name,goods_id,goods_img,num,price,total_fee,spec_text,goods_spec_id');
  34. }
  35. /**
  36. * @return \think\model\relation\HasOne
  37. * 关联订单配送
  38. */
  39. public function withOrderShipping ()
  40. {
  41. return self::hasOne(OrderShipping::class, 'order_id', 'order_id')->field('sp_name,sp_mobile,sp_province,sp_city,sp_county,sp_remark,sp_mergename');
  42. }
  43. /**
  44. * 订单列表
  45. */
  46. public static function list (array $map = [], array $paginate = [], $userId, ?string $field = '*')
  47. {
  48. $map['user_id'] = $userId;
  49. $field = 'order_id,status,order_sn,order_type,coupon_number,created_time,order_remark,payment,ship_postfee,rebate_score,ship_name,ship_code,ship_number,expires_time,rebate_lock_score';
  50. foreach ($map as $k => $v) {
  51. if (empty($v) && $v != '0') {
  52. unset($map[$k]);
  53. }
  54. }
  55. if (isset($map['status'])) {
  56. if ($map['status'] == -1) {
  57. $map['status'] = ['0','1','2', '4', '5', '6'];
  58. }
  59. }
  60. // if (isset($map['order_type'])) {
  61. // if ($map['order_type'] == -1) {
  62. // $map['order_type'] = ['1','2','3', '4', '5'];
  63. // }
  64. // }
  65. $data = self::where($map)->where('status', '<>', 3)->relation(['withOrderGoods'])->field($field)->order('order_id desc')->paginate($paginate['limit'])->toArray();
  66. foreach ($data['data'] as $k=>&$v){
  67. foreach ($v['withOrderGoods'] as $key=>$val){
  68. $goods_sn = Db::name('shop_goods')->where('goods_id', $val['goods_id'])->value('goods_sn');
  69. // sr_log($goods_sn);
  70. // $val['goods_sn'] = $goods_sn;
  71. $data['data'][$k]['withOrderGoods'][$key]['goods_sn'] = $goods_sn;
  72. // $data['data'][$k]['withOrderGoods'][$key]['goods_name'] = '云德商品购买';
  73. }
  74. $v['withOrderShipping'] = Db::name('shop_order_shipping')->where('order_id', $v['order_id'])->find();
  75. }
  76. $cur_xzmoney = Db::name('system_config')->where('name', 'xz_cur_money')->where('group', 'xzconfig')->value('value');
  77. foreach ($data['data'] as $k => &$v) {
  78. $v['withOrderExpress'] = [];
  79. // if (in_array($v['status'], [1, 2])) {
  80. $v['withOrderExpress'] = ExpressServices::instance()->orderId($v['order_id'])->code($v['ship_code'])->number($v['ship_number'])->find() ?: [];
  81. if (intval($v['status']) == 2){
  82. $v['express_url'] = "https://m.kuaidi100.com/result.jsp?nu=".$v['ship_number'];
  83. }else{
  84. $v['express_url'] = "";
  85. }
  86. // }
  87. if ($v['status'] == 1){
  88. if ($v['order_type'] == 1){
  89. $v['can_hg'] = 1;
  90. }
  91. }else{
  92. $v['can_hg'] = 2;
  93. }
  94. // if ($v['status'] == 4){
  95. // $v['yg_goodsid'] = Db::name('yg_order')->where('order_sn', $v['order_sn'])->max('id');
  96. // }else{
  97. // $v['yg_goodsid'] = 0;
  98. //
  99. // }
  100. switch ($v['status']){
  101. case 0:
  102. $v['status_title'] = '待付款';
  103. break;
  104. case 1:
  105. $v['status_title'] = '待发货';
  106. break;
  107. case 2:
  108. $v['status_title'] = '已发货';
  109. break;
  110. case 3:
  111. $v['status_title'] = '已过期';
  112. break;
  113. case 4:
  114. $v['status_title'] = '已完成';
  115. break;
  116. case 5:
  117. $v['status_title'] = '已完成';
  118. break;
  119. case 6:
  120. $v['status_title'] = '已完成';
  121. break;
  122. }
  123. // if ($v['expires_time']){
  124. // $v['expires_time']=strtotime($v['expires_time']);
  125. // }
  126. // 建议竞拍价格
  127. // $back_redscore = number_format($v['rebate_lock_score']*env('app.YP_APPLY_HUIGOU_SCALE')/100, '2', '.', '');
  128. // $cur_xzmoney = Db::name('system_config')->where('name', 'xz_cur_money')->where('group', 'xzconfig')->value('value');
  129. // $xz_price = getXzPirceWithPrice($cur_xzmoney, $back_redscore);
  130. // $v['jy_buyprice'] = number_format($xz_price + 1, '0', '.', '');
  131. // if ($xz_price < 1){
  132. // $v['jy_jpprice'] = 0.1;
  133. // }
  134. //
  135. // if ($xz_price > 1){
  136. // $v['jy_jpprice'] = 1;
  137. // }
  138. //
  139. // if ($xz_price > 4){
  140. // $v['jy_jpprice'] = number_format($xz_price-2, '0', '.', '');
  141. // }
  142. // if ($xz_price > 5){
  143. // $v['jy_jpprice'] = number_format($xz_price-3, '0', '.', '');
  144. // }
  145. // if ($v['order_type'] == 5){
  146. // foreach ($v['withOrderGoods'] as $k1=>&$v1){
  147. // $v1['price'] = getXzPirceWithPrice($cur_xzmoney ,$v1['price']);
  148. // }
  149. //
  150. // $v['payment'] = getXzPirceWithPrice($cur_xzmoney, $v['payment']);
  151. // }
  152. }
  153. return $data['data'];
  154. }
  155. /**
  156. * 订单详情
  157. */
  158. public static function details (array $map, $userId, ?string $field = '*'): array
  159. {
  160. $field = 'order_type,order_id,status,order_sn,created_time,coupon_number,order_remark,total_price,ship_postfee,payment,rebate_score,ship_code,ship_name,ship_number,expires_time,rebate_lock_score';
  161. $cur_xzmoney = Db::name('system_config')->where('name', 'xz_cur_money')->where('group', 'xzconfig')->value('value');
  162. $map['user_id'] = $userId;
  163. $details = self::where($map)->relation(['withOrderGoods', 'withOrderShipping'])->field($field)->findOrEmpty()->toArray();
  164. if (empty($details))
  165. throw new Exception('订单不存在');
  166. $details['withOrderExpress'] = [];
  167. if (in_array($details['status'], [1, 2])) {
  168. $details['withOrderExpress'] = ExpressServices::instance()->orderId($details['order_id'])->code($details['ship_code'])->number($details['ship_number'])->find() ?: [];
  169. if (intval($details['status']) == 2){
  170. $details['express_url'] = "https://m.kuaidi100.com/result.jsp?nu=".$details['ship_number'];
  171. }else{
  172. $details['express_url'] = "";
  173. }
  174. }
  175. if ($details['order_type'] == 5){
  176. $details['total_price'] = getXzPirceWithPrice($cur_xzmoney, $details['total_price']);
  177. }
  178. switch ($details['status']){
  179. case 0:
  180. $details['status_title'] = '待付款';
  181. break;
  182. case 1:
  183. $details['status_title'] = '待发货';
  184. break;
  185. case 2:
  186. $details['status_title'] = '已发货';
  187. break;
  188. case 3:
  189. $details['status_title'] = '取消订单';
  190. break;
  191. case 4:
  192. $details['status_title'] = '待发货(正在竞拍)';
  193. break;
  194. case 5:
  195. $details['status_title'] = '待发货(竞拍完成)';
  196. break;
  197. case 6:
  198. $details['status_title'] = '已发货(竞拍已发货)';
  199. break;
  200. }
  201. // if ($details['expires_time']){
  202. // $details['expires_time']=strtotime($details['expires_time']);
  203. // }
  204. // foreach ($details['data'] as $k=>$v){
  205. foreach ($details['withOrderGoods'] as $key=>$val){
  206. $goods_sn = Db::name('shop_goods')->where('goods_id', $val['goods_id'])->value('goods_sn');
  207. // sr_log($goods_sn);
  208. // $val['goods_sn'] = $goods_sn;
  209. //
  210. $details['withOrderGoods'][$key]['goods_sn'] = $goods_sn;
  211. // $details['withOrderGoods'][$key]['goods_name'] = '云德商品购买';
  212. $details['withOrderGoods'][$key]['price'] = getXzPirceWithPrice($cur_xzmoney, $details['withOrderGoods'][$key]['price']);
  213. }
  214. // }
  215. return $details;
  216. }
  217. /**
  218. * 下单详情,获取商品信息
  219. */
  220. public static function buyDetails (array $data, array $address = [])
  221. {
  222. $result = [];
  223. foreach ($data as $key => $value) {
  224. $result[$value['goods_sn'] . '_' . $value['spec_id']][] = $value;
  225. }
  226. $details = [];
  227. try {
  228. array_walk($result, function ($value, $key) use (&$details, &$flag) {
  229. $key_arrkass = explode('_', $key);
  230. $goodsBase = Db::name('shop_goods')->where(['goods_sn' => $key_arrkass[0]])->find();
  231. $num = array_sum(array_column($value, 'num'));
  232. $goodsSpec = Db::name('shop_goods_spec')->where(['goods_id' => $goodsBase['goods_id'], 'spec_ids' => $value[0]['spec_id']])->find();
  233. if (empty($goodsSpec) || empty($goodsBase)) {
  234. throw new Exception('操作失败,所选商品含有失效商品');
  235. }
  236. $superlizer = Db::name('shop_supplier')->where('id', $goodsBase['supplier'])->find();
  237. $details[] = [
  238. 'goods_sn' => $goodsBase['goods_sn'],
  239. 'goods_id' => $goodsBase['goods_id'],
  240. 'goods_type' => $goodsBase['goods_type'],
  241. 'goods_name' => $goodsBase['goods_name'],
  242. 'picture' => $goodsSpec['picture'] ?: $goodsBase['goods_img'],
  243. 'num' => $num, //数量
  244. 'price' => $goodsSpec['price'],//单价
  245. 'weight' => $goodsSpec['weight'], //重量
  246. 'total_fee' => bcmul($num, $goodsSpec['price'], 2), //总价
  247. 'rebate_score' => $goodsSpec['rebate_score'],//单个返利积分
  248. // 'rebate_score_most' => bcmul($num, $goodsBase['rebate_score_most'], 2),//返回积分 马上
  249. // 'rebate_score_lock' => bcmul($num, $goodsBase['rebate_score_lock'], 2),//返回积分 锁定
  250. 'total_items_rebate_score' => bcmul($num, $goodsSpec['rebate_score'], 2),//总返利积分
  251. 'spec_ids' => $goodsSpec['spec_ids'],
  252. 'spec_text' => $goodsSpec['spec_text'],
  253. // 'coupon_num' => $goodsBase['coupon_num'],
  254. 'post_template_id' => $goodsBase['post_template_id'], //是否包邮,否就是运费模板ID
  255. 'stock' => $goodsSpec['stock'],
  256. 'supplier_name'=>$superlizer['name']
  257. ];
  258. });
  259. //组合数据
  260. $details_arr = [];
  261. foreach ($details as $k => $v) {
  262. $details_arr[$v['goods_sn']]['goods'][] = $v;
  263. $total_rebate_score = multi_array_sum($details_arr[$v['goods_sn']]['goods'], 'total_items_rebate_score');
  264. // $total_rebate_most_score = multi_array_sum($details_arr[$v['goods_sn']]['goods'], 'rebate_score_most');
  265. // $total_rebate_lock_score = multi_array_sum($details_arr[$v['goods_sn']]['goods'], 'rebate_score_lock');
  266. $total_num = multi_array_sum($details_arr[$v['goods_sn']]['goods'], 'num');
  267. $total_weight = multi_array_sum($details_arr[$v['goods_sn']]['goods'], 'weight');
  268. $total_price = multi_array_sum($details_arr[$v['goods_sn']]['goods'], 'total_fee');
  269. // $total_coupon_num = multi_array_sum($details_arr[$v['goods_sn']]['goods'], 'coupon_num');
  270. $details_arr[$v['goods_sn']]['total_rebate_score'] = $total_rebate_score; //总返利积分
  271. // $details_arr[$v['goods_sn']]['total_rebate_most_score'] = $total_rebate_most_score; // 返利积分马上到账
  272. // $details_arr[$v['goods_sn']]['total_rebate_lock_score'] = $total_rebate_lock_score; //总返利积分
  273. $details_arr[$v['goods_sn']]['total_num'] = $total_num; //总数量
  274. $details_arr[$v['goods_sn']]['total_price'] = $total_price; //总金额
  275. $details_arr[$v['goods_sn']]['total_weight'] = $total_weight; //总重量
  276. // $details_arr[$v['goods_sn']]['total_coupon_num'] = $total_coupon_num * $total_num; //总抢购值
  277. //获取运费
  278. // if ($address) {
  279. // $details_arr[$v['goods_sn']]['post_fee'] = self::postFee(
  280. // $address['city'],
  281. // [
  282. // 'goods_sn' => $v['goods_sn'],
  283. // 'num' => $total_num,
  284. // 'total_price' => $total_price,
  285. // 'total_weight' => $details_arr
  286. // ],
  287. // $v['post_template_id']
  288. // );
  289. // } else {
  290. // $details_arr[$v['goods_sn']]['post_fee'] = '0.00';
  291. // }
  292. $details_arr[$v['goods_sn']]['post_fee'] = '0.00';
  293. $details_arr[$v['goods_sn']]['payment'] = bcadd($details_arr[$v['goods_sn']]['total_price'], $details_arr[$v['goods_sn']]['post_fee'], 2);
  294. $details_arr[$v['goods_sn']]['supplier_name'] = $details[$key]['supplier_name'];
  295. }
  296. $total = [
  297. 'count_payment' => sprintf("%.2f", multi_array_sum($details_arr, 'payment')),
  298. 'count_rebate_score' => (string)multi_array_sum($details_arr, 'total_rebate_score'),
  299. // 'count_rebate_most_score' => (string)multi_array_sum($details_arr, 'total_rebate_most_score'),
  300. // 'count_rebate_lock_score' => (string)multi_array_sum($details_arr, 'total_rebate_lock_score'),
  301. 'count_num' => multi_array_sum($details_arr, 'total_num'),
  302. // 'total_coupon_num' => multi_array_sum($details_arr, 'total_coupon_num')
  303. ];
  304. $details_arr = array_values($details_arr);
  305. return ['details' => $details_arr, 'total' => $total];
  306. } catch (\Exception $e) {
  307. throw new Exception($e->getMessage());
  308. }
  309. }
  310. /**
  311. * 生成订单
  312. */
  313. public static function createOrder (array $data, int $userId, $user, $buyData, $cart_id)
  314. {
  315. $m_machine = new MacheineExchangeModel();
  316. Db::startTrans();
  317. try {
  318. //-----组装商品数据,不同商品将拆分------
  319. $result = $data['order'];
  320. $results = [];
  321. $specStock = [];
  322. // $m_id = createdMachineID();
  323. // if ($data['order_type'] == 3){
  324. // // 生成矿机兑换券
  325. // $m_machine->insertGetId([
  326. // 'number'=>$m_id,
  327. // 'create_time'=>sr_getcurtime(time())
  328. // ]);
  329. // }
  330. array_walk($result, function ($value, $key) use (&$results, &$specStock) {
  331. $key_arrkass = explode('_', $key);
  332. $goodsBase = Db::name('shop_goods')->where(['goods_sn' => $key_arrkass[0]])->find();
  333. $results[$key_arrkass[0]]['goods'] = $goodsBase;
  334. $goodsSpec = Db::name('shop_goods_spec')->where(['goods_id' => $goodsBase['goods_id'], 'spec_ids' => $value[0]['spec_id']])->find();
  335. $num = array_sum(array_column($value, 'num'));
  336. $results[$key_arrkass[0]]['spec'][$key_arrkass[1]] = $specStock[] = [
  337. 'num' => $num, //数量
  338. 'total_fee' => bcmul($num, $goodsSpec['price'], 3), //总价
  339. 'total_weight' => bcmul($num, $goodsSpec['weight'], 3), //总重量
  340. 'spec_id' => $value[0]['spec_id'], //规格ids
  341. 'spec_data' => $goodsSpec, //规格数据
  342. 'total_rebate_score' => bcmul($num, $goodsBase['rebate_score'], 3),//总返积分
  343. // 'total_rebate_lock_score' => bcmul($num, $goodsBase['rebate_score_lock'], 3)//返利积分锁定
  344. ];
  345. });
  346. //------减库存--------
  347. $num = 0;
  348. foreach ($specStock as $k => $v) {
  349. Db::name('shop_goods_spec')->where(['goods_spec_id' => $v['spec_data']['goods_spec_id']])->dec('stock', $v['num'])->update();
  350. $spec_info = Db::name('shop_goods_spec')->where(['goods_spec_id' => $v['spec_data']['goods_spec_id']])->find();
  351. Db::name('shop_goods')->where(['goods_id' => $spec_info['goods_id']])->dec('inventory', $v['num'])->update();
  352. // CacheServices::clear(md5('goodsDetail_' . $v['goods_sn']));
  353. CacheServices::set(md5('goodsDetail_' . $spec_info['goods_sn']), false);
  354. }
  355. //-------生成订单商品,返回订单号--------
  356. $createOrder = [];
  357. $i = -1;
  358. $total_rebate_score = 0;
  359. // $total_rebate_lock_score = 0;
  360. array_walk($results, function ($value, $key) use ($userId, $data, &$createOrder, &$i, &$total_rebate_score) {
  361. $nowTime = date('Y-m-d H:i:s', time());
  362. $nums = multi_array_sum($value['spec'], 'num');
  363. $total_price = multi_array_sum($value['spec'], 'total_fee');
  364. $total_weight = multi_array_sum($value['spec'], 'total_weight');
  365. $total_rebate_score = multi_array_sum($value['spec'], 'total_rebate_score');
  366. // $total_rebate_score = $value['goods']['rebate_score_most']*
  367. // $total_rebate_lock_score = multi_array_sum($value['spec'], 'total_rebate_lock_score');
  368. //运费
  369. $post_fee = self::postFee(
  370. $data['address']['city'],
  371. [
  372. 'goods_sn' => $value['goods']['goods_sn'],
  373. 'num' => $nums,
  374. 'total_price' => $total_price,
  375. 'total_weight' => $total_weight
  376. ],
  377. $value['goods']['post_template_id']
  378. );
  379. $post_fee = 0;
  380. $give_vip = 0;
  381. if ($data['cls'] == 1 && $value['goods']['give_vip']) {
  382. $give_vip = $value['goods']['give_vip'];
  383. }
  384. $i++;
  385. $status = 0;
  386. // 积分订单 被锁积分订单
  387. // if (in_array($data['order_type'], [2, 4])){
  388. // $status = 1;
  389. // }
  390. //
  391. // // 自营订单 余额支付
  392. // if ( $data['order_type'] == 1 && $data['pay_type'] == 3){
  393. // $status = 1;
  394. // }
  395. // // 矿机 余额支付
  396. // if ( $data['order_type'] == 3 && $data['pay_type'] == 3){
  397. // $status = 2;
  398. // }
  399. //
  400. //
  401. //
  402. // // 星钻兑换
  403. // if ( $data['order_type'] == 5){
  404. // $status = 1;
  405. // }
  406. // sr_log(json_encode($data));
  407. // //写入订单
  408. $payment = bcadd($total_price, $post_fee, 3);
  409. $order = self::create([
  410. 'order_sn' => createdOrderSn(),
  411. 'total_price' => $total_price,
  412. 'payment' => $payment,
  413. 'user_id' => $userId,
  414. 'num' => $nums,
  415. 'status'=>$status,
  416. 'ship_postfee' => $post_fee,
  417. 'rebate_score' => $total_rebate_score, //总返利积分
  418. // 'rebate_lock_score' => $total_rebate_lock_score, //总返利积分锁定
  419. // 'rebate_money' => bcmul($value['goods']['rebate_money'], $nums, 2), //总返利金额
  420. 'created_time' => $nowTime, 'updated_time' => $nowTime,
  421. 'give_vip' => $give_vip,
  422. 'order_remark' => isset($data['order_remark']) ? $data['order_remark'] : '',
  423. 'pay_type'=>$data['pay_type'],
  424. 'order_type'=>$data['order_type'],
  425. 'coupon_number'=>'',
  426. 'expires_time'=>sr_getcurtime(time()+intval(env('common.ORDER_EXPIRES_TIME'))),
  427. 'supplier_name'=>$data['supplier_name']
  428. ]);
  429. // sr_log('ccccc'.$data['order_type']);
  430. //写入订单商品详情
  431. $orderGoods = [];
  432. foreach ($value['spec'] as $specKey => $specValue) {
  433. $orderGoods[] = [
  434. 'order_id' => $order->id, 'goods_id' => $value['goods']['goods_id'],
  435. 'goods_name' => $value['goods']['goods_name'], 'goods_category' => $value['goods']['category'],
  436. 'goods_img' => $specValue['spec_data']['picture'] ?: $value['goods']['goods_img'],
  437. 'num' => $specValue['num'],
  438. 'price' => $specValue['spec_data']['price'],
  439. 'total_fee' => $specValue['total_fee'],
  440. 'goods_spec_id' => $specValue['spec_data']['goods_spec_id'],
  441. 'spec_ids' => $specValue['spec_data']['spec_ids'],
  442. 'spec_text' => $specValue['spec_data']['spec_text'],
  443. 'rebate_score' => $specValue['spec_data']['rebate_score'],
  444. 'total_rebate_score' => $specValue['total_rebate_score'],
  445. 'order_type'=>$data['order_type'],
  446. 'uid'=>$userId
  447. // 'rebate_tpl' => $value['goods']['rebate_tpl']
  448. // 'rebate_money' => $value['goods']['rebate_money'],
  449. // 'total_rebate_money' => bcmul($value['goods']['rebate_money'], $specValue['num'], 3),
  450. ];
  451. }
  452. (new OrderGoods())->saveAll($orderGoods);
  453. //写入订单配送
  454. OrderShipping::create(OrderShipping::packageAddressShipPing($data['address'], $order->id));
  455. $createOrder[] = ['order_sn' => $order->order_sn, 'order_data' => $value['spec']];
  456. });
  457. if ($data['cart_ids']) {
  458. Db::name('shop_cart')->where('id', 'in', $data['cart_ids'])->where(['user_id' => $userId])->delete();
  459. }
  460. $total_score = multi_array_sum($specStock, 'total_rebate_score');
  461. // return $total_score;
  462. $m_user = new UserModel();
  463. // 积分订单
  464. // if ($data['order_type'] == 2){
  465. // edit_user_score(6,$userId, $buyData['total']['count_payment']);
  466. // }
  467. // 锁定积分 提货券 兑换
  468. // if ($data['order_type'] == 4){
  469. // edit_user_lock_score(2,$userId, $buyData['total']['count_payment']);
  470. // }
  471. // 如果是星钻订单
  472. // if ($data['order_type'] == 5){
  473. // $cur_xzmoney = Db::name('system_config')->where('name', 'xz_cur_money')->where('group', 'xzconfig')->value('value');
  474. //
  475. // $paymoney = getXzPirceWithPrice($cur_xzmoney, $buyData['total']['count_payment']);
  476. // $shouxu_scale = get_user_shouxufei($userId);
  477. // $shouxu = number_format($paymoney*$shouxu_scale/100, '2', '.', '');
  478. //
  479. // // 扣除星钻
  480. // edit_user_xz(9, $userId, ($shouxu + $paymoney) );
  481. // // 扣除抢购值
  482. // edit_user_couponnum(2, $userId, $buyData['total']['total_coupon_num']);
  483. // }
  484. // 自营商城 余额购买
  485. // if ($data['order_type']== 1 && $data['pay_type'] == 3){
  486. // edit_user_money(1, $userId, $buyData['total']['count_payment']);
  487. // edit_user_score(5, $userId, $total_rebate_score);
  488. // edit_user_redscore(1, $userId, $total_rebate_lock_score);
  489. // $m_user->buyGoodsSuccess($userId, $buyData['total']['count_rebate_score']);
  490. // }
  491. // 矿机 余额支付
  492. // if ($data['order_type']== 3 && $data['pay_type'] == 3){
  493. // edit_user_money(1, $userId, $buyData['total']['count_payment']);
  494. // }
  495. // 矿机 购买商品
  496. if (in_array($data['order_type'], [1, 3])){
  497. $ex_time = intval(env('common.ORDER_EXPIRES_TIME', 60*60));
  498. $order_sn = $createOrder[0]['order_sn'];
  499. Queue::instance()->log('订单过期执行成功')->job(ShopOrderJob::class)->do('ShopOrderExpired')->secs($ex_time)->push([$order_sn]);
  500. }
  501. // 增加销量
  502. if (in_array($data['order_type'], [2,4,5])){
  503. foreach ($createOrder as $key=>$val){
  504. $order_id = Db::name('shop_order')->where('order_sn', $val['order_sn'])->value('order_id');
  505. $orderGoods = OrderGoods::where(['order_id' => $order_id])->select()->toArray();
  506. foreach ($orderGoods as $k => $v) {
  507. ShopGoodsModel::where(['goods_id' => $v['goods_id']])->inc('sales_volume', $v['num'])->inc('real_sales_volume', $v['num'])->update();
  508. }
  509. }
  510. }
  511. if (intval($cart_id) > 0){
  512. Db::name('shop_cart')->where('id', $cart_id)->delete();
  513. }
  514. Db::commit();
  515. return ['flag' => 200, 'data' => array_column($createOrder, 'order_sn')];
  516. } catch (\Exception $e) {
  517. Db::rollback();
  518. if (strpos($e->getMessage(), 'SQLSTATE[22003]') !== false) {
  519. throw new Exception('所选商品含有库存不足');
  520. }
  521. throw new Exception($e->getMessage());
  522. }
  523. }
  524. /**
  525. * 校验库存
  526. */
  527. public static function checkStock (array $data)
  528. {
  529. $results = [];
  530. array_walk($data, function ($value, $key) use (&$results) {
  531. $num = array_sum(array_column($value, 'num'));
  532. $results[] = ['spec_id' => $value[0]['spec_id'], 'goods_sn' => $value[0]['goods_sn'], 'num' => $num];
  533. });
  534. foreach ($results as $k => $v) {
  535. $stock = Db::name('shop_goods_spec')->where(['goods_sn' => $v['goods_sn'], 'spec_ids' => $v['spec_id']])->value('stock') ?: 0;
  536. sr_log($stock);
  537. if ($v['num'] > $stock) {
  538. return false;
  539. }
  540. }
  541. return true;
  542. }
  543. /**
  544. * 支付前校验订单
  545. */
  546. public static function checkingOrder ($order_sn, $userPayMoney, $userId)
  547. {
  548. $order = self::where(['order_sn' => explode(',', $order_sn)])->select()->toArray();
  549. if (empty($order)) {
  550. return ['flag' => 110, 'msg' => '校验订单失败'];
  551. }
  552. $orderPayment = multi_array_sum($order, 'payment');
  553. // if ($orderPayment != $userPayMoney) {
  554. // return ['flag' => 111, 'msg' => '金额错误'];
  555. // }
  556. foreach ($order as $k => $v) {
  557. if ($v['user_id'] != $userId) {
  558. return ['flag' => 112, 'msg' => '校验订单失败'];
  559. }
  560. }
  561. return ['flag' => 200, 'msg' => '成功', 'orderPayment' => $orderPayment, 'order' => $order];
  562. }
  563. /**
  564. * 支付订单回调
  565. */
  566. public static function payDoneOrderCallback ($order, $payType, $userId)
  567. {
  568. $nowTime = date('Y-m-d H:i:s', time());
  569. self::where(['order_sn' => array_column($order, 'order_sn')])
  570. ->update(['pay_type' => $payType, 'status' => self::waitDelivery, 'updated_time' => $nowTime]);
  571. //根据订单商品 生成分红
  572. $orderId = array_column($order, 'order_id');
  573. $orderGoods = OrderGoods::where(['order_id' => $orderId])->select()->toArray();
  574. foreach ($orderGoods as $k => $v) {
  575. ShopGoodsModel::where(['goods_id' => $v['goods_id']])->inc('sales_volume', $v['num'])->inc('real_sales_volume', $v['num'])->update();
  576. }
  577. //赠送送会员
  578. if ($order[0]['give_vip']) {
  579. $vip = $order[0]['give_vip'] == 2 ? 'year_card' : 'monthly_card';
  580. $user = Db::name('user')->where('id', $userId)->field('vip,vip_expire_time')->find();
  581. $vip_config = get_vip_config($vip);
  582. $date = new \DateTime($user['vip_expire_time']);
  583. $date->add(new \DateInterval(get_vip_datetime_string($vip_config['type'])['time']));
  584. $vip_expire_time = $date->format('Y-m-d H:i:s'); // vip到期时间
  585. //更新用户vip信息
  586. Db::name('User')->where('id', $userId)->update(['vip' => get_vip_datetime_string($vip_config['type'])['vip_type'], 'vip_expire_time' => $vip_expire_time]);
  587. Db::name('vip_log')->insert(['uid' => $userId, 'type' => 2, 'pay_price' => 0, 'vip_expire_time' => $vip_expire_time, 'vip_type' => $vip]);
  588. }
  589. Queue::instance()->log('执行成功')->job(ShopBonusJob::class)->do('shopBonusJob')->push([$userId, $orderGoods]);
  590. }
  591. /**
  592. * 取消订单
  593. */
  594. public static function cancelOrder ($data, $userId)
  595. {
  596. $nowTime = date('Y-m-d H:i:s', time());
  597. $data = self::where(['order_sn' => $data['order_sn'], 'user_id' => $userId])->relation(['withOrderGoods'])->findOrEmpty()->toArray();
  598. if (empty($data)) {
  599. throw new Exception('参数错误');
  600. }
  601. if ($data['status'] != 0) {
  602. throw new Exception('订单状态错误');
  603. }
  604. self::where(['order_sn' => $data['order_sn']])->save(['status' => 3, 'updated_time' => $nowTime]);
  605. foreach ($data['withOrderGoods'] as $kk => $vv) {
  606. Db::name('shop_goods_spec')->where(['goods_spec_id' => $vv['goods_spec_id']])->inc('stock', $vv['num'])->update();
  607. }
  608. }
  609. /**
  610. * 确定订单
  611. */
  612. public static function receiveOrder ($data, $userId)
  613. {
  614. $nowTime = date('Y-m-d H:i:s', time());
  615. $data = self::where(['order_sn' => $data['order_sn'], 'user_id' => $userId])->relation(['withOrderGoods'])->findOrEmpty()->toArray();
  616. if (empty($data)) {
  617. throw new Exception('参数错误');
  618. }
  619. if ($data['status'] != 2) {
  620. throw new Exception('订单状态错误');
  621. }
  622. self::where(['order_sn' => $data['order_sn']])->save(['status' => 4, 'updated_time' => $nowTime]);
  623. }
  624. /**
  625. * @param $address 用户地址
  626. * @param $data 商品数据
  627. * @param $express_template_id 模板ID
  628. * 获取运费
  629. */
  630. public static function postFee ($address, $data, $express_template_id)
  631. {
  632. //获取运费模板
  633. $expressDelivery = Db::name('express_delivery')->where(['id' => $express_template_id])->findOrEmpty();
  634. //获取运费模板列表
  635. $expressDeliveryItems = Db::name('express_shipping_method')->where(['template_id' => $expressDelivery['id']])->select()->toArray();
  636. $price_method_field = '';
  637. switch ($expressDelivery['price_method']) {
  638. case 1:
  639. $price_method_field = $data['total_price']; //按金额
  640. break;
  641. case 2:
  642. $price_method_field = $data['num']; //按件数
  643. break;
  644. case 3:
  645. $price_method_field = $data['total_weight']; //按重量
  646. break;
  647. default:
  648. break;
  649. }
  650. if ($expressDelivery['price_method'] == 1) {
  651. //计算默认运费 【配送区域、免运费金额、达标时运费、未达标时运费;】
  652. if ($price_method_field < $expressDelivery['default_free_price']) {
  653. $default_postfee = $expressDelivery['default_fastandard_price'];
  654. } else {
  655. //达标时运费
  656. $default_postfee = $expressDelivery['default_price'];
  657. }
  658. if (empty($expressDeliveryItems)) {
  659. return $default_postfee;
  660. }
  661. //按指定地区计算邮费
  662. foreach ($expressDeliveryItems as $k => $node) {
  663. if (in_array($address, explode(',', $node['address_items_ids']))) {
  664. //未达标运费
  665. if ($price_method_field < $node['free_price']) {
  666. return $node['fastandard_price'];
  667. } else {
  668. //达标时运费
  669. return $node['price'];
  670. }
  671. } else {
  672. return $default_postfee;
  673. }
  674. }
  675. } else {
  676. //按件数 重量计费 【配送区域、首件、达标时运费、续件、未达标时运费】
  677. //计算默认运费
  678. if ($price_method_field <= $expressDelivery['default_pieces']) {
  679. $default_postfee = $expressDelivery['default_price'];
  680. } else {
  681. //达到续件条件时的运费
  682. if ($expressDelivery['add_pieces']) {
  683. //配置过续件费用
  684. //续件数 = (下单件数 - 首件) /续件数
  685. //总运费 = 首件运费 + (续件数 * 续件费用)
  686. $add_pieces = bcdiv(($price_method_field - $expressDelivery['default_pieces']), $expressDelivery['add_pieces'], 2);
  687. $default_postfee = bcadd($expressDelivery['default_price'], bcmul($add_pieces, $expressDelivery['add_price'], 2), 2);
  688. } else {
  689. //未配置过续件,按首件价格
  690. $default_postfee = $expressDelivery['default_price'];
  691. }
  692. }
  693. if (empty($expressDeliveryItems)) {
  694. return $default_postfee;
  695. }
  696. //按指定地区计算邮费
  697. foreach ($expressDeliveryItems as $k => $node) {
  698. if (in_array($address, explode(',', $node['address_items_ids']))) {
  699. //未达到续件条件时的运费
  700. if ($price_method_field <= $node['pieces']) {
  701. return $node['price'];
  702. } else {
  703. //达到续件条件时的运费
  704. if ($node['add_pieces']) {
  705. //配置过续件费用
  706. //续件数 = (下单件数 - 首件) /续件数
  707. //总运费 = 首件运费 + (续件数 * 续件费用)
  708. $add_pieces = bcdiv(($price_method_field - $node['pieces']), $node['add_pieces'], 2);
  709. return bcadd($node['price'], bcmul($add_pieces, $node['add_price'], 2), 2);
  710. } else {
  711. //未配置过续件,按首件价格
  712. return $node['price'];
  713. }
  714. }
  715. } else {
  716. return $default_postfee;
  717. }
  718. }
  719. }
  720. }
  721. public function boxGoodsSurePost($uid, $params){
  722. $hand_ids = $params['hand_ids'];
  723. $address_id = $params['address_id'];
  724. $total_ids = explode(',', $hand_ids);
  725. $model_hands = new BoxHandleModel();
  726. $list = $model_hands->where('id', 'in', $hand_ids)->where('status', 1)->where('uid', $uid)->select();
  727. if (count($list) != count($total_ids)){
  728. sr_throw('参数错误');
  729. }
  730. $address_info = Db::name('user_address')->where('id', $address_id)->where('uid', $uid)->find();
  731. if (!$address_info){
  732. sr_throw('地址错误');
  733. }
  734. $cur_time = sr_getcurtime(time());
  735. foreach ($total_ids as $key=>$val){
  736. $hand_info = Db::name('box_handle')->where('id', $val)->find();
  737. $goods_info = Db::name('shop_goods')->where('goods_id', $hand_info['goods_id'])->find();
  738. $supplier_info = Db::name('shop_supplier')->where('id', $goods_info['supplier'])->find();
  739. $order_id = Db::name('shop_order')->insertGetId([
  740. 'order_sn'=>createdFDOrderSn(),
  741. 'payment'=>0,
  742. 'ship_postfee'=>0,
  743. 'user_id'=>$uid,
  744. 'status'=>1,
  745. 'num'=>1,
  746. 'order_type'=>5,
  747. 'supplier_name'=>$supplier_info['name'],
  748. 'total_price'=>0,
  749. 'created_time'=>$cur_time,
  750. 'rebate_score'=>0,
  751. ]);
  752. Db::name('shop_order_goods')->insertGetId([
  753. 'order_id'=>$order_id,
  754. 'goods_id'=>$goods_info['goods_id'],
  755. 'goods_name'=>$goods_info['goods_name'],
  756. 'goods_category'=>$goods_info['category'],
  757. 'goods_img'=>$goods_info['goods_img'],
  758. 'num'=>1,
  759. 'price'=>$goods_info['price'],
  760. 'total_fee'=>$goods_info['price'],
  761. 'spec_ids'=>1,
  762. 'spec_text'=>$goods_info['spec_name'],
  763. 'uid'=>$uid,
  764. 'rebate_score'=>0,
  765. 'total_rebate_score'=>0
  766. ]);
  767. $pname = Db::name('area')->where('id', $address_info['province'])->value('name');
  768. $cname = Db::name('area')->where('id', $address_info['city'])->value('name');
  769. $countyname = Db::name('area')->where('id', $address_info['county'])->value('name');
  770. Db::name('shop_order_shipping')->insert([
  771. 'order_id'=>$order_id,
  772. 'sp_name'=>$address_info['name'],
  773. 'sp_mobile'=>$address_info['mobile'],
  774. 'sp_province'=>$pname,
  775. 'sp_city'=>$cname,
  776. 'sp_county'=>$countyname,
  777. 'sp_remark'=>$address_info['remark'],
  778. 'sp_mergename'=> $pname.' '.$cname.' '.$countyname.' '.$address_info['remark'],
  779. 'created_time'=>$cur_time
  780. ]);
  781. Db::name('box_handle')->where('id', $val)->save([
  782. 'status'=>2,
  783. 'handle_type'=>1
  784. ]);
  785. }
  786. }
  787. // 一件回收
  788. public function boxGoodsReBuy($uid, $params, $user_info){
  789. $hand_ids = $params['hand_ids'];
  790. $total_ids = explode(',', $hand_ids);
  791. $model_hands = new BoxHandleModel();
  792. $total_goodsnum = count($total_ids);
  793. $list = $model_hands->where('id', 'in', $total_ids)->where('status', 1)->where('uid', $uid)->select();
  794. if (count($list) != $total_goodsnum){
  795. sr_throw('参数或状态错误');
  796. }
  797. if ($model_hands->where('box_type', 10)->where('id', 'in', $hand_ids)->find()){
  798. sr_throw('普通商品只能发货,不能回收');
  799. }
  800. $cur_time = sr_getcurtime(time());
  801. // 待处理的总金额
  802. $total_money = Db::name('box_handle')->where('id', 'in', $hand_ids)->sum('goods_price');
  803. // 最终金额 总共商品金额减去 每个商品 10快
  804. $end_money = $total_money - $total_goodsnum* env('boxsetting.RECYCLE_ONBOX_PRICE');
  805. if ($end_money < 0){
  806. sr_throw('错误,请联系客服');
  807. }
  808. if ($params['action'] == 'apply'){
  809. return [
  810. 'total_count'=>count($list),
  811. 'end_money'=>$end_money,
  812. 'total_money'=>$total_money
  813. ];
  814. }
  815. if ($params['action'] == 'surerecycle'){
  816. $user_info = Db::name('user')->where(['id'=> $uid])->field('id,score,money,recycle_count')->find();
  817. // 回收卡扣除
  818. if ($user_info['recycle_count'] < $total_goodsnum){
  819. sr_throw('回收卡不足'.$total_goodsnum.'个');
  820. }
  821. // 扣除回收卡
  822. edit_user_recyclecard(3, $uid, $total_goodsnum, 0, $hand_ids);
  823. // 288的原价
  824. $oring_price = count($total_ids) * env('boxsetting.ONE_BOX_PRICE');
  825. edit_user_money(2, $uid, $oring_price);
  826. // 备注利润是否可以为负 by wes
  827. if ($total_money > $end_money){
  828. // 待结算利润
  829. Db::name('user')->where('id', $uid)->inc('profit_money',$end_money-$oring_price)->update();
  830. // 添加用户利润记录
  831. Db::name('user_unmoney')->insert([
  832. 'uid'=>$uid,
  833. 'money'=>$end_money-$oring_price,
  834. 'ids'=>$hand_ids,
  835. 'create_time'=>sr_getcurtime(time())
  836. ]);
  837. }
  838. // 改变用户处理状态
  839. Db::name('box_handle')->where('id', 'in', $hand_ids)->save([
  840. 'status'=>2,
  841. 'handle_type'=>2
  842. ]);
  843. }
  844. }
  845. }