Merge branch 'release/redis-memory-fix-20260521' of gitea.haiyihy.com:hy/chatapp3-java

This commit is contained in:
hy001 2026-05-21 11:19:21 +08:00
commit a48fddb613
57 changed files with 2458 additions and 790 deletions

View File

@ -64,6 +64,8 @@ BADGE_ACTIVATION.body=You have received a new achievement badge, go check it out
# cp\u5173\u7CFB\u89E3\u9664 # cp\u5173\u7CFB\u89E3\u9664
CP_DISMISS.title=CP Dismiss CP_DISMISS.title=CP Dismiss
CP_DISMISS.body=${nickname} Dissolved the CP relationship with you CP_DISMISS.body=${nickname} Dissolved the CP relationship with you
CP_BLESS.title=Cp bless
CP_BLESS.body=${nickname} has sent you CP blessing gifts
# \u63A5\u6536\u8D35\u65CFvip # \u63A5\u6536\u8D35\u65CFvip
ACCEPT_NOBLE_VIP.title=Receiving nobles ACCEPT_NOBLE_VIP.title=Receiving nobles
ACCEPT_NOBLE_VIP.body=${nickname} gives you ${days} days of noble status~ ACCEPT_NOBLE_VIP.body=${nickname} gives you ${days} days of noble status~

View File

@ -81,6 +81,8 @@ AGREE_BD_LEADER_INVITE_AGENT.body=${userProfile} menerima undangan BD Anda
BD_LEADER_SEND_INVITE_BD.title=Undangan BD BD_LEADER_SEND_INVITE_BD.title=Undangan BD
BD_LEADER_SEND_INVITE_BD.body=${userProfile}mengundang Anda untuk menjadi BD BD_LEADER_SEND_INVITE_BD.body=${userProfile}mengundang Anda untuk menjadi BD
# CP祝福通知 # CP祝福通知
CP_DISMISS.title=CP Dismiss
CP_DISMISS.body=${nickname} Dissolved the CP relationship with you
CP_BLESS.title=Cp memberkati CP_BLESS.title=Cp memberkati
CP_BLESS.body=${nickname} Saya memberi Anda hadiah berkah ruang CP CP_BLESS.body=${nickname} Saya memberi Anda hadiah berkah ruang CP
# 告白通知 # 告白通知

View File

@ -60,6 +60,8 @@ BADGE_ACTIVATION.body=Yeni bir ba\u015Far\u0131 rozeti ald\u0131n\u0131z, gidip
# cp\u5173\u7CFB\u89E3\u9664 # cp\u5173\u7CFB\u89E3\u9664
CP_DISMISS.title=CP s\u00FCr\u00FCm\u00FC CP_DISMISS.title=CP s\u00FCr\u00FCm\u00FC
CP_DISMISS.body= ${nickname} sizinle CP ili\u015Fkisini bozdu CP_DISMISS.body= ${nickname} sizinle CP ili\u015Fkisini bozdu
CP_BLESS.title=Cp bless
CP_BLESS.body=${nickname} has sent you CP blessing gifts
# \u63A5\u6536\u8D35\u65CFvip # \u63A5\u6536\u8D35\u65CFvip
ACCEPT_NOBLE_VIP.title=Soylular al\u0131r ACCEPT_NOBLE_VIP.title=Soylular al\u0131r
ACCEPT_NOBLE_VIP.body =${nickname} size ${days} g\u00FCnl\u00FCk asil stat\u00FCs\u00FC verir ~ ACCEPT_NOBLE_VIP.body =${nickname} size ${days} g\u00FCnl\u00FCk asil stat\u00FCs\u00FC verir ~

View File

@ -63,6 +63,8 @@ BADGE_ACTIVATION.body=\u60A8\u5DF2\u7372\u5F97\u65B0\u7684\u6210\u5C31\u5FBD\u7A
# cp\u5173\u7CFB\u89E3\u9664 # cp\u5173\u7CFB\u89E3\u9664
CP_DISMISS.title=CP \u89E3\u9664 CP_DISMISS.title=CP \u89E3\u9664
CP_DISMISS.body= ${nickname} \u8207\u60A8\u89E3\u9664\u4E86 CP \u95DC\u4FC2 CP_DISMISS.body= ${nickname} \u8207\u60A8\u89E3\u9664\u4E86 CP \u95DC\u4FC2
CP_BLESS.title=Cp \u795D\u798F
CP_BLESS.body=${nickname} \u7D66\u4F60\u5011\u9001\u4E86cp\u7A7A\u9593\u795D\u798F\u79AE\u7269
# \u63A5\u6536\u8D35\u65CFvip # \u63A5\u6536\u8D35\u65CFvip
ACCEPT_NOBLE_VIP.title=\u8CB4\u65CF\u63A5\u6536 ACCEPT_NOBLE_VIP.title=\u8CB4\u65CF\u63A5\u6536
ACCEPT_NOBLE_VIP.body =${nickname} \u8D08\u9001\u60A8 ${days} \u5929\u7684\u8CB4\u65CF\u8EAB\u4EFD~ ACCEPT_NOBLE_VIP.body =${nickname} \u8D08\u9001\u60A8 ${days} \u5929\u7684\u8CB4\u65CF\u8EAB\u4EFD~

View File

@ -72,6 +72,11 @@ public enum UserRelationErrorCode implements IResponseErrorCode {
*/ */
CP_RELATIONSHIP_NOT_EXISTS(4313, "CP relationship does not exist"), CP_RELATIONSHIP_NOT_EXISTS(4313, "CP relationship does not exist"),
/**
* 关系类型与用户性别不匹配.
*/
RELATION_TYPE_GENDER_NOT_MATCH(4314, "Relationship type does not match user gender"),
; ;

View File

@ -41,6 +41,11 @@ public class CpSimpleUserProfileCO implements Serializable {
*/ */
private String meUserNickname; private String meUserNickname;
/**
* 关系类型CP/BROTHER/SISTERS.
*/
private String relationType;
/** /**
* CP用户ID * CP用户ID
*/ */

View File

@ -16,10 +16,12 @@ import com.red.circle.other.inner.model.cmd.user.OnlineCountQryCmd;
import com.red.circle.other.inner.model.dto.user.ActiveUserCountryCodeDTO; import com.red.circle.other.inner.model.dto.user.ActiveUserCountryCodeDTO;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@ -41,6 +43,9 @@ public class DatavRestController extends BaseController {
private final CountryDashboardDailyMetricService countryDashboardDailyMetricService; private final CountryDashboardDailyMetricService countryDashboardDailyMetricService;
private final CountryDashboardGameMetricService countryDashboardGameMetricService; private final CountryDashboardGameMetricService countryDashboardGameMetricService;
@Value("${red-circle.country-dashboard.query-enabled:true}")
private boolean countryDashboardQueryEnabled;
@GetMapping("/active/user-country-code") @GetMapping("/active/user-country-code")
public List<ActiveUserCountryCodeDTO> latestActiveUserCountryCode() { public List<ActiveUserCountryCodeDTO> latestActiveUserCountryCode() {
return userExpandService.latestActiveUserCountryCode(LocalDateTime.now().minusHours(2)); return userExpandService.latestActiveUserCountryCode(LocalDateTime.now().minusHours(2));
@ -58,30 +63,45 @@ public class DatavRestController extends BaseController {
@GetMapping("/country-dashboard") @GetMapping("/country-dashboard")
public CountryDashboardCO countryDashboard(CountryDashboardQryCmd cmd) { public CountryDashboardCO countryDashboard(CountryDashboardQryCmd cmd) {
if (!countryDashboardQueryEnabled) {
return emptyCountryDashboard(cmd);
}
return countryDashboardService.query(cmd); return countryDashboardService.query(cmd);
} }
@GetMapping("/country-dashboard/recharge-details") @GetMapping("/country-dashboard/recharge-details")
public PageResult<CountryDashboardRechargeDetailCO> countryDashboardRechargeDetails( public PageResult<CountryDashboardRechargeDetailCO> countryDashboardRechargeDetails(
CountryDashboardRechargeDetailQryCmd cmd) { CountryDashboardRechargeDetailQryCmd cmd) {
if (!countryDashboardQueryEnabled) {
return PageResult.newPageResult(0);
}
return countryDashboardService.pageRechargeDetails(cmd); return countryDashboardService.pageRechargeDetails(cmd);
} }
@GetMapping("/country-dashboard/game-metrics") @GetMapping("/country-dashboard/game-metrics")
public PageResult<CountryDashboardGameMetricCO> countryDashboardGameMetrics( public PageResult<CountryDashboardGameMetricCO> countryDashboardGameMetrics(
CountryDashboardGameMetricQryCmd cmd) { CountryDashboardGameMetricQryCmd cmd) {
if (!countryDashboardQueryEnabled) {
return PageResult.newPageResult(0);
}
return countryDashboardGameMetricService.pageGameMetrics(cmd); return countryDashboardGameMetricService.pageGameMetrics(cmd);
} }
@GetMapping("/country-dashboard/game-metrics/games") @GetMapping("/country-dashboard/game-metrics/games")
public PageResult<CountryDashboardGameMetricCO> countryDashboardGameMetricGames( public PageResult<CountryDashboardGameMetricCO> countryDashboardGameMetricGames(
CountryDashboardGameMetricQryCmd cmd) { CountryDashboardGameMetricQryCmd cmd) {
if (!countryDashboardQueryEnabled) {
return PageResult.newPageResult(0);
}
return countryDashboardGameMetricService.pageGameSummaries(cmd); return countryDashboardGameMetricService.pageGameSummaries(cmd);
} }
@GetMapping("/country-dashboard/game-metrics/country-rank") @GetMapping("/country-dashboard/game-metrics/country-rank")
public List<CountryDashboardGameMetricCO> countryDashboardGameMetricCountryRanks( public List<CountryDashboardGameMetricCO> countryDashboardGameMetricCountryRanks(
CountryDashboardGameMetricQryCmd cmd) { CountryDashboardGameMetricQryCmd cmd) {
if (!countryDashboardQueryEnabled) {
return Collections.emptyList();
}
return countryDashboardGameMetricService.listGameCountryRanks(cmd); return countryDashboardGameMetricService.listGameCountryRanks(cmd);
} }
@ -91,6 +111,9 @@ public class DatavRestController extends BaseController {
@RequestParam String endDate, @RequestParam String endDate,
@RequestParam(value = "sysOrigin", defaultValue = "LIKEI") String sysOrigin, @RequestParam(value = "sysOrigin", defaultValue = "LIKEI") String sysOrigin,
@RequestParam(value = "statTimezones", required = false) String statTimezones) { @RequestParam(value = "statTimezones", required = false) String statTimezones) {
if (!countryDashboardQueryEnabled) {
return disabledCountryDashboardBackfill(startDate, endDate, sysOrigin);
}
LocalDate parsedStartDate = LocalDate.parse(startDate); LocalDate parsedStartDate = LocalDate.parse(startDate);
LocalDate parsedEndDate = LocalDate.parse(endDate); LocalDate parsedEndDate = LocalDate.parse(endDate);
List<String> refreshedTimezones = countryDashboardDailyMetricService.refreshRange( List<String> refreshedTimezones = countryDashboardDailyMetricService.refreshRange(
@ -109,6 +132,9 @@ public class DatavRestController extends BaseController {
@RequestParam String endDate, @RequestParam String endDate,
@RequestParam(value = "sysOrigin", defaultValue = "LIKEI") String sysOrigin, @RequestParam(value = "sysOrigin", defaultValue = "LIKEI") String sysOrigin,
@RequestParam(value = "statTimezones", required = false) String statTimezones) { @RequestParam(value = "statTimezones", required = false) String statTimezones) {
if (!countryDashboardQueryEnabled) {
return disabledCountryDashboardBackfill(startDate, endDate, sysOrigin);
}
LocalDate parsedStartDate = LocalDate.parse(startDate); LocalDate parsedStartDate = LocalDate.parse(startDate);
LocalDate parsedEndDate = LocalDate.parse(endDate); LocalDate parsedEndDate = LocalDate.parse(endDate);
List<String> refreshedTimezones = countryDashboardGameMetricService.refreshRange( List<String> refreshedTimezones = countryDashboardGameMetricService.refreshRange(
@ -121,4 +147,23 @@ public class DatavRestController extends BaseController {
"statTimezones", refreshedTimezones); "statTimezones", refreshedTimezones);
} }
private CountryDashboardCO emptyCountryDashboard(CountryDashboardQryCmd cmd) {
return new CountryDashboardCO()
.setPeriodType(cmd.getPeriodType())
.setStartDate(cmd.getStartDate())
.setEndDate(cmd.getEndDate())
.setStatTimezone(cmd.getStatTimezone())
.setTotal(new com.red.circle.console.app.dto.clientobject.datav.CountryDashboardMetricCO())
.setRecords(Collections.emptyList());
}
private Map<String, Object> disabledCountryDashboardBackfill(String startDate, String endDate,
String sysOrigin) {
return Map.of(
"status", "disabled",
"startDate", startDate,
"endDate", endDate,
"sysOrigin", sysOrigin);
}
} }

View File

@ -1,14 +1,15 @@
package com.red.circle.other.adapter.app.user.relation; package com.red.circle.other.adapter.app.user.relation;
import com.red.circle.common.business.dto.cmd.AppExtCommand; import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.common.business.dto.cmd.UserIdCmd;
import com.red.circle.framework.web.controller.BaseController; import com.red.circle.framework.web.controller.BaseController;
import com.red.circle.other.app.command.user.LoveLetterQueryCmdExe; import com.red.circle.other.app.command.user.LoveLetterQueryCmdExe;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpPairUserProfileCO; import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpPairUserProfileCO;
import com.red.circle.other.domain.model.cp.loveletter.LoveLetterDetailCO; import com.red.circle.other.domain.model.cp.loveletter.LoveLetterDetailCO;
import com.red.circle.other.domain.model.cp.loveletter.LoveLetterWallCO; import com.red.circle.other.domain.model.cp.loveletter.LoveLetterWallCO;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyIdQueryCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyDismissCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyDismissCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpRelationshipQueryCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.ProcessApplyCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.ProcessApplyCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.loveletter.SendLoveLetterCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.loveletter.SendLoveLetterCmd;
import com.red.circle.other.app.service.user.relation.UserCpRelationService; import com.red.circle.other.app.service.user.relation.UserCpRelationService;
@ -51,7 +52,7 @@ public class CpRelationshipRestController extends BaseController {
* @eo.request-type formdata * @eo.request-type formdata
*/ */
@GetMapping("/pair") @GetMapping("/pair")
public List<CpPairUserProfileCO> getCpPairUserProfileCO(AppExtCommand cmd) { public List<CpPairUserProfileCO> getCpPairUserProfileCO(CpRelationshipQueryCmd cmd) {
return userCpRelationService.getCpPairUserProfileCO(cmd); return userCpRelationService.getCpPairUserProfileCO(cmd);
} }
@ -103,7 +104,7 @@ public class CpRelationshipRestController extends BaseController {
* @eo.request-type formdata * @eo.request-type formdata
*/ */
@GetMapping("/apply-id") @GetMapping("/apply-id")
public String getCpApplyId(@Validated UserIdCmd cmd) { public String getCpApplyId(@Validated CpApplyIdQueryCmd cmd) {
return userCpRelationService.getCpApplyId(cmd); return userCpRelationService.getCpApplyId(cmd);
} }

View File

@ -1,13 +1,13 @@
package com.red.circle.other.adapter.app.user.user; package com.red.circle.other.adapter.app.user.user;
import com.red.circle.common.business.dto.cmd.UserIdCommonCmd;
import com.red.circle.framework.web.controller.BaseController; import com.red.circle.framework.web.controller.BaseController;
import com.red.circle.other.app.dto.clientobject.user.user.CpBlessRecordCO; import com.red.circle.other.app.dto.clientobject.user.user.CpBlessRecordCO;
import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinCO; import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinCO;
import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinUnreadCO; import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinUnreadCO;
import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinValueCO; import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinValueCO;
import com.red.circle.other.app.dto.cmd.user.user.UserCpBlessRecordQueryCmd; import com.red.circle.other.app.dto.cmd.user.user.UserCpBlessRecordQueryCmd;
import com.red.circle.other.app.dto.cmd.user.user.UserCpCabinQueryCmd;
import com.red.circle.other.app.service.user.user.UserCpCabinService; import com.red.circle.other.app.service.user.user.UserCpCabinService;
import java.util.List; import java.util.List;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@ -34,7 +34,7 @@ public class UserCpCabinRestController extends BaseController {
* cp小屋相关信息 * cp小屋相关信息
*/ */
@GetMapping @GetMapping
public UserCpCabinCO getCpCabinInfo(UserIdCommonCmd cmd) { public UserCpCabinCO getCpCabinInfo(UserCpCabinQueryCmd cmd) {
return userCpCabinService.getCpCabinInfo(cmd); return userCpCabinService.getCpCabinInfo(cmd);
} }
@ -42,7 +42,7 @@ public class UserCpCabinRestController extends BaseController {
* cp value. * cp value.
*/ */
@GetMapping("/value") @GetMapping("/value")
public UserCpCabinValueCO getCpCabinValue(UserIdCommonCmd cmd) { public UserCpCabinValueCO getCpCabinValue(UserCpCabinQueryCmd cmd) {
return userCpCabinService.getCpCabinValue(cmd); return userCpCabinService.getCpCabinValue(cmd);
} }
@ -50,7 +50,7 @@ public class UserCpCabinRestController extends BaseController {
* 获得最近两百条祝福记录,并标记为已读. * 获得最近两百条祝福记录,并标记为已读.
*/ */
@GetMapping("/list") @GetMapping("/list")
public UserCpCabinUnreadCO getCpBlessRecordAndUpRead(UserIdCommonCmd cmd) { public UserCpCabinUnreadCO getCpBlessRecordAndUpRead(UserCpCabinQueryCmd cmd) {
return userCpCabinService.getCpBlessRecordAndUpRead(cmd); return userCpCabinService.getCpBlessRecordAndUpRead(cmd);
} }

View File

@ -0,0 +1,30 @@
package com.red.circle.other.adapter.app.user.user;
import com.red.circle.framework.web.controller.BaseController;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpRightsConfigCO;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpRightsConfigQueryCmd;
import com.red.circle.other.app.service.user.user.UserCpCabinService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* CP rights.
*/
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/user/cp/rights", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserCpRightsRestController extends BaseController {
private final UserCpCabinService userCpCabinService;
/**
* CP rights config.
*/
@GetMapping("/config")
public CpRightsConfigCO getCpRightsConfig(CpRightsConfigQueryCmd cmd) {
return userCpCabinService.getCpRightsConfig(cmd);
}
}

View File

@ -1,10 +1,15 @@
package com.red.circle.other.app.command.user; package com.red.circle.other.app.command.user;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.red.circle.external.inner.endpoint.message.ImMessageClient; import com.red.circle.external.inner.endpoint.message.OfficialNoticeClient;
import com.red.circle.external.inner.model.cmd.message.notice.official.NoticeExtTemplateTypeCmd;
import com.red.circle.external.inner.model.enums.message.OfficialNoticeTypeEnum;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyDismissCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyDismissCmd;
import com.red.circle.other.app.service.user.user.UserProfileService; import com.red.circle.other.app.service.user.user.UserProfileService;
import com.red.circle.other.domain.gateway.user.UserProfileGateway; import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.infra.common.user.UserGiftBackpackCommon; import com.red.circle.other.infra.common.user.UserGiftBackpackCommon;
import com.red.circle.other.infra.database.cache.service.cp.CpRelationshipCacheService; import com.red.circle.other.infra.database.cache.service.cp.CpRelationshipCacheService;
import com.red.circle.other.infra.database.cache.service.user.UserCpValueCacheService; import com.red.circle.other.infra.database.cache.service.user.UserCpValueCacheService;
@ -15,6 +20,9 @@ import com.red.circle.other.infra.database.rds.service.user.user.CpBlessRecordSe
import com.red.circle.other.infra.database.rds.service.user.user.CpCabinAchieveService; import com.red.circle.other.infra.database.rds.service.user.user.CpCabinAchieveService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService; import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.database.rds.service.user.user.CpValueService; import com.red.circle.other.infra.database.rds.service.user.user.CpValueService;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import com.red.circle.tool.core.collection.MapBuilder;
import com.red.circle.tool.core.date.TimestampUtils;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -33,7 +41,7 @@ public class DismissCpApplyCmdExe {
private final CpValueService cpValueService; private final CpValueService cpValueService;
private final CpApplyService cpApplyService; private final CpApplyService cpApplyService;
private final ImMessageClient imMessageClient; private final OfficialNoticeClient officialNoticeClient;
private final CpRelationshipService cpRelationshipService; private final CpRelationshipService cpRelationshipService;
private final UserGiftBackpackCommon userGiftBackpackCommon; private final UserGiftBackpackCommon userGiftBackpackCommon;
private final WeekCpValueCountService weekCpValueCountService; private final WeekCpValueCountService weekCpValueCountService;
@ -44,20 +52,24 @@ public class DismissCpApplyCmdExe {
private final CpRelationshipCacheService cpRelationshipCacheService; private final CpRelationshipCacheService cpRelationshipCacheService;
public void execute(CpApplyDismissCmd cmd) { public void execute(CpApplyDismissCmd cmd) {
String relationType = parseRelationType(cmd.getRelationType());
var cpRelationship = cpRelationshipService.getByUserId(cmd.requiredReqUserId()); var cpRelationship = cpRelationshipService.getByUserId(
cmd.requiredReqUserId(), cmd.getCpUserId(), relationType);
if (Objects.isNull(cpRelationship)) { if (Objects.isNull(cpRelationship)) {
return; return;
} }
// 更新申请状态为解散 // 更新申请状态为解散
cpApplyService.dismiss(cmd.requiredReqUserId()); cpApplyService.dismiss(cmd.requiredReqUserId(), relationType);
// 更新CP关系为分手中不删除数据 // 更新CP关系为分手中不删除数据
cpRelationshipService.updateToDismissing(cmd.requiredReqUserId(), cmd.getCpUserId()); cpRelationshipService.updateToDismissing(cmd.requiredReqUserId(), cmd.getCpUserId(), relationType);
cpRelationshipCacheService.remove(Arrays.asList(cmd.requiredReqUserId(), cmd.getCpUserId())); cpRelationshipCacheService.remove(Arrays.asList(cmd.requiredReqUserId(), cmd.getCpUserId()));
sendDismissNotice(cmd, relationType);
// 以下数据不删除7天后由定时任务清理 // 以下数据不删除7天后由定时任务清理
// weekCpValueCountService.removeThisWeek(...) // weekCpValueCountService.removeThisWeek(...)
// cpValueService.deleteById(...) // cpValueService.deleteById(...)
@ -72,4 +84,36 @@ public class DismissCpApplyCmdExe {
return cmd.requiredReqUserId().toString(); return cmd.requiredReqUserId().toString();
} }
private void sendDismissNotice(CpApplyDismissCmd cmd, String relationType) {
UserProfile userProfile = userProfileGateway.getByUserId(cmd.requiredReqUserId());
if (Objects.isNull(userProfile)) {
return;
}
long dismissEndTime = TimestampUtils.now().getTime() + (7 * 24 * 60 * 60 * 1000L);
officialNoticeClient.send(NoticeExtTemplateTypeCmd.builder()
.toAccount(cmd.getCpUserId())
.noticeType(OfficialNoticeTypeEnum.CP_DISMISS)
.templateParam(MapBuilder.builder()
.put("nickname", userProfile.getUserNickname())
.put("userNickname", userProfile.getUserNickname())
.put("account", userProfile.getAccount())
.put("userAvatar", userProfile.getUserAvatar())
.put("countryCode", userProfile.getCountryCode())
.put("countryName", userProfile.getCountryName())
.put("relationType", relationType)
.put("dismissEndTime", dismissEndTime)
.build())
.expand(cmd.requiredReqUserId())
.build());
}
private String parseRelationType(String relationType) {
try {
return CpRelationshipType.normalize(relationType);
} catch (IllegalArgumentException ex) {
ResponseAssert.failure(CommonErrorCode.TYPE_IS_NOT_IN_SCOPE, "relationType is not supported.");
return CpRelationshipType.CP.name();
}
}
} }

View File

@ -16,6 +16,7 @@ import com.red.circle.other.infra.database.rds.service.user.user.CpApplyService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService; import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.database.rds.service.user.user.CpValueService; import com.red.circle.other.infra.database.rds.service.user.user.CpValueService;
import com.red.circle.other.infra.enums.user.user.CpApplyStatus; import com.red.circle.other.infra.enums.user.user.CpApplyStatus;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import com.red.circle.tool.core.date.TimestampUtils; import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.other.inner.asserts.user.UserRelationErrorCode; import com.red.circle.other.inner.asserts.user.UserRelationErrorCode;
import com.red.circle.wallet.inner.endpoint.wallet.WalletGoldClient; import com.red.circle.wallet.inner.endpoint.wallet.WalletGoldClient;
@ -55,6 +56,7 @@ public class ProcessCpApplyCmd {
CpApply cpApply = cpApplyService.getById(cmd.getApplyId()); CpApply cpApply = cpApplyService.getById(cmd.getApplyId());
// 没有找到映射信息 // 没有找到映射信息
ResponseAssert.notNull(CommonErrorCode.NOT_FOUND_MAPPING_INFO, cpApply); ResponseAssert.notNull(CommonErrorCode.NOT_FOUND_MAPPING_INFO, cpApply);
String relationType = CpRelationshipType.normalize(cpApply.getRelationType());
// 状态错误 // 状态错误
ResponseAssert.isTrue(CommonErrorCode.STATE_ERROR, ResponseAssert.isTrue(CommonErrorCode.STATE_ERROR,
@ -62,16 +64,17 @@ public class ProcessCpApplyCmd {
// 检查是否是复合申请 // 检查是否是复合申请
CpRelationship dismissingCp = cpRelationshipService.getDismissingCp( CpRelationship dismissingCp = cpRelationshipService.getDismissingCp(
cpApply.getSendApplyUserId(), cpApply.getAcceptApplyUserId()); cpApply.getSendApplyUserId(), cpApply.getAcceptApplyUserId(), relationType);
boolean isReconcile = Objects.nonNull(dismissingCp); boolean isReconcile = Objects.nonNull(dismissingCp);
if (!isReconcile) { if (!isReconcile) {
// 非复合申请CP已存在 // 非复合申请CP已存在
ResponseAssert.isFalse(UserRelationErrorCode.ME_OR_YOU_CP_EXISTED, ResponseAssert.isFalse(UserRelationErrorCode.ME_OR_YOU_CP_EXISTED,
cpRelationshipService.existsCp(cpApply.getSendApplyUserId(), cpApply.getAcceptApplyUserId())); cpRelationshipService.existsCp(cpApply.getSendApplyUserId(), cpApply.getAcceptApplyUserId(),
relationType));
// 检查CP数量限制最多4个 // 检查CP数量限制最多4个
int senderCpCount = cpRelationshipService.countCp(cmd.requiredReqUserId()); int senderCpCount = cpRelationshipService.countCp(cpApply.getSendApplyUserId());
int receiverCpCount = cpRelationshipService.countCp(cpApply.getAcceptApplyUserId()); int receiverCpCount = cpRelationshipService.countCp(cpApply.getAcceptApplyUserId());
ResponseAssert.isFalse(UserRelationErrorCode.CP_LIMIT_EXCEEDED, senderCpCount >= 4); ResponseAssert.isFalse(UserRelationErrorCode.CP_LIMIT_EXCEEDED, senderCpCount >= 4);
ResponseAssert.isFalse(UserRelationErrorCode.CP_LIMIT_EXCEEDED, receiverCpCount >= 4); ResponseAssert.isFalse(UserRelationErrorCode.CP_LIMIT_EXCEEDED, receiverCpCount >= 4);
@ -86,23 +89,24 @@ public class ProcessCpApplyCmd {
return; return;
} }
refuseStatusWait(cmd, cpApply); refuseStatusWait(cmd, cpApply, relationType);
if (isReconcile) { if (isReconcile) {
// 复合更新状态为NORMAL // 复合更新状态为NORMAL
cpRelationshipService.reconcile(cpApply.getSendApplyUserId(), cpApply.getAcceptApplyUserId()); cpRelationshipService.reconcile(cpApply.getSendApplyUserId(), cpApply.getAcceptApplyUserId(),
relationType);
} else { } else {
// 新建关系 // 新建关系
cpRelationshipService cpRelationshipService
.addCp(cpApply.getSendApplyUserId(), cpApply.getAcceptApplyUserId(), createCpValue(), .addCp(cpApply.getSendApplyUserId(), cpApply.getAcceptApplyUserId(), createCpValue(),
cmd.requireReqSysOrigin()); cmd.requireReqSysOrigin(), relationType);
} }
cpRelationshipCacheService.remove(Arrays.asList(cpApply.getSendApplyUserId(), cpApply.getAcceptApplyUserId())); cpRelationshipCacheService.remove(Arrays.asList(cpApply.getSendApplyUserId(), cpApply.getAcceptApplyUserId()));
} }
private void refuseStatusWait(ProcessApplyCmd cmd, CpApply cpApply) { private void refuseStatusWait(ProcessApplyCmd cmd, CpApply cpApply, String relationType) {
cpApplyService.refuseStatusWait(cmd.requiredReqUserId()); cpApplyService.refuseStatusWait(cmd.requiredReqUserId(), relationType);
userMqMessageService.cpApplyDelayed( userMqMessageService.cpApplyDelayed(
new CpApplyEvent() new CpApplyEvent()
.setId(cpApply.getId()) .setId(cpApply.getId())
@ -111,6 +115,11 @@ public class ProcessCpApplyCmd {
} }
private void returnGoldCoins(ProcessApplyCmd cmd, CpApply cpApply) { private void returnGoldCoins(ProcessApplyCmd cmd, CpApply cpApply) {
if (Objects.isNull(cpApply.getApplyConsumeGold())
|| cpApply.getApplyConsumeGold().compareTo(BigDecimal.ZERO) <= 0) {
cpApplyService.changeStatusById(cmd.getApplyId(), CpApplyStatus.REIMBURSE);
return;
}
walletGoldClient.changeBalance(GoldReceiptCmd.builder() walletGoldClient.changeBalance(GoldReceiptCmd.builder()
.appIncome() .appIncome()
.userId(cpApply.getSendApplyUserId()) .userId(cpApply.getSendApplyUserId())

View File

@ -5,6 +5,7 @@ import com.red.circle.external.inner.endpoint.message.OfficialNoticeClient;
import com.red.circle.external.inner.model.cmd.message.notice.official.NoticeExtTemplateTypeCmd; import com.red.circle.external.inner.model.cmd.message.notice.official.NoticeExtTemplateTypeCmd;
import com.red.circle.external.inner.model.enums.message.OfficialNoticeTypeEnum; import com.red.circle.external.inner.model.enums.message.OfficialNoticeTypeEnum;
import com.red.circle.framework.core.asserts.ResponseAssert; import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.mq.business.model.event.user.CpApplyEvent; import com.red.circle.mq.business.model.event.user.CpApplyEvent;
import com.red.circle.mq.rocket.business.producer.UserMqMessageService; import com.red.circle.mq.rocket.business.producer.UserMqMessageService;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor; import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
@ -18,6 +19,7 @@ import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship;
import com.red.circle.other.infra.database.rds.service.user.user.CpApplyService; import com.red.circle.other.infra.database.rds.service.user.user.CpApplyService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService; import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.enums.user.user.CpApplyStatus; import com.red.circle.other.infra.enums.user.user.CpApplyStatus;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import com.red.circle.other.inner.enums.config.EnumConfigKey; import com.red.circle.other.inner.enums.config.EnumConfigKey;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO; import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.tool.core.date.TimestampUtils; import com.red.circle.tool.core.date.TimestampUtils;
@ -27,10 +29,12 @@ import com.red.circle.wallet.inner.model.cmd.GoldReceiptCmd;
import com.red.circle.wallet.inner.model.dto.WalletReceiptResDTO; import com.red.circle.wallet.inner.model.dto.WalletReceiptResDTO;
import com.red.circle.wallet.inner.model.enums.GoldOrigin; import com.red.circle.wallet.inner.model.enums.GoldOrigin;
import java.math.BigDecimal;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
@ -40,6 +44,7 @@ import org.springframework.stereotype.Component;
*/ */
@Component @Component
@RequiredArgsConstructor @RequiredArgsConstructor
@Slf4j
public class SendCpApplyCmdExe { public class SendCpApplyCmdExe {
private final CpApplyService cpApplyService; private final CpApplyService cpApplyService;
@ -53,73 +58,101 @@ public class SendCpApplyCmdExe {
private final UserRegionGateway userRegionGateway; private final UserRegionGateway userRegionGateway;
public void execute(CpApplyCmd cmd) { public void execute(CpApplyCmd cmd) {
process(cmd.requiredReqUserId(), cmd.getAcceptApplyUserId(), cmd.requireReqSysOrigin(),
cmd.getRelationType(), true);
}
public boolean autoCreateFromCpGift(Long sendUserId, Long acceptUserId, String sysOrigin) {
try {
process(sendUserId, acceptUserId, sysOrigin, CpRelationshipType.CP.name(), false);
return true;
} catch (Exception ex) {
log.info("[CP] skip auto create cp apply from gift, sendUserId={}, acceptUserId={}, reason={}",
sendUserId, acceptUserId, ex.getMessage());
return false;
}
}
private void process(Long sendUserId, Long acceptUserId, String sysOrigin, String relationTypeValue,
boolean chargeGold) {
CpRelationshipType relationType = parseRelationType(relationTypeValue);
// 不可用操作自己 // 不可用操作自己
ResponseAssert.isFalse(UserRelationErrorCode.UNAVAILABLE_OPS_YOURSELF, ResponseAssert.isFalse(UserRelationErrorCode.UNAVAILABLE_OPS_YOURSELF,
Objects.equals(cmd.requiredReqUserId(), cmd.getAcceptApplyUserId())); Objects.equals(sendUserId, acceptUserId));
boolean eqRegion = userRegionGateway.checkEqRegion(cmd.requiredReqUserId(), cmd.getAcceptApplyUserId()); boolean eqRegion = userRegionGateway.checkEqRegion(sendUserId, acceptUserId);
ResponseAssert.isTrue(UserRelationErrorCode.UNAVAILABLE_NOT_REGION, eqRegion); ResponseAssert.isTrue(UserRelationErrorCode.UNAVAILABLE_NOT_REGION, eqRegion);
UserProfileDTO userProfile = userProfileAppConvertor.toUserProfileDTO(
userProfileGateway.getByUserId(sendUserId));
UserProfileDTO acceptUserProfile = userProfileAppConvertor.toUserProfileDTO(
userProfileGateway.getByUserId(acceptUserId));
validateRelationTypeGender(relationType, userProfile, acceptUserProfile);
// 检查是否是复合申请 // 检查是否是复合申请
CpRelationship dismissingCp = cpRelationshipService.getDismissingCp( CpRelationship dismissingCp = cpRelationshipService.getDismissingCp(
cmd.requiredReqUserId(), cmd.getAcceptApplyUserId()); sendUserId, acceptUserId, relationType.name());
boolean isReconcile = Objects.nonNull(dismissingCp); boolean isReconcile = Objects.nonNull(dismissingCp);
if (!isReconcile) { if (!isReconcile) {
// 非复合申请检查CP是否已存在 // 非复合申请检查CP是否已存在
ResponseAssert.isFalse(UserRelationErrorCode.ME_OR_YOU_CP_EXISTED, ResponseAssert.isFalse(UserRelationErrorCode.ME_OR_YOU_CP_EXISTED,
cpRelationshipService cpRelationshipService
.existsCp(cmd.requiredReqUserId(), cmd.getAcceptApplyUserId())); .existsCp(sendUserId, acceptUserId, relationType.name()));
// 检查CP数量限制最多4个 // 检查CP数量限制最多4个
int senderCpCount = cpRelationshipService.countCp(cmd.requiredReqUserId()); int senderCpCount = cpRelationshipService.countCp(sendUserId);
int receiverCpCount = cpRelationshipService.countCp(cmd.getAcceptApplyUserId()); int receiverCpCount = cpRelationshipService.countCp(acceptUserId);
ResponseAssert.isFalse(UserRelationErrorCode.CP_LIMIT_EXCEEDED, senderCpCount >= 4); ResponseAssert.isFalse(UserRelationErrorCode.CP_LIMIT_EXCEEDED, senderCpCount >= 4);
ResponseAssert.isFalse(UserRelationErrorCode.CP_LIMIT_EXCEEDED, receiverCpCount >= 4); ResponseAssert.isFalse(UserRelationErrorCode.CP_LIMIT_EXCEEDED, receiverCpCount >= 4);
} }
// 您已发送申请 // 您已发送申请
ResponseAssert.isFalse(UserRelationErrorCode.YOU_HAVE_SENT_AN_APPLICATION, ResponseAssert.isFalse(UserRelationErrorCode.YOU_HAVE_SENT_AN_APPLICATION,
cpApplyService.existsNotProcessSendApply(cmd.requiredReqUserId())); cpApplyService.existsNotProcessSendApply(sendUserId, relationType.name()));
// 对方已向你发送申请 // 对方已向你发送申请
ResponseAssert.isFalse(UserRelationErrorCode.OTHER_SIDE_ALREADY_APPLIED, ResponseAssert.isFalse(UserRelationErrorCode.OTHER_SIDE_ALREADY_APPLIED,
cpApplyService.exists(cmd.requiredReqUserId(), cmd.getAcceptApplyUserId())); cpApplyService.exists(sendUserId, acceptUserId, relationType.name()));
UserProfileDTO userProfile = userProfileAppConvertor.toUserProfileDTO(userProfileGateway.getByUserId(cmd.requiredReqUserId()));
UserProfileDTO acceptUserProfile = userProfileAppConvertor.toUserProfileDTO(userProfileGateway.getByUserId(cmd.getAcceptApplyUserId()));
ResponseAssert.isFalse(UserRelationErrorCode.UNAVAILABLE_SAME_GENDER, Objects.equals(userProfile.getUserSex(), acceptUserProfile.getUserSex()));
BigDecimal applyConsumeGold = BigDecimal.ZERO;
if (chargeGold) {
WalletReceiptResDTO receipt = ResponseAssert.requiredSuccess( WalletReceiptResDTO receipt = ResponseAssert.requiredSuccess(
walletGoldClient.changeBalance(GoldReceiptCmd.builder() walletGoldClient.changeBalance(GoldReceiptCmd.builder()
.appExpenditure() .appExpenditure()
.userId(cmd.requiredReqUserId()) .userId(sendUserId)
.eventId(cmd.getAcceptApplyUserIdString()) .eventId(acceptUserId.toString())
.sysOrigin(cmd.requireReqSysOrigin()) .sysOrigin(sysOrigin)
.origin(GoldOrigin.CP_BUILD) .origin(GoldOrigin.CP_BUILD)
.amount(enumConfigCacheService.getValueBigDecimal(EnumConfigKey.CP_PRICE, .amount(enumConfigCacheService.getValueBigDecimal(EnumConfigKey.CP_PRICE,
cmd.requireReqSysOrigin())) sysOrigin))
.build()) .build())
); );
applyConsumeGold = receipt.getOpAmount().getDollarAmount();
}
String applyText = isReconcile String applyText = isReconcile
? "User " + userProfile.getUserNickname() + " wants to reconcile with you; if you accept, you will be a couple again." ? "User " + userProfile.getUserNickname() + " wants to reconcile with you; if you accept, you will be "
: "User " + userProfile.getUserNickname() + " confessed the feeling to you; if you accept, you will become a couple."; + relationType.applyTargetText() + " again."
: "User " + userProfile.getUserNickname() + " invited you; if you accept, you will become "
+ relationType.applyTargetText() + ".";
CpApply cpApply = new CpApply() CpApply cpApply = new CpApply()
.setSendApplyUserId(cmd.requiredReqUserId()) .setSendApplyUserId(sendUserId)
.setAcceptApplyUserId(cmd.getAcceptApplyUserId()) .setAcceptApplyUserId(acceptUserId)
.setRelationType(relationType.name())
.setApplyText(applyText) .setApplyText(applyText)
.setStatus(CpApplyStatus.WAIT.name()) .setStatus(CpApplyStatus.WAIT.name())
.setApplyConsumeGold(receipt.getOpAmount().getDollarAmount()); .setApplyConsumeGold(applyConsumeGold);
cpApplyService.save(cpApply); cpApplyService.save(cpApply);
Map<Object, Object> map = OfficialNoticeUtils.buildUserProfile(userProfile); Map<Object, Object> map = OfficialNoticeUtils.buildUserProfile(userProfile);
map.put("applyType", isReconcile ? "RECONCILE" : "APPLY"); map.put("applyType", isReconcile ? "RECONCILE" : "APPLY");
map.put("relationType", relationType.name());
officialNoticeClient.send(NoticeExtTemplateTypeCmd.builder() officialNoticeClient.send(NoticeExtTemplateTypeCmd.builder()
.toAccount(cmd.getAcceptApplyUserId()) .toAccount(acceptUserId)
.noticeType(OfficialNoticeTypeEnum.CP_BUILD) .noticeType(OfficialNoticeTypeEnum.CP_BUILD)
.templateParam(map) .templateParam(map)
.expand(cpApply.getId()) .expand(cpApply.getId())
@ -129,8 +162,28 @@ public class SendCpApplyCmdExe {
userMqMessageService.cpApplyDelayed( userMqMessageService.cpApplyDelayed(
new CpApplyEvent() new CpApplyEvent()
.setId(cpApply.getId()) .setId(cpApply.getId())
.setSysOrigin(SysOriginPlatformEnum.valueOf(cmd.requireReqSysOrigin())), .setSysOrigin(SysOriginPlatformEnum.valueOf(sysOrigin)),
TimestampUtils.nowPlusDays(1)); TimestampUtils.nowPlusDays(1));
} }
private CpRelationshipType parseRelationType(String relationTypeValue) {
try {
return CpRelationshipType.of(relationTypeValue);
} catch (IllegalArgumentException ex) {
ResponseAssert.failure(CommonErrorCode.TYPE_IS_NOT_IN_SCOPE, "relationType is not supported.");
return CpRelationshipType.CP;
}
}
private void validateRelationTypeGender(CpRelationshipType relationType, UserProfileDTO userProfile,
UserProfileDTO acceptUserProfile) {
if (Objects.equals(relationType, CpRelationshipType.CP)) {
ResponseAssert.isFalse(UserRelationErrorCode.UNAVAILABLE_SAME_GENDER,
Objects.equals(userProfile.getUserSex(), acceptUserProfile.getUserSex()));
return;
}
ResponseAssert.isTrue(UserRelationErrorCode.RELATION_TYPE_GENDER_NOT_MATCH,
relationType.genderMatched(userProfile.getUserSex(), acceptUserProfile.getUserSex()));
}
} }

View File

@ -1,7 +1,8 @@
package com.red.circle.other.app.command.user.query; package com.red.circle.other.app.command.user.query;
import com.red.circle.common.business.dto.cmd.UserIdCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyIdQueryCmd;
import com.red.circle.other.infra.database.rds.service.user.user.CpApplyService; import com.red.circle.other.infra.database.rds.service.user.user.CpApplyService;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import java.util.Optional; import java.util.Optional;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -17,8 +18,9 @@ public class CpApplyIdQryExe {
private final CpApplyService cpApplyService; private final CpApplyService cpApplyService;
public String execute(UserIdCmd cmd) { public String execute(CpApplyIdQueryCmd cmd) {
return Optional.ofNullable(cpApplyService.getId(cmd.requiredReqUserId(), cmd.getUserId())) return Optional.ofNullable(cpApplyService.getId(cmd.requiredReqUserId(), cmd.getUserId(),
CpRelationshipType.normalize(cmd.getRelationType())))
.map(String::valueOf) .map(String::valueOf)
.orElse(null); .orElse(null);
} }

View File

@ -12,6 +12,7 @@ import com.red.circle.other.infra.database.rds.entity.user.user.CpBlessRecord;
import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship; import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship;
import com.red.circle.other.infra.database.rds.service.user.user.CpBlessRecordService; import com.red.circle.other.infra.database.rds.service.user.user.CpBlessRecordService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService; import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import com.red.circle.tool.core.collection.CollectionUtils; import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -37,7 +38,8 @@ public class UserCpBlessRecordQueryExe {
public List<CpBlessRecordCO> execute(UserCpBlessRecordQueryCmd cmd) { public List<CpBlessRecordCO> execute(UserCpBlessRecordQueryCmd cmd) {
CpRelationship relationship = cpRelationshipService.getByUserIdOrCpUserId(cmd.getUserId()); CpRelationship relationship = cpRelationshipService.getByUserIdOrCpUserId(
cmd.getUserId(), CpRelationshipType.normalize(cmd.getRelationType()));
if (Objects.isNull(relationship)) { if (Objects.isNull(relationship)) {
return Lists.newArrayList(); return Lists.newArrayList();
} }

View File

@ -2,9 +2,6 @@ package com.red.circle.other.app.command.user.query;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.red.circle.common.business.core.enums.CommonErrorEnum;
import com.red.circle.common.business.dto.cmd.UserIdCommonCmd;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.app.convertor.user.UserCpCabinConvertor; import com.red.circle.other.app.convertor.user.UserCpCabinConvertor;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor; import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpCabinConfigCO; import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpCabinConfigCO;
@ -12,6 +9,7 @@ import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpPairUserProf
import com.red.circle.other.app.dto.clientobject.user.relation.cp.UserCpCabinSpecialMemberCO; import com.red.circle.other.app.dto.clientobject.user.relation.cp.UserCpCabinSpecialMemberCO;
import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinCO; import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinCO;
import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinSpecialCO; import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinSpecialCO;
import com.red.circle.other.app.dto.cmd.user.user.UserCpCabinQueryCmd;
import com.red.circle.other.domain.gateway.user.UserProfileGateway; import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.model.user.UserProfile; import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.infra.database.rds.entity.user.user.CpBlessRecord; import com.red.circle.other.infra.database.rds.entity.user.user.CpBlessRecord;
@ -23,10 +21,12 @@ import com.red.circle.other.infra.database.rds.service.user.user.CpCabinAchieveS
import com.red.circle.other.infra.database.rds.service.user.user.CpCabinConfigService; import com.red.circle.other.infra.database.rds.service.user.user.CpCabinConfigService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService; import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.database.rds.service.user.user.CpValueService; import com.red.circle.other.infra.database.rds.service.user.user.CpValueService;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import com.red.circle.tool.core.collection.CollectionUtils; import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.TimestampUtils; import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.num.NumUtils; import com.red.circle.tool.core.num.NumUtils;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
@ -55,30 +55,26 @@ public class UserCpCabinQueryExe {
private final CpCabinAchieveService cpCabinAchieveService; private final CpCabinAchieveService cpCabinAchieveService;
private final CpRelationshipService cpRelationshipService; private final CpRelationshipService cpRelationshipService;
public UserCpCabinCO execute(UserIdCommonCmd cmd) { public UserCpCabinCO execute(UserCpCabinQueryCmd cmd) {
String relationType = CpRelationshipType.normalize(cmd.getRelationType());
List<CpCabinConfig> cpCabinConfig = cpCabinConfigService.getCpCabinConfig( CpRelationship relationship = cpRelationshipService.getByUserIdOrCpUserId(
cmd.getReqSysOrigin().getOrigin()); cmd.getUserId(), relationType);
ResponseAssert.notEmpty(CommonErrorEnum.NOT_FOUND_MAPPING_INFO, cpCabinConfig);
List<CpCabinConfigCO> cpCabinConfigList = userCpCabinConvertor.toCpCabinConfigCO(cpCabinConfig);
CpRelationship relationship = cpRelationshipService.getByUserIdOrCpUserId(cmd.getUserId());
Boolean selfCabin = Objects.equals(cmd.getUserId(), cmd.getReqUserId()); Boolean selfCabin = Objects.equals(cmd.getUserId(), cmd.getReqUserId());
if (Objects.isNull(relationship)) { if (Objects.isNull(relationship)) {
UserCpCabinCO userCpCabinCO = new UserCpCabinCO(); return emptyCabin(selfCabin);
CpPairUserProfileCO cpPairUserProfileCO = new CpPairUserProfileCO();
cpPairUserProfileCO.setMeUserProfile(userProfileAppConvertor.toUserProfileDTO(
userProfileGateway.getByUserId(cmd.getReqUserId())));
userCpCabinCO.setCpPairUserProfileCO(cpPairUserProfileCO);
userCpCabinCO.setCpCabinConfigCO(cpCabinConfigList);
userCpCabinCO.setCheckSelfCabin(selfCabin);
userCpCabinCO.setCpValLastMonth(0L);
return userCpCabinCO;
} }
List<CpCabinConfig> cpCabinConfig = cpCabinConfigService.getCpCabinConfig(
cmd.getReqSysOrigin().getOrigin());
List<CpCabinConfigCO> cpCabinConfigList = CollectionUtils.isEmpty(cpCabinConfig)
? Collections.emptyList()
: userCpCabinConvertor.toCpCabinConfigCO(cpCabinConfig);
CpValue cpValue = cpValueService.getById(relationship.getCpValId()); CpValue cpValue = cpValueService.getById(relationship.getCpValId());
CpPairUserProfileCO cpPairUserProfileCO = new CpPairUserProfileCO(); CpPairUserProfileCO cpPairUserProfileCO = new CpPairUserProfileCO();
cpPairUserProfileCO.setRelationType(CpRelationshipType.normalize(relationship.getRelationType()));
cpPairUserProfileCO.setCpUserProfile(userProfileAppConvertor.toUserProfileDTO( cpPairUserProfileCO.setCpUserProfile(userProfileAppConvertor.toUserProfileDTO(
userProfileGateway.getByUserId(relationship.getCpUserId()))); userProfileGateway.getByUserId(relationship.getCpUserId())));
cpPairUserProfileCO.setMeUserProfile(userProfileAppConvertor.toUserProfileDTO( cpPairUserProfileCO.setMeUserProfile(userProfileAppConvertor.toUserProfileDTO(
@ -104,6 +100,18 @@ public class UserCpCabinQueryExe {
.build(); .build();
} }
private static UserCpCabinCO emptyCabin(Boolean selfCabin) {
return UserCpCabinCO.builder()
.cpVal("0")
.blessVal(0L)
.cpPairUserProfileCO(null)
.cpCabinConfigCO(Collections.emptyList())
.currentCpCabinConfigCO(null)
.userCpCabinSpecial(null)
.checkSelfCabin(Boolean.TRUE.equals(selfCabin))
.build();
}
private UserCpCabinSpecialCO getUserCpCabinSpecialCO( private UserCpCabinSpecialCO getUserCpCabinSpecialCO(
CpRelationship relationship, CpPairUserProfileCO cpPairUserProfileCO, CpRelationship relationship, CpPairUserProfileCO cpPairUserProfileCO,
CpCabinConfigCO currentCpCabin) { CpCabinConfigCO currentCpCabin) {

View File

@ -1,12 +1,13 @@
package com.red.circle.other.app.command.user.query; package com.red.circle.other.app.command.user.query;
import com.red.circle.common.business.dto.cmd.UserIdCommonCmd;
import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinValueCO; import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinValueCO;
import com.red.circle.other.app.dto.cmd.user.user.UserCpCabinQueryCmd;
import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship; import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship;
import com.red.circle.other.infra.database.rds.entity.user.user.CpValue; import com.red.circle.other.infra.database.rds.entity.user.user.CpValue;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService; import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.database.rds.service.user.user.CpValueService; import com.red.circle.other.infra.database.rds.service.user.user.CpValueService;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import com.red.circle.tool.core.num.NumUtils; import com.red.circle.tool.core.num.NumUtils;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Objects; import java.util.Objects;
@ -27,9 +28,10 @@ public class UserCpCabinValueQueryExe {
private final CpValueService cpValueService; private final CpValueService cpValueService;
private final CpRelationshipService cpRelationshipService; private final CpRelationshipService cpRelationshipService;
public UserCpCabinValueCO execute(UserIdCommonCmd cmd) { public UserCpCabinValueCO execute(UserCpCabinQueryCmd cmd) {
CpRelationship relationship = cpRelationshipService.getByUserIdOrCpUserId(cmd.getUserId()); CpRelationship relationship = cpRelationshipService.getByUserIdOrCpUserId(
cmd.getUserId(), CpRelationshipType.normalize(cmd.getRelationType()));
if (Objects.isNull(relationship)) { if (Objects.isNull(relationship)) {
return UserCpCabinValueCO.builder() return UserCpCabinValueCO.builder()
.blessVal(0L) .blessVal(0L)

View File

@ -2,14 +2,14 @@ package com.red.circle.other.app.command.user.query;
import com.red.circle.common.business.core.enums.CommonErrorEnum; import com.red.circle.common.business.core.enums.CommonErrorEnum;
import com.red.circle.common.business.dto.cmd.UserIdCmd;
import com.red.circle.framework.core.asserts.ResponseAssert; import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpUserProfileCO;
import com.red.circle.other.app.dto.cmd.user.relation.cp.UserCpLightCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.UserCpLightCmd;
import com.red.circle.other.app.service.user.relation.UserCpLightCacheService; import com.red.circle.other.app.service.user.relation.UserCpLightCacheService;
import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import java.util.Objects; import java.util.Objects;
import com.red.circle.other.app.service.user.relation.UserCpRelationService;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -26,40 +26,41 @@ import org.springframework.stereotype.Component;
public class UserCpLightCmdExe { public class UserCpLightCmdExe {
private final UserCpLightCacheService userCpLightCacheService; private final UserCpLightCacheService userCpLightCacheService;
private final UserCpRelationService userCpRelationService; private final CpRelationshipService cpRelationshipService;
public void execute(UserCpLightCmd cmd) { public void execute(UserCpLightCmd cmd) {
if (StringUtils.isBlank(cmd.getNearUserId()) || Objects.equals(cmd.getNearUserId(), "null")) { if (StringUtils.isBlank(cmd.getNearUserId()) || Objects.equals(cmd.getNearUserId(), "null")) {
ResponseAssert.failure(CommonErrorEnum.DATA_PARSING_ERROR); ResponseAssert.failure(CommonErrorEnum.DATA_PARSING_ERROR);
} }
UserIdCmd userIdCmd = new UserIdCmd(); Long nearUserId = Long.parseLong(cmd.getNearUserId());
userIdCmd.setUserId(cmd.getReqUserId()); CpRelationship cpRelationship = cpRelationshipService.getByUserId(
CpUserProfileCO cpUserProfileCO = userCpRelationService.getCpUser(userIdCmd); cmd.getReqUserId(), nearUserId, CpRelationshipType.normalize(cmd.getRelationType()));
// 如果cp用户是空不点亮 // 如果cp用户是空不点亮
if (Objects.isNull(cpUserProfileCO)) { if (Objects.isNull(cpRelationship)) {
return; return;
} }
// 如果cp不是旁边用户不点亮 // 如果cp不是旁边用户不点亮
if (Objects.nonNull(cpUserProfileCO.getUserProfile().getId()) && !Objects.equals(cpUserProfileCO.getUserProfile().getId().toString(), cmd.getNearUserId())) { if (Objects.nonNull(cpRelationship.getCpUserId()) && !Objects.equals(
cpRelationship.getCpUserId(), nearUserId)) {
return; return;
} }
if (Objects.nonNull(cmd.getType()) && Objects.equals(cmd.getType(), "APPOINT")) { if (Objects.nonNull(cmd.getType()) && Objects.equals(cmd.getType(), "APPOINT")) {
userCpLightCacheService.lightCpUserAppoint(cmd.getReqUserId(), userCpLightCacheService.lightCpUserAppoint(cmd.getReqUserId(),
Long.parseLong(cmd.getNearUserId()), nearUserId,
cmd.getReqSysOrigin().getOrigin()); cmd.getReqSysOrigin().getOrigin());
userCpLightCacheService.lightCpUserAppoint( userCpLightCacheService.lightCpUserAppoint(
Long.parseLong(cmd.getNearUserId()), nearUserId,
cmd.getReqUserId(), cmd.getReqUserId(),
cmd.getReqSysOrigin().getOrigin()); cmd.getReqSysOrigin().getOrigin());
} else { } else {
userCpLightCacheService.lightCpUser(cmd.getReqUserId(), userCpLightCacheService.lightCpUser(cmd.getReqUserId(),
Long.parseLong(cmd.getNearUserId()), nearUserId,
cmd.getReqSysOrigin().getOrigin()); cmd.getReqSysOrigin().getOrigin());
userCpLightCacheService.lightCpUser( userCpLightCacheService.lightCpUser(
Long.parseLong(cmd.getNearUserId()), nearUserId,
cmd.getReqUserId(), cmd.getReqUserId(),
cmd.getReqSysOrigin().getOrigin()); cmd.getReqSysOrigin().getOrigin());
} }
@ -69,12 +70,12 @@ public class UserCpLightCmdExe {
if (StringUtils.isBlank(cmd.getNearUserId()) || Objects.equals(cmd.getNearUserId(), "null")) { if (StringUtils.isBlank(cmd.getNearUserId()) || Objects.equals(cmd.getNearUserId(), "null")) {
ResponseAssert.failure(CommonErrorEnum.DATA_PARSING_ERROR); ResponseAssert.failure(CommonErrorEnum.DATA_PARSING_ERROR);
} }
UserIdCmd userIdCmd = new UserIdCmd(); Long nearUserId = Long.parseLong(cmd.getNearUserId());
userIdCmd.setUserId(cmd.getReqUserId()); CpRelationship cpRelationship = cpRelationshipService.getByUserId(
CpUserProfileCO cpUserProfileCO = userCpRelationService.getCpUser(userIdCmd); cmd.getReqUserId(), nearUserId, CpRelationshipType.normalize(cmd.getRelationType()));
// 如果cp用户是空不点亮 // 如果cp用户是空不点亮
if (Objects.isNull(cpUserProfileCO)) { if (Objects.isNull(cpRelationship)) {
return; return;
} }
@ -85,18 +86,18 @@ public class UserCpLightCmdExe {
if (Objects.nonNull(cmd.getType()) && Objects.equals(cmd.getType(), "APPOINT")) { if (Objects.nonNull(cmd.getType()) && Objects.equals(cmd.getType(), "APPOINT")) {
userCpLightCacheService.cancelCpUserAppoint(cmd.getReqUserId(), userCpLightCacheService.cancelCpUserAppoint(cmd.getReqUserId(),
cpUserProfileCO.getUserProfile().getId(), cpRelationship.getCpUserId(),
cmd.getReqSysOrigin().getOrigin()); cmd.getReqSysOrigin().getOrigin());
userCpLightCacheService.cancelCpUserAppoint( userCpLightCacheService.cancelCpUserAppoint(
cpUserProfileCO.getUserProfile().getId(), cpRelationship.getCpUserId(),
cmd.getReqUserId(), cmd.getReqUserId(),
cmd.getReqSysOrigin().getOrigin()); cmd.getReqSysOrigin().getOrigin());
} else { } else {
userCpLightCacheService.cancelCpUser(cmd.getReqUserId(), userCpLightCacheService.cancelCpUser(cmd.getReqUserId(),
cpUserProfileCO.getUserProfile().getId(), cpRelationship.getCpUserId(),
cmd.getReqSysOrigin().getOrigin()); cmd.getReqSysOrigin().getOrigin());
userCpLightCacheService.cancelCpUser( userCpLightCacheService.cancelCpUser(
cpUserProfileCO.getUserProfile().getId(), cpRelationship.getCpUserId(),
cmd.getReqUserId(), cmd.getReqUserId(),
cmd.getReqSysOrigin().getOrigin()); cmd.getReqSysOrigin().getOrigin());
} }

View File

@ -1,6 +1,5 @@
package com.red.circle.other.app.command.user.query; package com.red.circle.other.app.command.user.query;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.framework.core.asserts.ResponseAssert; import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.mq.business.model.event.task.TaskApprovalEvent; import com.red.circle.mq.business.model.event.task.TaskApprovalEvent;
import com.red.circle.mq.rocket.business.producer.TaskMqMessage; import com.red.circle.mq.rocket.business.producer.TaskMqMessage;
@ -8,16 +7,19 @@ import com.red.circle.other.infra.database.rds.service.user.user.CpValueService;
import com.red.circle.tool.core.date.DateUtils; import com.red.circle.tool.core.date.DateUtils;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor; import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpPairUserProfileCO; import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpPairUserProfileCO;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpRelationshipQueryCmd;
import com.red.circle.other.domain.model.user.UserProfile; import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.domain.gateway.user.UserProfileGateway; import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship; import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService; import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import com.red.circle.other.inner.asserts.user.UserErrorCode; import com.red.circle.other.inner.asserts.user.UserErrorCode;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO; import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import java.time.ZoneId; import java.time.ZoneId;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@ -34,19 +36,24 @@ import org.springframework.stereotype.Component;
@RequiredArgsConstructor @RequiredArgsConstructor
public class UserCpPairUserProfileQryExe { public class UserCpPairUserProfileQryExe {
private static final long DISMISS_DURATION_MS = 7 * 24 * 60 * 60 * 1000L;
private final CpRelationshipService cpRelationshipService; private final CpRelationshipService cpRelationshipService;
private final UserProfileGateway userProfileGateway; private final UserProfileGateway userProfileGateway;
private final UserProfileAppConvertor userProfileAppConvertor; private final UserProfileAppConvertor userProfileAppConvertor;
private final CpValueService cpValueService; private final CpValueService cpValueService;
private final TaskMqMessage taskMqMessage; private final TaskMqMessage taskMqMessage;
public List<CpPairUserProfileCO> execute(AppExtCommand cmd) { public List<CpPairUserProfileCO> execute(CpRelationshipQueryCmd cmd) {
String relationType = CpRelationshipType.normalize(cmd.getRelationType());
UserProfile meUser = userProfileGateway.getByUserId(cmd.requiredReqUserId()); UserProfile meUser = userProfileGateway.getByUserId(cmd.requiredReqUserId());
ResponseAssert.notNull(UserErrorCode.USER_INFO_NOT_FOUND, meUser); ResponseAssert.notNull(UserErrorCode.USER_INFO_NOT_FOUND, meUser);
List<CpRelationship> cpRelationshipList = cpRelationshipService.getByUserId(cmd.requiredReqUserId()); List<CpRelationship> cpRelationshipList = cpRelationshipService.getByUserId(
List<CpRelationship> dismissing = cpRelationshipService.getDismissingByUserId(cmd.requiredReqUserId()); cmd.requiredReqUserId(), relationType);
List<CpRelationship> dismissing = cpRelationshipService.getDismissingByUserId(
cmd.requiredReqUserId(), relationType);
cpRelationshipList.addAll(dismissing); cpRelationshipList.addAll(dismissing);
if (cpRelationshipList.isEmpty()) { if (cpRelationshipList.isEmpty()) {
return Collections.emptyList(); return Collections.emptyList();
@ -56,10 +63,13 @@ public class UserCpPairUserProfileQryExe {
.map(cpRelationship -> new CpPairUserProfileCO() .map(cpRelationship -> new CpPairUserProfileCO()
.setMeUserProfile(userProfileAppConvertor.toUserProfileDTO((meUser))) .setMeUserProfile(userProfileAppConvertor.toUserProfileDTO((meUser)))
.setCpUserProfile(getUserProfile(cpRelationship.getCpUserId())) .setCpUserProfile(getUserProfile(cpRelationship.getCpUserId()))
.setRelationType(relationType(cpRelationship))
.setStatus(cpRelationship.getStatus()) .setStatus(cpRelationship.getStatus())
.setCpValue(cpValueService.getCpVal(cpRelationship.getCpValId())) .setCpValue(cpValueService.getCpVal(cpRelationship.getCpValId()))
.setDays(DateUtils.toDurationDays(cpRelationship.getCreateTime(), DateUtils.now())) .setDays(relationshipDays(cpRelationship.getCreateTime()))
.setFirstDay(cpRelationship.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString())) .setFirstDay(cpRelationship.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString())
.setDismissEndTime(dismissEndTime(cpRelationship))
.setDismissRemainSeconds(dismissRemainSeconds(cpRelationship)))
.sorted(Comparator.comparing(CpPairUserProfileCO::getCpValue).reversed()) .sorted(Comparator.comparing(CpPairUserProfileCO::getCpValue).reversed())
.toList(); .toList();
} }
@ -68,4 +78,31 @@ public class UserCpPairUserProfileQryExe {
return userProfileAppConvertor.toUserProfileDTO(userProfileGateway return userProfileAppConvertor.toUserProfileDTO(userProfileGateway
.getByUserId(cpUserId)); .getByUserId(cpUserId));
} }
private static long relationshipDays(Date createTime) {
Date now = DateUtils.now();
if (!createTime.before(now)) {
return 0L;
}
return DateUtils.toDurationDays(createTime, now);
}
private static String relationType(CpRelationship cpRelationship) {
return CpRelationshipType.normalize(cpRelationship.getRelationType());
}
private static Long dismissEndTime(CpRelationship cpRelationship) {
if (Objects.isNull(cpRelationship.getDismissTime())) {
return null;
}
return cpRelationship.getDismissTime() + DISMISS_DURATION_MS;
}
private static Long dismissRemainSeconds(CpRelationship cpRelationship) {
Long dismissEndTime = dismissEndTime(cpRelationship);
if (Objects.isNull(dismissEndTime)) {
return null;
}
return Math.max(0L, (dismissEndTime - System.currentTimeMillis()) / 1000);
}
} }

View File

@ -8,10 +8,12 @@ import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpUserProfileC
import com.red.circle.other.domain.gateway.user.UserProfileGateway; import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.cache.service.user.UserCpValueCacheService; import com.red.circle.other.infra.database.cache.service.user.UserCpValueCacheService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService; import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO; import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.enums.user.UserCpLevelEnum; import com.red.circle.other.inner.enums.user.UserCpLevelEnum;
import java.time.ZoneId; import java.time.ZoneId;
import java.util.Date;
import java.util.Optional; import java.util.Optional;
import com.red.circle.tool.core.date.LocalDateTimeUtils; import com.red.circle.tool.core.date.LocalDateTimeUtils;
@ -37,7 +39,8 @@ public class UserCpRelationQryExe {
return Optional.ofNullable(cpRelationshipService.getByUserId(cmd.getReqUserId(), cmd.getUserId())) return Optional.ofNullable(cpRelationshipService.getByUserId(cmd.getReqUserId(), cmd.getUserId()))
.map(cpRelationship -> new CpUserProfileCO() .map(cpRelationship -> new CpUserProfileCO()
.setUserProfile(getUserProfile(cpRelationship.getCpUserId())) .setUserProfile(getUserProfile(cpRelationship.getCpUserId()))
.setDays(DateUtils.toDurationDays(cpRelationship.getCreateTime(), DateUtils.now())) .setRelationType(CpRelationshipType.normalize(cpRelationship.getRelationType()))
.setDays(relationshipDays(cpRelationship.getCreateTime()))
.setFirstDay(cpRelationship.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString()) .setFirstDay(cpRelationship.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString())
) )
.orElse(null); .orElse(null);
@ -48,6 +51,14 @@ public class UserCpRelationQryExe {
.getByUserId(cpUserId)); .getByUserId(cpUserId));
} }
private static long relationshipDays(Date createTime) {
Date now = DateUtils.now();
if (!createTime.before(now)) {
return 0L;
}
return DateUtils.toDurationDays(createTime, now);
}
private UserCpLevelEnum getLevel(Long userId1, Long userId2) { private UserCpLevelEnum getLevel(Long userId1, Long userId2) {
Long val = userCpValueCacheService.getValue(userId1, userId2); Long val = userCpValueCacheService.getValue(userId1, userId2);

View File

@ -21,6 +21,7 @@ import com.red.circle.other.infra.database.rds.service.user.user.CpCabinAchieveS
import com.red.circle.other.infra.database.rds.service.user.user.CpCabinConfigService; import com.red.circle.other.infra.database.rds.service.user.user.CpCabinConfigService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService; import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.database.rds.service.user.user.CpValueService; import com.red.circle.other.infra.database.rds.service.user.user.CpValueService;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import com.red.circle.other.inner.enums.user.UserCpLevelEnum; import com.red.circle.other.inner.enums.user.UserCpLevelEnum;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO; import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.tool.core.collection.CollectionUtils; import com.red.circle.tool.core.collection.CollectionUtils;
@ -78,6 +79,7 @@ public class UserCpRelationQueryV4Exe {
return buildUserCpCabinSpecialCO(CpCabinUserProfileCO.builder() return buildUserCpCabinSpecialCO(CpCabinUserProfileCO.builder()
.userProfile(getUserProfile(cpRelationship.getCpUserId())) .userProfile(getUserProfile(cpRelationship.getCpUserId()))
.relationType(CpRelationshipType.normalize(cpRelationship.getRelationType()))
.days(TimestampUtils.durationNowDays(cpRelationship.getCreateTime())) .days(TimestampUtils.durationNowDays(cpRelationship.getCreateTime()))
.level(getLevel(cpRelationship.getUserId(), cpRelationship.getCpUserId())) .level(getLevel(cpRelationship.getUserId(), cpRelationship.getCpUserId()))
.currentCpCabinConfigCO(currentCpCabinConfigCO) .currentCpCabinConfigCO(currentCpCabinConfigCO)

View File

@ -0,0 +1,141 @@
package com.red.circle.other.app.command.user.query;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpRightsConfigCO;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpRightsConfigQueryCmd;
import com.red.circle.other.infra.database.rds.entity.user.user.CpCabinConfig;
import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship;
import com.red.circle.other.infra.database.rds.entity.user.user.CpValue;
import com.red.circle.other.infra.database.rds.service.user.user.CpCabinConfigService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.database.rds.service.user.user.CpValueService;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.IntStream;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
/**
* CP rights config query.
*/
@Component
@RequiredArgsConstructor
public class UserCpRightsConfigQueryExe {
private static final String RELATIONSHIP_STATUS_NONE = "NONE";
private final CpCabinConfigService cpCabinConfigService;
private final CpRelationshipService cpRelationshipService;
private final CpValueService cpValueService;
public CpRightsConfigCO execute(CpRightsConfigQueryCmd cmd) {
String relationType = CpRelationshipType.normalize(cmd.getRelationType());
CpRelationship relationship = findRelationship(cmd.getReqUserId(), cmd.getCpUserId(),
relationType);
Long intimacyValue = getIntimacyValue(relationship);
List<CpCabinConfig> configs = cpCabinConfigService.getCpCabinConfig(
cmd.getReqSysOrigin().getOrigin());
return CpRightsConfigCO.builder()
.relationType(relationType)
.cpUserId(resolveCpUserId(cmd.getReqUserId(), cmd.getCpUserId(), relationship))
.relationshipStatus(Objects.isNull(relationship) ? RELATIONSHIP_STATUS_NONE
: relationship.getStatus())
.intimacyValue(intimacyValue)
.levels(toLevels(relationType, configs, Objects.nonNull(relationship), intimacyValue))
.build();
}
private CpRelationship findRelationship(Long reqUserId, Long cpUserId, String relationType) {
if (Objects.isNull(reqUserId)) {
return null;
}
if (Objects.nonNull(cpUserId)) {
CpRelationship normal = cpRelationshipService.getByUserId(reqUserId, cpUserId,
relationType);
if (Objects.nonNull(normal)) {
return normal;
}
return cpRelationshipService.getDismissingCp(reqUserId, cpUserId, relationType);
}
return cpRelationshipService.getByUserIdOrCpUserId(reqUserId, relationType);
}
private Long getIntimacyValue(CpRelationship relationship) {
if (Objects.isNull(relationship)) {
return 0L;
}
CpValue cpValue = cpValueService.getById(relationship.getCpValId());
return Optional.ofNullable(cpValue)
.map(CpValue::getCpVal)
.map(BigDecimal::longValue)
.orElse(0L);
}
private Long resolveCpUserId(Long reqUserId, Long requestCpUserId, CpRelationship relationship) {
if (Objects.nonNull(requestCpUserId) || Objects.isNull(relationship)) {
return requestCpUserId;
}
if (Objects.equals(relationship.getUserId(), reqUserId)) {
return relationship.getCpUserId();
}
if (Objects.equals(relationship.getCpUserId(), reqUserId)) {
return relationship.getUserId();
}
return relationship.getCpUserId();
}
private List<CpRightsConfigCO.LevelCO> toLevels(String relationType, List<CpCabinConfig> configs,
boolean hasRelationship, Long intimacyValue) {
if (Objects.isNull(configs) || configs.isEmpty()) {
return Collections.emptyList();
}
return IntStream.range(0, configs.size())
.mapToObj(index -> toLevel(relationType, configs.get(index), index + 1, hasRelationship,
intimacyValue))
.toList();
}
private CpRightsConfigCO.LevelCO toLevel(String relationType, CpCabinConfig config, int level,
boolean hasRelationship, Long intimacyValue) {
Long requiredIntimacyValue = Optional.ofNullable(config.getCabinUnlockValue()).orElse(0L);
boolean unlocked = hasRelationship && Optional.ofNullable(intimacyValue).orElse(0L)
>= requiredIntimacyValue;
String levelName = StringUtils.defaultIfBlank(config.getName(), relationType + " Level "
+ level);
return CpRightsConfigCO.LevelCO.builder()
.level(level)
.levelName(levelName)
.requiredIntimacyValue(requiredIntimacyValue)
.unlocked(unlocked)
.rights(Collections.singletonList(toRight(relationType, config, level, levelName,
requiredIntimacyValue, unlocked)))
.build();
}
private CpRightsConfigCO.RightCO toRight(String relationType, CpCabinConfig config, int level,
String title, Long requiredIntimacyValue, boolean unlocked) {
return CpRightsConfigCO.RightCO.builder()
.rightKey(relationType + "_CABIN_LEVEL_" + level)
.icon(firstNotBlank(config.getCover(), config.getPersonCover(), config.getCardCover(),
config.getBackgroundCover(), config.getSourceMiniUrl(), config.getSourceUrl()))
.title(title)
.desc("Unlock when intimacy reaches " + requiredIntimacyValue)
.unlocked(unlocked)
.build();
}
private String firstNotBlank(String... values) {
for (String value : values) {
if (StringUtils.isNotBlank(value)) {
return value;
}
}
return null;
}
}

View File

@ -7,11 +7,14 @@ import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.common.business.enums.DynamicMessageEnum; import com.red.circle.common.business.enums.DynamicMessageEnum;
import com.red.circle.component.redis.service.RedisService; import com.red.circle.component.redis.service.RedisService;
import com.red.circle.external.inner.endpoint.message.OfficialNoticeClient; import com.red.circle.external.inner.endpoint.message.OfficialNoticeClient;
import com.red.circle.external.inner.model.cmd.message.notice.official.NoticeExtTemplateTypeCmd;
import com.red.circle.external.inner.model.enums.message.OfficialNoticeTypeEnum;
import com.red.circle.mq.business.model.event.gift.OfflineProcessGiftEvent; import com.red.circle.mq.business.model.event.gift.OfflineProcessGiftEvent;
import com.red.circle.mq.rocket.business.producer.TaskMqMessage; import com.red.circle.mq.rocket.business.producer.TaskMqMessage;
import com.red.circle.mq.rocket.business.producer.UserMqMessageService; import com.red.circle.mq.rocket.business.producer.UserMqMessageService;
import com.red.circle.other.app.common.game.GameIndoorTeamPkCommon; import com.red.circle.other.app.common.game.GameIndoorTeamPkCommon;
import com.red.circle.other.app.common.gift.GameLuckyGiftCommon; import com.red.circle.other.app.common.gift.GameLuckyGiftCommon;
import com.red.circle.other.app.command.user.SendCpApplyCmdExe;
import com.red.circle.other.app.dto.clientobject.dynamic.MessageItemCO; import com.red.circle.other.app.dto.clientobject.dynamic.MessageItemCO;
import com.red.circle.other.app.dto.clientobject.game.GameRoomPkUserCO; import com.red.circle.other.app.dto.clientobject.game.GameRoomPkUserCO;
import com.red.circle.other.app.dto.cmd.SpinsTaskProgressUpdateCmd; import com.red.circle.other.app.dto.cmd.SpinsTaskProgressUpdateCmd;
@ -77,6 +80,7 @@ import com.red.circle.other.inner.enums.material.GiftTabEnum;
import com.red.circle.other.inner.enums.task.RoomDailyTaskCode; import com.red.circle.other.inner.enums.task.RoomDailyTaskCode;
import com.red.circle.other.inner.model.dto.material.GiftConfigDTO; import com.red.circle.other.inner.model.dto.material.GiftConfigDTO;
import com.red.circle.tool.core.collection.CollectionUtils; import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.collection.MapBuilder;
import com.red.circle.tool.core.date.TimestampUtils; import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.date.ZonedDateTimeAsiaRiyadhUtils; import com.red.circle.tool.core.date.ZonedDateTimeAsiaRiyadhUtils;
import com.red.circle.tool.core.json.JacksonUtils; import com.red.circle.tool.core.json.JacksonUtils;
@ -147,6 +151,7 @@ public class GiftCountStrategy implements GiftStrategy {
private static final List<String> inRegionCodes = List.of("IN", "PK", "BD"); private static final List<String> inRegionCodes = List.of("IN", "PK", "BD");
private final UserRegionCacheService userRegionCacheService; private final UserRegionCacheService userRegionCacheService;
private final UserProfileGateway userProfileGateway; private final UserProfileGateway userProfileGateway;
private final SendCpApplyCmdExe sendCpApplyCmdExe;
@Override @Override
@ -187,6 +192,9 @@ public class GiftCountStrategy implements GiftStrategy {
// 动态礼物处理 // 动态礼物处理
processDynamicGift(runningWater); processDynamicGift(runningWater);
autoCreateCpApplyFromCpGift(runningWater);
saveBlessingsRecord(runningWater);
boolean isHighPriceGift = checkHighPriceGift(runningWater); boolean isHighPriceGift = checkHighPriceGift(runningWater);
BigDecimal giftValueCount = BigDecimal.valueOf(getActualAmount(giftValue, giftValue.getGiftValue())); BigDecimal giftValueCount = BigDecimal.valueOf(getActualAmount(giftValue, giftValue.getGiftValue()));
@ -357,16 +365,65 @@ public class GiftCountStrategy implements GiftStrategy {
cpValueService.incrBlessValue(cpValue.getId(), runningWater.getGiftValue().getGiftValue()); cpValueService.incrBlessValue(cpValue.getId(), runningWater.getGiftValue().getGiftValue());
sendCpBlessNotice(runningWater, cpRelationship, cache);
}
private void autoCreateCpApplyFromCpGift(GiftGiveRunningWater runningWater) {
try {
if (Objects.isNull(runningWater) || Objects.isNull(runningWater.getGiftValue())
|| !isCpGift(runningWater.getGiftValue())) {
return;
}
if (CollectionUtils.isEmpty(runningWater.getAcceptUsers())) {
return;
}
runningWater.getAcceptUsers().forEach(accept -> {
if (Objects.equals(runningWater.getUserId(), accept.getAcceptUserId())) {
return;
}
sendCpApplyCmdExe.autoCreateFromCpGift(
runningWater.getUserId(), accept.getAcceptUserId(), runningWater.getSysOrigin());
});
} catch (Exception ex) {
log.warn("[CP] skip auto create cp apply from gift, runningWaterId={}, giftId={}, sendUserId={}, reason={}",
Objects.nonNull(runningWater) ? runningWater.getId() : null,
Objects.nonNull(runningWater) ? runningWater.getGiftId() : null,
Objects.nonNull(runningWater) ? runningWater.getUserId() : null,
ex.getMessage());
}
}
private void sendCpBlessNotice(GiftGiveRunningWater runningWater, CpRelationship cpRelationship,
GiftConfigDTO giftConfig) {
UserProfile userProfile = userProfileRepository.getByUserId(runningWater.getUserId()); UserProfile userProfile = userProfileRepository.getByUserId(runningWater.getUserId());
// 发送祝福通知 if (Objects.isNull(userProfile)) {
/* officialService.send(NoticeExtTemplateTypeCmd.builder() return;
.toAccount(runningWater.getAcceptUsers().get(0).getAcceptUserId()) }
List<Long> toAccounts = Lists.newArrayList(cpRelationship.getUserId(), cpRelationship.getCpUserId())
.stream()
.filter(Objects::nonNull)
.distinct()
.toList();
if (CollectionUtils.isEmpty(toAccounts)) {
return;
}
officialService.send(NoticeExtTemplateTypeCmd.builder()
.toAccounts(toAccounts)
.noticeType(OfficialNoticeTypeEnum.CP_BLESS) .noticeType(OfficialNoticeTypeEnum.CP_BLESS)
.templateParam(MapBuilder.builder() .templateParam(MapBuilder.builder()
.put("nickname", userProfile.getUserNickname()) .put("nickname", userProfile.getUserNickname())
.put("userNickname", userProfile.getUserNickname())
.put("account", userProfile.getAccount())
.put("userAvatar", userProfile.getUserAvatar())
.put("countryCode", userProfile.getCountryCode())
.put("countryName", userProfile.getCountryName())
.put("giftCover", giftConfig.getGiftPhoto())
.put("giftCount", runningWater.getGiftValue().getQuantity())
.put("relationType", cpRelationship.getRelationType())
.build()) .build())
.build());*/ .expand(cpRelationship.getCpValId())
.build());
} }

View File

@ -75,6 +75,11 @@ public class CpApplyListener implements MessageListener {
} }
private void reimburse(CpApplyEvent param, CpApply cpApply) { private void reimburse(CpApplyEvent param, CpApply cpApply) {
if (Objects.isNull(cpApply.getApplyConsumeGold())
|| cpApply.getApplyConsumeGold().signum() <= 0) {
cpApplyService.changeStatusById(cpApply.getId(), CpApplyStatus.REIMBURSE);
return;
}
walletGoldClient.changeBalance(GoldReceiptCmd.builder() walletGoldClient.changeBalance(GoldReceiptCmd.builder()
.appIncome() .appIncome()
.userId(cpApply.getSendApplyUserId()) .userId(cpApply.getSendApplyUserId())

View File

@ -111,15 +111,53 @@ public class OnlineStatusUploadListener implements MessageListener {
} }
private void countActiveUser(UserProfile userProfile) { private void countActiveUser(UserProfile userProfile) {
long account = Objects.hash(userProfile.getAccount()); Long bitmapOffset = resolveActiveUserBitmapOffset(userProfile);
if (Objects.isNull(bitmapOffset) || bitmapOffset <= 0) {
log.warn("[在线状态]跳过活跃bitmap统计, userId={}, account={}, actualAccount={}",
userProfile.getId(),
userProfile.getAccount(),
userProfile.getActualAccount());
return;
}
if (userProfileGateway.checkTeamMember(userProfile.getId())) { if (userProfileGateway.checkTeamMember(userProfile.getId())) {
countUserActiveIndexService.countAnchorActiveUser(account); countUserActiveIndexService.countAnchorActiveUser(bitmapOffset);
countUserActiveIndexService.countAnchorActiveUser(userProfile.getOriginSys(), account); countUserActiveIndexService.countAnchorActiveUser(userProfile.getOriginSys(), bitmapOffset);
return; return;
} }
countUserActiveIndexService.countOrdinaryActiveUser(account); countUserActiveIndexService.countOrdinaryActiveUser(bitmapOffset);
countUserActiveIndexService.countOrdinaryActiveUser(userProfile.getOriginSys(), account); countUserActiveIndexService.countOrdinaryActiveUser(userProfile.getOriginSys(), bitmapOffset);
}
static Long resolveActiveUserBitmapOffset(UserProfile userProfile) {
if (Objects.isNull(userProfile)) {
return null;
}
Long offset = parsePositiveLong(userProfile.getAccount());
if (Objects.nonNull(offset)) {
return offset;
}
offset = parsePositiveLong(userProfile.getActualAccount());
if (Objects.nonNull(offset)) {
return offset;
}
return Optional.ofNullable(userProfile.getId())
.filter(id -> id > 0)
.orElse(null);
}
private static Long parsePositiveLong(String value) {
if (StringUtils.isBlank(value)) {
return null;
}
try {
long parsed = Long.parseLong(value.trim());
return parsed > 0 ? parsed : null;
} catch (NumberFormatException ignore) {
return null;
}
} }
private void addOnlineUser(UserOnlineStatusEvent event, UserProfile userProfile) { private void addOnlineUser(UserOnlineStatusEvent event, UserProfile userProfile) {

View File

@ -79,7 +79,7 @@ public class ActivityCorrectionDataManager {
log.warn("correctionActivityData:CHARM_RANK_MONTH-完成"); log.warn("correctionActivityData:CHARM_RANK_MONTH-完成");
// cp // cp
CpRelationship cpRelationship = cpRelationshipService.getByUserId(userId, null); CpRelationship cpRelationship = cpRelationshipService.getByUserId(userId, (Long) null);
if (Objects.nonNull(cpRelationship)) { if (Objects.nonNull(cpRelationship)) {
BigDecimal cpVal = cpValueService.getCpVal(cpRelationship.getCpValId()); BigDecimal cpVal = cpValueService.getCpVal(cpRelationship.getCpValId());

View File

@ -1,6 +1,5 @@
package com.red.circle.other.app.service.user.relation; package com.red.circle.other.app.service.user.relation;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.common.business.dto.cmd.UserIdCmd; import com.red.circle.common.business.dto.cmd.UserIdCmd;
import com.red.circle.common.business.dto.cmd.UserIdCommonCmd; import com.red.circle.common.business.dto.cmd.UserIdCommonCmd;
import com.red.circle.other.app.command.user.DismissCpApplyCmdExe; import com.red.circle.other.app.command.user.DismissCpApplyCmdExe;
@ -15,10 +14,12 @@ import com.red.circle.other.app.command.user.query.UserCpRelationQueryV4Exe;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpCabinUserProfileCO; import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpCabinUserProfileCO;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpPairUserProfileCO; import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpPairUserProfileCO;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpUserProfileCO; import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpUserProfileCO;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyIdQueryCmd;
import com.red.circle.other.domain.model.cp.loveletter.LoveLetterDetailCO; import com.red.circle.other.domain.model.cp.loveletter.LoveLetterDetailCO;
import com.red.circle.other.domain.model.cp.loveletter.LoveLetterWallCO; import com.red.circle.other.domain.model.cp.loveletter.LoveLetterWallCO;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyDismissCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyDismissCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpRelationshipQueryCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.ProcessApplyCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.ProcessApplyCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.loveletter.SendLoveLetterCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.loveletter.SendLoveLetterCmd;
import com.red.circle.other.app.util.DistributedLockUtil; import com.red.circle.other.app.util.DistributedLockUtil;
@ -26,6 +27,7 @@ import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; import java.util.List;
import java.util.Objects;
/** /**
* 用户cp关系实现. * 用户cp关系实现.
@ -53,13 +55,14 @@ public class UserCpRelationServiceImpl implements UserCpRelationService {
} }
@Override @Override
public List<CpPairUserProfileCO> getCpPairUserProfileCO(AppExtCommand cmd) { public List<CpPairUserProfileCO> getCpPairUserProfileCO(CpRelationshipQueryCmd cmd) {
return userCpPairUserProfileQryExe.execute(cmd); return userCpPairUserProfileQryExe.execute(cmd);
} }
@Override @Override
public void sendApply(CpApplyCmd cmd) { public void sendApply(CpApplyCmd cmd) {
String key = "SEND_CP_APPLY:" + cmd.getReqUserId() + "_" + cmd.getAcceptApplyUserId(); String key = "SEND_CP_APPLY:" + Objects.toString(cmd.getRelationType(), "CP")
+ "_" + cmd.getReqUserId() + "_" + cmd.getAcceptApplyUserId();
distributedLockUtil.executeWithLock(key, () -> { distributedLockUtil.executeWithLock(key, () -> {
sendCpApplyCmdExe.execute(cmd); sendCpApplyCmdExe.execute(cmd);
}); });
@ -79,7 +82,7 @@ public class UserCpRelationServiceImpl implements UserCpRelationService {
} }
@Override @Override
public String getCpApplyId(UserIdCmd cmd) { public String getCpApplyId(CpApplyIdQueryCmd cmd) {
return cpApplyIdQryExe.execute(cmd); return cpApplyIdQryExe.execute(cmd);
} }

View File

@ -1,17 +1,18 @@
package com.red.circle.other.app.service.user.user; package com.red.circle.other.app.service.user.user;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.red.circle.common.business.dto.cmd.UserIdCommonCmd;
import com.red.circle.other.app.convertor.user.CpBlessRecordConvert; import com.red.circle.other.app.convertor.user.CpBlessRecordConvert;
import com.red.circle.other.app.convertor.user.UserCpCabinConvertor; import com.red.circle.other.app.convertor.user.UserCpCabinConvertor;
import com.red.circle.other.app.dto.clientobject.user.user.CpBlessRecordCO; import com.red.circle.other.app.dto.clientobject.user.user.CpBlessRecordCO;
import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinUnreadCO; import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinUnreadCO;
import com.red.circle.other.app.dto.cmd.user.user.UserCpCabinQueryCmd;
import com.red.circle.other.domain.gateway.user.UserProfileGateway; import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.model.user.UserProfile; import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.infra.database.rds.entity.user.user.CpBlessRecord; import com.red.circle.other.infra.database.rds.entity.user.user.CpBlessRecord;
import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship; import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship;
import com.red.circle.other.infra.database.rds.service.user.user.CpBlessRecordService; import com.red.circle.other.infra.database.rds.service.user.user.CpBlessRecordService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService; import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import com.red.circle.tool.core.collection.CollectionUtils; import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -36,7 +37,7 @@ public class CpBlessRecordAndUpReadExe {
private final CpRelationshipService cpRelationshipService; private final CpRelationshipService cpRelationshipService;
private final CpBlessRecordConvert cpBlessRecordConvert; private final CpBlessRecordConvert cpBlessRecordConvert;
public UserCpCabinUnreadCO execute(UserIdCommonCmd cmd) { public UserCpCabinUnreadCO execute(UserCpCabinQueryCmd cmd) {
if (!Objects.equals(cmd.getReqUserId(), cmd.getUserId())) { if (!Objects.equals(cmd.getReqUserId(), cmd.getUserId())) {
return UserCpCabinUnreadCO.builder() return UserCpCabinUnreadCO.builder()
@ -45,7 +46,8 @@ public class CpBlessRecordAndUpReadExe {
.build(); .build();
} }
CpRelationship relationship = cpRelationshipService.getByUserId(cmd.getReqUserId(), cmd.getUserId()); CpRelationship relationship = cpRelationshipService.getByUserIdOrCpUserId(
cmd.getUserId(), CpRelationshipType.normalize(cmd.getRelationType()));
if (Objects.isNull(relationship)) { if (Objects.isNull(relationship)) {
return UserCpCabinUnreadCO.builder() return UserCpCabinUnreadCO.builder()
.topClassRecords(Lists.newArrayList()) .topClassRecords(Lists.newArrayList())

View File

@ -1,15 +1,18 @@
package com.red.circle.other.app.service.user.user; package com.red.circle.other.app.service.user.user;
import com.red.circle.common.business.dto.cmd.UserIdCommonCmd;
import com.red.circle.other.app.command.user.query.UserCpBlessRecordQueryExe; import com.red.circle.other.app.command.user.query.UserCpBlessRecordQueryExe;
import com.red.circle.other.app.command.user.query.UserCpCabinQueryExe; import com.red.circle.other.app.command.user.query.UserCpCabinQueryExe;
import com.red.circle.other.app.command.user.query.UserCpCabinValueQueryExe; import com.red.circle.other.app.command.user.query.UserCpCabinValueQueryExe;
import com.red.circle.other.app.command.user.query.UserCpRightsConfigQueryExe;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpRightsConfigCO;
import com.red.circle.other.app.dto.clientobject.user.user.CpBlessRecordCO; import com.red.circle.other.app.dto.clientobject.user.user.CpBlessRecordCO;
import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinCO; import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinCO;
import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinUnreadCO; import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinUnreadCO;
import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinValueCO; import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinValueCO;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpRightsConfigQueryCmd;
import com.red.circle.other.app.dto.cmd.user.user.UserCpBlessRecordQueryCmd; import com.red.circle.other.app.dto.cmd.user.user.UserCpBlessRecordQueryCmd;
import com.red.circle.other.app.dto.cmd.user.user.UserCpCabinQueryCmd;
import java.util.List; import java.util.List;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -26,19 +29,20 @@ public class UserCpCabinServiceImpl implements UserCpCabinService {
private final UserCpCabinValueQueryExe userCpCabinValueQueryExe; private final UserCpCabinValueQueryExe userCpCabinValueQueryExe;
private final CpBlessRecordAndUpReadExe cpBlessRecordAndUpReadExe; private final CpBlessRecordAndUpReadExe cpBlessRecordAndUpReadExe;
private final UserCpBlessRecordQueryExe userCpBlessRecordQueryExe; private final UserCpBlessRecordQueryExe userCpBlessRecordQueryExe;
private final UserCpRightsConfigQueryExe userCpRightsConfigQueryExe;
@Override @Override
public UserCpCabinCO getCpCabinInfo(UserIdCommonCmd cmd) { public UserCpCabinCO getCpCabinInfo(UserCpCabinQueryCmd cmd) {
return userCpCabinQueryExe.execute(cmd); return userCpCabinQueryExe.execute(cmd);
} }
@Override @Override
public UserCpCabinValueCO getCpCabinValue(UserIdCommonCmd cmd) { public UserCpCabinValueCO getCpCabinValue(UserCpCabinQueryCmd cmd) {
return userCpCabinValueQueryExe.execute(cmd); return userCpCabinValueQueryExe.execute(cmd);
} }
@Override @Override
public UserCpCabinUnreadCO getCpBlessRecordAndUpRead(UserIdCommonCmd cmd) { public UserCpCabinUnreadCO getCpBlessRecordAndUpRead(UserCpCabinQueryCmd cmd) {
return cpBlessRecordAndUpReadExe.execute(cmd); return cpBlessRecordAndUpReadExe.execute(cmd);
} }
@ -46,4 +50,9 @@ public class UserCpCabinServiceImpl implements UserCpCabinService {
public List<CpBlessRecordCO> pageCpBlessRecord(UserCpBlessRecordQueryCmd cmd) { public List<CpBlessRecordCO> pageCpBlessRecord(UserCpBlessRecordQueryCmd cmd) {
return userCpBlessRecordQueryExe.execute(cmd); return userCpBlessRecordQueryExe.execute(cmd);
} }
@Override
public CpRightsConfigCO getCpRightsConfig(CpRightsConfigQueryCmd cmd) {
return userCpRightsConfigQueryExe.execute(cmd);
}
} }

View File

@ -0,0 +1,52 @@
package com.red.circle.other.app.listener.user;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import com.red.circle.other.domain.model.user.OwnSpecialId;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.tool.core.date.TimestampUtils;
import org.junit.jupiter.api.Test;
class OnlineStatusUploadListenerTest {
@Test
void resolveActiveUserBitmapOffset_shouldUseNumericAccount() {
UserProfile profile = new UserProfile();
profile.setId(9988L);
profile.setAccount("123456");
assertEquals(123456L, OnlineStatusUploadListener.resolveActiveUserBitmapOffset(profile));
}
@Test
void resolveActiveUserBitmapOffset_shouldFallbackToNumericSpecialAccount() {
UserProfile profile = new UserProfile();
profile.setId(9988L);
profile.setAccount("abc");
OwnSpecialId ownSpecialId = new OwnSpecialId();
ownSpecialId.setAccount("654321");
ownSpecialId.setExpiredTime(TimestampUtils.nowPlusDays(1));
profile.setOwnSpecialId(ownSpecialId);
assertEquals(654321L, OnlineStatusUploadListener.resolveActiveUserBitmapOffset(profile));
}
@Test
void resolveActiveUserBitmapOffset_shouldFallbackToUserIdWhenAccountIsNotNumeric() {
UserProfile profile = new UserProfile();
profile.setId(9988L);
profile.setAccount("abc");
assertEquals(9988L, OnlineStatusUploadListener.resolveActiveUserBitmapOffset(profile));
}
@Test
void resolveActiveUserBitmapOffset_shouldReturnNullWhenNoPositiveCandidateExists() {
UserProfile profile = new UserProfile();
profile.setId(0L);
profile.setAccount("abc");
assertNull(OnlineStatusUploadListener.resolveActiveUserBitmapOffset(profile));
}
}

View File

@ -31,6 +31,11 @@ public class CpCabinUserProfileCO extends ClientObject {
*/ */
private UserProfileDTO userProfile; private UserProfileDTO userProfile;
/**
* 关系类型CP/BROTHER/SISTERS.
*/
private String relationType;
/** /**
* 组建天数. * 组建天数.
*/ */

View File

@ -33,6 +33,11 @@ public class CpPairUserProfileCO extends ClientObject {
private UserProfileDTO cpUserProfile; private UserProfileDTO cpUserProfile;
/**
* 关系类型CP/BROTHER/SISTERS.
*/
private String relationType;
/** /**
* CP关系状态NORMAL-正常, DISMISSING-分手中 * CP关系状态NORMAL-正常, DISMISSING-分手中
*/ */
@ -54,5 +59,16 @@ public class CpPairUserProfileCO extends ClientObject {
*/ */
private String firstDay; private String firstDay;
/**
* 解除冷静期结束时间戳.
*/
@JsonSerialize(using = ToStringSerializer.class)
private Long dismissEndTime;
/**
* 解除冷静期剩余秒数.
*/
private Long dismissRemainSeconds;
} }

View File

@ -0,0 +1,116 @@
package com.red.circle.other.app.dto.clientobject.user.relation.cp;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.red.circle.framework.dto.ClientObject;
import java.io.Serial;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* CP rights config.
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class CpRightsConfigCO extends ClientObject {
@Serial
private static final long serialVersionUID = 1L;
/**
* Relationship type: CP/BROTHER/SISTERS.
*/
private String relationType;
/**
* Relationship user id.
*/
@JsonSerialize(using = ToStringSerializer.class)
private Long cpUserId;
/**
* NORMAL/DISMISSING/NONE.
*/
private String relationshipStatus;
/**
* Current intimacy value.
*/
private Long intimacyValue;
/**
* Level rights config.
*/
private List<LevelCO> levels;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public static class LevelCO {
/**
* Level number.
*/
private Integer level;
/**
* Level display name.
*/
private String levelName;
/**
* Required intimacy value.
*/
private Long requiredIntimacyValue;
/**
* Whether current relationship has unlocked this level.
*/
private Boolean unlocked;
/**
* Rights under this level.
*/
private List<RightCO> rights;
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public static class RightCO {
/**
* Stable right key.
*/
private String rightKey;
/**
* Right icon.
*/
private String icon;
/**
* Right title.
*/
private String title;
/**
* Right description.
*/
private String desc;
/**
* Whether current relationship has unlocked this right.
*/
private Boolean unlocked;
}
}

View File

@ -26,6 +26,11 @@ public class CpUserProfileCO extends ClientObject {
*/ */
private UserProfileDTO userProfile; private UserProfileDTO userProfile;
/**
* 关系类型CP/BROTHER/SISTERS.
*/
private String relationType;
/** /**
* 组建天数. * 组建天数.
*/ */

View File

@ -26,6 +26,10 @@ public class CpApplyCmd extends AppExtCommand {
@NotNull(message = "acceptApplyUserId required.") @NotNull(message = "acceptApplyUserId required.")
private Long acceptApplyUserId; private Long acceptApplyUserId;
/**
* 关系类型CP/BROTHER/SISTERS默认 CP.
*/
private String relationType;
public String getAcceptApplyUserIdString() { public String getAcceptApplyUserIdString() {
return getAcceptApplyUserId().toString(); return getAcceptApplyUserId().toString();

View File

@ -25,4 +25,9 @@ public class CpApplyDismissCmd extends AppExtCommand {
@NotNull @NotNull
private Long cpUserId; private Long cpUserId;
/**
* 关系类型CP/BROTHER/SISTERS默认 CP.
*/
private String relationType;
} }

View File

@ -0,0 +1,18 @@
package com.red.circle.other.app.dto.cmd.user.relation.cp;
import com.red.circle.common.business.dto.cmd.UserIdCmd;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* CP apply id query.
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class CpApplyIdQueryCmd extends UserIdCmd {
/**
* 关系类型CP/BROTHER/SISTERS默认 CP.
*/
private String relationType;
}

View File

@ -0,0 +1,20 @@
package com.red.circle.other.app.dto.cmd.user.relation.cp;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* CP relationship query.
*/
@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
public class CpRelationshipQueryCmd extends AppExtCommand {
/**
* 关系类型CP/BROTHER/SISTERS默认 CP.
*/
private String relationType;
}

View File

@ -0,0 +1,26 @@
package com.red.circle.other.app.dto.cmd.user.relation.cp;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.red.circle.framework.core.dto.AppCommand;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* CP rights config query.
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class CpRightsConfigQueryCmd extends AppCommand {
/**
* Relationship type: CP/BROTHER/SISTERS, defaults to CP.
*/
private String relationType;
/**
* Optional relationship user id. If absent, only config can be returned safely.
*/
@JsonSerialize(using = ToStringSerializer.class)
private Long cpUserId;
}

View File

@ -29,4 +29,9 @@ public class UserCpLightCmd extends AppCommand {
@NotNull(message = "type required.") @NotNull(message = "type required.")
private String type; private String type;
/**
* 关系类型CP/BROTHER/SISTERS默认 CP.
*/
private String relationType;
} }

View File

@ -21,4 +21,9 @@ public class UserCpBlessRecordQueryCmd extends AppCommand {
* 最后一条记录id. * 最后一条记录id.
*/ */
private Long lastId; private Long lastId;
/**
* 关系类型CP/BROTHER/SISTERS默认 CP.
*/
private String relationType;
} }

View File

@ -0,0 +1,18 @@
package com.red.circle.other.app.dto.cmd.user.user;
import com.red.circle.common.business.dto.cmd.UserIdCommonCmd;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* CP cabin query.
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class UserCpCabinQueryCmd extends UserIdCommonCmd {
/**
* 关系类型CP/BROTHER/SISTERS默认 CP.
*/
private String relationType;
}

View File

@ -1,13 +1,14 @@
package com.red.circle.other.app.service.user.relation; package com.red.circle.other.app.service.user.relation;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.common.business.dto.cmd.UserIdCmd; import com.red.circle.common.business.dto.cmd.UserIdCmd;
import com.red.circle.common.business.dto.cmd.UserIdCommonCmd; import com.red.circle.common.business.dto.cmd.UserIdCommonCmd;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpCabinUserProfileCO; import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpCabinUserProfileCO;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpPairUserProfileCO; import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpPairUserProfileCO;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpUserProfileCO; import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpUserProfileCO;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyIdQueryCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyDismissCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyDismissCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpRelationshipQueryCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.ProcessApplyCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.ProcessApplyCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.loveletter.SendLoveLetterCmd; import com.red.circle.other.app.dto.cmd.user.relation.cp.loveletter.SendLoveLetterCmd;
@ -22,7 +23,7 @@ public interface UserCpRelationService {
CpUserProfileCO getCpUser(UserIdCmd cmd); CpUserProfileCO getCpUser(UserIdCmd cmd);
List<CpPairUserProfileCO> getCpPairUserProfileCO(AppExtCommand cmd); List<CpPairUserProfileCO> getCpPairUserProfileCO(CpRelationshipQueryCmd cmd);
void sendApply(CpApplyCmd cmd); void sendApply(CpApplyCmd cmd);
@ -30,7 +31,7 @@ public interface UserCpRelationService {
void dismissApply(CpApplyDismissCmd cmd); void dismissApply(CpApplyDismissCmd cmd);
String getCpApplyId(UserIdCmd cmd); String getCpApplyId(CpApplyIdQueryCmd cmd);
CpCabinUserProfileCO getCpUserV4(UserIdCommonCmd cmd); CpCabinUserProfileCO getCpUserV4(UserIdCommonCmd cmd);

View File

@ -1,12 +1,14 @@
package com.red.circle.other.app.service.user.user; package com.red.circle.other.app.service.user.user;
import com.red.circle.common.business.dto.cmd.UserIdCommonCmd;
import com.red.circle.other.app.dto.clientobject.user.user.CpBlessRecordCO; import com.red.circle.other.app.dto.clientobject.user.user.CpBlessRecordCO;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpRightsConfigCO;
import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinCO; import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinCO;
import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinUnreadCO; import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinUnreadCO;
import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinValueCO; import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinValueCO;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpRightsConfigQueryCmd;
import com.red.circle.other.app.dto.cmd.user.user.UserCpBlessRecordQueryCmd; import com.red.circle.other.app.dto.cmd.user.user.UserCpBlessRecordQueryCmd;
import com.red.circle.other.app.dto.cmd.user.user.UserCpCabinQueryCmd;
import java.util.List; import java.util.List;
/** /**
@ -15,11 +17,13 @@ import java.util.List;
*/ */
public interface UserCpCabinService { public interface UserCpCabinService {
UserCpCabinCO getCpCabinInfo(UserIdCommonCmd cmd); UserCpCabinCO getCpCabinInfo(UserCpCabinQueryCmd cmd);
UserCpCabinValueCO getCpCabinValue(UserIdCommonCmd cmd); UserCpCabinValueCO getCpCabinValue(UserCpCabinQueryCmd cmd);
UserCpCabinUnreadCO getCpBlessRecordAndUpRead(UserIdCommonCmd cmd); UserCpCabinUnreadCO getCpBlessRecordAndUpRead(UserCpCabinQueryCmd cmd);
List<CpBlessRecordCO> pageCpBlessRecord(UserCpBlessRecordQueryCmd cmd); List<CpBlessRecordCO> pageCpBlessRecord(UserCpBlessRecordQueryCmd cmd);
CpRightsConfigCO getCpRightsConfig(CpRightsConfigQueryCmd cmd);
} }

View File

@ -9,6 +9,7 @@ import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship;
import com.red.circle.other.infra.database.rds.service.user.user.BaseInfoService; import com.red.circle.other.infra.database.rds.service.user.user.BaseInfoService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService; import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.database.rds.service.user.user.CpValueService; import com.red.circle.other.infra.database.rds.service.user.user.CpValueService;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import com.red.circle.other.inner.model.dto.user.CpSimpleUserProfileCO; import com.red.circle.other.inner.model.dto.user.CpSimpleUserProfileCO;
import com.red.circle.tool.core.collection.CollectionUtils; import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.DateUtils; import com.red.circle.tool.core.date.DateUtils;
@ -80,7 +81,7 @@ public class CpRelationshipCacheServiceImpl implements CpRelationshipCacheServic
} }
BigDecimal cpValue = cpValueMap.getOrDefault(cpRelationship.getCpValId(), BigDecimal.ZERO); BigDecimal cpValue = cpValueMap.getOrDefault(cpRelationship.getCpValId(), BigDecimal.ZERO);
Long days = DateUtils.toDurationDays(cpRelationship.getCreateTime(), DateUtils.now()); Long days = relationshipDays(cpRelationship.getCreateTime());
String firstDay = cpRelationship.getCreateTime().toInstant() String firstDay = cpRelationship.getCreateTime().toInstant()
.atZone(ZoneId.systemDefault()).toLocalDate().toString(); .atZone(ZoneId.systemDefault()).toLocalDate().toString();
@ -89,6 +90,7 @@ public class CpRelationshipCacheServiceImpl implements CpRelationshipCacheServic
.setMeAccount(baseInfo.getAccount()) .setMeAccount(baseInfo.getAccount())
.setMeUserAvatar(baseInfo.getUserAvatar()) .setMeUserAvatar(baseInfo.getUserAvatar())
.setMeUserNickname(baseInfo.getUserNickname()) .setMeUserNickname(baseInfo.getUserNickname())
.setRelationType(CpRelationshipType.normalize(cpRelationship.getRelationType()))
.setCpUserId(cpUser.getId()) .setCpUserId(cpUser.getId())
.setCpAccount(cpUser.getAccount()) .setCpAccount(cpUser.getAccount())
.setCpUserAvatar(cpUser.getUserAvatar()) .setCpUserAvatar(cpUser.getUserAvatar())
@ -117,6 +119,14 @@ public class CpRelationshipCacheServiceImpl implements CpRelationshipCacheServic
return UserKey.CP.getKey(userId); return UserKey.CP.getKey(userId);
} }
private static long relationshipDays(Date createTime) {
Date now = DateUtils.now();
if (!createTime.before(now)) {
return 0L;
}
return DateUtils.toDurationDays(createTime, now);
}
@Override @Override
public void remove(List<Long> userIds) { public void remove(List<Long> userIds) {
userIds.forEach(userId -> { userIds.forEach(userId -> {

View File

@ -46,6 +46,12 @@ public class CpApply extends TimestampBaseEntity {
@TableField("accept_apply_user_id") @TableField("accept_apply_user_id")
private Long acceptApplyUserId; private Long acceptApplyUserId;
/**
* 关系类型CP/BROTHER/SISTERS.
*/
@TableField("relation_type")
private String relationType;
/** /**
* 申请消费金币. * 申请消费金币.
*/ */

View File

@ -58,6 +58,12 @@ public class CpRelationship extends TimestampBaseEntity {
@TableField("cp_user_id") @TableField("cp_user_id")
private Long cpUserId; private Long cpUserId;
/**
* 关系类型CP/BROTHER/SISTERS.
*/
@TableField("relation_type")
private String relationType;
/** /**
* 0.发起人 1.接收人 * 0.发起人 1.接收人
*/ */

View File

@ -23,6 +23,11 @@ public interface CpApplyService extends BaseService<CpApply> {
*/ */
void dismiss(Long requestUserId); void dismiss(Long requestUserId);
/**
* 解散指定类型关系申请.
*/
void dismiss(Long requestUserId, String relationType);
/** /**
* 获取申请记录. * 获取申请记录.
* *
@ -32,6 +37,11 @@ public interface CpApplyService extends BaseService<CpApply> {
*/ */
Long getId(Long acceptApplyUserId, Long sendApplyUserId); Long getId(Long acceptApplyUserId, Long sendApplyUserId);
/**
* 获取指定类型申请记录.
*/
Long getId(Long acceptApplyUserId, Long sendApplyUserId, String relationType);
/** /**
* 申请记录是否存在. * 申请记录是否存在.
* *
@ -41,6 +51,11 @@ public interface CpApplyService extends BaseService<CpApply> {
*/ */
boolean exists(Long acceptApplyUserId, Long sendApplyUserId); boolean exists(Long acceptApplyUserId, Long sendApplyUserId);
/**
* 指定类型申请记录是否存在.
*/
boolean exists(Long acceptApplyUserId, Long sendApplyUserId, String relationType);
/** /**
* 是否存在发送记录. * 是否存在发送记录.
* *
@ -49,6 +64,11 @@ public interface CpApplyService extends BaseService<CpApply> {
*/ */
boolean existsNotProcessSendApply(Long sendApplyUserId); boolean existsNotProcessSendApply(Long sendApplyUserId);
/**
* 是否存在指定类型发送记录.
*/
boolean existsNotProcessSendApply(Long sendApplyUserId, String relationType);
/** /**
* 改变状态同意. * 改变状态同意.
* *
@ -65,6 +85,11 @@ public interface CpApplyService extends BaseService<CpApply> {
*/ */
void refuseStatusWait(Long acceptApplyUserId); void refuseStatusWait(Long acceptApplyUserId);
/**
* 拒绝指定类型所有等待状态.
*/
void refuseStatusWait(Long acceptApplyUserId, String relationType);
/** /**
* 获取我拒绝都信息. * 获取我拒绝都信息.
*/ */

View File

@ -31,11 +31,21 @@ public interface CpRelationshipService extends BaseService<CpRelationship> {
*/ */
boolean existsCp(Long userId, Long cpUserId); boolean existsCp(Long userId, Long cpUserId);
/**
* 是否存在指定类型关系.
*/
boolean existsCp(Long userId, Long cpUserId, String relationType);
/** /**
* 获取分手中的cp信息集合 * 获取分手中的cp信息集合
*/ */
List<CpRelationship> getDismissingByUserId(Long userId); List<CpRelationship> getDismissingByUserId(Long userId);
/**
* 获取指定类型分手中的cp信息集合.
*/
List<CpRelationship> getDismissingByUserId(Long userId, String relationType);
/** /**
* 获取cp用户id. * 获取cp用户id.
* *
@ -49,11 +59,21 @@ public interface CpRelationshipService extends BaseService<CpRelationship> {
*/ */
List<CpRelationship> getByUserId(Long userId); List<CpRelationship> getByUserId(Long userId);
/**
* 获取指定类型cp信息集合.
*/
List<CpRelationship> getByUserId(Long userId, String relationType);
/** /**
* 获取cp信息. * 获取cp信息.
*/ */
CpRelationship getByUserId(Long userId, Long cpUserId); CpRelationship getByUserId(Long userId, Long cpUserId);
/**
* 获取指定类型cp信息.
*/
CpRelationship getByUserId(Long userId, Long cpUserId, String relationType);
/** /**
* 获取cpValId * 获取cpValId
* *
@ -77,6 +97,12 @@ public interface CpRelationshipService extends BaseService<CpRelationship> {
*/ */
void addCp(Long sendApplyUserId, Long acceptApplyUserId, Long bindCpValId, String sysOrigin); void addCp(Long sendApplyUserId, Long acceptApplyUserId, Long bindCpValId, String sysOrigin);
/**
* 组建指定类型关系.
*/
void addCp(Long sendApplyUserId, Long acceptApplyUserId, Long bindCpValId, String sysOrigin,
String relationType);
/** /**
* 获取cp信息. * 获取cp信息.
* *
@ -92,6 +118,11 @@ public interface CpRelationshipService extends BaseService<CpRelationship> {
*/ */
CpRelationship getByUserIdOrCpUserId(Long userId); CpRelationship getByUserIdOrCpUserId(Long userId);
/**
* 按关系类型获取任一用户关联关系.
*/
CpRelationship getByUserIdOrCpUserId(Long userId, String relationType);
/** /**
* 获取用户正常CP数量. * 获取用户正常CP数量.
* *
@ -109,6 +140,11 @@ public interface CpRelationshipService extends BaseService<CpRelationship> {
*/ */
CpRelationship getDismissingCp(Long userId, Long cpUserId); CpRelationship getDismissingCp(Long userId, Long cpUserId);
/**
* 获取指定类型分手中的关系.
*/
CpRelationship getDismissingCp(Long userId, Long cpUserId, String relationType);
/** /**
* 更新CP关系为分手中. * 更新CP关系为分手中.
* *
@ -116,6 +152,11 @@ public interface CpRelationshipService extends BaseService<CpRelationship> {
*/ */
void updateToDismissing(Long userId, Long cpUserId); void updateToDismissing(Long userId, Long cpUserId);
/**
* 更新指定类型关系为分手中.
*/
void updateToDismissing(Long userId, Long cpUserId, String relationType);
/** /**
* 复合CP更新为正常状态. * 复合CP更新为正常状态.
* *
@ -124,6 +165,11 @@ public interface CpRelationshipService extends BaseService<CpRelationship> {
*/ */
void reconcile(Long userId, Long cpUserId); void reconcile(Long userId, Long cpUserId);
/**
* 复合指定类型关系.
*/
void reconcile(Long userId, Long cpUserId, String relationType);
/** /**
* 获取7天前分手中的CP关系列表. * 获取7天前分手中的CP关系列表.
* *

View File

@ -9,6 +9,7 @@ import com.red.circle.other.infra.database.rds.dao.user.user.CpApplyDAO;
import com.red.circle.other.infra.database.rds.entity.user.user.CpApply; import com.red.circle.other.infra.database.rds.entity.user.user.CpApply;
import com.red.circle.other.infra.database.rds.service.user.user.CpApplyService; import com.red.circle.other.infra.database.rds.service.user.user.CpApplyService;
import com.red.circle.other.infra.enums.user.user.CpApplyStatus; import com.red.circle.other.infra.enums.user.user.CpApplyStatus;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import com.red.circle.other.inner.model.cmd.user.CpApplyQryCmd; import com.red.circle.other.inner.model.cmd.user.CpApplyQryCmd;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
@ -30,10 +31,16 @@ public class CpApplyServiceImpl extends BaseServiceImpl<CpApplyDAO, CpApply> imp
@Override @Override
public void dismiss(Long requestUserId) { public void dismiss(Long requestUserId) {
dismiss(requestUserId, CpRelationshipType.CP.name());
}
@Override
public void dismiss(Long requestUserId, String relationType) {
update() update()
.set(CpApply::getStatus, CpApplyStatus.DISMISS) .set(CpApply::getStatus, CpApplyStatus.DISMISS)
.set(CpApply::getUpdateTime, LocalDateTime.now()) .set(CpApply::getUpdateTime, LocalDateTime.now())
.set(CpApply::getUpdateUser, requestUserId) .set(CpApply::getUpdateUser, requestUserId)
.eq(CpApply::getRelationType, CpRelationshipType.normalize(relationType))
.eq(CpApply::getStatus, CpApplyStatus.AGREE) .eq(CpApply::getStatus, CpApplyStatus.AGREE)
.and(where -> where.eq(CpApply::getSendApplyUserId, requestUserId) .and(where -> where.eq(CpApply::getSendApplyUserId, requestUserId)
.or().eq(CpApply::getAcceptApplyUserId, requestUserId)) .or().eq(CpApply::getAcceptApplyUserId, requestUserId))
@ -43,10 +50,16 @@ public class CpApplyServiceImpl extends BaseServiceImpl<CpApplyDAO, CpApply> imp
@Override @Override
public Long getId(Long acceptApplyUserId, Long sendApplyUserId) { public Long getId(Long acceptApplyUserId, Long sendApplyUserId) {
return getId(acceptApplyUserId, sendApplyUserId, CpRelationshipType.CP.name());
}
@Override
public Long getId(Long acceptApplyUserId, Long sendApplyUserId, String relationType) {
return Optional.ofNullable( return Optional.ofNullable(
query() query()
.select(CpApply::getId) .select(CpApply::getId)
.eq(CpApply::getStatus, CpApplyStatus.WAIT) .eq(CpApply::getStatus, CpApplyStatus.WAIT)
.eq(CpApply::getRelationType, CpRelationshipType.normalize(relationType))
.eq(CpApply::getAcceptApplyUserId, acceptApplyUserId) .eq(CpApply::getAcceptApplyUserId, acceptApplyUserId)
.eq(CpApply::getSendApplyUserId, sendApplyUserId) .eq(CpApply::getSendApplyUserId, sendApplyUserId)
.last(PageConstant.LIMIT_ONE) .last(PageConstant.LIMIT_ONE)
@ -56,14 +69,25 @@ public class CpApplyServiceImpl extends BaseServiceImpl<CpApplyDAO, CpApply> imp
@Override @Override
public boolean exists(Long acceptApplyUserId, Long sendApplyUserId) { public boolean exists(Long acceptApplyUserId, Long sendApplyUserId) {
return Optional.ofNullable(getId(acceptApplyUserId, sendApplyUserId)).isPresent(); return exists(acceptApplyUserId, sendApplyUserId, CpRelationshipType.CP.name());
}
@Override
public boolean exists(Long acceptApplyUserId, Long sendApplyUserId, String relationType) {
return Optional.ofNullable(getId(acceptApplyUserId, sendApplyUserId, relationType)).isPresent();
} }
@Override @Override
public boolean existsNotProcessSendApply(Long sendApplyUserId) { public boolean existsNotProcessSendApply(Long sendApplyUserId) {
return existsNotProcessSendApply(sendApplyUserId, CpRelationshipType.CP.name());
}
@Override
public boolean existsNotProcessSendApply(Long sendApplyUserId, String relationType) {
return Optional.ofNullable(query() return Optional.ofNullable(query()
.select(CpApply::getId) .select(CpApply::getId)
.eq(CpApply::getSendApplyUserId, sendApplyUserId) .eq(CpApply::getSendApplyUserId, sendApplyUserId)
.eq(CpApply::getRelationType, CpRelationshipType.normalize(relationType))
.eq(CpApply::getStatus, CpApplyStatus.WAIT) .eq(CpApply::getStatus, CpApplyStatus.WAIT)
.getOne()) .getOne())
.map(cpApply -> Objects.nonNull(cpApply.getId())) .map(cpApply -> Objects.nonNull(cpApply.getId()))
@ -80,9 +104,15 @@ public class CpApplyServiceImpl extends BaseServiceImpl<CpApplyDAO, CpApply> imp
@Override @Override
public void refuseStatusWait(Long acceptApplyUserId) { public void refuseStatusWait(Long acceptApplyUserId) {
refuseStatusWait(acceptApplyUserId, CpRelationshipType.CP.name());
}
@Override
public void refuseStatusWait(Long acceptApplyUserId, String relationType) {
update() update()
.set(CpApply::getStatus, CpApplyStatus.REFUSE) .set(CpApply::getStatus, CpApplyStatus.REFUSE)
.eq(CpApply::getStatus, CpApplyStatus.WAIT) .eq(CpApply::getStatus, CpApplyStatus.WAIT)
.eq(CpApply::getRelationType, CpRelationshipType.normalize(relationType))
.eq(CpApply::getAcceptApplyUserId, acceptApplyUserId) .eq(CpApply::getAcceptApplyUserId, acceptApplyUserId)
.execute(); .execute();
} }

View File

@ -10,6 +10,7 @@ import com.red.circle.other.infra.database.rds.dao.user.user.CpRelationshipDAO;
import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship; import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService; import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.enums.user.user.CpRelationshipStatus; import com.red.circle.other.infra.enums.user.user.CpRelationshipStatus;
import com.red.circle.other.infra.enums.user.user.CpRelationshipType;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.*; import java.util.*;
@ -47,9 +48,15 @@ public class CpRelationshipServiceImpl extends
@Override @Override
public boolean existsCp(Long userId, Long cpUserId) { public boolean existsCp(Long userId, Long cpUserId) {
return existsCp(userId, cpUserId, CpRelationshipType.CP.name());
}
@Override
public boolean existsCp(Long userId, Long cpUserId, String relationType) {
return Optional.ofNullable( return Optional.ofNullable(
query().select(CpRelationship::getId) query().select(CpRelationship::getId)
.eq(CpRelationship::getStatus, CpRelationshipStatus.NORMAL.name()) .eq(CpRelationship::getStatus, CpRelationshipStatus.NORMAL.name())
.eq(CpRelationship::getRelationType, CpRelationshipType.normalize(relationType))
.and(where -> where .and(where -> where
.nested(w -> w.eq(CpRelationship::getUserId, userId).eq(CpRelationship::getCpUserId, cpUserId)) .nested(w -> w.eq(CpRelationship::getUserId, userId).eq(CpRelationship::getCpUserId, cpUserId))
.or() .or()
@ -62,9 +69,15 @@ public class CpRelationshipServiceImpl extends
@Override @Override
public List<CpRelationship> getDismissingByUserId(Long userId) { public List<CpRelationship> getDismissingByUserId(Long userId) {
return getDismissingByUserId(userId, CpRelationshipType.CP.name());
}
@Override
public List<CpRelationship> getDismissingByUserId(Long userId, String relationType) {
return query() return query()
.eq(CpRelationship::getUserId, userId) .eq(CpRelationship::getUserId, userId)
.eq(CpRelationship::getStatus, CpRelationshipStatus.DISMISSING.name()) .eq(CpRelationship::getStatus, CpRelationshipStatus.DISMISSING.name())
.eq(CpRelationship::getRelationType, CpRelationshipType.normalize(relationType))
.list(); .list();
} }
@ -72,6 +85,7 @@ public class CpRelationshipServiceImpl extends
public List<Long> getCpUserId(Long userId) { public List<Long> getCpUserId(Long userId) {
return query().select(CpRelationship::getCpUserId, TimestampBaseEntity::getCreateTime) return query().select(CpRelationship::getCpUserId, TimestampBaseEntity::getCreateTime)
.eq(CpRelationship::getUserId, userId) .eq(CpRelationship::getUserId, userId)
.eq(CpRelationship::getRelationType, CpRelationshipType.CP.name())
.list() .list()
.stream() .stream()
.sorted(Comparator.comparing(CpRelationship::getCreateTime).reversed()) .sorted(Comparator.comparing(CpRelationship::getCreateTime).reversed())
@ -81,17 +95,30 @@ public class CpRelationshipServiceImpl extends
@Override @Override
public List<CpRelationship> getByUserId(Long userId) { public List<CpRelationship> getByUserId(Long userId) {
return getByUserId(userId, CpRelationshipType.CP.name());
}
@Override
public List<CpRelationship> getByUserId(Long userId, String relationType) {
return query() return query()
.eq(CpRelationship::getUserId, userId) .eq(CpRelationship::getUserId, userId)
.eq(CpRelationship::getStatus, CpRelationshipStatus.NORMAL.name()) .eq(CpRelationship::getStatus, CpRelationshipStatus.NORMAL.name())
.eq(Objects.nonNull(relationType), CpRelationship::getRelationType,
Objects.nonNull(relationType) ? CpRelationshipType.normalize(relationType) : null)
.orderByAsc(TimestampBaseEntity::getCreateTime) .orderByAsc(TimestampBaseEntity::getCreateTime)
.list(); .list();
} }
@Override @Override
public CpRelationship getByUserId(Long userId, Long cpUserId) { public CpRelationship getByUserId(Long userId, Long cpUserId) {
return getByUserId(userId, cpUserId, CpRelationshipType.CP.name());
}
@Override
public CpRelationship getByUserId(Long userId, Long cpUserId, String relationType) {
return query() return query()
.eq(CpRelationship::getStatus, CpRelationshipStatus.NORMAL.name()) .eq(CpRelationship::getStatus, CpRelationshipStatus.NORMAL.name())
.eq(CpRelationship::getRelationType, CpRelationshipType.normalize(relationType))
.and(where -> where .and(where -> where
.nested(w -> w.eq(CpRelationship::getUserId, userId).eq(CpRelationship::getCpUserId, cpUserId)) .nested(w -> w.eq(CpRelationship::getUserId, userId).eq(CpRelationship::getCpUserId, cpUserId))
.or() .or()
@ -119,10 +146,16 @@ public class CpRelationshipServiceImpl extends
@Override @Override
public void addCp(Long sendApplyUserId, Long acceptApplyUserId, Long bindCpValId, public void addCp(Long sendApplyUserId, Long acceptApplyUserId, Long bindCpValId,
String sysOrigin) { String sysOrigin) {
addCp(sendApplyUserId, acceptApplyUserId, bindCpValId, sysOrigin, CpRelationshipType.CP.name());
}
@Override
public void addCp(Long sendApplyUserId, Long acceptApplyUserId, Long bindCpValId,
String sysOrigin, String relationType) {
CpRelationship sendUser = createCpRelationshipBean(sendApplyUserId, acceptApplyUserId, CpRelationship sendUser = createCpRelationshipBean(sendApplyUserId, acceptApplyUserId,
bindCpValId, 0, sysOrigin); bindCpValId, 0, sysOrigin, relationType);
CpRelationship cpUser = createCpRelationshipBean(acceptApplyUserId, sendApplyUserId, CpRelationship cpUser = createCpRelationshipBean(acceptApplyUserId, sendApplyUserId,
bindCpValId, 1, sysOrigin); bindCpValId, 1, sysOrigin, relationType);
saveBatch(Arrays.asList(sendUser, cpUser)); saveBatch(Arrays.asList(sendUser, cpUser));
} }
@ -136,7 +169,14 @@ public class CpRelationshipServiceImpl extends
@Override @Override
public CpRelationship getByUserIdOrCpUserId(Long userId) { public CpRelationship getByUserIdOrCpUserId(Long userId) {
return getByUserIdOrCpUserId(userId, CpRelationshipType.CP.name());
}
@Override
public CpRelationship getByUserIdOrCpUserId(Long userId, String relationType) {
return Optional.ofNullable(query() return Optional.ofNullable(query()
.eq(Objects.nonNull(relationType), CpRelationship::getRelationType,
Objects.nonNull(relationType) ? CpRelationshipType.normalize(relationType) : null)
.and(where -> where.eq(CpRelationship::getUserId, userId) .and(where -> where.eq(CpRelationship::getUserId, userId)
.or().eq(CpRelationship::getCpUserId, userId)) .or().eq(CpRelationship::getCpUserId, userId))
.last(PageConstant.LIMIT_ONE) .last(PageConstant.LIMIT_ONE)
@ -145,11 +185,12 @@ public class CpRelationshipServiceImpl extends
} }
private CpRelationship createCpRelationshipBean(Long userId, Long cpUserId, Long bindCpValId, private CpRelationship createCpRelationshipBean(Long userId, Long cpUserId, Long bindCpValId,
Integer initiate, String sysOrigin) { Integer initiate, String sysOrigin, String relationType) {
CpRelationship cpUser = new CpRelationship() CpRelationship cpUser = new CpRelationship()
.setUserId(userId) .setUserId(userId)
.setCpUserId(cpUserId) .setCpUserId(cpUserId)
.setCpValId(bindCpValId) .setCpValId(bindCpValId)
.setRelationType(CpRelationshipType.normalize(relationType))
.setInitiate(initiate) .setInitiate(initiate)
.setSysOrigin(sysOrigin) .setSysOrigin(sysOrigin)
.setAmount(BigDecimal.ZERO) .setAmount(BigDecimal.ZERO)
@ -169,6 +210,11 @@ public class CpRelationshipServiceImpl extends
@Override @Override
public CpRelationship getDismissingCp(Long userId, Long cpUserId) { public CpRelationship getDismissingCp(Long userId, Long cpUserId) {
return getDismissingCp(userId, cpUserId, CpRelationshipType.CP.name());
}
@Override
public CpRelationship getDismissingCp(Long userId, Long cpUserId, String relationType) {
return query() return query()
.and(where -> where .and(where -> where
.nested(w -> w.eq(CpRelationship::getUserId, userId).eq(CpRelationship::getCpUserId, cpUserId)) .nested(w -> w.eq(CpRelationship::getUserId, userId).eq(CpRelationship::getCpUserId, cpUserId))
@ -176,16 +222,23 @@ public class CpRelationshipServiceImpl extends
.nested(w -> w.eq(CpRelationship::getUserId, cpUserId).eq(CpRelationship::getCpUserId, userId)) .nested(w -> w.eq(CpRelationship::getUserId, cpUserId).eq(CpRelationship::getCpUserId, userId))
) )
.eq(CpRelationship::getStatus, CpRelationshipStatus.DISMISSING.name()) .eq(CpRelationship::getStatus, CpRelationshipStatus.DISMISSING.name())
.eq(CpRelationship::getRelationType, CpRelationshipType.normalize(relationType))
.last(PageConstant.LIMIT_ONE) .last(PageConstant.LIMIT_ONE)
.getOne(); .getOne();
} }
@Override @Override
public void updateToDismissing(Long userId, Long cpUserId) { public void updateToDismissing(Long userId, Long cpUserId) {
updateToDismissing(userId, cpUserId, CpRelationshipType.CP.name());
}
@Override
public void updateToDismissing(Long userId, Long cpUserId, String relationType) {
update() update()
.set(CpRelationship::getStatus, CpRelationshipStatus.DISMISSING.name()) .set(CpRelationship::getStatus, CpRelationshipStatus.DISMISSING.name())
.set(CpRelationship::getDismissTime, TimestampUtils.now().getTime()) .set(CpRelationship::getDismissTime, TimestampUtils.now().getTime())
.set(CpRelationship::getUpdateTime, TimestampUtils.now()) .set(CpRelationship::getUpdateTime, TimestampUtils.now())
.eq(CpRelationship::getRelationType, CpRelationshipType.normalize(relationType))
.and(where -> where .and(where -> where
.nested(w -> w.eq(CpRelationship::getUserId, userId).eq(CpRelationship::getCpUserId, cpUserId)) .nested(w -> w.eq(CpRelationship::getUserId, userId).eq(CpRelationship::getCpUserId, cpUserId))
.or() .or()
@ -197,10 +250,16 @@ public class CpRelationshipServiceImpl extends
@Override @Override
public void reconcile(Long userId, Long cpUserId) { public void reconcile(Long userId, Long cpUserId) {
reconcile(userId, cpUserId, CpRelationshipType.CP.name());
}
@Override
public void reconcile(Long userId, Long cpUserId, String relationType) {
update() update()
.set(CpRelationship::getStatus, CpRelationshipStatus.NORMAL.name()) .set(CpRelationship::getStatus, CpRelationshipStatus.NORMAL.name())
.set(CpRelationship::getDismissTime, null) .set(CpRelationship::getDismissTime, null)
.set(CpRelationship::getUpdateTime, TimestampUtils.now()) .set(CpRelationship::getUpdateTime, TimestampUtils.now())
.eq(CpRelationship::getRelationType, CpRelationshipType.normalize(relationType))
.and(where -> where .and(where -> where
.nested(w -> w.eq(CpRelationship::getUserId, userId).eq(CpRelationship::getCpUserId, cpUserId)) .nested(w -> w.eq(CpRelationship::getUserId, userId).eq(CpRelationship::getCpUserId, cpUserId))
.or() .or()

View File

@ -0,0 +1,63 @@
package com.red.circle.other.infra.enums.user.user;
import java.util.Locale;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
/**
* CP family relationship type.
*/
public enum CpRelationshipType {
/**
* Couple, requires different genders.
*/
CP,
/**
* Brothers, requires both users to be male.
*/
BROTHER,
/**
* Sisters, requires both users to be female.
*/
SISTERS;
private static final int FEMALE = 0;
private static final int MALE = 1;
public static CpRelationshipType of(String value) {
if (StringUtils.isBlank(value)) {
return CP;
}
String normalized = value.trim().toUpperCase(Locale.ROOT);
if (Objects.equals(normalized, "BROTHERS")) {
return BROTHER;
}
if (Objects.equals(normalized, "SISTER")) {
return SISTERS;
}
return CpRelationshipType.valueOf(normalized);
}
public static String normalize(String value) {
return of(value).name();
}
public boolean genderMatched(Integer sendUserSex, Integer acceptUserSex) {
return switch (this) {
case CP -> !Objects.equals(sendUserSex, acceptUserSex);
case BROTHER -> Objects.equals(sendUserSex, MALE) && Objects.equals(acceptUserSex, MALE);
case SISTERS -> Objects.equals(sendUserSex, FEMALE) && Objects.equals(acceptUserSex, FEMALE);
};
}
public String applyTargetText() {
return switch (this) {
case CP -> "a couple";
case BROTHER -> "brothers";
case SISTERS -> "sisters";
};
}
}

View File

@ -11,6 +11,7 @@
FROM (SELECT DISTINCT(`cp_val_id`) vId FROM (SELECT DISTINCT(`cp_val_id`) vId
FROM `user_cp_relationship` FROM `user_cp_relationship`
WHERE `sys_origin` = #{sysOrigin} WHERE `sys_origin` = #{sysOrigin}
AND `relation_type` = 'CP'
ORDER BY id DESC ORDER BY id DESC
LIMIT #{size}) tmp) LIMIT #{size}) tmp)
</select> </select>
@ -25,6 +26,7 @@
SELECT DISTINCT(`cp_val_id`) vId SELECT DISTINCT(`cp_val_id`) vId
FROM `user_cp_relationship` FROM `user_cp_relationship`
WHERE `sys_origin`= #{sysOrigin} WHERE `sys_origin`= #{sysOrigin}
AND `relation_type` = 'CP'
<if test="excludeUserId != null and excludeUserId.size() > 0"> <if test="excludeUserId != null and excludeUserId.size() > 0">
AND user_id NOT IN AND user_id NOT IN
<foreach item="item" collection="excludeUserId" open="(" separator="," close=")"> <foreach item="item" collection="excludeUserId" open="(" separator="," close=")">

View File

@ -23,6 +23,17 @@
<artifactId>component-redis</artifactId> <artifactId>component-redis</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<!-- Apache POI for Excel processing --> <!-- Apache POI for Excel processing -->
<dependency> <dependency>
<groupId>org.apache.poi</groupId> <groupId>org.apache.poi</groupId>
@ -38,6 +49,11 @@
<build> <build>
<finalName>${parent.artifactId}-${revision}</finalName> <finalName>${parent.artifactId}-${revision}</finalName>
<testResources combine.self="override">
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>

View File

@ -0,0 +1,441 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.red.circle.OtherServiceApplication;
import com.red.circle.framework.core.dto.ReqSysOrigin;
import com.red.circle.other.app.command.user.DismissCpApplyCmdExe;
import com.red.circle.other.app.command.user.ProcessCpApplyCmd;
import com.red.circle.other.app.command.user.SendCpApplyCmdExe;
import com.red.circle.other.app.command.user.query.UserCpPairUserProfileQryExe;
import com.red.circle.other.app.command.user.query.UserCpCabinQueryExe;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpPairUserProfileCO;
import com.red.circle.other.app.dto.clientobject.user.user.UserCpCabinCO;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpApplyDismissCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.CpRelationshipQueryCmd;
import com.red.circle.other.app.dto.cmd.user.relation.cp.ProcessApplyCmd;
import com.red.circle.other.app.dto.cmd.user.user.UserCpCabinQueryCmd;
import com.red.circle.other.domain.gateway.user.ability.UserRegionGateway;
import com.red.circle.other.infra.database.cache.service.other.GiftCacheService;
import com.red.circle.other.infra.database.mongo.entity.gift.GiftAcceptUser;
import com.red.circle.other.infra.database.mongo.entity.gift.GiftGiveRunningWater;
import com.red.circle.other.infra.database.mongo.entity.gift.GiftValue;
import com.red.circle.other.infra.database.rds.entity.user.user.BaseInfo;
import com.red.circle.other.infra.database.rds.entity.user.user.CpApply;
import com.red.circle.other.infra.database.rds.entity.user.user.CpBlessRecord;
import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship;
import com.red.circle.other.infra.database.rds.service.user.user.BaseInfoService;
import com.red.circle.other.infra.database.rds.service.user.user.CpApplyService;
import com.red.circle.other.infra.database.rds.service.user.user.CpBlessRecordService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.database.rds.service.user.user.CpValueService;
import com.red.circle.other.inner.enums.material.GiftCurrencyType;
import com.red.circle.other.inner.model.dto.material.GiftConfigDTO;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.annotation.IfProfileValue;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.AopTestUtils;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@IfProfileValue(name = "cp.local.flow", value = "true")
@AutoConfigureMockMvc
@SpringBootTest(classes = OtherServiceApplication.class)
public class CpLocalFlowSmokeTest {
private static final String SYS_ORIGIN = "LIKEI";
private static final ReqSysOrigin REQ_SYS_ORIGIN = ReqSysOrigin.of(SYS_ORIGIN, SYS_ORIGIN);
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private MockMvc mockMvc;
@Autowired
private BaseInfoService baseInfoService;
@Autowired
private UserRegionGateway userRegionGateway;
@Autowired
private SendCpApplyCmdExe sendCpApplyCmdExe;
@Autowired
private ProcessCpApplyCmd processCpApplyCmd;
@Autowired
private DismissCpApplyCmdExe dismissCpApplyCmdExe;
@Autowired
private UserCpPairUserProfileQryExe pairUserProfileQryExe;
@Autowired
private UserCpCabinQueryExe userCpCabinQueryExe;
@Autowired
private CpApplyService cpApplyService;
@Autowired
private CpRelationshipService cpRelationshipService;
@Autowired
private CpValueService cpValueService;
@Autowired
private CpBlessRecordService cpBlessRecordService;
@Autowired
private GiftCacheService giftCacheService;
private final List<Long> createdApplyIds = new ArrayList<>();
private final List<Long> createdCpValIds = new ArrayList<>();
private final List<RelationPair> createdPairs = new ArrayList<>();
@Before
public void ensureSchema() {
executeIgnoreDuplicate(
"ALTER TABLE `user_cp_apply` ADD COLUMN `relation_type` varchar(32) NOT NULL DEFAULT 'CP' "
+ "COMMENT '关系类型CP/BROTHER/SISTERS' AFTER `accept_apply_user_id`");
executeIgnoreDuplicate(
"ALTER TABLE `user_cp_relationship` ADD COLUMN `relation_type` varchar(32) NOT NULL DEFAULT 'CP' "
+ "COMMENT '关系类型CP/BROTHER/SISTERS' AFTER `cp_user_id`");
jdbcTemplate.update("UPDATE `user_cp_apply` SET `relation_type` = 'CP' "
+ "WHERE `relation_type` IS NULL OR `relation_type` = ''");
jdbcTemplate.update("UPDATE `user_cp_relationship` SET `relation_type` = 'CP' "
+ "WHERE `relation_type` IS NULL OR `relation_type` = ''");
}
@After
public void cleanup() {
for (RelationPair pair : createdPairs) {
cpRelationshipService.remove(new LambdaQueryWrapper<CpRelationship>()
.eq(CpRelationship::getRelationType, pair.relationType)
.and(where -> where
.nested(w -> w.eq(CpRelationship::getUserId, pair.userId)
.eq(CpRelationship::getCpUserId, pair.cpUserId))
.or()
.nested(w -> w.eq(CpRelationship::getUserId, pair.cpUserId)
.eq(CpRelationship::getCpUserId, pair.userId))));
}
for (Long cpValId : createdCpValIds) {
cpBlessRecordService.deleteByCpValId(cpValId);
cpValueService.deleteById(cpValId);
}
if (!createdApplyIds.isEmpty()) {
cpApplyService.removeByIds(createdApplyIds);
}
}
@Test
public void walkThroughCpBrotherAndSistersFlowsWithLocalData() throws Exception {
List<BaseInfo> candidates = baseInfoService.query()
.select(BaseInfo::getId, BaseInfo::getUserSex, BaseInfo::getOriginSys,
BaseInfo::getAccount, BaseInfo::getUserNickname, BaseInfo::getCountryCode)
.eq(BaseInfo::getOriginSys, SYS_ORIGIN)
.in(BaseInfo::getUserSex, Arrays.asList(0, 1))
.orderByDesc(BaseInfo::getId)
.last("LIMIT 500")
.list();
assertFalse("local LIKEI candidates should not be empty", candidates.isEmpty());
UserPair cpPair = findPair(candidates, 1, 0, "CP");
runCpGiftApplyBlessDismissFlow(cpPair);
UserPair brotherPair = findPair(candidates, 1, 1, "BROTHER");
runNoChargeApplyAndAgreeFlow(brotherPair, "BROTHER");
UserPair sistersPair = findPair(candidates, 0, 0, "SISTERS");
runNoChargeApplyAndAgreeFlow(sistersPair, "SISTERS");
}
@Test
public void cpCabinReturnsEmptyStateWhenUserHasNoRelationship() throws Exception {
Long queryUserId = 2042274349343506434L;
Long reqUserId = 4569421795454615555L;
assertCpCabinEmptyState(queryUserId, reqUserId, "CP");
assertCpCabinEmptyState(queryUserId, reqUserId, "BROTHER");
assertCpCabinEmptyState(queryUserId, reqUserId, "SISTERS");
assertCpCabinRestEmptyState(queryUserId, reqUserId, "CP");
assertCpCabinRestEmptyState(queryUserId, reqUserId, "BROTHER");
assertCpCabinRestEmptyState(queryUserId, reqUserId, "SISTERS");
assertCpRightsRestConfig(queryUserId, "CP");
assertCpRightsRestConfig(queryUserId, "BROTHER");
assertCpRightsRestConfig(queryUserId, "SISTERS");
}
@Test
public void cpGiftAutoApplySkipsWhenRulesDoNotMatch() {
List<BaseInfo> candidates = baseInfoService.query()
.select(BaseInfo::getId, BaseInfo::getUserSex, BaseInfo::getOriginSys)
.eq(BaseInfo::getOriginSys, SYS_ORIGIN)
.eq(BaseInfo::getUserSex, 1)
.orderByDesc(BaseInfo::getId)
.last("LIMIT 500")
.list();
assertFalse("local LIKEI male candidates should not be empty", candidates.isEmpty());
UserPair sameGenderPair = findPair(candidates, 1, 1, "CP");
boolean created = sendCpApplyCmdExe.autoCreateFromCpGift(sameGenderPair.sendUserId,
sameGenderPair.acceptUserId, SYS_ORIGIN);
assertFalse("CP gift auto apply should skip same gender users", created);
assertNull("CP gift auto apply should not create WAIT apply when skipped",
cpApplyService.getId(sameGenderPair.acceptUserId, sameGenderPair.sendUserId, "CP"));
}
private void runCpGiftApplyBlessDismissFlow(UserPair pair) throws Exception {
boolean created = sendCpApplyCmdExe.autoCreateFromCpGift(pair.sendUserId, pair.acceptUserId,
SYS_ORIGIN);
Long pendingApplyId = cpApplyService.getId(pair.acceptUserId, pair.sendUserId, "CP");
if (pendingApplyId != null && !createdApplyIds.contains(pendingApplyId)) {
createdApplyIds.add(pendingApplyId);
}
assertTrue("CP gift should auto create CP apply", created);
Long applyId = pendingApplyId;
assertNotNull("CP auto apply id", applyId);
createdApplyIds.add(applyId);
CpApply apply = cpApplyService.getById(applyId);
assertEquals("CP", apply.getRelationType());
assertEquals(0, BigDecimal.ZERO.compareTo(apply.getApplyConsumeGold()));
agree(applyId, pair.acceptUserId);
CpRelationship relationship = cpRelationshipService.getByUserId(pair.sendUserId,
pair.acceptUserId, "CP");
assertNotNull("CP relationship", relationship);
createdPairs.add(new RelationPair(pair.sendUserId, pair.acceptUserId, "CP"));
createdCpValIds.add(relationship.getCpValId());
sendBlessGift(relationship, pair);
List<CpBlessRecord> blessRecords = cpBlessRecordService.query()
.eq(CpBlessRecord::getCpValId, relationship.getCpValId())
.list();
assertEquals("bless records for both users", 2, blessRecords.size());
CpApplyDismissCmd dismissCmd = new CpApplyDismissCmd()
.setCpUserId(pair.acceptUserId)
.setRelationType("CP");
dismissCmd.setReqUserId(pair.sendUserId);
dismissCmd.setReqSysOrigin(REQ_SYS_ORIGIN);
dismissCpApplyCmdExe.execute(dismissCmd);
CpPairUserProfileCO dismissing = findPairView(pair.sendUserId, pair.acceptUserId, "CP");
assertNotNull("CP pair after dismiss", dismissing);
assertEquals("DISMISSING", dismissing.getStatus());
assertNotNull("dismissEndTime", dismissing.getDismissEndTime());
assertNotNull("dismissRemainSeconds", dismissing.getDismissRemainSeconds());
assertTrue("dismissRemainSeconds should be positive",
dismissing.getDismissRemainSeconds() > 0);
}
private void assertCpCabinEmptyState(Long queryUserId, Long reqUserId, String relationType) {
UserCpCabinQueryCmd cmd = new UserCpCabinQueryCmd();
cmd.setUserId(queryUserId);
cmd.setReqUserId(reqUserId);
cmd.setReqSysOrigin(REQ_SYS_ORIGIN);
cmd.setRelationType(relationType);
UserCpCabinCO cabin = userCpCabinQueryExe.execute(cmd);
assertNotNull(relationType + " empty cabin", cabin);
assertEquals("0", cabin.getCpVal());
assertEquals(Long.valueOf(0L), cabin.getBlessVal());
assertNull(cabin.getCpPairUserProfileCO());
assertNotNull(cabin.getCpCabinConfigCO());
assertTrue(cabin.getCpCabinConfigCO().isEmpty());
assertNull(cabin.getCurrentCpCabinConfigCO());
assertNull(cabin.getUserCpCabinSpecial());
assertFalse(cabin.getCheckSelfCabin());
}
private void assertCpCabinRestEmptyState(Long queryUserId, Long reqUserId,
String relationType) throws Exception {
mockMvc.perform(get("/user/cp/cabin")
.param("userId", String.valueOf(queryUserId))
.param("relationType", relationType)
.header("Req-Sys-Origin", "origin=LIKEI;originChild=LIKEI;")
.header("Req-App-Intel", "version=1.0.0;build=1;channel=local;")
.header("Req-Client", "Android")
.header("Req-Inner-Internal",
"time=" + System.currentTimeMillis() + ";uid=" + reqUserId + ";"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status").value(true))
.andExpect(jsonPath("$.body.cpVal").value("0"))
.andExpect(jsonPath("$.body.blessVal").value("0"))
.andExpect(jsonPath("$.body.cpPairUserProfileCO").doesNotExist())
.andExpect(jsonPath("$.body.cpCabinConfigCO").isArray())
.andExpect(jsonPath("$.body.cpCabinConfigCO").isEmpty())
.andExpect(jsonPath("$.body.currentCpCabinConfigCO").doesNotExist())
.andExpect(jsonPath("$.body.userCpCabinSpecial").doesNotExist())
.andExpect(jsonPath("$.body.checkSelfCabin").value(false));
}
private void assertCpRightsRestConfig(Long reqUserId, String relationType) throws Exception {
mockMvc.perform(get("/user/cp/rights/config")
.param("relationType", relationType)
.header("Req-Sys-Origin", "origin=LIKEI;originChild=LIKEI;")
.header("Req-App-Intel", "version=1.0.0;build=1;channel=local;")
.header("Req-Client", "Android")
.header("Req-Inner-Internal",
"time=" + System.currentTimeMillis() + ";uid=" + reqUserId + ";"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status").value(true))
.andExpect(jsonPath("$.body.relationType").value(relationType))
.andExpect(jsonPath("$.body.relationshipStatus").exists())
.andExpect(jsonPath("$.body.intimacyValue").exists())
.andExpect(jsonPath("$.body.levels").isArray());
}
private void runNoChargeApplyAndAgreeFlow(UserPair pair, String relationType) throws Exception {
Method process = SendCpApplyCmdExe.class.getDeclaredMethod("process", Long.class, Long.class,
String.class, String.class, boolean.class);
process.setAccessible(true);
process.invoke(sendCpApplyCmdExe, pair.sendUserId, pair.acceptUserId, SYS_ORIGIN, relationType,
false);
Long applyId = cpApplyService.getId(pair.acceptUserId, pair.sendUserId, relationType);
assertNotNull(relationType + " apply id", applyId);
createdApplyIds.add(applyId);
CpApply apply = cpApplyService.getById(applyId);
assertEquals(relationType, apply.getRelationType());
assertEquals(0, BigDecimal.ZERO.compareTo(apply.getApplyConsumeGold()));
agree(applyId, pair.acceptUserId);
CpRelationship relationship = cpRelationshipService.getByUserId(pair.sendUserId,
pair.acceptUserId, relationType);
assertNotNull(relationType + " relationship", relationship);
assertEquals(relationType, relationship.getRelationType());
createdPairs.add(new RelationPair(pair.sendUserId, pair.acceptUserId, relationType));
createdCpValIds.add(relationship.getCpValId());
CpPairUserProfileCO pairView = findPairView(pair.sendUserId, pair.acceptUserId, relationType);
assertNotNull(relationType + " pair view", pairView);
assertEquals(relationType, pairView.getRelationType());
assertEquals("NORMAL", pairView.getStatus());
assertNull(pairView.getDismissEndTime());
}
private void agree(Long applyId, Long acceptUserId) {
ProcessApplyCmd cmd = new ProcessApplyCmd()
.setApplyId(applyId)
.setAgree(Boolean.TRUE);
cmd.setReqUserId(acceptUserId);
cmd.setReqSysOrigin(REQ_SYS_ORIGIN);
processCpApplyCmd.execute(cmd);
}
private void sendBlessGift(CpRelationship relationship, UserPair pair) throws Exception {
GiftConfigDTO gift = giftCacheService.listBySysOrigin(
com.red.circle.common.business.core.enums.SysOriginPlatformEnum.LIKEI)
.stream()
.filter(g -> Objects.nonNull(g.getGiftPhoto()))
.findFirst()
.orElse(null);
assertNotNull("local gift config", gift);
GiftGiveRunningWater runningWater = GiftGiveRunningWater.builder()
.id(System.currentTimeMillis())
.sysOrigin(SYS_ORIGIN)
.originId("cp-local-flow")
.dynamicContentId(null)
.userId(pair.sendUserId)
.giftId(gift.getId())
.checkBlessingsGift(Boolean.TRUE)
.acceptUsers(Lists.newArrayList(GiftAcceptUser.builder()
.acceptUserId(pair.acceptUserId)
.build()))
.giftValue(GiftValue.builder()
.currencyType(GiftCurrencyType.GOLD.name())
.giftType("CP")
.unitPrice(BigDecimal.ONE)
.quantity(1)
.userSize(1)
.giftValue(BigDecimal.ONE)
.actualAmount(BigDecimal.ONE)
.build())
.build();
Object target = AopTestUtils.getUltimateTargetObject(giftCountStrategy);
ReflectionTestUtils.invokeMethod(target, "saveBlessingsRecord", runningWater);
}
@Autowired
private com.red.circle.other.app.listener.gift.strategy.GiftCountStrategy giftCountStrategy;
private CpPairUserProfileCO findPairView(Long userId, Long cpUserId, String relationType) {
CpRelationshipQueryCmd cmd = new CpRelationshipQueryCmd().setRelationType(relationType);
cmd.setReqUserId(userId);
cmd.setReqSysOrigin(REQ_SYS_ORIGIN);
return pairUserProfileQryExe.execute(cmd)
.stream()
.filter(item -> Objects.nonNull(item.getCpUserProfile())
&& Objects.equals(item.getCpUserProfile().getId(), cpUserId))
.findFirst()
.orElse(null);
}
private UserPair findPair(List<BaseInfo> candidates, Integer sendSex, Integer acceptSex,
String relationType) {
for (BaseInfo send : candidates) {
if (!Objects.equals(send.getUserSex(), sendSex) || hasWaitApply(send.getId(), relationType)
|| cpRelationshipService.countCp(send.getId()) >= 4) {
continue;
}
for (BaseInfo accept : candidates) {
if (Objects.equals(send.getId(), accept.getId())
|| !Objects.equals(accept.getUserSex(), acceptSex)
|| hasReceivedWaitApply(accept.getId(), relationType)
|| cpRelationshipService.countCp(accept.getId()) >= 4
|| cpRelationshipService.existsCp(send.getId(), accept.getId(), relationType)) {
continue;
}
if (userRegionGateway.checkEqRegion(send.getId(), accept.getId())) {
return new UserPair(send.getId(), accept.getId());
}
}
}
throw new AssertionError("No local candidate pair for " + relationType);
}
private boolean hasWaitApply(Long sendUserId, String relationType) {
return cpApplyService.existsNotProcessSendApply(sendUserId, relationType);
}
private boolean hasReceivedWaitApply(Long acceptUserId, String relationType) {
return cpApplyService.query()
.eq(CpApply::getAcceptApplyUserId, acceptUserId)
.eq(CpApply::getRelationType, relationType)
.eq(CpApply::getStatus, "WAIT")
.count() > 0;
}
private void executeIgnoreDuplicate(String sql) {
try {
jdbcTemplate.execute(sql);
} catch (Exception ignored) {
// Column already exists in local DB.
}
}
private record UserPair(Long sendUserId, Long acceptUserId) {
}
private record RelationPair(Long userId, Long cpUserId, String relationType) {
}
}

View File

@ -0,0 +1,131 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import org.apache.rocketmq.client.apis.ClientConfiguration;
import org.apache.rocketmq.client.apis.ClientConfigurationBuilder;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.StaticSessionCredentialsProvider;
import org.apache.rocketmq.client.apis.consumer.FilterExpression;
import org.apache.rocketmq.client.apis.consumer.FilterExpressionType;
import org.apache.rocketmq.client.apis.consumer.SimpleConsumer;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.apache.rocketmq.client.apis.producer.SendReceipt;
import org.junit.Test;
import org.springframework.test.annotation.IfProfileValue;
/**
* Local RocketMQ real-connection smoke test. Run explicitly with:
*
* <pre>
* mvn -pl rc-service/rc-service-other/other-start -am \
* -Drocketmq.local.real=true \
* -Dtest=RocketMqLocalSmokeTest#sendAndReceiveOrdinaryMessage test
*
* mvn -pl rc-service/rc-service-other/other-start -am \
* -Drocketmq.local.real=true \
* -Dtest=RocketMqLocalSmokeTest#sendAndReceiveDelayedMessage test
* </pre>
*/
@IfProfileValue(name = "rocketmq.local.real", value = "true")
public class RocketMqLocalSmokeTest {
private static final String DEFAULT_ENDPOINT = "127.0.0.1:18081";
private static final String DEFAULT_TOPIC = "RC_DEFAULT_APP_ORDINARY";
private static final String DEFAULT_DELAY_TOPIC = "RC_DEFAULT_APP_DELAYED";
private static final String TAG = "codex_local_mq_smoke";
@Test
public void sendAndReceiveOrdinaryMessage() throws Exception {
String endpoint = System.getProperty("rocketmq.endpoint", DEFAULT_ENDPOINT);
String topic = System.getProperty("rocketmq.topic", DEFAULT_TOPIC);
sendAndReceive(endpoint, topic, false);
}
@Test
public void sendAndReceiveDelayedMessage() throws Exception {
String endpoint = System.getProperty("rocketmq.endpoint", DEFAULT_ENDPOINT);
String topic = System.getProperty("rocketmq.delayTopic", DEFAULT_DELAY_TOPIC);
sendAndReceive(endpoint, topic, true);
}
private void sendAndReceive(String endpoint, String topic, boolean delayed) throws Exception {
String accessKey = System.getProperty("rocketmq.accessKey", "local");
String secretKey = System.getProperty("rocketmq.secretKey", "local");
String key = "codex-local-mq-" + UUID.randomUUID();
String body = "rocketmq-local-smoke:" + key;
ClientServiceProvider provider = ClientServiceProvider.loadService();
ClientConfiguration clientConfiguration = clientConfiguration(endpoint, accessKey, secretKey);
Producer producer = provider.newProducerBuilder()
.setClientConfiguration(clientConfiguration)
.setTopics(topic)
.build();
try {
org.apache.rocketmq.client.apis.message.MessageBuilder messageBuilder = provider.newMessageBuilder()
.setTopic(topic)
.setTag(TAG)
.setKeys(key)
.setBody(body.getBytes(StandardCharsets.UTF_8));
if (delayed) {
messageBuilder.setDeliveryTimestamp(System.currentTimeMillis() + Duration.ofSeconds(2).toMillis());
}
SendReceipt receipt = producer.send(messageBuilder.build());
assertTrue("message id should not be blank", receipt.getMessageId().toString().length() > 0);
} finally {
producer.close();
}
String group = "codex_local_mq_smoke_" + UUID.randomUUID().toString().replace("-", "");
SimpleConsumer consumer = provider.newSimpleConsumerBuilder()
.setClientConfiguration(clientConfiguration)
.setConsumerGroup(group)
.setSubscriptionExpressions(Collections.singletonMap(
topic, new FilterExpression(TAG, FilterExpressionType.TAG)))
.setAwaitDuration(Duration.ofSeconds(5))
.build();
try {
MessageView matched = receiveByKey(consumer, key);
assertEquals(body, decodeBody(matched.getBody()));
consumer.ack(matched);
} finally {
consumer.close();
}
}
private ClientConfiguration clientConfiguration(String endpoint, String accessKey, String secretKey) {
ClientConfigurationBuilder builder = ClientConfiguration.newBuilder()
.setEndpoints(endpoint)
.setRequestTimeout(Duration.ofSeconds(30));
if (accessKey != null && !accessKey.isEmpty()) {
builder.setCredentialProvider(new StaticSessionCredentialsProvider(accessKey, secretKey));
}
return builder.build();
}
private MessageView receiveByKey(SimpleConsumer consumer, String key) throws Exception {
long deadline = System.currentTimeMillis() + Duration.ofSeconds(30).toMillis();
while (System.currentTimeMillis() < deadline) {
List<MessageView> messages = consumer.receive(16, Duration.ofSeconds(15));
for (MessageView message : messages) {
if (message.getKeys().contains(key)) {
return message;
}
}
}
throw new AssertionError("message not received by key: " + key);
}
private String decodeBody(ByteBuffer body) {
ByteBuffer duplicate = body.asReadOnlyBuffer();
byte[] bytes = new byte[duplicate.remaining()];
duplicate.get(bytes);
return new String(bytes, StandardCharsets.UTF_8);
}
}

View File

@ -0,0 +1,13 @@
ALTER TABLE `user_cp_apply`
ADD COLUMN `relation_type` varchar(32) NOT NULL DEFAULT 'CP' COMMENT '关系类型CP/BROTHER/SISTERS' AFTER `accept_apply_user_id`;
ALTER TABLE `user_cp_relationship`
ADD COLUMN `relation_type` varchar(32) NOT NULL DEFAULT 'CP' COMMENT '关系类型CP/BROTHER/SISTERS' AFTER `cp_user_id`;
UPDATE `user_cp_apply`
SET `relation_type` = 'CP'
WHERE `relation_type` IS NULL OR `relation_type` = '';
UPDATE `user_cp_relationship`
SET `relation_type` = 'CP'
WHERE `relation_type` IS NULL OR `relation_type` = '';