Agent.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. <?php
  2. namespace app\admin\controller\commission;
  3. use app\common\controller\Backend;
  4. use app\common\model\commission\Agent as AgentModel;
  5. use app\common\model\User as UserModel;
  6. use app\common\model\commission\Log as LogModel;
  7. use app\common\model\commission\Level as LevelModel;
  8. use app\common\Service\Commission\Agent as AgentService;
  9. use EasyWeChat\OfficialAccount\Server\Handlers\EchoStrHandler;
  10. use think\Db;
  11. class Agent extends Backend
  12. {
  13. protected $noNeedRight = ['select'];
  14. protected $model = null;
  15. /**
  16. * 快速搜索时执行查找的字段
  17. */
  18. protected $searchFields = 'user_id,user.nickname,user.mobile';
  19. /**
  20. * 是否是关联查询
  21. */
  22. protected $relationSearch = true;
  23. public function _initialize()
  24. {
  25. parent::_initialize();
  26. $this->model = new AgentModel();
  27. }
  28. /**
  29. * 查看
  30. */
  31. public function index()
  32. {
  33. if (!$this->request->isAjax()) {
  34. return $this->view->fetch();
  35. }
  36. //如果发送的来源是 Selectpage,则转发到 Selectpage
  37. if ($this->request->request('keyField')) {
  38. return $this->selectpage();
  39. }
  40. [$where, $sort, $order, $offset, $limit] = $this->buildparams();
  41. // 处理特殊筛选条件
  42. $filter = $this->request->get("filter", '');
  43. if ($filter) {
  44. $filter = json_decode($filter, true);
  45. if (isset($filter['tabActive'])) {
  46. if ($filter['tabActive'] === 'pending') {
  47. $where['status'] = 'pending';
  48. } elseif ($filter['tabActive'] === '0') {
  49. $where['level_status'] = ['>', 0];
  50. }
  51. }
  52. }
  53. $list = $this->model
  54. ->with(['user.parent_user', 'level_info', 'level_status_info', 'upgrade_level'])
  55. ->where($where)
  56. ->order($sort, $order)
  57. ->paginate($limit);
  58. $result = ['total' => $list->total(), 'rows' => $list->items()];
  59. return json($result);
  60. }
  61. /**
  62. * 详情
  63. *
  64. * @param $id
  65. */
  66. public function detail($ids = null)
  67. {
  68. $row = $this->model->with(['user.parent_user', 'level_info', 'level_status_info', 'upgrade_level'])
  69. ->where('user_id', $ids)
  70. ->find();
  71. if (!$row) {
  72. $this->error(__('No Results were found'));
  73. }
  74. // 如果expire_time为空,设置默认值为become_time + 1年
  75. // if (!$row->expire_time && $row->become_time) {
  76. // $row->expire_time = strtotime('+1 year', $row->become_time);
  77. // }
  78. $this->view->assign('row', $row);
  79. return $this->view->fetch();
  80. }
  81. /**
  82. * 团队
  83. *
  84. * @param $id
  85. */
  86. public function team($ids = null)
  87. {
  88. // 获取ID参数,优先使用URL中的id参数
  89. $ids = $ids ?: $this->request->param('id');
  90. // 将当前分销商ID传递给前端
  91. $this->assignconfig('current_agent_id', $ids);
  92. if (!$this->request->isAjax()) {
  93. // 获取当前分销商详细信息用于模板渲染
  94. $currentAgent = $this->model->with(['user.parent_user', 'level_info'])
  95. ->where('user_id', $ids)
  96. ->find();
  97. if (!$currentAgent) {
  98. $this->error(__('No Results were found'));
  99. }
  100. $this->view->assign('currentAgent', $currentAgent);
  101. return $this->view->fetch();
  102. }
  103. //如果发送的来源是 Selectpage,则转发到 Selectpage
  104. if ($this->request->request('keyField')) {
  105. return $this->selectpage();
  106. }
  107. [$where, $sort, $order, $offset, $limit] = $this->buildparams();
  108. // 以分销商表为主表查询团队成员
  109. // 安全的排序字段处理
  110. // $allowedSorts = ['user_id', 'status', 'level', 'total_income', 'pending_reward', 'become_time'];
  111. // $safeSort = in_array($sort, $allowedSorts) ? $sort : 'user_id';
  112. $list = $this->model
  113. ->hasWhere('user', function ($query) use ($ids) {
  114. return $query->where('parent_user_id', $ids);
  115. })
  116. ->with(['user', 'level_info'])
  117. // ->order($safeSort, $order ?: 'desc')
  118. ->paginate($limit);
  119. $result = array("total" => $list->total(), "rows" => $list->items());
  120. return json($result);
  121. }
  122. // 选择分销商
  123. public function select()
  124. {
  125. if (!$this->request->isAjax()) {
  126. return $this->view->fetch();
  127. }
  128. [$where, $sort, $order, $offset, $limit] = $this->buildparams();
  129. $data = $this->model
  130. ->with(['user', 'level_info', 'level_status_info', 'upgrade_level'])
  131. ->where($where)
  132. ->order($sort, $order)
  133. ->paginate($limit);
  134. $result = ['total' => $data->total(), 'rows' => $data->items()];
  135. return json($result);
  136. }
  137. /**
  138. * 编辑
  139. *
  140. * @param $id
  141. */
  142. public function edit($ids = null)
  143. {
  144. $params = $this->request->only(['status', 'upgrade_lock', 'level_status', 'level']);
  145. $row = $this->model->with(['user', 'level_info', 'level_status_info', 'upgrade_level'])->where('user_id', $ids)->find();
  146. if (!$row) {
  147. $this->error('未找到该分销商');
  148. }
  149. $result = false;
  150. foreach ($params as $field => $value) {
  151. switch ($field) {
  152. case 'status': // 修改状态
  153. $result = $this->changeStatus($row, $value);
  154. break;
  155. case 'level_status': // 审核等级
  156. $result = $this->changeLevelStatus($row, $value);
  157. break;
  158. case 'level': // 修改等级
  159. $result = $this->changeLevel($row, $value);
  160. break;
  161. default:
  162. $result = $row->save([$field => $value]);
  163. }
  164. }
  165. if ($result) {
  166. $this->success('更新成功');
  167. } else {
  168. $this->error('更新失败');
  169. }
  170. }
  171. // 修改状态
  172. private function changeStatus($row, $value)
  173. {
  174. $result = $row->save(['status' => $value]);
  175. if ($result) {
  176. LogModel::add($row->user_id, 'agent', ['type' => 'status', 'value' => $value]);
  177. (new AgentService($row->user_id))->createAsyncAgentUpgrade();
  178. }
  179. return $result;
  180. }
  181. // 审核等级
  182. private function changeLevelStatus($row, $value)
  183. {
  184. if ($row->level_status == 0 && $value > 0) {
  185. $this->error('非法操作');
  186. }
  187. if ($value == 0) { // 拒绝操作
  188. return $row->save(['level_status' => 0]);
  189. } else { // 同意操作
  190. if ($row->upgrade_level) {
  191. $result = $row->save(['level_status' => 0, 'level' => $row->upgrade_level->level]);
  192. if ($result) {
  193. LogModel::add($row->user_id, 'agent', ['type' => 'level', 'level' => $row->upgrade_level]);
  194. (new AgentService($row->user_id))->createAsyncAgentUpgrade();
  195. }
  196. return $result;
  197. }
  198. }
  199. return false;
  200. }
  201. // 修改等级
  202. private function changeLevel($row, $value)
  203. {
  204. $level = LevelModel::find($value);
  205. if ($level) {
  206. $result = $row->save(['level' => $level->level]);
  207. if ($result) {
  208. LogModel::add($row->user_id, 'agent', ['type' => 'level', 'level' => $level]);
  209. (new AgentService($row->user_id))->createAsyncAgentUpgrade();
  210. }
  211. return $result;
  212. } else {
  213. $this->error('未找到该等级');
  214. }
  215. }
  216. // 更换推荐人
  217. public function changeParentUser($id)
  218. {
  219. $userAgent = new AgentService($id);
  220. if (!$userAgent->user) {
  221. $this->error('未找到该用户');
  222. }
  223. $parentUserId = $this->request->param('parent_user_id', 0);
  224. // 更换推荐人检查
  225. if ($parentUserId != 0) {
  226. $parentAgent = new AgentService($parentUserId);
  227. if (!$parentAgent->isAgentAvaliable()) {
  228. $this->error('选中用户暂未成为分销商,不能成为推荐人');
  229. }
  230. if (!$this->checkChangeParentAgent($id, $parentUserId)) {
  231. $this->error('不能绑定该上级');
  232. }
  233. LogModel::add($parentUserId, 'share', ['user' => $userAgent->user]);
  234. if ($userAgent->isAgentAvaliable()) {
  235. LogModel::add($id, 'bind', ['user' => $parentAgent->user ?? NULL]);
  236. }
  237. }
  238. $lastParentUserId = $userAgent->user->parent_user_id;
  239. $userAgent->user->parent_user_id = $parentUserId;
  240. $userAgent->user->save();
  241. if ($lastParentUserId > 0) {
  242. $userAgent->createAsyncAgentUpgrade($lastParentUserId);
  243. }
  244. if ($parentUserId > 0) {
  245. $userAgent->createAsyncAgentUpgrade($parentUserId);
  246. }
  247. $this->success('绑定成功');
  248. }
  249. // 递归往上找推荐人,防止出现推荐循环
  250. private function checkChangeParentAgent($userId, $parentUserId)
  251. {
  252. if ($userId == $parentUserId) {
  253. $this->error('推荐人不能是本人');
  254. }
  255. if ($parentUserId == 0) {
  256. return true;
  257. }
  258. $parentAgent = UserModel::find($parentUserId);
  259. if ($parentAgent) {
  260. if ($parentAgent->parent_user_id == $userId) {
  261. $this->error("已选中分销商的上级团队中已存在该用户");
  262. }
  263. if ($parentAgent->parent_user_id == 0) {
  264. return true;
  265. } else {
  266. return $this->checkChangeParentAgent($userId, $parentAgent->parent_user_id);
  267. }
  268. }
  269. return false;
  270. }
  271. /**
  272. * 更新分销商到期时间
  273. */
  274. public function updateExpireTime()
  275. {
  276. $userId = $this->request->param('user_id');
  277. $expireTime = $this->request->param('expire_time');
  278. if (!$userId) {
  279. $this->error(__('参数错误'));
  280. }
  281. // 验证分销商是否存在
  282. $agent = AgentModel::get($userId);
  283. if (!$agent) {
  284. $this->error(__('分销商不存在'));
  285. }
  286. // 验证时间格式
  287. if ($expireTime && !strtotime($expireTime)) {
  288. $this->error(__('时间格式不正确'));
  289. }
  290. // try {
  291. // 更新到期时间
  292. $updateData = [];
  293. if ($expireTime) {
  294. $updateData['expire_time'] = strtotime($expireTime);
  295. } else {
  296. $updateData['expire_time'] = null; // 设置为null表示永久有效
  297. }
  298. $result = AgentModel::where('user_id', $userId)->update($updateData);
  299. if ($result !== false) {
  300. $this->success(__('修改成功'));
  301. } else {
  302. $this->error(__('修改失败'));
  303. }
  304. // } catch (\Exception $e) {
  305. // $this->error(__('修改失败: %s', $e->getMessage()));
  306. // }
  307. }
  308. /**
  309. * 设置默认到期时间
  310. * 在用户成为分销商时调用,设置默认到期时间为成为分销商时间+1年
  311. */
  312. public function setDefaultExpireTime($userId, $becomeTime = null)
  313. {
  314. if (!$becomeTime) {
  315. $becomeTime = time(); // 如果没有传入成为分销商时间,使用当前时间
  316. }
  317. // 计算默认到期时间(1年后)
  318. $expireTime = strtotime('+1 year', $becomeTime);
  319. // 更新到期时间
  320. AgentModel::where('user_id', $userId)->update([
  321. 'expire_time' => $expireTime
  322. ]);
  323. return $expireTime;
  324. }
  325. }