123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648 |
- <?php
- namespace app\admin\controller\lottery;
- use app\common\controller\Backend;
- use app\common\Enum\ActivityEnum;
- use think\Db;
- use think\exception\ValidateException;
- use think\exception\PDOException;
- use Exception;
- /**
- * 抽奖活动管理
- *
- * @icon fa fa-gift
- */
- class Activity extends Backend
- {
- /**
- * Activity模型对象
- * @var \app\admin\model\lottery\Activity
- */
- protected $model = null;
- public function _initialize()
- {
- parent::_initialize();
- $this->model = new \app\admin\model\lottery\Activity;
-
- // 获取枚举值列表
- $this->view->assign("typeList", ActivityEnum::getActivityTypeMap());
- $this->assignconfig("typeList", json_encode(ActivityEnum::getActivityTypeMap()));
- $this->view->assign("statusList", ActivityEnum::getActivityStatusMap());
- $this->assignconfig("statusList", json_encode(ActivityEnum::getActivityStatusMap()));
- $this->view->assign("lotteryTypeList", ActivityEnum::getLotteryTypeMap());
- $this->assignconfig("lotteryTypeList", json_encode(ActivityEnum::getLotteryTypeMap()));
- $this->view->assign("userLimitTypeList", ActivityEnum::getUserLimitTypeMap());
- $this->assignconfig("userLimitTypeList", json_encode(ActivityEnum::getUserLimitTypeMap()));
- $this->view->assign("guideStyleList", ActivityEnum::getGuideStyleMap());
- $this->assignconfig("guideStyleList", json_encode(ActivityEnum::getGuideStyleMap()));
- $this->view->assign("conditionTypeList", ActivityEnum::getConditionTypeMap());
- $this->assignconfig("conditionTypeList", json_encode(ActivityEnum::getConditionTypeMap()));
-
- // 奖品类型配置
- $this->view->assign("prizeTypeList", ActivityEnum::getPrizeTypeMap());
- $this->assignconfig("prizeTypeList", json_encode(ActivityEnum::getPrizeTypeMap()));
-
- // 奖品默认图片配置
- $this->assignconfig("prizeDefaultImages", json_encode(ActivityEnum::getPrizeDefaultImageMap()));
- $config = config('site');
- $lottery_guide = $config['lottery_guide'] ?? '';
- $prize_losing_lottery = $config['prize_losing_lottery'] ?? '';
- $this->view->assign("prize_losing_lottery", $prize_losing_lottery);
- $this->view->assign("lottery_guide", $lottery_guide);
-
- }
- /**
- * 查看
- */
- 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(['prize'])
- ->where($where)
- ->order($sort, $order)
- ->paginate($limit);
- foreach ($list as $row) {
- $row->visible(['id','name','description','cover_image','type','status','start_time','end_time','lottery_type','total_draw_count','total_people_count','total_win_count']);
- $row->visible(['prize']);
- $row->getRelation('prize')->visible(['name','type','total_stock','remain_stock']);
- }
-
- $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);
-
- // 获取奖品和条件数据
- $prizesData = $this->request->post("prizes/a", []);
- $conditionData = $this->request->post("condition/a", []);
- $taskTypes = isset($params['task_type']) ? $params['task_type'] : [];
-
- // 处理活动基础数据
- $activityData = $this->processActivityData($params);
-
- // 验证奖品数据
- $this->validatePrizesData($prizesData);
-
- // 验证条件数据
- $this->validateConditionData($conditionData, $taskTypes);
- $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($activityData);
-
- if ($result) {
- $activityId = $this->model->id;
-
- // 保存奖品数据
- $this->savePrizesData($activityId, $prizesData);
-
- // 保存参与条件数据
- $this->saveConditionData($activityId, $conditionData, $taskTypes);
- }
-
- 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();
- }
-
- /**
- * 处理活动基础数据
- */
- private function processActivityData($params)
- {
- // 处理时间字段
- if (isset($params['start_time']) && $params['start_time']) {
- $params['start_time'] = strtotime($params['start_time']);
- }
- if (isset($params['end_time']) && $params['end_time']) {
- $params['end_time'] = strtotime($params['end_time']);
- }
- if (isset($params['lottery_time']) && $params['lottery_time']) {
- $params['lottery_time'] = strtotime($params['lottery_time']);
- }
-
- // 处理JSON字段
- if (isset($params['user_limit_value']) && $params['user_limit_value']) {
- $params['user_limit_value'] = json_encode($params['user_limit_value']);
- }
-
- // 处理渠道字段(如果存在的话)
- if (isset($params['channels']) && is_array($params['channels'])) {
- $params['channels'] = json_encode($params['channels']);
- }
-
- // 处理兑奖期限设置
- if (isset($params['redeem_expire_type'])) {
- $params['redeem_expire_type'] = intval($params['redeem_expire_type']);
- if ($params['redeem_expire_type'] == ActivityEnum::REDEEM_EXPIRE_FIXED) {
- $params['redeem_expire_days'] = isset($params['redeem_expire_days']) ? intval($params['redeem_expire_days']) : 7;
- } else {
- $params['redeem_expire_days'] = null;
- }
- }
-
- // 字段名映射 - 将前端字段名映射到实际数据表字段名
- if (isset($params['title'])) {
- $params['name'] = $params['title']; // 活动标题映射到name字段
- unset($params['title']);
- }
-
- if (isset($params['lottery_people'])) {
- $params['lottery_people_num'] = $params['lottery_people']; // 开奖人数字段名映射
- unset($params['lottery_people']);
- }
-
- if (isset($params['per_person_limit'])) {
- $params['person_limit_num'] = $params['per_person_limit']; // 单人限制次数字段名映射
- unset($params['per_person_limit']);
- }
-
- // 移除不属于活动表的字段
- unset($params['task_type']);
-
- // 设置默认值
- $params['type'] = ActivityEnum::ACTIVITY_TYPE_CONSUMPTION_LOTTERY; // 消费抽奖
-
- // 初始化统计字段
- if (!isset($params['total_draw_count'])) {
- $params['total_draw_count'] = 0;
- }
- if (!isset($params['total_people_count'])) {
- $params['total_people_count'] = 0;
- }
- if (!isset($params['total_win_count'])) {
- $params['total_win_count'] = 0;
- }
-
- return $params;
- }
-
- /**
- * 验证奖品数据
- */
- private function validatePrizesData($prizesData)
- {
- if (empty($prizesData) || count($prizesData) < 8) {
- throw new Exception('奖品数量不足,必须配置8个奖品(包含未中奖项)');
- }
-
- $totalRate = 0;
- foreach ($prizesData as $prize) {
- if (!isset($prize['name']) || !isset($prize['type']) || !isset($prize['rate'])) {
- throw new Exception('奖品配置不完整');
- }
-
- $totalRate += floatval($prize['rate']);
-
- // 验证特定类型奖品的必需字段
- switch (intval($prize['type'])) {
- case 5: // 优惠券
- if (empty($prize['coupon_id'])) {
- throw new Exception('优惠券奖品必须选择优惠券');
- }
- break;
- case 8: // 商城奖品
- if (empty($prize['goods_id'])) {
- throw new Exception('商城奖品必须选择商品');
- }
- break;
- }
- }
-
- if (abs($totalRate - 100) > 0.01) {
- throw new Exception('奖品总概率必须等于100%,当前为' . $totalRate . '%');
- }
- }
-
- /**
- * 验证条件数据
- */
- private function validateConditionData($conditionData, $taskTypes)
- {
- if (empty($taskTypes)) {
- throw new Exception('请至少选择一种任务类型');
- }
-
- foreach ($taskTypes as $taskType) {
- $type = intval($taskType);
-
- switch ($type) {
- case 1: // 购买指定商品
- if (!isset($conditionData[$type]) || empty($conditionData[$type]['goods_ids'])) {
- throw new Exception('购买指定商品任务必须選擇商品');
- }
- break;
- case 2: // 单笔订单消费满额
- case 3: // 单次充值满额
- case 4: // 活动期间累计消费满额
- if (!isset($conditionData[$type]) || empty($conditionData[$type]['condition_value'])) {
- throw new Exception('消费/充值任务必须设置金额');
- }
- if (floatval($conditionData[$type]['condition_value']) <= 0) {
- throw new Exception('消费/充值任务金额必须大于0');
- }
- break;
- }
- }
- }
-
- /**
- * 保存奖品数据
- */
- private function savePrizesData($activityId, $prizesData)
- {
- $prizeModel = new \app\admin\model\lottery\Prize;
-
- foreach ($prizesData as $index => $prize) {
- $prizeData = [
- 'activity_id' => $activityId,
- 'name' => $prize['name'],
- 'type' => intval($prize['type']),
- 'image' => isset($prize['image']) ? $prize['image'] : '',
- 'probability' => floatval($prize['rate']),
- 'total_stock' => isset($prize['quantity']) ? intval($prize['quantity']) : 0,
- 'remain_stock' => isset($prize['quantity']) ? intval($prize['quantity']) : 0,
- 'sort_order' => $index,
- 'status' => 1,
- 'createtime' => time()
- ];
-
- // 根据奖品类型设置特定字段
- switch (intval($prize['type'])) {
- case ActivityEnum::PRIZE_TYPE_POINTS: // 积分 - 使用amount字段存储积分数量
- $prizeData['amount'] = isset($prize['points']) ? intval($prize['points']) : 0;
- $prizeData['description'] = '积分奖品';
- break;
- case ActivityEnum::PRIZE_TYPE_BALANCE: // 余额 - 使用amount字段存储余额金额
- $prizeData['amount'] = isset($prize['balance']) ? floatval($prize['balance']) : 0;
- $prizeData['description'] = '余额奖品';
- break;
- case ActivityEnum::PRIZE_TYPE_COUPON: // 优惠券
- $prizeData['coupon_id'] = isset($prize['coupon_id']) ? intval($prize['coupon_id']) : 0;
- $prizeData['description'] = '优惠券奖品';
- break;
- case ActivityEnum::PRIZE_TYPE_REDPACK: // 红包 - 使用amount字段存储红包金额
- $prizeData['amount'] = isset($prize['redpack_amount']) ? floatval($prize['redpack_amount']) : 0;
- $prizeData['description'] = '红包奖品';
- break;
- case ActivityEnum::PRIZE_TYPE_CODE: // 兑换码
- if (isset($prize['manual_codes']) && !empty($prize['manual_codes'])) {
- $codes = array_filter(array_map('trim', explode("\n", $prize['manual_codes'])));
- $prizeData['exchange_codes'] = json_encode($codes);
- $prizeData['used_codes'] = json_encode([]); // 初始化已使用列表
- $prizeData['total_stock'] = count($codes);
- $prizeData['remain_stock'] = count($codes);
- }
- $prizeData['description'] = '兑换码奖品';
- break;
- case ActivityEnum::PRIZE_TYPE_SHOP_GOODS: // 商城奖品
- $prizeData['goods_id'] = isset($prize['goods_id']) ? intval($prize['goods_id']) : 0;
- $prizeData['goods_sku_id'] = isset($prize['goods_sku_id']) ? intval($prize['goods_sku_id']) : null;
- $prizeData['description'] = '商城奖品';
- break;
- case ActivityEnum::PRIZE_TYPE_GOODS: // 实物奖品
- $prizeData['description'] = isset($prize['description']) ? $prize['description'] : '实物奖品';
- break;
- case ActivityEnum::PRIZE_TYPE_NO_PRIZE: // 未中奖
- default:
- $prizeData['description'] = '未中奖';
- break;
- }
-
- $prizeModel->create($prizeData);
- }
- }
-
- /**
- * 保存参与条件数据
- */
- private function saveConditionData($activityId, $conditionData, $taskTypes)
- {
- $conditionModel = new \app\admin\model\lottery\Condition;
-
- foreach ($taskTypes as $taskType) {
- $type = intval($taskType);
- $condition = isset($conditionData[$type]) ? $conditionData[$type] : [];
-
- $conditionRecord = [
- 'activity_id' => $activityId,
- 'type' => $type,
- 'reward_times' => 1,
- 'is_repeatable' => 0,
- 'status' => $conditionModel::STATUS_ENABLED,
- 'createtime' => time()
- ];
-
- switch ($type) {
- case ActivityEnum::CONDITION_TYPE_BUY_GOODS: // 购买指定商品
- $goodsIds = isset($condition['goods_ids']) ? $condition['goods_ids'] : '[]';
- if (is_string($goodsIds)) {
- $goodsIds = json_decode($goodsIds, true) ?: [];
- }
- $conditionRecord['goods_ids'] = json_encode($goodsIds);
- $conditionRecord['goods_rule'] = isset($condition['goods_rule']) ? intval($condition['goods_rule']) : $conditionModel::GOODS_RULE_INCLUDE;
- break;
- case ActivityEnum::CONDITION_TYPE_ORDER_AMOUNT: // 单笔订单消费满额
- case ActivityEnum::CONDITION_TYPE_RECHARGE_AMOUNT: // 单次充值满额
- case ActivityEnum::CONDITION_TYPE_TOTAL_AMOUNT: // 活动期间累计消费满额
- $conditionRecord['condition_value'] = isset($condition['condition_value']) ? floatval($condition['condition_value']) : 0;
- if ($type == ActivityEnum::CONDITION_TYPE_TOTAL_AMOUNT) {
- $conditionRecord['is_repeatable'] = 0; // 累计消费不可重复
- } else {
- $conditionRecord['is_repeatable'] = 1; // 其他类型可重复
- }
- break;
- }
-
- $conditionModel->create($conditionRecord);
- }
- }
- /**
- * 编辑
- */
- 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);
-
- // 获取奖品和条件数据
- $prizesData = $this->request->post("prizes/a", []);
- $conditionData = $this->request->post("condition/a", []);
- $taskTypes = isset($params['task_type']) ? $params['task_type'] : [];
-
- // 处理活动基础数据
- $activityData = $this->processActivityData($params);
-
- // 验证奖品数据
- $this->validatePrizesData($prizesData);
-
- // 验证条件数据
- $this->validateConditionData($conditionData, $taskTypes);
- $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($activityData);
-
- if ($result !== false) {
- $activityId = $ids;
-
- // 删除原有奖品数据
- Db::name('shop_lottery_prize')->where('activity_id', $activityId)->delete();
-
- // 删除原有条件数据
- Db::name('shop_lottery_condition')->where('activity_id', $activityId)->delete();
-
- // 保存新的奖品数据
- $this->savePrizesData($activityId, $prizesData);
-
- // 保存新的参与条件数据
- $this->saveConditionData($activityId, $conditionData, $taskTypes);
- }
-
- 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->start_time) {
- $row->start_time = date('Y-m-d H:i:s', $row->start_time);
- }
- if ($row->end_time) {
- $row->end_time = date('Y-m-d H:i:s', $row->end_time);
- }
- if ($row->lottery_time) {
- $row->lottery_time = date('Y-m-d H:i:s', $row->lottery_time);
- }
-
- // 处理JSON字段
- if ($row->user_limit_value) {
- $row->user_limit_value = json_decode($row->user_limit_value, true);
- }
-
- // 处理渠道字段
- if ($row->channels) {
- $row->channels = json_decode($row->channels, true);
- }
-
- // 字段名映射 - 将数据表字段名映射回前端字段名
- if (isset($row->name)) {
- $row->title = $row->name; // 将name映射回title供前端使用
- }
- if (isset($row->lottery_people_num)) {
- $row->lottery_people = $row->lottery_people_num; // 映射回前端字段名
- }
- if (isset($row->person_limit_num)) {
- $row->per_person_limit = $row->person_limit_num; // 映射回前端字段名
- }
-
- // 获取奖品数据
- $prizes = Db::name('shop_lottery_prize')
- ->where('activity_id', $ids)
- ->order('sort_order', 'asc')
- ->select();
-
- // 处理奖品数据的字段映射
- foreach ($prizes as &$prize) {
- // 将数据表字段映射回前端字段
- $prize['quantity'] = $prize['total_stock']; // 前端使用quantity字段
- $prize['rate'] = $prize['probability']; // 前端使用rate字段
-
- // 根据奖品类型设置特定字段
- switch (intval($prize['type'])) {
- case ActivityEnum::PRIZE_TYPE_POINTS:
- $prize['points'] = $prize['amount'] ?? 0;
- break;
- case ActivityEnum::PRIZE_TYPE_BALANCE:
- $prize['balance'] = $prize['amount'] ?? 0;
- break;
- case ActivityEnum::PRIZE_TYPE_REDPACK:
- $prize['redpack_amount'] = $prize['amount'] ?? 0;
- break;
- case ActivityEnum::PRIZE_TYPE_CODE:
- if (!empty($prize['exchange_codes'])) {
- $codes = json_decode($prize['exchange_codes'], true) ?: [];
- $prize['manual_codes'] = implode("\n", $codes);
- }
- break;
- }
- }
-
- // 获取条件数据
- $conditions = Db::name('shop_lottery_condition')
- ->where('activity_id', $ids)
- ->select();
-
- // 处理条件数据的字段映射
- $taskTypes = [];
- $conditionsData = [];
- foreach ($conditions as $condition) {
- $taskTypes[] = $condition['type'];
- $conditionsData[$condition['type']] = $condition;
-
- // 处理商品IDs JSON
- if (!empty($condition['goods_ids'])) {
- $conditionsData[$condition['type']]['goods_ids_array'] = json_decode($condition['goods_ids'], true) ?: [];
- }
- }
-
- $this->view->assign("row", $row);
- $this->view->assign("prizes", $prizes);
- $this->view->assign("conditions", $conditions);
- $this->view->assign("conditionsData", $conditionsData);
- $this->view->assign("taskTypes", $taskTypes);
- return $this->view->fetch();
- }
- /**
- * 奖品管理
- */
- public function prize($ids = null)
- {
- $activity = $this->model->get($ids);
- if (!$activity) {
- $this->error(__('No Results were found'));
- }
-
- $this->view->assign("activity", $activity);
- return $this->view->fetch();
- }
- /**
- * 参与条件管理
- */
- public function condition($ids = null)
- {
- $activity = $this->model->get($ids);
- if (!$activity) {
- $this->error(__('No Results were found'));
- }
-
- $this->view->assign("activity", $activity);
- return $this->view->fetch();
- }
- /**
- * 抽奖记录
- */
- public function records($ids = null)
- {
- $activity = $this->model->get($ids);
- if (!$activity) {
- $this->error(__('No Results were found'));
- }
-
- $this->view->assign("activity", $activity);
- return $this->view->fetch();
- }
- /**
- * 统计数据
- */
- public function statistics($ids = null)
- {
- $activity = $this->model->get($ids);
- if (!$activity) {
- $this->error(__('No Results were found'));
- }
-
- // 获取统计数据
- $statisticsModel = new \app\admin\model\lottery\Statistics;
- $statistics = $statisticsModel->where('activity_id', $ids)->order('stat_date', 'desc')->paginate(15);
-
- $this->view->assign("activity", $activity);
- $this->view->assign("statistics", $statistics);
- return $this->view->fetch();
- }
- }
|