| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466 |
- <?php
- namespace hd\controllers;
- use bizHd\hb\classes\HbAutoRuleClass;
- use bizHd\hb\classes\HbManageClass;
- use bizHd\hb\classes\HbScopeClass;
- use bizHd\order\classes\OrderClass;
- use bizHd\recharge\classes\RechargeShbClass;
- use common\components\util;
- use bizHd\hb\classes\HbClass;
- use hd\models\hb\CreateHbForm;
- use hd\models\hb\SaveAutoRuleForm;
- use hd\models\hb\SendHbRuleItemForm;
- use hd\models\hb\UpdateHbForm;
- use Yii;
- class HbController extends BaseController
- {
- public $guestAccess = [];
- //获取新人红包福利 ssh 20211026(旧空壳保留,新客红包改为注册自动发放)
- public function actionGetNewGift()
- {
- util::complete('领取成功');
- }
- /**
- * 红包统计
- * 入参:dateType=today|7|30|custom,beginDate/endDate,getType(可选)
- */
- public function actionStat()
- {
- $get = Yii::$app->request->get();
- $dateType = $get['dateType'] ?? 'today';
- list($beginTs, $endTs) = $this->resolveStatRange($dateType, $get['beginDate'] ?? '', $get['endDate'] ?? '');
- $getType = isset($get['getType']) && $get['getType'] !== '' ? $get['getType'] : '';
- $data = HbClass::getStat($this->shopId, $beginTs, $endTs, $getType);
- $data['beginDate'] = date('Y-m-d', $beginTs);
- $data['endDate'] = date('Y-m-d', $endTs);
- util::success($data);
- }
- /**
- * 获取红包列表
- * 支持 status / customId / getType / beginDate / endDate
- */
- public function actionHbList()
- {
- $get = Yii::$app->request->get();
- $where = ['shopId' => $this->shopId];
- $customId = $get['customId'] ?? 0;
- if (!empty($customId)) {
- $where['customId'] = $customId;
- }
- $status = $get['status'] ?? '';
- if ($status != '') {
- $where['status'] = $status;
- }
- if (isset($get['getType']) && $get['getType'] !== '') {
- $where['getType'] = (int)$get['getType'];
- }
- if (!empty($get['beginDate'])) {
- $where['createdAt>='] = date('Y-m-d 00:00:00', strtotime($get['beginDate']));
- }
- if (!empty($get['endDate'])) {
- $where['createdAt<='] = date('Y-m-d 23:59:59', strtotime($get['endDate']));
- }
- $respond = HbClass::getList('*', $where, 'id desc', 'custom');
- //统计各状态总数量(不受当前 status 筛选影响,保留 getType/日期/客户筛选)
- $countWhere = $where;
- unset($countWhere['status']);
- $respond['all'] = HbClass::getCount($countWhere);
- $respond['unUse'] = HbClass::getCount(array_merge($countWhere, ['status' => 0]));
- $respond['used'] = HbClass::getCount(array_merge($countWhere, ['status' => 1]));
- $respond['expired'] = HbClass::getCount(array_merge($countWhere, ['status' => -1]));
- if (!empty($respond['list'])) {
- $hbIds = array_column($respond['list'], 'id');
- $scopeMap = HbScopeClass::getMapByHbIds($hbIds);
- foreach ($respond['list'] as $k => &$v) {
- $v['customName'] = $v['custom']['name'] ?? '';
- $v['getTypeName'] = HbClass::$getTypeNames[(int)$v['getType']] ?? '未知方式';
- $v = HbScopeClass::attachScopeToHb($v, $scopeMap);
- if ($v['status'] == 0 && $v['endTime'] < time()) {
- //发现红包已过期,需要作废,多有处作废操作,搜索关键词 cancellation_hb
- $id = $v['id'];
- HbClass::updateById($id, ['status' => -1]);
- if ($status == '' || $status == 0) {
- unset($respond['list'][$k]);
- $respond['all']--;
- $respond['unUse']--;
- $respond['expired']++;
- }
- }
- }
- $respond['list'] = array_values($respond['list']);
- }
- util::success($respond);
- }
- // 单个门店下所有可用红包
- public function actionAvailableHb()
- {
- $get = Yii::$app->request->get();
- $where = [];
- $where['customId'] = $get['customId'];
- $where['status'] = 0;
- $where['beginTime<='] = time(); // 生效时间小于等于当前时间
- $list = HbClass::getAllByCondition($where, 'id DESC');
- //已经过期的就不再显示,并且作废,多有处作废操作,搜索关键词 cancellation_hb
- if (!empty($list)) {
- $hbIds = array_column($list, 'id');
- $scopeMap = HbScopeClass::getMapByHbIds($hbIds);
- foreach ($list as $k => $v) {
- if ($v['status'] == 0 && $v['endTime'] < time()) {
- unset($list[$k]);
- $id = $v['id'];
- HbClass::updateById($id, ['status' => -1]);
- continue;
- }
- $list[$k] = HbScopeClass::attachScopeToHb($v, $scopeMap);
- }
- $list = array_values($list);
- }
- util::success($list);
- }
- /**
- * 获取红包详情(兼容 /hb/hb-detail 与 /hb/get-detail)
- */
- public function actionHbDetail()
- {
- $this->respondHbDetail();
- }
- /**
- * 前端历史路径 /hb/get-detail
- */
- public function actionGetDetail()
- {
- $this->respondHbDetail();
- }
- protected function respondHbDetail()
- {
- $hbId = Yii::$app->request->get('hbId', Yii::$app->request->get('id'));
- $hb = HbClass::getById($hbId);
- if (!empty($hb)) {
- $hb = HbScopeClass::attachScopeToHb($hb);
- $hb['getTypeName'] = HbClass::$getTypeNames[(int)$hb['getType']] ?? '未知方式';
- }
- util::success($hb);
- }
- /**
- * 创建红包(手动发放)
- * 新版:customs[] + rules[] + scopeType/scopeValue/specialApplicable
- * 旧版:userId/customId/amount/minConsume/days/count 仍兼容
- */
- public function actionCreateHb()
- {
- $form = new CreateHbForm();
- $form->load(Yii::$app->request->post(), '');
- if (!$form->validateForm()) {
- return;
- }
- $adminId = $this->shopAdminId;
- util::checkRepeatCommit($adminId, 5);
- if (isset($this->shopAdmin->founder) == false || $this->shopAdmin->founder != 2) {
- util::fail('管理员才能操作');
- }
- // 组装客户与规则
- if (!empty($form->customs) && !empty($form->rules)) {
- $customs = $form->customs;
- $rules = $form->rules;
- } else {
- $customs = [[
- 'userId' => (int)$form->userId,
- 'customId' => (int)$form->customId,
- ]];
- $rules = [[
- 'name' => $form->name ?: '红包',
- 'hbAmount' => $form->amount,
- 'hbNum' => $form->count ?: 1,
- 'miniCost' => $form->minConsume,
- 'duration' => $form->days,
- 'effectiveType' => 1,
- 'effectiveDate' => $form->effectiveDate ?: '',
- 'effectiveDays' => 0,
- ]];
- }
- // 规范化客户数组(兼容只传 customId)
- $normCustoms = [];
- foreach ($customs as $c) {
- if (!is_array($c)) {
- continue;
- }
- $customId = (int)($c['customId'] ?? $c['id'] ?? 0);
- $userId = (int)($c['userId'] ?? 0);
- if ($customId <= 0) {
- continue;
- }
- if ($userId <= 0) {
- // 尝试从客户表补全
- $customRow = \bizHd\custom\classes\CustomClass::getById($customId);
- $userId = (int)($customRow['userId'] ?? 0);
- }
- if ($userId <= 0) {
- continue;
- }
- $normCustoms[] = ['userId' => $userId, 'customId' => $customId];
- }
- if (empty($normCustoms)) {
- util::fail('请选择有效客户');
- }
- $scope = [
- 'scopeType' => (int)($form->scopeType ?: 1),
- 'scopeValue' => (string)($form->scopeValue ?: ''),
- 'specialApplicable' => isset($form->specialApplicable) ? ((int)$form->specialApplicable ? 1 : 0) : 1,
- ];
- if ($scope['scopeType'] != 1 && $scope['scopeValue'] === '') {
- util::fail('请选择适用范围内容');
- }
- $result = HbClass::batchCreateManual(
- $this->mainId,
- $this->shopId,
- $this->shopAdminId,
- $this->shopAdminName,
- $normCustoms,
- $rules,
- $scope,
- (string)($form->remark ?: '')
- );
- if ($result['count'] <= 0) {
- util::fail('发放失败,请检查红包配置');
- }
- $arr = $result['lastHb'] ?: [];
- $arr['count'] = $result['count'];
- util::success($arr);
- }
- /**
- * 更新红包
- * - 更新方法包含了:红包退回及其它更新
- */
- public function actionUpdateHb()
- {
- $rawPost = Yii::$app->request->post();
- $form = new UpdateHbForm();
- $form->load($rawPost, '');
- if (!$form->validateForm()) {
- return;
- }
- $id = (int)$form->id;
- $hb = HbClass::getById($id, true);
- //检测是否是本门店的红包
- if ($hb->shopId != $this->shopId) {
- util::fail('不是本门店的红包');
- }
- if (isset($this->shopAdmin->founder) == false || $this->shopAdmin->founder != 2) {
- util::fail('管理员才能操作');
- }
- $connection = Yii::$app->db;
- $transaction = $connection->beginTransaction();
- try {
- //当是退回红包时,必须检测对应订单 actPrice 为0
- if (isset($form->status) && $form->status == 0) {
- if ($hb->status == 1) {
- //查询订单数据,校验 actPrice,按情况更新
- $order = OrderClass::getById($form->orderId, true, 'id, hbId, hbAmount, actPrice');
- if ($order->hbId == $id) {
- if ($order->actPrice == 0.00) {
- //更新订单数据
- $order->hbId = -$order->hbId;
- $order->save();
- } else {
- Yii::error('使用红包的订单 actPrice 不等于0,无法执行红包退回。hbId=' . $id);
- util::fail('使用红包的订单 actPrice 不等于0,无法执行红包退回');
- }
- } else {
- Yii::error("订单中的红包id与当前红包不匹配。hbId={$id}, orderId={$form->orderId}");
- util::fail('订单中的红包id与当前红包不匹配');
- }
- } else {
- Yii::error("当前红包状态不是已使用,不能变更未使用。hbId={$id}");
- util::fail("当前红包状态不是已使用,不能变更未使用");
- }
- }
- // 仅更新允许字段,且只更新请求中实际传入的字段(避免用 null 覆盖原值)
- $allowFields = array_keys($form->attributes);
- foreach ($allowFields as $field) {
- if ($field === 'id') {
- continue;
- }
- if (array_key_exists($field, $rawPost)) {
- $hb->$field = $form->$field;
- }
- }
- // 当操作作废时,status改为-1,同时将endTime改为当前时间,多有处作废操作,搜索关键词 cancellation_hb
- if (isset($form->status) && $form->status == -1 && $hb->status != -1) {
- $hb->endTime = time();
- //记录作废人
- $updateData = [
- 'cancelStaffId' => $this->shopAdminId,
- 'cancelStaffName' => $this->shopAdminName,
- 'cancelTime' => date('Y-m-d H:i:s'),
- ];
- HbManageClass::updateByCondition(['hbId' => $id], $updateData);
- }
- $hb->save();
- $transaction->commit();
- } catch (\Exception $e) {
- $transaction->rollBack();
- $msg = $e->getMessage();
- Yii::error('actionUpdateHb', $msg);
- util::fail($msg);
- }
- util::success($hb->attributes);
- }
- /**
- * 自动发红包:4 种类型卡片列表
- */
- public function actionAutoRuleList()
- {
- $list = HbAutoRuleClass::listCards($this->shopId);
- util::success(['list' => $list]);
- }
- /**
- * 自动发红包:规则详情
- */
- public function actionAutoRuleDetail()
- {
- $type = (int)Yii::$app->request->get('type', 0);
- $detail = HbAutoRuleClass::getDetail($this->shopId, $type);
- util::success($detail);
- }
- /**
- * 自动发红包:保存规则
- */
- public function actionSaveAutoRule()
- {
- if (isset($this->shopAdmin->founder) == false || $this->shopAdmin->founder != 2) {
- util::fail('管理员才能操作');
- }
- $form = new SaveAutoRuleForm();
- $form->load(Yii::$app->request->post(), '');
- if (!$form->validateForm()) {
- return;
- }
- $detail = HbAutoRuleClass::saveRule($this->shopId, $this->mainId, $form->attributes);
- util::success($detail);
- }
- /**
- * 充值送红包规则列表
- */
- public function actionHbRules()
- {
- $list = RechargeShbClass::getList('*', ['shopId' => $this->shopId]);
- util::success($list);
- }
- /**
- * 充值送红包规则详情
- */
- public function actionHbRuleDetail()
- {
- $id = Yii::$app->request->get('id');
- $rule = RechargeShbClass::getById($id);
- util::success($rule);
- }
- /**
- * 充值送红包规则创建
- */
- public function actionSendHbRules()
- {
- $data = Yii::$app->request->post();
- $id = $data['id'];
- $amount = $data['amount'];
- $rules = $data['rules'];
- $validatedRules = [];
- foreach ($rules as $item) {
- if (!is_array($item)) {
- util::fail('参数格式错误');
- return;
- }
- $form = new SendHbRuleItemForm();
- $form->load($item, '');
- if (!$form->validateForm()) {
- return;
- }
- $validatedRules[] = $form->attributes;
- }
- $hbRules = RechargeShbClass::setRules($this->shopId, $this->mainId, $id, $amount, $validatedRules);
- util::success($hbRules);
- }
- /**
- * 充值送红包规则删除
- */
- public function actionDeleteHbRule()
- {
- $id = Yii::$app->request->post('id');
- $re = RechargeShbClass::deleteById($id);
- if ($re == 1) {
- util::complete();
- } else {
- util::fail('删除失败');
- }
- }
- /**
- * 解析统计时间范围
- * @return array [beginTs, endTs]
- */
- protected function resolveStatRange($dateType, $beginDate, $endDate)
- {
- $now = time();
- $endTs = strtotime(date('Y-m-d 23:59:59', $now));
- switch ($dateType) {
- case '7':
- $beginTs = strtotime(date('Y-m-d 00:00:00', strtotime('-6 days')));
- break;
- case '30':
- $beginTs = strtotime(date('Y-m-d 00:00:00', strtotime('-29 days')));
- break;
- case 'custom':
- if (empty($beginDate) || empty($endDate)) {
- util::fail('请选择自定义时间范围');
- }
- $beginTs = strtotime($beginDate . ' 00:00:00');
- $endTs = strtotime($endDate . ' 23:59:59');
- if ($beginTs <= 0 || $endTs <= 0 || $beginTs > $endTs) {
- util::fail('自定义时间范围无效');
- }
- break;
- case 'today':
- default:
- $beginTs = strtotime(date('Y-m-d 00:00:00', $now));
- break;
- }
- return [$beginTs, $endTs];
- }
- }
|