| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531 |
- <?php
- namespace app\common\service;
- use app\common\model\BoxHandleAllModel;
- use app\common\model\BoxHandleModel;
- use app\common\model\MoneyLogModel;
- use app\common\model\RecyclecardLogModel;
- use app\common\model\ShopGoods;
- use app\common\model\ShopOrder;
- use app\common\model\ShopOrderGoodsModel;
- use app\common\model\ShopOrderShippingModel;
- use app\common\model\UserAddressModel;
- use app\common\model\UserModel;
- use app\common\model\UserUnmoneyModel;
- use think\facade\Db;
- use utils\RedisCache;
- /**
- * 开出盒子服务 by wes
- * Class BoxHandleService
- * @package app\common\service
- */
- class BoxHandleService
- {
- protected static $instance = null;
- protected $model = null;
- public function __construct()
- {
- $this->model = new BoxHandleModel();
- }
- /**
- * 静态化入口
- * @return static|null
- */
- public static function make()
- {
- if(!self::$instance){
- self::$instance = new static();
- }
- return self::$instance;
- }
- /**
- * 获取今日中奖福袋
- * @param $uid
- * @param array $params
- * @param int $pageSize
- * @param string $field
- * @return array|mixed
- * @throws \think\Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- public function getBoxListByUser($uid, $params=[], $pageSize=10, $field='')
- {
- $type = isset($params['type'])? $params['type'] : 0;
- $boxType = isset($params['box_type'])? $params['box_type'] : 0;
- if (!in_array($type, [1, 2])) {
- sr_throw('订单类型参数错误');
- }
- if ($boxType && !in_array($boxType, [10, 20, 30, 40])) {
- sr_throw('盒子类型参数错误');
- }
- $where = ['r.uid'=>$uid,'r.box_type'=>0,'r.status'=>$type,'r.is_delete'=> 2];
- if($boxType>0){
- $where['r.box_type'] = $boxType;
- }else{
- unset($where['r.box_type']);
- }
- // var_dump($where);
- $list = $this->model->alias('r')
- ->where($where)
- ->where(function($query) use($params){
- $keyword = isset($params['keywords'])? trim($params['keywords']):'';
- if($keyword){
- $query->where('r.h_sn','like',"%{$keyword}%");
- }
- })
- ->where(function($query){
- $query->where('r.open_time','<=',date('Y-m-d H:i:s'))->whereOr('r.open_time','null');
- })
- ->where(function($query) use($params){
- $time = isset($params['time'])? $params['time'] : '';
- $time1 = isset($params['time1'])? $params['time1'] : '';
- if($time){
- $query->where('r.create_time','>=', $time);
- }else if($time1){
- $query->where('r.create_time','<', $time1);
- }
- })
- ->field('r.*')
- ->order('r.create_time desc,r.id desc')
- ->paginate($pageSize)
- ->each(function($val, $k){
- $goodsInfo = ShopGoodsService::make()->getCacheInfoById($val['goods_id'], 'goods_name,goods_sn,goods_img,price,spec_name');
- $val['goods_name'] = $goodsInfo['goods_name'];
- $val['goods_sn'] = $goodsInfo['goods_sn'];
- $val['goods_img'] = $goodsInfo['goods_img'];
- $val['price'] = $goodsInfo['price'];
- $val['time_text'] = $val['create_time']? date('H:i:s', strtotime($val['create_time'])):'';
- $val['spec_name'] = $goodsInfo['spec_name'];
- if ($val['box_type'] == 10) {
- $val['is_canrecycle'] = 0;
- } else {
- $val['is_canrecycle'] = 1;
- }
- });
- $list = $list?$list->toArray():[];
- return isset($list['data'])? $list['data'] : [];
- }
- /**
- * 获取历史中奖福袋
- * @param $uid
- * @param array $params
- * @param int $pageSize
- * @param string $field
- * @return array|mixed
- * @throws \think\Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- public function getHistoryBoxList($uid, $params=[], $pageSize=10, $field='')
- {
- $type = isset($params['type'])? $params['type'] : 0;
- $boxType = isset($params['box_type'])? $params['box_type'] : 0;
- if (!in_array($type, [1, 2])) {
- sr_throw('订单类型参数错误');
- }
- if ($boxType && !in_array($boxType, [10, 20, 30, 40])) {
- sr_throw('盒子类型参数错误');
- }
- $where = ['r.uid'=>$uid,'r.box_type'=>0,'r.status'=>$type,'r.is_delete'=> 2];
- if($boxType>0){
- $where['r.box_type'] = $boxType;
- }else{
- unset($where['r.box_type']);
- }
- $list = BoxHandleAllModel::alias('r')
- ->where($where)
- ->where(function($query) use($params){
- $keyword = isset($params['keywords'])? trim($params['keywords']):'';
- if($keyword){
- $query->where('r.h_sn','like',"%{$keyword}%");
- }
- })
- ->where(function($query){
- $query->where('r.open_time','<=',date('Y-m-d H:i:s'))->whereOr('r.open_time','null');
- })
- ->where('r.create_time','<',date('Y-m-d'))
- ->field('r.*')
- ->order('r.create_time desc,r.id desc')
- ->paginate($pageSize)
- ->each(function($val, $k){
- $goodsInfo = ShopGoodsService::make()->getCacheInfoById($val['goods_id'], 'goods_name,goods_sn,goods_img,price,spec_name');
- $val['goods_name'] = $goodsInfo['goods_name'];
- $val['goods_sn'] = $goodsInfo['goods_sn'];
- $val['goods_img'] = $goodsInfo['goods_img'];
- $val['price'] = $goodsInfo['price'];
- $val['time_text'] = $val['create_time']? date('H:i:s', strtotime($val['create_time'])):'';
- $val['spec_name'] = $goodsInfo['spec_name'];
- if ($val['box_type'] == 10) {
- $val['is_canrecycle'] = 0;
- } else {
- $val['is_canrecycle'] = 1;
- }
- });
- $list = $list?$list->toArray():[];
- return isset($list['data'])? $list['data'] : [];
- }
- /**
- * 获取福袋统计
- * @param $uid
- * @param $status
- * @param int $dateType
- * @return mixed
- */
- public function getBoxCount($uid,$status,$dateType=1)
- {
- $counts = ['10'=>0,'20'=>0,'30'=>0,'40'=>0];
- $model = new BoxHandleModel();
- // $model = $dateType == 1? new BoxHandleModel() : new BoxHandleAllModel();
- $datas = $model->where(['uid'=>$uid,'status'=>$status,'is_delete'=>2])
- ->where(function($query){
- $query->where('open_time','<=',date('Y-m-d H:i:s'))->whereOr('open_time','null');
- })
- ->where(function($query) use($dateType){
- if($dateType == 1){
- $query->where('create_time','>=',date('Y-m-d'));
- }else{
- $query->where('create_time','<',date('Y-m-d'));
- }
- })
- ->field(Db::raw('box_type,status,count(*) as total'))
- ->group('box_type')
- ->select();
- $datas = $datas? $datas->toArray() : [];
- $datas = array_column($datas,'total','box_type');
- if($datas){
- $counts = [
- '10'=> isset($datas[10])? $datas[10]:0,
- '20'=> isset($datas[20])? $datas[20]:0,
- '30'=> isset($datas[30])? $datas[30]:0,
- '40'=> isset($datas[40])? $datas[40]:0,
- ];
- }
- return $counts;
- }
- /**
- * 一键发货
- * @param $uid 用户ID
- * @param $params
- * @throws Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- public function boxDelivery($uid, $params){
- $handIds = $params['hand_ids'];
- $addressId = $params['address_id'];
- $catchType = isset($params['date_type'])? $params['date_type'] : 0;
- $ids = explode(',', $handIds);
- if(empty($ids)){
- sr_throw('请选择发货的商品');
- }
- if (!in_array($catchType, [1,2])){
- sr_throw('处理参数错误');
- }
- $model = new BoxHandleModel();
- // $model = $catchType==1? new BoxHandleModel() : new BoxHandleAllModel();
- $boxList = $model->whereIn('id', $ids)
- ->where(['uid'=>$uid,'status'=>1,'is_delete'=>2])
- ->field('id,h_sn,status,uid,rid,handle_type,goods_id,box_type,goods_price')
- ->select();
- if (count($boxList) != count($ids)){
- sr_throw('商品参数错误或已处理,请刷新后重试');
- }
- $addressInfo = UserAddressModel::getAddressIdDetails((int)$addressId, $uid);
- if (!$addressInfo){
- sr_throw('地址错误');
- }
- $i=0;
- $catchIds = [];
- $orders = $orderGoods = $orderShippings = [];
- $orderId = ShopOrder::max('order_id')+1;
- $curTime = sr_getcurtime(time());
- $cacheKey = "caches:box:deliveryCatch:user_{$uid}:";
- foreach ($boxList as $key=>$val){
- $goodsInfo = ShopGoodsService::make()->getCacheInfoById($val['goods_id']);
- if(empty($goodsInfo)){
- sr_throw('商品参数错误');
- }
- // 判断该福袋是否已经处理
- if($model->where(['id'=>$val['id'],'status'=>2])->value('id')){
- sr_throw('商品已处理');
- }
- // 验证是否有处理订单
- if(ShopOrder::where(['user_id'=> $uid,'order_source'=> '福袋单号:'.$val['h_sn'],'status'=>1])->value('order_id')){
- sr_throw('存在已发货商品');
- }
- // 订单数据
- $orderId = $orderId+$i;
- $orders[] = [
- 'order_id'=>$orderId,
- 'order_sn'=>createdFDOrderSn(),
- 'payment'=>0,
- 'ship_postfee'=>0,
- 'user_id'=>$uid,
- 'status'=>1,
- 'num'=>1,
- 'order_type'=>5,
- 'order_remark'=> '福袋:'.$val['h_sn'],
- 'order_source'=> '福袋单号:'.$val['h_sn'],
- 'supplier_name'=>$goodsInfo['supplier_name'],
- 'total_price'=>0,
- 'created_time'=>$curTime,
- 'rebate_score'=>0,
- ];
- $orderGoods[] = [
- 'order_id'=> $orderId,
- 'goods_id'=> $goodsInfo['goods_id'],
- 'goods_name'=> $goodsInfo['goods_name'],
- 'goods_category'=> $goodsInfo['category'],
- 'goods_img'=> $goodsInfo['goods_img'],
- 'num'=>1,
- 'price'=> $goodsInfo['price'],
- 'total_fee'=> $goodsInfo['price'],
- 'spec_ids'=>1,
- 'spec_text'=> $goodsInfo['spec_name'],
- 'uid'=>$uid,
- 'rebate_score'=>0,
- 'total_rebate_score'=>0
- ];
- $orderShippings[] = [
- 'order_id'=> $orderId,
- 'sp_name'=> $addressInfo['name'],
- 'sp_mobile'=> $addressInfo['mobile'],
- 'sp_province'=> $addressInfo['sp_province'],
- 'sp_city'=> $addressInfo['sp_city'],
- 'sp_county'=> $addressInfo['sp_county'],
- 'sp_remark'=> $addressInfo['remark'],
- 'sp_mergename'=> $addressInfo['mergename'],
- 'created_time'=>$curTime
- ];
- $catchIds[] = $val['id'];
- $i++;
- }
- // 验证处理数据
- if(empty($orders) || empty($catchIds) || empty($orderGoods) || empty($orderShippings)){
- sr_throw('发货处理失败');
- }
- // 插入订单
- if(!ShopOrder::insertAll($orders)){
- sr_throw('处理发货订单错误');
- }
- // 发货订单商品
- if(!ShopOrderGoodsModel::insertAll($orderGoods)){
- sr_throw('处理发货订单商品数据错误');
- }
- // 发货订单信息
- if(!ShopOrderShippingModel::insertAll($orderShippings)){
- sr_throw('处理发单数据错误');
- }
- // 今日数据处理/历史数据处理
- if(!$model->whereIn('id', $catchIds)->update(['status'=>2,'handle_type'=>1,'update_time'=> $curTime])){
- sr_throw('处理福袋数据失败');
- }
- return true;
- }
- /**
- * 一件回收
- * @param $uid
- * @param $params
- * @return array
- * @throws \think\Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- public function boxGoodsReBuy($uid, $params){
- $handIds = $params['hand_ids'];
- $isRetrieve = SystemConfigService::make()->getConfigByName('fudai_is_retrieve',1,'fudai');
- $isRetrieve = $isRetrieve? $isRetrieve : 0;
- if(!$isRetrieve){
- sr_throw('回收功能已暂时关闭');
- }
- $catchType = isset($params['date_type'])? $params['date_type'] : 0;
- $ids = explode(',', $handIds);
- if(empty($ids)){
- sr_throw('请选择回收的商品');
- }
- if (!in_array($catchType, [1,2])){
- sr_throw('处理参数错误');
- }
- $num = count($ids);
- $model = new BoxHandleModel();
- // $model = $catchType==1? new BoxHandleModel() : new BoxHandleAllModel();
- $boxList = $model->whereIn('id', $ids)
- ->where(['uid'=>$uid,'status'=>1,'is_delete'=>2])
- ->field('id,h_sn,status,uid,rid,handle_type,goods_id,box_type,goods_price')
- ->select();
- if (count($boxList) != count($ids)){
- sr_throw('商品参数错误或已处理,请刷新后重试');
- }
- if ($model->where('box_type', 10)->where('id', 'in', $ids)->value('id')){
- sr_throw('普通商品只能发货,不能回收');
- }
- if(UserUnmoneyModel::where(['ids'=> $handIds,'status'=>1])->value('id')){
- sr_throw('商品已处理');
- }
- // 待处理的总金额
- $totalMoney = $model->where('id', 'in', $ids)->sum('goods_price');
- $serviceFee = $num* env('boxsetting.RECYCLE_ONBOX_PRICE');
- $endMoney = $totalMoney - $serviceFee;
- if ($endMoney < 0){
- sr_throw('错误,请联系客服');
- }
- // 申请
- if ($params['action'] == 'apply'){
- return [
- 'total_count'=>count($boxList),
- 'end_money'=>$endMoney,
- 'total_money'=>$totalMoney
- ];
- }
- // 回收
- else if ($params['action'] == 'surerecycle'){
- $userInfo = UserService::make()->getCacheInfo($uid,'id,score,money,recycle_count,profit_money');
- $recycleCount = isset($userInfo['recycle_count'])? $userInfo['recycle_count'] : 0;
- $userProfitMoney = isset($userInfo['profit_money'])? $userInfo['profit_money'] : 0;
- $userMoney = isset($userInfo['money'])? $userInfo['money'] : 0;
- $userScore = isset($userInfo['score'])? $userInfo['score'] : 0;
- // 回收卡扣除
- if ($recycleCount < $num){
- sr_throw('回收卡不足'.$num.'个');
- }
- // 扣除回收卡
- if(!UserModel::where('id',$uid)->dec('recycle_count', $num)->update()){
- sr_throw('回收卡扣除失败');
- }
- $data = [
- 'uid'=>$uid,
- 'type'=>3,
- 'score'=> $num,
- 'create_at'=>sr_getcurtime(time()),
- 'state'=> 2,
- 'before_score'=> $recycleCount,
- 'after_score'=> max(0,$recycleCount - $num),
- 'from_id'=> 0,
- 'uid2'=> $handIds
- ];
- if(!RecyclecardLogModel::insertGetId($data)){
- sr_throw('回收卡扣除处理失败');
- }
- // 288的原价一个,累计回收到余额到钱
- $totalFee = $num * env('boxsetting.ONE_BOX_PRICE');
- // 扣除手续费后的钱除去原价为利润
- $profitMoney = max(0, $endMoney - $totalFee);
- if(!UserModel::where('id', $uid)->inc('money', $totalFee)->update()){
- sr_throw('回收余额结算错误');
- }
- $data = [
- 'uid'=>$uid,
- 'type'=> 2,
- 'money'=> $totalFee,
- 'create_at'=>sr_getcurtime(time()),
- 'state'=> 1,
- 'before_money'=> $userMoney,
- 'after_money'=> floatval($userMoney + $totalFee),
- 'from_id'=> 0,
- 'uid2'=> $handIds,
- 'free_type'=> 0,
- 'remark'=> "回收{$num}个福袋商品"
- ];
- if(!MoneyLogModel::insertGetId($data)){
- sr_throw('回收商品金额处理失败');
- }
- // 利润
- if ($profitMoney>0){
- // 利润结算
- if(!UserModel::where('id', $uid)->inc('profit_money', $profitMoney)->update()){
- sr_throw('回收商品利润结算错误');
- }
- // 添加用户利润记录
- $data = [
- 'uid'=>$uid,
- 'money'=> $profitMoney,
- 'status'=> 2,
- 'type'=> 1,
- 'ids'=> $handIds,
- 'state'=> 1,
- 'before_money'=> $userProfitMoney,
- 'after_money'=> floatval($userProfitMoney + $profitMoney),
- 'remark'=> "回收{$num}个福袋结算,总金额:{$totalMoney}",
- 'create_time'=>sr_getcurtime(time())
- ];
- if(!UserUnmoneyModel::insertGetId($data)){
- sr_throw('商品回收利润处理错误');
- }
- // 更新团队利润数据
- }
- // 改变用户处理状态
- if(!$model->whereIn('id', $ids)->update(['status'=>2, 'handle_type'=>2, 'update_time'=>date('Y-m-d H:i:s')])){
- sr_throw('更新回收处理状态失败');
- }
- $logData = ['ids'=> $ids,'totalMoney'=> $totalMoney,'fee'=>$serviceFee,'profit'=>$profitMoney,'back'=>$totalFee,'data'=>$data,'date'=>date('Y-m-d H:i:s')];
- RedisCache::set("caches:box:recycle:user_{$uid}:".md5(json_encode($ids)), $logData, 7200);
- return [
- 'ids'=> $ids,
- 'total_fee'=> $totalFee,
- 'profit_money'=> $profitMoney
- ];
- }
- }
- }
|