add calendar module

This commit is contained in:
Mauve
2026-09-14 10:47:46 +08:00
parent 1e995fec4d
commit 58d4b42901
41 changed files with 1854 additions and 86 deletions
@@ -16,6 +16,7 @@ import org.springframework.web.bind.annotation.*;
import com.mgm.mcrm.appsetting.services.SettingService;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
@@ -23,12 +24,18 @@ import java.util.Map;
@CrossOrigin(origins = "*")
@RequestMapping("/api")
public class CfgSettingController {
private static final List<String> PUBLIC_LOGIN_SETTING_KEYS = List.of("APP_MOCK_SSO", "APP_MOCK_TPD");
@Resource
private SettingService settingService;
@Resource
private SysSettingService sysSettingService;
@PostMapping(value = "/app/setting/get_calendar_setting", produces = "application/json;charset=UTF-8")
public ResponseEntity<BaseApiResponse<List<CfgSettings>>> getCalendarSetting() {
return ResponseEntity.ok(BaseApiResponse.ok("Get Setting Successed", settingService.getCalendarSetting()));
}
@RequestMapping(value = "/web/setting/get_setting_by_key", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public ResponseEntity<BaseApiResponse<CfgSettings>> getSettingByKey(HttpServletRequest request, @RequestBody CfgSettingQueryRequest params) throws Exception {
boolean isSuccess = false;
@@ -51,6 +58,29 @@ public class CfgSettingController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@PostMapping(value = "/web/setting/get_public_setting_by_key", produces = "application/json;charset=UTF-8")
public ResponseEntity<BaseApiResponse<CfgSettings>> getPublicSettingByKey(HttpServletRequest request,
@RequestBody(required=false) CfgSettingQueryRequest params) throws Exception {
if (params == null || !"MACAU_STRING".equals(params.getKeyName())) {
return ResponseEntity.ok(BaseApiResponse.error("SETTING_KEY_NOT_ALLOWED", "Setting key is not allowed"));
}
return getSettingByKey(request, params);
}
@PostMapping(value = "/system/sys_setting/get_public_login_settings", produces = "application/json;charset=UTF-8")
public ResponseEntity<BaseApiResponse<List<SysSetting>>> getPublicLoginSettings(HttpServletRequest request) {
boolean internalNetwork = NetworkUtil.isMatchInternal(NetworkUtil.getClientIpAddr(request));
List<SysSetting> settings = new ArrayList<>();
for (String key : PUBLIC_LOGIN_SETTING_KEYS) {
SysSetting setting = sysSettingService.getSysSettingByKey(key);
if (setting != null) {
setting.setInternalNetwork(internalNetwork);
settings.add(setting);
}
}
return ResponseEntity.ok(BaseApiResponse.ok("", settings));
}
@RequestMapping(value = "/system/sys_setting/get", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public ResponseEntity<BaseApiResponse<SysSetting>> getSysSettingByKey(HttpServletRequest request, @RequestBody SysSettingQueryRequest queryFilter) {
BaseApiResponse<SysSetting> result = new BaseApiResponse<>();
@@ -1,6 +1,8 @@
package com.mgm.mcrm.appsetting.services;
import java.util.List;
import java.util.ArrayList;
import org.apache.commons.lang3.Strings;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
@@ -9,9 +11,27 @@ import com.mgm.mcrm.appsetting.repositories.SettingDao;
@Service
public class SettingService {
@org.springframework.beans.factory.annotation.Value("${calendar.data-mock-enabled:false}")
private boolean calendarDataMockEnabled;
@Resource
private SettingDao settingDao;
public List<CfgSettings> getCalendarSetting() {
if (calendarDataMockEnabled)
return com.mgm.mcrm.roomcalendar.services.CalendarMockData.settings();
List<CfgSettings> result = new ArrayList<>();
for (CfgSettings setting : settingDao.findAll()) {
if (setting != null && setting.getKeys() != null
&& Strings.CS.equalsAny(setting.getKeys(),
"CALENDAR_VIEW_PREVIOUS_DAYS", "CALENDAR_VIEW_VISIBLE_DAYS",
"CALENDAR_VIEW_YESTERDAY_START", "CALENDAR_VIEW_YESTERDAY_END",
"MAX_SELECTED_ROOM_TYPES")) {
result.add(setting);
}
}
return result;
}
public CfgSettings getSettingByKey(String key) {
CfgSettings setting = null;
@@ -153,6 +153,7 @@ public class MobileLoginController {
if(SysConstants.PERMISSION_APP_TODO_LIST.equals(per.getId())) userInfo.setCanViewTodoList(true);
if(SysConstants.PERMISSION_APP_DASHBOARD.equals(per.getId())) userInfo.setCanViewDashboard(true);
if(SysConstants.PERMISSION_APP_APPROVAL.equals(per.getId())) userInfo.setCanViewApproval(true);
if(SysConstants.PERMISSION_APP_CALENDAR.equals(per.getId())) userInfo.setCanViewCalendar(true);
}
}
Token accessToken = JwtTokenUtil.generateTokenByLoginUser(request.getRequestURI(),loginUser, SysConstants.MOBILE_TOKEN_TYPE,false);
@@ -251,28 +252,9 @@ public class MobileLoginController {
String isReNew = request.getParameter("isRenewRefreshToken");
boolean isRenewRefreshToken = (!"false".equalsIgnoreCase(isReNew));
RefreshTokenResponse result = new RefreshTokenResponse();
LoginUserInfo loginUser = JwtTokenUtil.parseUserFromRequest(request);
if(loginUser!=null){
Token accessToken = JwtTokenUtil.generateTokenByLoginUser(request.getRequestURI(),loginUser,SysConstants.MOBILE_TOKEN_TYPE,false);
userTokenService.updateTokenByUniqueId(loginUser.getTokenUuid(),SysConstants.MOBILE_TOKEN_TYPE,accessToken);
result.setAccessToken(accessToken.getToken());
if(isRenewRefreshToken){
Token refreshToken = JwtTokenUtil.generateTokenByLoginUser(request.getRequestURI(),loginUser,SysConstants.MOBILE_TOKEN_TYPE,true);
userTokenService.saveToken(refreshToken);
result.setRefreshToken(refreshToken.getToken());
if(StringUtils.isNotBlank(loginUser.getTokenUuid())){
userTokenService.removeTokenByUniqueId(loginUser.getTokenUuid(),SysConstants.MOBILE_TOKEN_TYPE);
}
}
result.setSuccess(true);
return ResponseEntity.status(HttpStatus.OK).body(result);
}else{
result.setSuccess(false);
result.setCode("401");
result.setMessage("Unauthorized operation");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
}
RefreshTokenResponse result = userTokenService.refreshMobileToken(
request.getHeader("RefreshToken"), request.getRequestURI(), isRenewRefreshToken);
return ResponseEntity.status(result.isSuccess() ? HttpStatus.OK : HttpStatus.UNAUTHORIZED).body(result);
}
@RequestMapping(value="/app/logout",method = RequestMethod.POST)
@@ -60,7 +60,13 @@ public class JwtAuthFilter extends OncePerRequestFilter {
) throws ServletException, IOException{
boolean validatePass = true;
try {
String token = request.getHeader("Authorization");
boolean refreshRequest = "/api/app/refresh_token".equals(request.getRequestURI());
String token = request.getHeader(refreshRequest ? "RefreshToken" : "Authorization");
if (refreshRequest && !"OPTIONS".equalsIgnoreCase(request.getMethod())
&& userTokenService.validateMobileRefreshToken(token) == null) {
sendErrorResponse(response, 401, "Invalid Refresh Token");
return;
}
if(StringUtils.isNotBlank(token) && token.startsWith("Bearer ")){
token = token.substring(7);
}
@@ -68,7 +74,11 @@ public class JwtAuthFilter extends OncePerRequestFilter {
if(StringUtils.isNotBlank(token) && dbToken!=null) {
JWTVerifier jwtVerifier = JwtTokenUtil.getJwtVerifier();
try {
jwtVerifier.verify(token);
var verified = jwtVerifier.verify(token);
if (!refreshRequest && "refresh".equals(verified.getClaim("token_use").asString())) {
sendErrorResponse(response, 401, "Invalid Access Token");
return;
}
}
catch (SignatureVerificationException e) {
LogUtil.error(JwtAuthFilter.class, "[preHandle] SignatureVerificationException \nException Message:" + e.getMessage());
@@ -76,11 +86,9 @@ public class JwtAuthFilter extends OncePerRequestFilter {
validatePass=false;
}
catch (TokenExpiredException e) {
if(!request.getRequestURI().contains("refresh_token")) {
LogUtil.error(JwtAuthFilter.class, "[preHandle] TokenExpiredException \nException Message:" + e.getMessage());
sendErrorResponse(response,401, e.getMessage());
validatePass=false;
}
LogUtil.error(JwtAuthFilter.class, "[preHandle] TokenExpiredException \nException Message:" + e.getMessage());
sendErrorResponse(response,401, e.getMessage());
validatePass=false;
}
catch (JWTVerificationException e) {
LogUtil.error(JwtAuthFilter.class, "[preHandle] JWTVerificationException \nException Message:" + e.getMessage());
@@ -38,6 +38,10 @@ import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
@Service
public class MgmUserService {
// Temporary Calendar integration testing only; leave disabled outside test configuration.
@org.springframework.beans.factory.annotation.Value("${calendar.permission-mock-enabled:false}")
private boolean calendarPermissionMockEnabled;
@Resource
private MGMApiService mgmApiService;
@Resource
@@ -200,6 +204,7 @@ public class MgmUserService {
}
private UserInfoApiRecord supplementInfoId(String userId,UserInfoApiRecord info) {
info.setCanViewCalendar(calendarPermissionMockEnabled);
// 待完善,有可能需要一层一层获得property,division,department,team
CfgProperties property = propertyDao.getByName(info.getProperty());
if(property!=null) {
@@ -237,6 +242,7 @@ public class MgmUserService {
if(SysConstants.PERMISSION_APP_TODO_LIST.equals(per.getPermissionId())) info.setCanViewTodoList(true);
if(SysConstants.PERMISSION_APP_DASHBOARD.equals(per.getPermissionId())) info.setCanViewDashboard(true);
if(SysConstants.PERMISSION_APP_APPROVAL.equals(per.getPermissionId())) info.setCanViewApproval(true);
if(SysConstants.PERMISSION_APP_CALENDAR.equals(per.getPermissionId())) info.setCanViewCalendar(true);
}
}
}
@@ -1,6 +1,10 @@
package com.mgm.mcrm.authorization.services;
import com.auth0.jwt.JWT;
import com.mgm.mcrm.authorization.utils.JwtTokenUtil;
import com.mgm.mcrm.authorization.dtos.LoginUserInfo;
import com.mgm.mcrm.authorization.dtos.RefreshTokenResponse;
import com.mgm.mcrm.common.constants.SysConstants;
import com.mgm.mcrm.authorization.models.Token;
import com.mgm.mcrm.authorization.repositories.TokenDao;
import jakarta.transaction.Transactional;
@@ -15,6 +19,46 @@ import java.time.LocalDateTime;
public class UserTokenService {
private final TokenDao tokenDao;
public LoginUserInfo validateMobileRefreshToken(String value) {
if (StringUtils.isBlank(value)) return null;
if (value.startsWith("Bearer ")) value = value.substring(7);
try {
var jwt = JwtTokenUtil.getJwtVerifier().verify(value);
if (!"refresh".equals(jwt.getClaim("token_use").asString())
|| !Integer.valueOf(SysConstants.MOBILE_TOKEN_TYPE).equals(jwt.getClaim("token_type").asInt())
|| jwt.getExpiresAt() == null || StringUtils.isBlank(jwt.getId())) return null;
Token stored = tokenDao.findByUuidAndTokenType(jwt.getId(), SysConstants.MOBILE_TOKEN_TYPE);
if (stored == null || !value.equals(stored.getToken()) || stored.getExpireTime() == null
|| !stored.getExpireTime().isAfter(LocalDateTime.now())) return null;
LoginUserInfo user = JwtTokenUtil.parseUserFromToken(value);
return user != null && StringUtils.isNotBlank(user.getLoginId())
&& user.getLoginId().equals(stored.getCreatedBy()) ? user : null;
} catch (Exception invalidToken) {
return null;
}
}
@Transactional
public RefreshTokenResponse refreshMobileToken(String value, String issuer, boolean renew) {
RefreshTokenResponse result = new RefreshTokenResponse();
LoginUserInfo user = validateMobileRefreshToken(value);
if (user == null || (renew && tokenDao.deleteByUuidAndTokenType(user.getTokenUuid(), SysConstants.MOBILE_TOKEN_TYPE) != 1)) {
result.setCode("401");
result.setMessage("Unauthorized operation");
return result;
}
Token access = JwtTokenUtil.generateTokenByLoginUser(issuer, user, SysConstants.MOBILE_TOKEN_TYPE, false);
saveToken(access);
result.setAccessToken(access.getToken());
if (renew) {
Token refresh = JwtTokenUtil.generateTokenByLoginUser(issuer, user, SysConstants.MOBILE_TOKEN_TYPE, true);
saveToken(refresh);
result.setRefreshToken(refresh.getToken());
}
result.setSuccess(true);
return result;
}
@Transactional
public Token saveToken(Token token){
if(token!=null){
@@ -57,6 +101,7 @@ public class UserTokenService {
newDbToken.setTokenType(newToken.getTokenType());
newDbToken.setExpireTime(newToken.getExpireTime());
newDbToken.setCreatedAt(LocalDateTime.now());
newDbToken.setCreatedBy(newToken.getCreatedBy());
newDbToken.setUpdatedBy(newToken.getCreatedBy());
newDbToken.setUpdatedBy(newToken.getCreatedBy());
newDbToken.setUpdatedAt(LocalDateTime.now());
@@ -62,6 +62,8 @@ public class JwtTokenUtil {
.withIssuedAt(now).withNotBefore(now).withExpiresAt(expDate).withJWTId(uuid)
.withClaim("login_id", user.getLoginId())
.withClaim("group_name", user.getGroupName())
.withClaim("token_use", isRefreshToken ? "refresh" : "access")
.withClaim("token_type", tokenType)
.withClaim("last_post_time", now)
.withSubject(String.valueOf(user.getLoginId()))
.sign(Algorithm.HMAC256(secretKey));
@@ -106,7 +108,8 @@ public class JwtTokenUtil {
loginUser.setId(-1L);
}
loginUser.setLoginId(decodeData.getClaim("login_id").asString());
loginUser.setGroupName(decodeData.getClaim("user_group").asString());
String groupName = decodeData.getClaim("group_name").asString();
loginUser.setGroupName(groupName != null ? groupName : decodeData.getClaim("user_group").asString());
loginUser.setTokenUuid(decodeData.getId());
}catch(Exception err) {
LogUtil.error(SysCommon.class, "Parse Token failed:"+err.getMessage());
@@ -1019,10 +1019,10 @@ public class DaylightService {
// String currentDate = DateTimeUtil.getCurrentDate("yyyy-MM-dd");
String url = "/api-gateway/booking/v1/reservations?pageNumber=1&pageSize=50&filter=profileId==" + profileId
String url = "/api-gateway/aggregator/v1/reservations?pageNumber=1&pageSize=50&filter=profileId==" + profileId
+ ";(statusCode.code==DI,statusCode.code==RS,statusCode.code==DO,statusCode.code==IH,statusCode.code==CX)"
// + ";departureDate=ge=" + currentDate
+ "&extend=PurchaseElements&extend=CustomFields&extend=Breakdown&extend=DoorKeys&sort=-createdAt";
+ "&extend=PurchaseElements,CustomFields,Breakdown,DoorKeys&sort=-createdAt";
Map<String, Object> map = new HashMap<>();
try {
for (CfgProperties property : properties) {
@@ -36,6 +36,12 @@ public class CfgProperties implements Serializable {
private String dlPropertyId;
@Column(name="sort_order")
private Integer sortOrder;
@Column(name="show_calendar", nullable = false)
private Integer showCalendar;
@Column(name="calendar_name", length = 256)
private String calendarName;
@Column(name="calendar_order")
private Integer calendarOrder;
@Column(name="created_at")
private Date createdAt;
@@ -1,5 +1,6 @@
package com.mgm.mcrm.basesetting.property.repositories;
import java.util.Collection;
import java.util.List;
import org.springframework.data.domain.Page;
@@ -51,4 +52,6 @@ public interface PropertyDao extends JpaRepository<CfgProperties, String> {
CfgProperties queryByName(String propertyName);
List<CfgProperties> findByCategory(String category);
List<CfgProperties> findByCalendarNameIn(Collection<String> calendarNames);
}
@@ -51,6 +51,14 @@ public class CfgRooms implements Serializable {
@Column(name = "category")
private String category;
@Column(name="show_calendar", nullable = false)
private Integer showCalendar;
@Column(name="calendar_name", length = 256)
private String calendarName;
@Column(name="calendar_order")
private Integer calendarOrder;
@Column(name="default_show_calendar")
private Integer defaultShowCalendar;
@Transient
private List<String> roomTypeIds;
@@ -10,9 +10,11 @@ import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import com.mgm.mcrm.basesetting.room.models.CfgRooms;
import com.mgm.mcrm.roomcalendar.repositories.RoomCalendarRoomProjection;
public interface RoomDao extends JpaRepository<CfgRooms, String> {
@@ -34,4 +36,13 @@ public interface RoomDao extends JpaRepository<CfgRooms, String> {
@Query(value="select * from cfg_rooms where id =?1",nativeQuery=true)
CfgRooms getById(Long id);
@Query("select r.propertyId as propertyId, r.name as name, r.calendarName as calendarName, "
+ "r.calendarOrder as calendarOrder, r.defaultShowCalendar as defaultShowCalendar "
+ "from CfgRooms r "
+ "where r.showCalendar = 1 and r.propertyId in :propertyIds "
+ "order by r.propertyId asc, r.calendarOrder asc, r.name asc")
List<RoomCalendarRoomProjection> queryCalendarRoomsByPropertyIds(@Param("propertyIds") List<String> propertyIds);
List<CfgRooms> findByPropertyIdInAndCalendarNameIn(List<String> propertyIds, List<String> calendarNames);
}
@@ -1430,13 +1430,13 @@ public class BookingService {
DaylightReservationResponse daylightReservationByDlId =
dlService.getDaylightReservationByDlId(reservationId, property.getDlPropertyId());
bookings.setDlAccountId(daylightReservationByDlId.getAccountId());
bookings.setDlReservationId(reservationId);
bookings.setConfirmationNo(confirmationNumber);
bookings.setLastOperaStatus("RESERVED");
bookings.setApproveStatus("N");
bookingDao.save(bookings);
// bookings.setDlAccountId(daylightReservationByDlId.getAccountId());
// bookings.setDlReservationId(reservationId);
// bookings.setConfirmationNo(confirmationNumber);
// bookings.setLastOperaStatus("RESERVED");
// bookings.setApproveStatus("N");
//
// bookingDao.save(bookings);
dlService.createDaylightCompRule(
daylightReservationByDlId.getAccountId(),
@@ -1452,7 +1452,7 @@ public class BookingService {
//Create Reservation 后处理WaitListBooking
if (bookings.getWaitlistId() != null) {
Bookings waitlistBooking = bookingDao.findById(bookings.getWaitlistId()).orElse(null);
waitlistBooking.setConfirmationNo(bookings.getConfirmationNo());
// waitlistBooking.setConfirmationNo(bookings.getConfirmationNo());
waitlistBooking.setApproveStatus("WF");
waitlistBooking.setUpdatedAt(DateTimeUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss"));
bookingDao.save(waitlistBooking);
@@ -326,7 +326,7 @@ public class WaitlistBookingService {
Date creatdDate = DateTimeUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss");
if(request!=null) {
LoginUserInfo userInfo =SysCommon.parseUserFromToken(request);
LoginUserInfo userInfo = SysCommon.parseUserFromToken(request);
if (userInfo != null) {
userId = userInfo.getLoginId();
if(!StringUtils.isEmpty(userId)) {
@@ -59,11 +59,10 @@ public class WebFilterConfig {
JwtTokenUtil.setAppSessionExpiration(apiTokenExpiration);
JwtTokenUtil.setAppSessionExpiration(mobileSessionExpiration);
List<String> excludePatterns = Arrays.asList(
"/api/system/write_log",
"/api/system/sys_setting/get_list",
"/api/system/write_public_log",
"/api/system/sys_setting/get_public_login_settings",
"/api/app/sso/*",
"/api/app/booking/mock_cancel",
"/api/web/setting/get_setting_by_key",
"/api/web/setting/get_public_setting_by_key",
"/swagger*/*",
"/v3/**",
"/api-docs",
@@ -26,5 +26,6 @@ public class SysConstants {
public static final String PERMISSION_APP_TODO_LIST="10001_03";
public static final String PERMISSION_APP_DASHBOARD="10001_04";
public static final String PERMISSION_APP_APPROVAL="10001_05";
public static final String PERMISSION_APP_CALENDAR="10001_07";
}
@@ -21,14 +21,19 @@ public class TodoDetailResult {
private String Salutation = null;
private String Location=null;
private String ActivePrgId=null;
private Integer PrgTO=null;
private Integer PrgWin=null;
@com.alibaba.fastjson.annotation.JSONField(name = "PrgTO")
private String PrgTO = null;
@com.alibaba.fastjson.annotation.JSONField(name = "PrgWin")
private String PrgWin = null;
private Double TORIPercentage=null;
private Integer FrontMoney=null;
private Integer TTO=null;
@com.alibaba.fastjson.annotation.JSONField(name = "FrontMoney")
private String FrontMoney = null;
@com.alibaba.fastjson.annotation.JSONField(name = "TTO")
private String TTO = null;
@JsonProperty("01CompBalance")
private Integer ComBalance=null;
@com.alibaba.fastjson.annotation.JSONField(name = "01CompBalance")
private String ComBalance = null;
private String R3MTO=null;
private String R3MTOD=null;
@@ -42,21 +47,42 @@ public class TodoDetailResult {
private String R6MTPD=null;
private String R6MTheo = null;
private String R6MRIPercentage=null;
private Integer ExpComm=null;
private Integer NetCreditOutstanding=null;
private Integer UnsettledExpenses=null;
private Integer TodayTo=null;
private Integer TodayTPD=null;
private Integer TodayWin=null;
private Integer TodayTheo = null;
private Integer TripWin=null;
private Integer TripTPD=null;
private Integer TripTheo = null;
private Double TripRIPercentage=null;
private Integer YesterdayTO=null;
private Integer YesterdayWin=null;
private Integer YesterdayPlayHour=null;
private Integer AveragePlayHour = null;
@com.alibaba.fastjson.annotation.JSONField(name = "ExpComm")
private String ExpComm = null;
@com.alibaba.fastjson.annotation.JSONField(name = "IRCProgramFundBalance")
@JsonProperty("iRCProgramFundBalance")
private String ircProgramFundBalance = null;
@com.alibaba.fastjson.annotation.JSONField(name = "NetCreditOutstanding")
private String NetCreditOutstanding = null;
@com.alibaba.fastjson.annotation.JSONField(name = "UnsettledExpenses")
private String UnsettledExpenses = null;
@com.alibaba.fastjson.annotation.JSONField(name = "TodayTo")
private String TodayTo = null;
@com.alibaba.fastjson.annotation.JSONField(name = "TodayTPD")
private String TodayTPD = null;
@com.alibaba.fastjson.annotation.JSONField(name = "TodayWin")
private String TodayWin = null;
@com.alibaba.fastjson.annotation.JSONField(name = "TodayTheo")
private String TodayTheo = null;
@com.alibaba.fastjson.annotation.JSONField(name = "TripWin")
private String TripWin = null;
@com.alibaba.fastjson.annotation.JSONField(name = "TripTPD")
private String TripTPD = null;
@com.alibaba.fastjson.annotation.JSONField(name = "TripTheo")
private String TripTheo = null;
@com.alibaba.fastjson.annotation.JSONField(name = "TripRIPercentage")
private String TripRIPercentage = null;
@com.alibaba.fastjson.annotation.JSONField(name = "YesterdayTO")
private String YesterdayTO = null;
@com.alibaba.fastjson.annotation.JSONField(name = "YesterdayWin")
private String YesterdayWin = null;
@com.alibaba.fastjson.annotation.JSONField(name = "YesterdayPlayHour")
private String YesterdayPlayHour = null;
@com.alibaba.fastjson.annotation.JSONField(name = "AveragePlayHour")
private String AveragePlayHour = null;
@com.alibaba.fastjson.annotation.JSONField(name = "HouseAdvantagePercentage")
@JsonProperty("HouseAdvantagePercentage")
private String houseAdvantage = null;
private List<TodoDetailDescription> Descriptions = new ArrayList<TodoDetailDescription>();
public TodoDetailResult() {
}
@@ -211,6 +211,11 @@ public class TodoListRecord {
return MAId;
}
@com.fasterxml.jackson.annotation.JsonProperty("maId")
public Integer getCalendarMaId() {
return MAId;
}
public void setMAId(Integer mAId) {
MAId = mAId;
}
@@ -26,6 +26,7 @@ public class UserInfoApiRecord {
private boolean canViewTodoList=false;
private boolean canViewDashboard=false;
private boolean canViewApproval=false;
private boolean canViewCalendar=false;
private String groupName;
private String phone;
private boolean loginTag;
@@ -44,8 +44,38 @@ public class MGMApiService {
private static final String API_GET_APPROVER_DATA="/RequestWaitlistData";
private static final String API_GET_APPROVER="/RequestRoomBookingApprovalRouting";
private static final String API_GET_TODO_LIST = "/GetTodolist";
private static final String API_REQUEST_ROOM_CALENDAR = "/RequestRoomCalendar";
public HttpResponseResult invokeRequestRoomCalendar(
String playerId,
String property,
String roomType,
String startDate,
String endDate) throws Exception {
return invokeRequestRoomCalendar(playerId, property, roomType, startDate, endDate, 0);
}
public HttpResponseResult invokeRequestRoomCalendar(
String playerId,
String property,
String roomType,
String startDate,
String endDate,
int type) throws Exception {
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestHeader.put("Authorization", getAccessToken());
if (StringUtils.isNotBlank(playerId)) {
requestObj.put("PlayerId", playerId);
}
requestObj.put("Property", property);
requestObj.put("RoomType", roomType);
requestObj.put("StartDate", startDate);
requestObj.put("EndDate", endDate);
return invokeESBAPI(ESB_Server, API_REQUEST_ROOM_CALENDAR, requestObj, "POST", requestHeader, type);
}
public HttpResponseResult invokeGetPlayerProfile(
String playerId,
String userId) throws Exception {
@@ -416,4 +446,4 @@ public class MGMApiService {
LogUtil.info(MGMApiService.class, "[invokeESBAPI]SpendTime:" + spanTime + "ms");
return httpResult;
}
}
}
@@ -1,7 +1,10 @@
package com.mgm.mcrm.logging.controllers;
import java.util.Date;
import java.util.Map;
import com.mgm.mcrm.authorization.dtos.LoginUserInfo;
import com.mgm.mcrm.authorization.utils.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.util.HtmlUtils;
import com.mgm.mcrm.common.dtos.BaseApiResponse;
import com.mgm.mcrm.logging.dtos.AppLogDto;
@@ -28,18 +31,35 @@ public class SysLogAppController {
@RequestMapping(value = "/system/write_log", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public ResponseEntity<BaseApiResponse<SysLogApp>> writeAppLog(HttpServletRequest request, @RequestBody(required=true) AppLogDto appLogDto) {
// The JWT filter authenticates this route before the controller runs.
LoginUserInfo user = JwtTokenUtil.parseUserFromRequest(request);
if (user == null || StringUtils.isBlank(user.getLoginId())) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(BaseApiResponse.unauthorizedError("Invalid Token"));
}
return writeLog(request, appLogDto, limit(user.getLoginId(), 64));
}
@PostMapping(value = "/system/write_public_log", produces = "application/json;charset=UTF-8")
public ResponseEntity<BaseApiResponse<SysLogApp>> writePublicAppLog(HttpServletRequest request,
@RequestBody(required=true) AppLogDto appLogDto) {
return writeLog(request, appLogDto, "ANONYMOUS");
}
private ResponseEntity<BaseApiResponse<SysLogApp>> writeLog(HttpServletRequest request, AppLogDto appLogDto, String loginId) {
if (appLogDto == null) {
return ResponseEntity.badRequest().body(BaseApiResponse.badRequestError("Missing request data"));
}
String processMessage="";
String errorCode="";
BaseApiResponse<SysLogApp> result = new BaseApiResponse<>();
SysLogApp sysLogApp = new SysLogApp();
String loginId = appLogDto.getLoginId();
String eventCode = appLogDto.getEventCode();
String transId = appLogDto.getTransId();
String logDesc = appLogDto.getLogDesc();
Integer tagSuccess = appLogDto.getTagSuccess();
String requestBody = appLogDto.getRequestBody();
String responseBody = appLogDto.getResponseBody();
String eventCode = limit(appLogDto.getEventCode(), 100);
String transId = limit(appLogDto.getTransId(), 100);
String logDesc = escape(appLogDto.getLogDesc(), 1000);
Integer tagSuccess = appLogDto.getTagSuccess() == null ? 0 : appLogDto.getTagSuccess();
String requestBody = escape(appLogDto.getRequestBody(), 4000);
String responseBody = escape(appLogDto.getResponseBody(), 4000);
Date now = DateTimeUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSSSS");
sysLogApp.setLoginId(loginId);
@@ -61,5 +81,13 @@ public class SysLogAppController {
result.setData(appLog);
return ResponseEntity.status(HttpStatus.OK).body(result);
}
private static String limit(String value, int maxLength) {
return value == null ? null : value.substring(0, Math.min(value.length(), maxLength));
}
private static String escape(String value, int maxLength) {
return value == null ? null : HtmlUtils.htmlEscape(limit(value, maxLength));
}
}
@@ -414,12 +414,14 @@ public class TodoService {
Date newDate = DateTimeUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss");
Bookings booking = bookingDao.findById(bookId).orElse(null);
errors = cancelResponse;
String errorMessage = errors != null && StringUtils.isNotBlank(errors.getString("message"))
? errors.getString("message") : "Cancel Booking Fail";
booking.setUpdatedAt(newDate);
booking.setCreatedAt(newDate);
booking.setApproveStatus("F");
booking.setErrorMessage(errors.getString("message"));
booking.setErrorMessage(errorMessage);
processResult.setSuccess(false);
processResult.setMessage(errors.getString("message")!=null?errors.getString("message"):"System Error");
processResult.setMessage(errorMessage);
processResult.setCode("SYSTEM_ERROR");
processResult.setData(bookingView);
}
@@ -0,0 +1,94 @@
package com.mgm.mcrm.roomcalendar.controllers;
import com.mgm.mcrm.authorization.dtos.LoginUserInfo;
import com.mgm.mcrm.authorization.services.SysGroupPermissionService;
import com.mgm.mcrm.authorization.utils.JwtTokenUtil;
import com.mgm.mcrm.common.constants.SysConstants;
import com.mgm.mcrm.roomcalendar.dtos.RoomCalendarQualification;
import com.mgm.mcrm.roomcalendar.dtos.response.GetPropertyRoomTypeListResponse;
import com.mgm.mcrm.roomcalendar.dtos.response.RoomCalendarApiResponse;
import com.mgm.mcrm.roomcalendar.services.RoomCalendarService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api")
public class RoomCalendarController {
// Same switch as the user-info flag; authentication is still required.
@org.springframework.beans.factory.annotation.Value("${calendar.permission-mock-enabled:false}")
private boolean calendarPermissionMockEnabled;
@Resource
private RoomCalendarService roomCalendarService;
@Resource
private SysGroupPermissionService sysGroupPermissionService;
@PostMapping(
value = "/app/room_calendar/request_room_calendar",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public RoomCalendarApiResponse<List<RoomCalendarQualification>> requestRoomCalendar(
HttpServletRequest request,
@RequestBody(required = false) Map<String, Object> params) throws Exception {
return processCalendarRequest(request, params);
}
@PostMapping(
value = "/app/room_calendar/player_qualification",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public RoomCalendarApiResponse<List<RoomCalendarQualification>> getPlayerRoomQualification(
HttpServletRequest request,
@RequestBody(required = false) Map<String, Object> params) throws Exception {
return processCalendarRequest(request, params);
}
@GetMapping(
value = "/app/room_calendar/get_properties_room_types",
produces = MediaType.APPLICATION_JSON_VALUE)
public GetPropertyRoomTypeListResponse requestPropertiesRoomTypes(HttpServletRequest request) {
if (!canViewCalendar(request)) {
GetPropertyRoomTypeListResponse result = new GetPropertyRoomTypeListResponse();
result.setSuccess(false);
result.setMessage("NO PERMISSION");
result.setCalendarErrorCode("NO_PERMISSION");
return result;
}
return roomCalendarService.getPropertyRoomType();
}
private RoomCalendarApiResponse<List<RoomCalendarQualification>> processCalendarRequest(
HttpServletRequest request,
Map<String, Object> params) throws Exception {
RoomCalendarApiResponse<List<RoomCalendarQualification>> result = new RoomCalendarApiResponse<>();
if (params == null) {
result.setSuccess(false);
result.setMessage("Missing request data");
return result;
}
if (!canViewCalendar(request)) {
result.setSuccess(false);
result.setMessage("NO PERMISSION");
result.setCalendarErrorCode("NO_PERMISSION");
return result;
}
return roomCalendarService.getRoomCalendar(params);
}
private boolean canViewCalendar(HttpServletRequest request) {
LoginUserInfo user = JwtTokenUtil.parseUserFromRequest(request);
return user != null && (calendarPermissionMockEnabled || sysGroupPermissionService.checkGroupPermission(
user.getGroupName(), SysConstants.PERMISSION_APP_CALENDAR));
}
}
@@ -0,0 +1,14 @@
package com.mgm.mcrm.roomcalendar.dtos;
import lombok.Data;
@Data
public class RoomCalendarQualification {
private String property;
private String roomType;
private String date;
private String roomCriteria;
private Integer roomCount;
private String propertyLeader;
private Integer bookingDateQualificationFlag;
}
@@ -0,0 +1,12 @@
package com.mgm.mcrm.roomcalendar.dtos.response;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
public class GetPropertyRoomTypeListResponse extends RoomCalendarApiResponse<Void> {
private List<GetPropertyRoomTypeResponse> propertyList;
}
@@ -0,0 +1,17 @@
package com.mgm.mcrm.roomcalendar.dtos.response;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import java.util.List;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class GetPropertyRoomTypeResponse {
private String code;
private String name;
private String displayName;
private List<String> defaultRoomTypes;
private List<RoomType> roomTypes;
private List<GetPropertyRoomTypeResponse> otherProperties;
}
@@ -0,0 +1,18 @@
package com.mgm.mcrm.roomcalendar.dtos.response;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.mgm.mcrm.common.dtos.BaseApiResponse;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class RoomCalendarApiResponse<T> extends BaseApiResponse<T> {
@JsonInclude(JsonInclude.Include.NON_NULL)
private String errorCode;
public void setCalendarErrorCode(String errorCode) {
setCode(errorCode);
this.errorCode = errorCode;
}
}
@@ -0,0 +1,13 @@
package com.mgm.mcrm.roomcalendar.dtos.response;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RoomType {
private String code;
private String label;
private String displayName;
private Integer defaultShowCalendar;
}
@@ -0,0 +1,9 @@
package com.mgm.mcrm.roomcalendar.repositories;
public interface RoomCalendarRoomProjection {
String getPropertyId();
String getName();
String getCalendarName();
Integer getCalendarOrder();
Integer getDefaultShowCalendar();
}
@@ -0,0 +1,93 @@
package com.mgm.mcrm.roomcalendar.services;
import com.mgm.mcrm.appsetting.models.CfgSettings;
import com.mgm.mcrm.roomcalendar.dtos.RoomCalendarQualification;
import com.mgm.mcrm.roomcalendar.dtos.response.*;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
/** Calendar display fixtures only. Never writes bookings or configuration. */
public final class CalendarMockData {
private CalendarMockData() {}
private static GetPropertyRoomTypeResponse hotel(String code, String name, String... rooms) {
var hotel = new GetPropertyRoomTypeResponse();
hotel.setCode(code); hotel.setName(name + " [MOCK]"); hotel.setDisplayName(name + " [MOCK]");
var types = new ArrayList<RoomType>();
for (int i=0; i<rooms.length; i++) {
var type = new RoomType();
type.setCode(rooms[i]); type.setLabel(rooms[i]); type.setDefaultShowCalendar(i<3 ? 1 : 0);
types.add(type);
}
hotel.setRoomTypes(types);
hotel.setDefaultRoomTypes(Arrays.stream(rooms).limit(3).toList());
return hotel;
}
public static GetPropertyRoomTypeListResponse metadata() {
var cotai = hotel("SIM_COTAI", "Cotai", "CR", "ES", "CS", "CV");
var macau = hotel("SIM_MACAU", "Macau", "GR", "MS", "GDX", "MR");
var other = hotel("OTHER", "Other Property");
var children = List.of(hotel("SIM_MO","Mandarin Oriental","MO_STD","MO_SUITE"),
hotel("SIM_LB","Lisboeta","LB_GRAND","LB_STUDIO"),
hotel("SIM_YO","YOHO","YO_BALCONY","YO_ONSEN"),
hotel("SIM_RO","Roosevelt","RO_GRAND","RO_SUITE"));
other.setOtherProperties(children);
other.setDefaultRoomTypes(children.stream().limit(3).map(GetPropertyRoomTypeResponse::getCode).toList());
var response = new GetPropertyRoomTypeListResponse();
response.setSuccess(true); response.setCode("200");
response.setMessage("CALENDAR_MOCK_DATA");
response.setPropertyList(List.of(cotai, macau, other));
return response;
}
public static List<CfgSettings> settings() {
var result = new ArrayList<CfgSettings>();
String[][] values = {{"CALENDAR_VIEW_PREVIOUS_DAYS","7"},{"CALENDAR_VIEW_VISIBLE_DAYS","60"},
{"CALENDAR_VIEW_YESTERDAY_START","00:00"},{"CALENDAR_VIEW_YESTERDAY_END","23:59"},
{"MAX_SELECTED_ROOM_TYPES","3"}};
for (var value:values) {
var setting = new CfgSettings(); setting.setKeys(value[0]); setting.setKeyValues(value[1]);
result.add(setting);
}
return result;
}
public static List<RoomCalendarQualification> records(String playerId, String properties,
String rooms, String startDate, String endDate) {
LocalDate start = LocalDate.parse(startDate), end = LocalDate.parse(endDate);
if (end.isBefore(start) || ChronoUnit.DAYS.between(start,end)>120)
throw new IllegalArgumentException("Mock date range must be 1 to 121 days");
var catalog = new LinkedHashMap<String,GetPropertyRoomTypeResponse>();
for (var property:metadata().getPropertyList()) {
if (property.getOtherProperties()!=null)
property.getOtherProperties().forEach(child->catalog.put(child.getCode(),child));
else catalog.put(property.getCode(),property);
}
Set<String> requestedRooms = new LinkedHashSet<>(Arrays.asList(rooms.split(",")));
var result = new ArrayList<RoomCalendarQualification>();
Set<String> matchedRooms = new HashSet<>();
for (String code:new LinkedHashSet<>(Arrays.asList(properties.split(",")))) {
var property = catalog.get(code.trim());
if (property==null) throw new IllegalArgumentException("Unknown mock property: "+code);
for (var type:property.getRoomTypes()) {
if (!requestedRooms.contains(type.getCode())) continue;
matchedRooms.add(type.getCode());
for (var date=start; !date.isAfter(end); date=date.plusDays(1)) {
int seed = Math.floorMod(Objects.hash(code,type.getCode(),date.toString(),playerId),1000);
var record = new RoomCalendarQualification();
record.setProperty(code); record.setRoomType(type.getCode()); record.setDate(date.toString());
record.setRoomCount(seed%5==0 ? 0 : 1+seed%24);
record.setRoomCriteria(String.valueOf(1000+(seed%8)*500));
record.setPropertyLeader("Demo Host "+(1+seed%3));
record.setBookingDateQualificationFlag(seed%3==0 ? 0 : 1);
result.add(record);
}
}
}
if (!matchedRooms.containsAll(requestedRooms))
throw new IllegalArgumentException("Unknown mock room or room/property mismatch");
return result;
}
}
@@ -0,0 +1,465 @@
package com.mgm.mcrm.roomcalendar.services;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mgm.mcrm.basesetting.property.models.CfgProperties;
import com.mgm.mcrm.basesetting.property.repositories.PropertyDao;
import com.mgm.mcrm.basesetting.room.models.CfgRooms;
import com.mgm.mcrm.basesetting.room.repositories.RoomDao;
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.common.services.MGMApiService;
import com.mgm.mcrm.roomcalendar.dtos.RoomCalendarQualification;
import com.mgm.mcrm.roomcalendar.dtos.response.GetPropertyRoomTypeListResponse;
import com.mgm.mcrm.roomcalendar.dtos.response.GetPropertyRoomTypeResponse;
import com.mgm.mcrm.roomcalendar.dtos.response.RoomCalendarApiResponse;
import com.mgm.mcrm.roomcalendar.dtos.response.RoomType;
import com.mgm.mcrm.roomcalendar.repositories.RoomCalendarRoomProjection;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Service
public class RoomCalendarService {
@org.springframework.beans.factory.annotation.Value("${calendar.data-mock-enabled:false}")
private boolean calendarDataMockEnabled;
@Resource
private MGMApiService mgmApiService;
@Resource
private PropertyDao propertyDao;
@Resource
private RoomDao roomDao;
public RoomCalendarApiResponse<List<RoomCalendarQualification>> getRoomCalendar(Map<String, Object> params) throws Exception {
RoomCalendarApiResponse<List<RoomCalendarQualification>> result = new RoomCalendarApiResponse<>();
String playerId;
String property;
String roomType;
String startDate;
String endDate;
try {
playerId = getOptionalString(params, "playerId", "PlayerId");
property = getRequiredString(params, "property", "Property");
roomType = getRequiredString(params, "roomType", "RoomType");
startDate = getRequiredString(params, "startDate", "StartDate");
endDate = getRequiredString(params, "endDate", "EndDate");
} catch (IllegalArgumentException ex) {
result.setSuccess(false);
result.setMessage(ex.getMessage());
return result;
}
if (calendarDataMockEnabled) {
try {
result.setData(CalendarMockData.records(playerId, property, roomType, startDate, endDate));
result.setSuccess(true);
result.setCode("200");
result.setMessage("CALENDAR_MOCK_DATA");
} catch (java.time.DateTimeException | IllegalArgumentException ex) {
result.setSuccess(false);
result.setMessage(ex.getMessage());
}
return result;
}
CalendarVisibilityCheck visibility = validateCalendarVisibility(property, roomType);
if (visibility.errorCode != null) {
result.setSuccess(false);
result.setMessage(visibility.errorMessage);
result.setCalendarErrorCode(visibility.errorCode);
result.setData(new ArrayList<>());
return result;
}
List<RoomCalendarQualification> allRecords = new ArrayList<>();
boolean anySuccess = false;
if (StringUtils.isNotBlank(visibility.operaProperty) && StringUtils.isNotBlank(visibility.operaRoomType)) {
try {
HttpResponseResult response = mgmApiService.invokeRequestRoomCalendar(
playerId, visibility.operaProperty, visibility.operaRoomType, startDate, endDate, 0);
if (response.getStatusCode() == 200) {
allRecords.addAll(parseRoomCalendarResponse(response.getResponseContent()));
anySuccess = true;
}
} catch (Exception ignored) {
}
}
if (StringUtils.isNotBlank(visibility.daylightProperty) && StringUtils.isNotBlank(visibility.daylightRoomType)) {
try {
HttpResponseResult response = mgmApiService.invokeRequestRoomCalendar(
playerId, visibility.daylightProperty, visibility.daylightRoomType, startDate, endDate, 1);
if (response.getStatusCode() == 200) {
allRecords.addAll(parseRoomCalendarResponse(response.getResponseContent()));
anySuccess = true;
}
} catch (Exception ignored) {
}
}
if (!anySuccess) {
result.setSuccess(false);
result.setMessage("RequestRoomCalendar failed");
result.setData(new ArrayList<>());
return result;
}
result.setData(allRecords);
result.setSuccess(true);
result.setCode("200");
return result;
}
private CalendarVisibilityCheck validateCalendarVisibility(String property, String roomType) {
List<String> propertyNames = parseDelimitedValues(property);
List<String> roomTypeNames = parseDelimitedValues(roomType);
List<CfgProperties> properties = propertyDao.findByCalendarNameIn(propertyNames);
List<CfgProperties> visibleProperties = new ArrayList<>();
for (String propertyName : propertyNames) {
CfgProperties cfgProperty = findByCalendarName(properties, propertyName);
if (isShowCalendar(cfgProperty)) {
visibleProperties.add(cfgProperty);
}
}
if (visibleProperties.isEmpty()) {
return CalendarVisibilityCheck.failure("PROPERTYNOSHOW", "Property no show in calendar");
}
List<String> propertyIds = new ArrayList<>();
for (CfgProperties cfgProperty : visibleProperties) {
propertyIds.add(String.valueOf(cfgProperty.getId()));
}
List<CfgRooms> rooms = roomDao.findByPropertyIdInAndCalendarNameIn(propertyIds, roomTypeNames);
String operaProperty = "";
String operaRoomType = "";
String daylightProperty = "";
String daylightRoomType = "";
List<String> operaIds = new ArrayList<>();
List<String> operaCodes = new ArrayList<>();
List<String> daylightIds = new ArrayList<>();
List<String> daylightCodes = new ArrayList<>();
for (CfgProperties cfgProperty : visibleProperties) {
String category = cfgProperty.getCategory();
if (StringUtils.equalsIgnoreCase(category, "OPERA")) {
operaIds.add(String.valueOf(cfgProperty.getId()));
operaCodes.add(cfgProperty.getCode());
} else if (StringUtils.equalsIgnoreCase(category, "DAYLIGHT")) {
daylightIds.add(String.valueOf(cfgProperty.getId()));
daylightCodes.add(cfgProperty.getCode());
}
}
if (!operaIds.isEmpty()) {
List<String> visibleOperaRoomTypes = filterVisibleRoomTypes(roomTypeNames, rooms, operaIds);
if (!visibleOperaRoomTypes.isEmpty()) {
operaProperty = StringUtils.join(operaCodes, ",");
operaRoomType = StringUtils.join(visibleOperaRoomTypes, ",");
}
}
if (!daylightIds.isEmpty()) {
List<String> visibleDaylightRoomTypes = filterVisibleRoomTypes(roomTypeNames, rooms, daylightIds);
if (!visibleDaylightRoomTypes.isEmpty()) {
daylightProperty = StringUtils.join(daylightCodes, ",");
daylightRoomType = StringUtils.join(visibleDaylightRoomTypes, ",");
}
}
if (StringUtils.isBlank(operaRoomType) && StringUtils.isBlank(daylightRoomType)) {
return CalendarVisibilityCheck.failure("ROOMTYPENOSHOW", "Room type no show in calendar");
}
return CalendarVisibilityCheck.success(operaProperty, operaRoomType, daylightProperty, daylightRoomType);
}
public GetPropertyRoomTypeListResponse getPropertyRoomType() {
if (calendarDataMockEnabled) return CalendarMockData.metadata();
GetPropertyRoomTypeListResponse response = new GetPropertyRoomTypeListResponse();
List<CfgProperties> properties = propertyDao.findAll();
Map<String, List<RoomCalendarRoomProjection>> roomsByPropertyId = buildCalendarRoomsByPropertyId(properties);
List<GetPropertyRoomTypeResponse> propertyList = new ArrayList<>();
List<GetPropertyRoomTypeResponse> otherProperties = new ArrayList<>();
properties.sort(Comparator.comparing(RoomCalendarService::getPropertyCalendarOrder));
for (CfgProperties property : properties) {
if (!isShowCalendar(property)) {
continue;
}
List<RoomType> roomTypes = buildRoomTypes(property, roomsByPropertyId);
String calendarName = StringUtils.defaultIfBlank(property.getCalendarName(), property.getName());
if (StringUtils.equalsIgnoreCase(property.getCategory(), "OPERA")
|| StringUtils.equalsIgnoreCase(property.getCategory(), "DAYLIGHT")) {
propertyList.add(buildPropertyRoomTypeResponse(calendarName, calendarName, null, roomTypes));
} else if (StringUtils.equalsIgnoreCase(property.getCategory(), "OTHER")) {
otherProperties.add(buildPropertyRoomTypeResponse(
calendarName,
calendarName,
StringUtils.defaultIfBlank(property.getName(), property.getCalendarName()),
roomTypes));
}
}
if (!otherProperties.isEmpty()) {
GetPropertyRoomTypeResponse otherGroup = buildPropertyRoomTypeResponse(
"OTHER", "Other Property", null, new ArrayList<>());
otherGroup.setDefaultRoomTypes(buildDefaultProperties(otherProperties));
otherGroup.setOtherProperties(otherProperties);
propertyList.add(otherGroup);
}
response.setPropertyList(propertyList);
response.setSuccess(true);
response.setCode("200");
return response;
}
private Map<String, List<RoomCalendarRoomProjection>> buildCalendarRoomsByPropertyId(List<CfgProperties> properties) {
List<String> propertyIds = new ArrayList<>();
for (CfgProperties property : properties) {
if (isShowCalendar(property) && property.getId() != null) {
propertyIds.add(String.valueOf(property.getId()));
}
}
Map<String, List<RoomCalendarRoomProjection>> roomsByPropertyId = new HashMap<>();
if (propertyIds.isEmpty()) {
return roomsByPropertyId;
}
for (RoomCalendarRoomProjection room : roomDao.queryCalendarRoomsByPropertyIds(propertyIds)) {
if (room == null || StringUtils.isBlank(room.getPropertyId())) {
continue;
}
roomsByPropertyId.computeIfAbsent(room.getPropertyId(), key -> new ArrayList<>()).add(room);
}
return roomsByPropertyId;
}
private static List<RoomType> buildRoomTypes(
CfgProperties property,
Map<String, List<RoomCalendarRoomProjection>> roomsByPropertyId) {
List<RoomCalendarRoomProjection> rooms = new ArrayList<>(
roomsByPropertyId.getOrDefault(String.valueOf(property.getId()), new ArrayList<>()));
rooms.sort(Comparator.comparing(RoomCalendarService::getRoomCalendarOrder));
List<RoomType> roomTypes = new ArrayList<>();
for (RoomCalendarRoomProjection room : rooms) {
String calendarName = StringUtils.defaultIfBlank(room.getCalendarName(), room.getName());
if (StringUtils.isBlank(calendarName)) {
continue;
}
RoomType existing = findRoomType(roomTypes, calendarName);
if (existing != null) {
if (isDefaultShowCalendar(room.getDefaultShowCalendar())) {
existing.setDefaultShowCalendar(1);
}
continue;
}
RoomType item = new RoomType();
item.setCode(calendarName);
item.setLabel(calendarName);
item.setDefaultShowCalendar(isDefaultShowCalendar(room.getDefaultShowCalendar()) ? 1 : 0);
roomTypes.add(item);
}
return roomTypes;
}
private static GetPropertyRoomTypeResponse buildPropertyRoomTypeResponse(
String code, String name, String displayName, List<RoomType> roomTypes) {
GetPropertyRoomTypeResponse item = new GetPropertyRoomTypeResponse();
item.setCode(StringUtils.defaultString(code));
item.setName(StringUtils.defaultString(name));
item.setDisplayName(displayName);
item.setRoomTypes(roomTypes);
item.setDefaultRoomTypes(buildDefaultRoomTypes(roomTypes));
return item;
}
private static List<String> buildDefaultRoomTypes(List<RoomType> roomTypes) {
List<String> defaults = new ArrayList<>();
for (RoomType roomType : roomTypes) {
if (defaults.size() >= 3) {
break;
}
if (isDefaultShowCalendar(roomType.getDefaultShowCalendar()) && StringUtils.isNotBlank(roomType.getCode())) {
defaults.add(roomType.getCode());
}
}
return defaults;
}
private static List<String> buildDefaultProperties(List<GetPropertyRoomTypeResponse> properties) {
List<String> defaults = new ArrayList<>();
for (GetPropertyRoomTypeResponse property : properties) {
if (defaults.size() >= 3) {
break;
}
if (property.getDefaultRoomTypes() != null
&& !property.getDefaultRoomTypes().isEmpty()
&& StringUtils.isNotBlank(property.getCode())) {
defaults.add(property.getCode());
}
}
return defaults;
}
static List<RoomCalendarQualification> parseRoomCalendarResponse(String responseContent) {
JSONObject resultObj = JSONObject.parseObject(responseContent);
if (!StringUtils.equals("OK", resultObj.getString("StatusCode"))) {
throw new IllegalArgumentException(StringUtils.defaultIfBlank(
resultObj.getString("StatusDescription"), "RequestRoomCalendar failed"));
}
JSONArray records = resultObj.getJSONArray("Records");
List<RoomCalendarQualification> result = new ArrayList<>();
if (records == null) {
return result;
}
for (int i = 0; i < records.size(); i++) {
JSONObject item = records.getJSONObject(i);
RoomCalendarQualification record = new RoomCalendarQualification();
record.setProperty(item.getString("Property"));
record.setRoomType(item.getString("RoomType"));
record.setDate(normalizeDate(item.getString("Date")));
record.setRoomCriteria(item.getString("RoomCriteria"));
record.setRoomCount(item.getInteger("RoomCount"));
record.setPropertyLeader(item.getString("PropertyLeader"));
record.setBookingDateQualificationFlag(item.getInteger("BookingDateQualificationFlag"));
result.add(record);
}
return result;
}
private static List<String> filterVisibleRoomTypes(List<String> requestedNames, List<CfgRooms> rooms, List<String> propertyIds) {
Set<String> propertyIdSet = new LinkedHashSet<>(propertyIds);
Set<String> visible = new LinkedHashSet<>();
for (String requestedName : requestedNames) {
for (CfgRooms room : rooms) {
if (StringUtils.equals(requestedName, room.getCalendarName())
&& isShowCalendar(room)
&& propertyIdSet.contains(room.getPropertyId())) {
visible.add(requestedName);
break;
}
}
}
return new ArrayList<>(visible);
}
private static CfgProperties findByCalendarName(List<CfgProperties> properties, String name) {
for (CfgProperties property : properties) {
if (StringUtils.equals(property.getCalendarName(), name)) {
return property;
}
}
return null;
}
private static RoomType findRoomType(List<RoomType> roomTypes, String code) {
for (RoomType roomType : roomTypes) {
if (StringUtils.equals(roomType.getCode(), code)) {
return roomType;
}
}
return null;
}
private static List<String> parseDelimitedValues(String value) {
List<String> values = new ArrayList<>();
for (String item : StringUtils.split(StringUtils.defaultString(value), ",")) {
if (StringUtils.isNotBlank(item)) {
values.add(StringUtils.trim(item));
}
}
return values;
}
private static String getRequiredString(Map<String, Object> params, String lowerKey, String upperKey) {
Object value = params.get(lowerKey);
if (value == null) {
value = params.get(upperKey);
}
if (value == null || StringUtils.isBlank(String.valueOf(value))) {
throw new IllegalArgumentException("Missing parameter: " + lowerKey);
}
return String.valueOf(value);
}
private static String getOptionalString(Map<String, Object> params, String lowerKey, String upperKey) {
Object value = params.get(lowerKey);
if (value == null) {
value = params.get(upperKey);
}
return value == null || StringUtils.isBlank(String.valueOf(value)) ? "" : String.valueOf(value);
}
private static String normalizeDate(String value) {
if (StringUtils.isBlank(value)) {
return "";
}
return value.length() >= 10 ? value.substring(0, 10) : value;
}
private static boolean isShowCalendar(CfgProperties property) {
return property != null && Integer.valueOf(1).equals(property.getShowCalendar());
}
private static boolean isShowCalendar(CfgRooms room) {
return room != null && Integer.valueOf(1).equals(room.getShowCalendar());
}
private static boolean isDefaultShowCalendar(Integer value) {
return Integer.valueOf(1).equals(value);
}
private static Integer getPropertyCalendarOrder(CfgProperties property) {
return property == null || property.getCalendarOrder() == null ? Integer.MAX_VALUE : property.getCalendarOrder();
}
private static Integer getRoomCalendarOrder(RoomCalendarRoomProjection room) {
return room == null || room.getCalendarOrder() == null ? Integer.MAX_VALUE : room.getCalendarOrder();
}
private static final class CalendarVisibilityCheck {
private final String errorCode;
private final String errorMessage;
private final String operaProperty;
private final String operaRoomType;
private final String daylightProperty;
private final String daylightRoomType;
private CalendarVisibilityCheck(String errorCode, String errorMessage,
String operaProperty, String operaRoomType,
String daylightProperty, String daylightRoomType) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.operaProperty = operaProperty;
this.operaRoomType = operaRoomType;
this.daylightProperty = daylightProperty;
this.daylightRoomType = daylightRoomType;
}
private static CalendarVisibilityCheck success(String operaProperty, String operaRoomType,
String daylightProperty, String daylightRoomType) {
return new CalendarVisibilityCheck(null, null, operaProperty, operaRoomType, daylightProperty, daylightRoomType);
}
private static CalendarVisibilityCheck failure(String errorCode, String errorMessage) {
return new CalendarVisibilityCheck(errorCode, errorMessage, null, null, null, null);
}
}
}