This commit is contained in:
Mauve
2026-09-28 10:28:04 +08:00
parent 5ad104bdd7
commit 3b6f0495a3
94 changed files with 2941 additions and 2975 deletions
@@ -2,8 +2,8 @@ package com.mgm.mcrm;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.persistence.autoconfigure.EntityScan;
import org.springframework.boot.web.server.servlet.context.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.jms.annotation.EnableJms;
@@ -16,11 +16,10 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@ComponentScan(basePackages="com.mgm.mcrm")
@EntityScan(basePackages="com.mgm.mcrm")
@EnableTransactionManagement
@ServletComponentScan
@ServletComponentScan
@EnableScheduling
@EnableAsync
@EnableJms
@EnableCaching
public class CRMMobileApplication{
public static void main( String[] args ) {
SpringApplication.run(CRMMobileApplication.class, args);
@@ -86,9 +86,11 @@ public class SSORestProcessController {
private boolean checkValidUrl(String requestUrl){
boolean isValid = NetworkUtil.isValidURL(requestUrl);
if(isValid){
if(!requestUrl.startsWith(loginCallbackUrl)
if(isValid){
String callbackHost = loginCallbackUrl.replace("/sso_callback/login","");
if(!requestUrl.startsWith(callbackHost)
&& !requestUrl.startsWith(adfsHost)){
LogUtil.info(SSORestProcessController.class,"Failed validate of valid url["+callbackHost+"]["+adfsHost+"]");
isValid =false;
}
}
@@ -128,7 +130,21 @@ public class SSORestProcessController {
String paraRelying = StringUtils.isNotBlank(request.getParameter("relyingParty"))?request.getParameter("relyingParty"):relyingParty;
String authorizedUrl = adfsHost+ "/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp="+paraRelying;
String requestClientId = request.getParameter("client_request_id");
Map<String,String> cookieValues = new HashMap<String,String>();
Map<String,String> cookieValues = new HashMap<String,String>();String origin = request.getHeader("Origin");
LogUtil.info(SSORestProcessController.class,"URI:"+request.getRequestURI()+",Origin:"+origin);
//
// String origin = request.getHeader("Origin");
String sanitizedOrigin = NetworkUtil.sanitizeCRLF(origin);
if(SysCommon.isAllowOriginSource(sanitizedOrigin)) {
response.setHeader("Access-Control-Allow-Origin", NetworkUtil.sanitizeCRLF(sanitizedOrigin));
}else {
LogUtil.warn(SSORestProcessController.class, "Origin of ["+origin+"] is not allowed");
response.setHeader("Access-Control-Allow-Origin","");
//
String errorMessage = HtmlUtils.htmlEscape(("Origin of ["+origin+"] is not allowed"));
response.sendError(401, errorMessage);
}
if(StringUtils.isBlank(requestClientId)) {
requestClientId = UUID.randomUUID().toString();
}
@@ -182,6 +198,7 @@ public class SSORestProcessController {
String redirectUrl = loginCallbackUrl+"?";
redirectUrl+=("error="+URLEncoder.encode(errorCode,"UTF-8"));
redirectUrl+=("&errorMessage="+URLEncoder.encode(errorMessage,"UTF-8"));
response.setHeader("Origin","MGM_CRM_APP");
response.sendRedirect(redirectUrl);
}else {
CookieStore cookieStore = new BasicCookieStore();
@@ -242,7 +259,7 @@ public class SSORestProcessController {
for(String cookieKey:cookieKeys) {
try {
String cookieVal = cookieValues.get(cookieKey);
LogUtil.info(SSORestProcessController.class,"Set Cookie ["+cookieKey+"]="+cookieVal);
//LogUtil.info(SSORestProcessController.class,"Set Cookie ["+cookieKey+"]="+cookieVal);
if(cookieSetting!=null && !cookieSetting.isEmpty()) {
Iterator<String> cookieSetKeys = cookieSetting.keySet().iterator();
while(cookieSetKeys.hasNext()) {
@@ -253,7 +270,7 @@ public class SSORestProcessController {
cookieDomain="";
}
for(String cookiePath:cookiePaths) {
BasicClientCookie cookie = new BasicClientCookie(cookieKey, cookieVal);
BasicClientCookie cookie = new BasicClientCookie(NetworkUtil.sanitizeCRLF(cookieKey), NetworkUtil.sanitizeCRLF(cookieVal));
try {
Date currentDate = new Date();
Date expiryDate = new Date(currentDate.getTime() + 1800 * 1000);
@@ -261,8 +278,8 @@ public class SSORestProcessController {
}catch(Exception ignored) {
}
cookie.setPath(cookiePath);
cookie.setDomain(cookieDomain);
cookie.setPath(NetworkUtil.sanitizeCRLF(cookiePath));
cookie.setDomain(NetworkUtil.sanitizeCRLF(cookieDomain));
cookie.setSecure(true);
cookie.setAttribute("httponly", "true");
cookieStore.addCookie(cookie);
@@ -363,7 +380,7 @@ public class SSORestProcessController {
extraHeaders.forEach((key, value) -> {
//LogUtil.info(SSORestProcessController.class,"Expend Header:"+key+" Value:"+value);
if(!"content-type".equalsIgnoreCase(key)){
request.getHeaders().add(key, NetworkUtil.sanitizeHeaderValue(value));
request.getHeaders().add(key, NetworkUtil.sanitizeCRLF(value));
}
});
}
@@ -524,7 +541,7 @@ public class SSORestProcessController {
LogUtil.info(SSORestProcessController.class,"Read Response Body Failed:"+err.getMessage());
}
String responseBody = stringBuilder.toString();
LogUtil.info(SSORestProcessController.class,"Response 200:["+responseBody+"]");
//LogUtil.info(SSORestProcessController.class,"Response 200:["+responseBody+"]");
responseBody = responseBody.replace("<head>", "<head>\n<base href=\""+this.adfsHost+"\">");
responseBody = responseBody.replace("//<![CDATA[", "").replace("//]]>", "");
@@ -614,7 +631,7 @@ public class SSORestProcessController {
resHeaders.forEach((key, value) -> {
try {
//LogUtil.info(SSORestProcessController.class,"Res Header:"+key+" Value:"+value);
response.setHeader(key, NetworkUtil.sanitizeHeaderValue(value));
response.setHeader(key, NetworkUtil.sanitizeCRLF(value));
}catch(Exception ignored) {
}
@@ -628,34 +645,36 @@ public class SSORestProcessController {
response.setHeader("Content-Length", Long.toString(contentLength));
StreamUtils.copy(outputData, response.getOutputStream());
}else if(Strings.CS.equals(nextStep, "Redirect")){
String redirectUrl = nextUrl;
String redirectUrl = NetworkUtil.validateAndSanitizeUrl(nextUrl);
if(!checkValidUrl(redirectUrl)){
throw new Exception("Invalid redirect url:"+redirectUrl);
}
if(StringUtils.isBlank(response.getHeader("Location"))) {
LogUtil.info(SSORestProcessController.class,"Redirect location:"+redirectUrl);
response.setHeader("Location", NetworkUtil.sanitizeHeaderValue(redirectUrl));
response.setHeader("Location", NetworkUtil.sanitizeCRLF(redirectUrl));
}
response.sendRedirect(redirectUrl);
}else {
String redirectUrl = callbackUrl+"?";
redirectUrl+=("errorCode="+URLEncoder.encode(errorCode,"UTF-8"));
redirectUrl+=("&errorMessage="+URLEncoder.encode(errorMessage,"UTF-8"));
redirectUrl+=("errorCode="+URLEncoder.encode(errorCode, StandardCharsets.UTF_8));
redirectUrl+=("&errorMessage="+URLEncoder.encode(errorMessage, StandardCharsets.UTF_8));
if(!checkValidUrl(redirectUrl)){
throw new Exception("Invalid redirect url:"+redirectUrl);
}
response.setHeader("Location", NetworkUtil.sanitizeHeaderValue(redirectUrl));
String saintUrl = NetworkUtil.validateAndSanitizeUrl(redirectUrl);
response.setHeader("Location", NetworkUtil.sanitizeCRLF(saintUrl));
response.setHeader("Content-Length","0");
LogUtil.info(SSORestProcessController.class,"Callback with ErrorCode:"+redirectUrl+" [errorMessage]:"+errorMessage);
response.sendRedirect(redirectUrl);
LogUtil.info(SSORestProcessController.class,"Callback with ErrorCode:"+saintUrl+" [errorMessage]:"+errorMessage);
response.sendRedirect(saintUrl);
}
}else {
String redirectUrl = callbackUrl+"?errorCode=Invalid_Result&errorMessage=Invalid_Result";
if(!checkValidUrl(redirectUrl)){
throw new Exception("Invalid redirect url:"+redirectUrl);
}
response.setHeader("Location", NetworkUtil.sanitizeHeaderValue(redirectUrl));
response.setHeader("Location", NetworkUtil.sanitizeCRLF(redirectUrl));
response.setHeader("Content-Length","0");
response.setHeader("Origin","MGM_CRM_APP");
response.sendRedirect(redirectUrl);
}
}
@@ -29,21 +29,9 @@ public interface ApprovalRoutingDao extends JpaRepository<CfgApprovalRouting, Lo
@Query(value="select * from cfg_approval_routing where id =?1",nativeQuery=true)
CfgApprovalRouting getById(Integer id);
@Query(value="select * from cfg_approval_routing where name =?1",nativeQuery=true)
CfgApprovalRouting getByName(String name);
List<CfgApprovalRouting> findByBookingStatus(String bookingStatus);
Integer countByBookingStatus(String bookingStatus);
Integer countByBookingStatusAndApproverId(String bookingStatus, String approverId);
CfgApprovalRouting getByBookingId(Long bookingId);
List<CfgApprovalRouting> findByBookingStatusAndApproverId(String ap, String userId);
@Query(value = "select * from cfg_approval_routing where booking_status = 'AP' and approver_id like concat('%', ?1, '%')", nativeQuery = true)
List<CfgApprovalRouting> getApprovalList(String userId);
@@ -50,11 +50,12 @@ import com.mgm.mcrm.common.dtos.BaseApiResponse;
import com.mgm.mcrm.common.dtos.EumnApprovalStatus;
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.common.dtos.mgm_api.ApprovalGamingDataResult;
import com.mgm.mcrm.common.dtos.mgm_api.ApproverRecordResult;
import com.mgm.mcrm.common.dtos.mgm_api.ApproverResult;
import com.mgm.mcrm.common.dtos.mgm_api.PlayerProfileEntry;
import com.mgm.mcrm.common.dtos.mgm_api.UserInfoApiRecord;
import com.mgm.mcrm.common.jms.BookingControlMsgSender;
import com.mgm.mcrm.common.services.MGMApiService;
import com.mgm.mcrm.common.services.MGMEsbApiService;
import com.mgm.mcrm.common.utils.DateTimeUtil;
import com.mgm.mcrm.common.utils.LogUtil;
import com.mgm.mcrm.common.utils.SendEmail;
@@ -63,6 +64,7 @@ import com.mgm.mcrm.logging.repositories.SysLogBookingDao;
import com.mgm.mcrm.logging.services.SysLogBookingService;
import com.mgm.mcrm.notification.models.Email;
import com.mgm.mcrm.notification.repositories.EmailDao;
import com.mgm.mcrm.player.dtos.request.TodoChangeDateRequest;
import com.mgm.mcrm.player.services.PlayerService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
@@ -100,7 +102,7 @@ public class ApprovalService {
@Resource
private RequestReasonDao requestReasonDao;
@Resource
private MGMApiService mgmApiService;
private MGMEsbApiService mgmEsbApiService;
@Resource
private PropertyDao propertyDao;
@Resource
@@ -188,9 +190,11 @@ public class ApprovalService {
}
try {
HttpResponseResult httpResult = mgmApiService.invokeGetApprover(playerId,bookingType,propertyName,roomCategory,checkInDate,checkOutDate,userId);
HttpResponseResult httpResult = mgmEsbApiService.invokeGetApprover(playerId,bookingType,propertyName,roomCategory,checkInDate,checkOutDate,userId);
try {
JSONObject rawResult = JSONObject.parseObject(httpResult.getResponseContent());
ApproverResult resultObj = JSONObject.parseObject(httpResult.getResponseContent(), ApproverResult.class, Feature.SupportNonPublicField,Feature.IgnoreNotMatch);
fillApproverListFromRawJson(resultObj, rawResult);
if(Strings.CS.equals(resultObj.getStatusCode(), "OK")) {
if (resultObj.getRecords() != null && !resultObj.getRecords().isEmpty()) {
response.setSuccess(true);
@@ -222,11 +226,39 @@ public class ApprovalService {
return response;
}
private void fillApproverListFromRawJson(ApproverResult resultObj, JSONObject rawResult) {
if (resultObj == null || resultObj.getRecords() == null || rawResult == null) {
return;
}
JSONArray rawRecords = rawResult.getJSONArray("Records");
if (rawRecords == null) {
return;
}
List<ApproverRecordResult> records = resultObj.getRecords();
int size = Math.min(records.size(), rawRecords.size());
for (int i = 0; i < size; i++) {
JSONObject rawRecord = rawRecords.getJSONObject(i);
if (rawRecord == null) {
continue;
}
records.get(i).setApproverList(rawRecord.get("ApproverList"));
}
}
public BaseApiResponse<ApprovalGamingDataResult> getApprovalData(String bookingId) throws Exception {
BaseApiResponse<ApprovalGamingDataResult> response = new BaseApiResponse<>();
ApprovalGamingDataResult approvalGamingData = new ApprovalGamingDataResult();
ApprovalGamingDataResult approvalGamingData;
try {
HttpResponseResult httpResult = mgmApiService.invokeGetApprovalData(bookingId);
// String bookingCategory = bookingDao.findCategoryById(Long.valueOf(bookingId));
// HttpResponseResult httpResult;
// if ("DAYLIGHT".equalsIgnoreCase(bookingCategory)) {
// httpResult = mgmApiService.invokeGetApprovalData(bookingId, 1);
// } else {
// httpResult = mgmApiService.invokeGetApprovalData(bookingId, 0);
// }
HttpResponseResult httpResult = mgmEsbApiService.invokeGetApprovalData(bookingId, 1);
try {
approvalGamingData = JSONObject.parseObject(httpResult.getResponseContent(), ApprovalGamingDataResult.class, Feature.SupportNonPublicField,Feature.IgnoreNotMatch);
if(StringUtils.equalsIgnoreCase(approvalGamingData.getStatusCode(),"OK")) {
@@ -722,7 +754,7 @@ public class ApprovalService {
LogUtil.info(ApprovalService.class,"Submit Approval.UserId:"+userId);
//相同 处理approvalRouting记录 并调用 Call OWS createbooking
approvalRouting.setBookingStatus("AA");
CfgApprovalRouting changeRecord = approvalRoutingDao.save(approvalRouting);
approvalRoutingDao.save(approvalRouting);
//处理Pending Approval Booking 记录
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
@@ -791,8 +823,14 @@ public class ApprovalService {
// 获取Property
CfgProperties properties = propertyDao.findById(originBooking.getPropertyId()).orElse(null);
Boolean isOverBook = this.checkIsOverbook(bookingView.getRoomId(), bookingView.getCheckinDate(),
bookingView.getCheckoutDate(), bookingView.getPropertyId(), bookingView.getBlockId());
Boolean isOverBook;
if ("DAYLIGHT".equalsIgnoreCase(bookingView.getPropertyCategory())) {
isOverBook = false;
} else {
isOverBook = this.checkIsOverbook(bookingView.getRoomId(), bookingView.getCheckinDate(),
bookingView.getCheckoutDate(), bookingView.getPropertyId(), bookingView.getBlockId());
}
Boolean isOtherOverBook = this.checkOtherIsOverbook(Math.toIntExact(originBooking.getRoomId()), originBooking.getCheckoutDate(),
originBooking.getCheckinDate(), originBooking.getPropertyId(), originBooking.getSegmentId());
@@ -812,6 +850,7 @@ public class ApprovalService {
// BookingsView 中 roomId/blockId 为 Long,Bookings 为 Integer,copyProperties 会跳过;View 无 bookingTypeId
newBooking.setApprovalBookingId(String.valueOf(originBooking.getId()));
newBooking.setCategory("OPERA");
if (originBookingView.getRoomId() != null) {
newBooking.setRoomId(originBookingView.getRoomId());
@@ -850,6 +889,7 @@ public class ApprovalService {
newBooking.setApprovalBookingId(String.valueOf(originBooking.getId()));
newBooking.setDateList(originBooking.getDateList());
newBooking.setMember(originBooking.getMember());
newBooking.setCategory("DAYLIGHT");
if (originBookingView.getRoomId() != null) {
newBooking.setRoomId(originBookingView.getRoomId());
@@ -889,6 +929,7 @@ public class ApprovalService {
email.setBookId(originBooking.getId());
email.setCreatedAt(creatdDate);
email.setCreatedBy(originBooking.getCreatedBy());
emailBook.setCategory("OTHER");
email = SendEmail.sendApprovalNewEmail(emailBook, originBookingView,email,userId,userName,true,false,emailAddress.getKeyValues());
if(email.getStatus()==1) {
originBooking.setApproveStatus("AA");
@@ -905,6 +946,7 @@ public class ApprovalService {
newBooking.setLastOperaStatus("PENDING");
newBooking.setApprovedBy(userName);
newBooking.setApprovedId(Long.valueOf(userId));
newBooking.setCategory("OTHER");
//获取other room status
CfgOtherRoomStatus roomStatus = roomStatusDao.findByStatusName("Pending");
if(roomStatus!=null) {
@@ -960,6 +1002,35 @@ public class ApprovalService {
response.setLogMessage("Send Email Failed");
response.setMessage("Send Email Failed");
}
}else if (Strings.CS.equals(properties.getCategory(),"DAYLIGHT")) {
//调用daylight接口去Extend Booking
BaseApiResponse<PlayerProfileEntry> findPlayerResult = playerService.findPlayerProfileByPlayerIdAndUserId(originBooking.getPlayerId(), userId);
if(findPlayerResult.isSuccess()) {
originBooking.setApproveStatus("AA");
bookingDao.save(originBooking);
}else{
response.setSuccess(false);
response.setCode("Player Profile Not Found");
}
//Directly send email when submit Approval Routing for daylight
BookingsView originBookingView = bookingViewDao.findById(Long.parseLong(originBooking.getApprovalBookingId()));
originBookingView = this.getEmailInfo(originBookingView,originBookingView.getCreatedBy()).getData();
Email email = new Email();
email.setBookId(originBooking.getId());
email.setCreatedAt(creatdDate);
email.setCreatedBy(originBooking.getCreatedBy());
email = SendEmail.sendApprovalExtendEmail(originBooking, originBookingView,email,userId,userName,bookingView,isOtherOverBook,emailAddress.getKeyValues());
if(email.getStatus()==1) {
emailDao.save(email);
response.setSuccess(true);
response.setData(approvalMapper.toSubmitApprovalResponse(originBooking));
}else{
response.setSuccess(false);
response.setMessage("Send Email Failed");
response.setLogMessage("Send Email Failed");
}
}else{
//send email instead of sync other booking
BookingsView originBookingView = bookingViewDao.findById(Long.parseLong(originBooking.getApprovalBookingId()));
@@ -12,6 +12,7 @@ import com.mgm.mcrm.common.utils.NetworkUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@@ -20,7 +21,6 @@ import java.util.List;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api")
public class CfgSettingController {
private static final List<String> PUBLIC_LOGIN_SETTING_KEYS = List.of("APP_MOCK_SSO", "APP_MOCK_TPD");
@@ -30,12 +30,12 @@ public class CfgSettingController {
@Resource
private SysSettingService sysSettingService;
@PostMapping(value = "/app/setting/get_calendar_setting", produces = "application/json;charset=UTF-8")
@PostMapping(value = "/app/setting/get_calendar_setting", produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
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")
@RequestMapping(value = "/web/setting/get_setting_by_key", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<CfgSettings>> getSettingByKey(HttpServletRequest request, @RequestBody CfgSettingQueryRequest params) throws Exception {
boolean isSuccess = false;
String processMessage="";
@@ -57,7 +57,7 @@ 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")
@PostMapping(value = "/web/setting/get_public_setting_by_key", produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<CfgSettings>> getPublicSettingByKey(HttpServletRequest request,
@RequestBody(required=false) CfgSettingQueryRequest params) throws Exception {
if (params == null || !"MACAU_STRING".equals(params.getKeyName())) {
@@ -66,7 +66,7 @@ public class CfgSettingController {
return getSettingByKey(request, params);
}
@PostMapping(value = "/system/sys_setting/get_public_login_settings", produces = "application/json;charset=UTF-8")
@PostMapping(value = "/system/sys_setting/get_public_login_settings", produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<SysSetting>>> getPublicLoginSettings(HttpServletRequest request) {
boolean internalNetwork = NetworkUtil.isMatchInternal(NetworkUtil.getClientIpAddr(request));
List<SysSetting> settings = new ArrayList<>();
@@ -80,7 +80,7 @@ public class CfgSettingController {
return ResponseEntity.ok(BaseApiResponse.ok("", settings));
}
@RequestMapping(value = "/system/sys_setting/get", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/system/sys_setting/get", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<SysSetting>> getSysSettingByKey(HttpServletRequest request, @RequestBody SysSettingQueryRequest queryFilter) {
BaseApiResponse<SysSetting> result = new BaseApiResponse<>();
//--
@@ -99,7 +99,7 @@ public class CfgSettingController {
}
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/system/sys_setting/get_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/system/sys_setting/get_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<SysSetting>>> getSysSettings(HttpServletRequest request, @RequestBody(required=false) SysSettingQueryRequest queryFilter) {
boolean isSuccess = false;
String processMessage="";
@@ -16,6 +16,7 @@ import com.mgm.mcrm.common.utils.LogUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@@ -24,14 +25,13 @@ import java.util.List;
import java.util.Map;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api")
public class ConfigController {
@Resource
private ConfigService configService;
@RequestMapping(value = "/app/config/property_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/config/property_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<CfgProperties>>> queryCfgPropertys(HttpServletRequest request, @RequestBody(required=true) PropertyQueryRequest queryFilter) {
BaseApiResponse<List<CfgProperties>> processResult = new BaseApiResponse<>();
//--
@@ -42,7 +42,7 @@ public class ConfigController {
return ResponseEntity.status(HttpStatus.OK).body(processResult);
}
@RequestMapping(value = "/app/config/room_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/config/room_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<CfgRooms>>> queryRoom(HttpServletRequest request, @RequestBody(required=true) RoomQueryRequest queryFilter) {
BaseApiResponse<List<CfgRooms>> processResult = new BaseApiResponse<>();
List<CfgRooms> listCfgRooms = configService.listRoom(queryFilter);
@@ -52,7 +52,7 @@ public class ConfigController {
return ResponseEntity.status(HttpStatus.OK).body(processResult);
}
@RequestMapping(value = "/app/config/room_type_list", produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/config/room_type_list", produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<CfgRoomTypes>>> queryRoomType(HttpServletRequest request,@RequestBody(required=true) RoomTypeQueryRequest queryFilter) {
BaseApiResponse<List<CfgRoomTypes>> processResult = new BaseApiResponse<>();
//--
@@ -62,7 +62,7 @@ public class ConfigController {
return ResponseEntity.status(HttpStatus.OK).body(processResult);
}
@RequestMapping(value = "/app/config/bed_type_list", produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/config/bed_type_list", produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<BedType>>> queryBedType(HttpServletRequest request,@RequestBody(required=true) BedTypeQueryRequest queryFilter) {
BaseApiResponse<List<BedType>> processResult = new BaseApiResponse<>();
//--
@@ -72,7 +72,7 @@ public class ConfigController {
return ResponseEntity.status(HttpStatus.OK).body(processResult);
}
@RequestMapping(value = "/app/config/special_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/config/special_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<CfgRoomFeatures>>> queryCfgRoomFeatures(HttpServletRequest request, @RequestBody(required=true) RoomFeatureQueryRequest queryFilter) {
BaseApiResponse<List<CfgRoomFeatures>> processResult = new BaseApiResponse<>();
//--
@@ -82,7 +82,7 @@ public class ConfigController {
return ResponseEntity.status(HttpStatus.OK).body(processResult);
}
@RequestMapping(value = "/app/config/criteria_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/config/criteria_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<Map<String,JSONObject>>> queryRoomCriteria(HttpServletRequest request, @RequestBody(required=true) RoomCriteriaQueryRequest queryParas) throws Exception {
BaseApiResponse<Map<String,JSONObject>> processResult = new BaseApiResponse<>();
//--
@@ -92,7 +92,7 @@ public class ConfigController {
return ResponseEntity.status(HttpStatus.OK).body(processResult);
}
@RequestMapping(value = "/app/config/setting_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/config/setting_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<CfgSettings>>> queryRoomSetting(HttpServletRequest request) {
BaseApiResponse<List<CfgSettings>> processResult = new BaseApiResponse<>();
//--
@@ -110,7 +110,7 @@ public class ConfigController {
return ResponseEntity.status(HttpStatus.OK).body(processResult);
}
@RequestMapping(value = "/app/config/available_room_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/config/available_room_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<HashSet<String>>> queryRoomCriteriaAvailableRoom(HttpServletRequest request, @RequestBody(required=true) AvailableRoomQueryRequest queryParas) {
BaseApiResponse<HashSet<String>> processResult = new BaseApiResponse<>();
//--
@@ -121,7 +121,7 @@ public class ConfigController {
return ResponseEntity.status(HttpStatus.OK).body(processResult);
}
@RequestMapping(value = "/app/config/is_extend_booking", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/config/is_extend_booking", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<Bookings>>> queryIsExtendBooking(HttpServletRequest request, @RequestBody(required=true) ExtendBookingQueryRequest queryParas) {
BaseApiResponse<List<Bookings>> processResult = new BaseApiResponse<>();
//--
@@ -132,7 +132,7 @@ public class ConfigController {
return ResponseEntity.status(HttpStatus.OK).body(processResult);
}
@RequestMapping(value = "/app/config/booking_type_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/config/booking_type_list", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<CfgBookingTypes>>> queryCfgBookingTypes(HttpServletRequest request) {
BaseApiResponse<List<CfgBookingTypes>> processResult = new BaseApiResponse<>();
List<CfgBookingTypes> listCfgBookingTypes = configService.listAllBookingType();
@@ -142,7 +142,7 @@ public class ConfigController {
return ResponseEntity.status(HttpStatus.OK).body(processResult);
}
@RequestMapping(value = "/app/config/get_waitlist_booking", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/config/get_waitlist_booking", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<Bookings>>> queryGetWaitlistBooking(HttpServletRequest request, @RequestBody(required=true) WaitlistBookingQueryRequest queryParas) throws Exception {
BaseApiResponse<List<Bookings>> processResult = new BaseApiResponse<>();
//--
@@ -224,14 +224,15 @@ public class ConfigService {
if(Strings.CS.equals(property.getCategory(), "OPERA")) isOpera = true;
if(Strings.CS.equals(property.getCategory(), "DAYLIGHT")) isDaylight = true;
if(room.getForWaitlist() != null && room.getForWaitlist()==1&&room.getForBooking()==0) isWaitlist = true;
if(isOpera||isWaitlist) {
if (isOpera) {
resultList = getOperaCriteria( blockId,sectionId, bookingTypeId, propertyId, roomId, bedTypeMasterGroupId,userId);
} else if (isDaylight) {
resultList = getDaylightCriteria( blockId,sectionId, bookingTypeId, propertyId, roomId, bedTypeMasterGroupId,userId);
} else {
resultList = getOtherCriteria( segmentId, sectionId, bookingTypeId, propertyId, roomId);
}
if(!resultList.isEmpty()) {
checkCriteriaBooking(resultList, playerId, userId, userName);
}
@@ -518,7 +519,7 @@ public class ConfigService {
List<BookingsView> bookingList = bookingViewDao.getCalendarBooking(endDate, playerId);
Set<Date> protectionPeriod = new HashSet();
Set<Date> protectionPeriod = new HashSet<>();
for(BookingsView book:bookingList) {
if(StringUtils.isEmpty(book.getLastOperaStatus())||
Strings.CS.equals(book.getLastOperaStatus(), "DUE_IN")||
@@ -532,14 +533,14 @@ public class ConfigService {
differentUser = !Strings.CS.equals(book.getCreatedByName(), userName);
}
if(enableProtection&&differentUser) {
if(Integer.valueOf(checkinProtection)>=0) {
for(int q=0;q<=Integer.valueOf(checkinProtection);q++) {
Date protectCheckin = DateTimeUtil.addDay( book.getCheckinDate(), Integer.valueOf(q));
if(Integer.parseInt(checkinProtection)>=0) {
for(int q = 0; q<=Integer.parseInt(checkinProtection); q++) {
Date protectCheckin = DateTimeUtil.addDay( book.getCheckinDate(), q);
protectionPeriod.add(protectCheckin);
}
}else {
for(int q=0;q>=Integer.valueOf(checkinProtection);q--) {
Date protectCheckin = DateTimeUtil.addDay( book.getCheckinDate(), Integer.valueOf(q));
for(int q = 0; q>=Integer.parseInt(checkinProtection); q--) {
Date protectCheckin = DateTimeUtil.addDay( book.getCheckinDate(), q);
protectionPeriod.add(protectCheckin);
}
}
@@ -32,6 +32,7 @@ import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Base64Util;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@@ -41,7 +42,6 @@ import java.util.List;
@Tag(name = "Authorization", description = "APIs for Authorization functions")
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api")
public class MobileLoginController {
@Resource
@@ -60,7 +60,7 @@ public class MobileLoginController {
private SysGroupPermissionService sysGroupPermissionService;
// 该方法用于模拟sso登录,生产环境下不适用
@RequestMapping(value = "/app/sso/mock_user_sso_login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/sso/mock_user_sso_login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<AccountLoginResponse> mockupUserLogin(HttpServletRequest request, HttpServletResponse response, @RequestBody(required=true) @Valid AccountLoginRequest accountLoginRequest) throws IOException {
AccountLoginResponse result = new AccountLoginResponse();
String userId = accountLoginRequest.getUserId();
@@ -109,7 +109,7 @@ public class MobileLoginController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/app/sso/user_sso_login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/sso/user_sso_login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SsoLoginResponse> userSsoLogin(HttpServletRequest request, HttpServletResponse response, @RequestBody(required=true) SsoLoginRequest ssoLoginRequest) throws IOException {
SsoLoginResponse result = new SsoLoginResponse();
LoginUserInfo loginUser= null;
@@ -191,7 +191,7 @@ public class MobileLoginController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
// 接入SSO的时候修改此方法
@RequestMapping(value = "/app/sso/get_sso_token_by_code", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/sso/get_sso_token_by_code", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SsoLoginResponse> getTokenByCode(HttpServletRequest request, HttpServletResponse response, @RequestBody(required=true) SsoLoginRequest ssoLoginRequest) {
String code = ssoLoginRequest.getCode();
boolean mockSSO = ssoLoginRequest.isMockSSO();
@@ -244,14 +244,14 @@ public class MobileLoginController {
}
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/app/me", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/me", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public HashMap<String, Object> verifyToken(HttpServletRequest request, HttpServletResponse response) {
HashMap<String, Object> objReturn = new HashMap<String, Object>();
// 这里可以return一些信息,每次刷新页面或者跳转页面的时候重新拿一次某些信息。
objReturn.put("status", 200);
return objReturn;
}
@RequestMapping(value = "/app/refresh_token", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/refresh_token", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<RefreshTokenResponse> refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
String isReNew = request.getParameter("isRenewRefreshToken");
@@ -276,7 +276,7 @@ public class MobileLoginController {
return result;
}
@RequestMapping(value = "/web/user/lookup", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/web/user/lookup", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<UserInfoApiRecord>> lookupUser(HttpServletRequest request, HttpServletResponse response,
@RequestBody UserLookupRequest params) throws Exception {
BaseApiResponse<UserInfoApiRecord> result = new BaseApiResponse<>();
@@ -304,7 +304,7 @@ public class MobileLoginController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/web/user/lookup_name", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/web/user/lookup_name", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<UserInfoApiRecord>>> lookupUserName(HttpServletRequest request, HttpServletResponse response,
@RequestBody UserLookupRequest params) throws Exception {
String userName = params.getUserName();
@@ -316,7 +316,7 @@ public class MobileLoginController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/web/user/check_approver", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/web/user/check_approver", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<CheckApproverResult>> checkApprover(HttpServletRequest request, HttpServletResponse response,
@RequestBody CheckApproverResult params) throws Exception {
BaseApiResponse<CheckApproverResult> result = new BaseApiResponse<>();
@@ -329,7 +329,7 @@ public class MobileLoginController {
userId = userId.replace("@mgm.mo", "");
}
if (StringUtils.isAnyEmpty(userId, userName, roomType, property)) {
if (StringUtils.isAnyEmpty(userId, roomType, property)) {
result.setSuccess(false);
result.setMessage("Miss parameter");
return ResponseEntity.status(HttpStatus.OK).body(result);
@@ -25,7 +25,7 @@ import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.common.dtos.mgm_api.CheckApproverResult;
import com.mgm.mcrm.common.dtos.mgm_api.UserInfoApiRecord;
import com.mgm.mcrm.common.dtos.mgm_api.UserInfoApiResult;
import com.mgm.mcrm.common.services.MGMApiService;
import com.mgm.mcrm.common.services.MGMEsbApiService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
@@ -40,7 +40,7 @@ public class MgmUserService {
private boolean calendarPermissionMockEnabled;
@Resource
private MGMApiService mgmApiService;
private MGMEsbApiService mgmEsbApiService;
@Resource
private PropertyDao propertyDao;
@Resource
@@ -61,7 +61,7 @@ public class MgmUserService {
public BaseApiResponse<UserInfoApiRecord> findUserInfoByUserId(String userId) {
BaseApiResponse<UserInfoApiRecord> result = new BaseApiResponse<>();
try {
HttpResponseResult httpResult = mgmApiService.invokeGetUserInfo(userId,"");
HttpResponseResult httpResult = mgmEsbApiService.invokeGetUserInfo(userId,"");
if(httpResult.getStatusCode()==200) {
try {
UserInfoApiResult resultObj = JSONObject.parseObject(httpResult.getResponseContent(),UserInfoApiResult.class,Feature.SupportNonPublicField,Feature.IgnoreNotMatch);
@@ -115,7 +115,7 @@ public class MgmUserService {
BaseApiResponse<List<UserInfoApiRecord>> result = new BaseApiResponse<>();
String userId = SysCommon.mgmApiMockup?"80001":"";
try {
HttpResponseResult httpResult = mgmApiService.invokeGetUserInfo(userId,userName);
HttpResponseResult httpResult = mgmEsbApiService.invokeGetUserInfo(userId,userName);
if(httpResult.getStatusCode()==200) {
try {
UserInfoApiResult resultObj = JSONObject.parseObject(httpResult.getResponseContent(),UserInfoApiResult.class,Feature.SupportNonPublicField,Feature.IgnoreNotMatch);
@@ -161,7 +161,7 @@ public class MgmUserService {
public BaseApiResponse<CheckApproverResult> checkApprover(String userId,String userName,String roomType,String property) {
BaseApiResponse<CheckApproverResult> result = new BaseApiResponse<>();
try {
HttpResponseResult httpResult = mgmApiService.invokeCheckApprover(userId,userName,roomType,property);
HttpResponseResult httpResult = mgmEsbApiService.invokeCheckApprover(userId,userName,roomType,property);
if(httpResult.getStatusCode()==200) {
try {
CheckApproverResult resultObj = JSONObject.parseObject(httpResult.getResponseContent(),CheckApproverResult.class,Feature.SupportNonPublicField,Feature.IgnoreNotMatch);
@@ -30,4 +30,7 @@ public class CfgMarketCodes implements Serializable {
@Column(name = "category")
private String category;
@Column(name = "property_id")
private Integer propertyId;
}
@@ -29,4 +29,7 @@ public class CfgRateCodes implements Serializable {
private String dlRatePlanId;
@Column(name = "category")
private String category;
@Column(name = "property_id")
private Integer propertyId;
}
@@ -14,7 +14,7 @@ public class CfgSourceCodes implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long id;
@Column(name="code")
private String code;
@Column(name="created_at")
@@ -27,4 +27,7 @@ public class CfgSourceCodes implements Serializable {
private String updatedBy;
@Column(name="dl_source_id")
private String dlSourceId;
@Column(name = "property_id")
private Integer propertyId;
}
@@ -31,4 +31,7 @@ public class CfgTiers implements Serializable {
private Date updatedAt;
@Column(name="updated_by")
private String updatedBy;
@Column(name = "property_id")
private Integer propertyId;
}
@@ -24,9 +24,6 @@ public interface RateCodeDao extends JpaRepository<CfgRateCodes, Long> {
@Modifying
@Query(value = " delete from cfg_rate_codes where id=?1 ",nativeQuery=true)
int deleteById(long id);
@Query(value="select * from cfg_rate_codes where id =?1",nativeQuery=true)
CfgRateCodes getById(long id);
List<CfgRateCodes> findByCodeAndCategory(String ratePlanCode, String category);
@@ -16,6 +16,7 @@ import java.util.List;
public interface SourceCodeDao extends JpaRepository<CfgSourceCodes, Long> {
CfgSourceCodes findById(long id);
@Query(value="select top(1) * from cfg_source_codes with (nolock) where dl_source_id=?1", nativeQuery=true)
CfgSourceCodes findByDlSourceId(String dlSourceId);
List<CfgSourceCodes> findAll(Specification<CfgSourceCodes> spec,Sort sort);
List<CfgRateCodes> findAll(Specification<CfgSourceCodes> spec);
@@ -10,10 +10,12 @@ import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface TierDao extends JpaRepository<CfgTiers, Long> {
CfgTiers findByTierNameAndCategory(String string, String category);
CfgTiers findByTierNameAndCategoryAndPropertyId(String string, String category, Long propertyId);
List<CfgTiers> findAll(Specification<CfgTiers> spec);
List<CfgTiers> findAll(Specification<CfgTiers> spec, Sort sort);
Page<CfgTiers> findAll(Specification<CfgTiers> spec, Pageable pageable);
CfgTiers findByDaylightTier(String daylightTier);
CfgTiers findByTierNameAndCategory(String string, String category);
}
@@ -0,0 +1,351 @@
package com.mgm.mcrm.basesetting.daylight.services;
import com.mgm.mcrm.basesetting.daylight.dtos.request.*;
import com.mgm.mcrm.basesetting.daylight.dtos.response.CompRuleResponse;
import com.mgm.mcrm.basesetting.daylight.dtos.response.RequestorApproverResponse;
import com.mgm.mcrm.basesetting.daylight.models.CfgCompPreset;
import com.mgm.mcrm.basesetting.daylight.models.CfgDaylightView;
import com.mgm.mcrm.basesetting.daylight.repositories.CompPresetDao;
import com.mgm.mcrm.common.dtos.BaseApiResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jspecify.annotations.NonNull;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
@Slf4j
@Service
public class CompRuleService {
@Resource
private DaylightApiService daylightApiService;
@Resource
private CompPresetDao compPresetDao;
public BaseApiResponse<String> createCompRule(
String dlPropertyId,
String dlAccountId,
CfgDaylightView roomOnly,
CfgDaylightView miscChargeOrExtend,
String startDate,
String endDate,
String miscCharge,
Integer category) {
if (category == 1) {
return createRoomOnlyCompRule(dlPropertyId, dlAccountId, roomOnly);
}
if (category == 2) {
return createRoomCompRule(dlPropertyId, dlAccountId, miscChargeOrExtend, miscCharge, category);
}
if (category == 3) {
return createExtendRoomOnlyCompRule(dlPropertyId, dlAccountId, roomOnly, startDate, endDate);
}
if (category == 4) {
return createExtendRoomCompRule();
}
return null;
}
private BaseApiResponse<String> createRoomOnlyCompRule(
String dlPropertyId,
String dlAccountId,
CfgDaylightView roomOnly
) {
return null;
}
private BaseApiResponse<String> createRoomCompRule(
String dlPropertyId,
String dlAccountId,
CfgDaylightView miscChargeOrExtend,
String miscCharge,
Integer category
) {
return null;
}
private BaseApiResponse<String> createExtendRoomOnlyCompRule(
String dlPropertyId,
String dlAccountId,
CfgDaylightView roomOnly,
String startDate,
String endDate) {
return null;
}
private BaseApiResponse<String> createExtendRoomCompRule(
) {
return null;
}
public BaseApiResponse<String> updateCompRule(
String dlPropertyId,
String dlAccountId,
String dlCompRuleId,
String startDate,
String endDate,
CfgDaylightView miscChargeOrExtend,
String miscCharge,
Integer category) {
if (category == 2) {
return updateRoomCompRule(dlPropertyId, dlAccountId, dlCompRuleId, startDate, endDate, miscChargeOrExtend, miscCharge);
}
if (category == 3) {
return updateExtendRoomOnlyCompRule(dlPropertyId, dlAccountId, dlCompRuleId, startDate, endDate, miscChargeOrExtend, miscCharge);
}
if (category == 4) {
}
BaseApiResponse<String> response = new BaseApiResponse<>();
response.setSuccess(false);
response.setMessage("Invalid category");
return response;
}
private BaseApiResponse<String> updateRoomCompRule(
String dlPropertyId,
String dlAccountId,
String dlCompRuleId,
String startDate,
String endDate,
CfgDaylightView miscChargeOrExtend,
String miscCharge
) {
UpdateCompRuleRequest updateCompRuleRequest = new UpdateCompRuleRequest();
BaseApiResponse<CompRuleResponse> compRuleResponse = daylightApiService.getDaylightCompRule(dlPropertyId, dlAccountId, dlCompRuleId);
if (!compRuleResponse.isSuccess() || compRuleResponse.getData() == null) {
BaseApiResponse<String> result = new BaseApiResponse<>();
result.setSuccess(false);
result.setMessage(compRuleResponse.getMessage());
return result;
}
CompRuleResponse crr = compRuleResponse.getData();
ComplimentaryRuleLimits crl =
getMiscChargeOrExtendCompRuleLimits(startDate, endDate, miscCharge, miscChargeOrExtend.getSoftLimit(), 2);
updateCompRuleRequest.setComplimentaryRuleLimits(crl);
return daylightApiService.updateDaylightCompRule(dlPropertyId, dlAccountId, dlCompRuleId, String.valueOf(crr.getVersion()), updateCompRuleRequest);
}
private BaseApiResponse<String> updateExtendRoomOnlyCompRule(
String dlPropertyId,
String dlAccountId,
String dlCompRuleId,
String startDate,
String endDate,
CfgDaylightView miscChargeOrExtend,
String miscCharge
) {
UpdateCompRuleRequest updateCompRuleRequest = new UpdateCompRuleRequest();
BaseApiResponse<CompRuleResponse> compRuleResponse = daylightApiService.getDaylightCompRule(dlPropertyId, dlAccountId, dlCompRuleId);
if (!compRuleResponse.isSuccess() || compRuleResponse.getData() == null) {
BaseApiResponse<String> result = new BaseApiResponse<>();
result.setSuccess(false);
result.setMessage(compRuleResponse.getMessage());
return result;
}
CompRuleResponse crr = compRuleResponse.getData();
ComplimentaryRuleLimits crl =
getMiscChargeOrExtendCompRuleLimits(startDate, endDate, miscCharge, miscChargeOrExtend.getSoftLimit(), 3);
updateCompRuleRequest.setComplimentaryRuleLimits(crl);
return daylightApiService.updateDaylightCompRule(dlPropertyId, dlAccountId, dlCompRuleId, String.valueOf(crr.getVersion()), updateCompRuleRequest);
}
// 使用BigDecimal来计算金额以保留精度 by Mauve 2026-07-22
private static BigDecimal calculateAmount(String amountStr, String percentStr) {
BigDecimal amount = new BigDecimal(amountStr);
BigDecimal percent = new BigDecimal(percentStr)
.divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP);
return amount.multiply(percent)
.setScale(2, RoundingMode.HALF_UP);
}
private static @NonNull ComplimentaryRuleLimits getMiscChargeOrExtendCompRuleLimits(
String startDate,
String endDate,
String miscCharge,
String daylightPercentage,
Integer category
) {
AmountLimit totalAmountLimit = new AmountLimit();
totalAmountLimit.setCurrency("MOP");
totalAmountLimit.setAmount(new BigDecimal(miscCharge.trim()));
AmountLimit softTotalAmountLimit = new AmountLimit();
softTotalAmountLimit.setCurrency("MOP");
softTotalAmountLimit.setAmount(calculateAmount(miscCharge.trim(), daylightPercentage));
ComplimentaryRuleLimits complimentaryRuleLimits = new ComplimentaryRuleLimits();
if (category == 2) {
complimentaryRuleLimits.setTotalAmountLimit(totalAmountLimit);
complimentaryRuleLimits.setSoftTotalAmountLimit(softTotalAmountLimit);
}
if (category == 3) {
CompRuleDateRange dateRange = new CompRuleDateRange();
dateRange.setStart(startDate);
dateRange.setEnd(endDate);
complimentaryRuleLimits.setDateRanges(List.of(dateRange));
}
return complimentaryRuleLimits;
}
/**
* TODO 暂时写死, 之后参数可能需要多加几个 by Mauve
* @param startDate
* @param endDate
* @return
*/
private static @NonNull ComplimentaryRuleLimits getComplimentaryRuleLimits(String startDate, String endDate) {
CompRuleDateRange dateRange = new CompRuleDateRange();
dateRange.setStart(startDate);
dateRange.setEnd(endDate);
ComplimentaryRuleLimits complimentaryRuleLimits = new ComplimentaryRuleLimits();
complimentaryRuleLimits.setDateRanges(List.of(dateRange));
return complimentaryRuleLimits;
}
private CreateCompRuleRequest buildRoomOnlyCompRuleRequest(
String profileId,
String startDate,
String endDate,
RequestorApproverResponse requestorApprover,
CfgDaylightView daylightView,
boolean setRuleLimits) {
CreateCompRuleRequest crr = new CreateCompRuleRequest();
crr.setComplimentaryTypeId(daylightView.getDlCompTypeId());
crr.setPaymentMethodTransactionCodeId(daylightView.getDlPaymentMethodCodeId());
crr.setExecutive(false);
crr.setDoNotIssueInvoice(false);
crr.setProfileId(profileId);
if(setRuleLimits) crr.setComplimentaryRuleLimits(getComplimentaryRuleLimits(startDate, endDate));
List<CfgCompPreset> compPresetList = compPresetDao.findAllByDaylightMappingId(daylightView.getId());
CfgCompPreset compPreset = compPresetList.getFirst();
crr.setComplimentaryAccountingPresetsIds(List.of(compPreset.getDlCompPresetId()));
crr.setJustification("");
crr.setRequestorId(requestorApprover.getId());
crr.setApproverId(requestorApprover.getId());
return crr;
}
private BaseApiResponse<CreateCompRuleRequest> buildMiscChargeOrExtendCompRuleRequest(
String profileId,
String startDate,
String endDate,
CfgDaylightView daylightView,
RequestorApproverResponse requestorApprover,
String miscCharge,
Integer category) {
BaseApiResponse<CreateCompRuleRequest> result = new BaseApiResponse<>();
if (daylightView == null) {
result.setSuccess(false);
result.setMessage("Daylight config is empty");
log.error("Daylight config is empty");
return result;
}
if (StringUtils.isBlank(daylightView.getDlCompTypeId())) {
result.setSuccess(false);
result.setMessage("Daylight comp type id is empty");
log.error("Daylight comp type id is empty");
return result;
}
if (StringUtils.isBlank(daylightView.getDlPaymentMethodCodeId())) {
result.setSuccess(false);
result.setMessage("Daylight payment method code id is empty");
log.error("Daylight payment method code id is empty");
return result;
}
List<String> capIds = new ArrayList<>();
if (CollectionUtils.isEmpty(daylightView.getCfgCompPresetList())) {
result.setSuccess(false);
result.setMessage("Daylight comp preset id is empty");
log.error("Daylight comp preset id is empty");
return result;
}
for (CfgCompPreset cfgCompPreset : daylightView.getCfgCompPresetList()) {
if (cfgCompPreset != null && StringUtils.isNotBlank(cfgCompPreset.getDlCompPresetId())) {
capIds.add(cfgCompPreset.getDlCompPresetId());
}
}
List<String> distinctCapIds = new ArrayList<>(new HashSet<>(capIds));
if (CollectionUtils.isEmpty(capIds)) {
result.setSuccess(false);
result.setMessage("Daylight comp preset id is empty");
log.error("Daylight comp preset id is empty");
return result;
}
CreateCompRuleRequest crr = new CreateCompRuleRequest();
crr.setComplimentaryTypeId(daylightView.getDlCompTypeId());
crr.setPaymentMethodTransactionCodeId(daylightView.getDlPaymentMethodCodeId());
crr.setExecutive(false);
crr.setDoNotIssueInvoice(false);
crr.setProfileId(profileId);
crr.setComplimentaryRuleLimits(getMiscChargeOrExtendCompRuleLimits(startDate, endDate, miscCharge, daylightView.getSoftLimit(), category));
crr.setComplimentaryAccountingPresetsIds(distinctCapIds);
crr.setJustification("");
crr.setRequestorId(requestorApprover.getId());
crr.setApproverId(requestorApprover.getId());
result.setSuccess(true);
result.setData(crr);
return result;
}
}
@@ -3,6 +3,7 @@ package com.mgm.mcrm.basesetting.daylight.services;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mgm.mcrm.authorization.services.MgmUserService;
import com.mgm.mcrm.basesetting.agebucket.models.SysAgebucket;
import com.mgm.mcrm.basesetting.agebucket.services.AgebucketService;
import com.mgm.mcrm.basesetting.daylight.dtos.request.*;
@@ -28,7 +29,9 @@ import com.mgm.mcrm.booking.repositories.BookingDao;
import com.mgm.mcrm.booking.services.BookingService;
import com.mgm.mcrm.common.dtos.BaseApiResponse;
import com.mgm.mcrm.common.dtos.HttpResult;
import com.mgm.mcrm.common.dtos.config.ApiGatewaySetting;
import com.mgm.mcrm.common.dtos.mgm_api.PlayerProfileEntry;
import com.mgm.mcrm.common.dtos.mgm_api.UserInfoApiRecord;
import com.mgm.mcrm.common.enums.EnumBookingStatus;
import com.mgm.mcrm.common.httpclient.HttpHeaderBuilder;
import com.mgm.mcrm.common.services.HttpService;
@@ -43,7 +46,6 @@ import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hc.core5.http.Header;
import org.jspecify.annotations.NonNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@@ -88,8 +90,11 @@ public class DaylightApiService {
@Resource
private CompPresetDao compPresetDao;
@Value("${daylight.system-id}")
private String dlSystemId;
@Resource
private ApiGatewaySetting apiGatewaySetting;
@Resource
private MgmUserService mgmUserService;
public BaseApiResponse<JSONObject> daylightUpsertReservationNew(ReservationRequestDTO requestDTO, String dlPropertyId) {
BaseApiResponse<JSONObject> result = new BaseApiResponse<>();
@@ -943,7 +948,7 @@ public class DaylightApiService {
cfgProperties.getDlPropertyId(), properties.size(), profileId);
try {
String url = "/api-gateway/profiles/v1/individual/"+profileId;
String url = "/api-gateway/profiles/v1/individual/" + profileId + "/up-to-date";
// 获取对应的值
Header[] headers = HttpHeaderBuilder.custom()
.contentType("application/json")
@@ -1083,7 +1088,7 @@ public class DaylightApiService {
JSONObject res = JSON.parseObject(responseData);
JSONArray bookings = res.getJSONArray("results");
log.info("[getBookingRecordByProfileId_Optimize] Property dlPropertyId={}, bookings array size={}", dlPropertyId, bookings != null ? bookings.size() : 0);
bookingList.addAll(convertBookingDtoList(bookings, dlPropertyId, playerId));
bookingList.addAll(convertBookingDtoList(bookings, dlPropertyId, playerId, property.getId()));
}
} catch (Exception e) {
log.error("[getBookingRecordByProfileId_Optimize] Exception while querying Daylight bookings, profileId={}, error={}", profileId, e.getMessage(), e);
@@ -1093,7 +1098,7 @@ public class DaylightApiService {
return bookingList;
}
public List<BookingDto> convertBookingDtoList(JSONArray bookings, String dlPropertyId, String playerId){
public List<BookingDto> convertBookingDtoList(JSONArray bookings, String dlPropertyId, String playerId, Long propertyId) {
List<BookingDto> bookingList = new ArrayList<>();
if(bookings==null || bookings.isEmpty()) {
log.info("[convertBookingDtoList] bookings is null or empty for dlPropertyId={}", dlPropertyId);
@@ -1155,6 +1160,7 @@ public class DaylightApiService {
booking.setDlGuaranteeTypeId(bookingRes.getString("guaranteeTypeId"));
booking.setDlProfileId(bookingRes.getString("profileId"));
booking.setDlBlockId(bookingRes.getString("blockId"));
booking.setPropertyId(propertyId);
JSONObject sc = bookingRes.getJSONObject("statusCode");
@@ -1178,6 +1184,12 @@ public class DaylightApiService {
String booker = valueJson.getString("Booker");
String approver = valueJson.getString("Approver");
BaseApiResponse<UserInfoApiRecord> userInfoRes = mgmUserService.findUserInfoByUserId(booker);
if(userInfoRes.isSuccess()) {
UserInfoApiRecord userInfo = userInfoRes.getData();
booking.setSectionId(userInfo.getSectionId());
}
if (StringUtils.isNotBlank(booker)) {
booking.setCreatedBy(booker);
booking.setBooker(booker);
@@ -1259,7 +1271,7 @@ public class DaylightApiService {
String lastName = profileObj.getDetails().getLastName();
if (lastName != null && firstName != null) {
sharerName = lastName + firstName;
sharerName = lastName + " " + firstName;
} else if (lastName != null) {
sharerName = lastName;
} else if (firstName != null) {
@@ -1466,6 +1478,7 @@ public class DaylightApiService {
String profileId,
String dlPropertyId,
String userId,
String roomName,
String startDate,
String endDate,
List<CfgDaylightView> daylightViewList,
@@ -1541,27 +1554,33 @@ public class DaylightApiService {
.build();
String approver = daylightViewRoomOnly.getApprover();
BaseApiResponse<RequestorApproverResponse> requestorApproverByUserId;
if (StringUtils.isNotEmpty(approver)) {
requestorApproverByUserId = getDaylightRequestorApproverByUserId(dlPropertyId, approver);
} else {
requestorApproverByUserId = getDaylightRequestorApproverByUserId(dlPropertyId, userId);
}
boolean isMansion = StringUtils.containsIgnoreCase(roomName, "mansion");
String requestorUserId = StringUtils.isNotEmpty(approver) && isMansion ? userId
: StringUtils.isNotEmpty(approver) ? approver : userId;
BaseApiResponse<RequestorApproverResponse> requestorResponse =
getDaylightRequestorApproverByUserId(dlPropertyId, requestorUserId);
BaseApiResponse<RequestorApproverResponse> approverResponse =
StringUtils.isNotEmpty(approver) && !isMansion
? requestorResponse
: StringUtils.isNotEmpty(approver)
? getDaylightRequestorApproverByUserId(dlPropertyId, approver)
: requestorResponse;
// 如果查不到 requestor/approver 直接返回 false
if (!requestorApproverByUserId.isSuccess()) {
if (!requestorResponse.isSuccess() || !approverResponse.isSuccess()) {
result.setSuccess(false);
result.setMessage(requestorApproverByUserId.getMessage());
result.setMessage(!requestorResponse.isSuccess()
? requestorResponse.getMessage() : approverResponse.getMessage());
return result;
}
RequestorApproverResponse returnData = requestorApproverByUserId.getData();
RequestorApproverResponse requestor = requestorResponse.getData();
RequestorApproverResponse approverData = approverResponse.getData();
if (createRoomOnlyCompRule && daylightViewRoomOnly != null) {
CreateCompRuleRequest roomOnlyCompRuleRequest = buildRoomOnlyCompRuleRequest(
profileId, startDate, endDate, returnData, daylightViewRoomOnly,false);
profileId, startDate, endDate, requestor, approverData, daylightViewRoomOnly,false);
BaseApiResponse<String> createDefaultResult = createCompRule(url, headers, roomOnlyCompRuleRequest);
if (!createDefaultResult.isSuccess()) {
return createDefaultResult;
@@ -1570,7 +1589,7 @@ public class DaylightApiService {
if (createDaylightViewCompRule) {
BaseApiResponse<CreateCompRuleRequest> daylightViewCompRuleRequest = buildDaylightViewCompRuleRequest(
profileId, startDate, endDate, daylightView, returnData, miscCharge);
profileId, startDate, endDate, daylightView, requestor, approverData, miscCharge);
if (!daylightViewCompRuleRequest.isSuccess()) {
result.setSuccess(false);
result.setMessage(daylightViewCompRuleRequest.getMessage());
@@ -1647,7 +1666,7 @@ public class DaylightApiService {
RequestorApproverResponse returnData = requestorApproverByUserId.getData();
CreateCompRuleRequest roomOnlyCompRuleRequest = buildRoomOnlyCompRuleRequest(
profileId, startDate, endDate, returnData, daylightViewRoomOnly,true);
profileId, startDate, endDate, returnData, returnData, daylightViewRoomOnly,true);
BaseApiResponse<String> createDefaultResult = createCompRule(url, headers, roomOnlyCompRuleRequest);
if (!createDefaultResult.isSuccess()) {
return createDefaultResult;
@@ -1671,7 +1690,8 @@ public class DaylightApiService {
String profileId,
String startDate,
String endDate,
RequestorApproverResponse requestorApprover,
RequestorApproverResponse requestor,
RequestorApproverResponse approver,
CfgDaylightView daylightView,
boolean setRuleLimits) {
CreateCompRuleRequest crr = new CreateCompRuleRequest();
@@ -1688,8 +1708,8 @@ public class DaylightApiService {
crr.setComplimentaryAccountingPresetsIds(List.of(compPreset.getDlCompPresetId()));
crr.setJustification("");
crr.setRequestorId(requestorApprover.getId());
crr.setApproverId(requestorApprover.getId());
crr.setRequestorId(requestor.getId());
crr.setApproverId(approver.getId());
return crr;
}
@@ -1699,7 +1719,8 @@ public class DaylightApiService {
String startDate,
String endDate,
CfgDaylightView daylightView,
RequestorApproverResponse requestorApprover,
RequestorApproverResponse requestor,
RequestorApproverResponse approver,
String miscCharge) {
BaseApiResponse<CreateCompRuleRequest> result = new BaseApiResponse<>();
@@ -1756,8 +1777,8 @@ public class DaylightApiService {
crr.setComplimentaryRuleLimits(getMiscChargeComplimentaryRuleLimits(startDate, endDate, miscCharge, daylightView.getSoftLimit()));
crr.setComplimentaryAccountingPresetsIds(distinctCapIds);
crr.setJustification("");
crr.setRequestorId(requestorApprover.getId());
crr.setApproverId(requestorApprover.getId());
crr.setRequestorId(requestor.getId());
crr.setApproverId(approver.getId());
result.setSuccess(true);
result.setData(crr);
@@ -2291,7 +2312,7 @@ public class DaylightApiService {
ReservationRequestDTO.ExternalIdDTO externalIdDTO
= new ReservationRequestDTO.ExternalIdDTO();
externalIdDTO.setSystemId(dlSystemId);
externalIdDTO.setSystemId(apiGatewaySetting.getDaylightSystemId());
externalIdDTO.setNumber(dlExternalNo);
map.put("externalIds", List.of(externalIdDTO));
@@ -27,6 +27,9 @@ public interface PropertyDao extends JpaRepository<CfgProperties, Long> {
@Query(value="select * from cfg_properties with (nolock) where hotel_code=?1",nativeQuery=true)
CfgProperties findByHotelCode(String hotelCode);
@Query(value="select top(1) * from cfg_properties with (nolock) where hotel_code=?1 and category=?2", nativeQuery=true)
CfgProperties findByHotelCodeAndCategory(String hotelCode, String category);
@Query(value="select * from cfg_properties with (nolock) where dl_property_id=?1",nativeQuery=true)
CfgProperties getByDlPropertyId(String propertyId);
@@ -31,4 +31,7 @@ public class CfgRoomTypes implements Serializable {
private String dlRoomTypeId;
@Column(name = "category")
private String category;
@Column(name = "property_id")
private Integer propertyId;
}
@@ -28,5 +28,5 @@ public interface RoomTypeDao extends JpaRepository<CfgRoomTypes, Long> {
@Query(value="select * from cfg_room_types where id =?1",nativeQuery=true)
CfgRoomTypes getById(Long id);
CfgRoomTypes findByDlRoomTypeId(String dlRoomTypeId);
CfgRoomTypes findByDlRoomTypeIdAndPropertyId(String dlRoomTypeId, Long propertyId);
}
@@ -58,7 +58,6 @@ import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api")
public class BookingController {
@@ -73,8 +72,6 @@ public class BookingController {
@Resource
private SysSettingService sysSettingService;
@Resource
private OperaService operaSerivce;
@Resource
private PlayerService playerService;
@Resource
private MgmUserService mgmUserService;
@@ -92,7 +89,7 @@ public class BookingController {
private SysGroupPermissionService sysGroupPermissionService;
@RequestMapping(value = "/app/booking/get_bookings_by_nameId", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/booking/get_bookings_by_nameId", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<Object>> getBookingsByNameId(HttpServletRequest request,
@RequestBody GetBookingByNameIdRequest params) {
Integer startIndex = params.getStartIndex();
@@ -157,7 +154,7 @@ public class BookingController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = {"/app/booking/get_opera_booking_by_conf", "/app/booking/get_booking_by_conf"}, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = {"/app/booking/get_opera_booking_by_conf", "/app/booking/get_booking_by_conf"}, method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<BookingsView>>> getBookingByConfirmationNo(HttpServletRequest request,
@RequestBody GetOperaBookingRequest params) throws Exception {
LoginUserInfo loginUser = SysCommon.parseUserFromToken(request);
@@ -204,7 +201,7 @@ public class BookingController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/app/booking/get_booking_by_id", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/booking/get_booking_by_id", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<BookingsView>>> getBookingById(
HttpServletRequest request,
@RequestBody GetBookingByIdRequest params) {
@@ -252,7 +249,7 @@ public class BookingController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/app/booking/get_bookings_by_groupId", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/booking/get_bookings_by_groupId", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<BookingsView>>> getBookingsByGroupId(
HttpServletRequest request,
@RequestBody GetBookingByGroupRequest params) {
@@ -265,7 +262,7 @@ public class BookingController {
}
@OperationLog(actionName="Create Booking", eventCode = "booking_create")
@RequestMapping(value = "/app/booking/create", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/booking/create", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<Bookings>>> createBooking(HttpServletRequest request, @RequestBody BookingDto booking) throws Exception {
LoginUserInfo loginUser = SysCommon.parseUserFromToken(request);
String userId = loginUser.getLoginId();
@@ -315,7 +312,7 @@ public class BookingController {
}
@OperationLog(actionName="Edit Booking", eventCode = "booking_edit")
@RequestMapping(value = "/app/booking/edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/booking/edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<Bookings>>> editBooking(HttpServletRequest request, @RequestBody BookingDto booking) throws Exception {
LoginUserInfo loginUser = SysCommon.parseUserFromToken(request);
String userId = loginUser.getLoginId();
@@ -366,7 +363,7 @@ public class BookingController {
}
@OperationLog(actionName="Cancel Waitlist Booking", eventCode = "waitlist_booking_cancel")
@RequestMapping(value = "/app/booking/cancel_waitlist", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/booking/cancel_waitlist", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<Bookings>> cancelWaitlistBooking(HttpServletRequest request,
@RequestBody BookingDto booking) {
BaseApiResponse<Bookings> result = new BaseApiResponse<>();
@@ -394,7 +391,6 @@ public class BookingController {
String token = request.getHeader("Authorization");
String userId = JWT.decode(token).getClaim("login_id").asString();
String groupName = JWT.decode(token).getClaim("group_name").asString();
BaseApiResponse<Bookings> serviceResult = bookingService.changeMiscCharge(bookingId,misCharge,userId);
if(serviceResult.isSuccess()) {
@@ -409,7 +405,7 @@ public class BookingController {
}
@OperationLog(actionName="Approve Waitlist Booking", eventCode = "waitlist_booking_approve")
@RequestMapping(value = "/app/booking/approve_waitlist", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/booking/approve_waitlist", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<Bookings>> approveWaitlistBooking(HttpServletRequest request,
@RequestBody BookingDto booking) {
BaseApiResponse<Bookings> result = new BaseApiResponse<>();
@@ -427,7 +423,7 @@ public class BookingController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/app/bookings/search_optimize", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/bookings/search_optimize", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<BookingDto>> recordSearchOptimize(HttpServletRequest request,
@RequestBody @Valid BookingSearchRequest searchRequest) throws Exception {
LogUtil.info(BookingService.class,"[recordSearch] start recordSearch ");
@@ -700,7 +696,7 @@ public class BookingController {
return allPropertiesResults;
}
@RequestMapping(value = "/web/booking/get_page", produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/web/booking/get_page", produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<DataTableResult<BookingsView>>> getBookingByPage(
HttpServletRequest request,
@RequestBody(required=true) BookingQueryRequest queryFilter) throws Exception {
@@ -750,7 +746,7 @@ public class BookingController {
return result;
}
@RequestMapping(value = "/web/bookings/search", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/web/bookings/search", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<BookingsView>> webRecordSearch(HttpServletRequest request, @RequestBody WebRecordSearchRequest params) throws Exception {
// requireAnyWebPermission(request, "00501_01", "00401_01", "00402_01");
List<BookingsView> list = getWebRecordSearch(request, params);
@@ -12,12 +12,12 @@ import com.mgm.mcrm.logging.services.SysLogOperationService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api")
public class WaitlistController {
@@ -27,7 +27,7 @@ public class WaitlistController {
private SysLogOperationService sysAuditLogService;
@OperationLog(eventCode="booking_update",actionName="Update Waitlist Booking Status")
@RequestMapping(value = "/web/waitlist/update_waitlist_status", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/web/waitlist/update_waitlist_status", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<Bookings>> updateWaitlistStatus(HttpServletRequest request,
@RequestBody Bookings booking) throws Exception {
BaseApiResponse<Bookings> result = new BaseApiResponse<>();
@@ -59,7 +59,7 @@ public class WaitlistController {
@OperationLog(eventCode="booking_update",actionName="Update Waitlist Batch Booking Status")
@RequestMapping(value = "/web/waitlist/update_batch_waitlist_status", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/web/waitlist/update_batch_waitlist_status", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<String[]>> updateBatchWaitlistStatus(HttpServletRequest request,
@RequestBody WebBatchUpdateWaitlistRequest params) throws Exception {
BaseApiResponse<String[]> result = new BaseApiResponse<>();
@@ -2,6 +2,7 @@ package com.mgm.mcrm.booking.dtos;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.mgm.mcrm.common.dtos.mgm_api.PlayerProfileEntry;
import lombok.Data;
@@ -21,10 +22,19 @@ public class BookingDto {
private String memberTitle;
private String memberFirstName;
private String memberLastName;
@JsonProperty("checkinDate")
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
private Date checkinDate;
@JsonProperty("checkoutDate")
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
private Date checkoutDate;
@JsonProperty("checkInDate")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date checkInDate;
@JsonProperty("checkOutDate")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date checkOutDate;
private Long propertyId;
private Long roomTypeId;
private String dlProfileId;
@@ -117,6 +127,7 @@ public class BookingDto {
private String roomEmailName;
private String eta;
private String etaTime;
private String guaranteeType;
private String changeCheckinDate;
private String changeCheckoutDate;
private String dlChannelId;
@@ -140,7 +151,7 @@ public class BookingDto {
private String dlPropertyId;
private String dlRoomTypeId;
private String specialCode;
private Integer DepositType;
private Integer depositType;
private Integer isPost;
private List<BookingDateEntry> extendDate;
private String checkInDateVal;
@@ -161,4 +172,18 @@ public class BookingDto {
private BookingCancelInfo cancelInfo;
private String miscCharge;
public void setCheckOOutDate(Date checkOOutDate) {
this.checkOutDate = checkOOutDate;
}
public Date getCheckOOutDate() {
return checkOutDate;
}
public void setCheckIInDate(Date checkIInDate) {
this.checkInDate = checkIInDate;
}
public Date getCheckIInDate() {
return checkInDate;
}
}
@@ -5,6 +5,7 @@ import com.mgm.mcrm.booking.enums.ProfileTierEnums;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.List;
@Data
@@ -53,18 +54,22 @@ public class IndividualDTO {
IndividualDTO.IndividualDetailsDTO newProfileDetail = new IndividualDTO.IndividualDetailsDTO();
IndividualDTO.MembershipDTO membershipDto = new IndividualDTO.MembershipDTO();
String[] s = playerName.split(" ");
String[] lastAndFirst = playerName.split(","); // lastname, firstname
if (s.length == 1) {
String theName = s[0];
String substring = theName.substring(0, 1);
String substring2 = theName.substring(1);
if (lastAndFirst.length == 1) {
lastAndFirst = lastAndFirst[0].split(","); // user可能输入了中文的逗号
}
newProfileDetail.setFirstName(substring2);
newProfileDetail.setLastName(substring);
if (lastAndFirst.length == 1) {
String theName = lastAndFirst[0];
String lastname = theName.substring(0, 1).trim();
String firstname = theName.substring(1).trim();
newProfileDetail.setFirstName(firstname);
newProfileDetail.setLastName(lastname);
} else {
newProfileDetail.setFirstName(s[0]);
newProfileDetail.setLastName(s[s.length - 1]);
newProfileDetail.setFirstName(lastAndFirst[1].trim());
newProfileDetail.setLastName(lastAndFirst[0].trim());
}
membershipDto.setNumber(playerId);
@@ -98,18 +103,22 @@ public class IndividualDTO {
IndividualDTO newProfileDto = new IndividualDTO();
IndividualDTO.IndividualDetailsDTO newProfileDetail = new IndividualDTO.IndividualDetailsDTO();
String[] s = playerName.split(" ");
String[] lastAndFirst = playerName.split(","); // lastname, firstname
if (s.length == 1) {
String theName = s[0];
String substring = theName.substring(0, 1);
String substring2 = theName.substring(1);
if (lastAndFirst.length == 1) {
lastAndFirst = lastAndFirst[0].split(","); // user可能输入了中文的逗号
}
newProfileDetail.setFirstName(substring2);
newProfileDetail.setLastName(substring);
if (lastAndFirst.length == 1) {
String theName = lastAndFirst[0];
String lastname = theName.substring(0, 1).trim();
String firstname = theName.substring(1).trim();
newProfileDetail.setFirstName(firstname);
newProfileDetail.setLastName(lastname);
} else {
newProfileDetail.setFirstName(s[0]);
newProfileDetail.setLastName(s[s.length - 1]);
newProfileDetail.setFirstName(lastAndFirst[1].trim());
newProfileDetail.setLastName(lastAndFirst[0].trim());
}
newProfileDto.setDetails(newProfileDetail);
@@ -86,4 +86,7 @@ public interface BookingMapper {
BookingDto changeDateRequestToDto(TodoChangeDateRequest request);
TodoChangeDateRequest bookingDtoToChangeRequest(BookingDto param);
@Mapping(target = "dateList", source = "dateList", qualifiedByName = "jsonToDateList")
TodoChangeDateRequest bookingToChangeRequest(Bookings param);
}
@@ -2,6 +2,7 @@ package com.mgm.mcrm.booking.models;
import jakarta.persistence.*;
import lombok.Data;
import java.sql.Date;
@@ -45,7 +46,7 @@ import java.sql.Date;
procedureName = "CheckDBConnection"
)
})
@Data
public class OperaDBBooking {
@Id
@@ -97,150 +98,7 @@ public class OperaDBBooking {
private String roomNo;
@Column(name="Is_Queue")
private String isQueue;
public String getConfirmationNo() {
return confirmationNo;
}
public void setConfirmationNo(String confirmationNo) {
this.confirmationNo = confirmationNo;
}
public String getRoomType() {
return roomType;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
public String getRoomTypeDesc() {
return roomTypeDesc;
}
public void setRoomTypeDesc(String roomTypeDesc) {
this.roomTypeDesc = roomTypeDesc;
}
public String getArrivalDate() {
return arrivalDate;
}
public void setArrivalDate(String arrivalDate) {
this.arrivalDate = arrivalDate;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getDepartureDate() {
return departureDate;
}
public void setDepartureDate(String departureDate) {
this.departureDate = departureDate;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public String getResvStatus() {
return resvStatus;
}
public void setResvStatus(String resvStatus) {
this.resvStatus = resvStatus;
}
public String getBlockCode() {
return blockCode;
}
public void setBlockCode(String blockCode) {
this.blockCode = blockCode;
}
public String getCurrentBalance() {
return currentBalance;
}
public void setCurrentBalance(String currentBalance) {
this.currentBalance = currentBalance;
}
public String getOperaProfileId() {
return operaProfileId;
}
public void setOperaProfileId(String operaProfileId) {
this.operaProfileId = operaProfileId;
}
public String getResvNameId() {
return resvNameId;
}
public void setResvNameId(String resvNameId) {
this.resvNameId = resvNameId;
}
public String getRateCode() {
return rateCode;
}
public void setRateCode(String rateCode) {
this.rateCode = rateCode;
}
public String getAdults() {
return adults;
}
public void setAdults(String adults) {
this.adults = adults;
}
public String getChildren() {
return children;
}
public void setChildren(String children) {
this.children = children;
}
public String getMarketSegment() {
return marketSegment;
}
public void setMarketSegment(String marketSegment) {
this.marketSegment = marketSegment;
}
public String getSourceCode() {
return sourceCode;
}
public void setSourceCode(String sourceCode) {
this.sourceCode = sourceCode;
}
public String getSourceName() {
return sourceName;
}
public void setSourceName(String sourceName) {
this.sourceName = sourceName;
}
public String getResort() {
return resort;
}
public void setResort(String resort) {
this.resort = resort;
}
public String getBooker() {
return booker;
}
public void setBooker(String booker) {
this.booker = booker;
}
public String getExpDate() {
return expDate;
}
public void setExpDate(String expDate) {
this.expDate = expDate;
}
public String getProfileExpDate() {
return profileExpDate;
}
public void setProfileExpDate(String profileExpDate) {
this.profileExpDate = profileExpDate;
}
public String getRoomNo() {
return roomNo;
}
public void setRoomNo(String roomNo) {
this.roomNo = roomNo;
}
public String getIsQueue() {
return isQueue;
}
public void setIsQueue(String isQueue) {
this.isQueue = isQueue;
}
@Column(name="Misc_Charge")
private String miscCharge;
}
@@ -83,15 +83,18 @@ public interface BookingDao extends JpaRepository<Bookings, Long> {
+ "and((checkin_date<=?4 and checkout_date>?4))and approve_status in('N') and section_id is not null",nativeQuery=true)
int getPickupBooking(Long propertyId,Long roomId,Long blockId,Date date);
@Query(value="select * from bookings where confirmation_no =?1 and approve_status not like '%W%' and approve_status != 'C' and property_id = ?2",nativeQuery=true)
@Query(value="select * from bookings where confirmation_no =?1 and approve_status = 'N' and property_id = ?2",nativeQuery=true)
Bookings getByConfNoForETA(String confNo,Long propertyId);
@Query(value = "select * from bookings where confirmation_no =?1", nativeQuery = true)
Bookings getByConfNo(String confNo);
@Query(value = "select Top(1) * from bookings where dl_external_no is not null and ltrim(rtrim(dl_external_no)) = ltrim(rtrim(?1)) order by id asc", nativeQuery = true)
@Query(value = "select Top(1) * from bookings where dl_external_no is not null and dl_external_no = ?1 order by id asc", nativeQuery = true)
Bookings getByDlExternalNo(String dlExternalNo);
@Query(value = "select Top(1) * from bookings where property_id is not null and confirmation_no = ?1 order by id asc", nativeQuery = true)
Bookings findFirstByConfirmationNoAndPropertyIdIsNotNull(String confirmationNo);
@Query(value = "select b.category from Bookings b where b.id = :id")
String findCategoryById(Long id);
}
File diff suppressed because it is too large Load Diff
@@ -39,7 +39,7 @@ import com.mgm.mcrm.common.dtos.data_import.booking.OtherBookingImportRow;
import com.mgm.mcrm.common.dtos.excel_model.ImportDefine;
import com.mgm.mcrm.common.dtos.mgm_api.*;
import com.mgm.mcrm.common.enums.EnumBookingStatus;
import com.mgm.mcrm.common.services.MGMApiService;
import com.mgm.mcrm.common.services.MGMEsbApiService;
import com.mgm.mcrm.common.utils.DateTimeUtil;
import com.mgm.mcrm.common.utils.ExcelUtils;
import com.mgm.mcrm.common.utils.LogUtil;
@@ -63,7 +63,7 @@ import java.util.*;
@Service
public class NonMGMBookingService {
@Resource
private MGMApiService mgmApiService;
private MGMEsbApiService mgmEsbApiService;
@Resource
private NonMGMBookingDao nonMgmBookingDao;
@Resource
@@ -170,6 +170,7 @@ public class OperaDBBookingService {
booking.setProfieExpDate(operaBook.getProfileExpDate());
booking.setRoomNo(operaBook.getRoomNo());
booking.setQueue(!StringUtils.isEmpty(operaBook.getIsQueue()));
booking.setMiscCharge(operaBook.getMiscCharge());
bookings.add(booking);
}
return bookings;
@@ -180,6 +181,8 @@ public class OperaDBBookingService {
for(int i= 0 ;i<books.size();i++) {
OperaDBBooking operaBook = books.get(i);
BookingDto booking = new BookingDto();
Date now = new Date();
booking.setCreatedAt(now);
booking.setConfirmationNo(operaBook.getConfirmationNo());
booking.setRoomTypeCode(operaBook.getRoomType());
booking.setEta(operaBook.getArrivalTime());
@@ -196,6 +199,8 @@ public class OperaDBBookingService {
booking.setProfieExpDate(operaBook.getProfileExpDate());
booking.setRoomNo(operaBook.getRoomNo());
booking.setQueue(!StringUtils.isEmpty(operaBook.getIsQueue()));
booking.setSourceCode(operaBook.getSourceCode());
booking.setMiscCharge(operaBook.getMiscCharge());
bookings.add(booking);
}
return bookings;
@@ -9,6 +9,7 @@ import com.mgm.mcrm.booking.models.Bookings;
import com.mgm.mcrm.booking.models.BookingsView;
import com.mgm.mcrm.booking.models.OWSTransactions;
import com.mgm.mcrm.common.constants.SysCommon;
import com.mgm.mcrm.common.dtos.config.ApiGatewaySetting;
import com.mgm.mcrm.common.utils.DateTimeUtil;
import com.mgm.mcrm.common.utils.LogUtil;
import com.mgm.mcrm.common.utils.SOAPUtil;
@@ -38,6 +39,8 @@ public class OperaService {
private OWSTransactionsService owsTransService;
@Autowired
private SysSettingService settingService;
@Resource
private ApiGatewaySetting apiGatewaySetting;
public JSONObject guestRequests(GuestRequestsRequest obj) throws Exception {
boolean owsLog = settingService.isDBDbugLog();
@@ -62,9 +65,9 @@ public class OperaService {
Date startTime = new Date();
Date endTime = new Date();
returnStr = SOAPUtil.getWebServiceSOAPUTF(SysCommon.apiConfig.getServerUrl_OWS() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#GuestRequests", sendSoapString);
LogUtil.info(OperaService.class, "[OperaService GuestRequests URL:]" + SysCommon.apiConfig.getServerUrl_OWS()
returnStr = SOAPUtil.getWebServiceSOAPUTF(apiGatewaySetting.getOperaProxyUrl() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#GuestRequests", sendSoapString, apiGatewaySetting);
LogUtil.info(OperaService.class, "[OperaService GuestRequests URL:]" + apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl http://webservices.micros.com/ows/5.1/Reservation.wsdl#GuestRequests");
endTime = new Date();
@@ -100,7 +103,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl;http://webservices.micros.com/ows/5.1/Reservation.wsdl#GuestRequests");
if (owsTrans.getSuccess() == 0) {
owsTrans.setErrorCode(resp.getResult().getOperaErrorCode());
@@ -141,12 +144,12 @@ public class OperaService {
Gson gson = new Gson();
LogUtil.info(OperaService.class, "[OperaService createBooking request string:]" + gson.toJson(sendSoapString));
Date startTime = new Date();
Date endTime = new Date();
returnStr = SOAPUtil.getWebServiceSOAP(SysCommon.apiConfig.getServerUrl_OWS() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#CreateBooking", sendSoapString);
LogUtil.info(OperaService.class, "[OperaService CreateBooking URL:]" + SysCommon.apiConfig.getServerUrl_OWS()
returnStr = SOAPUtil.getWebServiceSOAP(apiGatewaySetting.getOperaProxyUrl() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#CreateBooking", sendSoapString, apiGatewaySetting);
LogUtil.info(OperaService.class, "[OperaService CreateBooking URL:]" + apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl http://webservices.micros.com/ows/5.1/Reservation.wsdl#CreateBooking");
endTime = new Date();
Date endTime = new Date();
spanTime = DateTimeUtil.getTimeSpanSSS(startTime, endTime);
if (StringUtils.isNotBlank(returnStr)) {
SOAPMessage soapMessage = SOAPUtil.getSOAPMessageFromXMLString(returnStr);
@@ -195,7 +198,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl;http://webservices.micros.com/ows/5.1/Reservation.wsdl#CreateBooking");
if (owsTrans.getSuccess() == 0) {
owsTrans.setErrorCode(resp.getResult().getOperaErrorCode());
@@ -221,7 +224,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl;http://webservices.micros.com/ows/5.1/Reservation.wsdl#CreateBooking");
owsTrans.setErrorCode("400");
owsTrans.setErrorMessage("Bad Request");
@@ -261,9 +264,9 @@ public class OperaService {
Date startTime = new Date();
Date endTime = new Date();
returnStr = SOAPUtil.getWebServiceSOAP(SysCommon.apiConfig.getServerUrl_OWS() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking", sendSoapString);
LogUtil.info(OperaService.class, "[OperaService modifyBooking URL:]" + SysCommon.apiConfig.getServerUrl_OWS()
returnStr = SOAPUtil.getWebServiceSOAP(apiGatewaySetting.getOperaProxyUrl() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking", sendSoapString, apiGatewaySetting);
LogUtil.info(OperaService.class, "[OperaService modifyBooking URL:]" + apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking");
endTime = new Date();
spanTime = DateTimeUtil.getTimeSpanSSS(startTime, endTime);
@@ -313,7 +316,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl;http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking");
if (owsTrans.getSuccess() == 0) {
owsTrans.setErrorCode(resp.getResult().getOperaErrorCode());
@@ -355,9 +358,9 @@ public class OperaService {
Date startTime = new Date();
Date endTime = new Date();
returnStr = SOAPUtil.getWebServiceSOAP(SysCommon.apiConfig.getServerUrl_OWS() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#CombineShare", sendSoapString);
LogUtil.info(OperaService.class, "[OperaService CombineShareRequest URL:]" + SysCommon.apiConfig.getServerUrl_OWS()
returnStr = SOAPUtil.getWebServiceSOAP(apiGatewaySetting.getOperaProxyUrl() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#CombineShare", sendSoapString, apiGatewaySetting);
LogUtil.info(OperaService.class, "[OperaService CombineShareRequest URL:]" + apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl http://webservices.micros.com/ows/5.1/Reservation.wsdl#CombineShare");
endTime = new Date();
@@ -393,7 +396,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl;http://webservices.micros.com/ows/5.1/Reservation.wsdl#CombineShare");
if (owsTrans.getSuccess() == 0) {
owsTrans.setErrorCode(resp.getResult().getOperaErrorCode());
@@ -435,9 +438,9 @@ public class OperaService {
LogUtil.info(OperaService.class, "[OperaService cancelBooking request string:]" + gson.toJson(sendSoapString));
Date startTime = new Date();
Date endTime = new Date();
returnStr = SOAPUtil.getWebServiceSOAP(SysCommon.apiConfig.getServerUrl_OWS() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#CancelBooking", sendSoapString);
LogUtil.info(OperaService.class, "[OperaService CancelBooking URL:]" + "https://" + SysCommon.apiConfig.getServerUrl_OWS()
returnStr = SOAPUtil.getWebServiceSOAP(apiGatewaySetting.getOperaProxyUrl() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#CancelBooking", sendSoapString, apiGatewaySetting);
LogUtil.info(OperaService.class, "[OperaService CancelBooking URL:]" + "https://" + apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl http://webservices.micros.com/ows/5.1/Reservation.wsdl#CancelBooking");
endTime = new Date();
spanTime = DateTimeUtil.getTimeSpanSSS(startTime, endTime);
@@ -473,7 +476,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl;http://webservices.micros.com/ows/5.1/Reservation.wsdl#CancelBooking");
if (owsTrans.getSuccess() == 0) {
owsTrans.setErrorCode(resp.getResult().getOperaErrorCode());
@@ -498,7 +501,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl;http://webservices.micros.com/ows/5.1/Reservation.wsdl#CancelBooking");
owsTrans.setErrorCode("400");
owsTrans.setErrorMessage("Bad Request");
@@ -539,9 +542,9 @@ public class OperaService {
Date startTime = new Date();
Date endTime = new Date();
returnStr = SOAPUtil.getWebServiceSOAP(SysCommon.apiConfig.getServerUrl_OWS() + "/OWS_WS_51/Name.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Name.wsdl#InsertGuestCard", sendSoapString);
LogUtil.info(OperaService.class, "[OperaService insertGustCard URL:]" + SysCommon.apiConfig.getServerUrl_OWS()
returnStr = SOAPUtil.getWebServiceSOAP(apiGatewaySetting.getOperaProxyUrl() + "/OWS_WS_51/Name.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Name.wsdl#InsertGuestCard", sendSoapString, apiGatewaySetting);
LogUtil.info(OperaService.class, "[OperaService insertGustCard URL:]" + apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Name.asmx?wsdl http://webservices.micros.com/ows/5.1/Name.wsdl#InsertGuestCard");
endTime = new Date();
spanTime = DateTimeUtil.getTimeSpanSSS(startTime, endTime);
@@ -577,7 +580,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Name.asmx?wsdl;http://webservices.micros.com/ows/5.1/Name.wsdl#InsertGuestCard");
if (owsTrans.getSuccess() == 0) {
owsTrans.setErrorCode(resp.getResult().getOperaErrorCode());
@@ -602,7 +605,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Name.asmx?wsdl;http://webservices.micros.com/ows/5.1/Name.wsdl#InsertGuestCard");
owsTrans.setErrorCode("400");
owsTrans.setErrorMessage("Bad Request");
@@ -642,9 +645,9 @@ public class OperaService {
Date startTime = new Date();
Date endTime = new Date();
returnStr = SOAPUtil.getWebServiceSOAP(SysCommon.apiConfig.getServerUrl_OWS() + "/OWS_WS_51/Name.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Name.wsdl#UpdatePassport", sendSoapString);
LogUtil.info(OperaService.class, "[OperaService UpdatePassport URL:]" + SysCommon.apiConfig.getServerUrl_OWS()
returnStr = SOAPUtil.getWebServiceSOAP(apiGatewaySetting.getOperaProxyUrl() + "/OWS_WS_51/Name.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Name.wsdl#UpdatePassport", sendSoapString, apiGatewaySetting);
LogUtil.info(OperaService.class, "[OperaService UpdatePassport URL:]" + apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Name.asmx?wsdl http://webservices.micros.com/ows/5.1/Name.wsdl#UpdatePassport");
endTime = new Date();
spanTime = DateTimeUtil.getTimeSpanSSS(startTime, endTime);
@@ -680,7 +683,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Name.asmx?wsdl;http://webservices.micros.com/ows/5.1/Name.wsdl#UpdatePassport");
if (owsTrans.getSuccess() == 0) {
owsTrans.setErrorCode(resp.getResult().getOperaErrorCode());
@@ -705,7 +708,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Name.asmx?wsdl;http://webservices.micros.com/ows/5.1/Name.wsdl#UpdatePassport");
owsTrans.setErrorCode("400");
owsTrans.setErrorMessage("Bad Request");
@@ -745,9 +748,9 @@ public class OperaService {
Date startTime = new Date();
Date endTime = new Date();
returnStr = SOAPUtil.getWebServiceSOAP(SysCommon.apiConfig.getServerUrl_OWS() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking", sendSoapString);
LogUtil.info(OperaService.class, "[OperaService modifyBooking URL:]" + SysCommon.apiConfig.getServerUrl_OWS()
returnStr = SOAPUtil.getWebServiceSOAP(apiGatewaySetting.getOperaProxyUrl() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking", sendSoapString, apiGatewaySetting);
LogUtil.info(OperaService.class, "[OperaService modifyBooking URL:]" + apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking");
endTime = new Date();
spanTime = DateTimeUtil.getTimeSpanSSS(startTime, endTime);
@@ -787,7 +790,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl;http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking");
if (owsTrans.getSuccess() == 0) {
owsTrans.setErrorCode(resp.getResult().getOperaErrorCode());
@@ -813,7 +816,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl;http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking");
if (owsTrans.getSuccess() == 0) {
owsTrans.setErrorCode("400");
@@ -853,9 +856,9 @@ public class OperaService {
Date startTime = new Date();
Date endTime = new Date();
returnStr = SOAPUtil.getWebServiceSOAP(SysCommon.apiConfig.getServerUrl_OWS() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking", sendSoapString);
LogUtil.info(OperaService.class, "[OperaService modifyBooking URL:]" + SysCommon.apiConfig.getServerUrl_OWS()
returnStr = SOAPUtil.getWebServiceSOAP(apiGatewaySetting.getOperaProxyUrl() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking", sendSoapString, apiGatewaySetting);
LogUtil.info(OperaService.class, "[OperaService modifyBooking URL:]" + apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking");
endTime = new Date();
spanTime = DateTimeUtil.getTimeSpanSSS(startTime, endTime);
@@ -905,7 +908,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl;http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking");
if (owsTrans.getSuccess() == 0) {
owsTrans.setErrorCode(resp.getResult().getOperaErrorCode());
@@ -947,10 +950,10 @@ public class OperaService {
Date startTime = new Date();
Date endTime = new Date();
returnStr = SOAPUtil.getWebServiceSOAP(SysCommon.apiConfig.getServerUrl_OWS() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#FetchBooking", sendSoapString);
returnStr = SOAPUtil.getWebServiceSOAP(apiGatewaySetting.getOperaProxyUrl() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#FetchBooking", sendSoapString, apiGatewaySetting);
LogUtil.info(OperaService.class, "[OperaService getFetchBooking URL:]" + SysCommon.apiConfig.getServerUrl_OWS()
LogUtil.info(OperaService.class, "[OperaService getFetchBooking URL:]" + apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl http://webservices.micros.com/ows/5.1/Reservation.wsdl#FetchBooking");
//returnStr = obj.getResponseString();
@@ -1008,7 +1011,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl;http://webservices.micros.com/ows/5.1/Reservation.wsdl#FetchBooking");
if (owsTrans.getSuccess() == 0) {
owsTrans.setErrorCode(resp.getResult().getOperaErrorCode());
@@ -1135,9 +1138,9 @@ public class OperaService {
Date startTime = new Date();
returnStr = SOAPUtil.getWebServiceSOAP(SysCommon.apiConfig.getServerUrl_OWS() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking", sendSoapString);
LogUtil.info(OperaService.class, "[OperaService modifyBooking URL:]" + SysCommon.apiConfig.getServerUrl_OWS()
returnStr = SOAPUtil.getWebServiceSOAP(apiGatewaySetting.getOperaProxyUrl() + "/OWS_WS_51/Reservation.asmx?wsdl",
"http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking", sendSoapString, apiGatewaySetting);
LogUtil.info(OperaService.class, "[OperaService modifyBooking URL:]" + apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking");
Date endTime = new Date();
spanTime = DateTimeUtil.getTimeSpanSSS(startTime, endTime);
@@ -1177,7 +1180,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl;http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking");
if (owsTrans.getSuccess() == 0) {
owsTrans.setErrorCode(resp.getResult().getOperaErrorCode());
@@ -1203,7 +1206,7 @@ public class OperaService {
owsTrans.setUpdatedAt(endTime);
owsTrans.setRequest(sendSoapString.toString());
owsTrans.setResponse(returnStr);
owsTrans.setUrlAction(SysCommon.apiConfig.getServerUrl_OWS()
owsTrans.setUrlAction(apiGatewaySetting.getOperaProxyUrl()
+ "/OWS_WS_51/Reservation.asmx?wsdl;http://webservices.micros.com/ows/5.1/Reservation.wsdl#ModifyBooking");
if (owsTrans.getSuccess() == 0) {
owsTrans.setErrorCode("400");
@@ -32,7 +32,7 @@ import com.mgm.mcrm.common.dtos.EumnApprovalStatus;
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.common.dtos.mgm_api.*;
import com.mgm.mcrm.common.jms.BookingControlMsgSender;
import com.mgm.mcrm.common.services.MGMApiService;
import com.mgm.mcrm.common.services.MGMEsbApiService;
import com.mgm.mcrm.common.utils.DateTimeUtil;
import com.mgm.mcrm.common.utils.LogUtil;
import com.mgm.mcrm.common.utils.SendEmail;
@@ -55,7 +55,7 @@ import java.util.Set;
@Service
public class WaitlistBookingService {
@Resource
private MGMApiService mgmApiService;
private MGMEsbApiService mgmEsbApiService;
@Resource
private BookingViewDao bookViewDao;
@Resource
@@ -88,14 +88,13 @@ public class WaitlistBookingService {
private SettingService settingService;
@Resource
private PropertyDao propertyDao;
@Autowired
private BookingMapper bookingMapper;
@Autowired
private BookingMapper bookingMapper;
public List<BookingsView> getBookingsByPlayer(String playerId) throws Exception {
List<BookingsView> bookingList = new ArrayList<BookingsView>();
try {
HttpResponseResult httpResult = mgmApiService.invokeWaitlistBooking(playerId);
HttpResponseResult httpResult = mgmEsbApiService.invokeWaitlistBooking(playerId);
if(httpResult.getStatusCode()==200) {
try {
WaitlistBookingApiResult resultObj = JSONObject.parseObject(httpResult.getResponseContent(),WaitlistBookingApiResult.class,Feature.SupportNonPublicField,Feature.IgnoreNotMatch);
@@ -132,9 +131,9 @@ public class WaitlistBookingService {
}
public List<GamingData> getWaitlistData(String bookIds) throws Exception {
List<GamingData> gamingList = new ArrayList<GamingData>();
List<GamingData> gamingList = new ArrayList<>();
try {
HttpResponseResult httpResult = mgmApiService.invokeWaitlistData(bookIds, 0);
HttpResponseResult httpResult = mgmEsbApiService.invokeWaitlistData(bookIds, 1);
if(httpResult.getStatusCode()==200) {
try {
WaitlistDataApiResult resultObj = JSONObject.parseObject(httpResult.getResponseContent(),WaitlistDataApiResult.class,Feature.SupportNonPublicField,Feature.IgnoreNotMatch);
@@ -143,8 +142,7 @@ public class WaitlistBookingService {
if(Strings.CS.equals("OK", resultCode)) {
List<WaitlistDataRecord> recordList = resultObj.getRecords();
for(WaitlistDataRecord rec:recordList) {
GamingData gamingData = new GamingData();
gamingData = this.convertWaitlistDataRecord(rec);
GamingData gamingData = this.convertWaitlistDataRecord(rec);
if(gamingData.getBookId()!=null) {
gamingList.add(gamingData);
}
@@ -171,11 +169,11 @@ public class WaitlistBookingService {
public List<GamingData> syncWaitlistData(String bookIds) throws Exception {
List<GamingData> gamingList = new ArrayList<GamingData>();
gamingList = getWaitlistData(bookIds);
if(gamingList.size()>0) {
if(!gamingList.isEmpty()) {
for(GamingData gd:gamingList) {
List<GamingData> getGaming = gamingDataDao.findByBookId(gd.getBookId());
Date newDate = DateTimeUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss");
if(getGaming!=null&&getGaming.size()>0) {
if(getGaming!=null&& !getGaming.isEmpty()) {
if(getGaming.size()>1) {
gamingDataDao.deleteAll(getGaming);
gd.setCreatedAt(newDate);
@@ -403,12 +401,50 @@ public class WaitlistBookingService {
email = SendEmail.sendApprovalExtendEmail(emailBook, originBookingView, email, userId, userName, bookingView, isOtherOverBook, emailAddress.getKeyValues());
if (email.getStatus() == 1) {
originBooking.setApproveStatus("WA");
bookingDao.save(originBooking);
}
emailDao.save(email);
} else {
//Send mgm booking email
} else if (StringUtils.equalsIgnoreCase(newBookingProperty.getCategory(), "DAYLIGHT")) {
// The selected row is the waitlist extension. Extend the real booking
// referenced by waitlistId with the requested checkout date.
BaseApiResponse<PlayerProfileEntry> findPlayerResult = playerService
.findPlayerProfileByPlayerIdAndUserId(originBooking.getPlayerId(), userId);
if (!findPlayerResult.isSuccess() || findPlayerResult.getData() == null) {
processResult.setSuccess(false);
processResult.setMessage("Player profile not found for booking id: " + id);
return processResult;
}
BaseApiResponse<List<Bookings>> extendResult = bookingService
.extendDaylightWaitlistBooking(originBooking, findPlayerResult.getData(), userId, userName);
if (!extendResult.isSuccess()) {
processResult.setSuccess(false);
processResult.setMessage("Extend Daylight booking failed for booking id: " + id
+ ". " + StringUtils.defaultString(extendResult.getMessage()));
return processResult;
}
//Directly send email when submit Approval Routing for daylight
BookingsView originBookingView = bookingViewDao.findById(
originBooking.getWaitlistId()).orElse(null);
if (originBookingView == null) {
processResult.setSuccess(false);
processResult.setMessage("Original booking view not found for booking id: " + id);
return processResult;
}
originBookingView = this.getEmailInfo(originBookingView,originBookingView.getCreatedBy());
Email email = new Email();
email.setBookId(originBooking.getId());
email.setCreatedAt(creatdDate);
email.setCreatedBy(originBooking.getCreatedBy());
email = SendEmail.sendApprovalExtendEmail(originBooking, originBookingView,email,userId,userName,bookingView,isOtherOverBook,emailAddress.getKeyValues());
if(email.getStatus()==1) {
emailDao.save(email);
}
} else {
//Send mgm booking email
BookingsView originBookingView = bookingViewDao.findById(originBooking.getWaitlistId()).orElse(null);
assert originBookingView != null;
originBookingView = this.getEmailInfo(originBookingView, originBookingView.getCreatedBy());
@@ -429,7 +465,7 @@ public class WaitlistBookingService {
emailDao.save(email);
}
} else {
//If overbook send email
//If overbook send email
isOverBook = false;
if ((isOverBook && originBooking.getBlockId() != null) || (isOtherOverBook && originBooking.getSegmentId() != null)) {
Bookings emailBook = originBooking;
@@ -499,9 +535,7 @@ public class WaitlistBookingService {
email = SendEmail.sendApprovalNewEmail(emailBook, bookingView, email, userId, userName, false, true, emailAddress.getKeyValues());
emailDao.save(email);
}
}
}
}else if(Strings.CS.equals(status, "WR")||Strings.CS.equals(status, "WF")) {
@@ -0,0 +1,125 @@
package com.mgm.mcrm.common.config;
import com.mgm.mcrm.common.dtos.config.ApiGatewaySetting;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApiGatewayConfig {
@Value("${api-gateway.base-url}")
private String serverUrl;
@Value("${api-gateway.request-timeout-ms:60000}")
private int apiRequestTimeout;
//-- Daylight
@Value("${api-gateway.daylight.proxy-path}")
private String daylightProxyPath;
@Value("${api-gateway.daylight.app-id}")
private String daylightAppId;
@Value("${api-gateway.daylight.auth-code}")
private String daylightAppSecret;
@Value("${api-gateway.daylight.system-id}")
private String daylightSystemId;
//-- Opera
@Value("${api-gateway.opera.proxy-path}")
private String operaProxyPath;
@Value("${api-gateway.daylight.app-id}")
private String operaAppId;
@Value("${api-gateway.daylight.auth-code}")
private String operaAppSecret;
//-- ESB MCRM
@Value("${api-gateway.esb-mcrm.proxy-path}")
private String esbMcrmProxyPath;
@Value("${api-gateway.esb-mcrm.app-id}")
private String esbMcrmAppId;
@Value("${api-gateway.esb-mcrm.auth-code}")
private String esbMcrmAppSecret;
//-- ESB Limo
@Value("${api-gateway.esb-limo.proxy-path}")
private String esbLimoProxyPath;
@Value("${api-gateway.esb-limo.app-id}")
private String esbLimoAppId;
@Value("${api-gateway.esb-limo.auth-code}")
private String esbLimoAppSecret;
//-- Limo
@Value("${api-gateway.limo.proxy-path}")
private String limoProxyPath;
@Value("${api-gateway.limo.app-id}")
private String limoAppId;
@Value("${api-gateway.limo.auth-code}")
private String limoAppSecret;
@Value("${api-gateway.limo.main-handle-url}")
private String limoMainHandleUrl;
@Value("${api-gateway.limo.access-account}")
private String limoAccessAccount;
@Value("${api-gateway.limo.access-password}")
private String limoAccessPassword;
@Value("${api-gateway.limo.token-expiry-seconds:60}")
private int limoTokenExpirySeconds;
//-- Notification
@Value("${api-gateway.notification.proxy-path}")
private String notificationProxyPath;
@Value("${api-gateway.notification.app-id}")
private String notificationAppId;
@Value("${api-gateway.notification.auth-code}")
private String notificationAppSecret;
@Bean
public ApiGatewaySetting configApiGateway() {
ApiGatewaySetting config = new ApiGatewaySetting();
config.setBaseUrl(serverUrl);
config.setRequestTimeout(apiRequestTimeout);
config.setDaylightProxyUrl(serverUrl+daylightProxyPath);
config.setDaylightAppId(daylightAppId);
config.setDaylightAppSecret(daylightAppSecret);
config.setDaylightSystemId(daylightSystemId);
config.setOperaProxyUrl(serverUrl+operaProxyPath);
config.setOperaAppId(operaAppId);
config.setOperaAppSecret(operaAppSecret);
config.setEsbMcrmProxyUrl(serverUrl+esbMcrmProxyPath);
config.setEsbMcrmAppId(esbMcrmAppId);
config.setEsbMcrmAppSecret(esbMcrmAppSecret);
config.setEsbLimoProxyUrl(serverUrl+esbLimoProxyPath);
config.setEsbLimoAppId(esbLimoAppId);
config.setEsbLimoAppSecret(esbLimoAppSecret);
config.setLimoProxyUrl(serverUrl+limoProxyPath);
config.setLimoAppId(limoAppId);
config.setLimoAppSecret(limoAppSecret);
config.setLimoMainHandleUrl(limoMainHandleUrl);
config.setLimoAccessAccount(limoAccessAccount);
config.setLimoAccessPassword(limoAccessPassword);
config.setLimoTokenExpirySecond(limoTokenExpirySeconds);
config.setNotificationProxyUrl(serverUrl+notificationProxyPath);
config.setNotificationAppId(notificationAppId);
config.setNotificationAppSecret(notificationAppSecret);
//--
return config;
}
}
@@ -4,11 +4,11 @@ import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.boot.hibernate.autoconfigure.HibernateProperties;
import org.springframework.boot.hibernate.autoconfigure.HibernateSettings;
import org.springframework.boot.jpa.EntityManagerFactoryBuilder;
import org.springframework.boot.jpa.autoconfigure.JpaProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@@ -51,7 +51,7 @@ public class MGMDataSourceConfig {
@Primary
@Bean(name = "entityManagerFactory") //mrbs实体工厂
public LocalContainerEntityManagerFactoryBean entityManagerFactory (@Qualifier("mgmDataSource") DataSource mgmDataSource,
@Qualifier("mgmJpaProperties") JpaProperties jpaProperties,EntityManagerFactoryBuilder builder) {
@Qualifier("mgmJpaProperties") JpaProperties jpaProperties, EntityManagerFactoryBuilder builder) {
return builder.dataSource(mgmDataSource)
.properties(jpaProperties.getProperties())
.properties(
@@ -4,11 +4,11 @@ import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.boot.hibernate.autoconfigure.HibernateProperties;
import org.springframework.boot.hibernate.autoconfigure.HibernateSettings;
import org.springframework.boot.jpa.EntityManagerFactoryBuilder;
import org.springframework.boot.jpa.autoconfigure.JpaProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@@ -46,7 +46,7 @@ public class OperaDataSourceConfig {
@Bean(name = "entityManagerFactoryOpera")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryOpera (@Qualifier("operaDataSource") DataSource operaDataSource,
@Qualifier("operaJpaProperties") JpaProperties jpaProperties,EntityManagerFactoryBuilder builder) {
@Qualifier("operaJpaProperties") JpaProperties jpaProperties, EntityManagerFactoryBuilder builder) {
return builder.dataSource(operaDataSource)
.properties(jpaProperties.getProperties())
.properties(
@@ -46,14 +46,13 @@ public class SysCommon {
//for stress test
public static int tokenExpMin = 5;
public static int refreshTokenExpDay = 30;
public static String tokenSecret = "SecretKeyWhichShouldBeLongEnoughToBeSecure67848563";
public static APIConfig apiConfig = new APIConfig();
private static Map<String,String> notifyTemplateMap = new HashMap<String,String>();
private static Map<String,AppServerState> appServerStates = new HashMap<String,AppServerState>();
private static List<String> allowOriginSource = new ArrayList<String>();
private static List<String> soapServers = new ArrayList<String>();
private static List<String> httpApiServers = new ArrayList<String>();
private static List<String> allowIPSource = new ArrayList<String>();
private static final Map<String,AppServerState> appServerStates = new HashMap<String,AppServerState>();
private static final List<String> allowOriginSource = new ArrayList<String>();
private static final List<String> soapServers = new ArrayList<String>();
private static final List<String> httpApiServers = new ArrayList<String>();
private static final List<String> allowIPSource = new ArrayList<String>();
// @Autowired
private static MessageSource messageSource;
@@ -67,7 +66,7 @@ public class SysCommon {
runtime_path = getSystemPath();
}
public static boolean loadSystemConfig() {
public static void loadSystemConfig() {
boolean isLoaded = true;
Properties props = new Properties();
try {
@@ -87,7 +86,6 @@ public class SysCommon {
props.clear();
props = null;
}
return isLoaded;
}
public static void loadSettingsFromDB(List<SysSetting> sysSettings) {
@@ -384,42 +382,8 @@ public class SysCommon {
}
// Load API Config
public static boolean loadAPIConfig(Properties props) {
public static void loadAPIConfig(Properties props) {
boolean isLoaded = true;
// ESB
SysCommon.apiConfig.setServerUrl_ESB(props.getProperty("esb_server", ""));
SysCommon.apiConfig.setApiKey_ESB(props.getProperty("esb_app_id", ""));
SysCommon.apiConfig.setApiSecret_ESB(props.getProperty("esb_app_secret", ""));
try {
SysCommon.apiConfig.setTimeout_ESB(Integer.parseInt(props.getProperty("esb_request_timeout", "30000")));
} catch (Exception err) {
SysCommon.apiConfig.setTimeout_ESB(0);
}
// OWS
SysCommon.apiConfig.setServerUrl_OWS(props.getProperty("ows_server", ""));
try {
SysCommon.apiConfig.setTimeout_OWS(Integer.parseInt(props.getProperty("ows_request_timeout", "30000")));
} catch (Exception err) {
SysCommon.apiConfig.setTimeout_OWS(0);
}
// RPA
SysCommon.apiConfig.setServerLoginUrl_RPA(props.getProperty("rpa_login_server", ""));
SysCommon.apiConfig.setApiAccessName_RPA(props.getProperty("rpa_username", ""));
SysCommon.apiConfig.setApiAccessPassword_RPA(props.getProperty("rpa_password", ""));
SysCommon.apiConfig.setApiAccessKey_RPA(props.getProperty("rpa_apiKey", ""));
SysCommon.apiConfig.setServerAddUrl_RPA(props.getProperty("rpa_add_server", ""));
SysCommon.apiConfig.setServerExtensionUrl_RPA(props.getProperty("rpa_extension_server", ""));
// SSO
SysCommon.apiConfig.setServerUrl_SSO(props.getProperty("idp_server", ""));
SysCommon.apiConfig.setClientId_SSO(props.getProperty("idp_client_id", ""));
SysCommon.apiConfig.setClientSecret_SSO(props.getProperty("idp_client_secret", ""));
//SMS Config
SysCommon.apiConfig.setTokenUrl_SMS(props.getProperty("sms_token_url", ""));
SysCommon.apiConfig.setSendUrl_SMS(props.getProperty("sms_send_url", ""));
SysCommon.apiConfig.setUsername_SMS(props.getProperty("sms_username", ""));
SysCommon.apiConfig.setPassword_SMS(props.getProperty("sms_password", ""));
SysCommon.apiConfig.setAccount_SMS(props.getProperty("sms_account", ""));
SysCommon.apiConfig.setPriority_SMS(props.getProperty("sms_priority", ""));
//SMS Config
SysCommon.apiConfig.setPort_SMTP(props.getProperty("mail_port", ""));
SysCommon.apiConfig.setHost_SMTP(props.getProperty("mail_smtp_host", ""));
@@ -428,7 +392,6 @@ public class SysCommon {
SysCommon.apiConfig.setSend_to_SMTP(props.getProperty("mail_send_to", ""));
LogUtil.info(SysCommon.class, "Loaded API config.");
return isLoaded;
}
//-- Path Type 1= Class path 2=Application path 3=URI Path
@@ -6,53 +6,7 @@ import lombok.Data;
public class APIConfig {
private boolean isLoaded = false;
//-- ESB Server
private String serverUrl_ESB= "";
private String apiKey_ESB="";
private String apiSecret_ESB="";
private int timeout_ESB=0;
private String limoService_ESB="";
private String limoApp_id="";
private String limoApp_key="";
private String serverUrl_ESB_Daylight="";
private String apiKey_ESB_Daylight="";
private String apiSecret_ESB_Daylight="";
private int timeout_ESB_Daylight=0;
//-- OWS Server
private String serverUrl_OWS= "";
private int timeout_OWS=0;
//-- RPA Server
private String serverLoginUrl_RPA= "";
private String apiAccessName_RPA="";
private String apiAccessPassword_RPA="";
private String apiAccessKey_RPA="";
private String serverAddUrl_RPA= "";
private String serverExtensionUrl_RPA= "";
private int timeout_RPA=0;
//-- SSO Server
private String serverUrl_SSO= "";
private String clientId_SSO="";
private String clientSecret_SSO="";
private int timeout_SSO=0;
//-- CallCenter Server
private String serverUrl_CallCenter= "";
private int timeout_CallCenter=0;
//SMS Config
private String tokenUrl_SMS= "";
private String sendUrl_SMS= "";
private String username_SMS= "";
private String password_SMS= "";
private String account_SMS= "";
private String priority_SMS= "";
//SMTP Config
private String port_SMTP= "";
private String host_SMTP= "";
@@ -0,0 +1,32 @@
package com.mgm.mcrm.common.dtos.config;
import lombok.Data;
@Data
public class ApiGatewaySetting {
private String baseUrl;
private int requestTimeout=30000;
private String daylightProxyUrl;
private String daylightSystemId;
private String daylightAppId;
private String daylightAppSecret;
private String operaProxyUrl;
private String operaAppId;
private String operaAppSecret;
private String esbMcrmProxyUrl;
private String esbMcrmAppId;
private String esbMcrmAppSecret;
private String esbLimoProxyUrl;
private String esbLimoAppId;
private String esbLimoAppSecret;
private String limoProxyUrl;
private String limoAppId;
private String limoAppSecret;
private String limoMainHandleUrl;
private String limoAccessAccount;
private String limoAccessPassword;
private int limoTokenExpirySecond;
private String notificationProxyUrl;
private String notificationAppId;
private String notificationAppSecret;
}
@@ -1,25 +1,32 @@
package com.mgm.mcrm.common.dtos.mgm_api;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ApproverRecord {
private String EmployeeId = null;
private String EmployeeName = null;
@JSONField(name = "EmployeeId")
@JsonProperty("employeeId")
private String employeeId = null;
@JSONField(name = "EmployeeName")
@JsonProperty("employeeName")
private String employeeName = null;
public String getEmployeeId() {
return EmployeeId;
return employeeId;
}
public void setEmployeeId(String employeeId) {
EmployeeId = employeeId;
this.employeeId = employeeId;
}
public String getEmployeeName() {
return EmployeeName;
return employeeName;
}
public void setEmployeeName(String employeeName) {
EmployeeName = employeeName;
this.employeeName = employeeName;
}
}
@@ -2,6 +2,8 @@ package com.mgm.mcrm.common.dtos.mgm_api;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
@@ -9,73 +11,117 @@ import java.util.List;
public class ApproverRecordResult {
private String PlayerId = null;
private String BookingType = null;
private String Property = null;
private String RoomCategory = null;
private String StartDate = null;
private String EndDate = null;
private String ApprovalRoutingType = null;
private String ApprovalRoutingMessage = null;
private Object ApproverList;
@JSONField(name = "PlayerId")
private String playerId = null;
@JSONField(name = "BookingType")
private String bookingType = null;
@JSONField(name = "Property")
private String property = null;
@JSONField(name = "RoomCategory")
private String roomCategory = null;
@JSONField(name = "StartDate")
private String startDate = null;
@JSONField(name = "EndDate")
private String endDate = null;
@JSONField(name = "ApprovalRoutingType")
private String approvalRoutingType = null;
@JSONField(name = "ApprovalRoutingMessage")
private String approvalRoutingMessage = null;
@JSONField(name = "ApproverList")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Object approverListRaw;
public String getPlayerId() {
return PlayerId;
return playerId;
}
public void setPlayerId(String playerId) {
PlayerId = playerId;
this.playerId = playerId;
}
public String getBookingType() {
return BookingType;
return bookingType;
}
public void setBookingType(String bookingType) {
BookingType = bookingType;
this.bookingType = bookingType;
}
public String getProperty() {
return Property;
return property;
}
public void setProperty(String property) {
Property = property;
this.property = property;
}
public String getRoomCategory() {
return RoomCategory;
return roomCategory;
}
public void setRoomCategory(String roomCategory) {
RoomCategory = roomCategory;
this.roomCategory = roomCategory;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getApprovalRoutingType() {
return ApprovalRoutingType;
return approvalRoutingType;
}
public void setApprovalRoutingType(String approvalRoutingType) {
ApprovalRoutingType = approvalRoutingType;
this.approvalRoutingType = approvalRoutingType;
}
public String getApprovalRoutingMessage() {
return ApprovalRoutingMessage;
return approvalRoutingMessage;
}
public void setApprovalRoutingMessage(String approvalRoutingMessage) {
ApprovalRoutingMessage = approvalRoutingMessage;
this.approvalRoutingMessage = approvalRoutingMessage;
}
@JSONField(name = "ApproverList")
public void setApproverList(Object approverList) {
this.approverListRaw = approverList;
}
@JsonProperty("approverList")
@JSONField(serialize = false, deserialize = false)
public List<ApproverRecord> getApproverList() {
if (ApproverList == null) {
return parseApproverList(approverListRaw);
}
private static List<ApproverRecord> parseApproverList(Object raw) {
if (raw == null) {
return new ArrayList<ApproverRecord>();
}
if (ApproverList instanceof JSONArray arr) {
if (raw instanceof List<?> list && !list.isEmpty() && list.getFirst() instanceof ApproverRecord) {
List<ApproverRecord> result = new ArrayList<ApproverRecord>();
for (Object item : list) {
result.add((ApproverRecord) item);
}
return result;
}
if (raw instanceof JSONArray arr) {
return arr.toJavaList(ApproverRecord.class);
}
if (ApproverList instanceof String s) {
if (raw instanceof String s) {
s = s.trim();
if (s.isEmpty()) {
return new ArrayList<ApproverRecord>();
@@ -83,20 +129,7 @@ public class ApproverRecordResult {
JSONArray arr = JSONArray.parseArray(s);
return arr == null ? new ArrayList<ApproverRecord>() : arr.toJavaList(ApproverRecord.class);
}
// List/Map 等其它情况:统一转成 JSON 再转回 List<ApproverRecord>
JSONArray arr = JSON.parseArray(JSON.toJSONString(ApproverList));
JSONArray arr = JSON.parseArray(JSON.toJSONString(raw));
return arr == null ? new ArrayList<ApproverRecord>() : arr.toJavaList(ApproverRecord.class);
}
public void setApproverList(List<ApproverRecord> approverList) {
ApproverList = approverList;
}
public void setApproverList(String approverList) {
ApproverList = approverList;
}
public void setApproverList(Object approverList) {
ApproverList = approverList;
}
}
@@ -1,5 +1,7 @@
package com.mgm.mcrm.common.dtos.mgm_api;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.ArrayList;
import java.util.List;
@@ -7,31 +9,34 @@ import java.util.List;
public class ApproverResult {
private String StatusCode = null;
private String StatusDescription=null;
private List<ApproverRecordResult> Records = new ArrayList<ApproverRecordResult>();
@JSONField(name = "StatusCode")
private String statusCode = null;
@JSONField(name = "StatusDescription")
private String statusDescription=null;
@JSONField(name = "Records")
private List<ApproverRecordResult> records = new ArrayList<ApproverRecordResult>();
public String getStatusCode() {
return StatusCode;
return statusCode;
}
public void setStatusCode(String statusCode) {
StatusCode = statusCode;
this.statusCode = statusCode;
}
public String getStatusDescription() {
return StatusDescription;
return statusDescription;
}
public void setStatusDescription(String statusDescription) {
StatusDescription = statusDescription;
this.statusDescription = statusDescription;
}
public List<ApproverRecordResult> getRecords() {
return Records;
return records;
}
public void setRecords(List<ApproverRecordResult> records) {
Records = records;
this.records = records;
}
}
@@ -7,7 +7,7 @@ import java.util.List;
public class TodoDateListRecord {
private String Date = null;
private String date = null;
private List<TodoListRecord> dateRecords = new ArrayList<TodoListRecord>();
public TodoDateListRecord() {
@@ -16,12 +16,12 @@ public class TodoDateListRecord {
public String getDate() {
return Date;
return date;
}
public void setDate(String date) {
Date = date;
this.date = date;
}
@@ -9,7 +9,7 @@ public class TodoDateListResult {
private String statusCode = null;
private String statusDescription=null;
private List<TodoDateListRecord> Records = new ArrayList<TodoDateListRecord>();
private List<TodoDateListRecord> records = new ArrayList<TodoDateListRecord>();
public TodoDateListResult() {
@@ -32,11 +32,11 @@ public class TodoDateListResult {
}
public List<TodoDateListRecord> getRecords() {
return Records;
return records;
}
public void setRecords(List<TodoDateListRecord> records) {
Records = records;
this.records = records;
}
}
@@ -1,33 +1,61 @@
package com.mgm.mcrm.common.dtos.mgm_api;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class TodoListRecord {
private String Date = null;
private String ActionDate = null;
private String OperaConfirmationNo = null;
private Integer PlayerId = null;
private String TierName = null;
private String ChineseName = null;
private String EnglishName = null;
private String Salutation = null;
private Integer HasArrivalRecord = null;
private Integer HasDepartureRecord = null;
private Integer HasInhouseRecord = null;
private Integer HasOthersRecord = null;
private Integer HasLimoRecord = null;
private Integer HasFlightRecord = null;
private String ETA = null;
@JSONField(name = "Date")
private String date = null;
@JSONField(name = "ActionDate")
private String actionDate = null;
@JSONField(name = "OperaConfirmationNo")
private String operaConfirmationNo = null;
@JSONField(name = "PlayerId")
private Integer playerId = null;
@JSONField(name = "TierName")
private String tierName = null;
@JSONField(name = "ChineseName")
private String chineseName = null;
@JSONField(name = "EnglishName")
private String englishName = null;
@JSONField(name = "Salutation")
private String salutation = null;
@JSONField(name = "HasArrivalRecord")
private Integer hasArrivalRecord = null;
@JSONField(name = "HasDepartureRecord")
private Integer hasDepartureRecord = null;
@JSONField(name = "HasInhouseRecord")
private Integer hasInhouseRecord = null;
@JSONField(name = "HasOthersRecord")
private Integer hasOthersRecord = null;
@JSONField(name = "HasLimoRecord")
private Integer hasLimoRecord = null;
@JSONField(name = "HasFlightRecord")
private Integer hasFlightRecord = null;
@JSONField(name = "ETA")
@JsonProperty("eta")
private String eta = null;
private Boolean roomReady = false;
private Boolean isQueue = false;
private Integer BigWinFlag = null;
private Integer BigLossFlag = null;
private Integer NoPlayFlag = null;
private Integer MAId = null;
private String MA = null;
private List<String> Descriptions = null;
@JSONField(name = "BigWinFlag")
private Integer bigWinFlag = null;
@JSONField(name = "BigLossFlag")
private Integer bigLossFlag = null;
@JSONField(name = "NoPlayFlag")
private Integer noPlayFlag = null;
@JSONField(name = "MAId")
@JsonProperty("maId")
private Integer maId = null;
@JSONField(name = "MA")
@JsonProperty("ma")
private String ma = null;
@JSONField(name = "Descriptions")
private List<String> descriptions = null;
public TodoListRecord() {
@@ -36,135 +64,147 @@ public class TodoListRecord {
public String getDate() {
return Date;
return date;
}
public void setDate(String date) {
Date = date;
this.date = date;
}
public String getActionDate() {
return ActionDate;
return actionDate;
}
public void setActionDate(String actionDate) {
ActionDate = actionDate;
this.actionDate = actionDate;
}
public String getOperaConfirmationNo() {
return OperaConfirmationNo;
return operaConfirmationNo;
}
public void setOperaConfirmationNo(String operaConfirmationNo) {
OperaConfirmationNo = operaConfirmationNo;
this.operaConfirmationNo = operaConfirmationNo;
}
public Integer getPlayerId() {
return PlayerId;
return playerId;
}
public void setPlayerId(Integer playerId) {
PlayerId = playerId;
this.playerId = playerId;
}
public String getTierName() {
return TierName;
return tierName;
}
public void setTierName(String tierName) {
TierName = tierName;
this.tierName = tierName;
}
public String getChineseName() {
return ChineseName;
return chineseName;
}
public void setChineseName(String chineseName) {
ChineseName = chineseName;
this.chineseName = chineseName;
}
public String getEnglishName() {
return EnglishName;
return englishName;
}
public void setEnglishName(String englishName) {
EnglishName = englishName;
this.englishName = englishName;
}
public String getSalutation() {
return Salutation;
return salutation;
}
public void setSalutation(String salutation) {
Salutation = salutation;
this.salutation = salutation;
}
public Integer getHasArrivalRecord() {
return HasArrivalRecord;
return hasArrivalRecord;
}
public void setHasArrivalRecord(Integer hasArrivalRecord) {
HasArrivalRecord = hasArrivalRecord;
this.hasArrivalRecord = hasArrivalRecord;
}
public Integer getHasDepartureRecord() {
return HasDepartureRecord;
return hasDepartureRecord;
}
public void setHasDepartureRecord(Integer hasDepartureRecord) {
HasDepartureRecord = hasDepartureRecord;
this.hasDepartureRecord = hasDepartureRecord;
}
public Integer getHasInhouseRecord() {
return HasInhouseRecord;
return hasInhouseRecord;
}
public void setHasInhouseRecord(Integer hasInhouseRecord) {
HasInhouseRecord = hasInhouseRecord;
this.hasInhouseRecord = hasInhouseRecord;
}
public Integer getHasOthersRecord() {
return HasOthersRecord;
return hasOthersRecord;
}
public void setHasOthersRecord(Integer hasOthersRecord) {
HasOthersRecord = hasOthersRecord;
this.hasOthersRecord = hasOthersRecord;
}
public Integer getHasLimoRecord() {
return HasLimoRecord;
return hasLimoRecord;
}
public void setHasLimoRecord(Integer hasLimoRecord) {
HasLimoRecord = hasLimoRecord;
this.hasLimoRecord = hasLimoRecord;
}
public Integer getHasFlightRecord() {
return HasFlightRecord;
return hasFlightRecord;
}
public void setHasFlightRecord(Integer hasFlightRecord) {
HasFlightRecord = hasFlightRecord;
this.hasFlightRecord = hasFlightRecord;
}
@JsonProperty("eta")
public String getEta() {
return eta;
}
@JsonProperty("eta")
public void setEta(String eta) {
this.eta = eta;
}
@JsonIgnore
public String getETA() {
return ETA;
return eta;
}
@JsonIgnore
public void setETA(String eTA) {
ETA = eTA;
this.eta = eTA;
}
public Boolean getRoomReady() {
@@ -184,56 +224,71 @@ public class TodoListRecord {
}
public Integer getBigWinFlag() {
return BigWinFlag;
return bigWinFlag;
}
public void setBigWinFlag(Integer bigWinFlag) {
BigWinFlag = bigWinFlag;
this.bigWinFlag = bigWinFlag;
}
public Integer getBigLossFlag() {
return BigLossFlag;
return bigLossFlag;
}
public void setBigLossFlag(Integer bigLossFlag) {
BigLossFlag = bigLossFlag;
this.bigLossFlag = bigLossFlag;
}
public Integer getNoPlayFlag() {
return NoPlayFlag;
return noPlayFlag;
}
public void setNoPlayFlag(Integer noPlayFlag) {
NoPlayFlag = noPlayFlag;
this.noPlayFlag = noPlayFlag;
}
@JsonProperty("maId")
public Integer getMaId() {
return maId;
}
@JsonIgnore
public Integer getMAId() {
return MAId;
return maId;
}
@com.fasterxml.jackson.annotation.JsonProperty("maId")
public Integer getCalendarMaId() {
return MAId;
public void setMaId(Integer maId) {
this.maId = maId;
}
public void setMAId(Integer mAId) {
MAId = mAId;
this.maId = mAId;
}
@JsonProperty("ma")
public String getMa() {
return ma;
}
@JsonIgnore
public String getMA() {
return MA;
return ma;
}
public void setMa(String ma) {
this.ma = ma;
}
public void setMA(String mA) {
MA = mA;
this.ma = mA;
}
public List<String> getDescriptions() {
return Descriptions;
return descriptions;
}
public void setDescriptions(List<String> descriptions) {
Descriptions = descriptions;
this.descriptions = descriptions;
}
@@ -30,27 +30,23 @@ public class ConfigHeaderFilter implements Filter {
if (response instanceof HttpServletResponse httpServletResponse) {
String origin = ((HttpServletRequest) request).getHeader("Origin");
if (StringUtils.isBlank(origin) && "127.0.0.1".equals(NetworkUtil.getClientIpAddr((HttpServletRequest) request))) {
httpServletResponse.setHeader("Access-Control-Allow-Origin", null);
String sanitizedOrigin = NetworkUtil.sanitizeCRLF(origin);
if (SysCommon.isAllowOriginSource(sanitizedOrigin) || "OPTIONS".equalsIgnoreCase(req.getMethod())) {
httpServletResponse.setHeader("Access-Control-Allow-Origin", sanitizedOrigin);
} else {
String sanitizedOrigin = NetworkUtil.encodePathWithSpring(origin);
if (SysCommon.isAllowOriginSource(sanitizedOrigin)) {
httpServletResponse.setHeader("Access-Control-Allow-Origin", sanitizedOrigin);
} else {
LogUtil.warn(ConfigHeaderFilter.class, "Origin of [" + sanitizedOrigin + "] is not allowed");
httpServletResponse.setHeader("Access-Control-Allow-Origin", "");
log.warn("Blocked request: method={}, uri={}, query={}, origin={}, referer={}, ip={}, xff={}, userAgent={}",
req.getMethod(),
req.getRequestURI(),
req.getQueryString(),
req.getHeader("Origin"),
req.getHeader("Referer"),
req.getRemoteAddr(),
req.getHeader("X-Forwarded-For"),
req.getHeader("User-Agent"));
LogUtil.warn(ConfigHeaderFilter.class, "Origin of [" + sanitizedOrigin + "] is not allowed");
httpServletResponse.setHeader("Access-Control-Allow-Origin", "");
log.warn("Blocked request: method={}, uri={}, query={}, origin={}, referer={}, ip={}, xff={}, userAgent={}",
req.getMethod(),
req.getRequestURI(),
req.getQueryString(),
req.getHeader("Origin"),
req.getHeader("Referer"),
req.getRemoteAddr(),
req.getHeader("X-Forwarded-For"),
req.getHeader("User-Agent"));
return;
}
return;
}
httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
httpServletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type,Authorization,ClientId,Refreshtoken");
@@ -60,7 +60,7 @@ public class BookingScheduleJob {
ArrayList bookIds = new ArrayList();
for(Bookings b:bookings) {
List <GamingData> getGaming = waitlistBookingService.findGamingDataByBookId(b.getId());
if(getGaming==null||getGaming.size()==0) {
if(getGaming==null|| getGaming.isEmpty()) {
bookIds.add(String.valueOf(b.getId()));
}
}
@@ -2,6 +2,7 @@ package com.mgm.mcrm.common.services;
import com.alibaba.fastjson.JSON;
import com.mgm.mcrm.common.dtos.HttpResult;
import com.mgm.mcrm.common.dtos.config.ApiGatewaySetting;
import com.mgm.mcrm.common.enums.HttpMethods;
import com.mgm.mcrm.common.httpclient.HttpClientExecutor;
import com.mgm.mcrm.common.httpclient.HttpRequestOptions;
@@ -10,12 +11,16 @@ import jakarta.annotation.Resource;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
@@ -37,14 +42,19 @@ public class HttpService {
@Qualifier("httpRequestConfig")
private RequestConfig requestConfig;
@Value("${daylight.url}")
private String daylightUrl;
@Resource
private ApiGatewaySetting apiGatewaySetting;
@Value("${notification_proxy.url}")
private String notificationProxyUrl;
private Header[] supplementDaylightProxySecurity(Header[] headers){
List<Header> newHeaders = (headers == null ? new ArrayList<>() : new ArrayList<>(Arrays.asList(headers)));
newHeaders.add(new BasicHeader("application-id",apiGatewaySetting.getDaylightAppId()));
newHeaders.add(new BasicHeader("Authorization",apiGatewaySetting.getDaylightAppSecret()));
return newHeaders.toArray(new Header[0]);
}
public String sslGet(String url, Header[] headers, Map<String, Object> map) throws Exception {
String daylightUrl=apiGatewaySetting.getDaylightProxyUrl();
// todo 在這裏需要把請求頭的信息插入到數據庫裏
log.info("GET method, url={}, headers={}, map={}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(map));
// 使用 HttpConfig 配置 GET 请求(带参数)
@@ -55,7 +65,7 @@ public class HttpService {
.encoding("utf-8")
.client(httpClient);
String result = HttpClientExecutor.get(getConfig, headers);
String result = HttpClientExecutor.get(getConfig, supplementDaylightProxySecurity(headers));
log.info("GET request result size={}", result.length());
return result;
@@ -63,6 +73,7 @@ public class HttpService {
public HttpResult sslGetHttpResult(String url, Header[] headers, Map<String, Object> map) throws Exception {
String daylightUrl=apiGatewaySetting.getDaylightProxyUrl();
// todo 在這裏需要把請求頭的信息插入到數據庫裏
log.info("GET method, url={}, headers={}, map={}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(map));
// 使用 HttpConfig 配置 GET 请求(带参数)
@@ -73,8 +84,8 @@ public class HttpService {
.encoding("utf-8")
.client(httpClient);
HttpResult result = HttpClientExecutor.sendAndGetResp(getConfig, headers);
log.info("GET request result size={}", result.getResult().length());
HttpResult result = HttpClientExecutor.sendAndGetResp(getConfig, supplementDaylightProxySecurity(headers));
log.info("GET request result size={}, statusCode={}", result.getResult().length(), result.getStatusCode());
return result;
}
@@ -88,7 +99,9 @@ public class HttpService {
* @return 接口結果的json數據
* @throws Exception 異常
*/
@Deprecated
public String sslPut(String url, Header[] headers, Map<String, Object> map) throws Exception {
String daylightUrl=apiGatewaySetting.getDaylightProxyUrl();
log.info("PUT method, url={}, headers={}, map={}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(map));
HttpRequestOptions putConfig = HttpRequestOptions.create()
.url(daylightUrl + url)
@@ -97,7 +110,7 @@ public class HttpService {
.json(JSON.toJSONString(map))
.encoding("utf-8")
.client(httpClient);
String result = HttpClientExecutor.send(putConfig, headers);
String result = HttpClientExecutor.send(putConfig, supplementDaylightProxySecurity(headers));
log.info("PUT request result={}", result);
return result;
@@ -112,7 +125,9 @@ public class HttpService {
* @return 接口結果的json數據
* @throws Exception 異常
*/
@Deprecated
public String sslDelete(String url, Header[] headers, Object requestBody) throws Exception {
String daylightUrl=apiGatewaySetting.getDaylightProxyUrl();
log.info("DELETE method, url={}, headers={}, map={}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(requestBody));
HttpRequestOptions deleteConfig = HttpRequestOptions.create()
.url(daylightUrl + url)
@@ -120,7 +135,7 @@ public class HttpService {
.json(JSON.toJSONString(requestBody))
.method(HttpMethods.DELETE)
.client(httpClient);
String result = HttpClientExecutor.send(deleteConfig, headers);
String result = HttpClientExecutor.send(deleteConfig, supplementDaylightProxySecurity(headers));
log.info("DELETE request result={}", result);
return result;
}
@@ -135,6 +150,7 @@ public class HttpService {
* @throws Exception 異常
*/
public HttpResult sslPost(String url, Header[] headers, Object requestBody) throws Exception {
String daylightUrl=apiGatewaySetting.getDaylightProxyUrl();
log.info("POST method, url={}, headers={}, map={}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(requestBody));
HttpRequestOptions postConfig = HttpRequestOptions.create()
.url(daylightUrl + url)
@@ -142,9 +158,9 @@ public class HttpService {
.json(JSON.toJSONString(requestBody))
.method(HttpMethods.POST)
.client(httpClient);
HttpResult result = HttpClientExecutor.sendAndPostResp(postConfig, headers);
HttpResult result = HttpClientExecutor.sendAndPostResp(postConfig, supplementDaylightProxySecurity(headers));
// System.out.println("POST 请求结果:\n" + result);
log.info("POST request result size={}", result.getResult().length());
log.info("POST request result size={}, statusCode={}", result.getResult() != null ? result.getResult().length() : null, result.getStatusCode());
return result;
}
@@ -158,6 +174,7 @@ public class HttpService {
* @throws Exception 異常
*/
public HttpResult sslPatch(String url, Header[] headers, Object requestBody) throws Exception {
String daylightUrl=apiGatewaySetting.getDaylightProxyUrl();
log.info("PATCH method, url={}, headers={}, map={}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(requestBody));
HttpRequestOptions patchConfig = HttpRequestOptions.create()
.url(daylightUrl + url)
@@ -166,12 +183,20 @@ public class HttpService {
.method(HttpMethods.PATCH)
.encoding("utf-8")
.client(httpClient);
HttpResult result = HttpClientExecutor.sendAndPatchResp(patchConfig, headers);
log.info("PATCH request result={}", result);
HttpResult result = HttpClientExecutor.sendAndPatchResp(patchConfig, supplementDaylightProxySecurity(headers));
log.info("PATCH request result={}, statusCode={}", result.getResult(), result.getStatusCode());
return result;
}
private Header[] supplementNotificationProxySecurity(Header[] headers){
List<Header> newHeaders = (headers == null ? new ArrayList<>() : new ArrayList<>(Arrays.asList(headers)));
newHeaders.add(new BasicHeader("application-id",apiGatewaySetting.getDaylightAppId()));
newHeaders.add(new BasicHeader("Authorization",apiGatewaySetting.getDaylightAppSecret()));
return newHeaders.toArray(new Header[0]);
}
public HttpResult sslSendNotification(String url, Header[] headers, SendNotificationRequest request) throws Exception {
String notificationProxyUrl=apiGatewaySetting.getNotificationProxyUrl();
log.info("POST method, send notification, url={}, headers={}, map={}", notificationProxyUrl + url, JSON.toJSONString(headers), JSON.toJSONString(request));
HttpRequestOptions postConfig = HttpRequestOptions.create()
.url(notificationProxyUrl + url)
@@ -179,7 +204,7 @@ public class HttpService {
.json(JSON.toJSONString(request))
.method(HttpMethods.POST)
.client(httpClient);
HttpResult result = HttpClientExecutor.sendAndPostResp(postConfig, headers);
HttpResult result = HttpClientExecutor.sendAndPostResp(postConfig, supplementNotificationProxySecurity(headers));
log.info("POST request result={}", result);
return result;
}
@@ -1,468 +0,0 @@
package com.mgm.mcrm.common.services;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.mgm.mcrm.booking.dtos.search.DateRange;
import com.mgm.mcrm.common.constants.SysCommon;
import com.mgm.mcrm.common.dtos.http_util.HttpRequestDefine;
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.common.utils.DateTimeUtil;
import com.mgm.mcrm.common.utils.HttpUtil;
import com.mgm.mcrm.common.utils.LogUtil;
import com.mgm.mcrm.common.utils.mockup.HttpUtilMockup;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class MGMApiService {
public static String ESB_APP_ID = "";
public static String ESB_APP_SECRET = "";
public static String ESB_Server = "";
public static String ESB_ACCESS_TOKEN = null;
public static Date ESB_EXPIRED_TIME = new Date();
private static final String API_GET_ACCESS_TOKEN = "/RequestAccessToken";
private static final String API_GET_PLAYER_PROFILE = "/GetReportingLinePlayerInfo";
private static final String API_CHECK_PLAYER_TPD = "/GetRoomBookingQualificationStatus";
private static final String API_GET_USER_INFO = "/GetLoginUserInfo";
private static final String API_NON_MGM_BOOKING = "/GetNonMGMRoomBookingRecord";
private static final String API_WAITLIST_BOOKING = "/GetRoomBookingWaitList";
private static final String API_CHECK_SECOND_ROOM_TPD = "/GetMultiRoomBookingQualificationStatus";
private static final String API_CHECK_APPROVER = "/CheckApprover";
private static final String API_WAITLIST_DATA = "/GetWaitlistData";
private static final String API_GET_ALL_PLAYER_PROFILE = "/GetPlayerInfo";
private static final String API_GET_TODO_DASHBOARD = "/GetDashboardData";
private static final String API_GET_TODO_DETAIL = "/GetTodolistDetails";
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";
private static final String API_GET_LIMO_BOOKING_FROM_LEGACY = "/GetLimoBookingFromLegacy";
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 {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestHeader.put("PlayerId", playerId);
requestHeader.put("UserId", userId);
requestObj.put("playerId", playerId);
requestObj.put("userId", userId);
result = this.invokeESBAPI(ESB_Server, API_GET_PLAYER_PROFILE, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeGetAllPlayerProfile(String playerId) throws Exception {
HttpResponseResult result;
String apiLink = SysCommon.mgmApiMockup ? API_GET_PLAYER_PROFILE : API_GET_ALL_PLAYER_PROFILE;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestHeader.put("PlayerId", playerId);
requestObj.put("playerId", playerId);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeCheckPlayerTPD(
String playerId,
String roomCate,
List<String> dates,
String bookingType,
String property) throws Exception {
HttpResponseResult result;
String apiLink = API_CHECK_PLAYER_TPD;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestHeader.put("PlayerId", playerId);
requestHeader.put("RoomCategory", roomCate);
requestHeader.put("BookingType", bookingType);
requestHeader.put("Property", property);
requestHeader.put("StartDate", dates.getFirst());
requestHeader.put("EndDate", dates.getLast());
requestObj.put("playerId", playerId);
requestObj.put("roomCategory", roomCate);
requestObj.put("startDate", dates.getFirst());
requestObj.put("endDate", dates.getLast());
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "GET", requestHeader, 1);
return result;
}
public HttpResponseResult invokeGetApprover(String playerId,String bookingType,String property,String roomCategory,String checkInDate,String checkOutDate,String userId) throws Exception {
HttpResponseResult result = null;
String apiLink =API_GET_APPROVER;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<String,String>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("PlayerId", playerId);
requestObj.put("BookingType", bookingType);
requestObj.put("Property", property);
requestObj.put("RoomCategory", roomCategory);
requestObj.put("StartDate", checkInDate);
requestObj.put("EndDate", checkOutDate);
requestObj.put("UserId", userId);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader);
return result;
}
public HttpResponseResult invokeGetApprovalData(String bookingId) throws Exception {
HttpResponseResult result = null;
String apiLink =API_GET_APPROVER_DATA;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<String,String>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("BookingId", bookingId);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader);
return result;
}
public HttpResponseResult invokeCheckApprover(
String userId,
String userName,
String roomType,
String property) throws Exception {
HttpResponseResult result;
String apiLink = API_CHECK_APPROVER;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
if (!StringUtils.isEmpty(userId)) {
requestObj.put("UserId", userId);
}
if (!StringUtils.isEmpty(userName)) {
requestObj.put("UserName", userName);
}
requestObj.put("RoomCategory", roomType);
requestObj.put("Property", property);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader);
return result;
}
public HttpResponseResult invokeGetUserInfo(String userId, String userName) throws Exception {
HttpResponseResult result;
String apiLink = API_GET_USER_INFO;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
if (!StringUtils.isEmpty(userId)) {
requestHeader.put("UserId", userId);
requestObj.put("userId", userId);
}
if (!StringUtils.isEmpty(userName)) {
requestHeader.put("UserName", userName);
requestObj.put("userName", userName);
}
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeNonMGMBooking(String playerId) throws Exception {
HttpResponseResult result;
String apiLink = API_NON_MGM_BOOKING;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestHeader.put("PlayerId", playerId);
requestObj.put("playerId", playerId);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeWaitlistBooking(String playerId) throws Exception {
HttpResponseResult result;
String apiLink = API_WAITLIST_BOOKING;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestHeader.put("PlayerId", playerId);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeWaitlistData(String bookIds, int categoryType) throws Exception {
HttpResponseResult result;
String apiLink = API_WAITLIST_DATA;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("BookingId", bookIds);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader, categoryType);
return result;
}
public HttpResponseResult invokeCheckPlayerSecondTPD(
String playerId,
String roomCate,
List<DateRange> dateRange,
String bookingType,
String property) throws Exception {
HttpResponseResult result;
String apiLink = API_CHECK_SECOND_ROOM_TPD;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("PlayerId", playerId);
requestObj.put("RoomCategory", roomCate);
requestObj.put("BookingType", bookingType);
requestObj.put("Property", property);
requestObj.put("DateRange", dateRange);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader);
return result;
}
public String getAccessToken() throws Exception {
String token = ESB_ACCESS_TOKEN;
if (SysCommon.mgmApiMockup) return token;
ESB_APP_ID = SysCommon.apiConfig.getApiKey_ESB();
ESB_APP_SECRET = SysCommon.apiConfig.getApiSecret_ESB();
ESB_Server = SysCommon.apiConfig.getServerUrl_ESB();
if (token == null || ESB_EXPIRED_TIME.getTime() < new Date().getTime()) {
String apiLink = API_GET_ACCESS_TOKEN;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("AppId", ESB_APP_ID);
requestObj.put("AppSecret", ESB_APP_SECRET);
HttpResponseResult result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader);
if (result.getStatusCode() == 200) {
JSONObject resultObj = JSONObject.parseObject(result.getResponseContent());
String status = resultObj.getString("StatusCode");
if (Strings.CS.equals("OK", status)) {
token = resultObj.getString("Token");
ESB_EXPIRED_TIME = DateTimeUtil.getDateFromString(resultObj.getString("ExpireTime"), "yyyy-MM-dd HH:mm:ss");
ESB_ACCESS_TOKEN = token;
} else {
token = null;
ESB_ACCESS_TOKEN = null;
ESB_EXPIRED_TIME = new Date();
}
}
}
return token;
}
public HttpResponseResult invokeGetTodoDashboard(
String userId,
int categoryType) throws Exception {
HttpResponseResult result;
String apiLink = API_GET_TODO_DASHBOARD;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("UserId", userId);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader, categoryType);
return result;
}
public HttpResponseResult invokeGetTodoDetail(
String playerId,
String todoCategory,
String todoSegment,
String date,
int categoryType) throws Exception {
HttpResponseResult result;
String apiLink = API_GET_TODO_DETAIL;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("PlayerId", playerId);
requestObj.put("TodoCategory", todoCategory);
requestObj.put("TodoSegment", todoSegment);
requestObj.put("Date", date);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader, categoryType);
return result;
}
public HttpResponseResult invokeGetLimoBookingFromLegacy(
String playerId
) throws Exception {
HttpResponseResult result = null;
String apiLink = API_GET_LIMO_BOOKING_FROM_LEGACY;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("PlayerId", playerId);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader);
return result;
}
public HttpResponseResult invokeGetTodoList(
String userId,
String category,
String type,
Date startDate,
Date endDate,
int categoryType) throws Exception {
HttpResponseResult result;
String apiLink = API_GET_TODO_LIST;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("UserId", userId);
requestObj.put("TodoCategory", category);
requestObj.put("TodoSegment", type);
requestObj.put("StartDate", startDate);
requestObj.put("EndDate", endDate);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader, categoryType);
return result;
}
// 如果不设置type,默认call opera
public HttpResponseResult invokeESBAPI(
String serverType,
String requestLink,
JSONObject requestContent,
String requestMethod,
Map<String, String> requestHeader) throws Exception {
return invokeESBAPI(serverType, requestLink, requestContent, requestMethod, requestHeader, 0);
}
/**
*
* @param serverType n
* @param requestLink n
* @param requestContent n
* @param requestMethod n
* @param requestHeader n
* @param type 0 - opera, 1 - daylight
* @return n
* @throws Exception e
*/
public HttpResponseResult invokeESBAPI(
String serverType,
String requestLink,
JSONObject requestContent,
String requestMethod,
Map<String, String> requestHeader,
int type) throws Exception {
String serverUrl;
int timeoutTime;
if (Strings.CS.equals(serverType, ESB_Server)) {
serverUrl = SysCommon.apiConfig.getServerUrl_ESB();
timeoutTime = SysCommon.apiConfig.getTimeout_ESB();
} else {
throw new Exception("Invalid server type");
}
if (type == 1) {
requestLink = "/Daylight" + requestLink;
}
HttpRequestDefine requestDef = new HttpRequestDefine();
String requestUrl = serverUrl + requestLink;
requestDef.setRequestUrl(requestUrl);
requestDef.setRequestMethod(requestMethod);
requestDef.setTimeout(timeoutTime);
requestHeader.put("Content-type", "application/json;charset=utf-8");
requestDef.setHeaders(requestHeader);
if (requestContent != null) {
requestDef.setEntityContent(requestContent.toString());
} else {
requestDef.setEntityContent("");
}
// --
//Get Start,EndTime
long spanTime;
Date startTime = new Date();
Date endTime;
LogUtil.info(MGMApiService.class, "[invokeESBAPI] start request:");
HttpResponseResult httpResult =
SysCommon.mgmApiMockup ?
HttpUtilMockup.processHttpRequest(requestDef) :
HttpUtil.processHttpRequest(requestDef);
httpResult.setRequestContent(requestDef.getEntityContent());
//RefreshEndTime
endTime = new Date();
//Get Spend Time
Gson gson = new Gson();
spanTime = DateTimeUtil.getTimeSpanSSS(startTime, endTime);
LogUtil.info(MGMApiService.class, "[invokeESBAPI]getRequestUrl:" + gson.toJson(requestDef.getRequestUrl()));
LogUtil.info(MGMApiService.class, "[invokeESBAPI]getHeaders:" + gson.toJson(requestDef.getHeaders()));
LogUtil.info(MGMApiService.class, "[invokeESBAPI]getRequestMethod:" + gson.toJson(requestDef.getRequestMethod()));
LogUtil.info(MGMApiService.class, "[invokeESBAPI]getEntityContent:" + gson.toJson(requestContent));
LogUtil.info(MGMApiService.class, "[invokeESBAPI]getStatusCode:" + gson.toJson(httpResult.getStatusCode()));
LogUtil.info(MGMApiService.class, "[invokeESBAPI]getErrorMessage:" + gson.toJson(httpResult.getErrorMessage()));
LogUtil.info(MGMApiService.class, "[invokeESBAPI]getResponseContent:" + gson.toJson(httpResult.getResponseContent()));
//Log Spend Time
LogUtil.info(MGMApiService.class, "[invokeESBAPI]SpendTime:" + spanTime + "ms");
return httpResult;
}
}
@@ -2,244 +2,403 @@ package com.mgm.mcrm.common.services;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.mgm.mcrm.booking.dtos.search.DateRange;
import com.mgm.mcrm.common.constants.SysCommon;
import com.mgm.mcrm.common.dtos.config.ApiGatewaySetting;
import com.mgm.mcrm.common.dtos.http_util.HttpRequestDefine;
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.common.utils.DateTimeUtil;
import com.mgm.mcrm.common.utils.HttpUtil;
import com.mgm.mcrm.common.utils.LogUtil;
import com.mgm.mcrm.common.utils.mockup.HttpUtilMockup;
import com.mgm.mcrm.limo.dtos.request.RequestPlayerEsbBookerRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class MGMEsbApiService {
public static String LIMO_ESB_APP_ID = "";
public static String LIMO_ESB_APP_SECRET = "";
public static String LIMO_ESB_SERVER = "";
public static String LIMO_ESB_ACCESS_TOKEN = "";
public static Date LIMO_ESB_EXPIRED_TIME = new Date();
private final Logger logger = LoggerFactory.getLogger(MGMEsbApiService.class);
public static final String ESB_MCRM_API_TYPE = "ESB_MCRM";
public static final String ESB_LIMO_API_TYPE= "ESB_LIMO";
private static final String API_GET_ACCESS_TOKEN = "/RequestAccessToken";
private static final String API_GET_LIMO_OVERRIDER = "/RequestLimoOverrider";
private static final String API_CHECK_SIMPLE_LIMO_BOOKING_QUALIFICATION_STATUS = "/RequestSimpleLimoBookingQualificationStatus";
private static final String API_CHECK_COMPLEX_LIMO_BOOKING_QUALIFICATION_STATUS = "/RequestComplexLimoBookingQualificationStatus";
private static final String API_REQUEST_EMPLOYEE_INFO = "/RequestEmployeeInfo";
private static final String API_REQUEST_PLAYER_LIMO_BOOKER = "/RequestPlayerLimoBooker";
private static final String API_REQUEST_PLAYER_INFO = "/RequestPlayerInfo";
private static final String API_GET_PLAYER_PROFILE = "/GetReportingLinePlayerInfo";
private static final String API_CHECK_PLAYER_TPD = "/GetRoomBookingQualificationStatus";
private static final String API_GET_USER_INFO = "/GetLoginUserInfo";
private static final String API_NON_MGM_BOOKING = "/GetNonMGMRoomBookingRecord";
private static final String API_WAITLIST_BOOKING = "/GetRoomBookingWaitList";
private static final String API_CHECK_SECOND_ROOM_TPD = "/GetMultiRoomBookingQualificationStatus";
private static final String API_CHECK_APPROVER = "/CheckApprover";
private static final String API_WAITLIST_DATA = "/GetWaitlistData";
private static final String API_GET_ALL_PLAYER_PROFILE = "/GetPlayerInfo";
private static final String API_GET_TODO_DASHBOARD = "/GetDashboardData";
private static final String API_GET_TODO_DETAIL = "/GetTodolistDetails";
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";
private static final String API_GET_LIMO_BOOKING_FROM_LEGACY = "/GetLimoBookingFromLegacy";
@Autowired
private ApiGatewaySetting apiGatewaySetting;
public HttpResponseResult invokeRequestPlayerLimoBooker(RequestPlayerEsbBookerRequest request) throws Exception {
String apiLink = API_REQUEST_PLAYER_LIMO_BOOKER;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getLimoAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("EmployeeIdOrName", request.getUserId());
requestObj.put("PlayerId", request.getPlayerId());
return this.invokeESBAPI(LIMO_ESB_SERVER, apiLink, requestObj, "POST", requestHeader);
public HttpResponseResult invokeRequestRoomCalendar(
String playerId,
String property,
String roomType,
String startDate,
String endDate) throws Exception {
return invokeRequestRoomCalendar(playerId, property, roomType, startDate, endDate, 0);
}
public String getLimoAccessToken() throws Exception {
String token = LIMO_ESB_ACCESS_TOKEN;
if (SysCommon.mgmApiMockup)
return token;
LIMO_ESB_APP_ID = SysCommon.apiConfig.getLimoApp_id();
LIMO_ESB_APP_SECRET = SysCommon.apiConfig.getLimoApp_key();
LIMO_ESB_SERVER = SysCommon.apiConfig.getLimoService_ESB();
if (token == null || LIMO_ESB_EXPIRED_TIME.getTime() < new Date().getTime()) {
String apiLink = API_GET_ACCESS_TOKEN;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("AppId", LIMO_ESB_APP_ID);
requestObj.put("AppSecret", LIMO_ESB_APP_SECRET);
HttpResponseResult result =
this.invokeESBAPI(LIMO_ESB_SERVER, apiLink, requestObj, "POST", requestHeader);
if (result.getStatusCode() == 200) {
JSONObject resultObj = JSONObject.parseObject(result.getResponseContent());
String status = resultObj.getString("StatusCode");
if (Strings.CI.equals("OK", status)) {
token = resultObj.getString("Token");
LIMO_ESB_EXPIRED_TIME =
DateTimeUtil.getDateFromString(resultObj.getString("ExpireTime"), "yyyy-MM-dd HH:mm:ss");
LIMO_ESB_ACCESS_TOKEN = token;
} else {
token = null;
LIMO_ESB_ACCESS_TOKEN = null;
LIMO_ESB_EXPIRED_TIME = new Date();
}
}
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<>();
if (StringUtils.isNotBlank(playerId)) {
requestObj.put("PlayerId", playerId);
}
return token;
requestObj.put("Property", property);
requestObj.put("RoomType", roomType);
requestObj.put("StartDate", startDate);
requestObj.put("EndDate", endDate);
return invokeESBAPI(ESB_MCRM_API_TYPE, API_REQUEST_ROOM_CALENDAR, requestObj, "POST", requestHeader, type);
}
public HttpResponseResult invokeLimoOverrider(
String overriderIdOrName
) throws Exception {
String apiLink = API_GET_LIMO_OVERRIDER;
public HttpResponseResult invokeGetPlayerProfile(
String playerId,
String userId) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestHeader.put("PlayerId", playerId);
requestHeader.put("UserId", userId);
String token = getLimoAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("OverriderIdOrName", "%");
return this.invokeESBAPI(LIMO_ESB_SERVER, apiLink, requestObj, "POST", requestHeader);
requestObj.put("playerId", playerId);
requestObj.put("userId", userId);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_PLAYER_PROFILE, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeLimoPlayerInfo(
Integer playerId
) throws Exception {
String apiLink = API_REQUEST_PLAYER_INFO;
public HttpResponseResult invokeGetAllPlayerProfile(String playerId) throws Exception {
HttpResponseResult result;
String apiLink = SysCommon.mgmApiMockup ? API_GET_PLAYER_PROFILE : API_GET_ALL_PLAYER_PROFILE;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestHeader.put("PlayerId", playerId);
String token = getLimoAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("PlayerId", playerId);
return this.invokeESBAPI(LIMO_ESB_SERVER, apiLink, requestObj, "POST", requestHeader);
requestObj.put("playerId", playerId);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, apiLink, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeSimpleLimoBookingQualificationStatus(
Integer playerId,
public HttpResponseResult invokeCheckPlayerTPD(
String playerId,
String roomCate,
List<String> dates,
String bookingType,
String bookingDate
) throws Exception {
String apiLink = API_CHECK_SIMPLE_LIMO_BOOKING_QUALIFICATION_STATUS;
String property) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestHeader.put("PlayerId", playerId);
requestHeader.put("RoomCategory", roomCate);
requestHeader.put("BookingType", bookingType);
requestHeader.put("Property", property);
requestHeader.put("StartDate", dates.getFirst());
requestHeader.put("EndDate", dates.getLast());
String token = getLimoAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("playerId", playerId);
requestObj.put("roomCategory", roomCate);
requestObj.put("startDate", dates.getFirst());
requestObj.put("endDate", dates.getLast());
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_CHECK_PLAYER_TPD, requestObj, "GET", requestHeader, 1);
return result;
}
public HttpResponseResult invokeGetApprover(String playerId,String bookingType,String property,String roomCategory,String checkInDate,String checkOutDate,String userId) throws Exception {
HttpResponseResult result = null;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("PlayerId", playerId);
requestObj.put("BookingType", bookingType);
requestObj.put("BookingDate", bookingDate);
requestObj.put("Property", property);
requestObj.put("RoomCategory", roomCategory);
requestObj.put("StartDate", checkInDate);
requestObj.put("EndDate", checkOutDate);
requestObj.put("UserId", userId);
return this.invokeESBAPI(LIMO_ESB_SERVER, apiLink, requestObj, "POST", requestHeader);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_APPROVER, requestObj, "POST", requestHeader, 1);
return result;
}
public HttpResponseResult invokeGetApprovalData(String bookingId, int type) throws Exception {
HttpResponseResult result = null;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<String,String>();
requestObj.put("BookingId", bookingId);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_APPROVER_DATA, requestObj, "POST", requestHeader,type);
return result;
}
public HttpResponseResult invokeRequestEmployeeInfo(String employeeId) throws Exception {
String apiLink = API_REQUEST_EMPLOYEE_INFO;
public HttpResponseResult invokeCheckApprover(
String userId,
String userName,
String roomType,
String property) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getLimoAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("EmployeeId", employeeId);
return this.invokeESBAPI(LIMO_ESB_SERVER, apiLink, requestObj, "POST", requestHeader);
if (!StringUtils.isEmpty(userId)) {
requestObj.put("UserId", userId);
}
if (!StringUtils.isEmpty(userName)) {
requestObj.put("UserName", userName);
}
requestObj.put("RoomCategory", roomType);
requestObj.put("Property", property);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_CHECK_APPROVER, requestObj, "POST", requestHeader);
return result;
}
public HttpResponseResult invokeGetUserInfo(String userId, String userName) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
if (!StringUtils.isEmpty(userId)) {
requestHeader.put("UserId", userId);
requestObj.put("userId", userId);
}
if (!StringUtils.isEmpty(userName)) {
requestHeader.put("UserName", userName);
requestObj.put("userName", userName);
}
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_USER_INFO, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeNonMGMBooking(String playerId) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestHeader.put("PlayerId", playerId);
requestObj.put("playerId", playerId);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_NON_MGM_BOOKING, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeWaitlistBooking(String playerId) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestHeader.put("PlayerId", playerId);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_WAITLIST_BOOKING, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeWaitlistData(String bookIds, int categoryType) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("BookingId", bookIds);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_WAITLIST_DATA, requestObj, "POST", requestHeader, categoryType);
return result;
}
public HttpResponseResult invokeCheckPlayerSecondTPD(
String playerId,
String roomCate,
List<DateRange> dateRange,
String bookingType,
String property) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("PlayerId", playerId);
requestObj.put("RoomCategory", roomCate);
requestObj.put("BookingType", bookingType);
requestObj.put("Property", property);
requestObj.put("DateRange", dateRange);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_CHECK_SECOND_ROOM_TPD, requestObj, "POST", requestHeader);
return result;
}
public HttpResponseResult invokeGetTodoDashboard(
String userId,
int categoryType) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("UserId", userId);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_TODO_DASHBOARD, requestObj, "POST", requestHeader, categoryType);
return result;
}
public HttpResponseResult invokeGetTodoDetail(
String playerId,
String todoCategory,
String todoSegment,
String date,
int categoryType) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("PlayerId", playerId);
requestObj.put("TodoCategory", todoCategory);
requestObj.put("TodoSegment", todoSegment);
requestObj.put("Date", date);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_TODO_DETAIL, requestObj, "POST", requestHeader, categoryType);
return result;
}
public HttpResponseResult invokeGetLimoBookingFromLegacy(
String playerId
) throws Exception {
HttpResponseResult result = null;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("PlayerId", playerId);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_LIMO_BOOKING_FROM_LEGACY, requestObj, "POST", requestHeader);
return result;
}
public HttpResponseResult invokeGetTodoList(
String userId,
String category,
String type,
Date startDate,
Date endDate,
int categoryType) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("UserId", userId);
requestObj.put("TodoCategory", category);
requestObj.put("TodoSegment", type);
requestObj.put("StartDate", startDate);
requestObj.put("EndDate", endDate);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_TODO_LIST, requestObj, "POST", requestHeader, categoryType);
return result;
}
// 如果不设置type,默认call opera
public HttpResponseResult invokeESBAPI(
String serverType,
String esbApiType,
String requestLink,
JSONObject requestContent,
String requestMethod,
Map<String, String> requestHeader) throws Exception {
return invokeESBAPI(esbApiType, requestLink, requestContent, requestMethod, requestHeader, 0);
}
/**
*
* @param esbApiType n
* @param requestLink n
* @param requestContent n
* @param requestMethod n
* @param requestHeader n
* @param type 0 - opera, 1 - daylight
* @return n
* @throws Exception e
*/
public HttpResponseResult invokeESBAPI(
String esbApiType,
String requestLink,
JSONObject requestContent,
String requestMethod,
Map<String, String> requestHeader,
int type) throws Exception {
String serverUrl;
int timeoutTime;
int timeoutTime = apiGatewaySetting.getRequestTimeout();
if (Strings.CS.equals(esbApiType, ESB_MCRM_API_TYPE)) {
serverUrl = apiGatewaySetting.getEsbMcrmProxyUrl();
//-- set proxy authorization
requestHeader.put("application-id", apiGatewaySetting.getEsbMcrmAppId());
requestHeader.put("Authorization", apiGatewaySetting.getEsbMcrmAppSecret());
//--
//Get Spend Time
Gson gson = new Gson();
HttpRequestDefine requestDef = new HttpRequestDefine();
LogUtil.info(MGMEsbApiService.class,"Request Url = "+gson.toJson(requestDef.getRequestUrl())+"serverType: " + serverType+"LIMO_ESB_SERVER"+LIMO_ESB_SERVER);
if (Strings.CS.equals(serverType, LIMO_ESB_SERVER)) {
serverUrl = SysCommon.apiConfig.getLimoService_ESB();
timeoutTime = SysCommon.apiConfig.getTimeout_ESB();
if (type == 1) {
requestLink = "/Daylight" + requestLink;
}
}else if (Strings.CS.equals(esbApiType, ESB_LIMO_API_TYPE)) {
serverUrl = apiGatewaySetting.getEsbLimoProxyUrl();
//-- set proxy authorization
requestHeader.put("application-id", apiGatewaySetting.getEsbLimoAppId());
requestHeader.put("Authorization", apiGatewaySetting.getEsbLimoAppSecret());
//--
} else {
throw new Exception("Invalid server type");
throw new Exception("Invalid ESB Api type");
}
HttpRequestDefine requestDef = new HttpRequestDefine();
String requestUrl = serverUrl + requestLink;
requestDef.setRequestUrl(requestUrl);
requestDef.setRequestMethod(requestMethod);
requestDef.setTimeout(timeoutTime);
requestHeader.put("Content-type", "application/json;charset=utf-8");
requestDef.setHeaders(requestHeader);
if (requestContent != null)
if (requestContent != null) {
requestDef.setEntityContent(requestContent.toString());
else
} else {
requestDef.setEntityContent("");
}
// --
//Get Start,EndTime
long spanTime;
Date startTime = new Date();
LogUtil.info(MGMEsbApiService.class, "[invokeESBAPI] start request:");
HttpResponseResult httpResult = (SysCommon.mgmApiMockup ?
HttpUtilMockup.processHttpRequest(requestDef)
: HttpUtil.processHttpRequest(requestDef));
Date endTime;
logger.info("[invoke {} API] start request:",esbApiType);
HttpResponseResult httpResult =
SysCommon.mgmApiMockup ?
HttpUtilMockup.processHttpRequest(requestDef) :
HttpUtil.processHttpRequest(requestDef);
httpResult.setRequestContent(requestDef.getEntityContent());
//RefreshEndTime
Date endTime = new Date();
endTime = new Date();
//Get Spend Time
Gson gson = new Gson();
spanTime = DateTimeUtil.getTimeSpanSSS(startTime, endTime);
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]getRequestUrl:" + gson.toJson(requestDef.getRequestUrl()));
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]getHeaders:" + gson.toJson(requestDef.getHeaders()));
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]getRequestMethod:" + gson.toJson(requestDef.getRequestMethod()));
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]getEntityContent:" + gson.toJson(requestContent));
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]getStatusCode:" + gson.toJson(httpResult.getStatusCode()));
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]getErrorMessage:" + gson.toJson(httpResult.getErrorMessage()));
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]getResponseContent:" + gson.toJson(httpResult.getResponseContent()));
logger.info("[invoke {} API]getRequestUrl:{}",esbApiType, gson.toJson(requestDef.getRequestUrl()));
logger.info("[invoke {} API]getHeaders:{}" ,esbApiType, gson.toJson(requestDef.getHeaders()));
logger.info("[invoke {} API]getRequestMethod:{}" ,esbApiType, gson.toJson(requestDef.getRequestMethod()));
logger.info("[invoke {} API]getEntityContent:{}" ,esbApiType, gson.toJson(requestContent));
logger.info("[invoke {} API]getStatusCode:{}" ,esbApiType, gson.toJson(httpResult.getStatusCode()));
logger.info("[invoke {} API]getErrorMessage:{}" ,esbApiType, gson.toJson(httpResult.getErrorMessage()));
logger.info("[invoke {} API]getResponseContent:{}" ,esbApiType, gson.toJson(httpResult.getResponseContent()));
//Log Spend Time
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]SpendTime:" + spanTime + "ms");
logger.info("[invoke {} API]SpendTime:{}" ,esbApiType, spanTime + "ms");
return httpResult;
}
}
}
@@ -0,0 +1,91 @@
package com.mgm.mcrm.common.services;
import com.alibaba.fastjson.JSONObject;
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.limo.dtos.request.RequestPlayerEsbBookerRequest;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class MGMEsbLimoApiService {
public static final String ESB_LIMO_API_TYPE= "ESB_LIMO";
private static final String API_GET_ACCESS_TOKEN = "/RequestAccessToken";
private static final String API_GET_LIMO_OVERRIDER = "/RequestLimoOverrider";
private static final String API_CHECK_SIMPLE_LIMO_BOOKING_QUALIFICATION_STATUS = "/RequestSimpleLimoBookingQualificationStatus";
private static final String API_CHECK_COMPLEX_LIMO_BOOKING_QUALIFICATION_STATUS = "/RequestComplexLimoBookingQualificationStatus";
private static final String API_REQUEST_EMPLOYEE_INFO = "/RequestEmployeeInfo";
private static final String API_REQUEST_PLAYER_LIMO_BOOKER = "/RequestPlayerLimoBooker";
private static final String API_REQUEST_PLAYER_INFO = "/RequestPlayerInfo";
@Resource
private MGMEsbApiService mgmEsbApiService;
public HttpResponseResult invokeRequestPlayerLimoBooker(RequestPlayerEsbBookerRequest request) throws Exception {
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("EmployeeIdOrName", request.getUserId());
requestObj.put("PlayerId", request.getPlayerId());
return mgmEsbApiService.invokeESBAPI(ESB_LIMO_API_TYPE, API_REQUEST_PLAYER_LIMO_BOOKER, requestObj, "POST", requestHeader);
}
public HttpResponseResult invokeLimoOverrider(
String overriderIdOrName
) throws Exception {
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("OverriderIdOrName", "%");
return mgmEsbApiService.invokeESBAPI(ESB_LIMO_API_TYPE, API_GET_LIMO_OVERRIDER, requestObj, "POST", requestHeader);
}
public HttpResponseResult invokeLimoPlayerInfo(
Integer playerId
) throws Exception {
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("PlayerId", playerId);
return mgmEsbApiService.invokeESBAPI(ESB_LIMO_API_TYPE, API_REQUEST_PLAYER_INFO, requestObj, "POST", requestHeader);
}
public HttpResponseResult invokeSimpleLimoBookingQualificationStatus(
Integer playerId,
String bookingType,
String bookingDate
) throws Exception {
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("PlayerId", playerId);
requestObj.put("BookingType", bookingType);
requestObj.put("BookingDate", bookingDate);
return mgmEsbApiService.invokeESBAPI(ESB_LIMO_API_TYPE, API_CHECK_SIMPLE_LIMO_BOOKING_QUALIFICATION_STATUS, requestObj, "POST", requestHeader);
}
public HttpResponseResult invokeRequestEmployeeInfo(String employeeId) throws Exception {
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("EmployeeId", employeeId);
return mgmEsbApiService.invokeESBAPI(ESB_LIMO_API_TYPE, API_REQUEST_EMPLOYEE_INFO, requestObj, "POST", requestHeader);
}
}
@@ -2,6 +2,7 @@ package com.mgm.mcrm.common.services;
import com.alibaba.fastjson.JSONObject;
import com.mgm.mcrm.common.constants.SysCommon;
import com.mgm.mcrm.common.dtos.config.ApiGatewaySetting;
import com.mgm.mcrm.common.dtos.http_util.HttpRequestDefine;
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.common.utils.HttpUtil;
@@ -10,11 +11,13 @@ import com.mgm.mcrm.common.utils.mockup.HttpUtilMockup;
import com.mgm.mcrm.limo.dtos.request.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
@@ -22,11 +25,8 @@ import java.util.stream.Collectors;
@Service
public class MGMLimoApiService {
public static String ESB_LIMO_SERVER = "";
public static String ESB_LIMO_ACCESS_TOKEN = null;
public static String ESB_LIMO_APP_ID;
public static String ESB_LIMO_APP_SECRET;
public static Date ESB_LIMO_EXPIRED_TIME = new Date();
public static String LIMO_ACCESS_TOKEN = null;
public static LocalDateTime LIMO_EXPIRED_TIME = LocalDateTime.now();
private static final String API_GET_ACCESS_TOKEN = "GetAccessToken";
private static final String API_GET_TRIP_PRICE = "GetTripPrice";
@@ -42,13 +42,8 @@ public class MGMLimoApiService {
// private static final String API_MAIN_HANDLER_HANDLER = "http://mmlimodevapp01/MCRMAPI/API/MainHandler.ashx ";
@Value("${limo_address}")
private String API_MAIN_HANDLER;
@Value("${limo_getAccessToken_Id}")
private String apiGetAccessTokenId;
@Value("${limo_getAccessToken_pwd}")
private String apiGetAccessTokenPwd;
@Autowired
private ApiGatewaySetting apiGatewaySetting;
public HttpResponseResult invokeGetTripPrice() throws Exception {
@@ -56,11 +51,10 @@ public class MGMLimoApiService {
Map<String, String> requestObj = new HashMap<>();
String token = getLimoAccessToken();
requestObj.put("action", API_GET_TRIP_PRICE);
requestObj.put("token", token);
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
public HttpResponseResult invokeGetLocation(String location) throws Exception {
@@ -68,12 +62,11 @@ public class MGMLimoApiService {
Map<String, String> requestObj = new HashMap<>();
String token = getLimoAccessToken();
requestObj.put("action", API_GET_LOCATION);
requestObj.put("token", token);
requestObj.put("Location", "%");
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
public HttpResponseResult invokeGetCarType() throws Exception {
@@ -85,7 +78,7 @@ public class MGMLimoApiService {
requestObj.put("action", API_GET_CAR_TYPE);
requestObj.put("token", token);
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
@@ -99,7 +92,7 @@ public class MGMLimoApiService {
requestObj.put("action", API_GET_GREET_TYPE);
requestObj.put("token", token);
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
public HttpResponseResult invokeGetBooking(String bookingId) throws Exception {
@@ -107,13 +100,11 @@ public class MGMLimoApiService {
Map<String, String> requestObj = new HashMap<>();
String token = getLimoAccessToken();
if(bookingId != null) requestObj.put("Id",bookingId);
requestObj.put("action", API_GET_BOOKING);
requestObj.put("token", token);
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
public HttpResponseResult getFlightDetails(GetLimoFlightDetailsRequest request) throws Exception {
@@ -131,7 +122,7 @@ public class MGMLimoApiService {
requestObj.put("token", token);
requestObj.put("itemObject", itemObject.toJSONString());
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
public HttpResponseResult getTotalAmount(GetLimoTotalAmountRequest request) throws Exception {
@@ -159,7 +150,7 @@ public class MGMLimoApiService {
requestObj.put("token", token);
requestObj.put("itemObject", itemObject.toJSONString());
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
/** 按 {@code ;} 拆分,去掉空白段;例如 {@code 1;2;3} → [1,2,3] */
@@ -293,7 +284,7 @@ public class MGMLimoApiService {
requestObj.put("itemObject", sb.toString());
requestObj.put("token", token);
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
// ---- Limo format helpers: single-quote + PascalCase + 1/0 for booleans ----
@@ -443,7 +434,7 @@ public class MGMLimoApiService {
requestObj.put("itemObject", sb.toString());
requestObj.put("token", token);
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
private static void appendStringUpdate(StringBuilder sb, String fieldName, String value) {
@@ -499,35 +490,28 @@ public class MGMLimoApiService {
requestObj.put("action", API_UPDATE_BOOKING_STATUS);
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
private String getLimoAccessToken() throws Exception {
String token = ESB_LIMO_ACCESS_TOKEN;
String token = LIMO_ACCESS_TOKEN;
if (SysCommon.mgmApiMockup)
return token;
ESB_LIMO_APP_ID = SysCommon.apiConfig.getApiKey_ESB();
ESB_LIMO_APP_SECRET = SysCommon.apiConfig.getApiSecret_ESB();
ESB_LIMO_SERVER = SysCommon.apiConfig.getServerUrl_ESB();
if (token == null || ESB_LIMO_EXPIRED_TIME.getTime() < new Date().getTime()) {
if (token == null || LIMO_EXPIRED_TIME.isBefore(LocalDateTime.now())) {
String itemObject = String.format(
"{'LoginID':'%s','Password':'%s'}",
apiGetAccessTokenId,
apiGetAccessTokenPwd);
apiGatewaySetting.getLimoAccessAccount(),
apiGatewaySetting.getLimoAccessPassword());
Map<String, String> formData = new HashMap<>();
formData.put("action", API_GET_ACCESS_TOKEN);
formData.put("itemObject", itemObject);
HttpResponseResult result = this.invokeESBFormUrlEncodedAPI(
ESB_LIMO_SERVER,
API_MAIN_HANDLER,
apiGatewaySetting.getLimoProxyUrl(),
apiGatewaySetting.getLimoMainHandleUrl(),
formData,
"POST",
null);
@@ -538,10 +522,12 @@ public class MGMLimoApiService {
if (Strings.CI.equals("200", status)) {
token = resultObj.getString("token");
ESB_LIMO_ACCESS_TOKEN = token;
LIMO_ACCESS_TOKEN = token;
LIMO_EXPIRED_TIME = LocalDateTime.now().plusSeconds(apiGatewaySetting.getLimoTokenExpirySecond());
} else {
token = null;
ESB_LIMO_ACCESS_TOKEN = null;
LIMO_ACCESS_TOKEN = null;
LIMO_EXPIRED_TIME = LocalDateTime.now();
}
}
}
@@ -557,8 +543,12 @@ public class MGMLimoApiService {
Map<String, String> requestHeader) throws Exception {
HttpRequestDefine requestDef = new HttpRequestDefine();
String requestUrl = requestLink;
String requestUrl = serverUrl+requestLink;
Map<String, String> headers = (requestHeader == null ? new HashMap<>() : new HashMap<>(requestHeader));
//-- set proxy authorization
headers.put("application-id", apiGatewaySetting.getLimoAppId());
headers.put("Authorization", apiGatewaySetting.getLimoAppSecret());
//--
String requestBody = buildFormUrlEncodedBody(formData);
requestDef.setRequestUrl(requestUrl);
@@ -589,9 +579,8 @@ public class MGMLimoApiService {
}
String responseContent = httpResult.getResponseContent();
int responseLength = (responseContent == null ? 0 : responseContent.length());
LogUtil.info(MGMLimoApiService.class, "[invokeFormUrlEncodedAPI] Limo action:" + (formData == null ? null : formData.get("action"))
+ " Limo ResponseLength:" + responseLength
+ " Limo Response:" + responseContent
+ " Status=" + httpResult.getStatusCode());
httpResult.setRequestContent(requestBody);
@@ -3,10 +3,18 @@ package com.mgm.mcrm.common.utils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class EncryptUtil {
private static final String AES_TRANSFORMATION = "AES/GCM/NoPadding";
private static final int GCM_IV_LENGTH = 12;
private static final int GCM_TAG_LENGTH = 16;
public static String sha256(String plainString) {
String cipherString = null;
try {
@@ -26,4 +34,43 @@ public class EncryptUtil {
return cipherString;
}
/**
* 与前端 cfgSettingCrypto.normalizeSecret 对齐:去空白、去 UTF-8 BOM,
* 避免 properties 或编辑器带入不可见字符导致与客户端 SHA-256 密钥不一致。
*/
public static String normalizeAllowKey(String secret) {
if (secret == null) {
return null;
}
String s = secret.trim();
if (!s.isEmpty() && s.charAt(0) == '\uFEFF') {
s = s.substring(1);
}
return s;
}
public static String aesEncryptToBase64(String plainText, String secret) {
if (plainText == null || secret == null || secret.isEmpty()) {
return null;
}
try {
secret = normalizeAllowKey(secret);
if (secret == null || secret.isEmpty()) {
return null;
}
byte[] keyBytes = MessageDigest.getInstance("SHA-256").digest(secret.getBytes(StandardCharsets.UTF_8));
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
byte[] iv = new byte[GCM_IV_LENGTH];
new SecureRandom().nextBytes(iv);
Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(iv) + ":" + Base64.getEncoder().encodeToString(encrypted);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
@@ -773,22 +773,31 @@ public class ExcelUtils {
public static void exportToResponse(ExportDefine reportDef, String reportFileName, Map<String,List<Object>> exportData,Map<String,List<GroupItem>> groupKeys, HttpServletResponse response, HttpServletRequest request) throws Exception {
File file = ExcelUtils.exportEXCEL(reportDef,exportData,groupKeys);
String origin = request.getHeader("Origin");
String sanitizedOrigin = NetworkUtil.encodePathWithSpring(origin);
response.reset();
String basePath = SysCommon.runtime_path + "\\"+SysCommon.runtimeName+"\\tmp\\";
String filePath = file.getCanonicalPath();
basePath = basePath.replace("/", "\\");
filePath = filePath.replace("/", "\\");
if (!filePath.startsWith(basePath)) {
throw new SecurityException("Invalid file path");
}
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Expose-Headers", "Location");
response.setHeader("Access-Control-Expose-Headers", "content-disposition");
response.setContentType("application/vnd.ms-excel; charset=utf-8");
response.setHeader("content-disposition",
"attachment;filename=" + (StringUtils.isNotBlank(reportFileName)?reportFileName:reportDef.getExportFileName()));
response.getOutputStream().write(FileUtils.readFileToByteArray(file));
ExcelUtils.clearTempFile(file.getName());
if(SysCommon.isAllowOriginSource(sanitizedOrigin)) {
String basePath = SysCommon.runtime_path + "\\"+SysCommon.runtimeName+"\\tmp\\";
String filePath = file.getCanonicalPath();
basePath = basePath.replace("/", "\\");
filePath = filePath.replace("/", "\\");
if (!filePath.startsWith(basePath)) {
throw new SecurityException("Invalid file path");
}
response.setHeader("Access-Control-Allow-Origin",sanitizedOrigin);
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Expose-Headers", "Location");
response.setHeader("Access-Control-Expose-Headers", "content-disposition");
response.setContentType("application/vnd.ms-excel; charset=utf-8");
response.setHeader("content-disposition",
"attachment;filename=" + (StringUtils.isNotBlank(reportFileName)?reportFileName:reportDef.getExportFileName()));
response.getOutputStream().write(FileUtils.readFileToByteArray(file));
ExcelUtils.clearTempFile(file.getName());
}else {
LogUtil.warn(ExcelUtils.class, "Origin of ["+sanitizedOrigin+"] is not allowed");
errorResponse("Download is not allowed from this site",request,response);
}
}
public static void errorResponse(String errorMessage,HttpServletRequest request, HttpServletResponse response) throws Exception {
//response.setContentType("text/html");
@@ -38,7 +38,9 @@ import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
@@ -51,14 +53,14 @@ public class HttpUtil {
HttpResponseResult responseResult = new HttpResponseResult();
CloseableHttpClient httpclient=null;
CloseableHttpResponse response = null;
String requestUrl =request.getRequestUrl();
if(!NetworkUtil.isValidURL(requestUrl)){
throw new SecurityException("Invalid URL of ["+requestUrl+"]");
String orgRequestUrl =request.getRequestUrl();
if(!NetworkUtil.isValidURL(orgRequestUrl)){
throw new SecurityException("Invalid URL of ["+orgRequestUrl+"]");
}
if (!SysCommon.isAllowApiServer(requestUrl)) {
if (!SysCommon.isAllowApiServer(orgRequestUrl)) {
throw new SecurityException("URL not allowed");
}
requestUrl = NetworkUtil.encodePathWithSpring(requestUrl);
String requestUrl = NetworkUtil.validateAndSanitizeUrl(orgRequestUrl);
try {
//--
RequestConfig.Builder configBuilder = RequestConfig.custom();
@@ -98,18 +100,19 @@ public class HttpUtil {
HttpClientContext context = HttpClientContext.create();
//--
if(Strings.CI.equals("POST", request.getRequestMethod())) {
HttpPost httppost = new HttpPost(requestUrl);
URI url = new URI(requestUrl);
HttpPost httppost = new HttpPost(url);
httppost.setConfig(requestConfig);
if(request.isUpload()!=true) {
if(!request.isUpload()) {
if(request.getHeaders()!=null) {
Map<String, String> headermap = request.getHeaders();
for (Map.Entry<String, String> entry : headermap.entrySet()) {
if(!Strings.CI.equals("Content-Length",entry.getKey())){
httppost.addHeader(entry.getKey(), NetworkUtil.sanitizeHeaderValue(entry.getValue()));
httppost.addHeader(entry.getKey(), NetworkUtil.sanitizeCRLF(entry.getValue()));
}
}
}
httppost.setEntity(new StringEntity(request.getEntityContent(), Charset.forName("UTF-8")));
httppost.setEntity(new StringEntity(request.getEntityContent(), StandardCharsets.UTF_8));
responseResult.setRequestContent(request.getEntityContent());
response = httpclient.execute(httppost,context);
}else {
@@ -128,7 +131,7 @@ public class HttpUtil {
Map<String, String> headermap = request.getHeaders();
for (Map.Entry<String, String> entry : headermap.entrySet()) {
if(!Strings.CI.equals("Content-Length",entry.getKey())){
httpput.addHeader(entry.getKey(), NetworkUtil.sanitizeHeaderValue(entry.getValue()));
httpput.addHeader(entry.getKey(), NetworkUtil.sanitizeCRLF(entry.getValue()));
}
}
}
@@ -147,7 +150,7 @@ public class HttpUtil {
Map<String, String> headermap = request.getHeaders();
for (Map.Entry<String, String> entry : headermap.entrySet()) {
if(!Strings.CI.equals("Content-Length",entry.getKey())){
httpget.addHeader(entry.getKey(), NetworkUtil.sanitizeHeaderValue(entry.getValue()));
httpget.addHeader(entry.getKey(), NetworkUtil.sanitizeCRLF(entry.getValue()));
}
}
}
@@ -6,15 +6,10 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.web.util.UriUtils;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URI;
import java.lang.management.ManagementFactory;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -27,7 +22,19 @@ public class NetworkUtil {
"10.", "192.168.", "172.16.", "172.17.", "172.18.", "172.19.",
"172.20.", "172.21.", "172.22.", "172.23.", "172.24.", "172.25.",
"172.26.", "172.27.", "172.28.", "172.29.", "172.30.", "172.31."
);
private static final Set<String> ALLOWED_PROTOCOLS = new HashSet<>(
Arrays.asList("http", "https")
);
// 禁止的端口
private static final Set<Integer> BLOCKED_PORTS = new HashSet<>(
Arrays.asList(22, 23, 25, 53, 110, 143, 3306, 5432, 6379, 27017)
);
public static void setInternalIpPattern(String patternConfig) {
interalIpPatterns.clear();
@@ -167,13 +174,13 @@ public class NetworkUtil {
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
ip = address.nextElement();
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().contains(":")) {// 外网IP
netip = ip.getHostAddress();
ips.add(netip);
finded = true;
break;
} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1) {// 内网IP
&& !ip.getHostAddress().contains(":")) {// 内网IP
localip = ip.getHostAddress();
ips.add(localip);
}
@@ -188,7 +195,7 @@ public class NetworkUtil {
* @return the real ip
*/
public static String getRealIp() {
return getRealIps().iterator().next();
return Objects.requireNonNull(getRealIps()).getFirst();
}
/**
@@ -202,22 +209,22 @@ public class NetworkUtil {
// 外网IP
String netip = null;
try {
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
// 是否找到外网IP
boolean finded = false;
while (netInterfaces.hasMoreElements() && !finded) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
Enumeration address = ni.getInetAddresses();
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
ip = (InetAddress) address.nextElement();
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().contains(":")) {
// 外网IP
netip = ip.getHostAddress();
finded = true;
break;
} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1) {
&& !ip.getHostAddress().contains(":")) {
// 内网IP
localip = ip.getHostAddress();
}
@@ -227,7 +234,7 @@ public class NetworkUtil {
e.printStackTrace();
}
if (netip != null && !"".equals(netip)) {
if (netip != null && !netip.isEmpty()) {
return netip;
} else {
return localip;
@@ -350,10 +357,7 @@ public class NetworkUtil {
if(!"https".equals(scheme) && !"http".equals(scheme)) {
return false;
}
if(host.matches("\\d+\\.\\d+\\.\\d+\\.\\d+")) {
return false;
}
return true;
return !host.matches("\\d+\\.\\d+\\.\\d+\\.\\d+");
} catch (Exception e) {
return false;
}
@@ -378,4 +382,116 @@ public class NetworkUtil {
value= value.replace("\r", "").replace("\n", "");
return UriUtils.encodePath(value, StandardCharsets.UTF_8);
}
public static String sanitizeCRLF(String input){
if(input==null)
return null;
return input.replaceAll("[\r\n]+", "");
}
public static String validateAndSanitizeUrl(String userInputUrl) throws SecurityException {
if (userInputUrl == null || userInputUrl.trim().isEmpty()) {
throw new SecurityException("URL should not be blank");
}
try {
// 1. 解析URL
URL url = new URI(userInputUrl).toURL();
// 2. 验证协议
validateProtocol(url.getProtocol());
// 3. 验证主机名/IP
String host = url.getHost();
validateHost(host);
// 4. 验证端口
int port = url.getPort();
if (port == -1) {
port = url.getDefaultPort();
}
validatePort(port);
// 5. 验证路径(防止路径遍历)
validatePath(url.getPath());
// 6. 返回净化后的URL(标准化)
return sanitizeUrl(url);
} catch (Exception e) {
throw new SecurityException("Invalid URL: " + e.getMessage(), e);
}
}
private static void validateProtocol(String protocol) throws SecurityException {
if (!ALLOWED_PROTOCOLS.contains(protocol.toLowerCase())) {
throw new SecurityException("No support protocol: " + protocol + ", only for HTTP/HTTPS");
}
}
private static void validateHost(String host) throws SecurityException {
if (host == null || host.isEmpty()) {
throw new SecurityException("Host name can not be empty");
}
// 解析IP并验证
try {
InetAddress address = InetAddress.getByName(host);
String ip = address.getHostAddress();
// 检查是否为回环地址(Debug 模式下允许,便于本地联调)
if (address.isLoopbackAddress() && !isDebugMode()) {
throw new SecurityException("Forbit loopback address");
}
} catch (UnknownHostException e) {
throw new SecurityException("Invalid host: " + host);
}
}
private static boolean isDebugMode() {
if (SysCommon.appDebugLog) {
return true;
}
return ManagementFactory.getRuntimeMXBean().getInputArguments().stream()
.anyMatch(arg -> arg.contains("-agentlib:jdwp") || arg.contains("-Xrunjdwp"));
}
private static void validatePort(int port) throws SecurityException {
// 检查是否为禁止端口
if (BLOCKED_PORTS.contains(port)) {
throw new SecurityException("Invalid Port: " + port);
}
}
private static void validatePath(String path) throws SecurityException {
if (path == null) return;
// 防止路径遍历攻击
if (path.contains("..")) {
throw new SecurityException("Invalid path contains '..'");
}
if (path.toLowerCase().contains("://")) {
throw new SecurityException("Invalid path prefix");
}
}
private static String sanitizeUrl(URL url) {
StringBuilder sb = new StringBuilder();
sb.append(url.getProtocol()).append("://");
sb.append(url.getHost());
int port = url.getPort();
if (port != -1 && port != url.getDefaultPort()) {
sb.append(":").append(port);
}
sb.append(url.getPath());
String query = url.getQuery();
if (query != null && !query.isEmpty()) {
sb.append("?").append(query);
}
return sb.toString();
}
}
@@ -1,12 +1,14 @@
package com.mgm.mcrm.common.utils;
import com.mgm.mcrm.common.constants.SysCommon;
import com.mgm.mcrm.common.dtos.config.ApiGatewaySetting;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.soap.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.hc.core5.http.message.BasicHeader;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
@@ -15,6 +17,7 @@ import javax.xml.namespace.QName;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
@@ -37,7 +40,7 @@ public class SOAPUtil {
* 参考---》http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?op=getWeatherbyCityName
*/
public static String getWebServiceSOAP(String url,String action,StringBuffer sendSoapString){
public static String getWebServiceSOAP(String url, String action, StringBuffer sendSoapString, ApiGatewaySetting apiGatewaySetting){
String soap = sendSoapString.toString();
if (soap == null) {
return null;
@@ -58,8 +61,12 @@ public class SOAPUtil {
conn.setRequestProperty("Content-Length",
Integer.toString(soap.length()));
conn.setRequestProperty("Content-Type", "text/xml; charset=GBK");
conn.setConnectTimeout(SysCommon.apiConfig.getTimeout_OWS());
conn.setReadTimeout(SysCommon.apiConfig.getTimeout_OWS());
//-- set proxy auth code
conn.setRequestProperty("application-id",apiGatewaySetting.getOperaAppId());
conn.setRequestProperty("Authorization",apiGatewaySetting.getOperaAppSecret());
//--
conn.setConnectTimeout(apiGatewaySetting.getRequestTimeout());
conn.setReadTimeout(apiGatewaySetting.getRequestTimeout());
// 调用的接口方法是
conn.setRequestProperty("SOAPAction",action);
OutputStream os = conn.getOutputStream();
@@ -88,7 +95,7 @@ public class SOAPUtil {
return null;
}
public static String getWebServiceSOAPUTF(String url,String action,StringBuffer sendSoapString){
public static String getWebServiceSOAPUTF(String url,String action,StringBuffer sendSoapString, ApiGatewaySetting apiGatewaySetting){
String soap = sendSoapString.toString();
if (soap == null) {
return null;
@@ -109,6 +116,10 @@ public class SOAPUtil {
conn.setRequestProperty("Content-Length",
Integer.toString(soap.length()));
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
//-- set proxy auth code
conn.setRequestProperty("application-id",apiGatewaySetting.getOperaAppId());
conn.setRequestProperty("Authorization",apiGatewaySetting.getOperaAppSecret());
//--
// 调用的接口方法是
conn.setRequestProperty("SOAPAction",action);
OutputStream os = conn.getOutputStream();
@@ -153,33 +164,40 @@ public class SOAPUtil {
}
private static final TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
private X509TrustManager defaultTrustManager=null;
{
try {
// 获取 JVM 默认的 TrustManager 作为核心校验逻辑
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init((KeyStore) null); // 使用系统的默认信任库
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
defaultTrustManager = (X509TrustManager) tm;
}
}
}catch(Exception err){
LogUtil.error(SOAPUtil.class,"Default X509TrustManager not found["+err.getMessage()+"]");
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
return defaultTrustManager.getAcceptedIssuers();
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String arg1) throws CertificateException {
if (chain == null || chain.length == 0) {
throw new IllegalArgumentException("No server certificates provided");
}
for (X509Certificate cert : chain) {
cert.checkValidity();
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
defaultTrustManager.checkServerTrusted(chain,authType);
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String arg1) throws CertificateException {
if (chain == null || chain.length == 0) {
throw new CertificateException("No client certificates provided");
}
for (X509Certificate cert : chain) {
cert.checkValidity(); // 检查证书是否在有效期内
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
defaultTrustManager.checkClientTrusted(chain,authType);
}
}};
private static final HostnameVerifier checkSoapServer = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
boolean isServerAllow = SysCommon.isAllowSoapServer(hostname);
@@ -453,7 +453,6 @@ public class SendEmail {
userName = !StringUtils.isEmpty(userName)?userName:"";
String tUser = userId+" "+userName;
String approvalStatus = EumnApprovalStatus.getApprovalStatusByDBValue(book.getApproveStatus());
content2 += "<tr>"+
"<td>"
@@ -562,6 +561,171 @@ public class SendEmail {
return emailObj;
}
public static Email sendCreateR2Y2NewEmail(Bookings book,BookingsView bookView,Email emailObj,String userId,String userName,boolean isOverBook,boolean isConnectRoom,String emailTo) {
String content1 = emailNewApprovalTemp;
try {
JavaMailSenderImpl sender = new JavaMailSenderImpl();
if(StringUtils.isEmpty(mail_smtp_host)) {
mail_smtp_host = SysCommon.apiConfig.getHost_SMTP();
}
mail_port = Integer.valueOf(SysCommon.apiConfig.getPort_SMTP());
if(StringUtils.isEmpty(mail_sender)) {
mail_sender = SysCommon.apiConfig.getUsername_SMTP();
}
if(StringUtils.isEmpty(mail_sender_password)) {
mail_sender_password = SysCommon.apiConfig.getPassword_SMTP();
}
if(!StringUtils.isEmpty(emailTo)) {
mail_to = emailTo;
}else {
mail_to = SysCommon.apiConfig.getSend_to_SMTP();
}
sender.setHost(mail_smtp_host);
sender.setPort(mail_port); // 默认就是25
sender.setUsername(mail_sender);
sender.setPassword(mail_sender_password);//
sender.setDefaultEncoding("UTF-8");
// 配置文件对象
Properties props = new Properties();
props.put("mail.smtp.auth", "false"); // 是否进行验证
Session session = Session.getInstance(props);
sender.setSession(session); // 为发送器指定会话
MimeMessage mail = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mail, true);
String mainTitle;
if(isConnectRoom) {
mainTitle = "[R2/Y2]";
}else if(isOverBook) {
mainTitle = "[Overbook]";
}else {
mainTitle = "[Urgent]";
}
helper.setSubject(mainTitle+"Booking Creation from Mobile CRM APP"); // 标题
helper.setFrom(mail_sender); // 来自
SimpleDateFormat sf = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String RequestDate = sf.format(new Date());
String content2 = "";
String tTime = RequestDate;
userId = !StringUtils.isEmpty(userId)?userId:"";
userName = !StringUtils.isEmpty(userName)?userName:"";
String tUser = userId+" "+userName;
String approvalStatus = EumnApprovalStatus.getApprovalStatusByDBValue(book.getApproveStatus());
content2 += "<tr>"+
"<td>"
+approvalStatus+
"</td> "+
"<td >"
+bookView.getPlayerId()+
"</td> " +
"<td>"
+bookView.getMemberLastName()+
"</td> " +
"<td>"
+(bookView.getMemberTier()!=null?bookView.getMemberTier():"")+
"</td> " +
"<td>"
+(bookView.getPropertyName()!=null?bookView.getPropertyName():"")+
"</td> " +
"<td>"
+(bookView.getRoom()!=null?bookView.getRoom():"")+
"</td> "+
"<td>"
+(bookView.getSharerName()!=null?bookView.getSharerName():"")+
"</td> " +
"<td>"
+"New"+
"</td> "+
"<td>"
+format.format(bookView.getCheckinDate())+
"</td> " +
"<td>"
+format.format(bookView.getCheckoutDate())+
"</td> " +
"<td>"
+(bookView.getBookerTeam()!=null?bookView.getBookerTeam():"")+
"</td> " +
"<td>"
+bookView.getCreatedBy()+
"</td> " +
"<td>"
+bookView.getCreatedByName()+
"</td> " +
"<td>"
+(bookView.getApprovalRemark()!=null?bookView.getApprovalRemark():"")+
"</td> " +
"<td>"
+(bookView.getRemark()!=null?bookView.getRemark():"")+
"</td> " +
"</tr> ";
String mailContent = isConnectRoom?"Please create TT/YY booking for below approved booking<br><br>":"";
content1 = content1.replace("{{tbody}}", content2);
content1 = content1.replace("{{ttime}}", tTime);
content1 = content1.replace("{{tuser}}", tUser);
content1 = content1.replace("{{content}}", mailContent);
helper.setText(content1,true); // 邮件内容,第二个参数指定发送的是HTML格式
JSONObject emailJson = new JSONObject();
emailJson.put("approvalStatus", approvalStatus);
emailJson.put("memberId", bookView.getPlayerId());
emailJson.put("memberName", bookView.getMemberLastName());
emailJson.put("tier", bookView.getMemberTier());
emailJson.put("property", bookView.getPropertyName());
emailJson.put("roomType", bookView.getRoom());
emailJson.put("type", "New");
emailJson.put("checkin", format.format(bookView.getCheckinDate()));
emailJson.put("checkout", format.format(bookView.getCheckoutDate()));
emailJson.put("bookerTeam", bookView.getBookerTeam());
emailJson.put("bookerId", bookView.getCreatedBy());
emailJson.put("bookerName", bookView.getCreatedByName());
emailJson.put("approvalRemark", bookView.getApprovalRemark());
emailJson.put("remark", bookView.getRemark());
emailObj.setSendObject(emailJson.toJSONString());
emailObj.setContent(content1);
emailObj.setSendTo(mail_to);
String[] mailToArr = StringUtils.split(mail_to,";");
if(mailToArr.length>1) {
for (String str : mailToArr) {
helper.setTo(str);
try {
sender.send(mail); // 发送
emailObj.setStatus(1);
} catch (Exception e) {
emailObj.setMessage("Send Email to "+str+" Failed:"+e.getMessage());
emailObj.setStatus(0);
}
}
}else {
helper.setTo(mail_to);
try {
sender.send(mail); // 发送
emailObj.setStatus(1);
LogUtil.info(SendEmail.class, "---mgmEmail.sendApprovalNewEmail--OK!");
} catch (Exception e) {
emailObj.setMessage("Send Email to "+mail_to+" Failed:"+e.getMessage());
emailObj.setStatus(0);
LogUtil.error(SendEmail.class, "---mgmEmail.sendApprovalNewEmail--Failed!"+e.getMessage());
}
}
} catch (Exception e) {
LogUtil.error(SendEmail.class,"---mgmEmail.sendApprovalNewEmail--Exception-->>"+e.getMessage());
emailObj.setMessage(e.getMessage());
emailObj.setStatus(0);
}
return emailObj;
}
public static Email sendApprovalExtendEmail(Bookings book,BookingsView originBook,Email emailObj,String userId,String userName,BookingsView viewBook,boolean isOverBook,String emailTo) {
String content1 = emailApprovalTemp;
@@ -590,7 +754,7 @@ public class SendEmail {
// 配置文件对象
Properties props = new Properties();
props.put("mail.smtp.auth", "false"); // 是否进行验证
props.put("mail.smtp.auth", "true"); // 是否进行验证
Session session = Session.getInstance(props);
sender.setSession(session); // 为发送器指定会话
@@ -623,7 +787,7 @@ public class SendEmail {
changeCheckInDate = viewBook.getCheckinDate()!=null?format.format(viewBook.getCheckinDate()):"";
}
content2 += "<tr>"+
"<td>"
+approvalStatus+
@@ -928,7 +1092,7 @@ public class SendEmail {
MimeMessageHelper helper = new MimeMessageHelper(mail, true);
String subject = emailTemplate.getSubject();
subject = StringUtils.replace(subject, "[TODAY]",DateTimeUtil.getCurrentDate("dd MMM"));
subject = Strings.CI.replace(subject, "[TODAY]", DateTimeUtil.getCurrentDate("dd MMM"));
helper.setSubject(subject); // 标题
helper.setFrom(mail_sender); // 来自
@@ -44,21 +44,19 @@ public class LimoController {
private MgmUserService userService;
@RequestMapping(value = "/search_limo", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public List limoRecordSearch(HttpServletRequest request, @RequestBody Map<String, Object> params) throws Exception {
HashMap member = (HashMap)params.get("member");
public List<LimoBookings> limoRecordSearch(HttpServletRequest request, @RequestBody Map<String, Object> params) throws Exception {
HashMap member = (HashMap) params.get("member");
String playerId = String.valueOf(member.get("playerId"));
List<LimoBookings> response = new ArrayList<>();
boolean havePermission = sysGroupPermissionService.checkAppPermission(request,"10001_08");
boolean havePermission = sysGroupPermissionService.checkAppPermission(request, "10001_08");
List<LimoBookings> bookingsByPlayerId = null;
if (havePermission) {
if(!SysCommon.mgmApiMockup)
if (!SysCommon.mgmApiMockup)
limoService.getTodayBooking(playerId);
response = limoService.getBookingsByPlayerId(playerId, request);
bookingsByPlayerId = limoService.getBookingsByPlayerId(playerId, request);
}
return response;
return bookingsByPlayerId;
}
@GetMapping("/getTripPriceList")
@@ -4,14 +4,12 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.auth0.jwt.JWT;
import com.mgm.mcrm.appsetting.services.SettingService;
import com.mgm.mcrm.common.constants.SysCommon;
import com.mgm.mcrm.common.dtos.BaseApiResponse;
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.common.dtos.mgm_api.PlayerProfileApiResult;
import com.mgm.mcrm.common.dtos.mgm_api.PlayerProfileEntry;
import com.mgm.mcrm.common.dtos.mgm_api.UserInfoApiRecord;
import com.mgm.mcrm.common.services.MGMApiService;
import com.mgm.mcrm.common.services.MGMEsbApiService;
import com.mgm.mcrm.common.utils.LogUtil;
import com.mgm.mcrm.limo.dtos.request.GetLimoFlightDetailsRequest;
import com.mgm.mcrm.limo.dtos.request.GetLimoTotalAmountRequest;
@@ -20,13 +18,12 @@ import com.mgm.mcrm.limo.dtos.request.InternalUpdateLimoBookingRequest;
import com.mgm.mcrm.limo.dtos.request.RequestPlayerEsbBookerRequest;
import com.mgm.mcrm.limo.dtos.request.*;
import com.mgm.mcrm.limo.dtos.response.*;
import com.mgm.mcrm.common.services.MGMEsbApiService;
import com.mgm.mcrm.common.services.MGMEsbLimoApiService;
import com.mgm.mcrm.common.services.MGMLimoApiService;
import com.mgm.mcrm.player.services.PlayerService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
@@ -52,8 +49,6 @@ import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@Slf4j
@@ -70,13 +65,11 @@ public class LimoService {
@Resource
private LimoBookingDraftRepository limoBookingDraftRepository;
@Resource
private MGMEsbApiService mgmEsbApiService;
private MGMEsbLimoApiService mgmEsbLimoApiService;
@Resource
private MGMLimoApiService mgmLimoApiService;
@Resource
private MGMApiService mgmApiService;
@Resource
private SettingService settingService;
private MGMEsbApiService mgmEsbApiService;
@Resource
private PlayerService playerService;
@Value("${limo.booking-draft.expiry-seconds:120}")
@@ -102,7 +95,7 @@ public class LimoService {
String token = requestHeader.getHeader("Authorization");
String userId = JWT.decode(token).getClaim("login_id").asString();
String userName = userInfo.getUserName();
Integer autoConfirm = 0;
int autoConfirm = 0;
StringBuilder missing = new StringBuilder();
if (request.getPlayerId() == null) {
@@ -140,7 +133,7 @@ public class LimoService {
request.getPickUpPointId(),
request.getDropOffPointId(),
request.getExtraOffPointId(),
parseIntegerOrDefault(request.getHour(), 0),
parseIntegerOrDefault(request.getHour()),
request.getTripType(),
request.getServiceType(),
request.getIsHourlyRate(),
@@ -241,7 +234,7 @@ public class LimoService {
entity.setCreatedAt(nowTs);
entity.setUpdatedAt(nowTs);
HttpResponseResult httpResponseResult = mgmEsbApiService.invokeSimpleLimoBookingQualificationStatus(
HttpResponseResult httpResponseResult = mgmEsbLimoApiService.invokeSimpleLimoBookingQualificationStatus(
request.getPlayerId(),
request.getBookingType(),
formatEsbBookingDate(request.getPickUpDatetime()));
@@ -459,7 +452,7 @@ public class LimoService {
request.getPickupPointId(),
request.getDropOffPointIds(),
request.getExtraDropOffPointId(),
parseIntegerOrDefault(String.valueOf(request.getHour()), 0),
parseIntegerOrDefault(String.valueOf(request.getHour())),
request.getTripType(),
request.getServiceType(),
request.getIsHourlyRate(),
@@ -749,7 +742,7 @@ public class LimoService {
String greetTypeIds = defaultString(returnLimoBooking.getGreetType(), "").trim();
String greetTypeNames = resolveGreetTypeNames(greetTypeIds, greetTypeNameMap);
entity.setGreetTypeId(greetTypeIds);
if (StringUtils.hasText(greetTypeNames) || entity == null) {
if (StringUtils.hasText(greetTypeNames)) {
entity.setGreetType(greetTypeNames);
}
@@ -805,7 +798,7 @@ public class LimoService {
//通过ESB接口获取到Limo Booker,即为前端Approver中可选信息
public BaseApiResponse<List<PlayerEsbBookerItem>> getPlayerEsbBooker(RequestPlayerEsbBookerRequest request)
throws Exception {
HttpResponseResult httpResponseResult = mgmEsbApiService.invokeRequestPlayerLimoBooker(request);
HttpResponseResult httpResponseResult = mgmEsbLimoApiService.invokeRequestPlayerLimoBooker(request);
if (httpResponseResult.getStatusCode() != 200) {
return BaseApiResponse.internalServerError(
"ESB HTTP error: " + httpResponseResult.getStatusCode());
@@ -837,7 +830,7 @@ public class LimoService {
//通过ESB接口 获取到当前Booking是否够分,不够分需要填入Overrider
public GetLimoBookingQualificationResponse checkBookingQualification(GetLimoBookingQualificationRequest request)
throws Exception {
HttpResponseResult httpResponseResult = mgmEsbApiService.invokeSimpleLimoBookingQualificationStatus(
HttpResponseResult httpResponseResult = mgmEsbLimoApiService.invokeSimpleLimoBookingQualificationStatus(
request.getPlayerId(), request.getBookingType(), request.getBookingDate());
if (httpResponseResult.getStatusCode() != 200) {
@@ -856,7 +849,7 @@ public class LimoService {
//通过ESB接口 获取到Overriver,当Booking不够分的时候填入Overrider
public GetOverriderInfoResponse getLimoOverriderData(GetLimoBookingGetOverriderRequest request)
throws Exception {
HttpResponseResult httpResponseResult = mgmEsbApiService.invokeLimoOverrider(request.getOverriderInfo());
HttpResponseResult httpResponseResult = mgmEsbLimoApiService.invokeLimoOverrider(request.getOverriderInfo());
if (httpResponseResult.getStatusCode() != 200) {
throw new IllegalStateException(
@@ -875,7 +868,7 @@ public class LimoService {
//通过ESB接口 获取到LimoEmployeeInfo
public GetLimoEmployeeInfoResponse getLimoEmployeeData(GetLimoEmployeeInfoRequest request)
throws Exception {
HttpResponseResult httpResponseResult = mgmEsbApiService.invokeRequestEmployeeInfo(request.getEmployeeId());
HttpResponseResult httpResponseResult = mgmEsbLimoApiService.invokeRequestEmployeeInfo(request.getEmployeeId());
if (httpResponseResult.getStatusCode() != 200) {
throw new IllegalStateException(
@@ -894,7 +887,7 @@ public class LimoService {
LimoBookings target = null;
List<LimoBookings> matchBookings = limoBookingsRepository.findByLimoBookingId(limoBookingId);
if(matchBookings!=null && !matchBookings.isEmpty()){
target = matchBookings.get(0);
target = matchBookings.getFirst();
for(int i=1;i<matchBookings.size();i++){
LogUtil.info(LimoService.class,"Delete duplicate booking id " + limoBookingId);
limoBookingsRepository.delete(matchBookings.get(i));
@@ -909,7 +902,7 @@ public class LimoService {
if (!SysCommon.mgmApiMockup){
//this.getTodayBooking();
HttpResponseResult httpResponseResult = mgmApiService.invokeGetLimoBookingFromLegacy(playerId);
HttpResponseResult httpResponseResult = mgmEsbApiService.invokeGetLimoBookingFromLegacy(playerId);
if (httpResponseResult.getStatusCode() == 200) {
String responseContent = httpResponseResult.getResponseContent();
GetLimoBookingFromLegacyResult resultObj = JSONObject.parseObject(responseContent,GetLimoBookingFromLegacyResult.class,Feature.SupportNonPublicField,Feature.IgnoreNotMatch);
@@ -1170,7 +1163,7 @@ public class LimoService {
// --- Guest Information ---
limoBookingRequest.setPlayerId(request.getPlayerId() != null ? String.valueOf(request.getPlayerId()) : "");
HttpResponseResult httpResponseResult = mgmEsbApiService.invokeLimoPlayerInfo(request.getPlayerId());
HttpResponseResult httpResponseResult = mgmEsbLimoApiService.invokeLimoPlayerInfo(request.getPlayerId());
String responseContent = httpResponseResult.getResponseContent();
GetPlayerInfoResponse getPlayerInfoResponse = JSONObject.parseObject(responseContent, GetPlayerInfoResponse.class);
if(Strings.CS.equals(getPlayerInfoResponse.getStatusCode(),"OK")) {
@@ -1182,7 +1175,7 @@ public class LimoService {
limoBookingRequest.setChineseFirstName(getPlayerInfoResponse.getChineseFirstName());
limoBookingRequest.setSalution(getPlayerInfoResponse.getSalutation());
} catch (Exception e) {
e.printStackTrace();
LogUtil.error(LimoService.class, e.getMessage());
}
}
@@ -2002,7 +1995,7 @@ public class LimoService {
}
return Optional.ofNullable(response.getData()).orElseGet(Collections::emptyList).stream()
.filter(item -> item.getId() != null && item.getId().longValue() == tripPriceId.longValue())
.filter(item -> item.getId() != null && item.getId() == tripPriceId.longValue())
.map(LimoTripPriceItem::getHourlyRate)
.filter(Objects::nonNull)
.findFirst()
@@ -2050,14 +2043,14 @@ public class LimoService {
return value == null ? "" : value.replace("_", "").replace(" ", "").trim().toUpperCase(Locale.ROOT);
}
private static Integer parseIntegerOrDefault(String value, Integer defaultValue) {
private static Integer parseIntegerOrDefault(String value) {
if (!StringUtils.hasText(value)) {
return defaultValue;
return 0;
}
try {
return Integer.parseInt(value.trim());
} catch (NumberFormatException e) {
return defaultValue;
return 0;
}
}
@@ -2264,7 +2257,7 @@ public class LimoService {
}
String value = confirmationNo.trim();
int suffixIndex = org.apache.commons.lang3.StringUtils.indexOfIgnoreCase(value, "-S");
int suffixIndex = org.apache.commons.lang3.Strings.CS.indexOf(value, "-S");
String bookingPart = suffixIndex >= 0 ? value.substring(0, suffixIndex) : value;
int firstDigitIndex = 0;
@@ -12,6 +12,7 @@ import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;
@@ -20,14 +21,13 @@ import java.util.Date;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api")
public class SysLogAppController {
@Resource
private SysLogAppService logService;
@RequestMapping(value = "/system/write_log", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/system/write_log", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
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);
@@ -37,7 +37,7 @@ public class SysLogAppController {
return writeLog(request, appLogDto, limit(user.getLoginId(), 64));
}
@PostMapping(value = "/system/write_public_log", produces = "application/json;charset=UTF-8")
@PostMapping(value = "/system/write_public_log", produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<SysLogApp>> writePublicAppLog(HttpServletRequest request,
@RequestBody(required=true) AppLogDto appLogDto) {
return writeLog(request, appLogDto, "ANONYMOUS");
@@ -7,19 +7,19 @@ import com.mgm.mcrm.logging.services.SysLogConfirmService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api")
public class SysLogConfirmController {
@Resource
private SysLogConfirmService logService;
@RequestMapping(value = "/app/log_confirm/save_confirm_log", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/log_confirm/save_confirm_log", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<SysLogMobileConfirm>> getOperaBookingByConfirmationNo(HttpServletRequest request,
@RequestBody MobileConfirmLogRequest params) {
BaseApiResponse<SysLogMobileConfirm> result =logService.saveConfirm(params);
@@ -7,6 +7,7 @@ import com.mgm.mcrm.notification.services.EmailTemplateService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@@ -14,7 +15,6 @@ import java.util.List;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api")
public class EmailTemplateController {
@@ -22,14 +22,14 @@ public class EmailTemplateController {
private EmailTemplateService emailTemplateService;
@RequestMapping(value = "/web/email_template/send", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/web/email_template/send", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<CfgEmailTemplate>> sendEmailTemplates(HttpServletRequest request, @RequestBody CfgEmailTemplate emailTemplate) {
//--
BaseApiResponse<CfgEmailTemplate> result = emailTemplateService.sendEmailTemplates(emailTemplate,request);
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/web/email_template/generate", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/web/email_template/generate", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<List<CfgEmailTemplate>>> generateEmailTemplates(HttpServletRequest request, @RequestBody(required=true) GenerateBookingEmailRequest generateRequest) {
BaseApiResponse<List<CfgEmailTemplate>> result = new BaseApiResponse<>();
//--
@@ -21,6 +21,7 @@ import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@@ -48,9 +49,9 @@ public class NotificationController {
boolean viewNotification = false;
userPermissions = sysGroupPermissionService.getRouterPermissionsByGroupName(groupName);
if(userPermissions.size()>0) {
if(!userPermissions.isEmpty()) {
for(SysRouterPermission per:userPermissions) {
if(StringUtils.equals(per.getId(), "10001_06") ) viewNotification = true;
if(Strings.CI.equals(per.getId(), "10001_06") ) viewNotification = true;
}
}
if (viewNotification) {
@@ -72,7 +73,7 @@ public class NotificationController {
return notificationService.countNotificationByUserId(userId,groupName);
}
@PostMapping("/change_status")
@PostMapping(value="/change_status", produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ChangeNotificationStatusResponse changeStatus(@RequestBody ChangeNotificationStatusRequest request) {
Long id = request != null ? request.getId() : null;
return notificationService.changeStatus(id);
@@ -95,12 +96,13 @@ public class NotificationController {
@ApiResponse(responseCode = "200", description = "Access Token generated successful"),
@ApiResponse(responseCode = "401", description = "Authorization key not math")
})
@PostMapping(value="/send_notification",produces = "application/json;charset=UTF-8")
@PostMapping(value="/send_notification",produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<String>> sendNotification(
HttpServletRequest request,
@Parameter(description = "Notification request info", required = true) @Valid @RequestBody SendNotificationRequest requestData) {
LoginUserInfo requestUser = SysCommon.parseUserFromToken(request);
if(requestUser!=null){
requestData.setRequestorId(requestUser.getLoginId());
BaseApiResponse<String> responseData = notificationService.sendNotificationByRequest(request,requestData);
return ResponseEntity.status(HttpStatus.OK).body(responseData);
}else{
@@ -27,4 +27,6 @@ public class SendNotificationRequest {
@Schema(description = "Type of booking ")
private String type;
private String requestorId;
}
@@ -1,6 +1,7 @@
package com.mgm.mcrm.notification.services;
import com.alibaba.fastjson.JSON;
import com.mgm.mcrm.approval.repositories.ApprovalRoutingDao;
import com.mgm.mcrm.authorization.models.SysRouterPermission;
import com.mgm.mcrm.authorization.services.SysGroupPermissionService;
import com.mgm.mcrm.basesetting.daylight.dtos.response.ProfileDetailResponse;
@@ -23,6 +24,7 @@ import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.hc.core5.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
@@ -37,6 +39,8 @@ public class NotificationService {
private SysGroupPermissionService sysGroupPermissionService;
@Resource
private HttpService httpService;
@Autowired
private ApprovalRoutingDao approvalRoutingDao;
public GetNotificationResponse getNotificationByUserId(String userId){
GetNotificationResponse response = new GetNotificationResponse();
@@ -64,6 +68,10 @@ public class NotificationService {
response.setNotificationCount(sysLogNotificationRepository.countByUserIdAndStatus(userId, 0));
count+=sysLogNotificationRepository.countByUserIdAndStatus(userId, 0);
}
if (viewApprovalRouting) {
response.setApprovalRoutingCount(approvalRoutingDao.countApprovalList(userId));
count+=approvalRoutingDao.countApprovalList(userId);
}
response.setCount(count);
return response;
}
@@ -103,7 +111,6 @@ public class NotificationService {
String url = "/send_notification";
// 获取对应的值
Header[] headers = HttpHeaderBuilder.custom()
.authorization(request.getHeader("Authorization"))
.contentType("application/json")
.build();
HttpResult responseData = httpService.sslSendNotification(url, headers, requestData);
@@ -19,6 +19,7 @@ import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@@ -26,7 +27,6 @@ import java.util.List;
import java.util.Map;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api")
public class PlayerController {
@@ -36,7 +36,7 @@ public class PlayerController {
@Resource
private SysSettingService sysSettingService;
@RequestMapping(value = "/app/mgm/player_lookup", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/mgm/player_lookup", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public BaseApiResponse<PlayerProfileEntry> getPlayerProfileByPlayerId(HttpServletRequest request, @RequestBody(required=false) Map<String,String> params) {
String playerId = params.get("playerId");
// String userId = params.get("userId");
@@ -59,7 +59,7 @@ public class PlayerController {
return result;
}
@RequestMapping(value = "/app/mgm/check_tpd_by_playerId_room_dates", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/mgm/check_tpd_by_playerId_room_dates", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<PlayerTPDApiResult>> checkTPDByPlayerIdAndRoomCatAndDates(HttpServletRequest request,
@RequestBody(required=true) CheckTPDRequest params) {
String playerId = params.getPlayerId();
@@ -95,7 +95,7 @@ public class PlayerController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/app/mgm/check_second_tpd_by_playerId_room_dates", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/mgm/check_second_tpd_by_playerId_room_dates", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<PlayerTPDApiResult>> checkSecondRoomTPDByPlayerIdAndRoomCatAndDates(HttpServletRequest request,
@RequestBody(required=true) CheckSecondTPDRequest params) {
String playerId = params.getPlayerId();
@@ -137,7 +137,7 @@ public class PlayerController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/web/player/lookup", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/web/player/lookup", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<PlayerProfileEntry>> lookupPlayer(HttpServletRequest request, HttpServletResponse response,
@RequestBody WebPlayerLookupRequest params) throws Exception {
BaseApiResponse<PlayerProfileEntry> processResult = new BaseApiResponse<>();
@@ -163,7 +163,7 @@ public class PlayerController {
return ResponseEntity.status(HttpStatus.OK).body(processResult);
}
@RequestMapping(value = "/web/mgm/check_tpd_by_playerId_room_dates", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/web/mgm/check_tpd_by_playerId_room_dates", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<PlayerTPDApiResult>> checkFirstRoomCriteria(HttpServletRequest request,
@RequestBody WebCheckPlayerTPDRequest params) {
String playerId = params.getPlayerId();
@@ -176,7 +176,7 @@ public class PlayerController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/web/mgm/check_second_tpd_by_playerId_room_dates", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/web/mgm/check_second_tpd_by_playerId_room_dates", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<PlayerTPDApiResult>> checkSecondRoomCriteria(HttpServletRequest request,
@RequestBody WebCheckPlayerTPDRequest params) {
String playerId = params.getPlayerId();
@@ -23,6 +23,7 @@ import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@@ -31,7 +32,6 @@ import java.util.ArrayList;
import java.util.List;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api")
public class TodoController {
@@ -47,7 +47,7 @@ public class TodoController {
@Resource
private SysGroupPermissionService sysGroupPermissionService;
@RequestMapping(value = "/app/todo/get_dashboard_data", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/todo/get_dashboard_data", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<TodoDashboardResult>> getTodoDashboard(HttpServletRequest request, @RequestBody GetDashboardRequest getDashboardRequest) throws Exception {
LoginUserInfo loginUser = SysCommon.parseUserFromToken(request);
@@ -74,7 +74,7 @@ public class TodoController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/app/todo/get_todolist_details", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/todo/get_todolist_details", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<TodoDetailResult>> getTodoDetail(HttpServletRequest request, @RequestBody GetTodoDetailRequest getTodoDetailRequest) throws Exception {
String playerId = getTodoDetailRequest.getPlayerId();
String todoSegment = getTodoDetailRequest.getTodosegment();
@@ -91,12 +91,13 @@ public class TodoController {
}else {
result.setSuccess(false);
result.setCode(getTodoDetailResponse.getErrorCode());
result.setMessage(getTodoDetailResponse.getErrorMessage());
}
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/app/todo/get_todolist", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/todo/get_todolist", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<TodoDateListResult>> getTodoList(HttpServletRequest request, @RequestBody GetTodoListRequest params) throws Exception {
LoginUserInfo loginUser = SysCommon.parseUserFromToken(request);
@@ -128,7 +129,7 @@ public class TodoController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/app/todo/change_date", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/todo/change_date", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<BookingDto>> changeDate(HttpServletRequest request, @RequestBody TodoChangeDateRequest bookingParams) throws Exception {
BaseApiResponse<BookingDto> result = new BaseApiResponse<>();
result.setRequestData(bookingParams);
@@ -174,7 +175,7 @@ public class TodoController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/app/todo/submit_ETA", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/todo/submit_ETA", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<Bookings>> submitETA(HttpServletRequest request,
@RequestBody TodoSubmitETARequest params) throws Exception {
LoginUserInfo loginUser = SysCommon.parseUserFromToken(request);
@@ -219,7 +220,7 @@ public class TodoController {
return ResponseEntity.status(HttpStatus.OK).body(result);
}
@RequestMapping(value = "/app/todo/cancel_booking", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/app/todo/cancel_booking", method = RequestMethod.POST, produces = "application/json;charset=UTF-8",consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseApiResponse<Object>> cancelBooking(HttpServletRequest request,
@RequestBody TodoCancelBookingRequest cancelRequest) throws Exception {
LoginUserInfo loginUser = SysCommon.parseUserFromToken(request);
@@ -1,6 +1,7 @@
package com.mgm.mcrm.player.dtos.request;
import com.mgm.mcrm.booking.dtos.BookingDateEntry;
import com.mgm.mcrm.player.dtos.UserInfo;
import lombok.Data;
import java.util.Date;
@@ -22,4 +23,5 @@ public class TodoChangeDateRequest {
private Long segmentId;
private List<BookingDateEntry> dateList;
private List<BookingDateEntry> extendDate;
private UserInfo user;
}
@@ -10,7 +10,7 @@ import com.mgm.mcrm.common.dtos.BaseApiResponse;
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.common.dtos.mgm_api.PlayerProfileEntry;
import com.mgm.mcrm.common.dtos.mgm_api.PlayerTPDApiResult;
import com.mgm.mcrm.common.services.MGMApiService;
import com.mgm.mcrm.common.services.MGMEsbApiService;
import com.mgm.mcrm.player.dtos.PlayerTPD;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
@@ -26,7 +26,7 @@ import java.util.Random;
public class PlayerService {
@Resource
private MGMApiService mgmApiService;
private MGMEsbApiService mgmEsbApiService;
@Resource
private SysSettingService sysSettingService;
@@ -39,7 +39,7 @@ public class PlayerService {
HttpResponseResult httpResult;
try {
// Daylight profile 调用不再需要 token,这里直接调用 MGM API
httpResult = mgmApiService.invokeGetPlayerProfile(playerId, userId);
httpResult = mgmEsbApiService.invokeGetPlayerProfile(playerId, userId);
if (httpResult.getStatusCode() != 200) {
result.setSuccess(false);
@@ -102,7 +102,7 @@ public class PlayerService {
HttpResponseResult httpResult;
try {
httpResult = mgmApiService.invokeGetAllPlayerProfile(playerId);
httpResult = mgmEsbApiService.invokeGetAllPlayerProfile(playerId);
if (httpResult.getStatusCode() != 200) {
result.setSuccess(false);
@@ -165,7 +165,7 @@ public class PlayerService {
HttpResponseResult httpResult;
try {
httpResult = mgmApiService.invokeCheckPlayerTPD(playerId, roomCate, dates, bookingType, property);
httpResult = mgmEsbApiService.invokeCheckPlayerTPD(playerId, roomCate, dates, bookingType, property);
if (httpResult.getStatusCode() != 200) {
result.setSuccess(false);
@@ -279,7 +279,7 @@ public class PlayerService {
HttpResponseResult httpResult;
try {
httpResult = mgmApiService.invokeCheckPlayerSecondTPD(playerId, roomCate, dateRange, bookingType, property);
httpResult = mgmEsbApiService.invokeCheckPlayerSecondTPD(playerId, roomCate, dateRange, bookingType, property);
if (httpResult.getStatusCode() != 200) {
result.setSuccess(false);
result.setMessage("Invoke check player second TPD Failed:[" + httpResult.getStatusCode() + "] " + httpResult.getErrorMessage());
@@ -34,7 +34,7 @@ import com.mgm.mcrm.common.dtos.BaseApiResponse;
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.common.dtos.mgm_api.*;
import com.mgm.mcrm.common.services.HttpService;
import com.mgm.mcrm.common.services.MGMApiService;
import com.mgm.mcrm.common.services.MGMEsbApiService;
import com.mgm.mcrm.common.utils.DateTimeUtil;
import com.mgm.mcrm.common.utils.LogUtil;
import com.mgm.mcrm.common.utils.SendEmail;
@@ -67,7 +67,7 @@ import java.util.concurrent.TimeUnit;
public class TodoService {
@Resource
private MGMApiService mgmApiService;
private MGMEsbApiService mgmEsbApiService;
@Resource
private SysSettingService sysSettingService;
@@ -129,7 +129,7 @@ public class TodoService {
GetDashboardResponse result = new GetDashboardResponse();
try {
HttpResponseResult httpResult = mgmApiService.invokeGetTodoDashboard(userId, 0);
HttpResponseResult httpResult = mgmEsbApiService.invokeGetTodoDashboard(userId, 0);
try {
TodoDashboardResult resultObj = JSONObject.parseObject(httpResult.getResponseContent(), TodoDashboardResult.class, Feature.SupportNonPublicField, Feature.IgnoreNotMatch);
if (Strings.CI.equals(resultObj.getStatusCode(), "OK")) {
@@ -159,7 +159,7 @@ public class TodoService {
public GetTodoDetailResponse getTodoDetail(String playerId, String todoCategory, String todoSegment, String date) throws Exception {
GetTodoDetailResponse result = new GetTodoDetailResponse();
try {
HttpResponseResult httpResult = mgmApiService.invokeGetTodoDetail(playerId, todoCategory, todoSegment, date, 1);
HttpResponseResult httpResult = mgmEsbApiService.invokeGetTodoDetail(playerId, todoCategory, todoSegment, date, 1);
try {
TodoDetailResult resultObj = JSONObject.parseObject(httpResult.getResponseContent(), TodoDetailResult.class, Feature.SupportNonPublicField, Feature.IgnoreNotMatch);
if (Strings.CI.equals(resultObj.getStatusCode(), "OK")) {
@@ -185,66 +185,74 @@ public class TodoService {
if ("Inhouse".equalsIgnoreCase(todoCategory) || "Arrival".equalsIgnoreCase(todoCategory)) {
Bookings bookings = bookingDao.findFirstByConfirmationNoAndPropertyIdIsNotNull(confNum);
CfgProperties property = propertyDao.findById(bookings.getPropertyId()).orElse(null);
if (Objects.nonNull(bookings)) {
CfgProperties property = propertyDao.findById(bookings.getPropertyId()).orElse(null);
if (Objects.nonNull(property)) {
if (Objects.nonNull(property)) {
if ("Inhouse".equalsIgnoreCase(todoCategory)) {
// Parse checkinDate from recordDesc (e.g., "Jun 25 – Jul 1 ...")
LocalDate ciDate = null;
try {
String ciDatePart = recordDesc.split("–")[0].trim();
// Use the year from the 'date' parameter
int year = Integer.parseInt(date.substring(0, 4));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy", Locale.US);
ciDate = LocalDate.parse(ciDatePart + " " + year, formatter);
} catch (Exception e) {
LogUtil.warn(TodoService.class, "Parse checkinDate error: " + e.getMessage() + ", recordDesc: " + recordDesc);
}
if (ciDate != null) {
LocalDate today = LocalDate.now();
if (ciDate.isAfter(today)) {
// 当checkindate大于今天不用拿room number 和room ready
continue;
if ("Inhouse".equalsIgnoreCase(todoCategory)) {
// Parse checkinDate from recordDesc (e.g., "Jun 25 – Jul 1 ...")
LocalDate ciDate = null;
try {
String ciDatePart = recordDesc.split("–")[0].trim();
// Use the year from the 'date' parameter
int year = Integer.parseInt(date.substring(0, 4));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy", Locale.US);
ciDate = LocalDate.parse(ciDatePart + " " + year, formatter);
} catch (Exception e) {
LogUtil.warn(TodoService.class, "Parse checkinDate error: " + e.getMessage() + ", recordDesc: " + recordDesc);
}
BaseApiResponse<ReservationDoorKeyResponse> doorKeyResult =
dlService.getReservationDoorKeyByConfirmationNumber(property.getDlPropertyId(), confNum);
ReservationDoorKeyResponse doorKeyData = doorKeyResult.getData();
if (doorKeyResult.isSuccess() && doorKeyData != null) {
String replaceStr = "Conf#" + confNum;
if (StringUtils.isNotBlank(doorKeyData.getRoomNumber())) {
detailRecord.setRoomNumber(doorKeyData.getRoomNumber());
replaceStr += " [Rm #" + doorKeyData.getRoomNumber() + "]";
if (ciDate != null) {
LocalDate today = LocalDate.now();
if (ciDate.isAfter(today)) {
// 当checkindate大于今天不用拿room number 和room ready
continue;
}
if (ciDate.isEqual(today)) {
// 当今天的时候要检查room ready
boolean isRoomReady = StringUtils.isNotBlank(doorKeyData.getId())
&& !doorKeyData.isHasKey();
if (isRoomReady) {
replaceStr += " [Rm Ready]";
BaseApiResponse<ReservationDoorKeyResponse> doorKeyResult =
dlService.getReservationDoorKeyByConfirmationNumber(property.getDlPropertyId(), confNum);
ReservationDoorKeyResponse doorKeyData = doorKeyResult.getData();
if (doorKeyResult.isSuccess() && doorKeyData != null) {
String replaceStr = "Conf#" + confNum;
if (StringUtils.isNotBlank(doorKeyData.getRoomNumber())) {
detailRecord.setRoomNumber(doorKeyData.getRoomNumber());
replaceStr += " [Rm #" + doorKeyData.getRoomNumber() + "]";
}
if (ciDate.isEqual(today)) {
// 当今天的时候要检查room ready
boolean isRoomReady = StringUtils.isNotBlank(doorKeyData.getId())
&& !doorKeyData.isHasKey();
if (isRoomReady) {
replaceStr += " [Rm Ready]";
}
}
if (!replaceStr.equals("Conf#" + confNum)) {
detailRecord.setItemRecordDescription(recordDesc.replace("Conf#" + confNum, replaceStr));
}
}
if (!replaceStr.equals("Conf#" + confNum)) {
detailRecord.setItemRecordDescription(recordDesc.replace("Conf#" + confNum, replaceStr));
}
}
}else{
BaseApiResponse<ReservationQueueResponse> queueResult =
dlService.getReservationQueueByConfirmationNumber(property.getDlPropertyId(), confNum);
ReservationQueueResponse queueData = queueResult.getData();
boolean isQueue = queueResult.isSuccess()
&& queueData != null
&& queueData.isQueue();
if (isQueue) {
detailRecord.setItemRecordDescription(recordDesc.replace("Conf#" + confNum, "Conf#" + confNum + " [In Queue]"));
}
}
}else{
BaseApiResponse<ReservationQueueResponse> queueResult =
dlService.getReservationQueueByConfirmationNumber(property.getDlPropertyId(), confNum);
ReservationQueueResponse queueData = queueResult.getData();
boolean isQueue = queueResult.isSuccess()
&& queueData != null
&& queueData.isQueue();
if (isQueue) {
detailRecord.setItemRecordDescription(recordDesc.replace("Conf#" + confNum, "Conf#" + confNum + " [In Queue]"));
}
}
} else {
// result.setSuccess(false);
// result.setErrorCode("BOOKING NOT FOUND");
// result.setErrorMessage("BOOKING NOT FOUND");
// LogUtil.warn(TodoService.class, "[GetTodoDetail] BOOKING NOT FOUND");
// return result;
}
}
}
@@ -475,7 +483,7 @@ public class TodoService {
HttpResponseResult httpResult;
try {
// TODO 这里现在写死只拿daylight的todolist,后面会要拿到Opera的todoList,这个时候要改成两个都拿 by Mauve
httpResult = mgmApiService.invokeGetTodoList(userId, category, type, startDate, endDate, 1);
httpResult = mgmEsbApiService.invokeGetTodoList(userId, category, type, startDate, endDate, 1);
} catch (Exception err) {
result.setSuccess(false);
result.setCode("INVOKE_TODOLISTDETAIL_API_ERROR");
@@ -534,31 +542,34 @@ public class TodoService {
if (StringUtils.isNotBlank(confNum)) {
if ("Inhouse".equalsIgnoreCase(category) || "Arrival".equalsIgnoreCase(category)) {
List<CfgProperties> daylightProperties = propertyDao.findByCategory("DAYLIGHT");
if (CollectionUtils.isNotEmpty(daylightProperties)) {
CfgProperties property = daylightProperties.get(0);
if ("Inhouse".equalsIgnoreCase(category)) {
BaseApiResponse<ReservationDoorKeyResponse> doorKeyResult =
dlService.getReservationDoorKeyByConfirmationNumber(property.getDlPropertyId(), confNum);
ReservationDoorKeyResponse doorKeyData = doorKeyResult.getData();
boolean isRoomReady = doorKeyResult.isSuccess()
&& doorKeyData != null
&& StringUtils.isNotBlank(doorKeyData.getId())
&& !doorKeyData.isHasKey();
if (isRoomReady) {
record.setRoomReady(true);
updateTodoRecordDescription(record, confNum, "[Rm Ready]");
}
} else {
BaseApiResponse<ReservationQueueResponse> queueResult =
dlService.getReservationQueueByConfirmationNumber(property.getDlPropertyId(), confNum);
ReservationQueueResponse queueData = queueResult.getData();
boolean isQueue = queueResult.isSuccess()
&& queueData != null
&& queueData.isQueue();
if (isQueue) {
record.setIsQueue(true);
updateTodoRecordDescription(record, confNum, "[In Queue]");
Bookings bookings = bookingDao.findFirstByConfirmationNoAndPropertyIdIsNotNull(confNum);
if (Objects.nonNull(bookings)) {
CfgProperties property = propertyDao.findById(bookings.getPropertyId()).orElse(null);
if (Objects.nonNull(property)) {
if ("Inhouse".equalsIgnoreCase(category)) {
BaseApiResponse<ReservationDoorKeyResponse> doorKeyResult =
dlService.getReservationDoorKeyByConfirmationNumber(property.getDlPropertyId(), confNum);
ReservationDoorKeyResponse doorKeyData = doorKeyResult.getData();
boolean isRoomReady = doorKeyResult.isSuccess()
&& doorKeyData != null
&& StringUtils.isNotBlank(doorKeyData.getId())
&& !doorKeyData.isHasKey();
if (isRoomReady) {
record.setRoomReady(true);
updateTodoRecordDescription(record, confNum, "[Rm Ready]");
}
} else {
BaseApiResponse<ReservationQueueResponse> queueResult =
dlService.getReservationQueueByConfirmationNumber(property.getDlPropertyId(), confNum);
ReservationQueueResponse queueData = queueResult.getData();
boolean isQueue = queueResult.isSuccess()
&& queueData != null
&& queueData.isQueue();
if (isQueue) {
record.setIsQueue(true);
updateTodoRecordDescription(record, confNum, "[In Queue]");
}
}
}
}
@@ -7,7 +7,7 @@ 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.common.services.MGMEsbApiService;
import com.mgm.mcrm.roomcalendar.dtos.RoomCalendarQualification;
import com.mgm.mcrm.roomcalendar.dtos.response.GetPropertyRoomTypeListResponse;
import com.mgm.mcrm.roomcalendar.dtos.response.GetPropertyRoomTypeResponse;
@@ -26,7 +26,7 @@ public class RoomCalendarService {
private boolean calendarDataMockEnabled;
@Resource
private MGMApiService mgmApiService;
private MGMEsbApiService mgmEsbApiService;
@Resource
private PropertyDao propertyDao;
@Resource
@@ -79,7 +79,7 @@ public class RoomCalendarService {
if (StringUtils.isNotBlank(visibility.operaProperty) && StringUtils.isNotBlank(visibility.operaRoomType)) {
try {
HttpResponseResult response = mgmApiService.invokeRequestRoomCalendar(
HttpResponseResult response = mgmEsbApiService.invokeRequestRoomCalendar(
playerId, visibility.operaProperty, visibility.operaRoomType, startDate, endDate, 0);
if (response.getStatusCode() == 200) {
allRecords.addAll(parseRoomCalendarResponse(response.getResponseContent()));
@@ -91,7 +91,7 @@ public class RoomCalendarService {
if (StringUtils.isNotBlank(visibility.daylightProperty) && StringUtils.isNotBlank(visibility.daylightRoomType)) {
try {
HttpResponseResult response = mgmApiService.invokeRequestRoomCalendar(
HttpResponseResult response = mgmEsbApiService.invokeRequestRoomCalendar(
playerId, visibility.daylightProperty, visibility.daylightRoomType, startDate, endDate, 1);
if (response.getStatusCode() == 200) {
allRecords.addAll(parseRoomCalendarResponse(response.getResponseContent()));
@@ -103,7 +103,7 @@ public class RoomCalendarService {
if (StringUtils.isNotBlank(visibility.otherProperty) && StringUtils.isNotBlank(visibility.otherRoomType)) {
try {
HttpResponseResult response = mgmApiService.invokeRequestRoomCalendar(
HttpResponseResult response = mgmEsbApiService.invokeRequestRoomCalendar(
playerId, visibility.otherProperty, visibility.otherRoomType, startDate, endDate, 0);
if (response.getStatusCode() == 200) {
allRecords.addAll(parseRoomCalendarResponse(response.getResponseContent()));
+35 -13
View File
@@ -82,7 +82,7 @@ server:
key-store-type: PKCS12
logging:
config: classpath:logback.xml
config: classpath:log4j2-spring.xml
springdoc:
swagger-ui:
path: /swagger-ui.html
@@ -104,16 +104,42 @@ mcrm:
security:
jwt:
secret-key: SecretKeyWhichShouldBeLongEnoughToBeSecure67848563
api-token-expiration: 5
mobile-session-expiration: 30
api-token-expiration: 5 # 分钟单位
mobile-session-expiration: 43200 # 分钟单位
#============== Daylight Service ===================
daylight:
url: http://localhost:9087/api/daylight/proxy
system-id: 3a151ad3-46be-4644-b656-71d3b037b309
notification_proxy:
url: http://localhost:9087/api/notification/proxy
api-gateway:
base-url: http://localhost:9087
request-timeout-ms: 30000
daylight:
proxy-path: /api/daylight/proxy
system-id: 3a151ad3-46be-4644-b656-71d3b037b309
app-id: MCRM_APP
auth-code: securItykeyOfCrmapp87895312
opera:
proxy-path: /api/opera/proxy
app-id: MCRM_APP
auth-code: securItykeyOfCrmapp87895312
esb-mcrm:
proxy-path: /api/esb/proxy/api/crmapp/v1.0
app-id: MCRM_APP
auth-code: securItykeyOfCrmapp87895312
esb-limo:
proxy-path: /api/esb_limo/proxy/api/limo/v1.0
app-id: MCRM_APP
auth-code: securItykeyOfCrmapp87895312
limo:
proxy-path: /api/limo/proxy
app-id: MCRM_APP
auth-code: securItykeyOfCrmapp87895312
main-handle-url: /MCRMAPI/API/MainHandler.ashx
access-account: test100
access-password: 1234567
token-expiry-seconds: 60
notification:
proxy-path: /api/notification/proxy
app-id: MCRM_APP
auth-code: securItykeyOfCrmapp87895312
sso:
callback:
@@ -169,10 +195,6 @@ calendar:
data-mock-enabled: true
#==================APP Config===================
limo_address: http://mmlimodevapp01/MCRMAPI/API/MainHandler.ashx
limo_getAccessToken_Id: test100
limo_getAccessToken_pwd: 1234567
notification:
recent-hours: 6
+41
View File
@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Properties>
<Property name="logPath">crm_mobile_runtime/logs</Property>
<Property name="logPattern">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Property>
</Properties>
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="${logPattern}"/>
</Console>
<RollingFile name="FILE-APPENDER"
fileName="${logPath}/mobile-api-active.log"
filePattern="${logPath}/mobile-api-%d{yyyy-MM-dd}-%i.log">
<PatternLayout pattern="${logPattern}" />
<Policies>
<SizeBasedTriggeringPolicy size="200 MB"/>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
</Policies>
<DefaultRolloverStrategy max="30"/>
</RollingFile>
</appenders>
<loggers>
<root level="info">
<AppenderRef ref="Console"/>
<appender-ref ref="FILE-APPENDER"/>
</root>
<Logger name="org.springframework" level="WARN" additivity="false">
<AppenderRef ref="Console"/>
<AppenderRef ref="FILE-APPENDER"/>
</Logger>
<Logger name="org.apache.shiro" level="WARN" additivity="false">
<AppenderRef ref="Console"/>
<AppenderRef ref="FILE-APPENDER"/>
</Logger>
<Logger name="org.hibernate" level="WARN" additivity="false">
<AppenderRef ref="Console"/>
<AppenderRef ref="FILE-APPENDER"/>
</Logger>
</loggers>
</Configuration>
-60
View File
@@ -1,60 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--======================================= 本地变量 ======================================== -->
<!--在没有定义${LOG_HOME}系统变量的时候,可以设置此本地变量。提交测试、上线时,要将其注释掉,使用系统变量。 -->
<!-- <property name="LOG_HOME" value="D:/data/logs" /> -->
<!-- 应用名称:和统一配置中的项目代码保持一致(小写) -->
<property name="APP_NAME" value="crm_runtime" />
<!--日志文件保留天数 -->
<property name="LOG_MAX_HISTORY" value="180" />
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径 -->
<!--应用日志文件保存路径 -->
<property name="LOG_APP_HOME" value="${APP_NAME}/logs" />
<!--=========================== 按照每天生成日志文件:默认配置=================================== -->
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%-5level] %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- 按照每天生成日志文件:主项目日志 -->
<appender name="APP"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名 -->
<FileNamePattern>${LOG_APP_HOME}/base.%d{yyyy-MM-dd}.log
</FileNamePattern>
<!--日志文件保留天数 -->
<MaxHistory>${LOG_MAX_HISTORY}</MaxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{500} - %msg%n</pattern>
</encoder>
</appender>
<!--=============================== 日志输出: 默认主业务日志 ====================================== -->
<logger name="org.springframework" level="WARN">
</logger>
<logger name="org.apache.shiro" level="WARN">
</logger>
<logger name="freemarker" level="WARN">
</logger>
<logger name="org.hibernate" level="WARN">
</logger>
<!--
<logger name="org.hibernate.SQL">
<level value="DEBUG" />
</logger>
-->
<root level="INFO">
<appender-ref ref="APP" />
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -6,7 +6,7 @@
"PlayerId": 11010001,
"Date": "Jun 24 (Tue)",
"ActionDate":"2025-07-24",
"OperaConfirmationNo":"12312312",
"OperaConfirmationNo":"MGM Cotai;002101C",
"TierName": "SUPREME 88",
"ChineseName": "劉明浩",
"EnglishName": "IVAN LAU",
@@ -25,7 +25,7 @@
"MA": "Jojo Chan",
"Descriptions": [
"Active Prg:N",
"May7 - May8 Macau -GR | Conf#12312312 | Sharer: Y"
"May7 - May8 Macau -GR | Conf#002101C | Sharer: N"
]
},
{