model = new \app\admin\model\lottery\Activity; // 获取枚举值列表 $this->view->assign("typeList", LotteryEnum::getLotteryTypeMap()); $this->assignconfig("typeList", json_encode(LotteryEnum::getLotteryTypeMap())); $this->view->assign("statusList", LotteryEnum::getActivityStatusMap()); $this->assignconfig("statusList", json_encode(LotteryEnum::getActivityStatusMap())); $this->view->assign("lotteryTypeList", LotteryEnum::getLotteryTypeMap()); $this->assignconfig("lotteryTypeList", json_encode(LotteryEnum::getLotteryTypeMap())); $this->view->assign("userLimitTypeList", LotteryEnum::getUserLimitTypeMap()); $this->assignconfig("userLimitTypeList", json_encode(LotteryEnum::getUserLimitTypeMap())); $this->view->assign("guideStyleList", LotteryEnum::getGuideStyleMap()); $this->assignconfig("guideStyleList", json_encode(LotteryEnum::getGuideStyleMap())); $this->view->assign("conditionTypeList", LotteryEnum::getConditionTypeMap()); $this->assignconfig("conditionTypeList", json_encode(LotteryEnum::getConditionTypeMap())); // 奖品类型配置 $this->view->assign("prizeTypeList", LotteryEnum::getPrizeTypeMap()); $this->assignconfig("prizeTypeList", json_encode(LotteryEnum::getPrizeTypeMap())); // 奖品默认图片配置 $this->assignconfig("prizeDefaultImages", json_encode(LotteryEnum::getPrizeDefaultImageMap())); // 渠道配置 $this->view->assign("channelList", ChannelEnum::getChannelMap()); $this->assignconfig("channelList", json_encode(ChannelEnum::getChannelMap())); // $this->view->assign("channelGroupList", ChannelEnum::getChannelGroupMap()); // $this->assignconfig("channelGroupList", json_encode(ChannelEnum::getChannelGroupMap())); // $this->view->assign("channelsByGroup", ChannelEnum::getChannelsByGroup()); // $this->assignconfig("channelsByGroup", json_encode(ChannelEnum::getChannelsByGroup())); $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']); // 处理奖品关联数据(hasMany关系) if (isset($row->prize) && $row->prize) { foreach ($row->prize as $prize) { if (is_object($prize) && method_exists($prize, 'visible')) { $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); // 获取奖品和条件数据 $prizesJson = $this->request->post("prizes_json", ""); $prizesData = []; if (!empty($prizesJson)) { $prizesData = json_decode($prizesJson, true); if (json_last_error() !== JSON_ERROR_NONE) { $this->error('奖品数据格式错误'); } } $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\LotteryPrize; 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); // 获取奖品和条件数据 $prizesJson = $this->request->post("prizes_json", ""); $prizesData = []; if (!empty($prizesJson)) { $prizesData = json_decode($prizesJson, true); if (json_last_error() !== JSON_ERROR_NONE) { $this->error('奖品数据格式错误'); } } $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("prizesJson", json_encode($prizes)); // 为前端JavaScript提供JSON格式的奖品数据 $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(); } }