SalonController.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. package com.train.controller;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.train.common.Result;
  4. import com.train.cfc.entity.CfcActivity;
  5. import com.train.cfc.mapper.CfcActivityMapper;
  6. import com.train.entity.TrainEnrollment;
  7. import com.train.entity.TrainInvite;
  8. import com.train.entity.TrainOrder;
  9. import com.train.entity.TrainSalon;
  10. import com.train.entity.TrainSalonCheckin;
  11. import com.train.entity.TrainSalonFeedback;
  12. import com.train.entity.TrainUser;
  13. import com.train.mapper.TrainEnrollmentMapper;
  14. import com.train.mapper.TrainInviteMapper;
  15. import com.train.mapper.TrainOrderMapper;
  16. import com.train.mapper.TrainSalonCheckinMapper;
  17. import com.train.mapper.TrainSalonFeedbackMapper;
  18. import com.train.mapper.TrainSalonMapper;
  19. import com.train.mapper.TrainUserMapper;
  20. import com.train.service.CfcReferralSyncService;
  21. import com.train.service.ScoreService;
  22. import io.swagger.v3.oas.annotations.Operation;
  23. import io.swagger.v3.oas.annotations.tags.Tag;
  24. import org.springframework.util.StringUtils;
  25. import org.springframework.web.bind.annotation.PostMapping;
  26. import org.springframework.web.bind.annotation.RequestAttribute;
  27. import org.springframework.web.bind.annotation.RequestBody;
  28. import org.springframework.web.bind.annotation.RequestMapping;
  29. import org.springframework.web.bind.annotation.RestController;
  30. import javax.annotation.Resource;
  31. import java.util.ArrayList;
  32. import java.util.Arrays;
  33. import java.util.Date;
  34. import java.util.HashMap;
  35. import java.util.List;
  36. import java.util.Map;
  37. @Tag(name = "沙龙", description = "沙龙期次列表、沙龙报名、我的沙龙报名")
  38. @RestController
  39. @RequestMapping("/api/salon")
  40. public class SalonController {
  41. @Resource
  42. private TrainSalonMapper trainSalonMapper;
  43. @Resource
  44. private TrainEnrollmentMapper trainEnrollmentMapper;
  45. @Resource
  46. private TrainInviteMapper trainInviteMapper;
  47. @Resource
  48. private TrainUserMapper trainUserMapper;
  49. @Resource
  50. private CfcActivityMapper cfcActivityMapper;
  51. @Resource
  52. private TrainOrderMapper trainOrderMapper;
  53. @Resource
  54. private TrainSalonCheckinMapper trainSalonCheckinMapper;
  55. @Resource
  56. private TrainSalonFeedbackMapper trainSalonFeedbackMapper;
  57. @Resource
  58. private ScoreService scoreService;
  59. @Resource
  60. private CfcReferralSyncService cfcReferralSyncService;
  61. /** 占用名额的报名状态 */
  62. private static final List<String> OCCUPY_STATUS = Arrays.asList("pending", "paid", "confirmed");
  63. /** 可签到/反馈的报名状态(已支付或已确认) */
  64. private static final List<String> ACTIVE_STATUS = Arrays.asList("paid", "confirmed");
  65. /**
  66. * 可报名沙龙期次列表(含剩余名额/价格)
  67. */
  68. @Operation(summary = "可报名沙龙期次列表")
  69. @PostMapping("/list")
  70. public Result<List<Map<String, Object>>> list(@RequestBody(required = false) Map<String, Object> body) {
  71. List<TrainSalon> salons = trainSalonMapper.selectList(
  72. new LambdaQueryWrapper<TrainSalon>()
  73. .eq(TrainSalon::getStatus, "active")
  74. .orderByAsc(TrainSalon::getId));
  75. List<Map<String, Object>> result = new ArrayList<>();
  76. for (TrainSalon salon : salons) {
  77. int salonPrice = salon.getPrice() == null ? 0 : salon.getPrice();
  78. int price = salonPrice;
  79. int memberPrice = price;
  80. // 价格来自 cfc activities(分为单位,cfc 同库),未关联活动则用沙龙自身价格
  81. if (salon.getActivityId() != null) {
  82. CfcActivity activity = cfcActivityMapper.selectById(salon.getActivityId());
  83. if (activity != null) {
  84. price = activity.getPrice() == null ? salonPrice : activity.getPrice();
  85. memberPrice = activity.getMemberPrice() == null ? price : activity.getMemberPrice();
  86. }
  87. }
  88. Long occupied = trainEnrollmentMapper.selectCount(
  89. new LambdaQueryWrapper<TrainEnrollment>()
  90. .eq(TrainEnrollment::getSalonId, salon.getId())
  91. .in(TrainEnrollment::getStatus, OCCUPY_STATUS));
  92. long num = (salon.getCapacity() == null ? 0 : salon.getCapacity()) - (occupied == null ? 0L : occupied);
  93. Map<String, Object> row = new HashMap<>();
  94. row.put("id", salon.getId());
  95. row.put("theme", salon.getTheme());
  96. row.put("title", salon.getTitle());
  97. row.put("time", salon.getTime());
  98. row.put("place", salon.getPlace());
  99. row.put("capacity", salon.getCapacity());
  100. row.put("price", price);
  101. row.put("memberPrice", memberPrice);
  102. row.put("occupied", occupied == null ? 0L : occupied);
  103. row.put("num", num);
  104. row.put("status", salon.getStatus());
  105. row.put("startAt", salon.getStartAt());
  106. row.put("endAt", salon.getEndAt());
  107. row.put("createdAt", salon.getCreatedAt());
  108. result.add(row);
  109. }
  110. return Result.success(result);
  111. }
  112. /**
  113. * 创建沙龙报名单(带邀请码则记录转介绍关系)
  114. */
  115. @Operation(summary = "创建沙龙报名单")
  116. @PostMapping("/create")
  117. public Result<Map<String, Object>> create(@RequestBody Map<String, Object> body,
  118. @RequestAttribute("userId") Long userId) {
  119. if (body.get("salonId") == null) {
  120. return Result.error("请选择沙龙期次");
  121. }
  122. Long salonId = Long.valueOf(body.get("salonId").toString());
  123. String name = body.get("name") == null ? "" : body.get("name").toString().trim();
  124. String phone = body.get("phone") == null ? "" : body.get("phone").toString().trim();
  125. if (!StringUtils.hasText(name) || !StringUtils.hasText(phone)) {
  126. return Result.error("请填写姓名和手机号");
  127. }
  128. TrainSalon salon = trainSalonMapper.selectById(salonId);
  129. if (salon == null) {
  130. return Result.error("沙龙不存在");
  131. }
  132. if (!"active".equals(salon.getStatus())) {
  133. return Result.error("该沙龙未开放报名");
  134. }
  135. // 容量校验(并发下允许少量超卖,最终以支付为准)
  136. Long occupied = trainEnrollmentMapper.selectCount(
  137. new LambdaQueryWrapper<TrainEnrollment>()
  138. .eq(TrainEnrollment::getSalonId, salonId)
  139. .in(TrainEnrollment::getStatus, OCCUPY_STATUS));
  140. if (salon.getCapacity() != null && occupied != null && occupied >= salon.getCapacity()) {
  141. return Result.error("该沙龙名额已满");
  142. }
  143. // 防重复报名(同期沙龙已有未支付/在途报名单)
  144. Long exists = trainEnrollmentMapper.selectCount(
  145. new LambdaQueryWrapper<TrainEnrollment>()
  146. .eq(TrainEnrollment::getUid, userId)
  147. .eq(TrainEnrollment::getSalonId, salonId)
  148. .in(TrainEnrollment::getStatus, OCCUPY_STATUS));
  149. if (exists != null && exists > 0) {
  150. return Result.error("您已报名该期沙龙");
  151. }
  152. String inviteCode = body.get("inviteCode") == null ? "" : body.get("inviteCode").toString().trim();
  153. // 邀请链:先解析邀请人,报名单冗余 inviter_id(被邀请人记录邀请人信息,便于平台奖励);不能自己邀自己
  154. TrainUser inviter = null;
  155. if (StringUtils.hasText(inviteCode)) {
  156. inviter = trainUserMapper.selectOne(
  157. new LambdaQueryWrapper<TrainUser>()
  158. .eq(TrainUser::getInviteCode, inviteCode)
  159. .last("LIMIT 1"));
  160. if (inviter != null && inviter.getId().equals(userId)) {
  161. inviter = null;
  162. }
  163. }
  164. TrainEnrollment en = new TrainEnrollment();
  165. en.setUid(userId);
  166. en.setSalonId(salonId);
  167. en.setName(name);
  168. en.setPhone(phone);
  169. en.setSource(StringUtils.hasText(inviteCode) ? "invite" : "scene");
  170. en.setInviteCode(StringUtils.hasText(inviteCode) ? inviteCode : null);
  171. en.setInviterId(inviter != null ? inviter.getId() : null);
  172. en.setStatus("pending");
  173. trainEnrollmentMapper.insert(en);
  174. // 转介绍关系(幂等:uk_code_invitee 唯一键兜底)
  175. if (inviter != null) {
  176. Long invCount = trainInviteMapper.selectCount(
  177. new LambdaQueryWrapper<TrainInvite>()
  178. .eq(TrainInvite::getInviteCode, inviteCode)
  179. .eq(TrainInvite::getInviteeId, userId));
  180. if (invCount == null || invCount == 0) {
  181. TrainInvite inv = new TrainInvite();
  182. inv.setInviterId(inviter.getId());
  183. inv.setInviteeId(userId);
  184. inv.setInviteCode(inviteCode);
  185. inv.setSuccessful(0);
  186. inv.setRewardStatus("pending");
  187. try {
  188. trainInviteMapper.insert(inv);
  189. } catch (Exception ex) {
  190. // 唯一键冲突(并发重复注册)可忽略
  191. }
  192. }
  193. // 同步 cfc 推荐关系(users.referrer_id + referral_tree;失败不阻塞报名)
  194. try {
  195. cfcReferralSyncService.syncReferrer(userId, inviter.getId());
  196. } catch (Exception ex) {
  197. org.slf4j.LoggerFactory.getLogger(getClass())
  198. .warn("同步 cfc 推荐关系失败: inviteeUid={}, inviterUid={}, err={}",
  199. userId, inviter.getId(), ex.getMessage());
  200. }
  201. }
  202. Map<String, Object> row = new HashMap<>();
  203. row.put("id", en.getId());
  204. row.put("salonId", salonId);
  205. row.put("theme", salon.getTheme());
  206. row.put("title", salon.getTitle());
  207. row.put("status", en.getStatus());
  208. return Result.success(row);
  209. }
  210. /**
  211. * 我的沙龙报名单列表
  212. */
  213. @Operation(summary = "我的沙龙报名单列表")
  214. @PostMapping("/mine")
  215. public Result<List<Map<String, Object>>> mine(@RequestAttribute("userId") Long userId) {
  216. List<TrainEnrollment> list = trainEnrollmentMapper.selectList(
  217. new LambdaQueryWrapper<TrainEnrollment>()
  218. .eq(TrainEnrollment::getUid, userId)
  219. .isNotNull(TrainEnrollment::getSalonId)
  220. .orderByDesc(TrainEnrollment::getId));
  221. List<Map<String, Object>> result = new ArrayList<>();
  222. for (TrainEnrollment e : list) {
  223. Map<String, Object> row = new HashMap<>();
  224. row.put("enrollmentId", e.getId());
  225. row.put("salonId", e.getSalonId());
  226. TrainSalon s = e.getSalonId() == null ? null : trainSalonMapper.selectById(e.getSalonId());
  227. row.put("theme", s == null ? null : s.getTheme());
  228. row.put("title", s == null ? null : s.getTitle());
  229. row.put("time", s == null ? null : s.getTime());
  230. row.put("place", s == null ? null : s.getPlace());
  231. row.put("status", e.getStatus());
  232. row.put("inviteCode", e.getInviteCode());
  233. row.put("inviterId", e.getInviterId());
  234. row.put("createdAt", e.getCreatedAt());
  235. // 补关联订单号:未关闭订单(unpaid)用于前端继续支付/取消;paid 也回填便于查询
  236. TrainOrder order = trainOrderMapper.selectOne(
  237. new LambdaQueryWrapper<TrainOrder>()
  238. .eq(TrainOrder::getEnrollmentId, e.getId())
  239. .ne(TrainOrder::getStatus, "closed")
  240. .orderByDesc(TrainOrder::getId)
  241. .last("LIMIT 1"));
  242. row.put("orderNo", order == null ? null : order.getOrderNo());
  243. // 沙龙状态(前端据此决定是否显示签到入口)
  244. row.put("salonStatus", s == null ? null : s.getStatus());
  245. row.put("salonStartAt", s == null ? null : s.getStartAt());
  246. row.put("salonEndAt", s == null ? null : s.getEndAt());
  247. // 沙龙展示状态(对齐 cfc applyDisplayState 语义):ended/ongoing/pending_start/active/draft
  248. row.put("displayStatus", calcDisplayStatus(s));
  249. // 已签到标记
  250. Long checkedIn = trainSalonCheckinMapper.selectCount(
  251. new LambdaQueryWrapper<TrainSalonCheckin>()
  252. .eq(TrainSalonCheckin::getUid, userId)
  253. .eq(TrainSalonCheckin::getSalonId, e.getSalonId()));
  254. row.put("checkedIn", checkedIn != null && checkedIn > 0);
  255. // 已提交反馈标记
  256. TrainSalonFeedback fb = e.getSalonId() == null ? null : trainSalonFeedbackMapper.selectOne(
  257. new LambdaQueryWrapper<TrainSalonFeedback>()
  258. .eq(TrainSalonFeedback::getUid, userId)
  259. .eq(TrainSalonFeedback::getSalonId, e.getSalonId())
  260. .last("LIMIT 1"));
  261. row.put("feedbackSubmitted", fb != null);
  262. result.add(row);
  263. }
  264. return Result.success(result);
  265. }
  266. /**
  267. * 沙龙现场签到(需已报名且已支付/已确认;幂等,重复签到返回 true)
  268. * 规则对齐 cfc 活动签到:仅在时间窗 [startAt, endAt] 内可签,签到发放积分(checkinPoints)
  269. */
  270. @Operation(summary = "沙龙签到")
  271. @PostMapping("/checkin")
  272. public Result<Map<String, Object>> checkin(@RequestBody Map<String, Object> body,
  273. @RequestAttribute("userId") Long userId) {
  274. if (body.get("salonId") == null) {
  275. return Result.error("请选择沙龙期次");
  276. }
  277. Long salonId = Long.valueOf(body.get("salonId").toString());
  278. TrainSalon salon = trainSalonMapper.selectById(salonId);
  279. if (salon == null) {
  280. return Result.error("沙龙不存在");
  281. }
  282. if (!"active".equals(salon.getStatus())) {
  283. return Result.error("该沙龙未在进行中");
  284. }
  285. // 时间窗校验(对齐 cfc 活动签到):开始前/结束后均不可签到
  286. Date now = new Date();
  287. if (salon.getStartAt() != null && now.before(salon.getStartAt())) {
  288. return Result.error("沙龙尚未开始,暂不能签到");
  289. }
  290. if (salon.getEndAt() != null && now.after(salon.getEndAt())) {
  291. return Result.error("沙龙已结束,不能签到");
  292. }
  293. // 报名且已支付/已确认才可签到
  294. Long enrolled = trainEnrollmentMapper.selectCount(
  295. new LambdaQueryWrapper<TrainEnrollment>()
  296. .eq(TrainEnrollment::getUid, userId)
  297. .eq(TrainEnrollment::getSalonId, salonId)
  298. .in(TrainEnrollment::getStatus, ACTIVE_STATUS));
  299. if (enrolled == null || enrolled == 0) {
  300. return Result.error("请先报名并完成支付");
  301. }
  302. // 幂等:已签到直接返回成功(积分已被发放,pointsEarned=0)
  303. Long existed = trainSalonCheckinMapper.selectCount(
  304. new LambdaQueryWrapper<TrainSalonCheckin>()
  305. .eq(TrainSalonCheckin::getUid, userId)
  306. .eq(TrainSalonCheckin::getSalonId, salonId));
  307. if (existed != null && existed > 0) {
  308. Map<String, Object> done = new HashMap<>();
  309. done.put("pointsEarned", 0);
  310. done.put("alreadyCompleted", true);
  311. return Result.success(done);
  312. }
  313. TrainSalonCheckin checkin = new TrainSalonCheckin();
  314. checkin.setUid(userId);
  315. checkin.setSalonId(salonId);
  316. try {
  317. trainSalonCheckinMapper.insert(checkin);
  318. } catch (Exception ex) {
  319. // 唯一键冲突(并发重复签到)按已签到处理
  320. }
  321. // 签到积分:取关联 cfc 活动的 checkinPoints(创建时默认 5),未关联则用默认 5
  322. int points = 5;
  323. if (salon.getActivityId() != null) {
  324. try {
  325. CfcActivity activity = cfcActivityMapper.selectById(salon.getActivityId());
  326. if (activity != null && activity.getCheckinPoints() != null && activity.getCheckinPoints() > 0) {
  327. points = activity.getCheckinPoints();
  328. }
  329. } catch (Exception e) {
  330. // 读取 cfc 活动失败用默认积分
  331. }
  332. }
  333. String title = salon.getTitle() == null ? "" : salon.getTitle();
  334. try {
  335. scoreService.addUserScoreIfAbsent(userId, "salon_checkin_" + salonId, points, userId, "沙龙签到:" + title);
  336. } catch (Exception e) {
  337. // 积分发放失败不阻塞签到
  338. org.slf4j.LoggerFactory.getLogger(getClass()).warn("沙龙签到积分发放失败: {}", e.getMessage());
  339. }
  340. Map<String, Object> result = new HashMap<>();
  341. result.put("pointsEarned", points);
  342. result.put("alreadyCompleted", false);
  343. return Result.success(result);
  344. }
  345. /**
  346. * 提交沙龙反馈(需已报名且已支付/已确认;评分 1-5;幂等,重复提交返回 true)
  347. */
  348. @Operation(summary = "提交沙龙反馈")
  349. @PostMapping("/feedback")
  350. public Result<Boolean> feedback(@RequestBody Map<String, Object> body,
  351. @RequestAttribute("userId") Long userId) {
  352. if (body.get("salonId") == null) {
  353. return Result.error("请选择沙龙期次");
  354. }
  355. Long salonId = Long.valueOf(body.get("salonId").toString());
  356. TrainSalon salon = trainSalonMapper.selectById(salonId);
  357. if (salon == null) {
  358. return Result.error("沙龙不存在");
  359. }
  360. Long enrolled = trainEnrollmentMapper.selectCount(
  361. new LambdaQueryWrapper<TrainEnrollment>()
  362. .eq(TrainEnrollment::getUid, userId)
  363. .eq(TrainEnrollment::getSalonId, salonId)
  364. .in(TrainEnrollment::getStatus, ACTIVE_STATUS));
  365. if (enrolled == null || enrolled == 0) {
  366. return Result.error("请先报名参加该沙龙");
  367. }
  368. int rating = 5;
  369. if (body.get("rating") != null) {
  370. try {
  371. rating = Integer.parseInt(body.get("rating").toString());
  372. } catch (NumberFormatException e) {
  373. rating = 5;
  374. }
  375. }
  376. if (rating < 1 || rating > 5) {
  377. return Result.error("评分需在 1-5 之间");
  378. }
  379. String comment = body.get("comment") == null ? "" : body.get("comment").toString().trim();
  380. if (comment.length() > 500) {
  381. comment = comment.substring(0, 500);
  382. }
  383. // 幂等:已提交直接返回成功
  384. Long existed = trainSalonFeedbackMapper.selectCount(
  385. new LambdaQueryWrapper<TrainSalonFeedback>()
  386. .eq(TrainSalonFeedback::getUid, userId)
  387. .eq(TrainSalonFeedback::getSalonId, salonId));
  388. if (existed != null && existed > 0) {
  389. return Result.success(true);
  390. }
  391. TrainSalonFeedback feedback = new TrainSalonFeedback();
  392. feedback.setUid(userId);
  393. feedback.setSalonId(salonId);
  394. feedback.setRating(rating);
  395. feedback.setComment(comment);
  396. try {
  397. trainSalonFeedbackMapper.insert(feedback);
  398. } catch (Exception ex) {
  399. // 唯一键冲突(并发重复提交)按已提交处理
  400. }
  401. return Result.success(true);
  402. }
  403. /**
  404. * 沙龙展示状态(对齐 cfc 活动 applyDisplayState 语义):
  405. * ended=已结束 / ongoing=进行中(时间窗内) / pending_start=未开始 / active=进行中(无时间窗) / draft=草稿
  406. */
  407. private String calcDisplayStatus(TrainSalon s) {
  408. if (s == null) {
  409. return null;
  410. }
  411. String status = s.getStatus();
  412. if ("draft".equals(status)) {
  413. return "draft";
  414. }
  415. Date now = new Date();
  416. if ("finished".equals(status)
  417. || (s.getEndAt() != null && now.after(s.getEndAt()))) {
  418. return "ended";
  419. }
  420. if (!"active".equals(status)) {
  421. return status;
  422. }
  423. if (s.getStartAt() != null && now.before(s.getStartAt())) {
  424. return "pending_start";
  425. }
  426. return "ongoing";
  427. }
  428. }