HbController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. <?php
  2. namespace hd\controllers;
  3. use bizHd\hb\classes\HbAutoRuleClass;
  4. use bizHd\hb\classes\HbManageClass;
  5. use bizHd\hb\classes\HbScopeClass;
  6. use bizHd\order\classes\OrderClass;
  7. use bizHd\recharge\classes\RechargeShbClass;
  8. use common\components\util;
  9. use bizHd\hb\classes\HbClass;
  10. use hd\models\hb\CreateHbForm;
  11. use hd\models\hb\SaveAutoRuleForm;
  12. use hd\models\hb\SendHbRuleItemForm;
  13. use hd\models\hb\UpdateHbForm;
  14. use Yii;
  15. class HbController extends BaseController
  16. {
  17. public $guestAccess = [];
  18. //获取新人红包福利 ssh 20211026(旧空壳保留,新客红包改为注册自动发放)
  19. public function actionGetNewGift()
  20. {
  21. util::complete('领取成功');
  22. }
  23. /**
  24. * 红包统计
  25. * 入参:dateType=today|7|30|custom,beginDate/endDate,getType(可选)
  26. */
  27. public function actionStat()
  28. {
  29. $get = Yii::$app->request->get();
  30. $dateType = $get['dateType'] ?? 'today';
  31. list($beginTs, $endTs) = $this->resolveStatRange($dateType, $get['beginDate'] ?? '', $get['endDate'] ?? '');
  32. $getType = isset($get['getType']) && $get['getType'] !== '' ? $get['getType'] : '';
  33. $data = HbClass::getStat($this->shopId, $beginTs, $endTs, $getType);
  34. $data['beginDate'] = date('Y-m-d', $beginTs);
  35. $data['endDate'] = date('Y-m-d', $endTs);
  36. util::success($data);
  37. }
  38. /**
  39. * 获取红包列表
  40. * 支持 status / customId / getType / beginDate / endDate
  41. */
  42. public function actionHbList()
  43. {
  44. $get = Yii::$app->request->get();
  45. $where = ['shopId' => $this->shopId];
  46. $customId = $get['customId'] ?? 0;
  47. if (!empty($customId)) {
  48. $where['customId'] = $customId;
  49. }
  50. $status = $get['status'] ?? '';
  51. if ($status != '') {
  52. $where['status'] = $status;
  53. }
  54. if (isset($get['getType']) && $get['getType'] !== '') {
  55. $where['getType'] = (int)$get['getType'];
  56. }
  57. if (!empty($get['beginDate'])) {
  58. $where['createdAt>='] = date('Y-m-d 00:00:00', strtotime($get['beginDate']));
  59. }
  60. if (!empty($get['endDate'])) {
  61. $where['createdAt<='] = date('Y-m-d 23:59:59', strtotime($get['endDate']));
  62. }
  63. $respond = HbClass::getList('*', $where, 'id desc', 'custom');
  64. //统计各状态总数量(不受当前 status 筛选影响,保留 getType/日期/客户筛选)
  65. $countWhere = $where;
  66. unset($countWhere['status']);
  67. $respond['all'] = HbClass::getCount($countWhere);
  68. $respond['unUse'] = HbClass::getCount(array_merge($countWhere, ['status' => 0]));
  69. $respond['used'] = HbClass::getCount(array_merge($countWhere, ['status' => 1]));
  70. $respond['expired'] = HbClass::getCount(array_merge($countWhere, ['status' => -1]));
  71. if (!empty($respond['list'])) {
  72. $hbIds = array_column($respond['list'], 'id');
  73. $scopeMap = HbScopeClass::getMapByHbIds($hbIds);
  74. foreach ($respond['list'] as $k => &$v) {
  75. $v['customName'] = $v['custom']['name'] ?? '';
  76. $v['getTypeName'] = HbClass::$getTypeNames[(int)$v['getType']] ?? '未知方式';
  77. $v = HbScopeClass::attachScopeToHb($v, $scopeMap);
  78. if ($v['status'] == 0 && $v['endTime'] < time()) {
  79. //发现红包已过期,需要作废,多有处作废操作,搜索关键词 cancellation_hb
  80. $id = $v['id'];
  81. HbClass::updateById($id, ['status' => -1]);
  82. if ($status == '' || $status == 0) {
  83. unset($respond['list'][$k]);
  84. $respond['all']--;
  85. $respond['unUse']--;
  86. $respond['expired']++;
  87. }
  88. }
  89. }
  90. $respond['list'] = array_values($respond['list']);
  91. }
  92. util::success($respond);
  93. }
  94. // 单个门店下所有可用红包
  95. public function actionAvailableHb()
  96. {
  97. $get = Yii::$app->request->get();
  98. $where = [];
  99. $where['customId'] = $get['customId'];
  100. $where['status'] = 0;
  101. $where['beginTime<='] = time(); // 生效时间小于等于当前时间
  102. $list = HbClass::getAllByCondition($where, 'id DESC');
  103. //已经过期的就不再显示,并且作废,多有处作废操作,搜索关键词 cancellation_hb
  104. if (!empty($list)) {
  105. $hbIds = array_column($list, 'id');
  106. $scopeMap = HbScopeClass::getMapByHbIds($hbIds);
  107. foreach ($list as $k => $v) {
  108. if ($v['status'] == 0 && $v['endTime'] < time()) {
  109. unset($list[$k]);
  110. $id = $v['id'];
  111. HbClass::updateById($id, ['status' => -1]);
  112. continue;
  113. }
  114. $list[$k] = HbScopeClass::attachScopeToHb($v, $scopeMap);
  115. }
  116. $list = array_values($list);
  117. }
  118. util::success($list);
  119. }
  120. /**
  121. * 获取红包详情(兼容 /hb/hb-detail 与 /hb/get-detail)
  122. */
  123. public function actionHbDetail()
  124. {
  125. $this->respondHbDetail();
  126. }
  127. /**
  128. * 前端历史路径 /hb/get-detail
  129. */
  130. public function actionGetDetail()
  131. {
  132. $this->respondHbDetail();
  133. }
  134. protected function respondHbDetail()
  135. {
  136. $hbId = Yii::$app->request->get('hbId', Yii::$app->request->get('id'));
  137. $hb = HbClass::getById($hbId);
  138. if (!empty($hb)) {
  139. $hb = HbScopeClass::attachScopeToHb($hb);
  140. $hb['getTypeName'] = HbClass::$getTypeNames[(int)$hb['getType']] ?? '未知方式';
  141. }
  142. util::success($hb);
  143. }
  144. /**
  145. * 创建红包(手动发放)
  146. * 新版:customs[] + rules[] + scopeType/scopeValue/specialApplicable
  147. * 旧版:userId/customId/amount/minConsume/days/count 仍兼容
  148. */
  149. public function actionCreateHb()
  150. {
  151. $form = new CreateHbForm();
  152. $form->load(Yii::$app->request->post(), '');
  153. if (!$form->validateForm()) {
  154. return;
  155. }
  156. $adminId = $this->shopAdminId;
  157. util::checkRepeatCommit($adminId, 5);
  158. if (isset($this->shopAdmin->founder) == false || $this->shopAdmin->founder != 2) {
  159. util::fail('管理员才能操作');
  160. }
  161. // 组装客户与规则
  162. if (!empty($form->customs) && !empty($form->rules)) {
  163. $customs = $form->customs;
  164. $rules = $form->rules;
  165. } else {
  166. $customs = [[
  167. 'userId' => (int)$form->userId,
  168. 'customId' => (int)$form->customId,
  169. ]];
  170. $rules = [[
  171. 'name' => $form->name ?: '红包',
  172. 'hbAmount' => $form->amount,
  173. 'hbNum' => $form->count ?: 1,
  174. 'miniCost' => $form->minConsume,
  175. 'duration' => $form->days,
  176. 'effectiveType' => 1,
  177. 'effectiveDate' => $form->effectiveDate ?: '',
  178. 'effectiveDays' => 0,
  179. ]];
  180. }
  181. // 规范化客户数组(兼容只传 customId)
  182. $normCustoms = [];
  183. foreach ($customs as $c) {
  184. if (!is_array($c)) {
  185. continue;
  186. }
  187. $customId = (int)($c['customId'] ?? $c['id'] ?? 0);
  188. $userId = (int)($c['userId'] ?? 0);
  189. if ($customId <= 0) {
  190. continue;
  191. }
  192. if ($userId <= 0) {
  193. // 尝试从客户表补全
  194. $customRow = \bizHd\custom\classes\CustomClass::getById($customId);
  195. $userId = (int)($customRow['userId'] ?? 0);
  196. }
  197. if ($userId <= 0) {
  198. continue;
  199. }
  200. $normCustoms[] = ['userId' => $userId, 'customId' => $customId];
  201. }
  202. if (empty($normCustoms)) {
  203. util::fail('请选择有效客户');
  204. }
  205. $scope = [
  206. 'scopeType' => (int)($form->scopeType ?: 1),
  207. 'scopeValue' => (string)($form->scopeValue ?: ''),
  208. 'specialApplicable' => isset($form->specialApplicable) ? ((int)$form->specialApplicable ? 1 : 0) : 1,
  209. ];
  210. if ($scope['scopeType'] != 1 && $scope['scopeValue'] === '') {
  211. util::fail('请选择适用范围内容');
  212. }
  213. $result = HbClass::batchCreateManual(
  214. $this->mainId,
  215. $this->shopId,
  216. $this->shopAdminId,
  217. $this->shopAdminName,
  218. $normCustoms,
  219. $rules,
  220. $scope,
  221. (string)($form->remark ?: '')
  222. );
  223. if ($result['count'] <= 0) {
  224. util::fail('发放失败,请检查红包配置');
  225. }
  226. $arr = $result['lastHb'] ?: [];
  227. $arr['count'] = $result['count'];
  228. util::success($arr);
  229. }
  230. /**
  231. * 更新红包
  232. * - 更新方法包含了:红包退回及其它更新
  233. */
  234. public function actionUpdateHb()
  235. {
  236. $rawPost = Yii::$app->request->post();
  237. $form = new UpdateHbForm();
  238. $form->load($rawPost, '');
  239. if (!$form->validateForm()) {
  240. return;
  241. }
  242. $id = (int)$form->id;
  243. $hb = HbClass::getById($id, true);
  244. //检测是否是本门店的红包
  245. if ($hb->shopId != $this->shopId) {
  246. util::fail('不是本门店的红包');
  247. }
  248. if (isset($this->shopAdmin->founder) == false || $this->shopAdmin->founder != 2) {
  249. util::fail('管理员才能操作');
  250. }
  251. $connection = Yii::$app->db;
  252. $transaction = $connection->beginTransaction();
  253. try {
  254. //当是退回红包时,必须检测对应订单 actPrice 为0
  255. if (isset($form->status) && $form->status == 0) {
  256. if ($hb->status == 1) {
  257. //查询订单数据,校验 actPrice,按情况更新
  258. $order = OrderClass::getById($form->orderId, true, 'id, hbId, hbAmount, actPrice');
  259. if ($order->hbId == $id) {
  260. if ($order->actPrice == 0.00) {
  261. //更新订单数据
  262. $order->hbId = -$order->hbId;
  263. $order->save();
  264. } else {
  265. Yii::error('使用红包的订单 actPrice 不等于0,无法执行红包退回。hbId=' . $id);
  266. util::fail('使用红包的订单 actPrice 不等于0,无法执行红包退回');
  267. }
  268. } else {
  269. Yii::error("订单中的红包id与当前红包不匹配。hbId={$id}, orderId={$form->orderId}");
  270. util::fail('订单中的红包id与当前红包不匹配');
  271. }
  272. } else {
  273. Yii::error("当前红包状态不是已使用,不能变更未使用。hbId={$id}");
  274. util::fail("当前红包状态不是已使用,不能变更未使用");
  275. }
  276. }
  277. // 仅更新允许字段,且只更新请求中实际传入的字段(避免用 null 覆盖原值)
  278. $allowFields = array_keys($form->attributes);
  279. foreach ($allowFields as $field) {
  280. if ($field === 'id') {
  281. continue;
  282. }
  283. if (array_key_exists($field, $rawPost)) {
  284. $hb->$field = $form->$field;
  285. }
  286. }
  287. // 当操作作废时,status改为-1,同时将endTime改为当前时间,多有处作废操作,搜索关键词 cancellation_hb
  288. if (isset($form->status) && $form->status == -1 && $hb->status != -1) {
  289. $hb->endTime = time();
  290. //记录作废人
  291. $updateData = [
  292. 'cancelStaffId' => $this->shopAdminId,
  293. 'cancelStaffName' => $this->shopAdminName,
  294. 'cancelTime' => date('Y-m-d H:i:s'),
  295. ];
  296. HbManageClass::updateByCondition(['hbId' => $id], $updateData);
  297. }
  298. $hb->save();
  299. $transaction->commit();
  300. } catch (\Exception $e) {
  301. $transaction->rollBack();
  302. $msg = $e->getMessage();
  303. Yii::error('actionUpdateHb', $msg);
  304. util::fail($msg);
  305. }
  306. util::success($hb->attributes);
  307. }
  308. /**
  309. * 自动发红包:4 种类型卡片列表
  310. */
  311. public function actionAutoRuleList()
  312. {
  313. $list = HbAutoRuleClass::listCards($this->shopId);
  314. util::success(['list' => $list]);
  315. }
  316. /**
  317. * 自动发红包:规则详情
  318. */
  319. public function actionAutoRuleDetail()
  320. {
  321. $type = (int)Yii::$app->request->get('type', 0);
  322. $detail = HbAutoRuleClass::getDetail($this->shopId, $type);
  323. util::success($detail);
  324. }
  325. /**
  326. * 自动发红包:保存规则
  327. */
  328. public function actionSaveAutoRule()
  329. {
  330. if (isset($this->shopAdmin->founder) == false || $this->shopAdmin->founder != 2) {
  331. util::fail('管理员才能操作');
  332. }
  333. $form = new SaveAutoRuleForm();
  334. $form->load(Yii::$app->request->post(), '');
  335. if (!$form->validateForm()) {
  336. return;
  337. }
  338. $detail = HbAutoRuleClass::saveRule($this->shopId, $this->mainId, $form->attributes);
  339. util::success($detail);
  340. }
  341. /**
  342. * 充值送红包规则列表
  343. */
  344. public function actionHbRules()
  345. {
  346. $list = RechargeShbClass::getList('*', ['shopId' => $this->shopId]);
  347. util::success($list);
  348. }
  349. /**
  350. * 充值送红包规则详情
  351. */
  352. public function actionHbRuleDetail()
  353. {
  354. $id = Yii::$app->request->get('id');
  355. $rule = RechargeShbClass::getById($id);
  356. util::success($rule);
  357. }
  358. /**
  359. * 充值送红包规则创建
  360. */
  361. public function actionSendHbRules()
  362. {
  363. $data = Yii::$app->request->post();
  364. $id = $data['id'];
  365. $amount = $data['amount'];
  366. $rules = $data['rules'];
  367. $validatedRules = [];
  368. foreach ($rules as $item) {
  369. if (!is_array($item)) {
  370. util::fail('参数格式错误');
  371. return;
  372. }
  373. $form = new SendHbRuleItemForm();
  374. $form->load($item, '');
  375. if (!$form->validateForm()) {
  376. return;
  377. }
  378. $validatedRules[] = $form->attributes;
  379. }
  380. $hbRules = RechargeShbClass::setRules($this->shopId, $this->mainId, $id, $amount, $validatedRules);
  381. util::success($hbRules);
  382. }
  383. /**
  384. * 充值送红包规则删除
  385. */
  386. public function actionDeleteHbRule()
  387. {
  388. $id = Yii::$app->request->post('id');
  389. $re = RechargeShbClass::deleteById($id);
  390. if ($re == 1) {
  391. util::complete();
  392. } else {
  393. util::fail('删除失败');
  394. }
  395. }
  396. /**
  397. * 解析统计时间范围
  398. * @return array [beginTs, endTs]
  399. */
  400. protected function resolveStatRange($dateType, $beginDate, $endDate)
  401. {
  402. $now = time();
  403. $endTs = strtotime(date('Y-m-d 23:59:59', $now));
  404. switch ($dateType) {
  405. case '7':
  406. $beginTs = strtotime(date('Y-m-d 00:00:00', strtotime('-6 days')));
  407. break;
  408. case '30':
  409. $beginTs = strtotime(date('Y-m-d 00:00:00', strtotime('-29 days')));
  410. break;
  411. case 'custom':
  412. if (empty($beginDate) || empty($endDate)) {
  413. util::fail('请选择自定义时间范围');
  414. }
  415. $beginTs = strtotime($beginDate . ' 00:00:00');
  416. $endTs = strtotime($endDate . ' 23:59:59');
  417. if ($beginTs <= 0 || $endTs <= 0 || $beginTs > $endTs) {
  418. util::fail('自定义时间范围无效');
  419. }
  420. break;
  421. case 'today':
  422. default:
  423. $beginTs = strtotime(date('Y-m-d 00:00:00', $now));
  424. break;
  425. }
  426. return [$beginTs, $endTs];
  427. }
  428. }