1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102 |
- <?php namespace App\Http\Controllers\Api;
- use App\Models\Orders as Model;
- use App\Models\Product;
- use App\Models\Product\Skus as ProductSkus;
- use App\Http\Requests\Api\Orders as Request;
- use App\Models\Business;
- use App\Models\City;
- use App\Models\Custom;
- use App\Models\CustomAddr;
- use App\Models\CustomCoupon;
- use App\Models\CustomScore;
- use App\Models\OrdersAddr;
- use App\Models\OrdersProduct;
- use App\Models\Regiment;
- use App\Models\RegimentActive;
- use App\Models\RegimentRecord;
- use App\Models\ShopCart;
- use Illuminate\Support\Facades\DB;
- use App\Models\WeiBan\Tags as WeiBanTags;
- use App\Models\PromoProduct as PromoProduct;
- use Kra8\Snowflake\Snowflake;
- /**
- * 订单接口
- *
- * @author 刘相欣
- *
- * */
- class Orders extends Api{
- /**
- * 创建订单 /api/orders/create
- *
- * */
- public function create(Request $request,Custom $Custom,City $City,Model $Model,WeiBanTags $WeiBanTags,OrdersAddr $OrdersAddr,OrdersProduct $OrdersProduct,Product $Product,ProductSkus $ProductSkus,CustomCoupon $CustomCoupon,ShopCart $ShopCart,CustomAddr $CustomAddr,CustomScore $CustomScore,PromoProduct $PromoProduct){
- // 接口验签
- // $this->verify_sign();
- // 验证参数
- $request->scene('create')->validate();
- // 检查登录
- $uid = $this->checkLogin();
- // 接收参数
- $isCart = request('is_cart',0);
- $productList = request('product_list','[]');
- $customCouponId = request('custom_coupon_id',0);
- $addrId = request('addr_id',0);
- $isPay = request('is_pay',0);
- // 如果不存在数据
- if( !$addrId ) return json_send(['code'=>'error','msg'=>'请选择收货地址','data'=>['error'=>'请选择收货地址']]);
- // 解码购买信息
- $buyList = json_decode($productList,true);
- // 如果不存在数据
- if( empty($buyList) ) return json_send(['code'=>'error','msg'=>'没有需下单的产品','data'=>['error'=>'产品列表为空']]);
- // 选择地址
- $addr = $CustomAddr->getOne($addrId);
- // 如果不存在数据
- if( !$addr ) return json_send(['code'=>'error','msg'=>'地址有误,请核对','data'=>['error'=>'没有找到对应的地址']]);
- // 如果不存在的话
- if( !$addr['contact_shop'] ) return json_send(['code'=>'error','msg'=>'请在店铺名称处填写具体药店名称','data'=>['error'=>'所用地址请补充店铺名称']]);
- // 重组数据
- $addr = ['contact_name'=>$addr['contact_name'],'contact_shop'=>$addr['contact_shop'],'shop_type'=>$addr['shop_type'],'contact_phone'=>$addr['contact_phone'],'contact_province'=>$addr['contact_province'],'contact_city'=>$addr['contact_city'],'contact_area'=>$addr['contact_area'],'contact_addr'=>$addr['contact_addr']];
- // 获取客户城市ID
- $custom = $Custom->getOne($uid);
- // 如果不存在的话
- if( !$custom ) return json_send(['code'=>'no_login','msg'=>'用户不存在,请重新登录','data'=>['error'=>'用户不存在,请重新登录']]);
- // 如果不存在的话
- if( !$custom['city_id'] ) return json_send(['code'=>'error','msg'=>'请选择所在城市后下单','data'=>['error'=>'请选择所在城市后下单']]);
- // 获取城市ID
- $cityId = $custom['city_id'];
- $cityName = $City->getOne($cityId,'name');
- $pid = $City->getOne($cityId,'pid');
- // 如果上级不是省份
- if( strlen($cityId) > 4 ) $pid = (int) $City->getOne($pid,'pid');
- $province = $City->getOne($pid,'name');
- // 如果不是海南,
- if( $province != '海南省' ) {
- // 判断选择的城市名称是不是一致
- if( trim($cityName) != trim($addr['contact_city']) ) return json_send(['code'=>'error','msg'=>'收货地址请选择'.($province=='直辖县级'?$cityName:$province).'/'.$cityName,'data'=>['error'=>'收货地址需与您所选城市一致']]);
- }else{
- if( trim($addr['contact_province']) != trim($province) ) return json_send(['code'=>'error','msg'=>'收货地址请选择海南范围','data'=>['error'=>'收货地址需与您所选城市一致']]);
- }
- // 商品购买数量
- $buyNum = [];
- // 循环购买信息
- foreach ($buyList as $key => $value) {
- // 获取每个商品的总量
- $buyNum[$value['product_id']] = isset($buyNum[$value['product_id']]) ? ($buyNum[$value['product_id']] + $value['buy_num']) : $value['buy_num'];
- }
- // 查询用户标签
- $tags = $WeiBanTags->getListByWeibanExtid($custom['weiban_extid']);
- // 查询产品信息
- $productList = $Product->getListByIds(array_column($buyList,'product_id'),[1,$cityId]);
- $skusList = $ProductSkus->getListByIds(array_column($buyList,'product_skuid'));
- // 当前时间
- $time = time();
- // 产品以店铺分组,方便写入订单
- $orderProduct = [];
- // 产品价格同级,用于优惠券计算
- $productPrice = [];
- $Snowflake = new Snowflake();
- $SnowflakeId = $Snowflake->next();
- // 循环处理购买信息
- foreach ($buyList as $buyInfo) {
- // 如果产品不存在
- if( empty($productList[$buyInfo['product_id']]) ) return json_send(['code'=>'error','msg'=>'产品不存在或已下架','data'=>['error'=>'产品不存在或已下架=>'.$buyInfo['product_id']]]);
- // 获取产信息
- $productInfo = $productList[$buyInfo['product_id']];
- // 判断是不是可以参与
- if( $productInfo['tag_scope'] ) {
- // 解析数组
- $productInfo['tag_scope'] = explode(',',$productInfo['tag_scope']);
- // 标签范围限定时,默认不能参与
- $allowJoin = 0;
- // 判断标签是不是存在
- foreach ($tags as $value) {
- // 标签范围内,允许参加
- if( in_array($value['name'],$productInfo['tag_scope']) ) $allowJoin = 1;
- }
- // 如果不能参与
- if( !$allowJoin ) return json_send(['code'=>'error','msg'=>'不在 '.$productInfo['product_name'].' 参与范围','data'=>['error'=>'不在标签范围内']]);
- }
- // 判断是不是可以参与
- if( $productInfo['tag_exclude'] ) {
- // 解析数组
- $productInfo['tag_exclude'] = explode(',',$productInfo['tag_exclude']);
- // 判断标签是不是存在
- foreach ($tags as $value) {
- // 标签排除范围内,不允许参加
- if( in_array($value['name'],$productInfo['tag_exclude']) ) return json_send(['code'=>'error','msg'=>'不在 '.$productInfo['product_name'].' 可参与范围','data'=>['error'=>'用户在标签排除范围']]);
- }
- }
- // 如果产品限购
- if( $productInfo['quota'] ) {
- // 是否在限购时间,当前时间大于开始时间,并且小于结束时间
- if( $productInfo['quota_start'] <= $time && $time <= $productInfo['quota_end'] ){
- // 通过时间查询商品的购买总数
- $total = $OrdersProduct->query()->whereIn('status',[0,1,2,3,8,9])->where([['custom_uid','=',$uid],['is_rebate','=',0],['product_id','=',$productInfo['id']],['insert_time','>=',$productInfo['quota_start']],['insert_time','<=',$productInfo['quota_end']]])->sum('buy_num');
- // 判断限购数量
- $total = $buyNum[$buyInfo['product_id']] + $total;
- // 如果超过数量
- if( $total > $productInfo['quota'] ) return json_send(['code'=>'error','msg'=>'限购'.$productInfo['quota'].'单-'.$productInfo['product_name'],'data'=>['error'=>'已超限=>'.($total - $productInfo['quota'])]]);
- }
- }
- // 如果有限制产品的SKU起购规则是与
- if( $productInfo['sku_min_quota_and'] ){
- // 查询该产品的所有SKU
- $skuMin = $ProductSkus->getListByProductId($productInfo['id']);
- // 循环产品的SKU
- foreach ($skuMin as $key => $value) {
- // 如果SKU不限制起购数量,跳过
- if( !$value['min_quota'] ) continue;
- // 如果限购的SKU不在购买列表中
- if( !in_array($value['id'],array_column($buyList,'product_skuid')) ) return json_send(['code'=>'error','msg'=>'请搭配'.$productInfo['product_name'].'【'.$value['attr_names'].'】下单','data'=>['error'=>'最少购买'.$value['min_quota'].'单-'.$productInfo['product_name']]]);;
- // 如果购买数量小于最低起购数量
- foreach ($buyList as $item) {
- // 如果SKU不匹配,跳过
- if( $item['product_skuid'] != $value['id'] ) continue;
- // 如果购买数量小于最低起购数量
- if( $item['buy_num'] < $value['min_quota'] ) return json_send(['code'=>'error','msg'=>'最少购买'.$value['min_quota'].'单-'.$productInfo['product_name'].'【'.$value['attr_names'].'】','data'=>['error'=>'最少购买'.$value['min_quota'].'单-'.$productInfo['product_name']]]);
- }
- }
- }
- // 如果存在SKU
- if( $buyInfo['product_skuid'] ) {
- // 判断SKU信息存不存在
- if( empty($skusList[$buyInfo['product_skuid']]) ) return json_send(['code'=>'error','msg'=>'该产品规格不存在或已下架','data'=>['error'=>'SKU不存在或已下架=>'.$buyInfo['product_skuid']]]);
- // 产品ID不匹配的话
- if( $skusList[$buyInfo['product_skuid']]['product_id'] != $buyInfo['product_id'] ) return json_send(['code'=>'error','msg'=>'该产品规格不存在或已下架','data'=>['error'=>'SKU不匹配=>'.$buyInfo['product_skuid']]]);
- // SKU信息
- $skuInfo = $skusList[$buyInfo['product_skuid']];
- // 如果产品有最低起购
- if( $skuInfo['min_quota'] ) {
- // 如果购买数量小于最低起购数量
- if( $buyInfo['buy_num'] < $skuInfo['min_quota'] ){
- // 如果超过数量
- return json_send(['code'=>'error','msg'=>'最少购买'.$skuInfo['min_quota'].'单-'.$productInfo['product_name'].'【'.$skuInfo['sku_attr_names'].'】','data'=>['error'=>'最少购买'.$skuInfo['min_quota'].'单-'.$productInfo['product_name']]]);
- }
- }
- // 如果SKU限购
- if( $skuInfo['quota'] ) {
- // 是否在限购时间,当前时间大于开始时间,并且小于结束时间
- if( $productInfo['quota_start'] <= $time && $time <= $productInfo['quota_end'] ){
- // 通过时间查询商品的购买总数
- $total = $OrdersProduct->query()->whereIn('status',[0,1,2,3,8,9])->where([['custom_uid','=',$uid],['is_rebate','=',0],['product_id','=',$productInfo['id']],['sku_attr_names','=',$skuInfo['sku_attr_names']],['insert_time','>=',$productInfo['quota_start']],['insert_time','<=',$productInfo['quota_end']]])->sum('buy_num');
- // 判断限购数量
- $total = $buyInfo['buy_num'] + $total;
- // 如果超过数量
- if( $total > $skuInfo['quota'] ) return json_send(['code'=>'error','msg'=>'限购'.$skuInfo['quota'].'单-'.$productInfo['product_name'].'【'.$skuInfo['sku_attr_names'].'】','data'=>['error'=>'已超限=>'.($total - $skuInfo['quota'])]]);
- }
- }
- // 删除起购字段,避免影响后续产品最低起购的判定
- unset($skuInfo['min_quota']);
- // 如果SKU存在,合并产品信息
- $productInfo = array_merge($productInfo,$skuInfo);
- // 需要扣除的库存
- $skusList[$buyInfo['product_skuid']]['decr'] = empty($skusList[$buyInfo['product_skuid']]['decr']) ? $buyInfo['buy_num'] : $skusList[$buyInfo['product_skuid']]['decr'] + $buyInfo['buy_num'];
- }
- // 如果产品有最低起购
- if( $productInfo['min_quota'] ) {
- // 如果购买数量小于最低起购数量
- if( $buyNum[$buyInfo['product_id']] < $productInfo['min_quota'] ){
- // 如果超过数量
- return json_send(['code'=>'error','msg'=>'最少购买'.$productInfo['min_quota'].'单-'.$productInfo['product_name'],'data'=>['error'=>'最少购买'.$productInfo['min_quota'].'单-'.$productInfo['product_name']]]);
- }
- }
- // 需要扣除的库存
- $productList[$buyInfo['product_id']]['decr'] = empty($productList[$buyInfo['product_id']]['decr']) ? $buyInfo['buy_num'] : $productList[$buyInfo['product_id']]['decr'] + $buyInfo['buy_num'];
- // 判断库存
- if( $productInfo['stock'] < $productList[$buyInfo['product_id']]['decr'] ) return json_send(['code'=>'error','msg'=>$productInfo['product_name'].'-库存不足','data'=>['error'=>'产品库存不足=>'.$buyInfo['product_id']]]);
- // 计算价值
- $priceTotal = $buyInfo['buy_num'] * $productInfo['price'];
- // 购买信息
- $buyInfo = ['is_rebate'=>0,'custom_uid'=>$uid,'business_id'=>$productInfo['business_id'],'product_id'=>$buyInfo['product_id'],'buy_num'=>$buyInfo['buy_num'],'price_total'=>$priceTotal,'pay_total'=>$priceTotal,'coupon_total'=>0,'product_name'=>$productInfo['product_name'],'sku_attr_names'=>$productInfo['sku_attr_names'],'product_thumb'=>$productInfo['product_thumb']];
- // 获取信息
- if( !isset($orderProduct[$buyInfo['business_id']]) ) $orderProduct[$buyInfo['business_id']] = ['business_id'=>$buyInfo['business_id'],'custom_uid'=>$buyInfo['custom_uid'],'price_total'=>0,'pay_total'=>0,'coupon_total'=>0,'product_list'=>[]];
- // 订单产品
- $orderProduct[$buyInfo['business_id']]['price_total'] += $buyInfo['price_total'];
- $orderProduct[$buyInfo['business_id']]['pay_total'] += $buyInfo['price_total'];
- $orderProduct[$buyInfo['business_id']]['product_list'][] = $buyInfo;
- // 商品优惠信息不存在,创建
- if( !isset($productPrice[$buyInfo['product_id']]) ) $productPrice[$buyInfo['product_id']] = ['price_total'=>0,'rebate_price'=>0];
- // 计算总价
- $productPrice[$buyInfo['product_id']]['price_total'] = $productPrice[$buyInfo['product_id']]['price_total'] + $priceTotal;
- }
- // 优惠券数据
- $couponRebate = $CustomCoupon->getRebatePrice($customCouponId,$uid,$productPrice);
- // 判断是否使用了优惠券
- $usedCoupon = $couponRebate['is_used'];
- // 获取优惠券扣减金额
- $productPrice = $couponRebate['product_price'];
- // 获取优惠券赠品信息
- $rebateProduct = $couponRebate['rebate_product'];
- /*活动优惠数据*/
- $promoList = $PromoProduct->getRebatePrice(array_column($buyList,'product_id'),$uid,$productPrice,$cityId,$tags);
- $promoProductPrice = $promoList['product_price'];
- $promoRebateProduct = $promoList['rebate_product'];
- //订单支付总价
- $orderPayTotal = 0;
- // 组合订单数据
- foreach ($orderProduct as $key => $order) {
- // 判断哪一家的赠品
- if( isset($rebateProduct[$order['business_id']]) ){
- // 循环赠品
- foreach ( $rebateProduct[$order['business_id']] as $value) {
- // 没有对应的产品
- if( !isset($productList[$value['product_id']]) ) $productList[$value['product_id']] = ['id'=>$value['id'],'stock'=>$value['stock']];
- // 判断库存,如果库存不足,只赠送最后的库存
- if( $productList[$value['product_id']]['stock'] <= $value['buy_num'] ) $value['buy_num'] = $productList[$value['product_id']]['stock'];
- // 库存扣减
- $productList[$value['product_id']]['decr'] = empty($productList[$value['product_id']]['decr']) ? $value['buy_num'] : $productList[$value['product_id']]['decr'] + $value['buy_num'];
- // 追加到订单表
- $order['product_list'][] = ['is_rebate'=>1,'custom_uid'=>$uid,'business_id'=>$value['business_id'],'product_id'=>$value['product_id'],'buy_num'=>$value['buy_num'],'price_total'=>$value['price_total'],'pay_total'=>$value['pay_total'],'coupon_total'=>$value['coupon_total'],'product_name'=>$value['product_name'],'sku_attr_names'=>$value['sku_attr_names'],'product_thumb'=>$value['product_thumb']];
- }
- }
- // 促销活动判断哪一家的赠品
- if( isset($promoRebateProduct[$order['business_id']]) ){
- // 循环赠品
- foreach ( $promoRebateProduct[$order['business_id']] as $value) {
- // 没有对应的产品
- if( !isset($productList[$value['product_id']]) ) $productList[$value['product_id']] = ['id'=>$value['product_id'],'stock'=>$value['stock']];
- // 判断库存,如果库存不足,只赠送最后的库存
- if( $productList[$value['product_id']]['stock'] <= $value['buy_num'] ) $value['buy_num'] = $productList[$value['product_id']]['stock'];
- // 库存扣减
- $productList[$value['product_id']]['decr'] = empty($productList[$value['product_id']]['decr']) ? $value['buy_num'] : $productList[$value['product_id']]['decr'] + $value['buy_num'];
- // 追加到订单表
- $order['product_list'][] = ['is_rebate'=>1,'custom_uid'=>$uid,'business_id'=>$value['business_id'],'product_id'=>$value['product_id'],'buy_num'=>$value['buy_num'],'price_total'=>$value['price_total'],'pay_total'=>$value['pay_total'],'coupon_total'=>$value['coupon_total'],'sku_attr_names'=>$value['sku_attr_names'],'product_name'=>$value['name'],'product_thumb'=>$value['thumb']];
- }
- }
- // 计算总价格
- foreach ($order['product_list'] as $k=>$product) {
- //促销活动扣减
- if (isset($promoProductPrice[$product['product_id']]['promo_rebate_price']) && $promoProductPrice[$product['product_id']]['promo_rebate_price']> 0){
- // 总优惠增加
- $order['coupon_total'] = $order['coupon_total'] + $promoProductPrice[$product['product_id']]['promo_rebate_price'];
- // 当前商品的优惠折扣计算
- $product['coupon_total'] = number_format( $promoProductPrice[$product['product_id']]['promo_rebate_price'] * ($product['price_total'] / $promoProductPrice[$product['product_id']]['price_total']) , 2 , '.' ,'');
- // 成交小计
- $product['pay_total'] = bcsub($product['pay_total'],$product['coupon_total'],2);
- }
- // 商品不存在,不进行扣减
- if( empty($productPrice[$product['product_id']]['rebate_price']) ) {
- // 重组
- $order['product_list'][$k] = $product;
- continue;
- }
- // 当前商品的优惠折扣计算
- $product['coupon_total'] = number_format( $productPrice[$product['product_id']]['rebate_price'] * ($product['price_total'] / $productPrice[$product['product_id']]['price_total']) , 2 , '.' ,'');
- // 总优惠增加
- $order['coupon_total'] = bcadd($order['coupon_total'],$product['coupon_total'],2);
- // 成交小计
- $product['pay_total'] = bcsub($product['pay_total'],$product['coupon_total'],2);
- // 重组
- $order['product_list'][$k] = $product;
- }
- // 成交总价
- $order['pay_total'] = bcsub($order['pay_total'],$order['coupon_total'],2);
- if ($order['pay_total'] <= 0) $order['pay_total'] = 0.01;
- $orderPayTotal = bcadd($orderPayTotal, $order['pay_total'],2);
- // 赠送积分
- $order['order_score'] = (config('order_score_send',0) && floor( $order['pay_total'] * 1 ) > 0 ) ? floor( $order['pay_total'] * 1 ) : 0;
- // 成交总价
- $order['custom_uid'] = $uid;
- // 重组
- $orderProduct[$key] = $order;
- }
- // 组合数据,写入订单表,子表
- DB::beginTransaction();
- // 写入数据
- try {
- // 扣减商品库存
- foreach ($productList as $key => $value) {
- // 扣减库存
- $result = $Product->edit($value['id'],['stock'=>DB::raw('stock+-'.$value['decr'])]);
- // 判断结果
- if( !$result ) {
- // 回退数据
- DB::rollBack();
- // 错误提示
- return json_send(['code'=>'error','msg'=>'库存扣减失败','data'=>['error'=>'库存扣减失败']]);
- }
- }
- // 扣减商品库存
- foreach ($skusList as $key => $value) {
- // 扣减库存
- $result = $ProductSkus->edit($value['sku_id'],['stock'=>DB::raw('stock+-'.$value['decr'])]);
- // 判断结果
- if( !$result ) {
- // 回退数据
- DB::rollBack();
- // 错误提示
- return json_send(['code'=>'error','msg'=>'库存扣减失败','data'=>['error'=>'库存扣减失败']]);
- }
- }
- // 循环订单数据
- foreach ($orderProduct as $order) {
- // 先获取产品列表,并去除key
- $productItem = array_values($order['product_list']);
- // 删除非必要数据
- unset($order['product_list']);
- $order['snowflake_id'] = $SnowflakeId;
- $order['is_pay'] = $isPay;
- $order['status'] = $isPay ? 0 : 1;
- // 创建总订单
- $orderId = $Model->add($order);
- // 如果订单写入失败
- if( !$orderId ) {
- // 回退数据
- DB::rollBack();
- // 错误提示
- return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'订单创建失败']]);
- }
- // 创建子订单
- foreach ($productItem as $key=>$value) {
- // 增加订单ID
- $value['order_id'] = $orderId;
- $value['status'] = $isPay ? 0 : 1;
- // 增加订单ID
- $value['insert_time']= $time;
- $value['update_time']= $time;
- // 结果
- $productItem[$key] = $value;
- }
- // 写入子表
- $result = $OrdersProduct->query()->insert($productItem);
- // 如果扣减失败
- if( !$result ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'子订单创建失败','data'=>['error'=>'子订单创建失败']]);
- }
- // 写入订单地址表
- $addr['order_id'] = $orderId;
- // 写入订单地址表
- $result = $OrdersAddr->add($addr);
- // 地址写入失败
- if( !$result ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'地址写入失败','data'=>['error'=>'地址写入失败']]);
- }
- if ($isPay == 0) {
- // 赠送积分
- if( $order['order_score'] > 0 ) $CustomScore->trade($order['custom_uid'],$orderId,$order['order_score'],5,1);
- }
- // 如果使用了优惠券
- if( $usedCoupon ) $CustomCoupon->edit($usedCoupon,['status'=>1,'order_id'=>$orderId]);
- // 购物车
- if( $isCart ) $ShopCart->query()->whereIn('id',array_column($buyList,'shop_cart_id'))->delete();
- }
- // 自动发放优惠券
- $this->autoCoupon($uid);
- // 提交数据
- DB::commit();
- $data = [
- 'order_id' =>$orderId,
- 'pay_total' =>$orderPayTotal,
- 'snowflake_id' =>$SnowflakeId,
- ];
- // 返回结果
- return json_send(['code'=>'success','msg'=>'下单成功','data'=>$data]);
- // 返回结果
- } catch (\Throwable $th) {
- // 回退数据
- DB::rollBack();
- // 判断结果,如果库存扣减失败的话
- if( stripos($th->getMessage(),'UNSIGNED') ) return json_send(['code'=>'error','msg'=>'库存不足','data'=>['error'=>'产品库存扣减失败']]);
- // 下单失败提示
- return json_send(['code'=>'error','msg'=>'系统异常,请稍后再试','data'=>['error'=>$th->getMessage().$th->getLine()]]);
- }
- }
- /**
- * 获取列表 /api/orders/get_list
- *
- * @param string $name 产品名称
- * @param int $page 页码,默认1
- * @param int $limit 每页条数,默认10条
- *
- * */
- public function get_list(Request $request, Model $Model, OrdersProduct $OrdersProduct, Business $Business){
- // 接口验签
- // $this->verify_sign();
- // 验证参数
- $request->scene('get_list')->validate();
- // 检查登录
- $uid = $this->checkLogin();
- // 接收参数
- $status = request('status',0);
- $limit = request('limit',10);
- // 显示
- $map = [['custom_uid','=',$uid]];
- // 查询状态
- if( $status ) $map[] = ['status','=',$status];
- // 查询
- $Paginator = $Model->query()->where($map)->orderByDesc('id')->paginate($limit,['id','regiment_id','is_pay','pay_total','status','price_total','coupon_total','business_id','pay_total','weizan_orderid','insert_time']);
- // 订单产品
- $productList = $OrdersProduct->query()->whereIn('order_id', array_column($Paginator->items(),'id'))->select(['id as item_id','order_id','product_id','buy_num','is_rebate','sku_attr_names as product_spec','product_name','product_thumb'])->get()->toArray();
- // 循环处理
- foreach ($Paginator as $key => $order) {
- // 商品列表
- $itemList = [];
- // 返回结果
- foreach ($productList as $item) {
- // 产品图路径
- $item['product_thumb'] = path_compat($item['product_thumb']);
- // 如果是订单的
- if( $item['order_id'] == $order['id'] ) $itemList[] = $item;
- }
- // 获取子列表
- $order['state'] = (string) $Model->getState($order['status'],'state');
- // 获取子列表
- $order['business_name'] = (string) ($order['business_id'] ? $Business->getOne($order['business_id'],'name') : ($order['weizan_orderid'] ? '微赞订单' : ''));
- // 获取子列表
- $order['contents_class']= 0;
- // 获取子列表
- $order['product_list'] = $itemList;
- // 重组
- $Paginator[$key] = $order;
- }
- // 获取数据
- $data['total'] = $Paginator->total();
- $data['current_page'] = $Paginator->currentPage();
- $data['per_page'] = $Paginator->perPage();
- $data['last_page'] = $Paginator->lastPage();
- $data['data'] = $Paginator->items();
- // 返回结果
- return json_send(['code'=>'success','msg'=>'获取成功','data'=>$data]);
- }
- /**
- * 自动发放优惠券
- *
- */
- private function autoCoupon($uid){
- // 模型实例
- $Rule = new \App\Models\CouponRewardRule();
- // 获取配置列表
- $ruleList = $Rule->getList();
- // 如果没有信息的话
- if( !$ruleList ) return ['success'=>'暂无活动'];
- // 其他实例
- $RuleProduct = new \App\Models\CouponRewardProduct();
- $OrdersProduct = new \App\Models\OrdersProduct();
- $Custom = new \App\Models\Custom();
- $Coupon = new \App\Models\Coupon();
- $CustomCoupon = new \App\Models\CustomCoupon();
- // 获取客户城市ID
- $customCityId = (int) $Custom->getValue($uid,'city_id');
- // 循环配置列表
- foreach ( $ruleList as $value ) {
- // 如果存在城市范围,并且不在城市范围,不参与这个活动
- if( $value['city_ids'] && !in_array($customCityId,explode(',',$value['city_ids'])) ) continue;
- // 未到开始时间
- if( $value['start_time'] > time() ) continue;
- // 通过配置ID获取对应的商品范围
- $productList = $RuleProduct->getListByRule($value['id']);
- // 如果不存在产品范围,跳过
- if( !$productList ) continue;
- // 获取客户 规定时段内订单的商品ID以及购买数量
- $orderList = $OrdersProduct->query()->where([['custom_uid','=',$uid],['status','=',1],['insert_time','>=',$value['start_time']],['insert_time','<=',$value['end_time']]])->get(['product_id','buy_num'])->toArray();
- // 如果没有订单总数
- if( !$orderList ) continue;
- // 计算商品总量
- $total = 0;
- // 循环商品范围
- foreach ($productList as $scope) {
- // 循环订单产品
- foreach ($orderList as $order) {
- // 如果产品不相等
- if( $scope['product_id'] != $order['product_id'] ) continue;
- // 相等的计算总量
- $total += $scope['product_units'] * $order['buy_num'];
- }
- }
- // 判断总数是不是达标
- if( $total < $value['std_num'] ) continue;
- if ($value['coupon_id']){
- $couponIdArray = explode(',',$value['coupon_id']);
- foreach ($couponIdArray as $couponId) {
- // 达标的是否已经发送过优惠券
- $havaCoupon = $CustomCoupon->query()->where([['custom_uid','=',$uid],['coupon_id','=',$couponId]])->first(['status']);
- // 已经发过优惠券的,不发
- if( $havaCoupon ) continue;
- // 获取优惠券的可用时间
- $expTime = $Coupon->query()->where([['id','=',$couponId]])->value('exp_time');
- // 时间转时间
- $expTime = $Coupon->getExpTime($expTime);
- // 发送优惠券
- $CustomCoupon->add(['coupon_id'=>$couponId,'custom_uid'=>$uid,'exp_time'=>$expTime]);
- }
- }
- }
- // 返回成功
- return ['success'=>'操作成功'];
- }
- /**
- * 取消 /api/orders/cancel
- *
- * */
- public function cancel( Request $request, Model $Model,OrdersProduct $OrdersProduct,CustomScore $CustomScore){
- // 验证参数
- $request->scene('cancel')->validate();
- // 检查登录
- $uid = $this->checkLogin();
- // 接收参数
- $id = request('id',0);
- $status = 4;
- // 获取产品和数量
- $oldData = $Model->query()->where([['id','=',$id],['custom_uid','=',$uid]])->first(['id','order_score','status','custom_uid','insert_time']);
- // 如果用户不存在
- if( !$oldData ) return json_send(['code'=>'error','msg'=>'订单不存在']);
- // 如果已经取消
- if( $oldData['status'] == 4 ) return json_send(['code'=>'error','msg'=>'订单已取消']);
- // 组合数据,写入订单表,子表
- DB::beginTransaction();
- try{
- // 查询数据
- $result = $Model->setOrderStatus($id,$status,$OrdersProduct);
- // 提示新增失败
- if( isset($result['error']) ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>$result['error'],'data'=>['error'=>$result['error']]]);
- }
- if( $status == 4 ){
- // 取消积分
- if( $oldData['order_score'] > 0 ) {
- // 如果扣减失败
- $result = $CustomScore->trade($oldData['custom_uid'],$oldData['id'],($oldData['order_score']*-1),6,1);
- // 提示新增失败
- if( isset($result['error']) ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'取消赠送积分失败','data'=>['error'=>$result['error']]]);
- }
- }
- // 取消关联订单
- $result = $Model->cancelRelate($oldData['insert_time'],$oldData['custom_uid'],$OrdersProduct,$CustomScore);
- // 提示新增失败
- if( isset($result['error']) ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'取消关联订单失败','data'=>['error'=>$result['error']]]);
- }
- }
- // 提交数据
- DB::commit();
- // 告知结果
- return json_send(['code'=>'success','msg'=>'取消成功']);
- // 返回结果
- } catch (\Throwable $th) {
- // 回退数据
- DB::rollBack();
- // 下单失败提示
- return json_send(['code'=>'error','msg'=>'取消失败','data'=>['error'=>$th->getMessage().$th->getLine()]]);
- }
- }
- /**
- * 获取订单子数据 /api/orders/get_item
- *
- * @param string $name 产品名称
- * @param int $page 页码,默认1
- * @param int $limit 每页条数,默认10条
- *
- * */
- public function get_item(Request $request, Model $Model, OrdersProduct $OrdersProduct, Business $Business){
- // 接口验签
- // $this->verify_sign();
- // 验证参数
- $request->scene('get_item')->validate();
- // 检查登录
- $uid = $this->checkLogin();
- // 接收参数
- $id = request('id',0);
- // 查询
- $orderInfo = $Model->query()->where([['id','=',$id],['custom_uid','=',$uid]])->first(['id','pay_total','status','price_total','coupon_total','business_id','pay_total','weizan_orderid','insert_time']);
- // 如果用户不存在
- if( !$orderInfo ) return json_send(['code'=>'error','msg'=>'订单不存在']);
- // 转数组
- $orderInfo = $orderInfo->toArray();
- // 订单产品
- $orderInfo['product_list'] = $OrdersProduct->query()->where([['order_id','=',$id]])->select(['id as item_id','order_id','product_id','buy_num','is_rebate','sku_attr_names as product_spec','product_name','product_thumb'])->get()->toArray();
- // 循环处理
- foreach ($orderInfo['product_list'] as $key => $item) {
- // 产品图路径
- $item['product_thumb'] = path_compat($item['product_thumb']);
- // 重组
- $orderInfo['product_list'][$key] = $item;
- }
- // 获取子列表
- $orderInfo['state'] = (string) $Model->getState($orderInfo['status'],'state');
- // 获取子列表
- $orderInfo['business_name'] = (string) ($orderInfo['business_id'] ? $Business->getOne($orderInfo['business_id'],'name') : ($orderInfo['weizan_orderid'] ? '微赞订单' : ''));
- // 返回结果
- return json_send(['code'=>'success','msg'=>'获取成功','data'=>$orderInfo]);
- }
- /**
- * 创建拼团订单 /api/orders/create_regiment
- *
- * */
- public function create_regiment(Request $request,Custom $Custom,City $City,Model $Model,WeiBanTags $WeiBanTags,OrdersAddr $OrdersAddr,OrdersProduct $OrdersProduct,Product $Product,CustomAddr $CustomAddr,CustomScore $CustomScore){
- // 接口验签
- // $this->verify_sign();
- // 验证参数
- $request->scene('create')->validate();
- // 检查登录
- $uid = $this->checkLogin();
- // 接收参数
- $productList = request('product_list','[]');
- $addrId = request('addr_id',0);
- $regimentId = request('regiment_id',0);
- $regimentActiveId = request('regiment_active_id',0);
- $btnType = request('btn_type',0);
- $isPay = request('is_pay',0);
- $Snowflake = new Snowflake();
- $SnowflakeId = $Snowflake->next();
- // 如果不存在数据
- if( !$addrId ) return json_send(['code'=>'error','msg'=>'请选择收货地址','data'=>['error'=>'请选择收货地址']]);
- // 解码购买信息
- $buyList = json_decode($productList,true);
- // 如果不存在数据
- if( empty($buyList) ) return json_send(['code'=>'error','msg'=>'没有需下单的产品','data'=>['error'=>'产品列表为空']]);
- $time = time();
- // 选择地址
- $addr = $CustomAddr->getOne($addrId);
- // 如果不存在数据
- if( !$addr ) return json_send(['code'=>'error','msg'=>'地址有误,请核对','data'=>['error'=>'没有找到对应的地址']]);
- // 重组数据
- $addr = ['contact_name'=>$addr['contact_name'],'contact_shop'=>$addr['contact_shop'],'contact_phone'=>$addr['contact_phone'],'contact_province'=>$addr['contact_province'],'contact_city'=>$addr['contact_city'],'contact_area'=>$addr['contact_area'],'contact_addr'=>$addr['contact_addr']];
- // 获取客户城市ID
- $custom = $Custom->getOne($uid);
- // 如果不存在的话
- if( !$custom ) return json_send(['code'=>'no_login','msg'=>'用户不存在,请重新登录','data'=>['error'=>'用户不存在,请重新登录']]);
- // 如果不存在的话
- if( !$custom['city_id'] ) return json_send(['code'=>'error','msg'=>'请选择所在城市后下单','data'=>['error'=>'请选择所在城市后下单']]);
- // 获取城市ID
- $cityId = $custom['city_id'];
- $cityName = $City->getOne($cityId,'name');
- $pid = $City->getOne($cityId,'pid');
- // 如果上级不是省份
- if( strlen($cityId) > 4 ) $pid = (int) $City->getOne($pid,'pid');
- // 获取省份
- $province = $City->getOne($pid,'name');
- // 如果不是海南,
- if( $province != '海南省' ) {
- // 判断选择的城市名称是不是一致
- if( $cityName != $addr['contact_city'] ) return json_send(['code'=>'error','msg'=>'收货地址请选择'.$province.'/'.$cityName,'data'=>['error'=>'收货地址需与您所选城市一致']]);
- }else{
- if( trim($addr['contact_province']) != trim($province) ) return json_send(['code'=>'error','msg'=>'收货地址请选择海南范围','data'=>['error'=>'收货地址需与您所选城市一致']]);
- }
- //获取团活动信息
- $regimentActiveInfo = RegimentActive::query()->where([['id','=',$regimentActiveId],['status','=',1],['start_time','<=',$time],['end_time','>=',$time]])->first();
- // 拼团结果
- if (!$regimentActiveInfo) return json_send(['code'=>'error','msg'=>'拼团活动不存在','data'=>['error'=>'拼团活动不存在']]);
- //是否符合开团条件
- if($btnType == 3){
- if ($regimentActiveInfo['open_people'] == 1){
- if ($custom['insert_time'] > $regimentActiveInfo['start_time']) return json_send(['code'=>'error','msg'=>'此活动只允许老用户开团','data'=>['error'=>'此活动只允许老用户开团']]);
- }
- if ($regimentActiveInfo['open_people'] == 2){
- if ($custom['insert_time'] < $regimentActiveInfo['start_time']) return json_send(['code'=>'error','msg'=>'此活动只允许新用户开团','data'=>['error'=>'此活动只允许新用户开团']]);
- }
- }
- //是否符合参团条件
- if($btnType == 4){
- if ($regimentActiveInfo['partake_people'] == 1){
- if ($custom['insert_time'] > $regimentActiveInfo['start_time']) return json_send(['code'=>'error','msg'=>'此活动只允许老用户参与','data'=>['error'=>'此活动只允许老用户开团']]);
- }
- if ($regimentActiveInfo['partake_people'] == 2){
- if ($custom['insert_time'] < $regimentActiveInfo['start_time']) return json_send(['code'=>'error','msg'=>'此活动只允许新用户参与','data'=>['error'=>'此活动只允许新用户开团']]);
- }
- //查询团信息
- $regimentInfo = Regiment::query()
- ->where([['id','=',$regimentId],['status','=',0],['start_time','<=',$time],['end_time','>=',$time]])
- ->first();
- if (!$regimentInfo) return json_send(['code'=>'error','msg'=>'拼团活动不存在','data'=>['error'=>'拼团活动不存在']]);
- $regimentRecordres = RegimentRecord::query()
- ->where([['custom_uid','=',$uid],['regiment_id','=',$regimentId]])
- ->first();
- if ($regimentRecordres) return json_send(['code'=>'error','msg'=>'您已参与此拼团','data'=>['error'=>'您已参与此拼团']]);
- }
- //查询用户参团记录
- $regimentRecordCount = RegimentRecord::query()
- ->where([['custom_uid','=',$uid],['active_id','=',$regimentActiveInfo['id']]])
- ->count('id');
- if ($regimentRecordCount >= $regimentActiveInfo['participation_number']) return json_send(['code'=>'error','msg'=>'该活动每人仅限参与'.$regimentActiveInfo['participation_number'].'次','data'=>['error'=>'该活动每人仅限参与'.$regimentActiveInfo['participation_number'].'次']]);
- // 标签信息
- $tags = $WeiBanTags->getListByWeibanExtid($custom['weiban_extid']);
- // 查询产品信息
- $productList = $Product->getListByIds(array_column($buyList,'product_id'));
- // 当前时间
- $time = time();
- $priceTotal = 0;
- $payTotal = 0;
- $buyInfo = $buyList[0];
- if ($buyInfo){
- if( empty($productList[$buyInfo['product_id']]) ) return json_send(['code'=>'error','msg'=>'产品不存在或已下架','data'=>['error'=>'产品不存在或已下架=>'.$buyInfo['product_id']]]);
- // 获取产信息
- $productInfo = $productList[$buyInfo['product_id']];
- // 判断是不是可以参与
- if( $productInfo['tag_scope'] ) {
- // 解析数组
- $productInfo['tag_scope'] = explode(',',$productInfo['tag_scope']);
- // 标签范围限定时,默认不能参与
- $allowJoin = 0;
- // 判断标签是不是存在
- foreach ($tags as $value) {
- // 标签范围内,允许参加
- if( in_array($value['name'],$productInfo['tag_scope']) ) $allowJoin = 1;
- }
- // 如果不能参与
- if( !$allowJoin ) return json_send(['code'=>'error','msg'=>'不在 '.$productInfo['product_name'].' 参与范围','data'=>['error'=>'不在标签范围内']]);
- }
- // 判断是不是可以参与
- if( $productInfo['tag_exclude'] ) {
- // 解析数组
- $productInfo['tag_exclude'] = explode(',',$productInfo['tag_exclude']);
- // 判断标签是不是存在
- foreach ($tags as $value) {
- // 标签排除范围内,不允许参加
- if( in_array($value['name'],$productInfo['tag_exclude']) ) return json_send(['code'=>'error','msg'=>'不在 '.$productInfo['product_name'].' 可参与范围','data'=>['error'=>'用户在标签排除范围']]);
- }
- }
- //拼团活动限购
- if ($regimentActiveInfo['quota']){
- if ($buyInfo['buy_num'] > $regimentActiveInfo['quota']) return json_send(['code'=>'error','msg'=>'超过拼团限购','data'=>['error'=>'拼团限购=>'.$buyInfo['product_id']]]);
- }
- // 如果产品限购
- if( $productInfo['quota'] ) {
- // 是否在限购时间,当前时间大于开始时间,并且小于结束时间
- if( $productInfo['quota_start'] <= $time && $time <= $productInfo['quota_end'] ){
- // 通过时间查询商品的购买总数
- $total = $OrdersProduct->query()->where([['custom_uid','=',$uid],['product_id','=',$productInfo['id']],['insert_time','>=',$productInfo['quota_start']],['insert_time','<=',$productInfo['quota_end']]])->sum('buy_num');
- // 判断限购数量
- $total = $buyInfo['buy_num'] + $total;
- // 如果超过数量
- if( $total > $productInfo['quota'] ) return json_send(['code'=>'error','msg'=>'限购'.$productInfo['quota'].'单-'.$productInfo['product_name'],'data'=>['error'=>'已超限=>'.($total - $productInfo['quota'])]]);
- }
- }
- // 需要扣除的库存
- $productList[$buyInfo['product_id']]['decr'] = $buyInfo['buy_num'];
- // 判断库存
- if( $productInfo['stock'] < $productList[$buyInfo['product_id']]['decr'] ) return json_send(['code'=>'error','msg'=>$productInfo['product_name'].'-库存不足','data'=>['error'=>'产品库存不足=>'.$buyInfo['product_id']]]);
- // 计算价值
- $priceTotal = $buyInfo['buy_num'] * $productInfo['price'];
- $payTotal = $buyInfo['buy_num'] * $regimentActiveInfo['regiment_price'];
- }
- $orderInfo = [
- 'custom_uid' => $uid,
- 'status' => $isPay ? 0 : 10,
- 'insert_time' => $time,
- 'update_time' => $time,
- 'pay_total' => $payTotal,
- 'price_total' => $priceTotal,
- 'business_id' => $productList[$buyInfo['product_id']]['business_id'],
- 'snowflake_id' => $SnowflakeId,
- ];
- // 赠送积分
- $orderInfo['order_score'] = (config('order_score_send',0) && floor( $orderInfo['pay_total'] * 1 ) > 0 ) ? floor( $orderInfo['pay_total'] * 1 ) : 0;
- $orderProductInfo = [
- 'product_name' => $productList[$buyInfo['product_id']]['product_name'],
- 'sku_attr_names' => $productList[$buyInfo['product_id']]['sku_attr_names'],
- 'product_thumb' => $productList[$buyInfo['product_id']]['product_thumb'],
- 'buy_num' => $buyInfo['buy_num'],
- 'price_total' => $priceTotal,
- 'pay_total' => $buyInfo['buy_num'] * $productList[$buyInfo['product_id']]['price'],
- 'product_id' => $buyInfo['product_id'],
- 'custom_uid' => $uid,
- 'business_id' => $productList[$buyInfo['product_id']]['business_id'],
- 'insert_time' => $time,
- 'update_time' => $time,
- 'status' => $isPay ? 0 : 10,
- ];
- // 组合数据,写入订单表,子表
- DB::beginTransaction();
- // 写入数据
- try {
- // 扣减商品库存
- foreach ($productList as $key => $value) {
- // 扣减库存
- $result = $Product->edit($value['id'],['stock'=>DB::raw('stock+-'.$value['decr'])]);
- // 判断结果
- if( !$result ) {
- // 回退数据
- DB::rollBack();
- // 错误提示
- return json_send(['code'=>'error','msg'=>'库存扣减失败','data'=>['error'=>'库存扣减失败']]);
- }
- }
- //创建拼团
- if($btnType == 3){
- $regimentInfo = [
- 'custom_uid' => $uid,
- 'active_id' => $regimentActiveInfo['id'],
- 'product_id' => $buyInfo['product_id'],
- 'people_number' => $isPay ? 0 : 1,
- 'status' => $isPay ? 4 : 0,
- 'start_time' => $time,
- 'end_time' => $time + $regimentActiveInfo['expiration']*3600,
- 'update_time' => $time,
- 'insert_time' => $time,
- ];
- $regimentId = Regiment::query()->insertGetId($regimentInfo);
- if( !$regimentId ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'创建拼团失败','data'=>['error'=>'创建拼团失败']]);
- }
- }
- $orderInfo['regiment_id'] = $regimentId;
- $orderInfo['is_pay'] = $isPay;
- // 创建总订单
- $orderId = $Model->add($orderInfo);
- // 如果订单写入失败
- if( !$orderId ) {
- // 回退数据
- DB::rollBack();
- // 错误提示
- return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'订单创建失败']]);
- }
- $orderProductInfo['order_id'] = $orderId;
- // 写入子表
- $result = $OrdersProduct->query()->insert($orderProductInfo);
- // 如果扣减失败
- if( !$result ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'子订单创建失败','data'=>['error'=>'子订单创建失败']]);
- }
- // 写入订单地址表
- $addr['order_id'] = $orderId;
- // 写入订单地址表
- $result = $OrdersAddr->add($addr);
- // 地址写入失败
- if( !$result ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'地址写入失败','data'=>['error'=>'地址写入失败']]);
- }
- //拼团记录
- $regimentRecordInfo = [
- 'custom_uid' => $uid,
- 'regiment_id' => $regimentId,
- 'active_id' => $regimentActiveInfo['id'],
- 'product_id' => $buyInfo['product_id'],
- 'order_id' => $orderId,
- 'status' => $isPay ? 4 : 0,
- 'update_time' => $time,
- 'insert_time' => $time,
- ];
- if($btnType == 4 && $isPay == 0){
- // 拼团人数加1
- $inc = Regiment::query()->where('id','=',$regimentId)->increment('people_number',1);
- if( !$inc ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'参与拼团失败','data'=>['error'=>'参与拼团失败']]);
- }
- //团满
- if ((($regimentInfo['people_number'] + 1) == $regimentActiveInfo['number']) && $regimentActiveInfo['exceed_people'] == 1) {
- $res = Regiment::query()->where('id','=',$regimentId)->update(['status'=>2]);
- if( !$res ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'修改成团状态失败','data'=>['error'=>'参与拼团失败']]);
- }
- //修改订单
- $orderRes = $Model::query()->where('regiment_id','=',$regimentId)->update(['status'=>'1']);
- if( !$orderRes ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'修改订单状态失败','data'=>['error'=>'参与拼团失败']]);
- }
- // 查询拼团对应的订单
- $orderIds = $Model::query()->where('regiment_id','=',$regimentId)->pluck('id')->toArray();
- // 修改这些订单的子订单状态
- $orderProductRes = $OrdersProduct::query()->whereIn('order_id',$orderIds)->update(['status'=>'1']);
- // 修改
- if( !$orderProductRes ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'修改子订单状态失败','data'=>['error'=>'参与拼团失败']]);
- }
- //赠送积分
- $orderList = $Model::query()->where('regiment_id','=',$regimentId)->get();
- foreach ($orderList as $key => $value) {
- if( $value['order_score'] > 0 ) $CustomScore->trade($orderInfo['custom_uid'],$value['id'],$value['order_score'],5,1);
- }
- // 修改所有参团中的为已成功
- $result = RegimentRecord::query()->where([['regiment_id','=',$regimentId],['status','=',0]])->update(['status'=>2]);
- if( !$result ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'创建拼团记录失败','data'=>['error'=>'创建拼团记录失败']]);
- }
- // 拼团成功
- $regimentRecordInfo['status'] = 2;
- }
- }
- $result = RegimentRecord::query()->insert($regimentRecordInfo);
- if( !$result ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'创建拼团记录失败','data'=>['error'=>'创建拼团记录失败']]);
- }
- // 提交数据
- DB::commit();
- $data = [
- 'order_id' =>$orderId,
- 'pay_total' =>$orderInfo['pay_total'],
- 'snowflake_id' =>$orderInfo['snowflake_id'],
- ];
- // 返回结果
- return json_send(['code'=>'success','msg'=>'拼团成功','data'=>$data]);
- // 返回结果
- } catch (\Throwable $th) {
- // 回退数据
- DB::rollBack();
- // 判断结果,如果库存扣减失败的话
- if( stripos($th->getMessage(),'UNSIGNED') ) return json_send(['code'=>'error','msg'=>'库存不足','data'=>['error'=>'产品库存扣减失败']]);
- // 下单失败提示
- return json_send(['code'=>'error','msg'=>'系统异常,请稍后再试','data'=>['error'=>$th->getMessage().$th->getLine()]]);
- }
- }
- /**
- * 取消拼团 /api/orders/cancel_regiment
- *
- * */
- public function cancel_regiment( Request $request, Model $Model,OrdersProduct $OrdersProduct){
- // 验证参数
- $request->scene('cancel')->validate();
- // 检查登录
- $uid = $this->checkLogin();
- // 接收参数
- $id = request('id',0);
- $status = 12;
- // 获取产品和数量
- $oldData = $Model->query()->where([['id','=',$id],['custom_uid','=',$uid]])->first(['id','order_score','status','custom_uid','insert_time','regiment_id']);
- // 如果用户不存在
- if( !$oldData ) return json_send(['code'=>'error','msg'=>'订单不存在']);
- // 如果已经取消
- if( $oldData['status'] == 12 ) return json_send(['code'=>'error','msg'=>'订单已取消']);
- // 如果团不存在
- if( !$oldData['regiment_id'] ) return json_send(['code'=>'error','msg'=>'拼团不存在']);
- //查询团信息
- $regimentInfo = Regiment::query()->find($oldData['regiment_id']);
- if( !$regimentInfo ) return json_send(['code'=>'error','msg'=>'拼团不存在']);
- // 组合数据,写入订单表,子表
- DB::beginTransaction();
- try{
- // 查询数据
- $result = $Model->setOrderStatus($id,$status,$OrdersProduct);
- // 提示新增失败
- if( isset($result['error']) ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>$result['error'],'data'=>['error'=>$result['error']]]);
- }
- //开团用户取消团订单
- if ($regimentInfo['people_number'] > 1 && $regimentInfo['custom_uid'] == $uid){
- //查询团记录
- $regimentRecordInfo = RegimentRecord::query()->where([['order_id','<>',$oldData['id']],['regiment_id','=',$regimentInfo['id']],['status','=',0]])->first();
- if ($regimentRecordInfo){
- //将参团成员中的第一个用户变成开团人
- $result = Regiment::query()->where('id','=',$regimentRecordInfo['regiment_id'])->update(['custom_uid'=>$regimentRecordInfo['custom_uid'],'update_time'=>time()]);
- if (!$result) {
- DB::rollBack();
- return json_send(['code'=>'error','msg'=>'取消拼团,改变开团人失败']);
- }
- }
- //扣减加入团人数
- $regimentRes = Regiment::query()->where('id','=',$oldData['regiment_id'])->decrement('people_number',1);
- if( !$regimentRes ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'扣减开团成员失败']);
- }
- }else{
- $regimentRes = Regiment::query()->where('id','=',$oldData['regiment_id'])->update(['status'=>1,'update_time'=>time()]);
- if (!$regimentRes){
- DB::rollBack();
- return json_send(['code'=>'error','msg'=>'取消拼团失败']);
- }
- }
- //修改拼团记录
- $regimentRes = RegimentRecord::query()->where([['order_id','=',$oldData['id']]])->update(['status'=>'1','update_time'=>time()]);
- if( !$regimentRes ) {
- // 回退数据
- DB::rollBack();
- // 提示信息
- return json_send(['code'=>'error','msg'=>'修改拼团记录失败']);
- }
- // 提交数据
- DB::commit();
- // 告知结果
- return json_send(['code'=>'success','msg'=>'取消成功']);
- // 返回结果
- } catch (\Throwable $th) {
- // 回退数据
- DB::rollBack();
- // 下单失败提示
- return json_send(['code'=>'error','msg'=>'取消失败','data'=>['error'=>$th->getMessage().$th->getLine()]]);
- }
- }
- /**
- * 订单详情
- *
- * @pamam int $id 订单ID
- *
- * */
- public function get_detail( Request $request, Model $Model,OrdersProduct $OrdersProduct,Business $Business,OrdersAddr $OrdersAddr){
- // 验证参数
- $request->scene('get_detail')->validate();
- // 接受参数
- $id = request('id',0);
- // 查询数据
- $order = $Model->query()->find($id,['id','pay_total','status','price_total','coupon_total','business_id','pay_total','weizan_orderid','insert_time']);
- // 查询不到订单
- if( !$order ) return json_send(['code'=>'error','msg'=>'订单不存在']);
- // 数据转换
- $order = $order->toArray();
- // id转编号
- $order['insert_time'] = date('Y-m-d H:i:s',$order['insert_time']);
- $order['business_name'] = (string) $Business->getOne($order['business_id'],'name');
- $order['order_code'] = $Model->idToCode($order['id']);
- $order['state'] = $Model->getState($order['status'],'state');
- // 查询子订单数据
- $order['order_items'] = $OrdersProduct->query()->where([['order_id','=',$id]])->select(['id as item_id','order_id','product_id','buy_num','pay_total','is_rebate','sku_attr_names as product_spec','product_name','product_thumb'])->get()->toArray();
- // 处理缩略图
- foreach ($order['order_items'] as $key => $value) {
- $order['order_items'][$key]['product_thumb'] = $value['product_thumb'] ? path_compat($value['product_thumb']) : '';
- }
- // 地址
- $order['order_addr'] = $OrdersAddr->query()->where([['order_id','=',$id]])->first(['contact_name','contact_phone','contact_province','contact_city','contact_area','contact_addr','contact_shop']);
- // 加载模板
- return json_send(['code'=>'success','msg'=>'获取成功','data'=>$order]);
- }
- }
|