| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443 |
- package com.train.controller;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.train.common.Result;
- import com.train.cfc.entity.CfcActivity;
- import com.train.cfc.mapper.CfcActivityMapper;
- import com.train.entity.TrainEnrollment;
- import com.train.entity.TrainInvite;
- import com.train.entity.TrainOrder;
- import com.train.entity.TrainSalon;
- import com.train.entity.TrainSalonCheckin;
- import com.train.entity.TrainSalonFeedback;
- import com.train.entity.TrainUser;
- import com.train.mapper.TrainEnrollmentMapper;
- import com.train.mapper.TrainInviteMapper;
- import com.train.mapper.TrainOrderMapper;
- import com.train.mapper.TrainSalonCheckinMapper;
- import com.train.mapper.TrainSalonFeedbackMapper;
- import com.train.mapper.TrainSalonMapper;
- import com.train.mapper.TrainUserMapper;
- import com.train.service.CfcReferralSyncService;
- import com.train.service.ScoreService;
- import io.swagger.v3.oas.annotations.Operation;
- import io.swagger.v3.oas.annotations.tags.Tag;
- import org.springframework.util.StringUtils;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestAttribute;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- import javax.annotation.Resource;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- @Tag(name = "沙龙", description = "沙龙期次列表、沙龙报名、我的沙龙报名")
- @RestController
- @RequestMapping("/api/salon")
- public class SalonController {
- @Resource
- private TrainSalonMapper trainSalonMapper;
- @Resource
- private TrainEnrollmentMapper trainEnrollmentMapper;
- @Resource
- private TrainInviteMapper trainInviteMapper;
- @Resource
- private TrainUserMapper trainUserMapper;
- @Resource
- private CfcActivityMapper cfcActivityMapper;
- @Resource
- private TrainOrderMapper trainOrderMapper;
- @Resource
- private TrainSalonCheckinMapper trainSalonCheckinMapper;
- @Resource
- private TrainSalonFeedbackMapper trainSalonFeedbackMapper;
- @Resource
- private ScoreService scoreService;
- @Resource
- private CfcReferralSyncService cfcReferralSyncService;
- /** 占用名额的报名状态 */
- private static final List<String> OCCUPY_STATUS = Arrays.asList("pending", "paid", "confirmed");
- /** 可签到/反馈的报名状态(已支付或已确认) */
- private static final List<String> ACTIVE_STATUS = Arrays.asList("paid", "confirmed");
- /**
- * 可报名沙龙期次列表(含剩余名额/价格)
- */
- @Operation(summary = "可报名沙龙期次列表")
- @PostMapping("/list")
- public Result<List<Map<String, Object>>> list(@RequestBody(required = false) Map<String, Object> body) {
- List<TrainSalon> salons = trainSalonMapper.selectList(
- new LambdaQueryWrapper<TrainSalon>()
- .eq(TrainSalon::getStatus, "active")
- .orderByAsc(TrainSalon::getId));
- List<Map<String, Object>> result = new ArrayList<>();
- for (TrainSalon salon : salons) {
- int salonPrice = salon.getPrice() == null ? 0 : salon.getPrice();
- int price = salonPrice;
- int memberPrice = price;
- // 价格来自 cfc activities(分为单位,cfc 同库),未关联活动则用沙龙自身价格
- if (salon.getActivityId() != null) {
- CfcActivity activity = cfcActivityMapper.selectById(salon.getActivityId());
- if (activity != null) {
- price = activity.getPrice() == null ? salonPrice : activity.getPrice();
- memberPrice = activity.getMemberPrice() == null ? price : activity.getMemberPrice();
- }
- }
- Long occupied = trainEnrollmentMapper.selectCount(
- new LambdaQueryWrapper<TrainEnrollment>()
- .eq(TrainEnrollment::getSalonId, salon.getId())
- .in(TrainEnrollment::getStatus, OCCUPY_STATUS));
- long num = (salon.getCapacity() == null ? 0 : salon.getCapacity()) - (occupied == null ? 0L : occupied);
- Map<String, Object> row = new HashMap<>();
- row.put("id", salon.getId());
- row.put("theme", salon.getTheme());
- row.put("title", salon.getTitle());
- row.put("time", salon.getTime());
- row.put("place", salon.getPlace());
- row.put("capacity", salon.getCapacity());
- row.put("price", price);
- row.put("memberPrice", memberPrice);
- row.put("occupied", occupied == null ? 0L : occupied);
- row.put("num", num);
- row.put("status", salon.getStatus());
- row.put("startAt", salon.getStartAt());
- row.put("endAt", salon.getEndAt());
- row.put("createdAt", salon.getCreatedAt());
- result.add(row);
- }
- return Result.success(result);
- }
- /**
- * 创建沙龙报名单(带邀请码则记录转介绍关系)
- */
- @Operation(summary = "创建沙龙报名单")
- @PostMapping("/create")
- public Result<Map<String, Object>> create(@RequestBody Map<String, Object> body,
- @RequestAttribute("userId") Long userId) {
- if (body.get("salonId") == null) {
- return Result.error("请选择沙龙期次");
- }
- Long salonId = Long.valueOf(body.get("salonId").toString());
- String name = body.get("name") == null ? "" : body.get("name").toString().trim();
- String phone = body.get("phone") == null ? "" : body.get("phone").toString().trim();
- if (!StringUtils.hasText(name) || !StringUtils.hasText(phone)) {
- return Result.error("请填写姓名和手机号");
- }
- TrainSalon salon = trainSalonMapper.selectById(salonId);
- if (salon == null) {
- return Result.error("沙龙不存在");
- }
- if (!"active".equals(salon.getStatus())) {
- return Result.error("该沙龙未开放报名");
- }
- // 容量校验(并发下允许少量超卖,最终以支付为准)
- Long occupied = trainEnrollmentMapper.selectCount(
- new LambdaQueryWrapper<TrainEnrollment>()
- .eq(TrainEnrollment::getSalonId, salonId)
- .in(TrainEnrollment::getStatus, OCCUPY_STATUS));
- if (salon.getCapacity() != null && occupied != null && occupied >= salon.getCapacity()) {
- return Result.error("该沙龙名额已满");
- }
- // 防重复报名(同期沙龙已有未支付/在途报名单)
- Long exists = trainEnrollmentMapper.selectCount(
- new LambdaQueryWrapper<TrainEnrollment>()
- .eq(TrainEnrollment::getUid, userId)
- .eq(TrainEnrollment::getSalonId, salonId)
- .in(TrainEnrollment::getStatus, OCCUPY_STATUS));
- if (exists != null && exists > 0) {
- return Result.error("您已报名该期沙龙");
- }
- String inviteCode = body.get("inviteCode") == null ? "" : body.get("inviteCode").toString().trim();
- // 邀请链:先解析邀请人,报名单冗余 inviter_id(被邀请人记录邀请人信息,便于平台奖励);不能自己邀自己
- TrainUser inviter = null;
- if (StringUtils.hasText(inviteCode)) {
- inviter = trainUserMapper.selectOne(
- new LambdaQueryWrapper<TrainUser>()
- .eq(TrainUser::getInviteCode, inviteCode)
- .last("LIMIT 1"));
- if (inviter != null && inviter.getId().equals(userId)) {
- inviter = null;
- }
- }
- TrainEnrollment en = new TrainEnrollment();
- en.setUid(userId);
- en.setSalonId(salonId);
- en.setName(name);
- en.setPhone(phone);
- en.setSource(StringUtils.hasText(inviteCode) ? "invite" : "scene");
- en.setInviteCode(StringUtils.hasText(inviteCode) ? inviteCode : null);
- en.setInviterId(inviter != null ? inviter.getId() : null);
- en.setStatus("pending");
- trainEnrollmentMapper.insert(en);
- // 转介绍关系(幂等:uk_code_invitee 唯一键兜底)
- if (inviter != null) {
- Long invCount = trainInviteMapper.selectCount(
- new LambdaQueryWrapper<TrainInvite>()
- .eq(TrainInvite::getInviteCode, inviteCode)
- .eq(TrainInvite::getInviteeId, userId));
- if (invCount == null || invCount == 0) {
- TrainInvite inv = new TrainInvite();
- inv.setInviterId(inviter.getId());
- inv.setInviteeId(userId);
- inv.setInviteCode(inviteCode);
- inv.setSuccessful(0);
- inv.setRewardStatus("pending");
- try {
- trainInviteMapper.insert(inv);
- } catch (Exception ex) {
- // 唯一键冲突(并发重复注册)可忽略
- }
- }
- // 同步 cfc 推荐关系(users.referrer_id + referral_tree;失败不阻塞报名)
- try {
- cfcReferralSyncService.syncReferrer(userId, inviter.getId());
- } catch (Exception ex) {
- org.slf4j.LoggerFactory.getLogger(getClass())
- .warn("同步 cfc 推荐关系失败: inviteeUid={}, inviterUid={}, err={}",
- userId, inviter.getId(), ex.getMessage());
- }
- }
- Map<String, Object> row = new HashMap<>();
- row.put("id", en.getId());
- row.put("salonId", salonId);
- row.put("theme", salon.getTheme());
- row.put("title", salon.getTitle());
- row.put("status", en.getStatus());
- return Result.success(row);
- }
- /**
- * 我的沙龙报名单列表
- */
- @Operation(summary = "我的沙龙报名单列表")
- @PostMapping("/mine")
- public Result<List<Map<String, Object>>> mine(@RequestAttribute("userId") Long userId) {
- List<TrainEnrollment> list = trainEnrollmentMapper.selectList(
- new LambdaQueryWrapper<TrainEnrollment>()
- .eq(TrainEnrollment::getUid, userId)
- .isNotNull(TrainEnrollment::getSalonId)
- .orderByDesc(TrainEnrollment::getId));
- List<Map<String, Object>> result = new ArrayList<>();
- for (TrainEnrollment e : list) {
- Map<String, Object> row = new HashMap<>();
- row.put("enrollmentId", e.getId());
- row.put("salonId", e.getSalonId());
- TrainSalon s = e.getSalonId() == null ? null : trainSalonMapper.selectById(e.getSalonId());
- row.put("theme", s == null ? null : s.getTheme());
- row.put("title", s == null ? null : s.getTitle());
- row.put("time", s == null ? null : s.getTime());
- row.put("place", s == null ? null : s.getPlace());
- row.put("status", e.getStatus());
- row.put("inviteCode", e.getInviteCode());
- row.put("inviterId", e.getInviterId());
- row.put("createdAt", e.getCreatedAt());
- // 补关联订单号:未关闭订单(unpaid)用于前端继续支付/取消;paid 也回填便于查询
- TrainOrder order = trainOrderMapper.selectOne(
- new LambdaQueryWrapper<TrainOrder>()
- .eq(TrainOrder::getEnrollmentId, e.getId())
- .ne(TrainOrder::getStatus, "closed")
- .orderByDesc(TrainOrder::getId)
- .last("LIMIT 1"));
- row.put("orderNo", order == null ? null : order.getOrderNo());
- // 沙龙状态(前端据此决定是否显示签到入口)
- row.put("salonStatus", s == null ? null : s.getStatus());
- row.put("salonStartAt", s == null ? null : s.getStartAt());
- row.put("salonEndAt", s == null ? null : s.getEndAt());
- // 沙龙展示状态(对齐 cfc applyDisplayState 语义):ended/ongoing/pending_start/active/draft
- row.put("displayStatus", calcDisplayStatus(s));
- // 已签到标记
- Long checkedIn = trainSalonCheckinMapper.selectCount(
- new LambdaQueryWrapper<TrainSalonCheckin>()
- .eq(TrainSalonCheckin::getUid, userId)
- .eq(TrainSalonCheckin::getSalonId, e.getSalonId()));
- row.put("checkedIn", checkedIn != null && checkedIn > 0);
- // 已提交反馈标记
- TrainSalonFeedback fb = e.getSalonId() == null ? null : trainSalonFeedbackMapper.selectOne(
- new LambdaQueryWrapper<TrainSalonFeedback>()
- .eq(TrainSalonFeedback::getUid, userId)
- .eq(TrainSalonFeedback::getSalonId, e.getSalonId())
- .last("LIMIT 1"));
- row.put("feedbackSubmitted", fb != null);
- result.add(row);
- }
- return Result.success(result);
- }
- /**
- * 沙龙现场签到(需已报名且已支付/已确认;幂等,重复签到返回 true)
- * 规则对齐 cfc 活动签到:仅在时间窗 [startAt, endAt] 内可签,签到发放积分(checkinPoints)
- */
- @Operation(summary = "沙龙签到")
- @PostMapping("/checkin")
- public Result<Map<String, Object>> checkin(@RequestBody Map<String, Object> body,
- @RequestAttribute("userId") Long userId) {
- if (body.get("salonId") == null) {
- return Result.error("请选择沙龙期次");
- }
- Long salonId = Long.valueOf(body.get("salonId").toString());
- TrainSalon salon = trainSalonMapper.selectById(salonId);
- if (salon == null) {
- return Result.error("沙龙不存在");
- }
- if (!"active".equals(salon.getStatus())) {
- return Result.error("该沙龙未在进行中");
- }
- // 时间窗校验(对齐 cfc 活动签到):开始前/结束后均不可签到
- Date now = new Date();
- if (salon.getStartAt() != null && now.before(salon.getStartAt())) {
- return Result.error("沙龙尚未开始,暂不能签到");
- }
- if (salon.getEndAt() != null && now.after(salon.getEndAt())) {
- return Result.error("沙龙已结束,不能签到");
- }
- // 报名且已支付/已确认才可签到
- Long enrolled = trainEnrollmentMapper.selectCount(
- new LambdaQueryWrapper<TrainEnrollment>()
- .eq(TrainEnrollment::getUid, userId)
- .eq(TrainEnrollment::getSalonId, salonId)
- .in(TrainEnrollment::getStatus, ACTIVE_STATUS));
- if (enrolled == null || enrolled == 0) {
- return Result.error("请先报名并完成支付");
- }
- // 幂等:已签到直接返回成功(积分已被发放,pointsEarned=0)
- Long existed = trainSalonCheckinMapper.selectCount(
- new LambdaQueryWrapper<TrainSalonCheckin>()
- .eq(TrainSalonCheckin::getUid, userId)
- .eq(TrainSalonCheckin::getSalonId, salonId));
- if (existed != null && existed > 0) {
- Map<String, Object> done = new HashMap<>();
- done.put("pointsEarned", 0);
- done.put("alreadyCompleted", true);
- return Result.success(done);
- }
- TrainSalonCheckin checkin = new TrainSalonCheckin();
- checkin.setUid(userId);
- checkin.setSalonId(salonId);
- try {
- trainSalonCheckinMapper.insert(checkin);
- } catch (Exception ex) {
- // 唯一键冲突(并发重复签到)按已签到处理
- }
- // 签到积分:取关联 cfc 活动的 checkinPoints(创建时默认 5),未关联则用默认 5
- int points = 5;
- if (salon.getActivityId() != null) {
- try {
- CfcActivity activity = cfcActivityMapper.selectById(salon.getActivityId());
- if (activity != null && activity.getCheckinPoints() != null && activity.getCheckinPoints() > 0) {
- points = activity.getCheckinPoints();
- }
- } catch (Exception e) {
- // 读取 cfc 活动失败用默认积分
- }
- }
- String title = salon.getTitle() == null ? "" : salon.getTitle();
- try {
- scoreService.addUserScoreIfAbsent(userId, "salon_checkin_" + salonId, points, userId, "沙龙签到:" + title);
- } catch (Exception e) {
- // 积分发放失败不阻塞签到
- org.slf4j.LoggerFactory.getLogger(getClass()).warn("沙龙签到积分发放失败: {}", e.getMessage());
- }
- Map<String, Object> result = new HashMap<>();
- result.put("pointsEarned", points);
- result.put("alreadyCompleted", false);
- return Result.success(result);
- }
- /**
- * 提交沙龙反馈(需已报名且已支付/已确认;评分 1-5;幂等,重复提交返回 true)
- */
- @Operation(summary = "提交沙龙反馈")
- @PostMapping("/feedback")
- public Result<Boolean> feedback(@RequestBody Map<String, Object> body,
- @RequestAttribute("userId") Long userId) {
- if (body.get("salonId") == null) {
- return Result.error("请选择沙龙期次");
- }
- Long salonId = Long.valueOf(body.get("salonId").toString());
- TrainSalon salon = trainSalonMapper.selectById(salonId);
- if (salon == null) {
- return Result.error("沙龙不存在");
- }
- Long enrolled = trainEnrollmentMapper.selectCount(
- new LambdaQueryWrapper<TrainEnrollment>()
- .eq(TrainEnrollment::getUid, userId)
- .eq(TrainEnrollment::getSalonId, salonId)
- .in(TrainEnrollment::getStatus, ACTIVE_STATUS));
- if (enrolled == null || enrolled == 0) {
- return Result.error("请先报名参加该沙龙");
- }
- int rating = 5;
- if (body.get("rating") != null) {
- try {
- rating = Integer.parseInt(body.get("rating").toString());
- } catch (NumberFormatException e) {
- rating = 5;
- }
- }
- if (rating < 1 || rating > 5) {
- return Result.error("评分需在 1-5 之间");
- }
- String comment = body.get("comment") == null ? "" : body.get("comment").toString().trim();
- if (comment.length() > 500) {
- comment = comment.substring(0, 500);
- }
- // 幂等:已提交直接返回成功
- Long existed = trainSalonFeedbackMapper.selectCount(
- new LambdaQueryWrapper<TrainSalonFeedback>()
- .eq(TrainSalonFeedback::getUid, userId)
- .eq(TrainSalonFeedback::getSalonId, salonId));
- if (existed != null && existed > 0) {
- return Result.success(true);
- }
- TrainSalonFeedback feedback = new TrainSalonFeedback();
- feedback.setUid(userId);
- feedback.setSalonId(salonId);
- feedback.setRating(rating);
- feedback.setComment(comment);
- try {
- trainSalonFeedbackMapper.insert(feedback);
- } catch (Exception ex) {
- // 唯一键冲突(并发重复提交)按已提交处理
- }
- return Result.success(true);
- }
- /**
- * 沙龙展示状态(对齐 cfc 活动 applyDisplayState 语义):
- * ended=已结束 / ongoing=进行中(时间窗内) / pending_start=未开始 / active=进行中(无时间窗) / draft=草稿
- */
- private String calcDisplayStatus(TrainSalon s) {
- if (s == null) {
- return null;
- }
- String status = s.getStatus();
- if ("draft".equals(status)) {
- return "draft";
- }
- Date now = new Date();
- if ("finished".equals(status)
- || (s.getEndAt() != null && now.after(s.getEndAt()))) {
- return "ended";
- }
- if (!"active".equals(status)) {
- return status;
- }
- if (s.getStartAt() != null && now.before(s.getStartAt())) {
- return "pending_start";
- }
- return "ongoing";
- }
- }
|