| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982 |
- <?php
- namespace addons\Agent\common\models;
- use addons\Agent\common\enums\AgentEnum;
- use common\components\export\CsvTool;
- use common\enums\AddonsEnum;
- use common\enums\DownloadEnum;
- use common\enums\LevelUpgradeLogEnum;
- use common\enums\StatusEnum;
- use common\helpers\ArrayHelper;
- use common\models\base\BaseActiveRecord;
- use common\models\common\Addons;
- use common\models\common\CommissionLog;
- use common\models\common\Download;
- use common\models\goods\GoodsAttr;
- use common\models\mall\MallAddons;
- use common\models\user\User;
- use common\models\user\UserAddress;
- use common\models\user\UserPartitionRelationship;
- use common\models\user\UserTeamStatistics;
- use common\helpers\csv\CsvImportForm;
- use common\enums\RabbitMqEnum;
- use Exception;
- use Yii;
- /**
- * This is the model class for table "{{%addons_agent}}".
- * @property int $id
- * @property int $mall_id
- * @property int $user_id
- * @property string|null $remarks 备注
- * @property int $status
- * @property int $created_at 创建时间
- * @property int $updated_at 修改时间
- * @property int $level 经销商等级
- * @property int $upgrade_level_at 经销商等级升级时间
- * @property float $total_commission 佣金
- * @property int $total_score 积分
- * @property int $province_id 省份ID
- * @property User $user
- * @property int $upgrade_status
- */
- class Agent extends BaseActiveRecord
- {
- public $limit = 10;
- public $page = 1;
- /**
- * {@inheritdoc}
- */
- public static function tableName()
- {
- return '{{%addons_agent}}';
- }
- /**
- * {@inheritdoc}
- */
- public function rules(){
- return [
- [['mall_id', 'user_id'], 'required'],
- [['mall_id', 'user_id', 'status', 'created_at', 'updated_at', 'level', 'upgrade_level_at', 'upgrade_status', 'province_id'], 'integer'],
- [['remarks'], 'string'],
- [['total_commission','total_score'], 'number'],
- ];
- }
- /**
- * {@inheritdoc}
- */
- public function attributeLabels(){
- return [
- 'id' => 'ID',
- 'mall_id' => 'Mall ID',
- 'user_id' => 'User ID',
- 'remarks' => '备注',
- 'status' => '状态[-1:删除;0:禁用;1启用]',
- 'created_at' => '创建时间',
- 'updated_at' => '修改时间',
- 'level' => '经销商等级',
- 'upgrade_level_at' => '经销商等级升级时间',
- 'total_commission' => '总佣金',
- 'total_score' => '总积分',
- 'upgrade_status' => '升级方式,1条件升级 2 购买指定商品升级 3手动升级',
- 'province_id' => '省份ID',
- ];
- }
- public static $head_list = [
- '0' => [
- 'field' => 'serial_number',
- 'field_name' => '序号',
- ],
- '1' => [
- 'field' => 'mobile',
- 'field_name' => '手机号码',
- ],
- '2' => [
- 'field' => 'level',
- 'field_name' => '经销商等级id',
- ]
- ];
- public static $max_count = 5000;
- public static $column_num = 3;
- /**
- * @param bool $insert
- * @return bool
- */
- public function beforeSave($insert)
- {
- if ($this->isNewRecord && !$this->province_id){
- $setting = \Yii::$app->services->setting->addons->get($this->mall_id, AgentEnum::ADDONS_NAME, 'basic');
- if($setting['is_enable_province']){
- $address = UserAddress::findOne(['user_id' => $this->user_id,'status' => StatusEnum::ENABLED]);
- $this->province_id = $address->province_id ?? 0;
- }
- }
- return parent::beforeSave($insert);
- }
- /**
- * @desc:关联会员信息
- * @Author: hua
- * @Date: 2021/11/5
- * @Time: 10:04
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @return \yii\db\ActiveQuery
- */
- public function getUser(){
- return $this->hasOne(User::class, ['id' => 'user_id']);
- }
- /**
- * @desc:关联经销商等级
- * @Author: hua
- * @Date: 2021/11/5
- * @Time: 10:04
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @return \yii\db\ActiveQuery
- */
- public function getAgentLevel(){
- return $this->hasOne(AgentLevel::class, ['level' => 'level','mall_id'=>'mall_id'])->andWhere(['<>','status',StatusEnum::DELETE]);
- }
- public function getUserTeamStatistics(){
- return $this->hasOne(UserTeamStatistics::class, ['user_id' => 'user_id']);
- }
- /**
- * @desc:保存数据
- * @Author: hua
- * @Date: 2021/10/23
- * @Time: 17:23
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param array $params
- * @return Agent|false|null
- */
- 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('服务不存在或已删除');
- // 记录升级日志
- if (
- isset($params['level']) &&
- $model->level != $params['level']
- ) {
- $upgrade_log_obj = new AgentLevelUpgradeLog();
- $upgrade_log_obj->before_level = $model->level;
- $upgrade_log_obj->upgrade_type = $params['level'] > $model->level ? LevelUpgradeLogEnum::MANUALLY_UPGRADE : LevelUpgradeLogEnum::DOWNGRADE_MANUALLY;
- }
- }else{
- $model = new self();
- $model->loadDefaultValues();
- // 记录升级日志(如果创建的不是默认等级,则认为手动升级)
- if ($params['level'] > 0) {
- $upgrade_log_obj = new AgentLevelUpgradeLog();
- $upgrade_log_obj->before_level = 0;
- $upgrade_log_obj->upgrade_type = LevelUpgradeLogEnum::MANUALLY_UPGRADE;
- }
- }
- if (!$model->load($params, '')) throw new \Exception($model->getErrorMessage());
- if (!$model->save()) throw new Exception($model->getErrorMessage());
- if (isset($upgrade_log_obj)) {
- $upgrade_log_obj->admin_id = $params['admin_id'] ?? 0;
- $upgrade_log_obj->mall_id = $params['mall_id'];
- $upgrade_log_obj->user_id = $params['user_id'];
- $upgrade_log_obj->after_level = $params['level'];
- $upgrade_log_obj->save();
- }
- return $model;
- } catch (\Exception $e) {
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- /**
- * @desc:批量修改等级
- * @Author: hua
- * @Date: 2021/10/23
- * @Time: 17:40
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $params
- * @return bool
- */
- public static function batchLevel($params) {
- try {
- if (isset($params['level']) && !empty($params['level'])) {
- $args = [];
- $args['where'] = [['mall_id'=>$params['mall_id']],['level'=>$params['level']],['<>','status',StatusEnum::DELETE]];
- $args['select'] = 'id,level,name';
- $agentList = AgentLevel::lists($args,true);
- if (empty($agentList)) {
- self::$static_error = '无效的经销商等级';
- return false;
- }
- } else {
- $params['level'] = 0;
- }
- self::updateAll(
- ['level' => $params['level'], 'upgrade_level_at' => time(), 'upgrade_status' => AgentEnum::UPGRADE_STATUS_MANUAL, 'updated_at' => time()],
- ['id' => $params['batch_ids']]
- );
- return true;
- } catch (\Exception $e) {
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- /**
- * 导出字段
- */
- public static function exportFieldsList($field = null)
- {
- $fields = [
- 'a.user_id' => '用户ID',
- 'u.nickname' => '昵称',
- 'u.mobile' => '手机号',
- 'a.created_at' => '成为经销商时间',
- 'a.upgrade_level_at' => '经销商升级时间',
- 'a.total_commission' => '累计佣金',
- 'a.level' => '经销商等级',
- 'a.level level_id' => '经销商等级id',
- 'u.nickname parent_name' => '推荐人',
- 'a.remarks' => '备注信息'
- ];
- $temp = [];
- foreach ($fields as $key => $val) {
- $showField = explode('.', $key)[1];
- if (strstr($showField, ' ')) {
- $showField = explode(' ', $showField)[1];
- }
- if ($field === null) {
- $temp[$showField] = $val;
- } else if (in_array($showField, $field)) {
- $temp[$key] = $val;
- }
- }
- return $temp;
- }
- /**
- * @name:
- * @msg: 处理导出数据,这个方法是异步队列处理时使用的,请别修改
- * @param {array} $data
- * @param {int} $mall_id
- * @return array
- */
- // 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);
- // $exportField = self::exportFieldsList($params['fields']);
- // $params = self::getParams($params);
- // $params['select'] = array_keys($exportField);
- // $filename = $download->name;
- // $type = $download->type;
- // $model = self::find();
- // self::paramPack($params, $model);
- // $csv = new CsvTool();
- // $csv->filename = $filename;
- // $csv->file_dirname = DownloadEnum::getTypeStorageDirMap($type);
- // $csv->export_mode = CsvTool::EXPORT_MODE_ASYNC;
- // $list = [];
- // foreach (array_values($exportField) as $val) {
- // $list[] = iconv("UTF-8", "gbk//TRANSLIT", $val);
- // }
- // foreach ($model->batch() as $agents) {
- // $agents = ArrayHelper::toArray($agents);
- // // $users 是一个包含100条或小于100条用户表数据的数组
- // empty($csv->header) && $csv->header = $list;
- // $csv->data = array_map(function($agent){
- // return array_values($agent);
- // },$agents);
- // $csv->export();
- // }
- // $url = $csv->upload($params['mall_id'],$csv->relative_filename);
- // $download->url = $url;
- // $download->status = 2;
- // $download->size = $csv->file_size;
- // $download->num = $csv->line_num;
- // $download->save();
- // return true;
- // }catch(Exception $e){
- // $download->status = 3;
- // self::setStaticError($e->getMessage());
- // return false;
- // }
- // }
- // }
- public static function fieldsList($field = null){
- $fields = [
- 'user_id' => '用户ID',
- 'nickname' => '昵称',
- 'mobile' => '手机号',
- 'created_at' => '成为经销商时间',
- 'upgrade_level_at' => '经销商升级时间',
- 'total_commission' => '累计佣金',
- 'level' => '经销商等级',
- 'level_id' => '经销商等级id',
- 'parent_name' => '推荐人',
- 'remarks' => '备注信息',
- ];
- if ($field === null) return $fields;
- $temp = [];
- foreach ($field as $val) {
- if (isset($fields[$val])) $temp[$val] = $fields[$val];
- }
- return $temp;
- }
- /**
- * @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::fieldsList();
- $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]);
- }
- $model->with(['user','agentLevel'=>function($query){
- $query->where(['status'=>StatusEnum::ENABLED]);
- }]);
- //遍历组装数据
- foreach ($model->batch() as $list) {
- $parent_id_arr = $parent_arr = [];
- //查询上级昵称数组
- if(in_array('parent_name',$fields)){
- foreach ($list as $item){
- $parent_id_arr[] = $item['user']['parent_id'];
- }
- $parent_arr = UserPartitionRelationship::getParentsNickname($parent_id_arr);
- }
- $csv->data = array_map(function($agent)use($fields,$parent_arr){
- $row = [];
- //遍历所选字段
- foreach ($fields as $field){
- if(in_array($field,['created_at'])){
- $row[] = !empty($agent[$field])?date('Y-m-d H:i:s',$agent[$field]):'';
- } elseif (in_array($field, ['upgrade_level_at'])) {
- $row[] = !empty($agent[$field]) ? date('Y-m-d H:i:s', $agent[$field]) : '';
- } elseif(in_array($field,['nickname','mobile'])){
- $row[] = !empty($agent['user'][$field])?$agent['user'][$field]:'';
- }elseif(in_array($field,['level'])){
- $row[] = !empty($agent['agentLevel']['name'])?$agent['agentLevel']['name']:'';
- }elseif(in_array($field,['level_id'])){
- $row[] = !empty($agent['agentLevel']['level'])?$agent['agentLevel']['level']:'';
- }
- elseif(in_array($field,['parent_name'])){
- $row[] = !empty($parent_arr[$agent['user']['parent_id']])?$parent_arr[$agent['user']['parent_id']]:'平台';
- }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 static function getParams($getData) {
- $params = [];
- if(isset($getData['user_id']) && !empty($getData['user_id'])) $params['where'][] = ['=', 'u.id', $getData['user_id']];
- if(isset($getData['level']) && !empty($getData['level'])) $params['where'][] = ['=', 'a.level', $getData['level']];
- if (isset($getData['keyword']) && !empty($getData['keyword'])) {
- $params['where'] = [[
- 'or',
- ['like', 'u.username', $getData['keyword']],
- ['like', 'u.nickname', $getData['keyword']],
- ['like', 'u.mobile', $getData['keyword']]
- ]];
- }
- $params['where'][] = ['=', 'a.mall_id', $getData['mall_id']];
- $params['where'][] = ['in', 'a.status', [StatusEnum::ENABLED,StatusEnum::DISABLED]];
- $params['alias'] = 'a';
- $params['join'] = [['LEFT JOIN', User::tableName() . ' up', "up.id = u.parent_id"]];
- $params['joinWith'] = ['user' => function($query){ $query->from(['u' => User::tableName()]); }];
- return $params;
- }
- /**
- * @desc:推广中心-调用
- * @Author: hua
- * @Date: 2021/11/12
- * @Time: 9:31
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param array $params ['user_id' => 1, 'mall_id' => 5, 'addons_name' => 'Agent']
- * @return array
- */
- public static function getIncomeInfo(array $params){
- $is_install = MallAddons::isInstall($params['mall_id'], $params['addons_name']);
- $data['total_commission'] = 0;
- $data['is_install'] = 0;
- $basic = \Yii::$app->services->setting->addons->get($params['mall_id'], $params['addons_name'], 'basic');
- $data['is_show_at_center'] = 1;
- if(isset($basic['is_show_at_center'])) $data['is_show_at_center'] = $basic['is_show_at_center'];
- if($is_install){
- $model = self::findOne(['user_id'=>$params['user_id'],'mall_id'=>$params['mall_id'],'status'=>[StatusEnum::ENABLED,StatusEnum::DISABLED]]);
- $data['total_commission'] = $model['total_commission']??0;
- $data['is_install'] = $is_install;
- }
- return $data;
- }
- public static function getAddons(array $params){
- $is_install = MallAddons::isInstall($params['mall_id'], AgentEnum::ADDONS_NAME);
- if($is_install){
- $detail = Addons::getOne([['name' => AgentEnum::ADDONS_NAME], ['is_online' => 1]], true);
- return [
- 'addons_name'=>AgentEnum::ADDONS_NAME,
- 'title'=>$detail['title'],
- ];
- }
- return [];
- }
- public static function getDeductMoney($params){
- if(empty($params['mall_id'])||empty($params['user_id'])||empty($params['type'])) return $params;
- $agent = Agent::findOne(['user_id'=>$params['user_id'],'status'=>StatusEnum::ENABLED]);
- $user_id = $params['user_id'];
- $mall_id = $params['mall_id'];
- $type = $params['type'];
- if(empty($agent)){
- if(!empty($params['goods_list'])) return $params;
- return $params;
- }
- $setting = \Yii::$app->services->setting->addons->get($mall_id, \common\enums\AddonsEnum::ADDONS_NAME_AGENT, 'basic');
- if (empty($setting['is_self_buy']) || empty($setting['enable_goods_deduct'])) {
- return $params;
- }
- switch ($type){
- case 'goods':
- $goods_ids = array_column( $params['goods_list'],'id');
- $item_setting_List = AgentCommissionItemSetting::find()->select('item_id,is_participate')
- ->where(['item_id' => $goods_ids, 'status' => StatusEnum::ENABLED])
- ->indexBy('item_id')
- ->asArray()->all();
- foreach ($goods_ids as $k=>$goods_id){
- if(isset($item_setting_List[$goods_id])&&empty($item_setting_List[$goods_id]['is_participate'])){
- unset($goods_ids[$k]);
- }
- }
- $attr_list = GoodsAttr::lists(['where'=>[['goods_id'=>$goods_ids],['status'=>StatusEnum::ENABLED]],'index'=>'goods_id']);
- $goods_attr_id_arr = [];
- $goods_attr_id_map = [];
- foreach ($attr_list as $value){
- $goods_attr_id_arr[$value['id']] = 1;
- $goods_attr_id_map[$value['goods_id']] =$value['id'] ;
- }
- $result = \common\logic\order\marketing\AgentMarketing::getDeductMoney($mall_id,$user_id,$goods_attr_id_arr);
- foreach ($params['goods_list'] as &$item){
- if(isset($goods_attr_id_map[$item['id']])){
- $attr_id =$goods_attr_id_map[$item['id']];
- if(isset($result[$attr_id])){
- $item['member_price']=bcadd($result[$attr_id],0,2);
- }else{
- $item['member_price'] = 0;
- }
- }
- }
- return $params;
- case 'goods_cate':
- foreach ($params['goods_list'] as &$item){
- if(!is_array($item)) continue;
- $goods_ids = array_column($item,'id');
- $item_setting_List = AgentCommissionItemSetting::find()->select('item_id,is_participate')
- ->where(['item_id' => $goods_ids, 'status' => StatusEnum::ENABLED])
- ->indexBy('item_id')
- ->asArray()->all();
- foreach ($goods_ids as $k=>$goods_id){
- if(isset($item_setting_List[$goods_id])&&empty($item_setting_List[$goods_id]['is_participate'])){
- unset($goods_ids[$k]);
- }
- }
- $attr_list = GoodsAttr::lists(['where'=>[['goods_id'=>$goods_ids],['status'=>StatusEnum::ENABLED]],'index'=>'goods_id']);
- $goods_attr_id_arr = [];
- $goods_attr_id_map = [];
- foreach ($attr_list as $value){
- $goods_attr_id_arr[$value['id']] = 1;
- $goods_attr_id_map[$value['goods_id']] =$value['id'] ;
- }
- $result = \common\logic\order\marketing\AgentMarketing::getDeductMoney($mall_id,$user_id,$goods_attr_id_arr);
- foreach ($item as &$val){
- if(isset($goods_attr_id_map[$val['id']])){
- $attr_id =$goods_attr_id_map[$val['id']];
- if(isset($result[$attr_id])){
- $val['member_price']=bcadd($result[$attr_id],0,2);
- }else{
- $val['member_price'] = 0;
- }
- }
- }
- }
- return $params;
- }
- }
- /**
- * 可供导出供应商库存的字段
- * @Author:hua
- * @Date:2024-02-23 16:37
- * @Copyright:copyright(c)2024 广东七件事集团
- * @return string[]
- */
- public static function getSupplierStockExportFieldsList()
- {
- return [
- 'user_id' => '代理ID',
- 'nickname' => '昵称',
- 'mobile' => '手机号',
- 'level' => '身份',
- 'stock' => '代理库存',
- 'cooperative_shipping_type' => '合作发货类型',
- 'counts' => '累计出货',
- 'change_num' => '当前收入',
- 'total_commission' => '累计收入',
- ];
- }
- /**
- * 导出供应商库存
- * @Author:hua
- * @Date:2024-02-23 16:38
- * @Copyright:copyright(c)2024 广东七件事集团
- * @param array $data
- * @return bool|void
- */
- public static function exportHandleSupplierStock(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::getSupplierStockExportFieldsList();
- $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']]);
- //拼接查询条件
- if (!empty($params['level'])) $model->andWhere(['=', 'level', $params['level']]);
- if (!empty($params['keyword'])) {
- $condition['where'] = [[
- 'or',
- ['=', 'id', $params['keyword']],
- ['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');
- $model->andWhere(['in', 'user_id', $user_id_arr]);
- }
- $model->with(['user']);
- //遍历组装数据
- $args = [];
- $args['where'] = [['mall_id' => $params['mall_id']], ['<>', 'status', StatusEnum::DELETE]];
- $args['select'] = 'id,level,name';
- $args['index'] = 'level';
- $level_list = AgentLevel::lists($args, true);
- foreach ($model->batch() as $list) {
- $user_id_arr = array_column($list,'user_id');
- $dsn = Yii::$app->db->dsn;
- $commission_log_list = $commission_log_count_list = [];
- if(strpos($dsn,'port=8066')===false){
- $commission_log_list = CommissionLog::lists([
- 'where'=>[
- ['user_id'=>$user_id_arr],
- ['from_type'=>'Agent']
- ],
- 'select'=>'sum(change_num) as change_num,user_id',
- 'group'=>'user_id',
- 'index'=>'user_id'
- ]);
- $commission_log_count_list = CommissionLog::lists([
- 'where'=>[
- ['user_id'=>$user_id_arr],
- ['from_type'=>'Agent']
- ],
- 'select'=>'count(*) counts,user_id',
- 'group'=>'user_id',
- 'index'=>'user_id'
- ]);
- }
- $csv->data = array_map(function ($agent) use ($fields, $level_list,$dsn,$commission_log_list,$commission_log_count_list) {
- $row = [];
- //遍历所选字段
- foreach ($fields as $field) {
- if (in_array($field, ['pay_time'])) {
- $row[] = !empty($agent[$field]) ? date('Y-m-d H:i:s', $agent[$field]) : '';
- } elseif (in_array($field, ['nickname'])) {
- $row[] = !empty($agent['user']['nickname']) ? $agent['user']['nickname'] : '';
- } elseif (in_array($field, ['mobile'])) {
- $row[] = !empty($agent['user']['mobile']) ? $agent['user']['mobile'] : '';
- } elseif (in_array($field, ['level'])) {
- if (isset($level_list[$agent['level']])) {
- $row[] = $level_list[$agent['level']]['name'];
- } else {
- $row[] = '普通会员';
- }
- } elseif (in_array($field, ['stock'])) {
- $row[] = '0件';
- } elseif (in_array($field, ['cooperative_shipping_type'])) {
- $row[] = '平台代发';
- } elseif (in_array($field, ['counts'])) {
- if(strpos($dsn,'port=8066')===false){
- if (isset($commission_log_count_list[$v['user_id']])) {
- $row[] = '¥'.$commission_log_count_list[$agent['user_id']]['counts'];
- } else {
- $row[] = '¥0';
- }
- }else{
- $counts = CommissionLog::find()->where(['user_id'=>$agent['user_id'],'from_type'=>'Agent'])->count();
- if(!empty($counts)) {
- $row[] = $counts;
- } else {
- $row[] = '¥0';
- }
- }
- } elseif (in_array($field, ['change_num'])) {
- if(strpos($dsn,'port=8066')===false) {
- if (isset($commission_log_list[$v['user_id']])) {
- $row[] = '¥'.$commission_log_list[$agent['user_id']]['change_num'];
- }else{
- $row[] = '¥0';
- }
- }else{
- $change_num = CommissionLog::find()->where(['user_id'=>$agent['user_id'],'from_type'=>'Agent'])->sum('change_num');
- if(!empty($change_num)) {
- $row[] = '¥'.$change_num;
- } else {
- $row[] = '¥0';
- }
- }
- } elseif (in_array($field, ['total_commission'])) {
- if(!empty($agent[$field])&&$agent[$field]!='0.00') {
- $row[] = '¥'.$agent[$field];
- }else{
- $row[] = '¥0';
- }
- } 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();
- self::setStaticError($e->getMessage());
- return false;
- }
- }
- }
- /**
- * 获取升级条件包含自身
- * @param $mall_id
- * @param $user_id
- * @return bool
- */
- public static function getUpgradeContainSelf($mall_id,$user_id)
- {
- $contain_self = true;
- $more_setting = \Yii::$app->services->setting->addons->get($mall_id, AddonsEnum::ADDONS_NAME_AGENT, 'more');
- $is_apply = $more_setting['is_apply'] ?? 0;
- if($is_apply){
- $agent_user = Agent::findOne(['user_id' => $user_id,'status' => StatusEnum::ENABLED]);
- $apply = AgentApply::findOne(['user_id' => $user_id,'status' => StatusEnum::ENABLED,'check_status' => AgentApply::CHECK_STATUS_SUCCESS]);
- if(!$agent_user && !$apply){
- $contain_self = false;
- }
- }
- return $contain_self;
- }
- /**
- * 批量更新代理等级
- * @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 = AgentImportLevelLog::setData($param);
- if (!$import_log_model) throw new \Exception(AgentImportLevelLog::getStaticError());
- if (!empty($fail_arr)) {
- $res = AgentImportLevelFailLog::setData($fail_arr, $import_log_model->id);
- if (!$res) throw new \Exception(AgentImportLevelFailLog::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 = AgentImportLevelLog::setData($param);
- if (!$user_import_log_model) throw new \Exception(AgentImportLevelLog::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 = AgentImportLevelLog::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 = AgentImportLevelLog::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++;
- $mobile=0;
- $level_id=0;
- foreach ($fileData as $k => &$val) {
- $val = mb_convert_encoding(trim($val), "UTF-8", "GBK");
- switch ($k) {
- case 1:
- $mobile = !empty($val)?$val:'';
- break;
- case 2:
- $level_id = !empty($val)?trim($val):0;
- break;
- }
- }
- $param['mobile'] = $mobile;
- $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 = AgentImportLevelFailLog::setData($fail_arr, $model->id);
- if (!$res) throw new \Exception(AgentImportLevelFailLog::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[] = ['mobile' => $item['mobile']];
- $user = User::getUser($where,'id,mobile');
- if (empty($user)) {
- $fail_params['reason'] = '用户不存在';
- list($fail_arr, $fail_counts) = AgentImportLevelFailLog::packFailArr($fail_params, $fail_arr, $fail_counts);
- } else if (empty(AgentLevel::getOne([['level' => $item['level'],'status'=>1,'mall_id'=>$mall_id]]))) {
- $fail_params['reason'] = '经销商等级id不存在';
- list($fail_arr, $fail_counts) = AgentImportLevelFailLog::packFailArr($fail_params, $fail_arr, $fail_counts);
- } else {
- $agent = Agent::getOne([['user_id' => $user['id'], 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]]]); //加上条件:状态= 1[启用] && 0[禁用]
- if ($agent) {
- $item['id'] = $agent['id'];
- }
- $item['mall_id']=$mall_id;
- $item['user_id']=$user['id'];
- $item['upgrade_level_at']=time();
- $item['upgrade_status']=AgentEnum::UPGRADE_STATUS_MANUAL;
- $res = Agent::setData($item);
- if ($res) {
- $success_user_id_arr[] = $res['id'];
- $success_counts++;
- } else {
- $fail_params['reason'] = Agent::getStaticError();
- list($fail_arr, $fail_counts) = AgentImportLevelFailLog::packFailArr($fail_params, $fail_arr, $fail_counts);
- }
- }
- }
- }
- }
|