123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315 |
- <?php
- namespace app\admin\controller\lottery;
- use app\common\controller\Backend;
- use think\Db;
- use think\exception\ValidateException;
- use think\exception\PDOException;
- use Exception;
- /**
- * 用户抽奖机会管理
- *
- * @icon fa fa-users
- */
- class UserChance extends Backend
- {
- /**
- * UserChance模型对象
- * @var \app\admin\model\lottery\UserChance
- */
- protected $model = null;
- public function _initialize()
- {
- parent::_initialize();
- $this->model = new \app\admin\model\lottery\UserChance;
-
- // 获取枚举值列表
- $this->view->assign("sourceTypeList", $this->model->getSourceTypeList());
- $this->view->assign("statusList", $this->model->getStatusList());
- }
- /**
- * 查看
- */
- public function index()
- {
- //当前是否为关联查询
- $this->relationSearch = true;
- //设置过滤方法
- $this->request->filter(['strip_tags', 'trim']);
- if ($this->request->isAjax()) {
- //如果发送的来源是Selectpage,则转发到Selectpage
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
-
- $list = $this->model
- ->with(['activity', 'user'])
- ->where($where)
- ->order($sort, $order)
- ->paginate($limit);
- foreach ($list as $row) {
- $row->visible(['id','activity_id','user_id','chance_count','used_count','source_type','source_value','expire_time','status','createtime']);
- $row->visible(['activity', 'user']);
- $row->getRelation('activity')->visible(['name']);
- $row->getRelation('user')->visible(['nickname', 'mobile']);
- }
-
- $result = array("total" => $list->total(), "rows" => $list->items());
- return json($result);
- }
- return $this->view->fetch();
- }
- /**
- * 添加
- */
- public function add()
- {
- if ($this->request->isPost()) {
- $params = $this->request->post("row/a");
- if ($params) {
- $params = $this->preExcludeFields($params);
-
- // 处理过期时间
- if (isset($params['expire_time']) && $params['expire_time']) {
- $params['expire_time'] = strtotime($params['expire_time']);
- }
-
- // 初始化已使用次数
- if (!isset($params['used_count'])) {
- $params['used_count'] = 0;
- }
- $result = false;
- Db::startTrans();
- try {
- //是否采用模型验证
- if ($this->modelValidate) {
- $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
- $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
- $this->model->validateFailException(true)->validate($validate);
- }
- $result = $this->model->allowField(true)->save($params);
- Db::commit();
- } catch (ValidateException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (PDOException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- if ($result !== false) {
- $this->success();
- } else {
- $this->error(__('No rows were inserted'));
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
- return $this->view->fetch();
- }
- /**
- * 编辑
- */
- public function edit($ids = null)
- {
- $row = $this->model->get($ids);
- if (!$row) {
- $this->error(__('No Results were found'));
- }
- $adminIds = $this->getDataLimitAdminIds();
- if (is_array($adminIds)) {
- if (!in_array($row[$this->dataLimitField], $adminIds)) {
- $this->error(__('You have no permission'));
- }
- }
- if ($this->request->isPost()) {
- $params = $this->request->post("row/a");
- if ($params) {
- $params = $this->preExcludeFields($params);
-
- // 处理过期时间
- if (isset($params['expire_time']) && $params['expire_time']) {
- $params['expire_time'] = strtotime($params['expire_time']);
- }
- $result = false;
- Db::startTrans();
- try {
- //是否采用模型验证
- if ($this->modelValidate) {
- $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
- $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
- $row->validateFailException(true)->validate($validate);
- }
- $result = $row->allowField(true)->save($params);
- Db::commit();
- } catch (ValidateException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (PDOException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- if ($result !== false) {
- $this->success();
- } else {
- $this->error(__('No rows were updated'));
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
-
- // 处理时间显示
- if ($row->expire_time) {
- $row->expire_time = date('Y-m-d H:i:s', $row->expire_time);
- }
-
- $this->view->assign("row", $row);
- return $this->view->fetch();
- }
- /**
- * 批量发放抽奖机会
- */
- public function batchGrant()
- {
- if ($this->request->isPost()) {
- $activity_id = $this->request->post('activity_id');
- $user_ids = $this->request->post('user_ids');
- $chance_count = $this->request->post('chance_count', 1);
- $source_type = $this->request->post('source_type', 1);
- $expire_time = $this->request->post('expire_time');
-
- if (empty($activity_id) || empty($user_ids)) {
- $this->error('活动ID和用户ID不能为空');
- }
-
- // 处理用户ID数组
- if (is_string($user_ids)) {
- $user_ids = array_filter(explode(',', $user_ids));
- }
-
- $expire_timestamp = $expire_time ? strtotime($expire_time) : null;
-
- $success_count = 0;
- Db::startTrans();
- try {
- foreach ($user_ids as $user_id) {
- $data = [
- 'activity_id' => $activity_id,
- 'user_id' => $user_id,
- 'chance_count' => $chance_count,
- 'used_count' => 0,
- 'source_type' => $source_type,
- 'source_value' => '管理员批量发放',
- 'expire_time' => $expire_timestamp,
- 'status' => 1,
- 'createtime' => time(),
- 'updatetime' => time()
- ];
-
- // 检查是否已存在
- $exists = $this->model->where([
- 'activity_id' => $activity_id,
- 'user_id' => $user_id,
- 'source_type' => $source_type
- ])->find();
-
- if ($exists) {
- // 更新现有记录
- $exists->chance_count += $chance_count;
- $exists->save();
- } else {
- // 创建新记录
- $this->model->create($data);
- }
- $success_count++;
- }
- Db::commit();
- $this->success("成功为 {$success_count} 个用户发放抽奖机会");
- } catch (Exception $e) {
- Db::rollback();
- $this->error('批量发放失败:' . $e->getMessage());
- }
- }
-
- // 获取活动列表
- $activityModel = new \app\admin\model\lottery\Activity;
- $activities = $activityModel->where('status', 1)->column('name', 'id');
- $this->view->assign('activities', $activities);
-
- return $this->view->fetch();
- }
- /**
- * 用户抽奖机会统计
- */
- public function statistics()
- {
- if ($this->request->isAjax()) {
- $activity_id = $this->request->get('activity_id');
- $where = [];
- if ($activity_id) {
- $where['activity_id'] = $activity_id;
- }
-
- // 统计数据
- $total_users = $this->model->where($where)->count('DISTINCT user_id');
- $total_chances = $this->model->where($where)->sum('chance_count');
- $used_chances = $this->model->where($where)->sum('used_count');
- $remain_chances = $total_chances - $used_chances;
-
- // 按来源类型统计
- $source_stats = $this->model->field('source_type, COUNT(*) as count, SUM(chance_count) as total_chance, SUM(used_count) as used_chance')
- ->where($where)
- ->group('source_type')
- ->select();
-
- $data = [
- 'total_users' => $total_users,
- 'total_chances' => $total_chances,
- 'used_chances' => $used_chances,
- 'remain_chances' => $remain_chances,
- 'source_stats' => $source_stats
- ];
-
- return json(['code' => 1, 'msg' => 'success', 'data' => $data]);
- }
-
- // 获取活动列表
- $activityModel = new \app\admin\model\lottery\Activity;
- $activities = $activityModel->where('status', 1)->column('name', 'id');
- $this->view->assign('activities', $activities);
-
- return $this->view->fetch();
- }
- /**
- * 清理过期机会
- */
- public function clearExpired()
- {
- $count = $this->model->where('expire_time', '<', time())
- ->where('expire_time', '>', 0)
- ->where('status', 1)
- ->update(['status' => 0]);
-
- $this->success("已清理 {$count} 条过期的抽奖机会");
- }
- }
|