2048], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'mall_id' => '商城id', 'user_id' => '用户id', 'remarks' => '备注', 'total_childs' => '所有下级数量', 'total_order' => '订单数量', 'upgrade_at' => '等级升级时间', 'total_price' => '累计收益', 'price' => '已结算收益', 'frozen_price' => '未结算收益', 'upgrade_status' => '升级类型;1条件升级;2升级礼包;3平台添加;4上级添加', 'level' => '代理商等级权重', 'before_level' => '升级前等级;null为无', 'status' => '状态[-1:删除;0:禁用;1启用]', 'created_at' => 'Created At', 'updated_at' => 'Updated At', 'fill_num' => '补货数量', 'stock' => '库存', 'cloud_warehouse_price' => 'cloud_warehouse_price', 'cloud_warehouse_frozen_price' => 'cloud_warehouse_frozen_price', 'loss_amount' => 'loss_amount', 'difference_profit' => 'difference_profit', 'is_equal_award_restriction' => '是否开启平级奖限制:1是;0:否', 'is_stock_deducted_by_subordinate' => '自己的库存是否可以给下级补货 0允许 1不允许', ]; } public static $head_list = [ '0' => [ 'field' => 'serial_number', 'field_name' => '序号', ], '1' => [ 'field' => 'user_id', 'field_name' => '用户id', ], '2' => [ 'field' => 'level', 'field_name' => '代理等级id', ] ]; public static $max_count = 5000; public static $column_num = 3; /** * 导出字段 */ public static function exportFieldsList($field = null) { $fields = [ 'user_id' => '用户ID', 'nickname' => '昵称', 'mobile' => '手机号', 'level' => '代理等级', 'level_id' => '代理等级id', 'parent_id' => '推荐人ID', 'parent_name' => '推荐人昵称', 'parent_mobile' => '推荐人手机号', 'supply_id' => '供货商ID', 'supply_name' => '供货商昵称', 'supply_mobile' => '供货商手机号', ]; return $fields; } /** * @name: * @msg: 处理导出数据,这个方法是异步队列处理时使用的,请别修改 * @param {array} $data * @return bool */ public static function exportHandle(array $data) { $download_id = $data['download_id'] ?? 0; $download = Download::findOne(['id' => $download_id]); if($download){ try{ $params = json_decode($download->params,true); $filename = $download->name; $type = $download->type; $fields = $params['fields']; $fields_arr = self::exportFieldsList(); $have_select_field_arr = []; foreach ($fields as $value){ $have_select_field_arr[]=$fields_arr[$value]; } $csv = new CsvTool(); $csv->filename = $filename; $csv->file_dirname = DownloadEnum::getTypeStorageDirMap($type); $csv->export_mode = CsvTool::EXPORT_MODE_ASYNC; $csv->header = $have_select_field_arr; $model = self::find(); $model->where(['mall_id'=>$params['mall_id']]); $model->andWhere(['>=','status',StatusEnum::DISABLED]); $user_id = 0; $user_id_arr = []; //拼接查询条件 if(!empty($params['user_id'])) $user_id = $params['user_id']; if(!empty($params['level'])) $model->andWhere( ['=', 'level', $params['level']]); if (!empty($params['keyword'])) { $condition['where'] = [[ 'or', ['like', 'username', $params['keyword']], ['like', 'nickname', $params['keyword']], ['like', 'mobile', $params['keyword']] ]]; $user_list = User::lists($condition); $user_id_arr = array_column($user_list,'id'); } if($user_id&&$user_id_arr){ $user_ids = array_intersect([$user_id],$user_id_arr); $model->andWhere(['in', 'user_id', $user_ids]); }else if($user_id){ $model->andWhere(['in', 'user_id', $user_id]); }elseif($user_id_arr){ $model->andWhere(['in', 'user_id', $user_id_arr]); } if (!empty($params['start'])) { $model->andWhere(['>=', 'created_at', strtotime($params['start'] . ' 00:00:00')]); } if (!empty($params['end'])) { $model->andWhere(['>=', 'created_at', strtotime($params['end'] . ' 00:00:00')]); } $model->with(['user','stockLevel'=>function($query){ $query->where(['status'=>StatusEnum::ENABLED]); }]); //遍历组装数据 foreach ($model->batch() as $list) { $parent_id_arr = $parent_arr = []; //查询上级昵称数组 $parent_id_arr = []; $supplier_id_arr = []; foreach ($list as $val) { if(!in_array($val['user']['parent_id'],$parent_id_arr))$parent_id_arr[]= $val['user']['parent_id']; $parent_agent = CloudStockAgent::getUserParentAgent($val['user_id'], $val['level']); if (!empty($parent_agent)) { $supplier_id_arr[$val['user_id']] = $parent_agent['user_id']; if(!in_array($parent_agent['user_id'],$parent_id_arr))$parent_id_arr[]=$parent_agent['user_id']; } } $parent_arr = User::lists(['where' => [['id' => array_unique($parent_id_arr)]], 'index' => 'id', 'select' => 'id,nickname,avatar_url,mobile,parent_id']); $csv->data = array_map(function($agent)use($fields,$parent_arr,$supplier_id_arr){ $row = []; //遍历所选字段 foreach ($fields as $field){ if(in_array($field,['nickname','mobile'])){ $row[] = !empty($agent['user'][$field])?$agent['user'][$field]:''; }elseif(in_array($field,['level'])){ $row[] = !empty($agent['stockLevel']['name'])?$agent['stockLevel']['name']:''; }elseif(in_array($field,['level_id'])){ $row[] = !empty($agent['stockLevel']['level'])?$agent['stockLevel']['level']:''; } elseif(in_array($field,['parent_id'])){ $row[] = !empty($agent['user']['parent_id'])?$agent['user']['parent_id']:'0'; } elseif(in_array($field,['parent_name'])){ $row[] = !empty($parent_arr[$agent['user']['parent_id']])?$parent_arr[$agent['user']['parent_id']]['nickname']:'平台'; } elseif(in_array($field,['parent_mobile'])){ $row[] = !empty($parent_arr[$agent['user']['parent_id']])?$parent_arr[$agent['user']['parent_id']]['mobile']:'平台'; } elseif(in_array($field,['supply_id'])||in_array($field,['supply_name'])||in_array($field,['supply_mobile'])){ if (isset($supplier_id_arr[$agent['user_id']])) { $supplier_id = $supplier_id_arr[$agent['user_id']]; $supplyItem=null; if(isset($parent_arr[$supplier_id])){ $supplyItem=[ 'user_id'=>$supplier_id, 'avatar_url'=>$parent_arr[$supplier_id]['avatar_url'], 'nickname'=>$parent_arr[$supplier_id]['nickname'], 'mobile'=>$parent_arr[$supplier_id]['mobile'], ]; } } if($field=='supply_id') { $row[] = !empty($supplyItem)?$supplyItem['user_id']:'平台'; } if($field=='supply_name') { $row[] = !empty($supplyItem)?$supplyItem['nickname']:'平台'; } if($field=='supply_mobile') { $row[] = !empty($supplyItem)?$supplyItem['mobile']:'平台'; } } else{ $row[] = !empty($agent[$field])?$agent[$field]:''; } } return $row; },$list); $csv->export(); } $csv->updateDown($download,$params['mall_id']); return true; }catch(Exception $e){ $download->status = 3; $res = $download->save(); var_dump($e->getMessage()); self::setStaticError($e->getMessage()); return false; } } } public function getUser() { return $this->hasOne(User::class, ['id' => 'user_id'])->select(['id', 'nickname', 'avatar_url', 'mobile', 'parent_id','inviter_at']); } public function getStockLevel() { return $this->hasOne(CloudStockLevel::class, ['level' => 'level', 'mall_id' => 'mall_id'])->where(['status'=>[StatusEnum::ENABLED,StatusEnum::DISABLED]]); } public static function setData(array $params) { try { if (!empty($params['id'])) { $model = self::findOne(['mall_id' => $params['mall_id'], 'id' => $params['id'], 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]]); if (empty($model)) throw new \Exception('服务不存在或已删除'); $params['before_level'] = $model->level; if(isset($params['level'])){ if ($params['before_level'] < $params['level']) $params['upgrade_at'] = time(); } } else { $model = new self(); $model->loadDefaultValues(); } if (!$model->load($params, '')) throw new \Exception($model->getErrorMessage()); if (!$model->save()) throw new \Exception($model->getErrorMessage()); if(isset($params['level'])&&$params['level']>$model['before_level']){ $level = CloudStockLevel::findOne(['mall_id' => $params['mall_id'], 'level' => $params['level'],'status'=>[StatusEnum::ENABLED]]); if (!empty($level)) { $give_quota = json_decode($level['give_quota'], true); if (!empty($give_quota)) { foreach($give_quota as $item){ if(!empty($item['is_use'])&&!empty($item['num'])){ $param = []; $param['mall_id'] = $model['mall_id']; $param['user_id'] = $model['user_id']; $param['num'] = $item['num']; $param['level'] = $item['level']; $res = CloudStockAgentQuota::setData($param); if ($res==false) throw new Exception(CloudStockAgentQuota::getStaticError()); } } } } } if(isset($params['status'])&&$params['status']==StatusEnum::DELETE){ CloudStockAgentQuota::updateAll(['status'=>StatusEnum::DELETE],['user_id'=>$model['user_id']]); } return $model; } catch (\Exception $e) { self::$static_error = $e->getMessage(); return false; } } /** * @name: * @msg: 获取供应商 * @param {*} $agent_user_id 当前代理商 user_id * @param {*} $level 当前代理商等级 * @return object */ public static function getUserParentAgent($agent_user_id, $level, $type_level = 0) { $parent_id_arr = UserPartitionRelationship::getParentIdArr($agent_user_id); $parent_id_arr = array_reverse($parent_id_arr); //补货只能找等级比自己大的代理补货 $where = [['user_id' => $parent_id_arr], ['status' => [StatusEnum::DISABLED, StatusEnum::ENABLED]]]; if ($type_level == 0) { $where[] = ['>', 'level', $level]; } else { $where[] = ['>=', 'level', $level]; } $parent_agent_list = CloudStockAgent::lists(['where' => $where, 'index' => 'user_id'], false); $parent_agent = null; foreach ($parent_id_arr as $user_id) { if (isset($parent_agent_list[$user_id])) { $parent_agent = $parent_agent_list[$user_id]; break; } } return $parent_agent; } public static function getUserParentAgentByAppointLevel($agent_user_id, $level) { $parent_id_arr = UserPartitionRelationship::getParentIdArr($agent_user_id); $parent_id_arr = array_reverse($parent_id_arr); //补货只能找等级比自己大的代理补货 $parent_agent_list = CloudStockAgent::lists(['where' => [['user_id' => $parent_id_arr], ['>=', 'level', $level],['status'=>[StatusEnum::DISABLED, StatusEnum::ENABLED]]], 'index' => 'user_id'], false); $parent_agent = null; foreach ($parent_id_arr as $user_id) { if (isset($parent_agent_list[$user_id])) { $parent_agent = $parent_agent_list[$user_id]; break; } } return $parent_agent; } public static function getUserParentAgentList($agent_user_id) { $parent_id_arr = UserPartitionRelationship::getParentIdArr($agent_user_id); $parent_id_arr = array_reverse($parent_id_arr); $parent_agent_list = CloudStockAgent::lists(['where' => [['user_id' => $parent_id_arr]], 'index' => 'user_id'], false); $list = []; foreach ($parent_id_arr as $user_id) { if (isset($parent_agent_list[$user_id])) { $list[] = $parent_agent_list[$user_id]; } } return $list; } //投递到资产队列 public static function sendUserWalletQueue($insert_wallet) { try { if ($insert_wallet) { $res = UserWalletService::batchHandleByQueue($insert_wallet); if ($res == false) throw new \Exception(UserWalletService::getStaticError()); $user_ids = array_column($insert_wallet,'user_id'); $user_arr = User::lists(['where'=>[['id'=>$user_ids]],'select'=>'id,mobile','index'=>'id']); foreach ($insert_wallet as $k => $user) { $agent = CloudStockAgent::findOne(['user_id' => $user['user_id'],'status'=>StatusEnum::ENABLED]); if(empty($agent)) continue; if (!empty($user['is_frozen'])) { $agent->frozen_price += $user['money']; } else { $agent->price += $user['money']; } $agent->total_price += $user['money']; $res = $agent->save(); if (empty($res)) throw new \Exception($agent->getErrorMessage()); //奖励短信 $mobile = $user_arr[$user['user_id']]['mobile']??0; if(!empty($mobile)&&!$user['is_frozen']){ if (in_array($user['capital_type'], [UserWalletEnum::FILL, UserWalletEnum::OVER, UserWalletEnum::EQUAL])) { $obj = new CloudStockAgent(); $obj->sendMessage($user['mall_id'],$mobile,$user['money']); } //货款短信 if (in_array($user['capital_type'], [UserWalletEnum::PAYMENT_FOR_GOODS_FILL, UserWalletEnum::PAYMENT_FOR_GOODS_BUY])) { $obj = new CloudStockAgent(); $obj->sendMessage($user['mall_id'],$mobile,$user['money']); } } } } } catch (\Exception $e) { echo 'sendUserWalletQueue:' . $e->getMessage(); } } /** * @name: * @msg: 设置下级代理 * @param {int} $mall_id * @param {array} $data user_id:当前代理会员主表 id;agent_id:当前代理 id;child_id:下级会员 id;set_level:给下级设定的等级 * @return bool */ public static function setWholesaler(int $mall_id, array $data): bool { $transaction = \Yii::$app->db->beginTransaction(); $params_agent = [ 'mall_id' => $mall_id, 'user_id' => $data['child_id'], 'level' => $data['set_level'], 'upgrade_status' => $data['upgrade_status'], ]; unset($data['upgrade_status']); $res_agent = self::setData($params_agent); if (false === $res_agent) { $transaction->rollBack(); return false; } $data['mall_id'] = $mall_id; $data['child_agent_id'] = $res_agent->id; $res_log = CloudStockSetAgentLog::setData($mall_id, $data); if (false === $res_log) { $transaction->rollBack(); self::$static_error = CloudStockSetAgentLog::getStaticError(); return false; } $params = []; $params['mall_id'] = $mall_id; $params['user_id'] = $data['user_id']; $params['num'] = -1; $params['level'] =$data['set_level']; CloudStockAgentQuota::setData($params); $transaction->commit(); self::setWholesalerGiveGoods($mall_id,$data['set_level'],$data['user_id'],$data['child_id']); return true; } //设置代理等级,送库存,根据升级礼包对应等级送库存 public static function setWholesalerGiveGoods($mall_id,$set_level,$user_id,$child_id){ try { $configs = \Yii::$app->services->setting->addons->get($mall_id, AddonsEnum::ADDONS_NAME_CLOUD_STOCK, 'basic'); if(empty($configs['is_deduct_goods'])) return false; $upgrade_bag_list = CloudStockUpgradeBag::lists([ 'where'=>[ ['mall_id'=>$mall_id], ['level'=>$set_level], ['status'=>StatusEnum::ENABLED], ], ]); if(!empty($upgrade_bag_list)){ $give_arr = []; foreach ($upgrade_bag_list as $upgrade_bag){ //走配货逻辑的逻辑 if(!empty(intval($upgrade_bag['give_goods_num']))){ $give_goods_num[]= intval($upgrade_bag['give_goods_num']); if (!empty($upgrade_bag['give_goods_id'])) { if(isset($give_arr[$upgrade_bag['give_goods_id']])){ $give_arr[$upgrade_bag['give_goods_id']] += $upgrade_bag['give_goods_num']; }else{ $give_arr[$upgrade_bag['give_goods_id']] = $upgrade_bag['give_goods_num']; } } }else{ $give_goods_num= json_decode($upgrade_bag['give_goods_num'],true); foreach ($give_goods_num as $give_goods){ if(isset($give_arr[$give_goods['goods_id']])){ $give_arr[$give_goods['goods_id']] += $give_goods['num']; }else{ $give_arr[$give_goods['goods_id']] = $give_goods['num']; } } } } $goods_ids = array_keys($give_arr); $cloud_stock_agent_goods_list = CloudStockAgentGoods::lists([ 'where'=>[ ['user_id'=>$user_id], ['goods_id'=>$goods_ids] ], 'index'=>'goods_id', ]); foreach ($give_arr as $goods_id=>$num){ if(isset($cloud_stock_agent_goods_list[$goods_id])){ $cloud_stock_agent_goods =$cloud_stock_agent_goods_list[$goods_id]; if($cloud_stock_agent_goods['num']<$num){ $num = $cloud_stock_agent_goods['num']; } $post = [ 'goods_id'=>$goods_id, 'number'=>$num, 'user_id'=>$user_id, 'target_user_id'=>$child_id, ]; $res = CloudStockGoodsStockLog::stockHandle($mall_id, $post, CloudStockEnum::STOCK_CHANGE_TYPE201); } } } }catch (\Exception $e){ \Yii::error("{$user_id}设置{$child_id}代理等级,送库存,异常".$e->getMessage()); } } //发送短信 public function sendMessage($mall_id,$mobile,$money){ try{ if(!empty($mobile)){ $SmsConfig = new Sms($mall_id); $easy_sms = $SmsConfig->easySms; $message = new RewardMessage($mall_id,bcmul($money,1,2)); $easy_sms->send($mobile, $message); } }catch (NoGatewayAvailableException $e){ $res = $e->getExceptions(); if(!empty($res)){ foreach ($res as $exception){ if(is_string($exception->getMessage())){ \Yii::error('云库存收益通知短信发送失败:' .$exception->getMessage()); } } } }catch (\Exception $e){ var_dump('云库存收益通知短信发送失败:' .$e->getMessage()); } } //货款短信 public function sendGoodsMoneyMessage($user_arr,$item){ $mobile = $user_arr[$item['user_id']]['mobile']??0; if(!empty($mobile)){ $this->sendMessage($item['mall_id'],$mobile, $item['change_num']); } } public static function getAddons(array $params){ $is_install = MallAddons::isInstall($params['mall_id'], CloudStockEnum::ADDONS_NAME); if($is_install){ $detail = Addons::getOne([['name' => CloudStockEnum::ADDONS_NAME], ['is_online' => 1]], true); return [ 'addons_name'=>CloudStockEnum::ADDONS_NAME, 'title'=>$detail['title'], ]; } return []; } public static function fieldsLists($field = null){ $fields = [ 'user_id' => '代理商用户ID', 'nickname' => '代理商用户昵称', 'mobile' => '手机号', 'level' => '代理等级', 'total_stock_num' => '库存总数量', 'goods_stock_num' => '商品库存数量', ]; if ($field === null) return $fields; $temp = []; foreach ($field as $val) { if (isset($fields[$val])) $temp[$val] = $fields[$val]; } return $temp; } public static function exportOrder(array $data) { $download_id = $data['download_id'] ?? 0; $download = Download::findOne(['id' => $download_id]); if ($download) { try { $params = json_decode($download->params, true); $filename = $download->name; $type = $download->type; $fields = isset($params['fields']) ? $params['fields'] : null; $where[] = ['=', 'mall_id', $params['mall_id']]; $where[] = ['in', 'status', [StatusEnum::DISABLED, StatusEnum::ENABLED]]; if (!empty($params['keyword'])) { $user_list = User::find()->where(['or', ['id' => $params['keyword']], ['like', 'mobile', $params['keyword']], ['like', 'nickname', $params['keyword']]])->select('id')->asArray()->all(); $user_id_arr = array_column($user_list, 'id'); $where[] = ['user_id' => $user_id_arr]; } if (!empty($params['level'])) $where[] = ['level' => $params['level']]; $wheres['order'] = 'level desc'; $wheres['with'] = ['user']; $wheres['where'] = $where; $model = self::find(); self::paramPack($wheres, $model); $list = []; $exportheader = []; $isSetHeader = true; $i = 1; $page_size = 1000; $cloudStockGoodsList = CloudStockGoods::lists(['where'=>[['mall_id'=>$params['mall_id']],['status'=>StatusEnum::ENABLED]]]); while ($log_list = $model->asArray()->offset(($i - 1) * $page_size)->limit($page_size)->all()){ $level_arr = array_column($log_list, 'level'); $level_list = CloudStockLevel::lists(['where' => [['mall_id' =>$params['mall_id']], ['level' => $level_arr], ['status' => StatusEnum::ENABLED]], 'index' => 'level']); $user_ids = array_column($log_list, 'user_id'); $goods_ids = array_column($cloudStockGoodsList,'goods_id'); $agent_goods_list = CloudStockAgentGoods::lists(['where' => [['user_id' => $user_ids],['goods_id'=>$goods_ids],['status'=>StatusEnum::ENABLED]], 'select' => 'sum(num) num ,user_id', 'group' => 'user_id', 'index' => 'user_id']); $agent_goods_arr = CloudStockAgentGoods::lists(['where' => [['user_id' => $user_ids],['goods_id'=>$goods_ids],['status'=>StatusEnum::ENABLED]], 'select' => 'num,goods_id ,user_id']); $agent_goods_arr_new = []; foreach ($agent_goods_arr as $val){ $agent_goods_arr_new[$val['user_id']][$val['goods_id']] = $val['num']; } foreach ($log_list as $l){ $temp = []; //按顺序组装 if(in_array('user_id', $fields)) { $temp['user_id'] = $l['user_id']; $isSetHeader && array_push($exportheader, '代理商用户ID'); } if(in_array('nickname', $fields)) { $temp['nickname'] = ''; if(isset($l['user'])){ $temp['nickname'] = $l['user']['nickname']; } $isSetHeader && array_push($exportheader, '代理商用户昵称'); } if(in_array('mobile', $fields)) { $temp['mobile'] = ''; if(isset($l['user'])){ $temp['mobile'] = $l['user']['mobile']; } $isSetHeader && array_push($exportheader, '手机号'); } if(in_array('level', $fields)) { $temp['level'] = $level_list[$l['level']]['name'] ?? ''; $isSetHeader && array_push($exportheader, '代理等级'); } if(in_array('total_stock_num', $fields)) { $temp['total_stock_num'] = 0; if (isset($agent_goods_list[$l['user_id']])){ $temp['total_stock_num'] = $agent_goods_list[$l['user_id']]['num']; } $isSetHeader && array_push($exportheader, '库存总数量'); } if(in_array('goods_stock_num', $fields)) { foreach ($goods_ids as $goods_id) { $temp[$goods_id . '_num'] = 0; if (isset($agent_goods_arr_new[$l['user_id']]) && isset($agent_goods_arr_new[$l['user_id']][$goods_id])) { $temp[$goods_id . '_num'] = $agent_goods_arr_new[$l['user_id']][$goods_id]; } $isSetHeader && array_push($exportheader, '商品ID' . $goods_id); } } $list[] = $temp; $isSetHeader = false; } $i++; } if (!empty($list)) { $csv = new CsvTool(); $csv->filename = $filename; $csv->file_dirname = DownloadEnum::getTypeStorageDirMap($type); $csv->export_mode = CsvTool::EXPORT_MODE_ASYNC; $csv->header = $exportheader; $csv->data = $list; $csv->export(); $csv->updateDown($download, $params['mall_id']); } }catch (\Exception $e) { $download->status = 3; $res = $download->save(); var_dump($e->getMessage().$e->getFile().$e->getLine()); self::setStaticError($e->getMessage()); return $e->getMessage(); } } } public static function fixStock($mall_id,$user_id){ $cloudStockGoodsList = CloudStockGoods::lists(['where'=>[['mall_id'=>$mall_id],['status'=>StatusEnum::ENABLED]]]); $goods_ids = array_column($cloudStockGoodsList,'goods_id'); $sum_stock = CloudStockAgentGoods::find()->where(['user_id' => $user_id,'goods_id'=>$goods_ids,'status'=>StatusEnum::ENABLED]) ->sum('num'); if(empty($sum_stock)) $sum_stock = 0; CloudStockAgent::updateAll(['stock'=>$sum_stock],['user_id'=>$user_id,'mall_id'=>$mall_id,'status'=>[StatusEnum::DISABLED, StatusEnum::ENABLED]]); } public static function fixStockOne($mall_id = 0){ $cloudStockGoodsList = CloudStockGoods::lists(['where'=>[['mall_id'=>$mall_id],['status'=>StatusEnum::ENABLED]]]); $goods_ids = array_column($cloudStockGoodsList,'goods_id'); $list = CloudStockAgentGoods::lists([ 'where'=>[ ['goods_id'=>$goods_ids], ['mall_id'=>$mall_id], ['status'=>StatusEnum::ENABLED] ], 'select' => 'sum(num) num ,user_id', 'group' => 'user_id', ]); foreach ($list as $item){ $res = CloudStockAgent::updateAll(['stock'=>$item['num']],['user_id'=>$item['user_id'],'mall_id'=>$mall_id,'status'=>[StatusEnum::DISABLED, StatusEnum::ENABLED]]); var_dump($res); } } public static function fixStockAll(){ $mall_list = Mall::getEnableMallList(true); foreach ($mall_list as $mall){ $mall_id = $mall['id']; $cloudStockGoodsList = CloudStockGoods::lists(['where'=>[['mall_id'=>$mall_id],['status'=>StatusEnum::ENABLED]]]); $goods_ids = array_column($cloudStockGoodsList,'goods_id'); $list = CloudStockAgentGoods::lists([ 'where'=>[ ['goods_id'=>$goods_ids], ['mall_id'=>$mall_id], ['status'=>StatusEnum::ENABLED] ], 'select' => 'sum(num) num ,user_id', 'group' => 'user_id', ]); foreach ($list as $item){ $res = CloudStockAgent::updateAll(['stock'=>$item['num']],['user_id'=>$item['user_id'],'mall_id'=>$mall_id,'status'=>[StatusEnum::DISABLED, StatusEnum::ENABLED]]); var_dump($res); } } } public static function fixStockAlls(){ $mall_list = Mall::getEnableMallList(true); foreach ($mall_list as $mall){ $mall_id = $mall['id']; $i = 1; $page_size = 1000; $where = ['mall_id' => $mall_id, 'status' => ['status' => StatusEnum::ENABLED]]; while ($list = CloudStockAgent::find() ->where($where) ->offset(($i - 1) * $page_size) ->limit($page_size)->all()) { foreach ($list as $item){ CloudStockAgent::fixStock($mall_id,$item['user_id']); } $i++; } } } /** * 批量更新代理等级 * @param $params * @return array|bool */ public static function importLevel($params) { $t = \Yii::$app->db->beginTransaction(); try { self::isCanImport($params['mall_id']); $csvImport = new CsvImportForm(); $data = $csvImport->setDataForm($params) ->setMaxCount(self::$max_count) ->setImportFieldConfig(self::$head_list) ->setColumnNum(self::$column_num) ->readCsvData(); if (!$data) throw new \Exception(CsvImportForm::getStaticError()); $success_counts = $fail_counts = 0; $counts = count($data); $fail_arr = []; $success_user_id_arr = []; $merge_arr = []; foreach ($data as $item) { $param = $item; $merge_arr[] = $param; } self::batchUpdateLevel($params['mall_id'], $merge_arr, $success_counts, $fail_arr, $fail_counts, $success_user_id_arr); $param['counts'] = $counts; $param['success_counts'] = $success_counts; $param['fail_counts'] = $fail_counts; $param['status'] = 1; $param['mall_id']=$params['mall_id']; $import_log_model = CloudStockImportLevelLog::setData($param); if (!$import_log_model) throw new \Exception(CloudStockImportLevelLog::getStaticError()); if (!empty($fail_arr)) { $res = CloudStockImportLevelFailLog::setData($fail_arr, $import_log_model->id); if (!$res) throw new \Exception(CloudStockImportLevelFailLog::getStaticError()); } $t->commit(); return ['counts' => $counts, 'success_counts' => $success_counts, 'fail_counts' => $fail_counts]; } catch (\Exception $e) { var_dump($e->getMessage().$e->getFile()); self::$static_error = $e->getMessage(); $t->rollBack(); return false; } } public static function importLevelSync($params) { $t = \Yii::$app->db->beginTransaction(); try { self::isCanImport($params['mall_id']); $basePath = \Yii::$app->basePath; if (empty($_FILES) || !isset($_FILES['file'])) throw new \Exception('请上传csv文件'); $fileName = $_FILES['file']['name']; $tmpName = $_FILES['file']['tmp_name']; $basePath = $basePath . '/web/uploads/'; if (!is_dir($basePath))mkdir($basePath, 0775, true); $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); if ($ext != 'csv') throw new \Exception('请上传csv文件'); $uploadFile = $basePath . 'ADMIN-' . date('Y-m-d His') . '.' . $ext; //上传 move_uploaded_file($tmpName, $uploadFile); $success_counts = $fail_counts = 0; $counts = 0; $param['counts'] = $counts; $param['success_counts'] = $success_counts; $param['fail_counts'] = $fail_counts; $param['upload_file'] = $uploadFile; $param['mall_id'] = $params['mall_id']; $user_import_log_model = CloudStockImportLevelLog::setData($param); if (!$user_import_log_model) throw new \Exception(CloudStockImportLevelLog::getStaticError()); $t->commit(); $params = ['id'=>$user_import_log_model['id']]; \Yii::$app->services->rabbitMq->push(RabbitMqEnum::TASK_QUEUE, RabbitMqEnum::TASK_QUEUE, $params, self::class, 'syncImportLevel'); return ['counts' => $counts, 'success_counts' => $success_counts, 'fail_counts' => $fail_counts]; } catch (\Exception $e) { self::$static_error = $e->getMessage(); var_dump($e->getMessage()); $t->rollBack(); return false; } } public static function isCanImport($mall_id){ $time = strtotime('2024-04-28 23:59:59'); $res = CloudStockImportLevelLog::find()->where(['mall_id'=>$mall_id,'status'=>3])->andWhere(['>=','created_at',$time])->one(); if(!empty($res)) throw new \Exception('等上一次导入执行完再导入'); } //异步执行 public static function syncImportLevel($params){ if(empty($params['id'])) return false; $model = CloudStockImportLevelLog::findOne(['id' => $params['id']]); if (!empty($model['upload_file'])) { $upload_file = $model['upload_file']; $mall_id = $model['mall_id']; $cvsFile = fopen($upload_file, 'r'); //开始读取csv文件数据 $fail_arr = []; $success_counts = $fail_counts =$counts = $i = 0; $counts = 0; $success_user_id_arr = []; $data = [];// 初始化数据 while ($fileData = fgetcsv($cvsFile)) { $i++; if ($i == 1) continue;//过滤表头 $counts++; $user_id=0; $level_id=0; foreach ($fileData as $k => &$val) { $val = mb_convert_encoding(trim($val), "UTF-8", "GBK"); switch ($k) { case 1: $user_id = !empty($val)?$val:''; break; case 2: $level_id = !empty($val)?trim($val):0; break; } } $param['user_id'] = $user_id; $param['level'] = $level_id; $data[] = $param; } self::batchUpdateLevel($mall_id, $data, $success_counts, $fail_arr, $fail_counts); $model->counts = $counts; $model->success_counts = $success_counts; $model->fail_counts = $fail_counts; $model->status = 1; if (!$model->save()) throw new \Exception($model->getErrorMessage()); if (!empty($fail_arr)) { $res = CloudStockImportLevelFailLog::setData($fail_arr, $model->id); if (!$res) throw new \Exception(CloudStockImportLevelFailLog::getStaticError()); } } } /** * 批量更新等级 * @Author: zfh * @DateTime: 2024/4/28 0003 15:16 * @Copyright: copyright (c) 2021 广东七件事集团 * @param $mall_id * @param $data * @param int $success_counts * @param array $fail_arr * @param int $fail_counts * @throws Exception */ public static function batchUpdateLevel($mall_id, $data, &$success_counts = 0, &$fail_arr = [], &$fail_counts = 0, &$success_user_id_arr = []) { foreach ($data as $item) { $fail_params = $item; $fail_params['maill_id']=$mall_id; $where = []; $where[] = ['mall_id' => $mall_id]; $where[] = ['id' => $item['user_id']]; if (empty(User::getUser($where))) { $fail_params['reason'] = '用户不存在'; list($fail_arr, $fail_counts) = CloudStockImportLevelFailLog::packFailArr($fail_params, $fail_arr, $fail_counts); } else if (empty(CloudStockLevel::getOne([['level' => $item['level'],'status'=>1,'mall_id'=>$mall_id]]))) { $fail_params['reason'] = '代理等级id不存在'; list($fail_arr, $fail_counts) = CloudStockImportLevelFailLog::packFailArr($fail_params, $fail_arr, $fail_counts); } else { $agent = CloudStockAgent::getOne([['user_id' => $item['user_id']]]); if ($agent) { $item['id'] = $agent['id']; } $item['mall_id']=$mall_id; $item['upgrade_level_at']=time(); $item['upgrade_status']=CloudStockEnum::UPGRADE_STATUS_MANUAL; $res = CloudStockAgent::setData($item); if ($res) { $success_user_id_arr[] = $res['id']; $success_counts++; } else { $fail_params['reason'] = CloudStockAgent::getStaticError(); list($fail_arr, $fail_counts) = CloudStockImportLevelFailLog::packFailArr($fail_params, $fail_arr, $fail_counts); } } } } public static function fixCloudWarehousePrice() { $list = CloudStockPaymentLog::lists([ 'where' => [ ['status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]] ], 'select' => 'sum(money) as money,user_id,status', 'group' => 'user_id,status' ]); foreach ($list as $item) { switch ($item['status']) { case 0: CloudStockAgent::updateAll(['cloud_warehouse_frozen_price' => $item['money']], ['user_id' => $item['user_id']]); break; case 1: $agent = CloudStockAgent::findOne(['user_id' => $item['user_id'], 'status' => StatusEnum::ENABLED]); $agent->cloud_warehouse_price = $item['money'] - $agent->cloud_warehouse_withdraw_price; $agent->save(); break; } } } }