Distribution.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. <?php
  2. namespace addons\CircleDistribution\common\models;
  3. use addons\CircleDistribution\common\enums\DistributionEnum;
  4. use common\enums\AddonsEnum;
  5. use common\enums\StatusEnum;
  6. use common\models\base\BaseActiveRecord;
  7. use common\models\common\Addons;
  8. use common\models\common\CapitalLog;
  9. use common\models\common\Download;
  10. use common\enums\DownloadEnum;
  11. use common\models\mall\MallAddons;
  12. use common\models\user\User;
  13. use common\models\user\UserPartitionRelationship;
  14. use Exception;
  15. use common\components\export\CsvTool;
  16. /**
  17. * This is the model class for table "{{%addons_circle_distribution}}".
  18. *
  19. * @property int $id
  20. * @property int $mall_id
  21. * @property int $user_id
  22. * @property string|null $remarks 备注
  23. * @property int $status
  24. * @property int $created_at 创建时间
  25. * @property int $updated_at 修改时间
  26. * @property int $level 分销商等级
  27. * @property int $upgrade_level_at 分销商等级升级时间
  28. * @property float $total_commission 佣金
  29. * @property float $total_score 积分
  30. * @property User $user
  31. * @property int $upgrade_status
  32. */
  33. class Distribution extends BaseActiveRecord
  34. {
  35. const UPGRADE_STATUS_CONDITION = 1;
  36. const UPGRADE_STATUS_GOODS = 2;
  37. const UPGRADE_STATUS_MANUAL = 3;
  38. /**
  39. * {@inheritdoc}
  40. */
  41. public static function tableName()
  42. {
  43. return '{{%addons_circle_distribution}}';
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function rules()
  49. {
  50. return [
  51. [['mall_id', 'user_id'], 'required'],
  52. [['mall_id', 'user_id', 'status', 'created_at', 'updated_at', 'level', 'upgrade_level_at', 'upgrade_status'], 'integer'],
  53. [['remarks'], 'string'],
  54. [['total_commission','total_score'], 'number'],
  55. ];
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public function attributeLabels()
  61. {
  62. return [
  63. 'id' => 'ID',
  64. 'mall_id' => 'Mall ID',
  65. 'user_id' => 'User ID',
  66. 'remarks' => '备注',
  67. 'status' => '状态[-1:删除;0:禁用;1启用]',
  68. 'created_at' => '创建时间',
  69. 'updated_at' => '修改时间',
  70. 'level' => '分销商等级',
  71. 'upgrade_level_at' => '分销商等级升级时间',
  72. 'total_commission' => '总佣金',
  73. 'total_score' => '总积分',
  74. 'upgrade_status' => '升级方式,1条件升级 2 购买指定商品升级 3手动升级'
  75. ];
  76. }
  77. public function getUser()
  78. {
  79. return $this->hasOne(User::class, ['id' => 'user_id']);
  80. }
  81. // public function getDistributionLevel()
  82. // {
  83. // return $this->hasOne(DistributionLevel::class, ['level' => 'level','mall_id'=>'mall_id'])->where(['status' => StatusEnum::ENABLED]);
  84. // }
  85. public function afterSave($insert, $changedAttributes)
  86. {
  87. return parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
  88. }
  89. /**
  90. * @desc:保存数据
  91. * @Author: hua
  92. * @Date: 2021/10/23
  93. * @Time: 18:07
  94. * @Copyright: copyright (c) 2021 广东七件事集团
  95. * @param array $params
  96. * @return Distribution|false|null
  97. */
  98. public static function setData(array $params)
  99. {
  100. try {
  101. if (!empty($params['id'])) {
  102. $model = self::findOne(['mall_id' => $params['mall_id'], 'id' => $params['id'], 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]]);
  103. if (empty($model)) throw new \Exception('服务不存在或已删除');
  104. } else {
  105. $model = new self();
  106. $model->loadDefaultValues();
  107. }
  108. if (!$model->load($params, '')) throw new \Exception($model->getErrorMessage());
  109. if (!$model->save()) throw new Exception($model->getErrorMessage());
  110. return $model;
  111. } catch (\Exception $e) {
  112. self::$static_error = $e->getMessage();
  113. return false;
  114. }
  115. }
  116. /**
  117. * @desc:导出字段
  118. * @param array|null $field
  119. * @Author: hua
  120. * @Date: 2021/10/23
  121. * @Time: 18:03
  122. * @Copyright: copyright (c) 2021 广东七件事集团
  123. * @return \string[][]
  124. */
  125. public static function exportFieldsList($field = null)
  126. {
  127. $fields = [
  128. 'a.user_id' => '用户ID',
  129. 'u.nickname' => '昵称',
  130. 'u.mobile' => '手机号',
  131. 'a.created_at' => '成为经销商时间',
  132. 'a.total_commission' => '累计佣金',
  133. 'a.level' => '经销商等级',
  134. 'u.nickname parent_name' => '推荐人',
  135. 'a.remarks' => '备注信息'
  136. ];
  137. $temp = [];
  138. foreach ($fields as $key => $val) {
  139. $showField = explode('.', $key)[1];
  140. if (strstr($showField, ' ')) {
  141. $showField = explode(' ', $showField)[1];
  142. }
  143. if ($field === null) {
  144. $temp[$showField] = $val;
  145. } else if (in_array($showField, $field)) {
  146. $temp[$key] = $val;
  147. }
  148. }
  149. return $temp;
  150. }
  151. public static function fieldsList($field = null)
  152. {
  153. $fields = [
  154. 'user_id' => '用户ID',
  155. 'nickname' => '昵称',
  156. 'mobile' => '手机号',
  157. 'created_at' => '成为分销商时间',
  158. 'total_commission' => '累计佣金',
  159. 'level' => '分销商等级',
  160. 'parent_name' => '推荐人',
  161. 'remarks' => '备注信息',
  162. ];
  163. if ($field === null) return $fields;
  164. $temp = [];
  165. foreach ($field as $val) {
  166. if (isset($fields[$val])) $temp[$val] = $fields[$val];
  167. }
  168. return $temp;
  169. }
  170. /**
  171. * @name:
  172. * @msg: 处理导出数据,这个方法是异步队列处理时使用的,请别修改
  173. * @param {array} $data
  174. * @return bool
  175. */
  176. public static function exportHandle(array $data)
  177. {
  178. $download_id = $data['download_id'] ?? 0;
  179. $download = Download::findOne(['id' => $download_id]);
  180. if ($download) {
  181. try {
  182. $params = json_decode($download->params, true);
  183. $filename = $download->name;
  184. $type = $download->type;
  185. $fields = $params['fields'];
  186. $fields_arr = self::fieldsList();
  187. $have_select_field_arr = [];
  188. foreach ($fields as $value) {
  189. $have_select_field_arr[] = $fields_arr[$value];
  190. }
  191. $csv = new CsvTool();
  192. $csv->filename = $filename;
  193. $csv->file_dirname = DownloadEnum::getTypeStorageDirMap($type);
  194. $csv->export_mode = CsvTool::EXPORT_MODE_ASYNC;
  195. $csv->header = $have_select_field_arr;
  196. $model = self::find();
  197. $model->where(['mall_id' => $params['mall_id']]);
  198. $model->andWhere(['>=', 'status', StatusEnum::DISABLED]);
  199. $user_id = 0;
  200. $user_id_arr = [];
  201. //拼接查询条件
  202. if (!empty($params['user_id'])) $user_id = $params['user_id'];
  203. if (!empty($params['level'])) $model->andWhere(['=', 'level', $params['level']]);
  204. if (!empty($params['keyword'])) {
  205. $condition['where'] = [[
  206. 'or',
  207. ['like', 'username', $params['keyword']],
  208. ['like', 'nickname', $params['keyword']],
  209. ['like', 'mobile', $params['keyword']]
  210. ]];
  211. $user_list = User::lists($condition);
  212. $user_id_arr = array_column($user_list, 'id');
  213. }
  214. if ($user_id && $user_id_arr) {
  215. $user_ids = array_intersect([$user_id], $user_id_arr);
  216. $model->andWhere(['in', 'user_id', $user_ids]);
  217. } else if ($user_id) {
  218. $model->andWhere(['in', 'user_id', $user_id]);
  219. } elseif ($user_id_arr) {
  220. $model->andWhere(['in', 'user_id', $user_id_arr]);
  221. }
  222. $model->with(['user']);//关联查询
  223. //遍历组装数据
  224. foreach ($model->batch() as $list) {
  225. $parent_id_arr = $parent_arr = [];
  226. //查询上级昵称数组
  227. if (in_array('parent_name', $fields)) {
  228. foreach ($list as $item) {
  229. $parent_id_arr[] = $item['user']['parent_id'];
  230. }
  231. $parent_arr = UserPartitionRelationship::getParentsNickname($parent_id_arr);
  232. }
  233. $csv->data = array_map(function ($distribution) use ($fields, $parent_arr) {
  234. $row = [];
  235. //遍历所选字段
  236. foreach ($fields as $field) {
  237. if (in_array($field, ['created_at'])) {
  238. $row[] = !empty($distribution[$field]) ? date('Y-m-d H:i:s', $distribution[$field]) : '';
  239. } elseif (in_array($field, ['nickname', 'mobile'])) {
  240. $row[] = !empty($distribution['user'][$field]) ? $distribution['user'][$field] : '';
  241. } elseif (in_array($field, ['level'])) {
  242. //$row[] = !empty($distribution['distributionLevel']['name']) ? $distribution['distributionLevel']['name'] : '';
  243. } elseif (in_array($field, ['parent_name'])) {
  244. $row[] = !empty($parent_arr[$distribution['user']['parent_id']]) ? $parent_arr[$distribution['user']['parent_id']] : '平台';
  245. } else {
  246. $row[] = !empty($distribution[$field]) ? $distribution[$field] : '';
  247. }
  248. }
  249. return $row;
  250. }, $list);
  251. $csv->export();
  252. }
  253. //上传云存储
  254. $csv->updateDown($download, $params['mall_id']);
  255. return true;
  256. } catch (Exception $e) {
  257. $download->status = 3;
  258. $res = $download->save();
  259. self::setStaticError($e->getMessage());
  260. return false;
  261. }
  262. }
  263. }
  264. public static function getParams($getData)
  265. {
  266. $params = [];
  267. if (isset($getData['user_id']) && !empty($getData['user_id'])) $params['where'][] = ['=', 'u.id', $getData['user_id']];
  268. if (isset($getData['level']) && !empty($getData['level'])) $params['where'][] = ['=', 'a.level', $getData['level']];
  269. if (isset($getData['keyword']) && !empty($getData['keyword'])) {
  270. $params['where'] = [[
  271. 'or',
  272. ['like', 'u.username', $getData['keyword']],
  273. ['like', 'u.nickname', $getData['keyword']],
  274. ['like', 'u.mobile', $getData['keyword']]
  275. ]];
  276. }
  277. $params['where'][] = ['=', 'a.mall_id', $getData['mall_id']];
  278. $params['where'][] = ['in', 'a.status', [StatusEnum::ENABLED, StatusEnum::DISABLED]];
  279. $params['alias'] = 'a';
  280. $params['join'] = [['LEFT JOIN', User::tableName() . ' up', "up.id = u.parent_id"]];
  281. $params['joinWith'] = ['user' => function ($query) {
  282. $query->from(['u' => User::tableName()]);
  283. }];
  284. return $params;
  285. }
  286. /**
  287. * @desc:推广中心-调用
  288. * @Author: hua
  289. * @Date: 2021/11/12
  290. * @Time: 9:30
  291. * @Copyright: copyright (c) 2021 广东七件事集团
  292. * @param array $params ['user_id' => 1, 'mall_id' => 5, 'addons_name' => 'Agent']
  293. * @return array
  294. */
  295. public static function getIncomeInfo(array $params)
  296. {
  297. $is_install = MallAddons::isInstall($params['mall_id'], $params['addons_name']);
  298. $data['total_commission'] = 0;
  299. $data['is_install'] = 0;
  300. $basic = \Yii::$app->services->setting->addons->get($params['mall_id'], $params['addons_name'], 'basic');
  301. $data['is_show_at_center'] = 1;
  302. if(isset($basic['is_show_at_center'])) $data['is_show_at_center'] = $basic['is_show_at_center'];
  303. if ($is_install) {
  304. $model = self::findOne(['user_id' => $params['user_id']]);
  305. $data['total_commission'] = $model['total_commission'] ?? 0;
  306. $data['is_install'] = $is_install;
  307. }
  308. return $data;
  309. }
  310. public static function getDistributionList($is_self_buy, $mall_id, $user_id)
  311. {
  312. $parent_id_arr = UserPartitionRelationship::getParentIdArr($user_id);
  313. $deep = ($is_self_buy == 1) ? 2 : 3;
  314. $new_parent_id_arr = [];
  315. for ($i = 0; $i < $deep; $i++) {
  316. $new_parent_id_arr[] = array_pop($parent_id_arr);
  317. }
  318. $where = ['user_id' => $new_parent_id_arr, 'mall_id' => $mall_id, 'status' => StatusEnum::ENABLED];
  319. $addons_distribution_list = Distribution::find()->where($where)->indexBy('user_id')->all();//查询分销商列表
  320. $distribution_list = [];
  321. foreach ($new_parent_id_arr as $k => $parent_id) {
  322. $distribution_list[$k] = [];
  323. if (!empty($addons_distribution_list[$parent_id])) $distribution_list[$k] = $addons_distribution_list[$parent_id];//按照关系排序
  324. }
  325. if ($is_self_buy) {
  326. $distribution = Distribution::findOne(['user_id' => $user_id]);
  327. if ($distribution) array_unshift($distribution_list, $distribution);
  328. }
  329. return $distribution_list;
  330. }
  331. public static function distributionInfo($user, $mall_id)
  332. {
  333. $configs = \Yii::$app->services->setting->addons->get($mall_id, DistributionEnum::ADDONS_NAME, 'basic');
  334. $distribution = Distribution::getOne([['user_id' => $user['id']], ['status' => StatusEnum::ENABLED], ['mall_id' => $mall_id]], true);
  335. if (empty($configs['is_apply'])) {
  336. //无条件
  337. if (empty($distribution)) {
  338. $params['user_id'] = $user['id'];
  339. $params['mall_id'] = $mall_id;
  340. $params['status'] = StatusEnum::ENABLED;
  341. $distribution = Distribution::setData($params);
  342. }
  343. }
  344. $data = [];
  345. $data['user_id'] = $user['id'];
  346. $data['nickname'] = empty($user->nickname) ? '' : $user->nickname;
  347. $data['avatar_url'] = empty($user->avatar_url) ? '' : $user->avatar_url;
  348. if (empty($distribution)) {
  349. $res = DistributionApply::getOne([['user_id' => $user['id']], ['status' => StatusEnum::ENABLED], ['mall_id' => $mall_id]], true, [], 'id desc');
  350. $setting = \Yii::$app->services->setting->addons->get($mall_id, DistributionEnum::ADDONS_NAME, 'basic');
  351. if (!empty($res)) {
  352. if ($res['check_status'] == 0) {
  353. $data['msg'] = '您已经申请了,请等待审核';
  354. $data['result'] = ['is_apply' => 2, 'msg' => '您已经申请了,请等待审核', 'is_distribution' => 0];
  355. return $data;
  356. }
  357. if ($res['check_status'] == 2) {
  358. $data['msg'] = $res['check_remark'];
  359. $data['result'] = ['is_apply' => 3, 'protocol' => $setting['protocol'], 'msg' => $res['check_remark'], 'is_distribution' => 0];
  360. }
  361. return $data;
  362. }
  363. $result = ['is_apply' => $setting['is_apply'], 'protocol' => $setting['protocol'], 'is_distribution' => 0];
  364. $data['msg'] = '您不是分销商';
  365. $data['result'] = $result;
  366. return $data;
  367. }
  368. $data['parent_name'] = '平台方';
  369. $data['parent_avatar_url'] = '';
  370. $data['parent_level_name'] = '';
  371. $parent_id = $user->parent_id ?? 0;
  372. if ($parent_id) {
  373. $parent = User::findOne($parent_id);
  374. $data['parent_name'] = $parent['nickname'] ?? '';
  375. $data['parent_avatar_url'] = $parent['avatar_url'] ?? '';
  376. $parent_distribution = Distribution::findOne(['user_id' => $parent_id]);
  377. //$data['parent_level_name'] = $parent_distribution->distributionLevel->name ?? '默认等级';
  378. }
  379. $data['is_distribution'] = 0;
  380. $data['level_name'] = '';
  381. $data['frozen_price'] = 0;
  382. $data['total_price'] = 0;
  383. $data['total_income'] = 0;
  384. $data['yesterday_price'] = 0;
  385. if ($distribution) {
  386. $data['is_distribution'] = 1;
  387. //$data['level_name'] = $distribution['distributionLevel']['name'] ?? '默认等级';
  388. $wallet_type = 'commission';
  389. $yesterday = date('Y-m-d', strtotime('-1 day'));
  390. $start_time = "{$yesterday} 00:00:00";
  391. $end_time = "{$yesterday} 23:59:59";
  392. CapitalLog::$capitalType = "{$wallet_type}_frozen";
  393. $where = ['user_id' => $user['id'], 'from_type' => DistributionEnum::ADDONS_NAME, 'status' => CapitalLog::STATUS_WAIT_SEND];
  394. $query = CapitalLog::find();
  395. $frozen_price = $query->where($where)->sum('change_num');
  396. $yesterday_frozen_price = $query->where($where)
  397. ->andWhere(['<=', 'created_at', $end_time])
  398. ->andWhere(['>=', 'created_at', $start_time])
  399. ->sum('change_num');
  400. if (empty($yesterday_frozen_price)) $yesterday_frozen_price = 0;
  401. CapitalLog::$capitalType = "{$wallet_type}";
  402. $where = ['user_id' => $user['id'], 'from_type' => DistributionEnum::ADDONS_NAME];
  403. $query = CapitalLog::find();
  404. $total_price = $query->where($where)->sum('change_num');
  405. $yesterday_total_price = $query->where($where)
  406. ->andWhere(['<=', 'created_at', $end_time])
  407. ->andWhere(['>=', 'created_at', $start_time])
  408. ->sum('change_num');
  409. if (empty($yesterday_total_price)) $yesterday_total_price = 0;
  410. $data['total_price'] = empty($total_price) ? 0 : $total_price;
  411. $data['frozen_price'] = empty($frozen_price) ? 0 : $frozen_price;
  412. $data['total_income'] = intval(($data['total_price'] + $data['frozen_price']) * 100) / 100;
  413. $data['yesterday_price'] = $yesterday_total_price + $yesterday_frozen_price;
  414. }
  415. $data['is_show_share_level'] = $configs['is_show_share_level'] ?? 0;
  416. $data['msg'] = '';
  417. return $data;
  418. }
  419. public static function getAddons(array $params){
  420. $addons_name = $params['addons_name'];
  421. $is_install = MallAddons::isInstall($params['mall_id'], $addons_name);
  422. if($is_install){
  423. $detail = Addons::getOne([['name' =>$addons_name], ['is_online' => 1]], true);
  424. return [
  425. 'addons_name'=>$addons_name,
  426. 'title'=>$detail['title'],
  427. ];
  428. }
  429. return [];
  430. }
  431. }