From a834c7a004d55b97413fdc7b9f56d4cf92326c03 Mon Sep 17 00:00:00 2001 From: bcjang Date: Tue, 29 Jul 2025 16:14:18 +0900 Subject: [PATCH] =?UTF-8?q?=EB=B9=84=EC=A6=88=EB=8B=88=EC=8A=A4=20?= =?UTF-8?q?=EB=A1=9C=EA=B7=B8=20=EA=B5=AC=EC=A1=B0=20=EC=83=9D=EC=84=B1=20?= =?UTF-8?q?=EC=84=9C=EB=B9=84=EC=8A=A4=EB=B3=84=20=EB=B9=84=EC=A6=88?= =?UTF-8?q?=EB=8B=88=EC=8A=A4=20=EB=A1=9C=EA=B7=B8=20=EC=B2=98=EB=A6=AC=20?= =?UTF-8?q?=EC=BD=94=EB=93=9C=20=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../RabbitMq/MessageHandlerService.java | 178 ++++- .../domain/adminlog/AdminItemDeleteLog.java | 17 - .../admin/domain/adminlog/AdminLogBase.java | 76 -- .../domain/adminlog/AdminLoginPermitLog.java | 13 - .../domain/adminlog/AdminPasswordInitLog.java | 16 - .../admin/domain/adminlog/IAdminLog.java | 8 - .../admin/domain/batch/CustomProcessor.java | 18 - .../admin/domain/batch/CustomReader.java | 26 - .../admin/domain/batch/CustomWriter.java | 18 - .../caliverse/admin/domain/batch/TestJob.java | 64 -- .../admin/domain/dao/admin/AdminMapper.java | 2 +- .../admin/domain/dao/admin/GroupMapper.java | 2 +- .../admin/domain/dao/admin/HistoryMapper.java | 22 - .../admin/domain/dao/admin/LandMapper.java | 7 - .../caliverse/admin/domain/entity/Admin.java | 1 + .../admin/domain/entity/EMetaData.java | 1 + .../admin/domain/entity/EReqType.java | 17 + .../{adminlog => entity}/FieldChange.java | 2 +- .../caliverse/admin/domain/entity/InGame.java | 5 + .../caliverse/admin/domain/entity/Mail.java | 1 + .../entity/common/BeforeDataResolver.java | 5 + .../admin/domain/entity/log/LogAction.java | 63 ++ .../admin/domain/entity/log/LogCategory.java | 21 + .../admin/domain/entity/log/LogStatus.java | 13 + .../domain/entity/metaEnum/EGameModeType.java | 25 + .../entity/metaEnum/EJoinInProgressType.java | 9 + .../entity/metaEnum/ETeamAssignmentType.java | 7 + .../metadata/MetaGameModeCommonData.java | 40 ++ .../metadata/MetaGameModeMatchData.java | 35 + .../admin/domain/request/LandRequest.java | 2 - .../admin/domain/request/NoticeRequest.java | 4 +- .../admin/domain/response/GameResponse.java | 57 ++ .../admin/domain/service/AIService.java | 10 +- .../admin/domain/service/AdminService.java | 49 +- .../domain/service/AuthenticateService.java | 15 +- .../domain/service/BattleEventService.java | 60 +- .../domain/service/BlackListService.java | 37 +- .../admin/domain/service/CaliumService.java | 33 +- .../admin/domain/service/DataService.java | 39 +- .../admin/domain/service/EventService.java | 82 ++- .../domain/service/GameSettingService.java | 82 +++ .../admin/domain/service/GroupService.java | 34 +- .../admin/domain/service/HistoryService.java | 26 +- .../admin/domain/service/ItemsService.java | 4 +- .../admin/domain/service/LandService.java | 136 +--- .../admin/domain/service/MailService.java | 106 ++- .../admin/domain/service/MenuService.java | 78 +- .../admin/domain/service/NoticeService.java | 102 +-- .../admin/domain/service/S3Service.java | 3 +- .../service/UserGameSessionService.java | 2 + .../admin/domain/service/UsersService.java | 9 + .../repository/BaseDynamoDBRepository.java | 63 ++ .../Impl/AccountBaseRepositoryImpl.java | 19 - .../repository/Impl/BannerRepositoryImpl.java | 31 +- .../Impl/BattleEventRepositoryImpl.java | 25 +- .../Impl/BuildingRepositoryImpl.java | 28 +- .../Impl/CaliumStorageRepositoryImpl.java | 13 - .../repository/Impl/ItemRepositoryImpl.java | 12 - .../LandAuctionActivityRepositoryImpl.java | 17 - ...ndAuctionHighestBidUserRepositoryImpl.java | 11 - .../Impl/LandAuctionRecordRepositoryImpl.java | 6 - ...ndAuctionRefundBidPriceRepositoryImpl.java | 6 - .../LandAuctionRegistryRepositoryImpl.java | 24 - .../repository/Impl/LandRepositoryImpl.java | 26 - .../Impl/MailJsonRepositoryImpl.java | 19 - .../repository/Impl/MailRepositoryImpl.java | 17 - .../Impl/NicknameRepositoryImpl.java | 7 - .../Impl/OwnedBuildingRepositoryImpl.java | 18 - .../Impl/OwnedLandRepositoryImpl.java | 17 - .../repository/Impl/QuestRepositoryImpl.java | 12 - .../Impl/SystemMetaMailRepositoryImpl.java | 14 - .../UserNicknameRegistryRepositoryImpl.java | 11 - .../dynamodb/service/DynamoDBOperations.java | 2 +- .../dynamodb/service/DynamodbDataService.java | 2 +- .../service/DynamodbLandAuctionService.java | 2 +- .../dynamodb/service/DynamodbLandService.java | 2 +- .../common/annotation/BusinessProcess.java | 14 + .../common/aspect/BusinessProcessAspect.java | 56 ++ .../aspect/DynamoDBTransactionAspect.java | 4 +- .../common/aspect/TransactionIdAspect.java | 2 +- .../common/constants/MysqlConstants.java | 3 + .../admin/global/common/utils/FileUtils.java | 5 +- .../component/MysqlLoggingInterceptor.java | 138 ++++ .../component/manager/BeforeDataResolver.java | 381 ++++++++++ .../manager/BusinessProcessIdManager.java | 38 + .../DynamoDBTransactionContext.java | 2 +- .../TransactionIdManager.java | 2 +- .../configuration/BatchConfiguration.java | 163 ----- .../global/configuration/MybatisConfig.java | 13 +- .../configuration/TestBatchConfiguration.java | 162 ----- .../admin/mongodb/ChangeDetector.java | 2 +- .../admin/mongodb/domain/BatchJobDomain.java | 19 + .../admin/mongodb/domain/BusinessLog.java | 53 ++ .../admin/mongodb/domain/DataInitDomain.java | 17 + .../admin/mongodb/domain/DynamodbDomain.java | 23 + .../domain/DynamodbHistoryLogInfo.java | 2 +- .../mongodb/domain/HistoryLogInfoBase.java | 2 +- .../admin/mongodb/domain/MariadbDomain.java | 20 + .../mongodb/domain/MessageQueueDomain.java | 16 + .../mongodb/domain/MysqlHistoryLogInfo.java | 2 +- .../admin/mongodb/domain/RedisDomain.java | 15 + .../admin/mongodb/domain/S3Domain.java | 17 + .../admin/mongodb/domain/SchedulerDomain.java | 19 + .../repository/BusinessLogRepository.java | 36 + .../mongodb/service/BusinessLogService.java | 235 ++++++ .../service/DataInitializeHistoryService.java | 2 +- .../service/DynamodbHistoryLogService.java | 96 ++- .../service/MysqlHistoryLogService.java | 122 ++-- .../admin/scheduler/CommonScheduler.java | 32 +- .../admin/scheduler/DynamicScheduler.java | 666 ------------------ .../admin/scheduler/OneTimeSchedule.java | 12 +- .../admin/scheduler/ScheduleSetter.java | 202 ------ .../admin/scheduler/ScheduleSetter.java.bak | 178 ----- .../admin/scheduler/SchedulerManager.java | 2 + .../scheduler/batch/ScheduleRunnerBatch.java | 78 ++ .../polling/ScheduleRunnerPolling.java | 78 +- .../polling/service/BattleEventScheduler.java | 153 ++++ .../polling/service/BlackListScheduler.java | 118 ++++ .../service/DataInitializeScheduler.java | 14 +- .../polling/service/EventScheduler.java | 110 +++ .../polling/service/LandAuctionScheduler.java | 173 +++++ .../service/LandOwnerChangesScheduler.java | 99 ++- .../polling/service/MailScheduler.java | 223 ++++++ .../polling/service/NoticeScheduler.java | 283 ++++++-- .../polling/service/cleanupScheduler.java | 8 +- src/main/resources/mappers/AdminMapper.xml | 12 +- src/main/resources/mappers/EventMapper.xml | 2 +- src/main/resources/mappers/GroupMapper.xml | 4 +- src/main/resources/mappers/HistoryMapper.xml | 96 --- src/main/resources/mappers/LandMapper.xml | 52 +- src/main/resources/mappers/MailMapper.xml | 3 +- src/main/resources/mappers/NoticeMapper.xml | 3 +- 132 files changed, 3481 insertions(+), 2887 deletions(-) delete mode 100644 src/main/java/com/caliverse/admin/domain/adminlog/AdminItemDeleteLog.java delete mode 100644 src/main/java/com/caliverse/admin/domain/adminlog/AdminLogBase.java delete mode 100644 src/main/java/com/caliverse/admin/domain/adminlog/AdminLoginPermitLog.java delete mode 100644 src/main/java/com/caliverse/admin/domain/adminlog/AdminPasswordInitLog.java delete mode 100644 src/main/java/com/caliverse/admin/domain/adminlog/IAdminLog.java delete mode 100644 src/main/java/com/caliverse/admin/domain/batch/CustomProcessor.java delete mode 100644 src/main/java/com/caliverse/admin/domain/batch/CustomReader.java delete mode 100644 src/main/java/com/caliverse/admin/domain/batch/CustomWriter.java delete mode 100644 src/main/java/com/caliverse/admin/domain/batch/TestJob.java delete mode 100644 src/main/java/com/caliverse/admin/domain/dao/admin/HistoryMapper.java create mode 100644 src/main/java/com/caliverse/admin/domain/entity/EReqType.java rename src/main/java/com/caliverse/admin/domain/{adminlog => entity}/FieldChange.java (90%) create mode 100644 src/main/java/com/caliverse/admin/domain/entity/common/BeforeDataResolver.java create mode 100644 src/main/java/com/caliverse/admin/domain/entity/log/LogAction.java create mode 100644 src/main/java/com/caliverse/admin/domain/entity/log/LogCategory.java create mode 100644 src/main/java/com/caliverse/admin/domain/entity/log/LogStatus.java create mode 100644 src/main/java/com/caliverse/admin/domain/entity/metaEnum/EGameModeType.java create mode 100644 src/main/java/com/caliverse/admin/domain/entity/metaEnum/EJoinInProgressType.java create mode 100644 src/main/java/com/caliverse/admin/domain/entity/metaEnum/ETeamAssignmentType.java create mode 100644 src/main/java/com/caliverse/admin/domain/entity/metadata/MetaGameModeCommonData.java create mode 100644 src/main/java/com/caliverse/admin/domain/entity/metadata/MetaGameModeMatchData.java create mode 100644 src/main/java/com/caliverse/admin/domain/response/GameResponse.java create mode 100644 src/main/java/com/caliverse/admin/domain/service/GameSettingService.java create mode 100644 src/main/java/com/caliverse/admin/global/common/annotation/BusinessProcess.java create mode 100644 src/main/java/com/caliverse/admin/global/common/aspect/BusinessProcessAspect.java create mode 100644 src/main/java/com/caliverse/admin/global/component/MysqlLoggingInterceptor.java create mode 100644 src/main/java/com/caliverse/admin/global/component/manager/BeforeDataResolver.java create mode 100644 src/main/java/com/caliverse/admin/global/component/manager/BusinessProcessIdManager.java rename src/main/java/com/caliverse/admin/global/component/{transaction => manager}/DynamoDBTransactionContext.java (92%) rename src/main/java/com/caliverse/admin/global/component/{transaction => manager}/TransactionIdManager.java (94%) delete mode 100644 src/main/java/com/caliverse/admin/global/configuration/BatchConfiguration.java delete mode 100644 src/main/java/com/caliverse/admin/global/configuration/TestBatchConfiguration.java create mode 100644 src/main/java/com/caliverse/admin/mongodb/domain/BatchJobDomain.java create mode 100644 src/main/java/com/caliverse/admin/mongodb/domain/BusinessLog.java create mode 100644 src/main/java/com/caliverse/admin/mongodb/domain/DataInitDomain.java create mode 100644 src/main/java/com/caliverse/admin/mongodb/domain/DynamodbDomain.java create mode 100644 src/main/java/com/caliverse/admin/mongodb/domain/MariadbDomain.java create mode 100644 src/main/java/com/caliverse/admin/mongodb/domain/MessageQueueDomain.java create mode 100644 src/main/java/com/caliverse/admin/mongodb/domain/RedisDomain.java create mode 100644 src/main/java/com/caliverse/admin/mongodb/domain/S3Domain.java create mode 100644 src/main/java/com/caliverse/admin/mongodb/domain/SchedulerDomain.java create mode 100644 src/main/java/com/caliverse/admin/mongodb/repository/BusinessLogRepository.java create mode 100644 src/main/java/com/caliverse/admin/mongodb/service/BusinessLogService.java delete mode 100644 src/main/java/com/caliverse/admin/scheduler/DynamicScheduler.java delete mode 100644 src/main/java/com/caliverse/admin/scheduler/ScheduleSetter.java delete mode 100644 src/main/java/com/caliverse/admin/scheduler/ScheduleSetter.java.bak create mode 100644 src/main/java/com/caliverse/admin/scheduler/polling/service/BattleEventScheduler.java create mode 100644 src/main/java/com/caliverse/admin/scheduler/polling/service/BlackListScheduler.java create mode 100644 src/main/java/com/caliverse/admin/scheduler/polling/service/EventScheduler.java create mode 100644 src/main/java/com/caliverse/admin/scheduler/polling/service/LandAuctionScheduler.java create mode 100644 src/main/java/com/caliverse/admin/scheduler/polling/service/MailScheduler.java delete mode 100644 src/main/resources/mappers/HistoryMapper.xml diff --git a/src/main/java/com/caliverse/admin/domain/RabbitMq/MessageHandlerService.java b/src/main/java/com/caliverse/admin/domain/RabbitMq/MessageHandlerService.java index 68ae36f..3f75353 100644 --- a/src/main/java/com/caliverse/admin/domain/RabbitMq/MessageHandlerService.java +++ b/src/main/java/com/caliverse/admin/domain/RabbitMq/MessageHandlerService.java @@ -4,40 +4,81 @@ import com.caliverse.admin.domain.RabbitMq.message.LogoutReasonType; import com.caliverse.admin.domain.RabbitMq.message.MailItem; import com.caliverse.admin.domain.RabbitMq.message.OperationSystemMessage; import com.caliverse.admin.domain.RabbitMq.message.ServerMessage; +import com.caliverse.admin.domain.entity.log.LogStatus; +import com.caliverse.admin.global.common.constants.CommonConstants; +import com.caliverse.admin.global.common.utils.CommonUtils; +import com.caliverse.admin.mongodb.service.BusinessLogService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.List; +import java.util.concurrent.CompletableFuture; @Slf4j @Service public class MessageHandlerService { private final RabbitMqService rabbitMqService; + private final BusinessLogService businessLogService; - public MessageHandlerService(RabbitMqService rabbitMqService) { + public MessageHandlerService(RabbitMqService rabbitMqService, BusinessLogService businessLogService) { this.rabbitMqService = rabbitMqService; + this.businessLogService = businessLogService; + } + + private void logMessage(LogStatus logStatus, String message, String queName, String serverName, Object content){ + CompletableFuture logFuture = businessLogService.logMessageQueue( + logStatus, + message, + CommonUtils.getAdmin() == null ? CommonConstants.SYSTEM : CommonUtils.getAdmin().getEmail(), + CommonUtils.getClientIp() == null ? CommonConstants.SYSTEM : CommonUtils.getClientIp(), + queName, + serverName, + content + ); + + logFuture.whenComplete((result, throwable) -> { + if (throwable != null) { + log.warn("MessageQueue Business log failed for info: {}, error: {}", CommonUtils.objectByString(content), throwable.getMessage()); + } + }); } public void sendUserKickMessage(String userGuid, String serverName, String reason){ - var user_kick_builder = ServerMessage.MOS2GS_NTF_USER_KICK.newBuilder(); - user_kick_builder.setUserGuid(userGuid); - user_kick_builder.setKickReasonMsg(String.format("backoffice %s", reason)); - user_kick_builder.setLogoutReasonType(LogoutReasonType.LogoutReasonType_None); + try { + var user_kick_builder = ServerMessage.MOS2GS_NTF_USER_KICK.newBuilder(); + user_kick_builder.setUserGuid(userGuid); + user_kick_builder.setKickReasonMsg(String.format("backoffice %s", reason)); + user_kick_builder.setLogoutReasonType(LogoutReasonType.LogoutReasonType_None); - rabbitMqService.SendMessage(user_kick_builder.build(), serverName); + rabbitMqService.SendMessage(user_kick_builder.build(), serverName); + + logMessage( + LogStatus.SUCCESS, + "", + "sendUserKickMessage", + serverName, + user_kick_builder + ); + }catch(Exception e){ + log.error(e.getMessage()); + logMessage( + LogStatus.FAILURE, + String.format("User Kick Fail UserGuid: %s, reason: %s, error: %s", userGuid, reason, e.getMessage()), + "sendUserKickMessage", + serverName, + null + ); + } } public void sendNoticeMessage(List serverList, String type, List msgList, List senderList){ try { var noticeBuilder = ServerMessage.MOS2GS_NTF_NOTICE_CHAT.newBuilder(); noticeBuilder.addNoticeType(type); -// noticeBuilder.setNoticeType(0, type); -// int msgIdx = 0; + for (OperationSystemMessage msg : msgList) { noticeBuilder.addChatMessage(msg); -// noticeBuilder.setChatMessage(msgIdx, msg); -// msgIdx++; } for (OperationSystemMessage sender : senderList) { noticeBuilder.addSender(sender); @@ -45,50 +86,117 @@ public class MessageHandlerService { for (String server : serverList) { rabbitMqService.SendMessage(noticeBuilder.build(), server); } + logMessage( + LogStatus.SUCCESS, + "", + "sendNoticeMessage", + serverList.toString(), + noticeBuilder + ); }catch (Exception e){ log.error(e.getMessage()); + logMessage( + LogStatus.FAILURE, + String.format("Send Notice Fail Type: %s, senderList: %s, msgList: %s, error: %s", type, senderList.toString(), msgList.toString(), e.getMessage()), + "sendNoticeMessage", + serverList.toString(), + null + ); } } public void sendMailMessage(String serverName, String userGuid, String mailType, List titleList, List msgList , List itemList, List senderList){ - var mail_builder = ServerMessage.MOS2GS_NTF_MAIL_SEND.newBuilder(); - mail_builder.setUserGuid(userGuid); - mail_builder.setMailType(mailType); + try { + var mail_builder = ServerMessage.MOS2GS_NTF_MAIL_SEND.newBuilder(); + mail_builder.setUserGuid(userGuid); + mail_builder.setMailType(mailType); - for(OperationSystemMessage title : titleList){ - mail_builder.addTitle(title); + for (OperationSystemMessage title : titleList) { + mail_builder.addTitle(title); + } + for (OperationSystemMessage msg : msgList) { + mail_builder.addMsg(msg); + } + for (MailItem item : itemList) { + mail_builder.addItemList(item); + } + for (OperationSystemMessage sender : senderList) { + mail_builder.addSender(sender); + } + rabbitMqService.SendMessage(mail_builder.build(), serverName); + logMessage( + LogStatus.SUCCESS, + "", + "sendMailMessage", + serverName, + mail_builder + ); + }catch (Exception e){ + log.error(e.getMessage()); + logMessage( + LogStatus.FAILURE, + String.format("Send Mail Fail UserGuid: %s, mailType: %s, senderList: %s, titleList: %s, itemList: %s, error: %s", + userGuid, mailType, senderList.toString(), titleList.toString(), itemList.toString(), e.getMessage()), + "sendMailMessage", + serverName, + null + ); } - for(OperationSystemMessage msg : msgList){ - mail_builder.addMsg(msg); - } - for(MailItem item : itemList){ - mail_builder.addItemList(item); - } - for(OperationSystemMessage sender : senderList){ - mail_builder.addSender(sender); - } - rabbitMqService.SendMessage(mail_builder.build(), serverName); - } public void sendBannerMessage(String serverName){ - var banner_builder = ServerMessage.MOS2GS_NTF_UPDATE_BANNER.newBuilder(); + try { + var banner_builder = ServerMessage.MOS2GS_NTF_UPDATE_BANNER.newBuilder(); - rabbitMqService.SendMessage(banner_builder.build(), serverName); + rabbitMqService.SendMessage(banner_builder.build(), serverName); + logMessage( + LogStatus.SUCCESS, + "", + "sendBannerMessage", + serverName, + banner_builder + ); + }catch(Exception e){ + log.error(e.getMessage()); + logMessage( + LogStatus.FAILURE, + String.format("Banner Fail error: %s", e.getMessage()), + "sendBannerMessage", + serverName, + null + ); + } } public void sendQuestTaskCompleteMessage(String serverName, String accountId, int reqId, String questKey, int taskId){ - var quest_task_builder = ServerMessage.MOS2GS_NTF_QUEST_TASK_FORCE_COMPLETE.newBuilder(); - quest_task_builder.setAccountId(accountId); - quest_task_builder.setReqId(reqId); - quest_task_builder.setQuestKey(questKey); - quest_task_builder.setTaskId(taskId); + try { + var quest_task_builder = ServerMessage.MOS2GS_NTF_QUEST_TASK_FORCE_COMPLETE.newBuilder(); + quest_task_builder.setAccountId(accountId); + quest_task_builder.setReqId(reqId); + quest_task_builder.setQuestKey(questKey); + quest_task_builder.setTaskId(taskId); + rabbitMqService.SendMessage(quest_task_builder.build(), serverName); - rabbitMqService.SendMessage(quest_task_builder.build(), serverName); - + logMessage( + LogStatus.SUCCESS, + "", + "sendQuestTaskCompleteMessage", + serverName, + quest_task_builder + ); + }catch(Exception e){ + log.error(e.getMessage()); + logMessage( + LogStatus.FAILURE, + String.format("Quest Task Complete Fail accountId: %s, questKey: %s, taskId: %s, error: %s", accountId, questKey, taskId, e.getMessage()), + "sendQuestTaskCompleteMessage", + serverName, + null + ); + } } } diff --git a/src/main/java/com/caliverse/admin/domain/adminlog/AdminItemDeleteLog.java b/src/main/java/com/caliverse/admin/domain/adminlog/AdminItemDeleteLog.java deleted file mode 100644 index 4700359..0000000 --- a/src/main/java/com/caliverse/admin/domain/adminlog/AdminItemDeleteLog.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.caliverse.admin.domain.adminlog; - -import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; - -public class AdminItemDeleteLog extends AdminLogBase { - - public AdminItemDeleteLog(String userGuid, String itemGuid, String itemCount){ - super(HISTORYTYPEDETAIL.USER_ITEM_DELETE); - - var jsonObject = getJsonContentObject(); - - jsonObject.put("userGuid", userGuid); - jsonObject.put("itemGuid", itemGuid); - jsonObject.put("itemCount", itemCount); - } - -} diff --git a/src/main/java/com/caliverse/admin/domain/adminlog/AdminLogBase.java b/src/main/java/com/caliverse/admin/domain/adminlog/AdminLogBase.java deleted file mode 100644 index 480a837..0000000 --- a/src/main/java/com/caliverse/admin/domain/adminlog/AdminLogBase.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.caliverse.admin.domain.adminlog; - - -import com.caliverse.admin.domain.dao.admin.HistoryMapper; -import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; -import com.caliverse.admin.global.common.utils.CommonUtils; -import com.caliverse.admin.global.component.AdminApplicationContextProvider; -import lombok.Getter; -import lombok.extern.slf4j.Slf4j; -import org.json.JSONObject; -import org.springframework.context.ApplicationContext; - -import java.util.HashMap; -import java.util.Map; - - -@Slf4j -public abstract class AdminLogBase implements IAdminLog{ - - - private final HistoryMapper historyMapper; - private static ApplicationContext context; - - private final HISTORYTYPEDETAIL historyType; - - protected Map map; - - @Getter - protected JSONObject jsonContentObject = new JSONObject(); - - - public AdminLogBase(HISTORYTYPEDETAIL historyType) { - - this.historyMapper = AdminApplicationContextProvider.getContext().getBean(HistoryMapper.class); - this.historyType = historyType; - - jsonContentObject = new JSONObject(); - this.map = new HashMap<>(); - - makeDefaultMap(); - } - - //protected abstract void saveAdminLog(); - - - private void makeDefaultMap(){ - - - Long adminId = 0L; - String adminName = ""; - String adminMail = ""; - HISTORYTYPEDETAIL type = HISTORYTYPEDETAIL.NONE; - try { - adminId = CommonUtils.getAdmin().getId(); - adminName = CommonUtils.getAdmin().getName(); - adminMail = CommonUtils.getAdmin().getEmail(); - } - catch (Exception e){ - log.error("makeDefaultMap getAdmin() null error message : {}", e.getMessage()); - } - - this.map.put("adminId", adminId); - this.map.put("name", adminName); - this.map.put("mail", adminMail); - this.map.put("type", historyType); - } - - @Override - public void saveLogToDB(){ - this.map.put("content", jsonContentObject.toString()); - historyMapper.saveLog(map); - } - - - -} diff --git a/src/main/java/com/caliverse/admin/domain/adminlog/AdminLoginPermitLog.java b/src/main/java/com/caliverse/admin/domain/adminlog/AdminLoginPermitLog.java deleted file mode 100644 index a531495..0000000 --- a/src/main/java/com/caliverse/admin/domain/adminlog/AdminLoginPermitLog.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.caliverse.admin.domain.adminlog; - -import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; - -public class AdminLoginPermitLog extends AdminLogBase { - - public AdminLoginPermitLog() { - super(HISTORYTYPEDETAIL.LOGIN_PERMITTED); - - - - } -} diff --git a/src/main/java/com/caliverse/admin/domain/adminlog/AdminPasswordInitLog.java b/src/main/java/com/caliverse/admin/domain/adminlog/AdminPasswordInitLog.java deleted file mode 100644 index fb6d691..0000000 --- a/src/main/java/com/caliverse/admin/domain/adminlog/AdminPasswordInitLog.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.caliverse.admin.domain.adminlog; - - -import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; - -public class AdminPasswordInitLog extends AdminLogBase { - - public AdminPasswordInitLog(String name, String email) { - super(HISTORYTYPEDETAIL.PASSWORD_INIT); - - var jsonObject = getJsonContentObject(); - - jsonObject.put("name", name); - jsonObject.put("email", email); - } -} diff --git a/src/main/java/com/caliverse/admin/domain/adminlog/IAdminLog.java b/src/main/java/com/caliverse/admin/domain/adminlog/IAdminLog.java deleted file mode 100644 index 2e5d50c..0000000 --- a/src/main/java/com/caliverse/admin/domain/adminlog/IAdminLog.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.caliverse.admin.domain.adminlog; - -import java.util.Map; - -public interface IAdminLog { - - public void saveLogToDB(); -} diff --git a/src/main/java/com/caliverse/admin/domain/batch/CustomProcessor.java b/src/main/java/com/caliverse/admin/domain/batch/CustomProcessor.java deleted file mode 100644 index 5e1480e..0000000 --- a/src/main/java/com/caliverse/admin/domain/batch/CustomProcessor.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.caliverse.admin.domain.batch; - -import org.springframework.batch.item.ItemProcessor; -import lombok.extern.slf4j.Slf4j; - -@Slf4j -public class CustomProcessor implements ItemProcessor { - - @Override - public String process(String data) throws Exception { - log.info("Processing data: " + data); - //data = data.toUpperCase(); - - return data; - - } - -} diff --git a/src/main/java/com/caliverse/admin/domain/batch/CustomReader.java b/src/main/java/com/caliverse/admin/domain/batch/CustomReader.java deleted file mode 100644 index 25b02b9..0000000 --- a/src/main/java/com/caliverse/admin/domain/batch/CustomReader.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.caliverse.admin.domain.batch; - -import org.springframework.batch.item.ItemReader; - -import lombok.extern.slf4j.Slf4j; - -@Slf4j -public class CustomReader implements ItemReader { - private String[] tokens = { "Hello World!", "Hello Spring!", "Hello Batch!" }; - private int index = 0; - - @Override - public String read() throws Exception { - if (index >= tokens.length) { - return null; - } - - String data = index + " " + tokens[index]; - index++; - - log.info("reading data: {}", data); - - return data; - } - -} \ No newline at end of file diff --git a/src/main/java/com/caliverse/admin/domain/batch/CustomWriter.java b/src/main/java/com/caliverse/admin/domain/batch/CustomWriter.java deleted file mode 100644 index 970e4ad..0000000 --- a/src/main/java/com/caliverse/admin/domain/batch/CustomWriter.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.caliverse.admin.domain.batch; - -import org.springframework.batch.item.Chunk; -import org.springframework.batch.item.ItemWriter; - -import lombok.extern.slf4j.Slf4j; - -@Slf4j -public class CustomWriter implements ItemWriter { - @Override - public void write(Chunk chunk) throws Exception { - - for (String data : chunk) { - log.info("Writing item: " + data.toString()); - } - } - -} diff --git a/src/main/java/com/caliverse/admin/domain/batch/TestJob.java b/src/main/java/com/caliverse/admin/domain/batch/TestJob.java deleted file mode 100644 index 969ef88..0000000 --- a/src/main/java/com/caliverse/admin/domain/batch/TestJob.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.caliverse.admin.domain.batch; - -// import org.springframework.batch.core.Job; -// import org.springframework.batch.core.JobExecutionException; -// import org.springframework.batch.core.JobParameters; -// import org.springframework.batch.core.JobParametersBuilder; -// import org.springframework.batch.core.Step; -// import org.springframework.batch.core.job.builder.JobBuilder; -// import org.springframework.batch.core.launch.JobLauncher; -// import org.springframework.batch.core.repository.JobRepository; -// import org.springframework.batch.core.step.builder.StepBuilder; -// import org.springframework.batch.core.step.tasklet.Tasklet; -// import org.springframework.batch.repeat.RepeatStatus; -//import org.springframework.context.annotation.Bean; -//import org.springframework.context.annotation.Configuration; -//import org.springframework.transaction.PlatformTransactionManager; - -import lombok.Getter; -import lombok.extern.slf4j.Slf4j; - -//@Configuration -//@RequiredArgsConstructor -@Slf4j -@Getter -public class TestJob { - - // private final JobLauncher jobLauncher; - // private final PlatformTransactionManager transactionManager; - - - // @Bean - // public Job testSimpleJob(PlatformTransactionManager transactionManager, JobRepository jobRepository) { - // return new JobBuilder("testSimpleJob", jobRepository) - // .start(testSimpleStep(transactionManager, jobRepository)) - // .build(); - // } - - // @Bean - // public Step testSimpleStep(PlatformTransactionManager transactionManager, JobRepository jobRepository) { - - // return new StepBuilder("testSimpleStep", jobRepository) - // .tasklet(testTasklet(), transactionManager) - // .build(); - // } - - // public Tasklet testTasklet() { - // return (contribution, chunkContext) -> { - // log.info("test job runned"); - // return RepeatStatus.FINISHED; - // }; - // } - - // public void runJob() { - // try { - // JobParameters jobParameters = new JobParametersBuilder() - // .addLong("run.id", System.currentTimeMillis()) - // .toJobParameters(); - // jobLauncher.run(testSimpleJob(transactionManager, null), jobParameters); - // } catch (JobExecutionException e) { - // log.error("Failed to execute job", e); - // } - // } - -} diff --git a/src/main/java/com/caliverse/admin/domain/dao/admin/AdminMapper.java b/src/main/java/com/caliverse/admin/domain/dao/admin/AdminMapper.java index 1fdf335..acc7d45 100644 --- a/src/main/java/com/caliverse/admin/domain/dao/admin/AdminMapper.java +++ b/src/main/java/com/caliverse/admin/domain/dao/admin/AdminMapper.java @@ -8,6 +8,7 @@ import com.caliverse.admin.domain.entity.STATUS; public interface AdminMapper { Optional findByEmail(String email); + Optional findById(Long id); boolean existsByEmail(String email); @@ -18,7 +19,6 @@ public interface AdminMapper { void initPwd(String password,Long id, Long updateBy); void updatePwd(String password, Long updateBy, STATUS status); - void saveHistoryPwd(String password,Long adminId); //운영자 리스트 조회 List getAdminList(Map requestMap); diff --git a/src/main/java/com/caliverse/admin/domain/dao/admin/GroupMapper.java b/src/main/java/com/caliverse/admin/domain/dao/admin/GroupMapper.java index bf0ad82..77412ee 100644 --- a/src/main/java/com/caliverse/admin/domain/dao/admin/GroupMapper.java +++ b/src/main/java/com/caliverse/admin/domain/dao/admin/GroupMapper.java @@ -21,7 +21,7 @@ public interface GroupMapper { int findGroupName(String groupNm); int getAllCnt(); // 권한 등록 - void postAdminGroup(GroupRequest groupRequest); + void postGroup(GroupRequest groupRequest); //group_auth 테이블 삭제 by groupId void deleteGroupAuth(String groupId); diff --git a/src/main/java/com/caliverse/admin/domain/dao/admin/HistoryMapper.java b/src/main/java/com/caliverse/admin/domain/dao/admin/HistoryMapper.java deleted file mode 100644 index 57a1cad..0000000 --- a/src/main/java/com/caliverse/admin/domain/dao/admin/HistoryMapper.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.caliverse.admin.domain.dao.admin; - -import com.caliverse.admin.domain.entity.Log; - -import java.util.List; -import java.util.Map; - -public interface HistoryMapper { - // 사용 이력 리스트 조회 - List getHistoryList(Map map); - - //전체 데이터 count - int getAllCnt(Map map); - int getTotal(); - String getLogJson(String id); - void saveLog(Map map); - - //임시로 Meta Data를 넣기 위한 Mepper - void truncateMetaTable(); - void insertMetaData(Map map); - -} diff --git a/src/main/java/com/caliverse/admin/domain/dao/admin/LandMapper.java b/src/main/java/com/caliverse/admin/domain/dao/admin/LandMapper.java index 4a1c470..cf05646 100644 --- a/src/main/java/com/caliverse/admin/domain/dao/admin/LandMapper.java +++ b/src/main/java/com/caliverse/admin/domain/dao/admin/LandMapper.java @@ -1,11 +1,8 @@ package com.caliverse.admin.domain.dao.admin; -import com.caliverse.admin.domain.entity.Event; import com.caliverse.admin.domain.entity.LandAuction; import com.caliverse.admin.domain.entity.LandOwnerChange; -import com.caliverse.admin.domain.entity.Message; import com.caliverse.admin.domain.request.LandRequest; -import org.apache.ibatis.annotations.Select; import java.util.List; import java.util.Map; @@ -24,8 +21,6 @@ public interface LandMapper { LandOwnerChange getLandOwnerChangeDetail(Long id); List getLandOwnerChangeInfo(int landId); - List getMessage(Long id); - int getMaxLandSeq(Integer landId); int getPossibleLand(Integer landId); int getPossibleLandOwnerChanges(Integer landId); @@ -33,11 +28,9 @@ public interface LandMapper { int postLandAuction(LandRequest landRequest); int postLandOwnerChange(LandRequest landRequest); - void insertMessage(Map map); int updateLandAuction(LandRequest landRequest); int updateLandOwnerChange(LandRequest landRequest); - int deleteMessage(Map map); int initLandAuction(Long id); int initLandOwnedChanges(Long id); diff --git a/src/main/java/com/caliverse/admin/domain/entity/Admin.java b/src/main/java/com/caliverse/admin/domain/entity/Admin.java index 5f8034c..d74b362 100644 --- a/src/main/java/com/caliverse/admin/domain/entity/Admin.java +++ b/src/main/java/com/caliverse/admin/domain/entity/Admin.java @@ -58,6 +58,7 @@ public class Admin implements UserDetails{ private LocalDateTime updateDt; @JsonProperty("update_by") private String updateBy; + private boolean deleted; @Override public Collection getAuthorities() { diff --git a/src/main/java/com/caliverse/admin/domain/entity/EMetaData.java b/src/main/java/com/caliverse/admin/domain/entity/EMetaData.java index e302e89..f45744e 100644 --- a/src/main/java/com/caliverse/admin/domain/entity/EMetaData.java +++ b/src/main/java/com/caliverse/admin/domain/entity/EMetaData.java @@ -14,6 +14,7 @@ public enum EMetaData { GAME_MODE_DATA("GameMode", true), GAME_MODE_FFA_DATA("GameModeTpsFfa", true), GAME_MODE_TDM_DATA("GameModeTpsTdm", true), + GAME_MODE_MATCH_DATA("GameModeMatch", true), BATTLE_CONFIG_DATA("BattleFFAConfig", true), BATTLE_REWARD_DATA("BattleFFAReward", true), SYSTEM_MAIL_DATA("SystemMail", true) diff --git a/src/main/java/com/caliverse/admin/domain/entity/EReqType.java b/src/main/java/com/caliverse/admin/domain/entity/EReqType.java new file mode 100644 index 0000000..d931585 --- /dev/null +++ b/src/main/java/com/caliverse/admin/domain/entity/EReqType.java @@ -0,0 +1,17 @@ +package com.caliverse.admin.domain.entity; + +public enum EReqType { + MAIL("MAIL"), + NOTICE("NOTICE"), + QUEST_TASK("QUEST_TASK"); + + private final String value; + + EReqType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/src/main/java/com/caliverse/admin/domain/adminlog/FieldChange.java b/src/main/java/com/caliverse/admin/domain/entity/FieldChange.java similarity index 90% rename from src/main/java/com/caliverse/admin/domain/adminlog/FieldChange.java rename to src/main/java/com/caliverse/admin/domain/entity/FieldChange.java index d99f299..b6436f5 100644 --- a/src/main/java/com/caliverse/admin/domain/adminlog/FieldChange.java +++ b/src/main/java/com/caliverse/admin/domain/entity/FieldChange.java @@ -1,4 +1,4 @@ -package com.caliverse.admin.domain.adminlog; +package com.caliverse.admin.domain.entity; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/com/caliverse/admin/domain/entity/InGame.java b/src/main/java/com/caliverse/admin/domain/entity/InGame.java index 8628099..188aee6 100644 --- a/src/main/java/com/caliverse/admin/domain/entity/InGame.java +++ b/src/main/java/com/caliverse/admin/domain/entity/InGame.java @@ -1,6 +1,7 @@ package com.caliverse.admin.domain.entity; import java.time.LocalDateTime; +import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @@ -57,6 +58,10 @@ public class InGame { @JsonProperty("send_status") private SENDSTATUS sendStatus; + @JsonProperty("message_list") + List messageList; + + private boolean deleted; // 수정자 이메일주소 @JsonProperty("update_by") private String updateBy; diff --git a/src/main/java/com/caliverse/admin/domain/entity/Mail.java b/src/main/java/com/caliverse/admin/domain/entity/Mail.java index f18cacc..af972b8 100644 --- a/src/main/java/com/caliverse/admin/domain/entity/Mail.java +++ b/src/main/java/com/caliverse/admin/domain/entity/Mail.java @@ -60,6 +60,7 @@ public class Mail { // 단일 / 복수 -> guid / 엑셀 경로 private String target; + private boolean deleted; @JsonProperty("create_by") private String createBy; @JsonProperty("create_dt") diff --git a/src/main/java/com/caliverse/admin/domain/entity/common/BeforeDataResolver.java b/src/main/java/com/caliverse/admin/domain/entity/common/BeforeDataResolver.java new file mode 100644 index 0000000..7b06f54 --- /dev/null +++ b/src/main/java/com/caliverse/admin/domain/entity/common/BeforeDataResolver.java @@ -0,0 +1,5 @@ +package com.caliverse.admin.domain.entity.common; + +public interface BeforeDataResolver { + Object resolveBeforeData(Object parameter); +} diff --git a/src/main/java/com/caliverse/admin/domain/entity/log/LogAction.java b/src/main/java/com/caliverse/admin/domain/entity/log/LogAction.java new file mode 100644 index 0000000..a6d8ba9 --- /dev/null +++ b/src/main/java/com/caliverse/admin/domain/entity/log/LogAction.java @@ -0,0 +1,63 @@ +package com.caliverse.admin.domain.entity.log; + +public enum LogAction { + UNKNOWN, + + // 특화 + LOGIN, + LOGOUT, + UPLOAD, + DOWNLOAD, + CONNECT, + DISCONNECT, + START, + STOP, + PAUSE, + RESUME, + RETRY, + CANCEL, + + KICK_USER, + ADMIN_LEVEL, + NICKNAME_CHANGE, + MAIL_ITEM, + QUEST_TASK, + + SCHEDULE_CLEANUP, + SCHEDULE_DATA_INIT, + SCHEDULE_LAND_OWNER_CHANGE, + SCHEDULE_BLACK_LIST, + SCHEDULE_NOTICE, + SCHEDULE_MAIL, + SCHEDULE_EVENT, + SCHEDULE_BATTLE_EVENT, + SCHEDULE_LAND_AUCTION, + + // 파일 + COMPRESS, + EXTRACT, + BACKUP, + RESTORE, + + BANNER, + BATTLE_EVENT, + BUILDING, + LAND_OWNER_CHANGE, + LAND_AUCTION, + GROUP, + ADMIN, + ADMIN_GROUP, + ADMIN_DELETE, + AUTH_ADMIN, + PASSWORD_INIT, + PASSWORD_CHANGE, + BLACK_LIST, + CALIUM_REQUEST, + EVENT, + MAIL, + NOTICE, + DATA_INIT, + DATA, + USER, + ITEM +} diff --git a/src/main/java/com/caliverse/admin/domain/entity/log/LogCategory.java b/src/main/java/com/caliverse/admin/domain/entity/log/LogCategory.java new file mode 100644 index 0000000..58ff1ef --- /dev/null +++ b/src/main/java/com/caliverse/admin/domain/entity/log/LogCategory.java @@ -0,0 +1,21 @@ +package com.caliverse.admin.domain.entity.log; + +public enum LogCategory { + SCHEDULER, + MAIL, + NOTICE, + DYNAMODB, + MARIADB, + MESSAGE_QUEUE, + REDIS, + S3, + USER_MANAGEMENT, + EXTERNAL_API, + BATCH_JOB, + AUTHENTICATION, + AUTHORIZATION, + FILE_PROCESSING, + VALIDATION, + DATA_INIT, + ; +} diff --git a/src/main/java/com/caliverse/admin/domain/entity/log/LogStatus.java b/src/main/java/com/caliverse/admin/domain/entity/log/LogStatus.java new file mode 100644 index 0000000..641486c --- /dev/null +++ b/src/main/java/com/caliverse/admin/domain/entity/log/LogStatus.java @@ -0,0 +1,13 @@ +package com.caliverse.admin.domain.entity.log; + +public enum LogStatus { + SUCCESS, + FAILURE, + PENDING, + RUNNING, + CANCELLED, + TIMEOUT, + RETRY, + PARTIAL_SUCCESS, + WARNING +} diff --git a/src/main/java/com/caliverse/admin/domain/entity/metaEnum/EGameModeType.java b/src/main/java/com/caliverse/admin/domain/entity/metaEnum/EGameModeType.java new file mode 100644 index 0000000..87aaded --- /dev/null +++ b/src/main/java/com/caliverse/admin/domain/entity/metaEnum/EGameModeType.java @@ -0,0 +1,25 @@ +package com.caliverse.admin.domain.entity.metaEnum; + + +import com.caliverse.admin.domain.entity.common.ValueEnum; + +public enum EGameModeType implements ValueEnum { + None(0), + TPS_FFA(1), + TPS_TDM(2), + RUN_ADV(3), + RUN_RACE(4), + DANCE(5) + ; + + private final int value; + + EGameModeType(int value) { + this.value = value; + } + + @Override + public int getValue() { + return value; + } +} diff --git a/src/main/java/com/caliverse/admin/domain/entity/metaEnum/EJoinInProgressType.java b/src/main/java/com/caliverse/admin/domain/entity/metaEnum/EJoinInProgressType.java new file mode 100644 index 0000000..7efb52d --- /dev/null +++ b/src/main/java/com/caliverse/admin/domain/entity/metaEnum/EJoinInProgressType.java @@ -0,0 +1,9 @@ +package com.caliverse.admin.domain.entity.metaEnum; + +public enum EJoinInProgressType { + None, + JoinIn, + JoinInSnapShot, + ReEntry + ; +} diff --git a/src/main/java/com/caliverse/admin/domain/entity/metaEnum/ETeamAssignmentType.java b/src/main/java/com/caliverse/admin/domain/entity/metaEnum/ETeamAssignmentType.java new file mode 100644 index 0000000..45a93a2 --- /dev/null +++ b/src/main/java/com/caliverse/admin/domain/entity/metaEnum/ETeamAssignmentType.java @@ -0,0 +1,7 @@ +package com.caliverse.admin.domain.entity.metaEnum; + +public enum ETeamAssignmentType { + Random, + Greedy, + ; +} diff --git a/src/main/java/com/caliverse/admin/domain/entity/metadata/MetaGameModeCommonData.java b/src/main/java/com/caliverse/admin/domain/entity/metadata/MetaGameModeCommonData.java new file mode 100644 index 0000000..6637947 --- /dev/null +++ b/src/main/java/com/caliverse/admin/domain/entity/metadata/MetaGameModeCommonData.java @@ -0,0 +1,40 @@ +package com.caliverse.admin.domain.entity.metadata; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.models.security.SecurityScheme; +import lombok.Getter; +import lombok.Setter; + + +@Getter @Setter +public class MetaGameModeCommonData { + private Integer id; + private String desc; + @JsonProperty("ax_start_wait_time") + private Integer axStartWaitTime; + @JsonProperty("proceed_if_no_enemies") + private boolean proceedIfNoEnemies; + @JsonProperty("max_play_time") + private Integer maxPlayTime; + @JsonProperty("character_base_stat_data_id") + private Integer characterBaseStatDataID; + @JsonProperty("character_attribute_stat_data_id") + private Integer characterAttributeStatDataID; + @JsonProperty("character_ability_level_data_id") + private Integer characterAbilityLevelDataID; + @JsonProperty("attribute_func_data_id_ue") + private String attributeFuncDataID_UE; + @JsonProperty("genre_name") + private String genreName; + @JsonProperty("mode_name") + private String modeName; + @JsonProperty("map_name") + private String mapName; + @JsonProperty("map_description") + private String mapDescription; + @JsonProperty("map_image") + private String mapImage; + @JsonProperty("map_tooltip_group_id") + private Integer mapTooltipGroupID; + @JsonProperty("guide_url") + private String guideUrl; +} diff --git a/src/main/java/com/caliverse/admin/domain/entity/metadata/MetaGameModeMatchData.java b/src/main/java/com/caliverse/admin/domain/entity/metadata/MetaGameModeMatchData.java new file mode 100644 index 0000000..bc5cf3f --- /dev/null +++ b/src/main/java/com/caliverse/admin/domain/entity/metadata/MetaGameModeMatchData.java @@ -0,0 +1,35 @@ +package com.caliverse.admin.domain.entity.metadata; +import com.caliverse.admin.domain.entity.metaEnum.EJoinInProgressType; +import com.caliverse.admin.domain.entity.metaEnum.ETeamAssignmentType; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; + + +@Getter @Setter +public class MetaGameModeMatchData { + private Integer id; + private String desc; + @JsonProperty("mmr_check") + private boolean mmrCheck; + @JsonProperty("party_match_player_count_able_array") + private List partyMatchPlayerCountAbleArray; + @JsonProperty("match_wait_time_sec") + private Integer matchWaitTimeSec; + @JsonProperty("game_mode_mmr_id") + private Integer gameModeMmrID; + @JsonProperty("match_retry_count") + private Integer matchRetryCount; + @JsonProperty("mmr_expansion_phase") + private Integer mmrExpansionPhase; + @JsonProperty("team_assignment") + private ETeamAssignmentType teamAssignment; + @JsonProperty("join_in_progress") + private EJoinInProgressType joinInProgress; + @JsonProperty("join_in_max_time_sec") + private Integer joinInMaxTimeSec; + @JsonProperty("entrance_closing_time") + private Integer entranceClosingTime; +} diff --git a/src/main/java/com/caliverse/admin/domain/request/LandRequest.java b/src/main/java/com/caliverse/admin/domain/request/LandRequest.java index 123f289..7d6d9a7 100644 --- a/src/main/java/com/caliverse/admin/domain/request/LandRequest.java +++ b/src/main/java/com/caliverse/admin/domain/request/LandRequest.java @@ -47,8 +47,6 @@ public class LandRequest { //경매 시작가 @JsonProperty("start_price") private Double startPrice; - @JsonProperty("message_list") - private List massageList; //소유권 변경 @JsonProperty("user_guid") diff --git a/src/main/java/com/caliverse/admin/domain/request/NoticeRequest.java b/src/main/java/com/caliverse/admin/domain/request/NoticeRequest.java index f1573b9..347c18c 100644 --- a/src/main/java/com/caliverse/admin/domain/request/NoticeRequest.java +++ b/src/main/java/com/caliverse/admin/domain/request/NoticeRequest.java @@ -57,7 +57,7 @@ public class NoticeRequest { @Getter public static class MessageId{ - @JsonProperty("message_id") - private Long messageId; + @JsonProperty("id") + private Long id; } } diff --git a/src/main/java/com/caliverse/admin/domain/response/GameResponse.java b/src/main/java/com/caliverse/admin/domain/response/GameResponse.java new file mode 100644 index 0000000..46d7789 --- /dev/null +++ b/src/main/java/com/caliverse/admin/domain/response/GameResponse.java @@ -0,0 +1,57 @@ +package com.caliverse.admin.domain.response; + +import com.caliverse.admin.domain.entity.BattleEvent; +import com.caliverse.admin.domain.entity.metadata.MetaBattleConfigData; +import com.caliverse.admin.domain.entity.metadata.MetaBattleRewardData; +import com.caliverse.admin.domain.entity.metadata.MetaGameModeData; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class GameResponse { + private int status; + + private String result; + @JsonProperty("data") + private ResultData resultData; + + @Data + @Builder + @JsonInclude(JsonInclude.Include.NON_NULL) + public static class ResultData { + + @JsonProperty("event_detail") + private BattleEvent battleEvent; + + @JsonProperty("event_list") + private List battleEventList; + + @JsonProperty("battle_config_list") + private List battleConfigList; + + @JsonProperty("battle_reward_list") + private List battleRewardList; + + @JsonProperty("game_mode_list") + private List gameModeList; + + private String message; + + private int total; + @JsonProperty("total_all") + private int totalAll; + @JsonProperty("page_no") + private int pageNo; + + } + +} diff --git a/src/main/java/com/caliverse/admin/domain/service/AIService.java b/src/main/java/com/caliverse/admin/domain/service/AIService.java index 9e03193..33f8610 100644 --- a/src/main/java/com/caliverse/admin/domain/service/AIService.java +++ b/src/main/java/com/caliverse/admin/domain/service/AIService.java @@ -64,7 +64,7 @@ public class AIService { } catch (JsonProcessingException e) { throw new RuntimeException("JSON 변환 실패", e); } - messages.add(CommonUtils.getAIMessage(AIRole.user, messageMerge(userMessage, dataJson))); + messages.add(getAIMessage(AIRole.user, messageMerge(userMessage, dataJson))); return messages; } @@ -75,7 +75,7 @@ public class AIService { private List> initMessage(){ List> messages = new ArrayList<>(); - messages.add(CommonUtils.getAIMessage(AIRole.system, + messages.add(getAIMessage(AIRole.system, """ 너는 프론트엔드 게시용 데이터를 생성하는 게임 데이터 분석 AI야. \ 사용자는 게임 로그 데이터와 함께 다양한 질문을 보낼 수 있어. \ @@ -97,7 +97,7 @@ public class AIService { switch (type){ case BUSINESS_LOG -> { LogGenericRequest logReq = mapper.convertValue(conditions, LogGenericRequest.class); - List logs = businessLogGenericService.loadBusinessLogData(logReq, GenericMongoLog.class, true); + List logs = businessLogGenericService.loadBusinessLogData(logReq, GenericMongoLog.class); return logs; } case MAIL -> { @@ -107,4 +107,8 @@ public class AIService { default -> throw new RuntimeException("Not Type"); } } + + private static Map getAIMessage(AIRole role, String message){ + return Map.of("role", role.toString(), "content", message); + } } diff --git a/src/main/java/com/caliverse/admin/domain/service/AdminService.java b/src/main/java/com/caliverse/admin/domain/service/AdminService.java index 286f02e..994e0b4 100644 --- a/src/main/java/com/caliverse/admin/domain/service/AdminService.java +++ b/src/main/java/com/caliverse/admin/domain/service/AdminService.java @@ -1,24 +1,22 @@ package com.caliverse.admin.domain.service; -import com.caliverse.admin.domain.adminlog.AdminPasswordInitLog; -import com.caliverse.admin.domain.adminlog.IAdminLog; import com.caliverse.admin.domain.dao.admin.AdminMapper; import com.caliverse.admin.domain.dao.admin.GroupMapper; import com.caliverse.admin.domain.entity.*; +import com.caliverse.admin.domain.entity.log.LogAction; import com.caliverse.admin.domain.request.AdminRequest; import com.caliverse.admin.domain.request.AuthenticateRequest; import com.caliverse.admin.domain.response.AdminResponse; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.code.CommonCode; import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.global.common.code.SuccessCode; -import com.caliverse.admin.global.common.constants.MysqlConstants; import com.caliverse.admin.global.common.exception.RestApiException; import com.caliverse.admin.global.common.utils.CommonUtils; import com.caliverse.admin.mongodb.service.MysqlHistoryLogService; import jakarta.mail.internet.MimeMessage; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -56,20 +54,16 @@ public class AdminService { @Value("${spring.mail.password}") private String password; // 비번 초기화 + @BusinessProcess(action = LogAction.PASSWORD_INIT) @Transactional(transactionManager = "transactionManager") public AdminResponse initPassword(AuthenticateRequest authenticateRequest){ Optional admin = adminMapper.findByEmail(authenticateRequest.getEmail()); String initPwd = randomPwd(); adminMapper.initPwd(passwordEncoder.encode(initPwd), admin.get().getId(), CommonUtils.getAdmin().getId()); - //유저 비번 기록 남기기 - adminMapper.saveHistoryPwd(passwordEncoder.encode(initPwd), admin.get().getId()); //smtp sendMail(authenticateRequest.getEmail(),initPwd); - IAdminLog adminLog = new AdminPasswordInitLog(admin.get().getName(), admin.get().getEmail()); - adminLog.saveLogToDB(); - log.info("initPassword id: {}, email: {}", admin.get().getId(), admin.get().getEmail()); return AdminResponse.builder() @@ -80,6 +74,7 @@ public class AdminService { } // 비번 재설정 + @BusinessProcess(action = LogAction.PASSWORD_CHANGE) @Transactional(transactionManager = "transactionManager") public AdminResponse updatePassword(AuthenticateRequest authenticateRequest){ @@ -87,6 +82,8 @@ public class AdminService { String newPwd = authenticateRequest.getNewPassword(); String pwdById = adminMapper.findPwdById(CommonUtils.getAdmin().getId()); + Optional beforeInfo = adminMapper.findByEmail(CommonUtils.getAdmin().getEmail()); + /* https://nzin-publisher-bts.atlassian.net/browse/CAL-120 임시 비밀번호 재설정 화면에서 현재 비밀번호 입력 필드가 노출되는 현상 @@ -102,8 +99,6 @@ public class AdminService { if(count == 0){ adminMapper.updatePwd(passwordEncoder.encode(newPwd), CommonUtils.getAdmin().getId(), STATUS.PERMITTED ); - //유저 비번 기록 남기기 - adminMapper.saveHistoryPwd(passwordEncoder.encode(newPwd), CommonUtils.getAdmin().getId()); }else{ throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.PASSWORD_INCLUDE.getMessage()); } @@ -168,6 +163,7 @@ public class AdminService { } // 로그인 승인/불가 + @BusinessProcess(action = LogAction.ADMIN) @Transactional(transactionManager = "transactionManager") public AdminResponse updateStatus(AdminRequest adminRequest){ Map map = new HashMap<>(); @@ -187,14 +183,6 @@ public class AdminService { } //로그인 승인 adminMapper.updateStatus(map); - - mysqlHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.LOGIN_PERMITTED, - MysqlConstants.TABLE_NAME_ADMIN, - HISTORYTYPEDETAIL.LOGIN_PERMITTED.name(), - info.get(), - adminMapper.findByEmail(email) - ); } ); @@ -207,7 +195,8 @@ public class AdminService { .build(); } - //운영자 그룹 저장 + //운영자 그룹 변경 + @BusinessProcess(action = LogAction.ADMIN_GROUP) @Transactional(transactionManager = "transactionManager") public AdminResponse updateGroup(AdminRequest adminRequest){ Map map = new HashMap<>(); @@ -218,19 +207,9 @@ public class AdminService { map.put("group_id", item.getGroupId()); map.put("id", CommonUtils.getAdmin().getId()); - //변경전 그룹 명세 조회 - Optional info = adminMapper.findByEmail(email); - //쿼리 실행 adminMapper.updateGroup(map); - mysqlHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.ADMIN_INFO_UPDATE, - MysqlConstants.TABLE_NAME_ADMIN, - HISTORYTYPEDETAIL.ADMIN_INFO_UPDATE.name(), - info.get(), - adminMapper.findByEmail(email) - ); } ); @@ -243,6 +222,7 @@ public class AdminService { } // 운영자 선택 삭제 + @BusinessProcess(action = LogAction.ADMIN_DELETE) @Transactional(transactionManager = "transactionManager") public AdminResponse deleteAdmin(AdminRequest adminRequest){ Map map = new HashMap<>(); @@ -250,18 +230,9 @@ public class AdminService { item -> { map.put("email", item.getEmail()); map.put("deleted", String.valueOf(1)); - //로그 기록 - Optional info = adminMapper.findByEmail(item.getEmail()); //쿼리 실행 adminMapper.deleteAdmin(map); - - mysqlHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.ADMIN_INFO_DELETE, - MysqlConstants.TABLE_NAME_ADMIN, - HISTORYTYPEDETAIL.ADMIN_INFO_DELETE.name(), - info.get() - ); } ); log.info("deleteAdmin Deleted Admin: {}", map); diff --git a/src/main/java/com/caliverse/admin/domain/service/AuthenticateService.java b/src/main/java/com/caliverse/admin/domain/service/AuthenticateService.java index de3e1e2..749d2b0 100644 --- a/src/main/java/com/caliverse/admin/domain/service/AuthenticateService.java +++ b/src/main/java/com/caliverse/admin/domain/service/AuthenticateService.java @@ -5,8 +5,10 @@ import com.caliverse.admin.domain.dao.admin.TokenMapper; import com.caliverse.admin.domain.entity.Admin; import com.caliverse.admin.domain.entity.STATUS; import com.caliverse.admin.domain.entity.Token; +import com.caliverse.admin.domain.entity.log.LogAction; import com.caliverse.admin.domain.request.AuthenticateRequest; import com.caliverse.admin.domain.response.AuthenticateResponse; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.code.CommonCode; import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.global.common.code.SuccessCode; @@ -21,6 +23,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio import org.springframework.security.core.AuthenticationException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.time.ZoneId; @@ -32,7 +35,7 @@ import java.time.temporal.ChronoUnit; @RequiredArgsConstructor public class AuthenticateService{ - private final AdminMapper userMapper; + private final AdminMapper adminMapper; private final TokenMapper tokenMapper; private final AuthenticationManager authenticationManager; private final JwtService jwtService; @@ -47,7 +50,7 @@ public class AuthenticateService{ String email = authenticateRequest.getEmail(); String pw = authenticateRequest.getPassword(); // 삭제 계정 여부 - if(!userMapper.existsByEmail(email)){ + if(!adminMapper.existsByEmail(email)){ throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.NOT_MATCH_USER.getMessage()); } @@ -58,7 +61,7 @@ public class AuthenticateService{ throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.NOT_FOUND_USER.getMessage()); } - Admin admin = userMapper.findByEmail(authenticateRequest.getEmail()) + Admin admin = adminMapper.findByEmail(authenticateRequest.getEmail()) .orElseThrow(() -> new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.NOT_MATCH_USER.getMessage())); //비번 기간 만료 @@ -93,9 +96,11 @@ public class AuthenticateService{ } //회원가입 + @BusinessProcess(action = LogAction.USER) + @Transactional(transactionManager = "transactionManager") public AuthenticateResponse register(AuthenticateRequest authenticateRequest){ - if(userMapper.existsByEmail(authenticateRequest.getEmail())){ + if(adminMapper.existsByEmail(authenticateRequest.getEmail())){ throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.DUPLICATED_EMAIL.getMessage()); } @@ -108,7 +113,7 @@ public class AuthenticateService{ .password(passwordEncoder.encode(authenticateRequest.getPassword())) .build(); - userMapper.save(admin); + adminMapper.save(admin); log.info("register Sign Up : {}", admin); return AuthenticateResponse.builder() .status(CommonCode.SUCCESS.getHttpStatus()) diff --git a/src/main/java/com/caliverse/admin/domain/service/BattleEventService.java b/src/main/java/com/caliverse/admin/domain/service/BattleEventService.java index eec5600..ccf37db 100644 --- a/src/main/java/com/caliverse/admin/domain/service/BattleEventService.java +++ b/src/main/java/com/caliverse/admin/domain/service/BattleEventService.java @@ -4,6 +4,8 @@ import com.caliverse.admin.domain.dao.admin.BattleMapper; import com.caliverse.admin.domain.datacomponent.MetaDataHandler; import com.caliverse.admin.domain.entity.BattleEvent; import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; import com.caliverse.admin.domain.entity.metadata.MetaBattleConfigData; import com.caliverse.admin.domain.entity.metadata.MetaBattleRewardData; import com.caliverse.admin.domain.entity.metadata.MetaGameFFAConfigData; @@ -11,6 +13,7 @@ import com.caliverse.admin.domain.entity.metadata.MetaGameModeData; import com.caliverse.admin.domain.request.BattleEventRequest; import com.caliverse.admin.domain.response.BattleEventResponse; import com.caliverse.admin.dynamodb.service.DynamodbBattleEventService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.code.CommonCode; import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.global.common.code.SuccessCode; @@ -127,6 +130,7 @@ public class BattleEventService { } // 전투시스템 이벤트 저장 + @BusinessProcess(action = LogAction.BATTLE_EVENT) @Transactional(transactionManager = "transactionManager") public BattleEventResponse postBattleEvent(BattleEventRequest battleEventRequest){ if(battleEventRequest.getRepeatType().equals(BattleEvent.BATTLE_REPEAT_TYPE.NONE)){ @@ -153,7 +157,7 @@ public class BattleEventService { .result(ErrorCode.ERROR_BATTLE_EVENT_TIME_OVER.toString()) .build(); } - + // metadata기준 되기전에 운영툴에서 입력값받아서 계산하던 부분 // int operation_time = ffACalcEndTime(battleEventRequest); List existingList = battleMapper.getCheckBattleEventList(battleEventRequest); @@ -171,23 +175,11 @@ public class BattleEventService { // battleEventRequest.setEventId(next_event_id); int result = battleMapper.postBattleEvent(battleEventRequest); - log.info("AdminToolDB BattleEvent Save: {}", battleEventRequest); + log.info("AdminToolDB BattleEvent Save id: {}", battleEventRequest.getId()); long battle_event_id = battleEventRequest.getId(); battleEventRequest.setEventId((int) battle_event_id); - HashMap map = new HashMap<>(); - map.put("id",String.valueOf(battle_event_id)); - - BattleEvent event_info = battleMapper.getBattleEventDetail(battle_event_id); - - mysqlHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.BATTLE_EVENT_ADD, - MysqlConstants.TABLE_NAME_BATTLE_EVENT, - HISTORYTYPEDETAIL.BATTLE_EVENT_ADD.name(), - event_info - ); - dynamodbBattleEventService.insertBattleEvent(battleEventRequest); return BattleEventResponse.builder() @@ -200,6 +192,7 @@ public class BattleEventService { } // 전투시스템 이벤트 수정 + @BusinessProcess(action = LogAction.BATTLE_EVENT) @Transactional(transactionManager = "transactionManager") public BattleEventResponse updateBattleEvent(Long id, BattleEventRequest battleEventRequest) { battleEventRequest.setId(id); @@ -237,20 +230,7 @@ public class BattleEventService { battleEventRequest.setEventEndDt(end_dt_kst); int result = battleMapper.updateBattleEvent(battleEventRequest); - log.info("AdminToolDB BattleEvent Update Complete: {}", battleEventRequest); - - Map map = new HashMap<>(); - map.put("id", String.valueOf(id)); - - BattleEvent after_info = battleMapper.getBattleEventDetail(id); - - mysqlHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.BATTLE_EVENT_UPDATE, - MysqlConstants.TABLE_NAME_BATTLE_EVENT, - HISTORYTYPEDETAIL.BATTLE_EVENT_UPDATE.name(), - before_info, - after_info - ); + log.info("AdminToolDB BattleEvent Update Complete id: {}", id); dynamodbBattleEventService.updateBattleEvent(battleEventRequest); @@ -263,6 +243,7 @@ public class BattleEventService { } // 전투시스템 이벤트 중단 + @BusinessProcess(action = LogAction.BATTLE_EVENT) @Transactional(transactionManager = "transactionManager") public BattleEventResponse updateStopBattleEvent(Long id){ Map map = new HashMap<>(); @@ -280,19 +261,7 @@ public class BattleEventService { map.put("status", BattleEvent.BATTLE_STATUS.STOP); map.put("updateBy", CommonUtils.getAdmin().getId()); int result = battleMapper.updateStatusBattleEvent(map); - try{ - log.info("BattleEvent Stop Complete: {}", objectMapper.writeValueAsString(info)); - }catch(Exception e){ - log.error("BattleEvent Stop Failed: {}", e.getMessage()); - } - - mysqlHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.BATTLE_EVENT_UPDATE, - MysqlConstants.TABLE_NAME_BATTLE_EVENT, - HISTORYTYPEDETAIL.BATTLE_EVENT_UPDATE.name(), - info, - battleMapper.getBattleEventDetail(id) - ); + log.info("BattleEvent Stop Complete id: {}", id); dynamodbBattleEventService.updateStopBattleEvent(info); @@ -305,6 +274,7 @@ public class BattleEventService { } // 전투시스템 이벤트 삭제(사용안함) + @BusinessProcess(action = LogAction.BATTLE_EVENT) @Transactional(transactionManager = "transactionManager") public BattleEventResponse deleteBattleEvent(BattleEventRequest battleEventRequest){ Map map = new HashMap<>(); @@ -325,13 +295,6 @@ public class BattleEventService { int result = battleMapper.deleteBattleEvent(map); log.info("BattleEvent Delete Complete: {}", item); - mysqlHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.BATTLE_EVENT_DELETE, - MysqlConstants.TABLE_NAME_BATTLE_EVENT, - HISTORYTYPEDETAIL.BATTLE_EVENT_DELETE.name(), - info - ); - // dynamodbLandAuctionService.cancelLandAuction(auction_info); } ); @@ -355,6 +318,7 @@ public class BattleEventService { return battleMapper.getScheduleBattleEventList(); } + @BusinessProcess(action = LogAction.BATTLE_EVENT) @Transactional(transactionManager = "transactionManager") public void updateBattleEventStatus(Map map){ try{ diff --git a/src/main/java/com/caliverse/admin/domain/service/BlackListService.java b/src/main/java/com/caliverse/admin/domain/service/BlackListService.java index ea8832a..8a5cc2f 100644 --- a/src/main/java/com/caliverse/admin/domain/service/BlackListService.java +++ b/src/main/java/com/caliverse/admin/domain/service/BlackListService.java @@ -4,9 +4,11 @@ import com.caliverse.admin.domain.dao.admin.BlackListMapper; import com.caliverse.admin.domain.entity.BlackList; import com.caliverse.admin.domain.entity.Excel; import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; +import com.caliverse.admin.domain.entity.log.LogAction; import com.caliverse.admin.domain.request.BlackListRequest; import com.caliverse.admin.domain.response.BlackListResponse; import com.caliverse.admin.dynamodb.service.DynamodbUserService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.code.CommonCode; import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.global.common.code.SuccessCode; @@ -142,6 +144,7 @@ public class BlackListService { return resourceLoader.getResource(excelPath + fileName); } + @BusinessProcess(action = LogAction.BLACK_LIST) @Transactional(transactionManager = "transactionManager") public BlackListResponse postBlackList(BlackListRequest blackListRequest){ @@ -167,16 +170,8 @@ public class BlackListService { blackListRequest.setGuid(guid); blackListRequest.setNickname(item.getNickname()); blackListMapper.postBlackList(blackListRequest); - logger.info("postBlackList insertBlackList: {}",blackListRequest); + logger.info("postBlackList insertBlackList id: {}",blackListRequest.getId()); - BlackList info = blackListMapper.getBlackListDetail(blackListRequest.getId()); - - mysqlHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.BLACKLIST_ADD, - MysqlConstants.TABLE_NAME_USER_BLOCK, - HISTORYTYPEDETAIL.BLACKLIST_ADD.name(), - info - ); } } ); @@ -201,16 +196,8 @@ public class BlackListService { blackListRequest.setGuid(item.getGuid()); blackListRequest.setNickname(dynamodbUserService.getGuidByName(item.getGuid())); blackListMapper.postBlackList(blackListRequest); - logger.info("postBlackList insertBlackList: {}",blackListRequest); + logger.info("postBlackList insertBlackList id: {}",blackListRequest.getId()); - BlackList info = blackListMapper.getBlackListDetail(blackListRequest.getId()); - - mysqlHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.BLACKLIST_ADD, - MysqlConstants.TABLE_NAME_USER_BLOCK, - HISTORYTYPEDETAIL.BLACKLIST_ADD.name(), - info - ); } } ); @@ -225,6 +212,7 @@ public class BlackListService { } + @BusinessProcess(action = LogAction.BLACK_LIST) @Transactional(transactionManager = "transactionManager") public BlackListResponse deleteBlackList(BlackListRequest blackListRequest){ @@ -238,15 +226,7 @@ public class BlackListService { map.put("reason",item.getReason()); blackListMapper.deleteBlackList(map); - logger.info("deleteBlackList delete: {}",map); - - mysqlHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.BLACKLIST_DELETE, - MysqlConstants.TABLE_NAME_USER_BLOCK, - HISTORYTYPEDETAIL.BLACKLIST_DELETE.name(), - blackList, - blackListMapper.getBlackListDetail(id) - ); + logger.info("deleteBlackList delete id: {}", id); if(dynamodbUserService.isBlockUser(blackList.getGuid())) dynamodbUserService.updateBlockUser(BlackList.STATUSTYPE.EXPIRATION, blackList); @@ -261,6 +241,7 @@ public class BlackListService { .build(); } + @BusinessProcess(action = LogAction.BLACK_LIST) @Transactional(transactionManager = "transactionManager") public void updateBlackListStatus(Long id, BlackList.STATUSTYPE status){ Map map = new HashMap<>(); @@ -269,7 +250,7 @@ public class BlackListService { blackListMapper.updateStatus(map); - logger.info("updateBlackListStatus BlackListSchedule status update: {}",map); + logger.info("updateBlackListStatus status update id: {}, status: {}", id, status.toString()); } public List getScheduleBlackList(){ diff --git a/src/main/java/com/caliverse/admin/domain/service/CaliumService.java b/src/main/java/com/caliverse/admin/domain/service/CaliumService.java index 581786c..b14d969 100644 --- a/src/main/java/com/caliverse/admin/domain/service/CaliumService.java +++ b/src/main/java/com/caliverse/admin/domain/service/CaliumService.java @@ -13,19 +13,16 @@ import com.caliverse.admin.domain.request.Web3Request; import com.caliverse.admin.domain.response.CaliumResponse; import com.caliverse.admin.domain.response.Web3Response; import com.caliverse.admin.dynamodb.service.DynamodbCaliumService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.code.CommonCode; import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.global.common.code.SuccessCode; -import com.caliverse.admin.global.common.constants.MysqlConstants; import com.caliverse.admin.global.common.constants.Web3Constants; import com.caliverse.admin.global.common.utils.CommonUtils; -import com.caliverse.admin.logs.Indicatordomain.GenericMongoLog; import com.caliverse.admin.logs.entity.LogAction; import com.caliverse.admin.logs.logservice.businesslogservice.BusinessLogGenericService; -import com.caliverse.admin.mongodb.service.MysqlHistoryLogService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.json.JSONObject; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -42,11 +39,8 @@ import java.util.Optional; public class CaliumService { private final CaliumMapper caliumMapper; - private final HistoryService historyService; private final Web3Service web3Service; -// private final DynamoDBService dynamoDBService; private final DynamodbCaliumService dynamodbCaliumService; - private final MysqlHistoryLogService mysqlHistoryLogService; private final BusinessLogGenericService businessLogGenericService; public CaliumResponse getCaliumLimit(){ @@ -125,6 +119,7 @@ public class CaliumService { .build(); } + @BusinessProcess(action = com.caliverse.admin.domain.entity.log.LogAction.CALIUM_REQUEST) @Transactional(transactionManager = "transactionManager") public CaliumResponse postCaliumRequest(CaliumRequest caliumRequest){ caliumRequest.setCreateBy(CommonUtils.getAdmin().getId()); @@ -159,15 +154,6 @@ public class CaliumService { int result = caliumMapper.postCaliumRequest(caliumRequest); log.info("postEvent AdminToolDB Event Save: {}", caliumRequest); - Calium calium = caliumMapper.getCaliumRequestDetail(caliumRequest.getId()); - - mysqlHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.CALIUM_ADD, - MysqlConstants.TABLE_NAME_CALIUM_REQUEST, - HISTORYTYPEDETAIL.CALIUM_ADD.name(), - calium - ); - return CaliumResponse.builder() .status(CommonCode.SUCCESS.getHttpStatus()) .result(CommonCode.SUCCESS.getResult()) @@ -177,6 +163,7 @@ public class CaliumService { .build(); } + @BusinessProcess(action = com.caliverse.admin.domain.entity.log.LogAction.CALIUM_REQUEST) @Transactional(transactionManager = "transactionManager") public CaliumResponse updateCaliumCharged(CaliumRequest caliumRequest){ log.info("updateCaliumCharged calium Request: {}", caliumRequest); @@ -200,25 +187,13 @@ public class CaliumService { updateCaliumRequest(caliumRequest.getId(), Calium.CALIUMREQUESTSTATUS.FINISH); - mysqlHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.CALIUM_TOTAL_UPDATE, - MysqlConstants.TABLE_NAME_CALIUM_REQUEST, - HISTORYTYPEDETAIL.CALIUM_TOTAL_UPDATE.name(), - info, - caliumMapper.getCaliumRequestDetail(caliumRequest.getId()) - ); - -// JSONObject jsonObject = new JSONObject(); -// jsonObject.put("dynamoDB_update",dynamoResult); - -// historyService.setLog(HISTORYTYPEDETAIL.CALIUM_TOTAL_UPDATE, jsonObject); - return CaliumResponse.builder() .status(CommonCode.SUCCESS.getHttpStatus()) .result(CommonCode.SUCCESS.getResult()) .build(); } + @BusinessProcess(action = com.caliverse.admin.domain.entity.log.LogAction.CALIUM_REQUEST) @Transactional(transactionManager = "transactionManager") public void getScheduleCaliumRequestList(){ List scheduleList = caliumMapper.getScheduleCaliumRequest(); diff --git a/src/main/java/com/caliverse/admin/domain/service/DataService.java b/src/main/java/com/caliverse/admin/domain/service/DataService.java index 3a489f0..80c3509 100644 --- a/src/main/java/com/caliverse/admin/domain/service/DataService.java +++ b/src/main/java/com/caliverse/admin/domain/service/DataService.java @@ -3,10 +3,12 @@ package com.caliverse.admin.domain.service; import com.caliverse.admin.domain.dao.admin.DataMapper; import com.caliverse.admin.domain.dao.admin.LandMapper; import com.caliverse.admin.domain.entity.*; +import com.caliverse.admin.domain.entity.log.LogAction; import com.caliverse.admin.domain.request.DataRequest; import com.caliverse.admin.domain.request.LogGenericRequest; import com.caliverse.admin.domain.response.DataResponse; import com.caliverse.admin.dynamodb.service.DynamodbDataService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.code.CommonCode; import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.global.common.code.SuccessCode; @@ -33,7 +35,6 @@ import java.util.Map; public class DataService { private final DynamodbDataService dynamodbDataService; - private final MysqlHistoryLogService mysqlHistoryLogService; private final LandMapper landMapper; private final DataMapper dataMapper; private final DataInitializeHistoryService dataInitializeHistoryService; @@ -78,6 +79,7 @@ public class DataService { } + @BusinessProcess(action = LogAction.DATA) @Transactional(transactionManager = "transactionManager") public DataResponse initData(DataRequest dataRequest){ EInitDataType dataType = dataRequest.getInitDataType(); @@ -86,13 +88,6 @@ public class DataService { dataMapper.postDataInit(dataRequest); - mysqlHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.DATA_INIT_ADD, - MysqlConstants.TABLE_NAME_DATA_INIT, - HISTORYTYPEDETAIL.DATA_INIT_ADD.name(), - dataMapper.getDataInitDetail(dataRequest.getId()) - ); - // switch(dataType){ // case LandAuction -> { // int result = initLandAuction(); @@ -131,26 +126,6 @@ public class DataService { long auctionId = landAuction.getId(); int result = landMapper.initLandAuction(auctionId); - List message = landMapper.getMessage(auctionId); - Map map = new HashMap(); - map.put("id", landAuction.getId()); - landMapper.deleteMessage(map); - - mysqlHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.LAND_AUCTION_INITIALIZE, - MysqlConstants.TABLE_NAME_LAND_AUCTION, - HISTORYTYPEDETAIL.LAND_AUCTION_INITIALIZE.name(), - landAuction - ); - if (!message.isEmpty()) { - mysqlHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.LAND_AUCTION_INITIALIZE, - MysqlConstants.TABLE_NAME_MESSAGE, - HISTORYTYPEDETAIL.LAND_AUCTION_INITIALIZE.name(), - message - ); - } - dataInitializeHistoryService.mysqlDataInitHistory( EInitDataType.LandAuction, MysqlConstants.TABLE_NAME_LAND_AUCTION, @@ -176,13 +151,6 @@ public class DataService { long id = landOwnerChange.getId(); landMapper.initLandOwnedChanges(id); - mysqlHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.LAND_OWNED_INITIALIZE, - MysqlConstants.TABLE_NAME_LAND_OWNER_CHANGE, - HISTORYTYPEDETAIL.LAND_OWNED_INITIALIZE.name(), - landOwnerChange - ); - dataInitializeHistoryService.mysqlDataInitHistory( EInitDataType.LandOwned, MysqlConstants.TABLE_NAME_LAND_OWNER_CHANGE, @@ -206,6 +174,7 @@ public class DataService { return dataMapper.getDataInit(); } + @BusinessProcess(action = LogAction.DATA) public void updateStatus(long id, DataInit.DATA_INIT_STATUS status){ dataMapper.updateStatus(id, status.toString()); } diff --git a/src/main/java/com/caliverse/admin/domain/service/EventService.java b/src/main/java/com/caliverse/admin/domain/service/EventService.java index 2caa0d1..aa7aa0c 100644 --- a/src/main/java/com/caliverse/admin/domain/service/EventService.java +++ b/src/main/java/com/caliverse/admin/domain/service/EventService.java @@ -3,21 +3,27 @@ package com.caliverse.admin.domain.service; import com.caliverse.admin.domain.dao.admin.EventMapper; import com.caliverse.admin.domain.datacomponent.MetaDataHandler; import com.caliverse.admin.domain.entity.*; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; import com.caliverse.admin.domain.request.EventRequest; import com.caliverse.admin.domain.response.EventResponse; import com.caliverse.admin.dynamodb.service.DynamodbMailService; import com.caliverse.admin.dynamodb.service.DynamodbService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.code.CommonCode; import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.global.common.code.SuccessCode; import com.caliverse.admin.global.common.constants.MysqlConstants; import com.caliverse.admin.global.common.utils.CommonUtils; +import com.caliverse.admin.global.component.manager.BusinessProcessIdManager; import com.caliverse.admin.mongodb.service.MysqlHistoryLogService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.json.JSONObject; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; import java.time.LocalDateTime; import java.util.HashMap; @@ -33,8 +39,8 @@ public class EventService { private final EventMapper eventMapper; private final MetaDataHandler metaDataHandler; - private final HistoryService historyService; private final MysqlHistoryLogService mysqlHistoryLogService; + private final BusinessProcessIdManager processIdManager; public EventResponse getList(Map requestParam){ //페이징 처리 @@ -80,6 +86,7 @@ public class EventService { .build(); } + @BusinessProcess(action = LogAction.EVENT) @Transactional(transactionManager = "transactionManager") public EventResponse postEvent(EventRequest eventRequest){ eventRequest.setCreateBy(CommonUtils.getAdmin().getId()); @@ -117,14 +124,29 @@ public class EventService { } log.info("postEvent AdminToolDB Message Save Complete"); - Event event = eventMapper.getEventDetail(event_id); + String prodId = processIdManager.getCurrentProcessId(); - mysqlHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.EVENT_ADD, - MysqlConstants.TABLE_NAME_EVENT, - HISTORYTYPEDETAIL.EVENT_ADD.name(), - event - ); + Event event = eventMapper.getEventDetail(event_id); + event.setMailList(eventMapper.getMessage(event_id)); + event.setItemList(eventMapper.getItem(event_id)); + + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + try { + mysqlHistoryLogService.insertHistoryLog( + prodId, + LogAction.EVENT, + LogStatus.SUCCESS, + MysqlConstants.TABLE_NAME_EVENT, + "", + event + ); + } catch (Exception e) { + log.warn("Failed to log event creation: {}", e.getMessage()); + } + } + }); return EventResponse.builder() .status(CommonCode.SUCCESS.getHttpStatus()) @@ -135,6 +157,7 @@ public class EventService { .build(); } + @BusinessProcess(action = LogAction.EVENT) @Transactional(transactionManager = "transactionManager") public EventResponse updateEvent(Long id, EventRequest eventRequest) { eventRequest.setId(id); @@ -147,7 +170,7 @@ public class EventService { before_info.setItemList(eventMapper.getItem(event_id)); int result = eventMapper.updateEvent(eventRequest); - log.info("updateEvent AdminToolDB Event Update Complete: {}", eventRequest); + Map map = new HashMap<>(); map.put("mailId", String.valueOf(event_id)); @@ -164,7 +187,6 @@ public class EventService { eventMapper.insertItem(map); }); } - log.info("updateEvent AdminToolDB Item Update Complete"); // message 테이블 데이터 삭제 처리 by mail_id eventMapper.deleteMessage(map); @@ -179,19 +201,31 @@ public class EventService { eventMapper.insertMessage(map); }); } - log.info("updateEvent AdminToolDB Message Update Complete"); + log.info("updateEvent AdminToolDB Event Update Complete id: {}", eventRequest.getId()); Event after_event = eventMapper.getEventDetail(event_id); after_event.setMailList(eventMapper.getMessage(event_id)); after_event.setItemList(eventMapper.getItem(event_id)); - mysqlHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.EVENT_UPDATE, - MysqlConstants.TABLE_NAME_EVENT, - HISTORYTYPEDETAIL.EVENT_UPDATE.name(), - before_info, - after_event - ); + String prodId = processIdManager.getCurrentProcessId(); + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + try { + mysqlHistoryLogService.updateHistoryLog( + prodId, + LogAction.EVENT, + LogStatus.SUCCESS, + MysqlConstants.TABLE_NAME_EVENT, + "", + before_info, + after_event + ); + } catch (Exception e) { + log.warn("Failed to log event creation: {}", e.getMessage()); + } + } + }); return EventResponse.builder() .status(CommonCode.SUCCESS.getHttpStatus()) @@ -202,6 +236,7 @@ public class EventService { .build(); } + @BusinessProcess(action = LogAction.EVENT) @Transactional(transactionManager = "transactionManager") public EventResponse deleteEvent(EventRequest eventRequest){ Map map = new HashMap<>(); @@ -213,17 +248,10 @@ public class EventService { event.setMailList(eventMapper.getMessage(event_id)); event.setItemList(eventMapper.getItem(event_id)); - map.put("mailId",event_id); + map.put("id",event_id); map.put("desc", item.getDeleteDesc()); int result = eventMapper.deleteEvent(map); - log.info("updateEvent AdminTool Delete Complete: {}", eventRequest); - - mysqlHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.EVENT_DELETE, - MysqlConstants.TABLE_NAME_EVENT, - HISTORYTYPEDETAIL.EVENT_DELETE.name(), - event - ); + log.info("updateEvent AdminTool Delete Complete id: {}", event_id); } ); diff --git a/src/main/java/com/caliverse/admin/domain/service/GameSettingService.java b/src/main/java/com/caliverse/admin/domain/service/GameSettingService.java new file mode 100644 index 0000000..ccd3269 --- /dev/null +++ b/src/main/java/com/caliverse/admin/domain/service/GameSettingService.java @@ -0,0 +1,82 @@ +package com.caliverse.admin.domain.service; + +import com.caliverse.admin.domain.datacomponent.MetaDataHandler; +import com.caliverse.admin.domain.entity.BattleEvent; +import com.caliverse.admin.domain.entity.metadata.*; +import com.caliverse.admin.domain.request.BattleEventRequest; +import com.caliverse.admin.domain.response.BattleEventResponse; +import com.caliverse.admin.dynamodb.service.DynamodbBattleEventService; +import com.caliverse.admin.global.common.code.CommonCode; +import com.caliverse.admin.global.common.utils.CommonUtils; +import com.caliverse.admin.mongodb.service.MysqlHistoryLogService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.RequestParam; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +@Service +@RequiredArgsConstructor +@Slf4j +public class GameSettingService { + + private final DynamodbBattleEventService dynamodbBattleEventService; + + private final MetaDataHandler metaDataHandler; + private final MysqlHistoryLogService mysqlHistoryLogService; + + // 게임 셋팅 설정 조회 + public BattleEventResponse getGameSettingList(@RequestParam Map requestParam){ + + requestParam = CommonUtils.pageSetting(requestParam); + + List list = metaDataHandler.getMetaGameModeMatchListData(); + + return BattleEventResponse.builder() + .status(CommonCode.SUCCESS.getHttpStatus()) + .result(CommonCode.SUCCESS.getResult()) + .resultData(BattleEventResponse.ResultData.builder() +// .battleEventList(list) + .pageNo(requestParam.get("page_no")!=null? + Integer.parseInt(requestParam.get("page_no")):1) + .build() + ) + .build(); + } + + // 게임 셋팅 설정 상세조회 + public BattleEventResponse getGameSettingDetail(Long id){ + + BattleEvent battleEvent = null; + + return BattleEventResponse.builder() + .status(CommonCode.SUCCESS.getHttpStatus()) + .result(CommonCode.SUCCESS.getResult()) + .resultData(BattleEventResponse.ResultData.builder() + .battleEvent(battleEvent) + .build()) + .build(); + } + + // 게임 셋팅 설정 저장/수정 + @Transactional(transactionManager = "transactionManager") + public BattleEventResponse updateGameSetting(Long id, BattleEventRequest battleEventRequest) { + battleEventRequest.setId(id); + battleEventRequest.setUpdateBy(CommonUtils.getAdmin().getId()); + battleEventRequest.setUpdateDt(LocalDateTime.now()); + + dynamodbBattleEventService.updateBattleEvent(battleEventRequest); + + return BattleEventResponse.builder() + .resultData(BattleEventResponse.ResultData.builder() + .build()) + .status(CommonCode.SUCCESS.getHttpStatus()) + .result(CommonCode.SUCCESS.getResult()) + .build(); + } + +} diff --git a/src/main/java/com/caliverse/admin/domain/service/GroupService.java b/src/main/java/com/caliverse/admin/domain/service/GroupService.java index 2885138..c83263d 100644 --- a/src/main/java/com/caliverse/admin/domain/service/GroupService.java +++ b/src/main/java/com/caliverse/admin/domain/service/GroupService.java @@ -1,10 +1,11 @@ package com.caliverse.admin.domain.service; import com.caliverse.admin.domain.dao.admin.GroupMapper; -import com.caliverse.admin.domain.dao.admin.HistoryMapper; import com.caliverse.admin.domain.entity.*; +import com.caliverse.admin.domain.entity.log.LogAction; import com.caliverse.admin.domain.request.GroupRequest; import com.caliverse.admin.domain.response.GroupResponse; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.code.CommonCode; import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.global.common.code.SuccessCode; @@ -12,7 +13,6 @@ import com.caliverse.admin.global.common.exception.RestApiException; import com.caliverse.admin.global.common.utils.CommonUtils; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.json.JSONObject; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -24,7 +24,6 @@ import java.util.*; public class GroupService { private final GroupMapper groupMapper; - private final HistoryMapper historyMapper; // 관리자 권한 리스트 조회 @@ -84,6 +83,8 @@ public class GroupService { } //권한 그룹 등록 + @BusinessProcess(action = LogAction.GROUP) + @Transactional(transactionManager = "transactionManager") public GroupResponse postAdminGroup(GroupRequest groupRequest){ List authList = Arrays.asList(1, 5, 6, 9, 10, 11, 13, 14, 15, 16, 19, 22, 24, 26, 32, 36, 41,46, 49); //그룹 초기 권한 Map map = new HashMap<>(); @@ -92,7 +93,7 @@ public class GroupService { int groupName = groupMapper.findGroupName(groupRequest.getGroupNm()); if(groupName == 0){ - groupMapper.postAdminGroup(groupRequest); + groupMapper.postGroup(groupRequest); map.put("groupId", groupRequest.getId()); authList.forEach(val->{ @@ -112,6 +113,7 @@ public class GroupService { .build(); } //그룹 권한 수정 + @BusinessProcess(action = LogAction.GROUP) @Transactional(transactionManager = "transactionManager") public GroupResponse updateAdminGroup(String groupId,GroupRequest groupRequest){ @@ -132,18 +134,7 @@ public class GroupService { ); //로그 남기 before 그룹 설정 List afterAuth = groupMapper.getGroupAuth(Long.valueOf(groupId)); - log.info("updateAdminGroup after::{}",afterAuth); - //로그 기록 - map.put("adminId", CommonUtils.getAdmin().getId()); - map.put("name", CommonUtils.getAdmin().getName()); - map.put("mail", CommonUtils.getAdmin().getEmail()); - map.put("type", HISTORYTYPEDETAIL.GROUP_AUTH_UPDATE); - JSONObject jsonObject = new JSONObject(); - jsonObject.put("groupNm",groupMapper.getGroupInfo(Long.valueOf(groupId)).get("name")); - jsonObject.put("auth(before)",beforeAuth); - jsonObject.put("auth(after)",afterAuth); - map.put("content",jsonObject.toString()); - historyMapper.saveLog(map); + log.info("updateAdminGroup groupId: {}", groupId); return GroupResponse.builder() .status(CommonCode.SUCCESS.getHttpStatus()) @@ -152,25 +143,16 @@ public class GroupService { .build(); } //그룹 삭제 + @BusinessProcess(action = LogAction.GROUP) @Transactional(transactionManager = "transactionManager") public GroupResponse deleteAdminGroup(GroupRequest groupRequest){ Map map = new HashMap(); groupRequest.getGroupList().forEach( item-> { - //순서 바뀜 안됨, 삭제 하기전 그룹명 가져오기 Map groupInfo = groupMapper.getGroupInfo(item.getGroupId()); groupMapper.deleteGroup(item.getGroupId()); - //로그 기록 - JSONObject jsonObject = new JSONObject(); - jsonObject.put("groupNm",groupInfo.get("name")); - map.put("adminId", CommonUtils.getAdmin().getId()); - map.put("name", CommonUtils.getAdmin().getName()); - map.put("mail", CommonUtils.getAdmin().getEmail()); - map.put("type", HISTORYTYPEDETAIL.GROUP_DELETE); - map.put("content",jsonObject.toString()); - historyMapper.saveLog(map); } ); log.info("deleteAdminGroup group: {}", map); diff --git a/src/main/java/com/caliverse/admin/domain/service/HistoryService.java b/src/main/java/com/caliverse/admin/domain/service/HistoryService.java index ec8bda4..301cdb2 100644 --- a/src/main/java/com/caliverse/admin/domain/service/HistoryService.java +++ b/src/main/java/com/caliverse/admin/domain/service/HistoryService.java @@ -3,7 +3,6 @@ package com.caliverse.admin.domain.service; import com.caliverse.admin.domain.dao.admin.AdminMapper; import com.caliverse.admin.domain.entity.Admin; import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; -import com.caliverse.admin.domain.dao.admin.HistoryMapper; import com.caliverse.admin.domain.request.HistoryRequest; import com.caliverse.admin.domain.response.HistoryResponse; import com.caliverse.admin.global.common.code.CommonCode; @@ -16,16 +15,9 @@ import com.caliverse.admin.mongodb.service.HistoryLogService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.io.FileUtils; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; import org.springframework.stereotype.Service; -import java.io.File; -import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -36,7 +28,6 @@ import java.util.Optional; public class HistoryService { private final AdminMapper adminMapper; - private final HistoryMapper historyMapper; private final HistoryLogService historyLogService; public HistoryResponse getHistoryList(Map requestParams){ @@ -74,8 +65,6 @@ public class HistoryService { List historyList = historyLogService.loadHistoryData(historyRequest, HistoryLogInfoBase.class); - int allCnt = historyMapper.getAllCnt(requestParams); - return HistoryResponse.builder() .resultData(HistoryResponse.ResultData.builder() .list(historyList) @@ -99,24 +88,11 @@ public class HistoryService { } public HistoryResponse getHistoryDetail(String id){ - String logJson = historyMapper.getLogJson(id); return HistoryResponse.builder() - .resultData(HistoryResponse.ResultData.builder().content(logJson).build()) + .resultData(HistoryResponse.ResultData.builder().build()) .status(CommonCode.SUCCESS.getHttpStatus()) .result(CommonCode.SUCCESS.getResult()) .build(); } - public void setScheduleLog(HISTORYTYPEDETAIL type, String message){ - //스케줄 로그 기록 - Map logMap = new HashMap<>(); - logMap.put("adminId", 1); - logMap.put("name", "schedule"); - logMap.put("mail", "schedule"); - logMap.put("type", type); - JSONObject jsonObject = new JSONObject(); - jsonObject.put("message",message); - logMap.put("content",jsonObject.toString()); - historyMapper.saveLog(logMap); - } } diff --git a/src/main/java/com/caliverse/admin/domain/service/ItemsService.java b/src/main/java/com/caliverse/admin/domain/service/ItemsService.java index 0731d2b..28c1ef8 100644 --- a/src/main/java/com/caliverse/admin/domain/service/ItemsService.java +++ b/src/main/java/com/caliverse/admin/domain/service/ItemsService.java @@ -3,6 +3,7 @@ package com.caliverse.admin.domain.service; import com.caliverse.admin.domain.datacomponent.MetaDataHandler; import com.caliverse.admin.domain.entity.ITEMLARGETYPE; import com.caliverse.admin.domain.entity.SEARCHTYPE; +import com.caliverse.admin.domain.entity.log.LogAction; import com.caliverse.admin.domain.response.ItemDeleteResponse; import com.caliverse.admin.domain.response.UsersResponse; import com.caliverse.admin.dynamodb.domain.atrrib.ItemAttrib; @@ -10,6 +11,7 @@ import com.caliverse.admin.dynamodb.domain.doc.ItemDoc; import com.caliverse.admin.dynamodb.dto.PageResult; import com.caliverse.admin.dynamodb.service.DynamodbItemService; import com.caliverse.admin.dynamodb.service.DynamodbUserService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.global.common.utils.CommonUtils; import lombok.extern.slf4j.Slf4j; @@ -98,7 +100,7 @@ public class ItemsService { .build(); } - + @BusinessProcess(action = LogAction.ITEM) @Transactional(transactionManager = "transactionManager") public ItemDeleteResponse postItemDelete(ItemsRequest itemDeleteRequest){ String userGuid = itemDeleteRequest.getUserGuid(); diff --git a/src/main/java/com/caliverse/admin/domain/service/LandService.java b/src/main/java/com/caliverse/admin/domain/service/LandService.java index 3618c82..6b59db8 100644 --- a/src/main/java/com/caliverse/admin/domain/service/LandService.java +++ b/src/main/java/com/caliverse/admin/domain/service/LandService.java @@ -3,6 +3,7 @@ package com.caliverse.admin.domain.service; import com.caliverse.admin.domain.dao.admin.LandMapper; import com.caliverse.admin.domain.datacomponent.MetaDataHandler; import com.caliverse.admin.domain.entity.*; +import com.caliverse.admin.domain.entity.log.LogAction; import com.caliverse.admin.dynamodb.domain.atrrib.LandAttrib; import com.caliverse.admin.dynamodb.domain.atrrib.LandAuctionHighestBidUserAttrib; import com.caliverse.admin.dynamodb.domain.atrrib.LandAuctionRegistryAttrib; @@ -16,6 +17,7 @@ import com.caliverse.admin.dynamodb.service.DynamodbLandAuctionService; import com.caliverse.admin.dynamodb.service.DynamodbLandService; import com.caliverse.admin.dynamodb.service.DynamodbService; import com.caliverse.admin.dynamodb.service.DynamodbUserService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.code.CommonCode; import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.global.common.code.SuccessCode; @@ -45,17 +47,14 @@ import static com.caliverse.admin.global.common.utils.DateUtils.stringISOToLocal @Slf4j public class LandService { -// private final DynamoDBService dynamoDBService; private final DynamodbLandAuctionService dynamodbLandAuctionService; private final DynamodbLandService dynamodbLandService; private final DynamodbUserService dynamodbUserService; private final LandMapper landMapper; private final MetaDataHandler metaDataHandler; - private final HistoryService historyService; private final ObjectMapper objectMapper; private final MysqlHistoryLogService mysqlHistoryLogService; - private final DynamodbService dynamodbService; public LandResponse getLandInfo(@RequestParam Map requestParam){ String searchType = requestParam.getOrDefault("land_type", "ID"); @@ -314,8 +313,6 @@ public class LandService { LandAuction event = landMapper.getLandAuctionDetail(id); - event.setMessageList(landMapper.getMessage(id)); - log.info("call User Email: {}, event_id: {}", CommonUtils.getAdmin().getEmail(), id); return LandResponse.builder() @@ -355,8 +352,6 @@ public class LandService { LandAuction landAuction = landMapper.getLandAuctionDetail(id); - landAuction.setMessageList(landMapper.getMessage(id)); - log.info("call User Email: {}, id: {}", CommonUtils.getAdmin().getEmail(), id); return LandResponse.builder() @@ -368,6 +363,7 @@ public class LandService { .build(); } + @BusinessProcess(action = LogAction.LAND_AUCTION) @Transactional(transactionManager = "transactionManager") public LandResponse postLandAuction(LandRequest landRequest){ @@ -393,35 +389,7 @@ public class LandService { landRequest.setCreateBy(CommonUtils.getAdmin().getId()); int result = landMapper.postLandAuction(landRequest); - log.info("AdminToolDB LandAuction Save: {}", landRequest); - - long auction_id = landRequest.getId(); - - HashMap map = new HashMap<>(); - map.put("id",String.valueOf(auction_id)); - - //메시지 저장 -// if(landRequest.getMassageList()!= null && !landRequest.getMassageList().isEmpty()){ -// landRequest.getMassageList().forEach( -// item -> { -// map.put("title",item.getTitle()); -// map.put("content",item.getContent()); -// map.put("language",item.getLanguage()); -// landMapper.insertMessage(map); -// } -// ); -// } -// log.info("AdminToolDB Message Save Complete"); - - LandAuction auction_info = landMapper.getLandAuctionDetail(auction_id); - auction_info.setMessageList(landMapper.getMessage(auction_id)); - - mysqlHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.LAND_AUCTION_ADD, - MysqlConstants.TABLE_NAME_LAND_AUCTION, - HISTORYTYPEDETAIL.LAND_AUCTION_ADD.name(), - auction_info - ); + log.info("AdminToolDB LandAuction Save id: {}", landRequest.getId()); dynamodbLandAuctionService.insertLandAuctionRegistryWithActivity(landRequest); @@ -434,6 +402,7 @@ public class LandService { .build(); } + @BusinessProcess(action = LogAction.LAND_OWNER_CHANGE) @Transactional(transactionManager = "transactionManager") public LandResponse postLandOwnerChanges(LandRequest landRequest){ String guid = landRequest.getUserGuid(); @@ -469,25 +438,7 @@ public class LandService { } int result = landMapper.postLandOwnerChange(landRequest); - try { - log.info("AdminToolDB LandOwnerChanges Save: {}", objectMapper.writeValueAsString(landRequest)); - } catch (JsonProcessingException e) { - throw new RuntimeException(e); - } - - long id = landRequest.getId(); - - HashMap map = new HashMap<>(); - map.put("id",String.valueOf(id)); - - LandOwnerChange info = landMapper.getLandOwnerChangeDetail(id); - - mysqlHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_ADD, - MysqlConstants.TABLE_NAME_LAND_OWNER_CHANGE, - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_ADD.name(), - info - ); + log.info("AdminToolDB LandOwnerChanges Save id: {}", landRequest.getId()); // if(!is_reserve){ // dynamodbLandService.ChangesLandOwner(landRequest); @@ -505,6 +456,7 @@ public class LandService { .build(); } + @BusinessProcess(action = LogAction.LAND_AUCTION) @Transactional(transactionManager = "transactionManager") public LandResponse updateLandAuction(Long id, LandRequest landRequest) { landRequest.setId(id); @@ -512,7 +464,6 @@ public class LandService { landRequest.setUpdateDt(LocalDateTime.now()); LandAuction before_info = landMapper.getLandAuctionDetail(id); -// before_info.setMessageList(landMapper.getMessage(id)); if(!before_info.getStatus().equals(LandAuction.AUCTION_STATUS.WAIT) && !before_info.getStatus().equals(LandAuction.AUCTION_STATUS.RESV_START)){ return LandResponse.builder() @@ -522,40 +473,10 @@ public class LandService { } int result = landMapper.updateLandAuction(landRequest); - log.info("AdminToolDB LandAuction Update Complete: {}", landRequest); - - Map map = new HashMap<>(); - map.put("id", String.valueOf(id)); - - // message 테이블 데이터 삭제 처리 by mail_id -// landMapper.deleteMessage(map); -// -// // 메시지 업데이트 -// if (landRequest.getMassageList() != null && !landRequest.getMassageList().isEmpty()) { -// landRequest.getMassageList().forEach(item -> { -// map.put("title", item.getTitle()); -// map.put("content", item.getContent()); -// map.put("language", item.getLanguage()); -// -// landMapper.insertMessage(map); -// }); -// } -// log.info("AdminToolDB Message Update Complete"); - - LandAuction after_info = landMapper.getLandAuctionDetail(id); -// after_info.setMessageList(landMapper.getMessage(id)); - - mysqlHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.LAND_AUCTION_UPDATE, - MysqlConstants.TABLE_NAME_LAND_AUCTION, - HISTORYTYPEDETAIL.LAND_AUCTION_UPDATE.name(), - before_info, - after_info - ); + log.info("AdminToolDB LandAuction Update Complete id: {}", id); dynamodbLandAuctionService.updateLandAuction(landRequest); - return LandResponse.builder() .resultData(LandResponse.ResultData.builder() .build()) @@ -564,29 +485,15 @@ public class LandService { .build(); } + @BusinessProcess(action = LogAction.LAND_OWNER_CHANGE) @Transactional(transactionManager = "transactionManager") public LandResponse updateLandOwnerChanges(Long id, LandRequest landRequest) { landRequest.setId(id); landRequest.setUpdateBy(CommonUtils.getAdmin().getId()); landRequest.setUpdateDt(LocalDateTime.now()); - Map map = new HashMap<>(); - map.put("id", String.valueOf(id)); - - LandOwnerChange before_info = landMapper.getLandOwnerChangeDetail(id); - int result = landMapper.updateLandOwnerChange(landRequest); - log.info("AdminToolDB LandOwnerChanges Update Complete: {}", landRequest); - - LandOwnerChange after_info = landMapper.getLandOwnerChangeDetail(id); - - mysqlHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_UPDATE, - MysqlConstants.TABLE_NAME_LAND_OWNER_CHANGE, - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_UPDATE.name(), - before_info, - after_info - ); + log.info("AdminToolDB LandOwnerChanges Update Complete id: {}", id); dynamodbLandService.ChangesLandOwner(landRequest); @@ -598,6 +505,7 @@ public class LandService { .build(); } + @BusinessProcess(action = LogAction.LAND_AUCTION) @Transactional(transactionManager = "transactionManager") public LandResponse deleteLandAuction(LandRequest landRequest){ Map map = new HashMap<>(); @@ -607,7 +515,6 @@ public class LandService { item->{ Long auction_id = item.getId(); LandAuction auction_info = landMapper.getLandAuctionDetail(auction_id); - auction_info.setMessageList(landMapper.getMessage(auction_id)); if(!auction_info.getStatus().equals(LandAuction.AUCTION_STATUS.WAIT) && !auction_info.getStatus().equals(LandAuction.AUCTION_STATUS.RESV_START)){ is_falil.set(true); @@ -616,15 +523,10 @@ public class LandService { map.put("id", auction_id); map.put("updateBy", CommonUtils.getAdmin().getId()); - int result = landMapper.deleteLandAuction(map); - log.info("LandAuction Delete Complete: {}", item); - mysqlHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.LAND_AUCTION_DELETE, - MysqlConstants.TABLE_NAME_LAND_AUCTION, - HISTORYTYPEDETAIL.LAND_AUCTION_DELETE.name(), - auction_info - ); + int result = landMapper.deleteLandAuction(map); + + log.info("LandAuction Delete Complete id: {}", auction_id); dynamodbLandAuctionService.cancelLandAuction(auction_info); } @@ -645,6 +547,7 @@ public class LandService { .build(); } + @BusinessProcess(action = LogAction.LAND_OWNER_CHANGE) @Transactional(transactionManager = "transactionManager") public LandResponse deleteLandOwnerChanges(LandRequest landRequest){ Long id = landRequest.getId(); @@ -662,14 +565,7 @@ public class LandService { map.put("id", id); map.put("updateBy", CommonUtils.getAdmin().getId()); int result = landMapper.deleteLandOwnerChanges(map); - log.info("LandOwnerChanges Delete Complete: {}", landRequest); - - mysqlHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_DELETE, - MysqlConstants.TABLE_NAME_LAND_OWNER_CHANGE, - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_DELETE.name(), - info - ); + log.info("LandOwnerChanges Delete Complete id: {}", id); return LandResponse.builder() .resultData(LandResponse.ResultData.builder() diff --git a/src/main/java/com/caliverse/admin/domain/service/MailService.java b/src/main/java/com/caliverse/admin/domain/service/MailService.java index 9c73968..465fd76 100644 --- a/src/main/java/com/caliverse/admin/domain/service/MailService.java +++ b/src/main/java/com/caliverse/admin/domain/service/MailService.java @@ -1,14 +1,16 @@ package com.caliverse.admin.domain.service; -import com.caliverse.admin.domain.dao.admin.HistoryMapper; import com.caliverse.admin.domain.dao.admin.MailMapper; import com.caliverse.admin.domain.dao.total.WalletUserMapper; import com.caliverse.admin.domain.datacomponent.MetaDataHandler; import com.caliverse.admin.domain.entity.*; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; import com.caliverse.admin.domain.request.MailRequest; import com.caliverse.admin.domain.response.MailResponse; import com.caliverse.admin.dynamodb.service.DynamodbCaliumService; import com.caliverse.admin.dynamodb.service.DynamodbUserService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.code.CommonCode; import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.global.common.code.SuccessCode; @@ -17,6 +19,7 @@ import com.caliverse.admin.global.common.constants.MysqlConstants; import com.caliverse.admin.global.common.exception.RestApiException; import com.caliverse.admin.global.common.utils.CommonUtils; import com.caliverse.admin.global.common.utils.ExcelUtils; +import com.caliverse.admin.global.component.manager.BusinessProcessIdManager; import com.caliverse.admin.mongodb.service.MysqlHistoryLogService; import com.caliverse.admin.scheduler.ScheduleService; import lombok.RequiredArgsConstructor; @@ -26,6 +29,8 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.web.multipart.MultipartFile; import org.springframework.core.io.ResourceLoader; @@ -47,13 +52,13 @@ public class MailService { private String samplePath; private final ExcelUtils excelUtils; private final MailMapper mailMapper; - private final HistoryMapper historyMapper; private final MetaDataHandler metaDataHandler; private final ResourceLoader resourceLoader; private final ScheduleService scheduleService; private final HistoryService historyService; private final DynamodbCaliumService dynamodbCaliumService; private final MysqlHistoryLogService mysqlHistoryLogService; + private final BusinessProcessIdManager processIdManager; public MailResponse getStockCalium(){ double stock_calium = dynamodbCaliumService.getCaliumTotal(); @@ -168,6 +173,7 @@ public class MailService { } } + @BusinessProcess(action = LogAction.MAIL) @Transactional(transactionManager = "transactionManager") public MailResponse postMail(MailRequest mailRequest){ mailRequest.setCreateBy(CommonUtils.getAdmin().getId()); @@ -274,7 +280,6 @@ public class MailService { } } - //메시지 저장 if(mailRequest.getMailList()!= null && !mailRequest.getMailList().isEmpty()){ mailRequest.getMailList().forEach( @@ -292,12 +297,24 @@ public class MailService { info.setMailList(mailMapper.getMessage(mailRequest.getId())); info.setItemList(mailMapper.getItem(mailRequest.getId())); - mysqlHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.MAIL_ADD, - MysqlConstants.TABLE_NAME_MAIL, - HISTORYTYPEDETAIL.MAIL_ADD.name(), - info - ); + String prodId = processIdManager.getCurrentProcessId(); + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + try { + mysqlHistoryLogService.insertHistoryLog( + prodId, + LogAction.MAIL, + LogStatus.SUCCESS, + MysqlConstants.TABLE_NAME_MAIL, + "", + info + ); + } catch (Exception e) { + log.warn("Failed to log mail creation: {}", e.getMessage()); + } + } + }); return MailResponse.builder() .status(CommonCode.SUCCESS.getHttpStatus()) @@ -307,6 +324,8 @@ public class MailService { .build()) .build(); } + + @BusinessProcess(action = LogAction.MAIL) @Transactional(transactionManager = "transactionManager") public MailResponse updateMail(Long id, MailRequest mailRequest) { mailRequest.setId(id); @@ -341,8 +360,6 @@ public class MailService { before_info.setMailList(mailMapper.getMessage(mail_id)); before_info.setItemList(mailMapper.getItem(mail_id)); - log.info("updateMail Update Before MailInfo: {}", before_info); - mailMapper.updateMail(mailRequest); // 스케줄에서 제거 @@ -377,30 +394,31 @@ public class MailService { mailMapper.insertMessage(map); }); } - log.info("updateMail Update After Mail: {}", mailRequest); + log.info("updateMail Update Complete Mail Id: {}", mailRequest.getId()); Mail after_info = mailMapper.getMailDetail(mail_id); after_info.setMailList(mailMapper.getMessage(mail_id)); after_info.setItemList(mailMapper.getItem(mail_id)); - mysqlHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.MAIL_UPDATE, - MysqlConstants.TABLE_NAME_MAIL, - HISTORYTYPEDETAIL.MAIL_UPDATE.name(), - before_info, - after_info - ); - - //로그 기록 -// JSONObject jsonObject = new JSONObject(); -// jsonObject.put("before_info",before_info.toString()); -// jsonObject.put("mail_type",mailRequest.getMailType()); -// jsonObject.put("receiver",mailRequest.getTarget()); -// Mail.SENDTYPE sendType = mailRequest.getSendType(); -// jsonObject.put("send_type",sendType); -// if(sendType.equals(Mail.SENDTYPE.RESERVE_SEND)) -// jsonObject.put("send_dt",mailRequest.getSendDt()); -// historyService.setLog(HISTORYTYPE.MAIL_UPDATE, jsonObject); + String prodId = processIdManager.getCurrentProcessId(); + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + try { + mysqlHistoryLogService.updateHistoryLog( + prodId, + LogAction.MAIL, + LogStatus.SUCCESS, + MysqlConstants.TABLE_NAME_MAIL, + "", + before_info, + after_info + ); + } catch (Exception e) { + log.warn("Failed to log mail creation: {}", e.getMessage()); + } + } + }); return MailResponse.builder() .status(CommonCode.SUCCESS.getHttpStatus()) @@ -411,6 +429,7 @@ public class MailService { .build(); } + @BusinessProcess(action = LogAction.MAIL) @Transactional(transactionManager = "transactionManager") public MailResponse deleteMail(MailRequest mailRequest){ Map map = new HashMap<>(); @@ -419,8 +438,6 @@ public class MailService { item->{ long id = item.getId(); - Mail info = mailMapper.getMailDetail(id); - map.put("id",id); mailMapper.deleteMail(map); @@ -428,25 +445,6 @@ public class MailService { scheduleService.closeTask("mail-" + item.getId()); log.info("deleteMail Mail: {}", item); - mysqlHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.MAIL_DELETE, - MysqlConstants.TABLE_NAME_MAIL, - HISTORYTYPEDETAIL.MAIL_DELETE.name(), - info - ); - - //로그 기록 -// List message = mailMapper.getMessage(Long.valueOf(item.getId())); -// map.put("adminId", CommonUtils.getAdmin().getId()); -// map.put("name", CommonUtils.getAdmin().getName()); -// map.put("mail", CommonUtils.getAdmin().getEmail()); -// map.put("type", HISTORYTYPE.MAIL_DELETE); -// JSONObject jsonObject = new JSONObject(); -// if(!message.isEmpty()){ -// jsonObject.put("message",message.get(0).getTitle()); -// } -// map.put("content",jsonObject.toString()); -// historyMapper.saveLog(map); } ); @@ -471,6 +469,7 @@ public class MailService { return mailMapper.getItem(id); } + @Transactional(transactionManager = "transactionManager") public void updateMailStatus(Long id, Mail.SENDSTATUS status){ Map map = new HashMap<>(); map.put("id", id); @@ -514,9 +513,4 @@ public class MailService { } return target; } - - public void setScheduleLog(HISTORYTYPEDETAIL type, String message){ - //스케줄 로그 기록 - historyService.setScheduleLog(type, message); - } } diff --git a/src/main/java/com/caliverse/admin/domain/service/MenuService.java b/src/main/java/com/caliverse/admin/domain/service/MenuService.java index 275ae9a..5645e63 100644 --- a/src/main/java/com/caliverse/admin/domain/service/MenuService.java +++ b/src/main/java/com/caliverse/admin/domain/service/MenuService.java @@ -3,9 +3,12 @@ package com.caliverse.admin.domain.service; import com.caliverse.admin.domain.RabbitMq.MessageHandlerService; import com.caliverse.admin.domain.dao.admin.MenuMapper; import com.caliverse.admin.domain.entity.*; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; import com.caliverse.admin.domain.request.MenuRequest; import com.caliverse.admin.domain.response.MenuResponse; import com.caliverse.admin.dynamodb.service.DynamodbMenuService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.code.CommonCode; import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.global.common.code.SuccessCode; @@ -14,6 +17,7 @@ import com.caliverse.admin.global.common.constants.MysqlConstants; import com.caliverse.admin.global.common.exception.RestApiException; import com.caliverse.admin.global.common.utils.CommonUtils; import com.caliverse.admin.global.common.utils.FileUtils; +import com.caliverse.admin.global.component.manager.BusinessProcessIdManager; import com.caliverse.admin.mongodb.service.MysqlHistoryLogService; import com.caliverse.admin.redis.service.RedisUserInfoService; import lombok.RequiredArgsConstructor; @@ -24,6 +28,8 @@ import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.UrlResource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.web.multipart.MultipartFile; import software.amazon.awssdk.services.s3.model.S3Exception; @@ -53,6 +59,7 @@ public class MenuService { private final DynamodbMenuService dynamodbMenuService; private final MessageHandlerService messageHandlerService; private final RedisUserInfoService redisUserInfoService; + private final BusinessProcessIdManager processIdManager; public MenuResponse getList(Map requestParam){ @@ -91,6 +98,7 @@ public class MenuService { public MenuResponse imageUpload(MultipartFile file){ if (file.isEmpty()) { + log.error("File is empty"); throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.NOT_EXIT_FILE.toString()); } @@ -151,6 +159,7 @@ public class MenuService { } } + @BusinessProcess(action = LogAction.BANNER) @Transactional(transactionManager = "transactionManager") public MenuResponse postBanner(MenuRequest menuRequest){ menuRequest.setCreateBy(CommonUtils.getAdmin().getId()); @@ -208,12 +217,31 @@ public class MenuService { MenuBanner banner = menuMapper.getBannerDetail(menuRequest.getId()); banner.setImageList(menuMapper.getMessage(menuRequest.getId())); - mysqlHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.MENU_BANNER_ADD, - MysqlConstants.TABLE_NAME_MENU_BANNER, - HISTORYTYPEDETAIL.MENU_BANNER_ADD.name(), - banner - ); + String prodId = processIdManager.getCurrentProcessId(); + LogAction action = processIdManager.getCurrentAction(); + + //message 정보까지 저장해야해서 수동 로그 + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + try { + mysqlHistoryLogService.insertHistoryLog( + prodId, + action, + LogStatus.SUCCESS, + MysqlConstants.TABLE_NAME_MENU_BANNER, + "", + banner + ); + } catch (Exception e) { + log.warn("Failed to log banner creation: {}", e.getMessage()); + } + } + }); + + if(redisUserInfoService.getAllServerList().isEmpty()){ + throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.NOT_FOUND_SERVER.getMessage()); + } dynamodbMenuService.insertBanner(banner); @@ -229,6 +257,7 @@ public class MenuService { .build(); } + @BusinessProcess(action = LogAction.BANNER) @Transactional(transactionManager = "transactionManager") public MenuResponse updateBanner(Long id, MenuRequest menuRequest) { menuRequest.setId(id); @@ -244,34 +273,14 @@ public class MenuService { menuMapper.updateBanner(menuRequest); -// Map map = new HashMap<>(); -// map.put("id", String.valueOf(menuRequest.getId())); - -// menuMapper.deleteMessage(map); -// -// if(menuRequest.getImageList()!= null && !menuRequest.getImageList().isEmpty()){ -// menuRequest.getImageList().forEach(image -> { -// map.put("title", image.getContent()); -// map.put("language", image.getLanguage()); -// if(menuRequest.isLink() && menuRequest.getLinkList() != null && !menuRequest.getLinkList().isEmpty()){ -// String link = menuRequest.getLinkList().stream().filter(data -> data.getLanguage().equals(image.getLanguage())).findFirst().get().getContent(); -// map.put("content", link); -// } -// menuMapper.insertMessage(map); -// }); -// } log.info("updateBanner Update After Banner: {}", menuRequest); MenuBanner after_info = menuMapper.getBannerDetail(banner_id); after_info.setImageList(menuMapper.getMessage(banner_id)); - mysqlHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.MENU_BANNER_UPDATE, - MysqlConstants.TABLE_NAME_MENU_BANNER, - HISTORYTYPEDETAIL.MENU_BANNER_UPDATE.name(), - before_info, - after_info - ); + if(redisUserInfoService.getAllServerList().isEmpty()){ + throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.NOT_FOUND_SERVER.getMessage()); + } dynamodbMenuService.updateBanner(after_info); @@ -287,6 +296,7 @@ public class MenuService { .build(); } + @BusinessProcess(action = LogAction.BANNER) @Transactional(transactionManager = "transactionManager") public MenuResponse deleteBanner(Long id){ Map map = new HashMap<>(); @@ -306,13 +316,11 @@ public class MenuService { } menuMapper.deleteBanner(map); + menuMapper.deleteMessage(map); - mysqlHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.MENU_BANNER_DELETE, - MysqlConstants.TABLE_NAME_MENU_BANNER, - HISTORYTYPEDETAIL.MENU_BANNER_DELETE.name(), - banner - ); + if(redisUserInfoService.getAllServerList().isEmpty()){ + throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.NOT_FOUND_SERVER.getMessage()); + } dynamodbMenuService.deleteBanner(banner.getId().intValue()); diff --git a/src/main/java/com/caliverse/admin/domain/service/NoticeService.java b/src/main/java/com/caliverse/admin/domain/service/NoticeService.java index fb68d1b..4d659c5 100644 --- a/src/main/java/com/caliverse/admin/domain/service/NoticeService.java +++ b/src/main/java/com/caliverse/admin/domain/service/NoticeService.java @@ -1,23 +1,26 @@ package com.caliverse.admin.domain.service; -import com.caliverse.admin.domain.dao.admin.HistoryMapper; import com.caliverse.admin.domain.dao.admin.NoticeMapper; -import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; import com.caliverse.admin.domain.entity.InGame; import com.caliverse.admin.domain.entity.Message; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; import com.caliverse.admin.domain.request.NoticeRequest; import com.caliverse.admin.domain.response.NoticeResponse; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.code.CommonCode; import com.caliverse.admin.global.common.code.SuccessCode; import com.caliverse.admin.global.common.constants.MysqlConstants; import com.caliverse.admin.global.common.utils.CommonUtils; +import com.caliverse.admin.global.component.manager.BusinessProcessIdManager; import com.caliverse.admin.mongodb.service.MysqlHistoryLogService; import com.caliverse.admin.scheduler.ScheduleService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.json.JSONObject; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; import java.util.HashMap; import java.util.List; @@ -30,10 +33,9 @@ import java.util.stream.Collectors; public class NoticeService { private final NoticeMapper noticeMapper; - private final HistoryMapper historyMapper; private final ScheduleService scheduleService; - private final HistoryService historyService; private final MysqlHistoryLogService mysqlHistoryLogService; + private final BusinessProcessIdManager processIdManager; public NoticeResponse getNoticeList(){ @@ -77,6 +79,7 @@ public class NoticeService { } //인게임 메시지 등록 + @BusinessProcess(action = LogAction.NOTICE) @Transactional(transactionManager = "transactionManager") public NoticeResponse postInGameMessage(NoticeRequest noticeRequest){ // 등록자는 메일로 넣어주자 @@ -98,13 +101,27 @@ public class NoticeService { } log.info("postInGameMessage notice: {}", noticeRequest); - mysqlHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.NOTICE_ADD, - MysqlConstants.TABLE_NAME_NOTICE, - HISTORYTYPEDETAIL.NOTICE_ADD.name(), - noticeMapper.getNoticeDetail(noticeRequest.getId()) - ); + InGame info = noticeMapper.getNoticeDetail(noticeRequest.getId()); + info.setMessageList(noticeMapper.getMessage(noticeRequest.getId())); + String prodId = processIdManager.getCurrentProcessId(); + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + try { + mysqlHistoryLogService.insertHistoryLog( + prodId, + LogAction.NOTICE, + LogStatus.SUCCESS, + MysqlConstants.TABLE_NAME_NOTICE, + "", + info + ); + } catch (Exception e) { + log.warn("Failed to log notice creation: {}", e.getMessage()); + } + } + }); return NoticeResponse.builder() .resultData(NoticeResponse.ResultData.builder().message(SuccessCode.REGISTRATION.getMessage()).build()) @@ -113,16 +130,19 @@ public class NoticeService { .build(); } + @BusinessProcess(action = LogAction.NOTICE) @Transactional(transactionManager = "transactionManager") public NoticeResponse updateInGameMessage(Long id, NoticeRequest noticeRequest){ noticeRequest.setId(id); noticeRequest.setUpdateBy(CommonUtils.getAdmin().getId()); InGame before_info = noticeMapper.getNoticeDetail(id); + before_info.setMessageList(noticeMapper.getMessage(id)); int i = noticeMapper.updateNotice(noticeRequest); // 스케줄에서 기존 등록 제거 scheduleService.closeTask(noticeRequest.getId().toString()); + if(i > 0){ InGame before_notice = noticeMapper.getNoticeDetail(noticeRequest.getId()); log.info("updateInGameMessage Before notice: {}", before_notice); @@ -148,13 +168,29 @@ public class NoticeService { } log.info("updateInGameMessage After notice: {}", noticeRequest); - mysqlHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.NOTICE_UPDATE, - MysqlConstants.TABLE_NAME_NOTICE, - HISTORYTYPEDETAIL.NOTICE_UPDATE.name(), - before_info, - noticeMapper.getNoticeDetail(id) - ); + InGame info = noticeMapper.getNoticeDetail(noticeRequest.getId()); + info.setMessageList(noticeMapper.getMessage(noticeRequest.getId())); + + String prodId = processIdManager.getCurrentProcessId(); + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + try { + mysqlHistoryLogService.updateHistoryLog( + prodId, + LogAction.NOTICE, + LogStatus.SUCCESS, + MysqlConstants.TABLE_NAME_NOTICE, + "", + before_info, + info + ); + } catch (Exception e) { + log.warn("Failed to log notice creation: {}", e.getMessage()); + } + } + }); + return NoticeResponse.builder() .resultData(NoticeResponse.ResultData.builder().message(SuccessCode.UPDATE.getMessage()).build()) .result(CommonCode.SUCCESS.getResult()) @@ -162,6 +198,7 @@ public class NoticeService { .build(); } + @BusinessProcess(action = LogAction.NOTICE) @Transactional(transactionManager = "transactionManager") public NoticeResponse deleteInGameMessage(NoticeRequest noticeRequest){ @@ -169,26 +206,16 @@ public class NoticeService { noticeRequest.getList().forEach( item->{ - //사용자 로그 기록 (인게임 메시지 삭제) - String message = noticeMapper.getMessageById(item.getMessageId()); - - noticeMapper.deleteNotice(item.getMessageId()); + noticeMapper.deleteNotice(item.getId()); // 스케줄에서 제거 - scheduleService.closeTask("notice-" + item.getMessageId()); + scheduleService.closeTask("notice-" + item.getId()); log.info("deleteInGameMessage notice: {}", item); - mysqlHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.NOTICE_DELETE, - MysqlConstants.TABLE_NAME_NOTICE, - HISTORYTYPEDETAIL.NOTICE_DELETE.name(), - noticeMapper.getNoticeDetail(item.getMessageId()) - ); - } ); - log.info("deleteInGameMessage notice: {}", noticeRequest); + log.info("deleteInGameMessage notice id: {}", noticeRequest.getList().get(0).getId()); return NoticeResponse.builder() .resultData(NoticeResponse.ResultData.builder().message(SuccessCode.DELETE.getMessage()).build()) .result(CommonCode.SUCCESS.getResult()) @@ -204,6 +231,7 @@ public class NoticeService { return noticeMapper.getMessage(id); } + @Transactional(transactionManager = "transactionManager") public void updateNoticeStatus(Long id, InGame.SENDSTATUS status){ HashMap map = new HashMap(); map.put("id", id); @@ -215,16 +243,4 @@ public class NoticeService { noticeMapper.updateCountNotice(id); } - public void setScheduleLog(HISTORYTYPEDETAIL type, String message){ - //스케줄 로그 기록 - Map logMap = new HashMap<>(); - logMap.put("adminId", 1); - logMap.put("name", "schedule"); - logMap.put("mail", "schedule"); - logMap.put("type", type); - JSONObject jsonObject = new JSONObject(); - jsonObject.put("message",message); - logMap.put("content",jsonObject.toString()); - historyMapper.saveLog(logMap); - } } diff --git a/src/main/java/com/caliverse/admin/domain/service/S3Service.java b/src/main/java/com/caliverse/admin/domain/service/S3Service.java index 8397351..81eba0f 100644 --- a/src/main/java/com/caliverse/admin/domain/service/S3Service.java +++ b/src/main/java/com/caliverse/admin/domain/service/S3Service.java @@ -1,5 +1,6 @@ package com.caliverse.admin.domain.service; +import com.caliverse.admin.global.common.utils.CommonUtils; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; @@ -53,7 +54,7 @@ public class S3Service { } public String uploadFile(File file, String directoryName, String contentType) throws IOException, S3Exception { - String fileName = UUID.randomUUID() + "-" + file.getName(); + String fileName = CommonUtils.getCreateGuId() + "-" + file.getName(); // S3 객체 키 (경로 + 파일명) String objectKey = String.format("%s/%s/%s", activeProfile, directoryName, fileName); diff --git a/src/main/java/com/caliverse/admin/domain/service/UserGameSessionService.java b/src/main/java/com/caliverse/admin/domain/service/UserGameSessionService.java index 4833532..437214c 100644 --- a/src/main/java/com/caliverse/admin/domain/service/UserGameSessionService.java +++ b/src/main/java/com/caliverse/admin/domain/service/UserGameSessionService.java @@ -2,6 +2,8 @@ package com.caliverse.admin.domain.service; import com.caliverse.admin.domain.RabbitMq.MessageHandlerService; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.code.CommonCode; import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.global.common.exception.RestApiException; diff --git a/src/main/java/com/caliverse/admin/domain/service/UsersService.java b/src/main/java/com/caliverse/admin/domain/service/UsersService.java index 8b1194b..d01e54a 100644 --- a/src/main/java/com/caliverse/admin/domain/service/UsersService.java +++ b/src/main/java/com/caliverse/admin/domain/service/UsersService.java @@ -11,6 +11,7 @@ import com.caliverse.admin.domain.RabbitMq.MessageHandlerService; import com.caliverse.admin.domain.entity.EReqType; import com.caliverse.admin.domain.entity.FriendRequest; import com.caliverse.admin.domain.entity.SEARCHTYPE; +import com.caliverse.admin.domain.entity.log.LogAction; import com.caliverse.admin.domain.request.MailRequest; import com.caliverse.admin.dynamodb.domain.atrrib.AccountBaseAttrib; import com.caliverse.admin.dynamodb.domain.atrrib.MailAttrib; @@ -19,6 +20,7 @@ import com.caliverse.admin.dynamodb.domain.atrrib.MoneyAttrib; import com.caliverse.admin.dynamodb.domain.doc.MailDoc; import com.caliverse.admin.dynamodb.dto.PageResult; import com.caliverse.admin.dynamodb.service.*; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.global.common.constants.CommonConstants; import com.caliverse.admin.redis.service.RedisUserInfoService; import lombok.extern.slf4j.Slf4j; @@ -61,6 +63,7 @@ public class UsersService { private MetaDataHandler metaDataHandler; // 닉네임 변경 + @BusinessProcess(action = LogAction.NICKNAME_CHANGE) public UsersResponse changeNickname(UsersRequest usersRequest){ String guid = usersRequest.getGuid(); String nickname = usersRequest.getNickname(); @@ -86,6 +89,7 @@ public class UsersService { } // GM 권한 변경 + @BusinessProcess(action = LogAction.ADMIN_LEVEL) public UsersResponse changeAdminLevel(UsersRequest usersRequest){ String guid = usersRequest.getGuid(); @@ -102,6 +106,7 @@ public class UsersService { } // 유저 킥 + @BusinessProcess(action = LogAction.KICK_USER) public UsersResponse userKick(UsersRequest usersRequest){ String guid = usersRequest.getGuid(); String adminUser = CommonUtils.getAdmin().getEmail(); @@ -269,6 +274,7 @@ public class UsersService { } //인벤토리 아이템 삭제 + @BusinessProcess(action = LogAction.ITEM) public UsersResponse deleteInventoryItem(Map requestParams){ String guid = requestParams.get("guid"); String item_guid = requestParams.get("item_guid"); @@ -381,6 +387,7 @@ public class UsersService { } //우편 삭제 + @BusinessProcess(action = LogAction.MAIL) public UsersResponse deleteMail(Map requestParams){ String guid = requestParams.get("guid"); String mail_guid = requestParams.get("mail_guid"); @@ -399,6 +406,7 @@ public class UsersService { } //우편 아이템 삭제 + @BusinessProcess(action = LogAction.MAIL_ITEM) public UsersResponse deleteMailItem(MailRequest.DeleteMailItem deleteMailItem){ userGameSessionService.kickUserSession(deleteMailItem.getGuid(), "delete mail item"); dynamodbMailService.deleteMailItem(deleteMailItem.getType(), deleteMailItem.getGuid(), @@ -510,6 +518,7 @@ public class UsersService { } + @BusinessProcess(action = LogAction.QUEST_TASK) public UsersResponse CompleteQuestTask(UsersRequest usersRequest){ String serverName = redisUserInfoService.getFirstChannel(); if(serverName.isEmpty()){ diff --git a/src/main/java/com/caliverse/admin/dynamodb/repository/BaseDynamoDBRepository.java b/src/main/java/com/caliverse/admin/dynamodb/repository/BaseDynamoDBRepository.java index c9f9d9f..da7fe89 100644 --- a/src/main/java/com/caliverse/admin/dynamodb/repository/BaseDynamoDBRepository.java +++ b/src/main/java/com/caliverse/admin/dynamodb/repository/BaseDynamoDBRepository.java @@ -1,6 +1,9 @@ package com.caliverse.admin.dynamodb.repository; import com.caliverse.admin.domain.entity.EFilterOperator; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; +import com.caliverse.admin.dynamodb.domain.doc.DynamoDBDocBase; import com.caliverse.admin.dynamodb.dto.PageResult; import com.caliverse.admin.dynamodb.service.DynamoDBOperations; import com.caliverse.admin.global.common.code.CommonCode; @@ -27,6 +30,22 @@ public abstract class BaseDynamoDBRepository implements DynamoDBRepository @Override public void save(T item) { operations.addPutItem(item, entityClass); + + try { + dynamodbHistoryLogService.insertHistoryLog( + LogStatus.SUCCESS, + "", + (DynamoDBDocBase) item + ); + + } catch (Exception e) { + dynamodbHistoryLogService.insertHistoryLog( + LogStatus.FAILURE, + e.getMessage(), + (DynamoDBDocBase) item + ); + throw e; + } } @Override @@ -36,7 +55,32 @@ public abstract class BaseDynamoDBRepository implements DynamoDBRepository @Override public void update(T item) { + DynamoDBDocBase doc = (DynamoDBDocBase) item; + Key key = Key.builder() + .partitionValue(doc.getPK()) + .sortValue(doc.getSK()) + .build(); + T beforeDoc = findById(key); + operations.addUpdateItem(item, entityClass); + + try { + dynamodbHistoryLogService.updateHistoryLog( + LogStatus.SUCCESS, + "", + (DynamoDBDocBase) beforeDoc, + (DynamoDBDocBase) item + ); + + } catch (Exception e) { + dynamodbHistoryLogService.updateHistoryLog( + LogStatus.FAILURE, + e.getMessage(), + null, + (DynamoDBDocBase) item + ); + throw e; + } } @Override @@ -46,7 +90,26 @@ public abstract class BaseDynamoDBRepository implements DynamoDBRepository @Override public void delete(Key key) { + T beforeDoc = findById(key); + operations.addDeleteItem(key, entityClass); + + try { + + dynamodbHistoryLogService.deleteHistoryLog( + LogStatus.SUCCESS, + "", + (DynamoDBDocBase) beforeDoc + ); + + } catch (Exception e) { + dynamodbHistoryLogService.deleteHistoryLog( + LogStatus.FAILURE, + e.getMessage(), + (DynamoDBDocBase) beforeDoc + ); + throw e; + } } @Override diff --git a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/AccountBaseRepositoryImpl.java b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/AccountBaseRepositoryImpl.java index 1047f5c..e1ae56d 100644 --- a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/AccountBaseRepositoryImpl.java +++ b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/AccountBaseRepositoryImpl.java @@ -1,7 +1,6 @@ package com.caliverse.admin.dynamodb.repository.Impl; import com.caliverse.admin.domain.entity.BlackList; -import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; import com.caliverse.admin.dynamodb.domain.atrrib.AccountBaseAttrib; import com.caliverse.admin.dynamodb.domain.doc.AccountBaseDoc; import com.caliverse.admin.dynamodb.entity.EAuthAdminLevelType; @@ -80,12 +79,6 @@ public class AccountBaseRepositoryImpl extends BaseDynamoDBRepository impl log.info("BannerDoc Insert Success: {}", objectMapper.writeValueAsString(doc)); - dynamodbHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.MENU_BANNER_ADD, - HISTORYTYPEDETAIL.MENU_BANNER_ADD.name(), - doc - ); - }catch (Exception e){ log.error("insert Error: {}", e.getMessage()); + throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.DYNAMODB_CONNECTION_ERROR.getMessage()); } } @@ -143,16 +129,10 @@ public class BannerRepositoryImpl extends BaseDynamoDBRepository impl update(afterDoc); log.info("BannerDoc Update Success: {}", objectMapper.writeValueAsString(afterDoc)); - - dynamodbHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.MENU_BANNER_UPDATE, - HISTORYTYPEDETAIL.MENU_BANNER_UPDATE.name(), - beforeDoc, - afterDoc - ); } }catch (Exception e){ log.error("Update Error: {}", e.getMessage()); + throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.DYNAMODB_CONNECTION_ERROR.getMessage()); } } @@ -171,17 +151,12 @@ public class BannerRepositoryImpl extends BaseDynamoDBRepository impl log.info("BannerDoc Delete Success: {}", objectMapper.writeValueAsString(doc)); - dynamodbHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.MENU_BANNER_DELETE, - HISTORYTYPEDETAIL.MENU_BANNER_DELETE.name(), - doc - ); - return new DynamodbOperationResult(true, "", doc); } return new DynamodbOperationResult(true, "null", doc); }catch (Exception e){ log.error("Delete Error: {}", e.getMessage()); + return new DynamodbOperationResult(false, e.getMessage(), null); } } diff --git a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/BattleEventRepositoryImpl.java b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/BattleEventRepositoryImpl.java index c228acb..5499266 100644 --- a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/BattleEventRepositoryImpl.java +++ b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/BattleEventRepositoryImpl.java @@ -2,6 +2,8 @@ package com.caliverse.admin.dynamodb.repository.Impl; import com.caliverse.admin.domain.entity.BattleEvent; import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; import com.caliverse.admin.domain.request.BattleEventRequest; import com.caliverse.admin.dynamodb.domain.atrrib.BattleEventAttrib; import com.caliverse.admin.dynamodb.domain.doc.BattleEventDoc; @@ -119,11 +121,6 @@ public class BattleEventRepositoryImpl extends BaseDynamoDBRepository log.info("BuildingDoc Insert Success: {}", objectMapper.writeValueAsString(doc)); - dynamodbHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_ADD, - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_ADD.name(), - doc - ); - }catch (Exception e){ - log.error("insert Error: {}", e.getMessage()); + log.error("insert info: {}, Error: {}", CommonUtils.objectByString(landRequest), e.getMessage()); throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.DYNAMODB_CONNECTION_ERROR.getMessage()); } } @@ -126,14 +119,9 @@ public class BuildingRepositoryImpl extends BaseDynamoDBRepository log.info("BuildingDoc Update Success: {}", objectMapper.writeValueAsString(afterDoc)); - dynamodbHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_UPDATE, - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_UPDATE.name(), - beforeDoc, - afterDoc - ); } }catch (Exception e){ + log.error("update info: {}, Error: {}", CommonUtils.objectByString(landRequest), e.getMessage()); throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.DYNAMODB_CONNECTION_ERROR.getMessage()); } } @@ -162,12 +150,6 @@ public class BuildingRepositoryImpl extends BaseDynamoDBRepository log.info("BuildingDoc Owned Init Update Success: {}", objectMapper.writeValueAsString(afterDoc)); - dynamodbHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.LAND_OWNED_INITIALIZE, - HISTORYTYPEDETAIL.LAND_OWNED_INITIALIZE.name(), - beforeDoc, - afterDoc - ); return new DynamodbOperationResult(true, "", afterDoc); } return new DynamodbOperationResult(false, "null", null); @@ -205,12 +187,6 @@ public class BuildingRepositoryImpl extends BaseDynamoDBRepository log.info("BuildingDoc Desc Init Update Success: {}", objectMapper.writeValueAsString(afterDoc)); - dynamodbHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.LAND_DESC_INITIALIZE, - HISTORYTYPEDETAIL.LAND_DESC_INITIALIZE.name(), - beforeDoc, - afterDoc - ); return new DynamodbOperationResult(true, "Success", afterDoc); } return new DynamodbOperationResult(true, "null", beforeDoc); diff --git a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/CaliumStorageRepositoryImpl.java b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/CaliumStorageRepositoryImpl.java index d7ebaf8..d15379c 100644 --- a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/CaliumStorageRepositoryImpl.java +++ b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/CaliumStorageRepositoryImpl.java @@ -1,6 +1,5 @@ package com.caliverse.admin.dynamodb.repository.Impl; -import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; import com.caliverse.admin.dynamodb.domain.atrrib.CaliumStorageAttrib; import com.caliverse.admin.dynamodb.domain.doc.CaliumStorageDoc; import com.caliverse.admin.dynamodb.repository.BaseDynamoDBRepository; @@ -82,12 +81,6 @@ public class CaliumStorageRepositoryImpl extends BaseDynamoDBRepository implemen log.info("updateItemStack Update Success: {}", CommonUtils.objectByString(afterDoc)); - dynamodbHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.ITEM_UPDATE, - HISTORYTYPEDETAIL.ITEM_UPDATE.name(), - beforeDoc, - afterDoc - ); } }catch (Exception e){ log.error("Update Item Error: {}", e.getMessage()); @@ -106,11 +99,6 @@ public class ItemRepositoryImpl extends BaseDynamoDBRepository implemen log.info("ItemDoc Delete Success: {}", CommonUtils.objectByString(beforeDoc)); - dynamodbHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.ITEM_DELETE, - HISTORYTYPEDETAIL.ITEM_DELETE.name(), - beforeDoc - ); } }catch (Exception e){ log.error("Update LandAuctionRegistry Error: {}", e.getMessage()); diff --git a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/LandAuctionActivityRepositoryImpl.java b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/LandAuctionActivityRepositoryImpl.java index ea72816..e936fd4 100644 --- a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/LandAuctionActivityRepositoryImpl.java +++ b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/LandAuctionActivityRepositoryImpl.java @@ -72,12 +72,6 @@ public class LandAuctionActivityRepositoryImpl extends BaseDynamoDBRepository implemen log.info("LandDoc Insert Success: {}", objectMapper.writeValueAsString(doc)); - dynamodbHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_ADD, - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_ADD.name(), - doc - ); - }catch (Exception e){ log.error("insertLand Error: {}", e.getMessage()); throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.DYNAMODB_CONNECTION_ERROR.getMessage()); @@ -120,13 +114,6 @@ public class LandRepositoryImpl extends BaseDynamoDBRepository implemen update(afterDoc); log.info("LandDoc Update Success: {}", objectMapper.writeValueAsString(afterDoc)); - - dynamodbHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_UPDATE, - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_UPDATE.name(), - beforeDoc, - afterDoc - ); } }catch (Exception e){ log.error("updateLand Error: {}", e.getMessage()); @@ -159,13 +146,6 @@ public class LandRepositoryImpl extends BaseDynamoDBRepository implemen log.info("LandDoc Owned Init Update Success: {}", objectMapper.writeValueAsString(afterDoc)); - dynamodbHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.LAND_OWNED_INITIALIZE, - HISTORYTYPEDETAIL.LAND_OWNED_INITIALIZE.name(), - beforeDoc, - afterDoc - ); - return new DynamodbOperationResult(true, "",afterDoc); } return new DynamodbOperationResult(false, "null",null); @@ -200,12 +180,6 @@ public class LandRepositoryImpl extends BaseDynamoDBRepository implemen log.info("LandDoc Desc Init Update Success: {}", objectMapper.writeValueAsString(afterDoc)); - dynamodbHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.LAND_DESC_INITIALIZE, - HISTORYTYPEDETAIL.LAND_DESC_INITIALIZE.name(), - beforeDoc, - afterDoc - ); return new DynamodbOperationResult(true, "Success",afterDoc); } return new DynamodbOperationResult(false, "null",beforeDoc); diff --git a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/MailJsonRepositoryImpl.java b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/MailJsonRepositoryImpl.java index 518ac53..031b8d3 100644 --- a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/MailJsonRepositoryImpl.java +++ b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/MailJsonRepositoryImpl.java @@ -81,12 +81,6 @@ public class MailJsonRepositoryImpl extends BaseDynamoDBRepository log.info("MailDoc Recv Insert Success: {}", objectMapper.writeValueAsString(doc)); - dynamodbHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_MAIL, - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_MAIL.name(), - doc - ); - }catch (Exception e){ log.error("insert Error: {}", e.getMessage()); throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.DYNAMODB_CONNECTION_ERROR.getMessage()); @@ -144,12 +138,6 @@ public class MailJsonRepositoryImpl extends BaseDynamoDBRepository delete(key); log.info("MailJsonDoc Delete Success: {}", objectMapper.writeValueAsString(beforeDoc)); - - dynamodbHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.MAIL_DELETE, - HISTORYTYPEDETAIL.MAIL_DELETE.name(), - beforeDoc - ); } }catch (Exception e){ log.error("Delete Mail Error: {}", e.getMessage()); @@ -189,13 +177,6 @@ public class MailJsonRepositoryImpl extends BaseDynamoDBRepository update(afterDoc); log.info("MailJsonDoc Item Update Success: {}", objectMapper.writeValueAsString(beforeDoc)); - - dynamodbHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.MAIL_ITEM_DELETE, - HISTORYTYPEDETAIL.MAIL_ITEM_DELETE.name(), - beforeDoc, - afterDoc - ); } }catch (Exception e){ log.error("Update Mail Item Error: {}", e.getMessage()); diff --git a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/MailRepositoryImpl.java b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/MailRepositoryImpl.java index c86d8f0..cb301a0 100644 --- a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/MailRepositoryImpl.java +++ b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/MailRepositoryImpl.java @@ -82,12 +82,6 @@ public class MailRepositoryImpl extends BaseDynamoDBRepository implemen log.info("MailDoc Recv Insert Success: {}", objectMapper.writeValueAsString(doc)); - dynamodbHistoryLogService.insertHistoryLog( - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_MAIL, - HISTORYTYPEDETAIL.LAND_OWNER_CHANGE_MAIL.name(), - doc - ); - }catch (Exception e){ log.error("RECV Mail Insert Error: {}", e.getMessage()); throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.DYNAMODB_PROCESS_ERROR.getMessage()); @@ -146,11 +140,6 @@ public class MailRepositoryImpl extends BaseDynamoDBRepository implemen log.info("MailDoc Delete Success: {}", objectMapper.writeValueAsString(beforeDoc)); - dynamodbHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.MAIL_DELETE, - HISTORYTYPEDETAIL.MAIL_DELETE.name(), - beforeDoc - ); } }catch (Exception e){ log.error("Delete Mail Error: {}", e.getMessage()); @@ -191,12 +180,6 @@ public class MailRepositoryImpl extends BaseDynamoDBRepository implemen log.info("MailDoc Item Update Success: {}", objectMapper.writeValueAsString(beforeDoc)); - dynamodbHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.MAIL_ITEM_DELETE, - HISTORYTYPEDETAIL.MAIL_ITEM_DELETE.name(), - beforeDoc, - afterDoc - ); } }catch (Exception e){ log.error("Update Mail Item Error: {}", e.getMessage()); diff --git a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/NicknameRepositoryImpl.java b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/NicknameRepositoryImpl.java index 31be706..35c6985 100644 --- a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/NicknameRepositoryImpl.java +++ b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/NicknameRepositoryImpl.java @@ -1,6 +1,5 @@ package com.caliverse.admin.dynamodb.repository.Impl; -import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; import com.caliverse.admin.dynamodb.domain.atrrib.NicknameAttrib; import com.caliverse.admin.dynamodb.domain.doc.NicknameDoc; import com.caliverse.admin.dynamodb.repository.BaseDynamoDBRepository; @@ -68,12 +67,6 @@ public class NicknameRepositoryImpl extends BaseDynamoDBRepository log.info("NicknameDoc Update Success: {}", objectMapper.writeValueAsString(afterDoc)); - dynamodbHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.NICKNAME_UPDATE, - HISTORYTYPEDETAIL.NICKNAME_UPDATE.name(), - beforeDoc, - afterDoc - ); } }catch (Exception e){ log.error("Update Nickname Error: {}", e.getMessage()); diff --git a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/OwnedBuildingRepositoryImpl.java b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/OwnedBuildingRepositoryImpl.java index ac1b18d..0bde695 100644 --- a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/OwnedBuildingRepositoryImpl.java +++ b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/OwnedBuildingRepositoryImpl.java @@ -1,6 +1,5 @@ package com.caliverse.admin.dynamodb.repository.Impl; -import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; import com.caliverse.admin.dynamodb.domain.atrrib.OwnedBuildingAttrib; import com.caliverse.admin.dynamodb.domain.doc.OwnedBuildingDoc; import com.caliverse.admin.dynamodb.entity.EOwnedType; @@ -71,12 +70,6 @@ public class OwnedBuildingRepositoryImpl extends BaseDynamoDBRepository implem log.info("updateQuest Update Success: {}", CommonUtils.objectByString(afterDoc)); - dynamodbHistoryLogService.updateHistoryLog( - HISTORYTYPEDETAIL.QUEST_UPDATE, - HISTORYTYPEDETAIL.QUEST_UPDATE.name(), - beforeDoc, - afterDoc - ); } }catch (Exception e){ log.error("Update Quest Error: {}", e.getMessage()); @@ -96,11 +89,6 @@ public class QuestRepositoryImpl extends BaseDynamoDBRepository implem log.info("QuestDoc Delete Success: {}", CommonUtils.objectByString(beforeDoc)); - dynamodbHistoryLogService.deleteHistoryLog( - HISTORYTYPEDETAIL.QUEST_DELETE, - HISTORYTYPEDETAIL.QUEST_DELETE.name(), - beforeDoc - ); } }catch (Exception e){ log.error("Update QuestRegistry Error: {}", e.getMessage()); diff --git a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/SystemMetaMailRepositoryImpl.java b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/SystemMetaMailRepositoryImpl.java index d3c45a3..1d12e52 100644 --- a/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/SystemMetaMailRepositoryImpl.java +++ b/src/main/java/com/caliverse/admin/dynamodb/repository/Impl/SystemMetaMailRepositoryImpl.java @@ -1,10 +1,8 @@ package com.caliverse.admin.dynamodb.repository.Impl; import com.caliverse.admin.domain.entity.Event; -import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; import com.caliverse.admin.domain.entity.Message; import com.caliverse.admin.dynamodb.domain.atrrib.SystemMetaMailAttrib; -import com.caliverse.admin.dynamodb.domain.doc.LandAuctionRegistryDoc; import com.caliverse.admin.dynamodb.domain.doc.SystemMetaMailDoc; import com.caliverse.admin.dynamodb.entity.DynamodbOperationResult; import com.caliverse.admin.dynamodb.repository.BaseDynamoDBRepository; @@ -61,12 +59,6 @@ public class SystemMetaMailRepositoryImpl extends BaseDynamoDBRepository mysqlHistoryLogService.insertHistoryLog( + processId, action, LogStatus.SUCCESS, tableName, "", result + ); + case UPDATE -> mysqlHistoryLogService.updateHistoryLog( + processId, action, LogStatus.SUCCESS, tableName, "", beforeData, result + ); + case DELETE -> mysqlHistoryLogService.deleteHistoryLog( + processId, action, LogStatus.SUCCESS, tableName, "", beforeData + ); + } + } + + private String extractTableName(String sqlId) { + // sqlId에서 테이블명 추출 로직 + if (sqlId.contains("Admin")) return MysqlConstants.TABLE_NAME_ADMIN; + if (sqlId.contains("Banner") && sqlId.contains("Menu")) return MysqlConstants.TABLE_NAME_MENU_BANNER; + if (sqlId.contains("BlackList")) return MysqlConstants.TABLE_NAME_USER_BLOCK; + if (sqlId.contains("Calium")) return MysqlConstants.TABLE_NAME_CALIUM_REQUEST; + if (sqlId.contains("Data")) return MysqlConstants.TABLE_NAME_DATA_INIT; + if (sqlId.contains("Event")) return MysqlConstants.TABLE_NAME_EVENT; + if (sqlId.contains("Battle")) return MysqlConstants.TABLE_NAME_BATTLE_EVENT; + if (sqlId.contains("GroupAuth")) return MysqlConstants.TABLE_NAME_GROUP_AUTH; + if (sqlId.contains("Group")) return MysqlConstants.TABLE_NAME_GROUP; + if (sqlId.contains("Mail")) return MysqlConstants.TABLE_NAME_MAIL; + if (sqlId.contains("Notice")) return MysqlConstants.TABLE_NAME_NOTICE; + if (sqlId.contains("LandAuction")) return MysqlConstants.TABLE_NAME_LAND_AUCTION; + if (sqlId.contains("LandOwner")) return MysqlConstants.TABLE_NAME_LAND_OWNER_CHANGE; + + return "unknown"; + } + +} diff --git a/src/main/java/com/caliverse/admin/global/component/manager/BeforeDataResolver.java b/src/main/java/com/caliverse/admin/global/component/manager/BeforeDataResolver.java new file mode 100644 index 0000000..97e3632 --- /dev/null +++ b/src/main/java/com/caliverse/admin/global/component/manager/BeforeDataResolver.java @@ -0,0 +1,381 @@ +package com.caliverse.admin.global.component.manager; + +import com.caliverse.admin.domain.dao.admin.*; +import com.caliverse.admin.domain.dao.total.WalletUserMapper; +import com.caliverse.admin.domain.entity.*; +import com.caliverse.admin.domain.request.*; +import com.caliverse.admin.global.common.utils.CommonUtils; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; + +@Component +@Slf4j +public class BeforeDataResolver { + private final AdminMapper adminMapper; + private final MenuMapper menuMapper; + private final LandMapper landMapper; + private final BattleMapper battleMapper; + private final BlackListMapper blackListMapper; + private final CaliumMapper caliumMapper; + private final EventMapper eventMapper; + private final GroupMapper groupMapper; + private final MailMapper mailMapper; + private final NoticeMapper noticeMapper; + private final DataMapper dataMapper; + + public BeforeDataResolver(@Lazy AdminMapper adminMapper, + @Lazy MenuMapper menuMapper, + @Lazy LandMapper landMapper, + @Lazy BattleMapper battleMapper, + @Lazy BlackListMapper blackListMapper, + @Lazy CaliumMapper caliumMapper, + @Lazy EventMapper eventMapper, + @Lazy GroupMapper groupMapper, + @Lazy MailMapper mailMapper, + @Lazy NoticeMapper noticeMapper, + @Lazy DataMapper dataMapper + ) { + this.adminMapper = adminMapper; + this.menuMapper = menuMapper; + this.landMapper = landMapper; + this.battleMapper = battleMapper; + this.blackListMapper = blackListMapper; + this.caliumMapper = caliumMapper; + this.eventMapper = eventMapper; + this.groupMapper = groupMapper; + this.mailMapper = mailMapper; + this.noticeMapper = noticeMapper; + this.dataMapper = dataMapper; + } + + private static final Map>> RESOLVER_MAP = Map.ofEntries( + Map.entry("AdminMapper", resolver -> resolver::resolveAdminBeforeData), + Map.entry("MenuMapper", resolver -> resolver::resolveBannerBeforeData), + Map.entry("BattleMapper", resolver -> resolver::resolveBattleBeforeData), + Map.entry("BlackListMapper", resolver -> resolver::resolveBlackListBeforeData), + Map.entry("CaliumMapper", resolver -> resolver::resolveCaliumBeforeData), + Map.entry("EventMapper", resolver -> resolver::resolveEventBeforeData), + Map.entry("MailMapper", resolver -> resolver::resolveMailBeforeData), + Map.entry("NoticeMapper", resolver -> resolver::resolveNoticeBeforeData), + Map.entry("LandMapper", resolver -> resolver::resolveLandBeforeData), + Map.entry("DataMapper", resolver -> resolver::resolveDataBeforeData), + Map.entry("GroupMapper", resolver -> resolver::resolveGroupBeforeData) + ); + + public Object resolveBeforeData(String sqlId, Object parameter) { + try { + return RESOLVER_MAP.entrySet().stream() + .filter(entry -> sqlId.contains(entry.getKey())) + .findFirst() + .map(entry -> entry.getValue().apply(this).apply(sqlId, parameter)) + .orElse(null); + + } catch (Exception e) { + log.warn("Failed to resolve before data for {}: {}", sqlId, e.getMessage()); + return null; + } + } + + private Object resolveGroupBeforeData(String sqlId, Object parameter) { + if(sqlId.contains("postGroup") || sqlId.contains("deleteGroup")){ + if (parameter instanceof Map) { + Map params = (Map) parameter; + + if (params.containsKey("groupId")) { + return groupMapper.getGroupInfo(Long.parseLong((String) params.get("groupId"))); + } + } + + if (parameter instanceof GroupRequest params) { + return groupMapper.getGroupInfo(params.getId()); + } + + if(parameter instanceof Long id){ + return groupMapper.getGroupInfo(id); + } + } + + if (parameter instanceof Map) { + Map params = (Map) parameter; + + if (params.containsKey("groupId")) { + return groupMapper.getGroupAuth(Long.parseLong((String) params.get("groupId"))); + } + } + + if (parameter instanceof GroupRequest params) { + return groupMapper.getGroupAuth(params.getId()); + } + + if(parameter instanceof Long id){ + return groupMapper.getGroupAuth(id); + } + + if(parameter instanceof String id){ + return groupMapper.getGroupAuth(Long.parseLong(id)); + } + + return null; + } + + private Object resolveDataBeforeData(String sqlId, Object parameter) { + if (parameter instanceof Map) { + Map params = (Map) parameter; + + if (params.containsKey("id")) { + return dataMapper.getDataInitDetail((Long) params.get("id")); + } + } + + if (parameter instanceof DataRequest params) { + return dataMapper.getDataInitDetail(params.getId()); + } + + if(parameter instanceof Long id){ + return dataMapper.getDataInitDetail(id); + } + + return null; + } + + private Object resolveLandBeforeData(String sqlId, Object parameter) { + if (parameter instanceof Map) { + Map params = (Map) parameter; + + if (params.containsKey("id")) { + if(sqlId.contains("LandOwnerChange")){ + return landMapper.getLandOwnerChangeDetail((Long) params.get("id")); + } + return landMapper.getLandAuctionDetail((Long) params.get("id")); + } + } + + if (parameter instanceof LandRequest params) { + if(sqlId.contains("LandOwnerChange")){ + return landMapper.getLandOwnerChangeDetail(params.getId()); + } + return landMapper.getLandAuctionDetail(params.getId()); + } + + if(parameter instanceof Long id){ + if(sqlId.contains("LandOwnerChange")){ + return landMapper.getLandOwnerChangeDetail(id); + } + return landMapper.getLandAuctionDetail(id); + } + + return null; + } + + private Object resolveAdminBeforeData(String sqlId, Object parameter) { + + if(sqlId.contains("initPwd") || sqlId.contains("updatePwd")) { + if (parameter instanceof AuthenticateRequest params) { + String email = params.getEmail() == null ? CommonUtils.getAdmin().getEmail() : params.getEmail(); + return adminMapper.findByEmail(email).get(); + } + if (parameter instanceof Map) { + Map params = (Map) parameter; + + if (params.containsKey("id")) { + return adminMapper.findById((Long) params.get("id")).get(); + } + Long id = CommonUtils.getAdmin().getId(); + if (id != null) { + return adminMapper.findById(id).get(); + } + } + } + + if(sqlId.contains("updateStatus") || sqlId.contains("updateGroup") || sqlId.contains("deleteAdmin")) { + if (parameter instanceof AdminRequest params) { + String email = params.getList().get(0).getEmail() == null ? CommonUtils.getAdmin().getEmail() : params.getList().get(0).getEmail(); + return adminMapper.findByEmail(email).get(); + } + if (parameter instanceof Map) { + Map params = (Map) parameter; + + if (params.containsKey("email")) { + return adminMapper.findByEmail((String) params.get("email")).get(); + } + } + } + + if(sqlId.contains("save")){ + if(parameter instanceof Admin params){ + return adminMapper.findByEmail(params.getEmail()).get(); + } + } + + return null; + } + + private Object resolveBannerBeforeData(String sqlId, Object parameter) { + if (sqlId.contains("insertBanner")) { + return null; + } + + if (parameter instanceof Map) { + Map params = (Map) parameter; + + if (params.containsKey("id")) { + MenuBanner info = menuMapper.getBannerDetail((Long) params.get("id")); + if(info != null){ + info.setImageList(menuMapper.getMessage((Long) params.get("id"))); + } + return info; + } + } + + if (parameter instanceof MenuRequest params) { + MenuBanner info =menuMapper.getBannerDetail(params.getId()); + if(info != null) { + info.setImageList(menuMapper.getMessage(params.getId())); + } + return info; + } + + return null; + } + + private Object resolveBattleBeforeData(String sqlId, Object parameter) { + if (parameter instanceof Map) { + Map params = (Map) parameter; + + if (params.containsKey("id")) { + return battleMapper.getBattleEventDetail((Long) params.get("id")); + } + } + + if (parameter instanceof BattleEventRequest params) { + return battleMapper.getBattleEventDetail(params.getId()); + } + + return null; + } + + private Object resolveBlackListBeforeData(String sqlId, Object parameter) { + if (parameter instanceof Map) { + Map params = (Map) parameter; + + if (params.containsKey("id")) { + return blackListMapper.getBlackListDetail((Long) params.get("id")); + } + } + + if (parameter instanceof BlackListRequest params) { + return blackListMapper.getBlackListDetail(params.getId()); + } + + return null; + } + + private Object resolveCaliumBeforeData(String sqlId, Object parameter) { + if (parameter instanceof Map) { + Map params = (Map) parameter; + + if (params.containsKey("id")) { + return caliumMapper.getCaliumRequestDetail((Long) params.get("id")); + } + } + + if (parameter instanceof CaliumRequest params) { + return caliumMapper.getCaliumRequestDetail(params.getId()); + } + + return null; + } + + private Object resolveEventBeforeData(String sqlId, Object parameter) { + if (sqlId.contains("postEvent") || sqlId.contains("updateEvent")) { + return null; + } + + if (parameter instanceof Map) { + Map params = (Map) parameter; + + if (params.containsKey("id")) { + Long id = (Long) params.get("id"); + Event event = eventMapper.getEventDetail(id); + event.setMailList(eventMapper.getMessage(id)); + event.setItemList(eventMapper.getItem(id)); + return event; + } + } + + if (parameter instanceof EventRequest params) { + Long id = params.getId(); + Event event = eventMapper.getEventDetail(id); + event.setMailList(eventMapper.getMessage(id)); + event.setItemList(eventMapper.getItem(id)); + return event; + } + + return null; + } + + private Object resolveMailBeforeData(String sqlId, Object parameter) { + if (sqlId.contains("postMail") || sqlId.contains("updateMail")) { + return null; + } + + if (parameter instanceof Map) { + Map params = (Map) parameter; + + if (params.containsKey("id")) { + Long id = (Long) params.get("id"); + Mail mail = mailMapper.getMailDetail(id); + mail.setMailList(mailMapper.getMessage(id)); + mail.setItemList(mailMapper.getItem(id)); + return mail; + } + } + + if (parameter instanceof MailRequest params) { + Long id = params.getId(); + Mail mail = mailMapper.getMailDetail(id); + mail.setMailList(mailMapper.getMessage(id)); + mail.setItemList(mailMapper.getItem(id)); + return mail; + } + + return null; + } + + private Object resolveNoticeBeforeData(String sqlId, Object parameter) { + if (sqlId.contains("postNotice") || sqlId.contains("updateNotice")) { + return null; + } + + if (parameter instanceof Map) { + Map params = (Map) parameter; + + if (params.containsKey("id")) { + Long id = (Long) params.get("id"); + InGame notice = noticeMapper.getNoticeDetail(id); + notice.setMessageList(noticeMapper.getMessage(id)); + return notice; + } + } + + if (parameter instanceof NoticeRequest params) { + Long id = params.getId(); + InGame notice = noticeMapper.getNoticeDetail(id); + notice.setMessageList(noticeMapper.getMessage(id)); + return notice; + } + + if(parameter instanceof Long id){ + InGame notice = noticeMapper.getNoticeDetail(id); + notice.setMessageList(noticeMapper.getMessage(id)); + return notice; + } + + return null; + } +} diff --git a/src/main/java/com/caliverse/admin/global/component/manager/BusinessProcessIdManager.java b/src/main/java/com/caliverse/admin/global/component/manager/BusinessProcessIdManager.java new file mode 100644 index 0000000..916df31 --- /dev/null +++ b/src/main/java/com/caliverse/admin/global/component/manager/BusinessProcessIdManager.java @@ -0,0 +1,38 @@ +package com.caliverse.admin.global.component.manager; + +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.global.common.utils.CommonUtils; +import org.springframework.stereotype.Component; + +@Component +public class BusinessProcessIdManager { + private static final ThreadLocal processId = new ThreadLocal<>(); + private static final ThreadLocal businessAction = new ThreadLocal<>(); + + public String getCurrentProcessId() { + return processId.get(); + } + + public LogAction getCurrentAction() { + return businessAction.get(); + } + + public String createNewProcessId() { + String newId = CommonUtils.getCreateGuId(); + processId.set(newId); + return newId; + } + + public void setCurrentAction(LogAction action) { + businessAction.set(action); + } + + public void clear() { + processId.remove(); + businessAction.remove(); + } + + public boolean hasProcessId() { + return processId.get() != null; + } +} diff --git a/src/main/java/com/caliverse/admin/global/component/transaction/DynamoDBTransactionContext.java b/src/main/java/com/caliverse/admin/global/component/manager/DynamoDBTransactionContext.java similarity index 92% rename from src/main/java/com/caliverse/admin/global/component/transaction/DynamoDBTransactionContext.java rename to src/main/java/com/caliverse/admin/global/component/manager/DynamoDBTransactionContext.java index 60b9154..01093d9 100644 --- a/src/main/java/com/caliverse/admin/global/component/transaction/DynamoDBTransactionContext.java +++ b/src/main/java/com/caliverse/admin/global/component/manager/DynamoDBTransactionContext.java @@ -1,4 +1,4 @@ -package com.caliverse.admin.global.component.transaction; +package com.caliverse.admin.global.component.manager; import software.amazon.awssdk.enhanced.dynamodb.model.TransactWriteItemsEnhancedRequest; diff --git a/src/main/java/com/caliverse/admin/global/component/transaction/TransactionIdManager.java b/src/main/java/com/caliverse/admin/global/component/manager/TransactionIdManager.java similarity index 94% rename from src/main/java/com/caliverse/admin/global/component/transaction/TransactionIdManager.java rename to src/main/java/com/caliverse/admin/global/component/manager/TransactionIdManager.java index b676643..9c3557a 100644 --- a/src/main/java/com/caliverse/admin/global/component/transaction/TransactionIdManager.java +++ b/src/main/java/com/caliverse/admin/global/component/manager/TransactionIdManager.java @@ -1,4 +1,4 @@ -package com.caliverse.admin.global.component.transaction; +package com.caliverse.admin.global.component.manager; import com.caliverse.admin.global.common.utils.CommonUtils; import org.springframework.stereotype.Component; diff --git a/src/main/java/com/caliverse/admin/global/configuration/BatchConfiguration.java b/src/main/java/com/caliverse/admin/global/configuration/BatchConfiguration.java deleted file mode 100644 index b5d31a5..0000000 --- a/src/main/java/com/caliverse/admin/global/configuration/BatchConfiguration.java +++ /dev/null @@ -1,163 +0,0 @@ -package com.caliverse.admin.global.configuration; - -import com.caliverse.admin.domain.batch.CustomProcessor; -import com.caliverse.admin.domain.batch.CustomReader; -import com.caliverse.admin.domain.batch.CustomWriter; -import org.springframework.batch.core.Job; -import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.support.DefaultBatchConfiguration; -import org.springframework.batch.core.job.builder.JobBuilder; -import org.springframework.batch.core.repository.JobRepository; -import org.springframework.batch.core.step.builder.StepBuilder; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.transaction.PlatformTransactionManager; - -import javax.sql.DataSource; - -@Configuration -public class BatchConfiguration { -//public class BatchConfiguration extends DefaultBatchConfiguration { - -// @Autowired -// @Qualifier("dataSource") -// private DataSource dataSource; -// -// @Autowired -// @Qualifier("batchTransactionManager") -// private PlatformTransactionManager transactionManger; -// -// @Override -// public DataSource getDataSource() { -// return dataSource; -// } -// -// @Override -// public PlatformTransactionManager getTransactionManager() { -// return transactionManger; -// -// } -// -// -// @Bean -// public Job createJob(JobRepository jobRepository, PlatformTransactionManager transactionManager) { -// return new JobBuilder("testJob", jobRepository) -// .flow(createStep(jobRepository, transactionManager)).end().build(); -// } -// -// @Bean -// Step createStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) { -// return new StepBuilder("testStep", jobRepository) -// . chunk(3, transactionManager) -// .allowStartIfComplete(true) -// .reader(new CustomReader()) -// .processor(new CustomProcessor()) -// .writer(new CustomWriter()) -// .build(); -// } - - - // @Bean - // public org.springframework.batch.core.Job testJob(JobRepository jobRepository,PlatformTransactionManager transactionManager) throws DuplicateJobException { - // org.springframework.batch.core.Job job = new JobBuilder("testJob",jobRepository) - // .start(testStep(jobRepository,transactionManager)) - // .build(); - // return job; - // } - - // public Step testStep(JobRepository jobRepository,PlatformTransactionManager transactionManager){ - // Step step = new StepBuilder("testStep",jobRepository) - // .tasklet(testTasklet(),transactionManager) - // .build(); - // return step; - // } - - // public Tasklet testTasklet(){ - // return ((contribution, chunkContext) -> { - // System.out.println("***** hello batch! *****"); - // // 원하는 비지니스 로직 작성 - // return RepeatStatus.FINISHED; - // }); - // } - - - // @Bean - // public JobRepository jobRepository() { - // JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); - // factory.setDataSource(dataSource); - // factory.setTransactionManager(transactionManager); - // try { - // return factory.getObject(); - // } catch (Exception e) { - // // TODO Auto-generated catch block - // e.printStackTrace(); - // } - // return null; - // } - - // @Bean - // public JobLauncher jobLauncher() { - // TaskExecutorJobLauncher jobLauncher = new TaskExecutorJobLauncher(); - // jobLauncher.setJobRepository(jobRepository()); - // jobLauncher.setTaskExecutor(new SyncTaskExecutor()); // Optional: You can use a different TaskExecutor - // return jobLauncher; - // } - - // @Bean - // public JobLauncher jobLauncher() { - // JobLauncherFactoryBean factory = new JobLauncherFactoryBean(); - // factory.setJobRepository(jobRepository()); - // return factory.getObject(); - // } - - // tag::readerwriterprocessor[] - // @Bean - // public FlatFileItemReader reader() { - // return new FlatFileItemReaderBuilder() - // .name("personItemReader") - // .resource(new ClassPathResource("sample-data.csv")) - // .delimited() - // .names("firstName", "lastName") - // .targetType(Person.class) - // .build(); - // } - - // @Bean - // public PersonItemProcessor processor() { - // return new PersonItemProcessor(); - // } - - // @Bean - // public JdbcBatchItemWriter writer(DataSource dataSource) { - // return new JdbcBatchItemWriterBuilder() - // .sql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)") - // .dataSource(dataSource) - // .beanMapped() - // .build(); - // } - // // end::readerwriterprocessor[] - - // // tag::jobstep[] - // @Bean - // public Job importUserJob(JobRepository jobRepository,Step step1, JobCompletionNotificationListener listener) { - // return new JobBuilder("importUserJob", jobRepository) - // .listener(listener) - // .start(step1) - // .build(); - // } - - // @Bean - // public Step step1(JobRepository jobRepository, DataSourceTransactionManager transactionManager, - // FlatFileItemReader reader, PersonItemProcessor processor, JdbcBatchItemWriter writer) { - // return new StepBuilder("step1", jobRepository) - // . chunk(3, transactionManager) - // .reader(reader) - // .processor(processor) - // .writer(writer) - // .build(); - - // end::jobstep[] - -} \ No newline at end of file diff --git a/src/main/java/com/caliverse/admin/global/configuration/MybatisConfig.java b/src/main/java/com/caliverse/admin/global/configuration/MybatisConfig.java index 637032d..1c5f268 100644 --- a/src/main/java/com/caliverse/admin/global/configuration/MybatisConfig.java +++ b/src/main/java/com/caliverse/admin/global/configuration/MybatisConfig.java @@ -1,9 +1,12 @@ package com.caliverse.admin.global.configuration; +import com.caliverse.admin.global.component.MysqlLoggingInterceptor; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; +import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -32,10 +35,18 @@ public class MybatisConfig { @Bean(name = "SqlSessionFactory") - public SqlSessionFactory SqlSessionFactory(@Qualifier("dataSource") DataSource DataSource, ApplicationContext applicationContext) throws Exception { + public SqlSessionFactory SqlSessionFactory( + @Qualifier("dataSource") DataSource DataSource, + ApplicationContext applicationContext, + @Autowired(required = false)MysqlLoggingInterceptor interceptor + ) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(DataSource); sqlSessionFactoryBean.setMapperLocations(applicationContext.getResources(mPath)); + + if (interceptor != null) { + sqlSessionFactoryBean.setPlugins(interceptor); + } return sqlSessionFactoryBean.getObject(); } diff --git a/src/main/java/com/caliverse/admin/global/configuration/TestBatchConfiguration.java b/src/main/java/com/caliverse/admin/global/configuration/TestBatchConfiguration.java deleted file mode 100644 index 5dc8611..0000000 --- a/src/main/java/com/caliverse/admin/global/configuration/TestBatchConfiguration.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.caliverse.admin.global.configuration; - -import javax.sql.DataSource; - -import org.springframework.batch.core.Job; -import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.support.DefaultBatchConfiguration; -import org.springframework.batch.core.job.builder.JobBuilder; -import org.springframework.batch.core.repository.JobRepository; -import org.springframework.batch.core.step.builder.StepBuilder; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.transaction.PlatformTransactionManager; -import com.caliverse.admin.domain.batch.CustomProcessor; -import com.caliverse.admin.domain.batch.CustomReader; -import com.caliverse.admin.domain.batch.CustomWriter; - -@Configuration -//public class TestBatchConfiguration extends DefaultBatchConfiguration { -public class TestBatchConfiguration { -// @Autowired -// @Qualifier("dataSource-normal") -// private DataSource dataSource; -// -// @Autowired -// @Qualifier("batchTransactionManager") -// private PlatformTransactionManager transactionManger; -// -// @Override -// public DataSource getDataSource() { -// return dataSource; -// } -// -// @Override -// public PlatformTransactionManager getTransactionManager() { -// return transactionManger; -// -// } -// -// -// @Bean -// public Job createJob(JobRepository jobRepository, PlatformTransactionManager transactionManager) { -// return new JobBuilder("testJob", jobRepository) -// .flow(createStep(jobRepository, transactionManager)).end().build(); -// } -// -// @Bean -// Step createStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) { -// return new StepBuilder("testStep", jobRepository) -// . chunk(3, transactionManager) -// .allowStartIfComplete(true) -// .reader(new CustomReader()) -// .processor(new CustomProcessor()) -// .writer(new CustomWriter()) -// .build(); -// } - - - // @Bean - // public org.springframework.batch.core.Job testJob(JobRepository jobRepository,PlatformTransactionManager transactionManager) throws DuplicateJobException { - // org.springframework.batch.core.Job job = new JobBuilder("testJob",jobRepository) - // .start(testStep(jobRepository,transactionManager)) - // .build(); - // return job; - // } - - // public Step testStep(JobRepository jobRepository,PlatformTransactionManager transactionManager){ - // Step step = new StepBuilder("testStep",jobRepository) - // .tasklet(testTasklet(),transactionManager) - // .build(); - // return step; - // } - - // public Tasklet testTasklet(){ - // return ((contribution, chunkContext) -> { - // System.out.println("***** hello batch! *****"); - // // 원하는 비지니스 로직 작성 - // return RepeatStatus.FINISHED; - // }); - // } - - - // @Bean - // public JobRepository jobRepository() { - // JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); - // factory.setDataSource(dataSource); - // factory.setTransactionManager(transactionManager); - // try { - // return factory.getObject(); - // } catch (Exception e) { - // // TODO Auto-generated catch block - // e.printStackTrace(); - // } - // return null; - // } - - // @Bean - // public JobLauncher jobLauncher() { - // TaskExecutorJobLauncher jobLauncher = new TaskExecutorJobLauncher(); - // jobLauncher.setJobRepository(jobRepository()); - // jobLauncher.setTaskExecutor(new SyncTaskExecutor()); // Optional: You can use a different TaskExecutor - // return jobLauncher; - // } - - // @Bean - // public JobLauncher jobLauncher() { - // JobLauncherFactoryBean factory = new JobLauncherFactoryBean(); - // factory.setJobRepository(jobRepository()); - // return factory.getObject(); - // } - - // tag::readerwriterprocessor[] - // @Bean - // public FlatFileItemReader reader() { - // return new FlatFileItemReaderBuilder() - // .name("personItemReader") - // .resource(new ClassPathResource("sample-data.csv")) - // .delimited() - // .names("firstName", "lastName") - // .targetType(Person.class) - // .build(); - // } - - // @Bean - // public PersonItemProcessor processor() { - // return new PersonItemProcessor(); - // } - - // @Bean - // public JdbcBatchItemWriter writer(DataSource dataSource) { - // return new JdbcBatchItemWriterBuilder() - // .sql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)") - // .dataSource(dataSource) - // .beanMapped() - // .build(); - // } - // // end::readerwriterprocessor[] - - // // tag::jobstep[] - // @Bean - // public Job importUserJob(JobRepository jobRepository,Step step1, JobCompletionNotificationListener listener) { - // return new JobBuilder("importUserJob", jobRepository) - // .listener(listener) - // .start(step1) - // .build(); - // } - - // @Bean - // public Step step1(JobRepository jobRepository, DataSourceTransactionManager transactionManager, - // FlatFileItemReader reader, PersonItemProcessor processor, JdbcBatchItemWriter writer) { - // return new StepBuilder("step1", jobRepository) - // . chunk(3, transactionManager) - // .reader(reader) - // .processor(processor) - // .writer(writer) - // .build(); - - // end::jobstep[] - -} \ No newline at end of file diff --git a/src/main/java/com/caliverse/admin/mongodb/ChangeDetector.java b/src/main/java/com/caliverse/admin/mongodb/ChangeDetector.java index 1998e53..6657f50 100644 --- a/src/main/java/com/caliverse/admin/mongodb/ChangeDetector.java +++ b/src/main/java/com/caliverse/admin/mongodb/ChangeDetector.java @@ -1,6 +1,6 @@ package com.caliverse.admin.mongodb; -import com.caliverse.admin.domain.adminlog.FieldChange; +import com.caliverse.admin.domain.entity.FieldChange; import com.caliverse.admin.dynamodb.domain.DocAttributeHandler; import com.caliverse.admin.dynamodb.domain.doc.DynamoDBDocBase; import com.fasterxml.jackson.core.JsonProcessingException; diff --git a/src/main/java/com/caliverse/admin/mongodb/domain/BatchJobDomain.java b/src/main/java/com/caliverse/admin/mongodb/domain/BatchJobDomain.java new file mode 100644 index 0000000..3d60411 --- /dev/null +++ b/src/main/java/com/caliverse/admin/mongodb/domain/BatchJobDomain.java @@ -0,0 +1,19 @@ +package com.caliverse.admin.mongodb.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class BatchJobDomain { + private String jobName; + private Long duration; + private Object info; + private String query; +} diff --git a/src/main/java/com/caliverse/admin/mongodb/domain/BusinessLog.java b/src/main/java/com/caliverse/admin/mongodb/domain/BusinessLog.java new file mode 100644 index 0000000..121fbae --- /dev/null +++ b/src/main/java/com/caliverse/admin/mongodb/domain/BusinessLog.java @@ -0,0 +1,53 @@ +package com.caliverse.admin.mongodb.domain; + +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogCategory; +import com.caliverse.admin.domain.entity.log.LogStatus; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.Document; + +import java.time.LocalDateTime; + +@Document(collection = "businessLog") +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class BusinessLog { + @Id + private String id; + + @Indexed + private LocalDateTime logTime; + + @Indexed + private LogCategory category; + + @Indexed + private LogAction action; + + @Indexed + private LogStatus status; + + private String worker; + private String workerIp; + + private String message; + + private String procId; + + private Object domain; + + @CompoundIndex(def = "{'category': 1, 'action': 1, 'logTime': -1}") + @CompoundIndex(def = "{'status': 1, 'logTime': -1}") + @CompoundIndex(def = "{'procId': 1, 'logTime': -1}") + @CompoundIndex(def = "{'category': 1, 'logTime': -1}") + @CompoundIndex(def = "{'action': 1, 'logTime': -1}") + public static class Indexes {} +} diff --git a/src/main/java/com/caliverse/admin/mongodb/domain/DataInitDomain.java b/src/main/java/com/caliverse/admin/mongodb/domain/DataInitDomain.java new file mode 100644 index 0000000..39bda74 --- /dev/null +++ b/src/main/java/com/caliverse/admin/mongodb/domain/DataInitDomain.java @@ -0,0 +1,17 @@ +package com.caliverse.admin.mongodb.domain; + +import com.caliverse.admin.domain.entity.EInitDataType; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class DataInitDomain { + private EInitDataType initDataType; + private Object key; + private Object data; +} diff --git a/src/main/java/com/caliverse/admin/mongodb/domain/DynamodbDomain.java b/src/main/java/com/caliverse/admin/mongodb/domain/DynamodbDomain.java new file mode 100644 index 0000000..a5b0577 --- /dev/null +++ b/src/main/java/com/caliverse/admin/mongodb/domain/DynamodbDomain.java @@ -0,0 +1,23 @@ +package com.caliverse.admin.mongodb.domain; + +import com.caliverse.admin.domain.entity.FieldChange; +import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; +import com.caliverse.admin.dynamodb.domain.doc.DynamoDBDocBase; +import com.caliverse.admin.mongodb.entity.EDBOperationType; +import lombok.*; + +import java.util.List; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class DynamodbDomain { + + private EDBOperationType operationType; + private HISTORYTYPEDETAIL historyType; + private DynamoDBDocBase data; + private List changed; + private String tableName; + private String tranId; +} diff --git a/src/main/java/com/caliverse/admin/mongodb/domain/DynamodbHistoryLogInfo.java b/src/main/java/com/caliverse/admin/mongodb/domain/DynamodbHistoryLogInfo.java index 11f2034..3087398 100644 --- a/src/main/java/com/caliverse/admin/mongodb/domain/DynamodbHistoryLogInfo.java +++ b/src/main/java/com/caliverse/admin/mongodb/domain/DynamodbHistoryLogInfo.java @@ -1,6 +1,6 @@ package com.caliverse.admin.mongodb.domain; -import com.caliverse.admin.domain.adminlog.FieldChange; +import com.caliverse.admin.domain.entity.FieldChange; import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; import com.caliverse.admin.dynamodb.domain.doc.DynamoDBDocBase; import com.caliverse.admin.global.common.utils.DateUtils; diff --git a/src/main/java/com/caliverse/admin/mongodb/domain/HistoryLogInfoBase.java b/src/main/java/com/caliverse/admin/mongodb/domain/HistoryLogInfoBase.java index 8a7f70b..b88a78d 100644 --- a/src/main/java/com/caliverse/admin/mongodb/domain/HistoryLogInfoBase.java +++ b/src/main/java/com/caliverse/admin/mongodb/domain/HistoryLogInfoBase.java @@ -1,6 +1,6 @@ package com.caliverse.admin.mongodb.domain; -import com.caliverse.admin.domain.adminlog.FieldChange; +import com.caliverse.admin.domain.entity.FieldChange; import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; import com.caliverse.admin.mongodb.entity.DBType; import com.caliverse.admin.mongodb.entity.EDBOperationType; diff --git a/src/main/java/com/caliverse/admin/mongodb/domain/MariadbDomain.java b/src/main/java/com/caliverse/admin/mongodb/domain/MariadbDomain.java new file mode 100644 index 0000000..269d196 --- /dev/null +++ b/src/main/java/com/caliverse/admin/mongodb/domain/MariadbDomain.java @@ -0,0 +1,20 @@ +package com.caliverse.admin.mongodb.domain; + +import com.caliverse.admin.domain.entity.FieldChange; +import com.caliverse.admin.mongodb.entity.EDBOperationType; +import lombok.*; + +import java.util.List; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class MariadbDomain { + + private Object data; + private EDBOperationType operationType; + private List changed; + private String tableName; + private String tranId; +} diff --git a/src/main/java/com/caliverse/admin/mongodb/domain/MessageQueueDomain.java b/src/main/java/com/caliverse/admin/mongodb/domain/MessageQueueDomain.java new file mode 100644 index 0000000..d7873b3 --- /dev/null +++ b/src/main/java/com/caliverse/admin/mongodb/domain/MessageQueueDomain.java @@ -0,0 +1,16 @@ +package com.caliverse.admin.mongodb.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class MessageQueueDomain { + private String queueName; + private String targetServer; + private Object messageContent; +} diff --git a/src/main/java/com/caliverse/admin/mongodb/domain/MysqlHistoryLogInfo.java b/src/main/java/com/caliverse/admin/mongodb/domain/MysqlHistoryLogInfo.java index 9ee7c76..86a1bfe 100644 --- a/src/main/java/com/caliverse/admin/mongodb/domain/MysqlHistoryLogInfo.java +++ b/src/main/java/com/caliverse/admin/mongodb/domain/MysqlHistoryLogInfo.java @@ -1,6 +1,6 @@ package com.caliverse.admin.mongodb.domain; -import com.caliverse.admin.domain.adminlog.FieldChange; +import com.caliverse.admin.domain.entity.FieldChange; import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; import com.caliverse.admin.global.common.utils.DateUtils; import com.caliverse.admin.mongodb.entity.DBType; diff --git a/src/main/java/com/caliverse/admin/mongodb/domain/RedisDomain.java b/src/main/java/com/caliverse/admin/mongodb/domain/RedisDomain.java new file mode 100644 index 0000000..df3c492 --- /dev/null +++ b/src/main/java/com/caliverse/admin/mongodb/domain/RedisDomain.java @@ -0,0 +1,15 @@ +package com.caliverse.admin.mongodb.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class RedisDomain { + private String key; + private Object value; +} diff --git a/src/main/java/com/caliverse/admin/mongodb/domain/S3Domain.java b/src/main/java/com/caliverse/admin/mongodb/domain/S3Domain.java new file mode 100644 index 0000000..faceec4 --- /dev/null +++ b/src/main/java/com/caliverse/admin/mongodb/domain/S3Domain.java @@ -0,0 +1,17 @@ +package com.caliverse.admin.mongodb.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class S3Domain { + private String bucket; + private String key; + private Long fileSize; + private String contentType; +} diff --git a/src/main/java/com/caliverse/admin/mongodb/domain/SchedulerDomain.java b/src/main/java/com/caliverse/admin/mongodb/domain/SchedulerDomain.java new file mode 100644 index 0000000..a1ab423 --- /dev/null +++ b/src/main/java/com/caliverse/admin/mongodb/domain/SchedulerDomain.java @@ -0,0 +1,19 @@ +package com.caliverse.admin.mongodb.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class SchedulerDomain { + private String schedulerName; + private LocalDateTime startTime; + private LocalDateTime endTime; + private Object info; +} diff --git a/src/main/java/com/caliverse/admin/mongodb/repository/BusinessLogRepository.java b/src/main/java/com/caliverse/admin/mongodb/repository/BusinessLogRepository.java new file mode 100644 index 0000000..0b73bbe --- /dev/null +++ b/src/main/java/com/caliverse/admin/mongodb/repository/BusinessLogRepository.java @@ -0,0 +1,36 @@ +package com.caliverse.admin.mongodb.repository; + +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogCategory; +import com.caliverse.admin.domain.entity.log.LogStatus; +import com.caliverse.admin.mongodb.domain.BusinessLog; +import org.springframework.data.mongodb.repository.Aggregation; +import org.springframework.data.mongodb.repository.MongoRepository; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +public interface BusinessLogRepository extends MongoRepository { + List findByCategoryAndLogTimeBetween( + LogCategory category, LocalDateTime logTime, LocalDateTime logTime2); + + List findByActionAndLogTimeBetween( + LogAction action, LocalDateTime logTime, LocalDateTime logTime2); + + List findByStatusAndLogTimeBetween( + LogStatus status, LocalDateTime logTime, LocalDateTime logTime2); + + List findByProcIdOrderByLogTimeAsc(String tranId); + + List findByCategoryAndActionAndLogTimeBetween( + LogCategory category, LogAction action, LocalDateTime logTime, LocalDateTime logTime2); + + // 집계 쿼리 + @Aggregation(pipeline = { + "{ $match: { 'LogTime': { $gte: ?0, $lte: ?1 } } }", + "{ $group: { _id: { category: '$category', action: '$action' }, count: { $sum: 1 } } }", + "{ $sort: { count: -1 } }" + }) + List> getCategoryActionStats(LocalDateTime start, LocalDateTime end); +} diff --git a/src/main/java/com/caliverse/admin/mongodb/service/BusinessLogService.java b/src/main/java/com/caliverse/admin/mongodb/service/BusinessLogService.java new file mode 100644 index 0000000..a032240 --- /dev/null +++ b/src/main/java/com/caliverse/admin/mongodb/service/BusinessLogService.java @@ -0,0 +1,235 @@ +package com.caliverse.admin.mongodb.service; + +import com.caliverse.admin.domain.entity.FieldChange; +import com.caliverse.admin.domain.entity.EInitDataType; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogCategory; +import com.caliverse.admin.domain.entity.log.LogStatus; +import com.caliverse.admin.dynamodb.domain.doc.DynamoDBDocBase; +import com.caliverse.admin.global.common.constants.CommonConstants; +import com.caliverse.admin.global.component.manager.BusinessProcessIdManager; +import com.caliverse.admin.mongodb.domain.*; +import com.caliverse.admin.mongodb.entity.EDBOperationType; +import com.caliverse.admin.mongodb.repository.BusinessLogRepository; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +@AllArgsConstructor +@Slf4j +@Service +public class BusinessLogService { + private final BusinessLogRepository businessLogRepository; + private final BusinessProcessIdManager processIdManager; + + @Async + public CompletableFuture saveLog(LogCategory category, LogStatus status, + String message, Object domain, String worker, String workerIp, String processId, LogAction action) { + try { + BusinessLog businessLog = BusinessLog.builder() + .logTime(LocalDateTime.now()) + .category(category) + .action(action) + .procId(processId) + .status(status) + .worker(worker == null || worker.isEmpty() ? CommonConstants.SYSTEM : worker) + .workerIp(workerIp == null || workerIp.isEmpty() ? "" : workerIp) + .message(message) + .domain(domain) + .build(); + + BusinessLog saved = businessLogRepository.save(businessLog); + log.debug("Business log saved: {}", saved.getId()); + return CompletableFuture.completedFuture(saved.getId()); + } catch (Exception e) { + log.error("Failed to save business log: {}", e.getMessage(), e); + return CompletableFuture.failedFuture(e); + } + } + + // DYNAMODB 로그 + public CompletableFuture logDynamodb(String tableName, EDBOperationType operationType, String userId, String userIP, + DynamoDBDocBase docData, LogStatus status, List changes, String message, String tranId) { + + DynamodbDomain domain = DynamodbDomain.builder() + .tranId(tranId) + .tableName(tableName) + .operationType(operationType) + .changed(changes) + .data(docData) + .build(); + + return saveLog( + LogCategory.DYNAMODB, + status, + message, + domain, + userId, + userIP, + processIdManager.getCurrentProcessId(), + processIdManager.getCurrentAction() + ); + } + + // MARIADB 로그 + public CompletableFuture logMariadb(String prodId, LogAction logAction, String tableName, EDBOperationType operationType, String userId, String userIP, + Object data, LogStatus status, List changes, String message, String tranId) { + + MariadbDomain domain = MariadbDomain.builder() + .tranId(tranId) + .tableName(tableName) + .operationType(operationType) + .changed(changes) + .data(data) + .build(); + + return saveLog( + LogCategory.MARIADB, + status, + message, + domain, + userId, + userIP, + prodId, + logAction + ); + } + + // MessageQueue 로그 + public CompletableFuture logMessageQueue(LogStatus status, String message, String userId, String userIP, + String queueName, String targetServer, Object messageContent) { + + MessageQueueDomain domain = MessageQueueDomain.builder() + .queueName(queueName) + .targetServer(targetServer) + .messageContent(messageContent) + .build(); + + return saveLog( + LogCategory.MESSAGE_QUEUE, + status, + message, + domain, + userId, + userIP, + processIdManager.getCurrentProcessId(), + processIdManager.getCurrentAction() + ); + } + + // Redis 로그 + public CompletableFuture logRedis(LogStatus status, String message, String userId, String userIP, + String key, Object value) { + + RedisDomain domain = RedisDomain.builder() + .key(key) + .value(value) + .build(); + + return saveLog( + LogCategory.REDIS, + status, + message, + domain, + userId, + userIP, + processIdManager.getCurrentProcessId(), + processIdManager.getCurrentAction() + ); + } + + // S3 로그 + public CompletableFuture logS3(LogStatus status, String message, String userId, String userIP, + String bucket, String key, Long fileSize, String contentType) { + + S3Domain domain = S3Domain.builder() + .bucket(bucket) + .key(key) + .fileSize(fileSize) + .contentType(contentType) + .build(); + + return saveLog( + LogCategory.MESSAGE_QUEUE, + status, + message, + domain, + userId, + userIP, + processIdManager.getCurrentProcessId(), + processIdManager.getCurrentAction() + ); + } + + // 스케줄러 로그 + public CompletableFuture logScheduler(LogStatus status, String message, + String schedulerName, LocalDateTime startTime, LocalDateTime endTime, Object data) { + + SchedulerDomain domain = SchedulerDomain.builder() + .schedulerName(schedulerName) + .startTime(startTime) + .endTime(endTime) + .info(data) + .build(); + + return saveLog( + LogCategory.SCHEDULER, + status, + message, + domain, + "SYSTEM", + "", + processIdManager.getCurrentProcessId(), + processIdManager.getCurrentAction() + ); + } + + // 배치잡 로그 + public CompletableFuture logBatchJob(LogStatus status, String message, String userId, String userIP, + String jobName, LocalDateTime startTime, LocalDateTime endTime, Object data, String query) { + + BatchJobDomain domain = BatchJobDomain.builder() + .jobName(jobName) + .duration(startTime != null && endTime != null ? + Duration.between(startTime, endTime).toMillis() : null) + .info(data) + .query(query) + .build(); + + return saveLog( + LogCategory.BATCH_JOB, + status, + message, + domain, + userId, + userIP, + processIdManager.getCurrentProcessId(), + processIdManager.getCurrentAction()); + } + + public CompletableFuture logDataInit(LogStatus status, String message, String userId, String userIP, + EInitDataType initDataType, String key, String subKey, Object data) { + + DataInitDomain domain = DataInitDomain.builder() + .initDataType(initDataType) + .key(key) + .data(data) + .build(); + + return saveLog( + LogCategory.DATA_INIT, + status, + message, + domain, + userId, + userIP, + processIdManager.getCurrentProcessId(), + processIdManager.getCurrentAction()); + } +} diff --git a/src/main/java/com/caliverse/admin/mongodb/service/DataInitializeHistoryService.java b/src/main/java/com/caliverse/admin/mongodb/service/DataInitializeHistoryService.java index 3bd009c..c9114bd 100644 --- a/src/main/java/com/caliverse/admin/mongodb/service/DataInitializeHistoryService.java +++ b/src/main/java/com/caliverse/admin/mongodb/service/DataInitializeHistoryService.java @@ -4,7 +4,7 @@ import com.caliverse.admin.domain.entity.EInitDataType; import com.caliverse.admin.domain.request.LogGenericRequest; import com.caliverse.admin.dynamodb.domain.doc.DynamoDBDocBase; import com.caliverse.admin.global.common.constants.AdminConstants; -import com.caliverse.admin.global.component.transaction.TransactionIdManager; +import com.caliverse.admin.global.component.manager.TransactionIdManager; import com.caliverse.admin.mongodb.domain.APILogInfo; import com.caliverse.admin.mongodb.domain.DynamodbDataInitializeHistory; import com.caliverse.admin.mongodb.domain.MysqlDataInitializeHistory; diff --git a/src/main/java/com/caliverse/admin/mongodb/service/DynamodbHistoryLogService.java b/src/main/java/com/caliverse/admin/mongodb/service/DynamodbHistoryLogService.java index a54969b..2d5cd55 100644 --- a/src/main/java/com/caliverse/admin/mongodb/service/DynamodbHistoryLogService.java +++ b/src/main/java/com/caliverse/admin/mongodb/service/DynamodbHistoryLogService.java @@ -1,30 +1,122 @@ package com.caliverse.admin.mongodb.service; -import com.caliverse.admin.domain.adminlog.FieldChange; +import com.caliverse.admin.domain.entity.FieldChange; import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; +import com.caliverse.admin.domain.entity.log.LogStatus; import com.caliverse.admin.dynamodb.domain.doc.DynamoDBDocBase; import com.caliverse.admin.global.common.constants.CommonConstants; import com.caliverse.admin.global.common.utils.CommonUtils; -import com.caliverse.admin.global.component.transaction.TransactionIdManager; +import com.caliverse.admin.global.component.manager.TransactionIdManager; import com.caliverse.admin.mongodb.ChangeDetector; import com.caliverse.admin.mongodb.domain.DynamodbHistoryLogInfo; import com.caliverse.admin.mongodb.entity.EDBOperationType; import com.caliverse.admin.mongodb.repository.DynamodbHistoryLogRepository; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; +import java.util.concurrent.CompletableFuture; @Service @RequiredArgsConstructor +@Slf4j public class DynamodbHistoryLogService { @Value("${amazon.dynamodb.metaTable}") private String tableName; private final TransactionIdManager transactionIdManager; private final DynamodbHistoryLogRepository dynamodbHistoryLogRepository; + private final BusinessLogService businessLogService; + + public void insertHistoryLog(LogStatus logStatus, + String message, + DynamoDBDocBase metadata + ){ + + List changes = ChangeDetector.detectInsertChanges(metadata); + + if(!changes.isEmpty()) { + CompletableFuture logFuture = businessLogService.logDynamodb( + tableName, + EDBOperationType.INSERT, + CommonUtils.getAdmin() == null ? CommonConstants.SYSTEM : CommonUtils.getAdmin().getEmail(), + CommonUtils.getClientIp() == null ? CommonConstants.SYSTEM : CommonUtils.getClientIp(), + metadata, + logStatus, + changes, + message, + transactionIdManager.getCurrentTransactionId() + ); + + logFuture.whenComplete((result, throwable) -> { + if (throwable != null) { + log.warn("Business log failed for info: {}, error: {}", CommonUtils.objectByString(metadata), throwable.getMessage()); + } + }); + } + } + + public void updateHistoryLog(LogStatus logStatus, + String message, + DynamoDBDocBase beforeMetadata, + DynamoDBDocBase afterMetadata + ){ + List changes = ChangeDetector.detectChanges( + beforeMetadata, + afterMetadata + ); + + if(!changes.isEmpty()) { + CompletableFuture logFuture = businessLogService.logDynamodb( + tableName, + EDBOperationType.UPDATE, + CommonUtils.getAdmin() == null ? CommonConstants.SYSTEM : CommonUtils.getAdmin().getEmail(), + CommonUtils.getClientIp() == null ? CommonConstants.SYSTEM : CommonUtils.getClientIp(), + afterMetadata, + logStatus, + changes, + message, + transactionIdManager.getCurrentTransactionId() + ); + + logFuture.whenComplete((result, throwable) -> { + if (throwable != null) { + log.warn("Business log failed for info: {}, error: {}", CommonUtils.objectByString(afterMetadata), throwable.getMessage()); + } + }); + } + } + + public void deleteHistoryLog(LogStatus logStatus, + String message, + DynamoDBDocBase metadata + ){ + + List changes = ChangeDetector.detectDeleteChanges(metadata); + + if(!changes.isEmpty()) { + CompletableFuture logFuture = businessLogService.logDynamodb( + tableName, + EDBOperationType.DELETE, + CommonUtils.getAdmin() == null ? CommonConstants.SYSTEM : CommonUtils.getAdmin().getEmail(), + CommonUtils.getClientIp() == null ? CommonConstants.SYSTEM : CommonUtils.getClientIp(), + metadata, + logStatus, + changes, + message, + transactionIdManager.getCurrentTransactionId() + ); + + logFuture.whenComplete((result, throwable) -> { + if (throwable != null) { + log.warn("Business log failed for info: {}, error: {}", CommonUtils.objectByString(metadata), throwable.getMessage()); + } + }); + } + } public void insertHistoryLog(HISTORYTYPEDETAIL historyType, String message, diff --git a/src/main/java/com/caliverse/admin/mongodb/service/MysqlHistoryLogService.java b/src/main/java/com/caliverse/admin/mongodb/service/MysqlHistoryLogService.java index f54f9b7..60de828 100644 --- a/src/main/java/com/caliverse/admin/mongodb/service/MysqlHistoryLogService.java +++ b/src/main/java/com/caliverse/admin/mongodb/service/MysqlHistoryLogService.java @@ -1,23 +1,24 @@ package com.caliverse.admin.mongodb.service; -import com.caliverse.admin.domain.adminlog.FieldChange; -import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL; +import com.caliverse.admin.domain.entity.FieldChange; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; import com.caliverse.admin.global.common.code.CommonCode; import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.global.common.constants.CommonConstants; import com.caliverse.admin.global.common.exception.RestApiException; import com.caliverse.admin.global.common.utils.CommonUtils; -import com.caliverse.admin.global.component.transaction.TransactionIdManager; +import com.caliverse.admin.global.component.manager.TransactionIdManager; import com.caliverse.admin.mongodb.ChangeDetector; import com.caliverse.admin.mongodb.domain.MysqlHistoryLogInfo; import com.caliverse.admin.mongodb.entity.EDBOperationType; import com.caliverse.admin.mongodb.repository.MysqlHistoryLogRepository; -import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.*; +import java.util.concurrent.CompletableFuture; @Service @RequiredArgsConstructor @@ -26,30 +27,40 @@ public class MysqlHistoryLogService { private final TransactionIdManager transactionIdManager; private final MysqlHistoryLogRepository mysqlHistoryLogRepository; - private final ObjectMapper objectMapper; + private final BusinessLogService businessLogService; - public void insertHistoryLog(HISTORYTYPEDETAIL historyType, - String tableName, - String message, - T data + public void insertHistoryLog( + String prodId, + LogAction action, + LogStatus logStatus, + String tableName, + String message, + T data ){ try { List changes = ChangeDetector.detectInsertChanges(data); - if(!changes.isEmpty()) { - MysqlHistoryLogInfo historyLog = new MysqlHistoryLogInfo( - EDBOperationType.INSERT, - historyType, + if(!changes.isEmpty() || action != null) { + + CompletableFuture logFuture = businessLogService.logMariadb( + prodId, + action, tableName, - message, - transactionIdManager.getCurrentTransactionId(), - changes, + EDBOperationType.INSERT, CommonUtils.getAdmin() == null ? CommonConstants.SYSTEM : CommonUtils.getAdmin().getEmail(), CommonUtils.getClientIp() == null ? CommonConstants.SYSTEM : CommonUtils.getClientIp(), - data + data, + logStatus, + changes, + message, + transactionIdManager.getCurrentTransactionId() ); - mysqlHistoryLogRepository.save(historyLog); + logFuture.whenComplete((result, throwable) -> { + if (throwable != null) { + log.warn("Business log failed for info: {}, error: {}", CommonUtils.objectByString(data), throwable.getMessage()); + } + }); } }catch(Exception e){ log.error("Insert historyLog Save Error", e); @@ -57,31 +68,40 @@ public class MysqlHistoryLogService { } } - public void updateHistoryLog(HISTORYTYPEDETAIL historyType, - String tableName, - String message, - T beforeData, - T afterData + public void updateHistoryLog( + String prodId, + LogAction action, + LogStatus logStatus, + String tableName, + String message, + T beforeData, + T afterData ){ try { List changes = ChangeDetector.detectChanges( beforeData, afterData ); - if(!changes.isEmpty()) { - MysqlHistoryLogInfo historyLog = new MysqlHistoryLogInfo( - EDBOperationType.UPDATE, - historyType, + if(!changes.isEmpty() || action != null) { + CompletableFuture logFuture = businessLogService.logMariadb( + prodId, + action, tableName, - message, - transactionIdManager.getCurrentTransactionId(), - changes, + EDBOperationType.UPDATE, CommonUtils.getAdmin() == null ? CommonConstants.SYSTEM : CommonUtils.getAdmin().getEmail(), CommonUtils.getClientIp() == null ? CommonConstants.SYSTEM : CommonUtils.getClientIp(), - afterData + afterData, + logStatus, + changes, + message, + transactionIdManager.getCurrentTransactionId() ); - mysqlHistoryLogRepository.save(historyLog); + logFuture.whenComplete((result, throwable) -> { + if (throwable != null) { + log.warn("Business log failed for info: {}, error: {}", CommonUtils.objectByString(afterData), throwable.getMessage()); + } + }); } }catch(Exception e){ log.error("Update historyLog Save Error", e); @@ -89,13 +109,14 @@ public class MysqlHistoryLogService { } } - public void deleteHistoryLog(HISTORYTYPEDETAIL historyType, - String tableName, - String message, - T data + public void deleteHistoryLog( + String prodId, + LogAction action, + LogStatus logStatus, + String tableName, + String message, + T data ){ - -// List changes = ChangeDetector.detectDeleteChanges(data); try { List changes; if (data instanceof Collection && !((Collection) data).isEmpty()) { @@ -103,20 +124,27 @@ public class MysqlHistoryLogService { } else { changes = ChangeDetector.detectDeleteChanges(data); } - if(!changes.isEmpty()){ - MysqlHistoryLogInfo historyLog = new MysqlHistoryLogInfo( - EDBOperationType.DELETE, - historyType, + + if(!changes.isEmpty() || action != null){ + CompletableFuture logFuture = businessLogService.logMariadb( + prodId, + action, tableName, - message, - transactionIdManager.getCurrentTransactionId(), - changes, + EDBOperationType.DELETE, CommonUtils.getAdmin() == null ? CommonConstants.SYSTEM : CommonUtils.getAdmin().getEmail(), CommonUtils.getClientIp() == null ? CommonConstants.SYSTEM : CommonUtils.getClientIp(), - data + data, + logStatus, + changes, + message, + transactionIdManager.getCurrentTransactionId() ); - mysqlHistoryLogRepository.save(historyLog); + logFuture.whenComplete((result, throwable) -> { + if (throwable != null) { + log.warn("Business log failed for info: {}, error: {}", CommonUtils.objectByString(data), throwable.getMessage()); + } + }); } }catch(Exception e){ log.error("Delete historyLog Save Error", e); diff --git a/src/main/java/com/caliverse/admin/scheduler/CommonScheduler.java b/src/main/java/com/caliverse/admin/scheduler/CommonScheduler.java index 19b44d0..f171e2e 100644 --- a/src/main/java/com/caliverse/admin/scheduler/CommonScheduler.java +++ b/src/main/java/com/caliverse/admin/scheduler/CommonScheduler.java @@ -1,18 +1,44 @@ package com.caliverse.admin.scheduler; +import com.caliverse.admin.domain.entity.log.LogStatus; +import com.caliverse.admin.mongodb.service.BusinessLogService; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; + +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.Map; @Slf4j public abstract class CommonScheduler implements Scheduler { + protected final BusinessLogService businessLogService; + + protected CommonScheduler(BusinessLogService businessLogService) { + this.businessLogService = businessLogService; + } + @Override public void execute() { + LocalDateTime startTime = LocalDateTime.now(); + String schedulerName = getSchedulerType().name(); + try { - log.info("Start executing scheduler: {}", getSchedulerType()); + log.info("Start executing scheduler: {}", schedulerName); + executeInternal(); - log.info("Finished executing scheduler: {}", getSchedulerType()); + + log.info("Finished executing scheduler: {}", schedulerName); } catch (Exception e) { - log.error("Error executing scheduler {}: {}", getSchedulerType(), e.getMessage(), e); + businessLogService.logScheduler( + LogStatus.FAILURE, + String.format("Scheduler %s failed: %s", schedulerName, e.getMessage()), + schedulerName, + startTime, + LocalDateTime.now(), + Map.of("error", e.getMessage(), "stackTrace", Arrays.toString(e.getStackTrace())) + ); + log.error("Error executing scheduler {}: {}", schedulerName, e.getMessage(), e); } } diff --git a/src/main/java/com/caliverse/admin/scheduler/DynamicScheduler.java b/src/main/java/com/caliverse/admin/scheduler/DynamicScheduler.java deleted file mode 100644 index 1138696..0000000 --- a/src/main/java/com/caliverse/admin/scheduler/DynamicScheduler.java +++ /dev/null @@ -1,666 +0,0 @@ -package com.caliverse.admin.scheduler; - -import com.caliverse.admin.domain.RabbitMq.MessageHandlerService; -import com.caliverse.admin.domain.RabbitMq.message.LanguageType; -import com.caliverse.admin.domain.RabbitMq.message.MailItem; -import com.caliverse.admin.domain.RabbitMq.message.OperationSystemMessage; -import com.caliverse.admin.domain.entity.*; -import com.caliverse.admin.dynamodb.entity.ELandAuctionResult; -import com.caliverse.admin.dynamodb.entity.ELandAuctionState; -import com.caliverse.admin.dynamodb.domain.atrrib.LandAuctionHighestBidUserAttrib; -import com.caliverse.admin.dynamodb.domain.atrrib.LandAuctionRegistryAttrib; -import com.caliverse.admin.domain.entity.redis.RedisLoginInfo; -import com.caliverse.admin.domain.service.*; -import com.caliverse.admin.dynamodb.service.DynamodbService; -import com.caliverse.admin.global.common.utils.CommonUtils; -import com.caliverse.admin.global.common.utils.ExcelUtils; -import com.caliverse.admin.redis.service.RedisUserInfoService; -import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.*; -import org.springframework.stereotype.Service; - -import lombok.extern.slf4j.Slf4j; - -import java.time.Duration; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.util.*; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -@Service -@AllArgsConstructor -@Slf4j -public class DynamicScheduler { - - private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); - - private final MailService mailService; - private final NoticeService noticeService; - private final BlackListService blackListService; - private final EventService eventService; - private final LandService landService; - private final UserGameSessionService userGameSessionService; - private final ScheduleService schedulerService; - private final RedisUserInfoService redisUserInfoService; - private final MessageHandlerService messageHandlerService; - private final BattleEventService battleEventService; - private final HistoryService historyService; - - private final DynamodbService dynamodbService; - - private final ExcelUtils excelUtils; - private final ObjectMapper objectMapper; - - public void battleEventSchedule(){ - List eventList = battleEventService.getScheduleBattleEventList(); - - try{ - eventList.forEach(event -> { - BattleEvent.BATTLE_STATUS status = event.getStatus(); - LocalDateTime start_dt = event.getEventStartDt(); - LocalTime startTime = start_dt.toLocalTime(); - - LocalDateTime now = LocalDateTime.now(); - LocalTime currentTime = LocalDateTime.now().toLocalTime(); - LocalDateTime end_dt = event.getEventEndDt(); - int operation_time = event.getEventOperationTime(); - - LocalTime endTime = startTime.plusSeconds(operation_time); - - // 현재시간이 자정을 넘어간 경우(00:00 ~ endTime)라면 전날을 기준으로 - LocalDate baseDate; - if (startTime.isAfter(endTime)) { // 시작시간이 종료시간보다 늦은 경우 (자정을 걸치는 경우) - if (currentTime.isBefore(endTime)) { - // 현재시간이 00:00 ~ endTime 사이면 전날 기준 - baseDate = now.toLocalDate().minusDays(1); - } else if (!currentTime.isBefore(startTime)) { - // 현재시간이 startTime 이후면 현재 날짜 기준 - baseDate = now.toLocalDate(); - } else { - baseDate = now.toLocalDate(); - } - } else { - // 자정을 걸치지 않는 일반적인 경우 - baseDate = now.toLocalDate(); - } - - //오늘자 기준 시작, 종료 시간 - LocalDateTime todayStart = LocalDateTime.of(baseDate, startTime); - LocalDateTime todayEnd = todayStart.plusSeconds(operation_time); - - BattleEvent.BATTLE_STATUS change_status = null; - - Map map = new HashMap<>(); - map.put("id", event.getId()); - - if(status.equals(BattleEvent.BATTLE_STATUS.REGISTER) || status.equals(BattleEvent.BATTLE_STATUS.WAIT)){ - if(!now.isBefore(start_dt) && (!now.isBefore(todayStart) && !now.isAfter(todayEnd))){ - log.info("battle event_id: {}, start_dt: {}, todayStart: {}, todayEnd: {} STATUS CHANGE RUNNING", event.getId(), start_dt, todayStart, todayEnd); - change_status = BattleEvent.BATTLE_STATUS.RUNNING; - map.put("status", change_status); - battleEventService.updateBattleEventStatus(map); - } - }else if(status.equals(BattleEvent.BATTLE_STATUS.RUNNING) || status.equals(BattleEvent.BATTLE_STATUS.STOP)){ - if(!(!now.isBefore(todayStart) && !now.isAfter(todayEnd))){ - if(!baseDate.isBefore(end_dt.toLocalDate())){ - change_status = BattleEvent.BATTLE_STATUS.END; - }else{ - change_status = status.equals(BattleEvent.BATTLE_STATUS.STOP) ? BattleEvent.BATTLE_STATUS.STOP : BattleEvent.BATTLE_STATUS.WAIT; - } - log.info("battle event_id: {}, start_dt: {}, end_dt: {}, todayStart: {}, todayEnd: {} STATUS CHANGE {}", event.getId(), start_dt, end_dt, todayStart, todayEnd, change_status); - map.put("status", change_status); - battleEventService.updateBattleEventStatus(map); - } - } - }); - }catch(Exception e){ - log.error("battleEventSchedule Exception: {}", e.getMessage()); - } - } - - public void landAuctionSchedule(){ - List auctionList = landService.getScheduleLandAuctionList(); - - try{ - auctionList.forEach(auction -> { - LocalDateTime nowDate = LocalDateTime.now(); - LocalDateTime reservationDate = auction.getResvStartDt(); - LocalDateTime auctionStartDate = auction.getAuctionStartDt(); - LocalDateTime auctionEndDate = auction.getAuctionEndDt(); - - LandAuction.AUCTION_STATUS auction_status = auction.getStatus(); - - //예약 시작시간이 되지않으면 체크하지 않는다 - if(nowDate.isBefore(reservationDate)){ - return; - } - - //예약일때 경매 시작시간이 되지않았다면 체크하지 않는다 - if(auction_status.equals(LandAuction.AUCTION_STATUS.RESV_START) && nowDate.isBefore(auctionStartDate)){ - return; - } - - // 비정상종료일때가 있다고 상시체크로 해달라고 함(23.02.18) - // 경매중일때 경매 종료시간이 되지않았다면 체크하지 않는다 -// if(auction_status.equals(LandAuction.AUCTION_STATUS.AUCTION_START) && nowDate.isBefore(auctionEndDate)){ -// return; -// } - - Map map = new HashMap<>(); - map.put("id", auction.getId()); - - LandAuctionRegistryAttrib attrib = landService.getLandAuctionRegistryAttrib(auction.getLandId(), auction.getAuctionSeq()); - String dynamodb_auction_state = attrib.getAuctionState(); - LandAuction.AUCTION_STATUS change_status = null; - if(dynamodb_auction_state.equals(ELandAuctionState.SCHEDULED.getName())){ - change_status = LandAuction.AUCTION_STATUS.RESV_START; - map.put("status", change_status); - landService.updateLandAuctionStatus(map); - log.info("land_auction id: {} Status Schedule Changed", auction.getId()); - }else if(dynamodb_auction_state.equals(ELandAuctionState.STARTED.getName())){ - change_status = LandAuction.AUCTION_STATUS.AUCTION_START; - map.put("status", change_status); - landService.updateLandAuctionStatus(map); - log.info("land_auction id: {} Status Auction Start Changed", auction.getId()); - }else if(dynamodb_auction_state.equals(ELandAuctionState.ENDED.getName())){ - String result = attrib.getAuctionResult(); - - if(result.equals(ELandAuctionResult.SUCCESSED.getName())){ - LandAuctionHighestBidUserAttrib bidUser = landService.getLandAuctionHighestUserAttrib(auction.getLandId(), auction.getAuctionSeq()); - if(bidUser == null) return; - log.info("land_auction id: {} Status SUCCESS Changed. bidUser: {}", auction.getId(), bidUser); - String close_dt = CommonUtils.convertIsoByDatetime(attrib.getProcessVersionTime()); - change_status = LandAuction.AUCTION_STATUS.AUCTION_END; - map.put("status", change_status); - map.put("closeEndDt", close_dt); - map.put("bidderGuid", bidUser.getHighestBidUserGuid()); - map.put("bidderNickname", bidUser.getHighestBidUserNickname()); - map.put("closePrice", bidUser.getHighestBidPrice()); - landService.updateLandAuctionStatus(map); - }else{ - if(result.equals(ELandAuctionResult.CANCELED.getName())){ - change_status = LandAuction.AUCTION_STATUS.CANCEL; - map.put("status", change_status); - }else{ - change_status = LandAuction.AUCTION_STATUS.FAIL; - map.put("status", change_status); - } - log.info("land_auction id: {} Status {} Changed.", auction.getId(), change_status); - landService.updateLandAuctionStatus(map); - } - } - }); - } catch (Exception e){ - log.error("landAuctionSchedule Exception: {}", e.getMessage()); - } - } - - public void eventSchedule(){ - List eventList = eventService.getScheduleMailList(); - - try{ - eventList.forEach(event -> { - LocalDateTime nowDate = LocalDateTime.now(); - LocalDateTime startTime = event.getStartDt(); - LocalDateTime endTime = event.getEndDt(); - - if(nowDate.isAfter(endTime) && event.getStatus().equals(Event.EVENTSTATUS.WAIT)){ - eventService.updateEventStatus(event.getId(), Event.EVENTSTATUS.FAIL); - log.error("eventJob eventSchedule timeOut : {}", event); - return; - } - - // 시작시간이 30분 남았을때 게임DB에 insert 해준다 - if (event.getStatus().equals(Event.EVENTSTATUS.WAIT) && Duration.between(nowDate, startTime).abs().toMinutes() <= 30 && !event.isAddFlag()) { -// systemMailInsert(event); - eventService.insertSystemMail(event); -// eventService.updateEventStatus(event.getId(), Event.EVENTSTATUS.RUNNING); - log.info("eventJob eventSchedule dynamoDB Insert & Start: {}", event); - } - -// if(!nowDate.isBefore(startTime) && event.getStatus().equals(Event.EVENTSTATUS.WAIT)){ -// eventService.updateEventStatus(event.getId(), Event.EVENTSTATUS.RUNNING); -// log.info("eventJob eventSchedule block start : {}", event); -// } - - if(!nowDate.isBefore(endTime) && event.getStatus().equals(Event.EVENTSTATUS.RUNNING)){ - eventService.updateEventStatus(event.getId(), Event.EVENTSTATUS.FINISH); - log.info("eventJob eventSchedule block end : {}", event); - } - }); - }catch (Exception e){ - log.error("eventSchedule Exception: {}", e.getMessage()); - } - } - - public void blackListSchedule(){ - List blackList = blackListService.getScheduleBlackList(); - - try{ - LocalDateTime nowDate = LocalDateTime.now(); - blackList.forEach(blockUser -> { - BlackList.STATUSTYPE status = blockUser.getStatus(); - - // WAIT 상태 처리 - if(status == BlackList.STATUSTYPE.WAIT) { - if(nowDate.isAfter(blockUser.getEndDt())) { - // 만료시간 초과 - FAIL 처리 - blackListService.updateBlackListStatus(blockUser.getId(), BlackList.STATUSTYPE.FAIL); - log.error("blackListJob blackListSchedule timeOut : {}", blockUser); - } else if(!nowDate.isBefore(blockUser.getStartDt())) { - // 시작시간 도달 - INPROGRESS 처리 - userGameSessionService.kickUserSession(blockUser.getGuid(), "user block"); - blackListService.updateScheduleBlockUser(blockUser, BlackList.STATUSTYPE.INPROGRESS); - blackListService.updateBlackListStatus(blockUser.getId(), BlackList.STATUSTYPE.INPROGRESS); - log.info("blackListJob blackListSchedule block start : {}", blockUser); - } - } - // INPROGRESS 상태 처리 - else if(status == BlackList.STATUSTYPE.INPROGRESS && !nowDate.isBefore(blockUser.getEndDt())) { - // 만료시간 도달 - EXPIRATION 처리 - blackListService.updateScheduleBlockUser(blockUser, BlackList.STATUSTYPE.EXPIRATION); - blackListService.updateBlackListStatus(blockUser.getId(), BlackList.STATUSTYPE.EXPIRATION); - log.info("blackListJob blackListSchedule block end : {}", blockUser); - } -// LocalDateTime startTime = blockUser.getStartDt(); -// LocalDateTime endTime = blockUser.getEndDt(); -// -// // 상태가 대기중이고 만료시간이 지났으면 실패 처리 -// if(nowDate.isAfter(endTime) && blockUser.getStatus().equals(BlackList.STATUSTYPE.WAIT)){ -// blackListService.updateBlackListStatus(blockUser.getId(), BlackList.STATUSTYPE.FAIL); -// log.error("blackListJob blackListSchedule timeOut : {}", blockUser); -// return; -// } -// -// // 상태가 대기중이고 시작시간 지났으면 유저제재 처리 -// if(!nowDate.isBefore(startTime) && blockUser.getStatus().equals(BlackList.STATUSTYPE.WAIT)){ -// // user kick 처리 -// userGameSessionService.kickUserSession(blockUser.getGuid()); -// blackListService.updateScheduleBlockUser(blockUser, BlackList.STATUSTYPE.INPROGRESS); -// blackListService.updateBlackListStatus(blockUser.getId(), BlackList.STATUSTYPE.INPROGRESS); -// log.info("blackListJob blackListSchedule block start : {}", blockUser); -// } -// -// // 상태가 제재중이고 만료시간 지났으면 상태 종료 처리 -// if(!nowDate.isBefore(endTime) && blockUser.getStatus().equals(BlackList.STATUSTYPE.INPROGRESS)){ -// blackListService.updateScheduleBlockUser(blockUser, BlackList.STATUSTYPE.EXPIRATION); -// blackListService.updateBlackListStatus(blockUser.getId(), BlackList.STATUSTYPE.EXPIRATION); -// log.info("blackListJob blackListSchedule block end : {}", blockUser); -// } - }); - }catch (Exception e){ - log.error("blackListSchedule Exception: {}", e.getMessage()); - } - - } - - public void mailSchedule() { - List mailList = mailService.getScheduleMailList(); - - try{ - mailList.forEach(mail -> { - if(mail.getSendStatus().equals(Mail.SENDSTATUS.WAIT)){ - if(mail.getSendType() == Mail.SENDTYPE.DIRECT_SEND){ - log.info("mailJob mailSchedule direct run : {}", mail); - mailTypeProcess(mail); - }else { - String key = "mail-" + mail.getId(); - if (!schedulerService.isTaskExist(key)) { - Runnable taskRunner = () -> { - log.info("mailJob mailSchedule schedule run : {}", mail); - mailTypeProcess(mail); - // 스케줄 해제 - schedulerService.closeTask(key); - }; - - // 시작일자 - 현재일자 - LocalDateTime startDate = mail.getSendDt(); - long initialDelay = Duration.between(LocalDateTime.now(), startDate).toMillis(); - - log.info("mailJob mailSchedule schedule add : {}", mail); - ScheduledFuture schedule = scheduler.schedule(taskRunner, initialDelay, TimeUnit.MILLISECONDS); - schedulerService.addTask(key, schedule); - } - } - } - }); - }catch (Exception e){ - log.error("mailSchedule Exception: {}", e.getMessage()); - mailService.setScheduleLog(HISTORYTYPEDETAIL.SCHEDULE_MAIL_FAIL, e.getMessage()); - } - } - - public void noticeSchedule() { - List noticeList = noticeService.getScheduleNoticeList(); - - try{ - noticeList.forEach(notice -> { - String key = "notice-" + notice.getId(); - if (!schedulerService.isTaskExist(key)) { - Runnable taskRunner = new Runnable() { - private int count = notice.getSendCnt().intValue(); - private final int repeat_cnt = notice.getRepeatCnt().intValue(); - private final boolean isRepeat = notice.getIsRepeat(); - private final long id = notice.getId(); - private final String runKey = key; - private final InGame.REPEATTYPE repeatType = notice.getRepeatType(); - private final LocalDateTime endDate = notice.getEndDt(); - - @Override - public void run() { - log.info("noticeJob noticeSchedule schedule run : {}", notice); - - boolean is_send = noticeSend(notice); - if(!is_send) return; - noticeService.updateNoticeCount(id); - - // 반복여부 - if(isRepeat){ - // 반복타입 - switch(repeatType){ - // 횟수 - case COUNT -> { - count++; - // 정해진 횟수만큼 돌았으면 종료 - if(count >= repeat_cnt){ - noticeService.updateNoticeStatus(id, InGame.SENDSTATUS.FINISH); - schedulerService.closeTask(runKey); - log.info("Notice Schedule End RepeatType: Count, id: {}", id); - } - } - // 일자 - case DATE -> { - if (LocalDateTime.now().isAfter(endDate)) { - noticeService.updateNoticeStatus(id, InGame.SENDSTATUS.FINISH); - schedulerService.closeTask(runKey); - log.info("Notice Schedule End RepeatType: Date, id: {}", id); - } - } - } - }else{ - // 스케줄 해제 및 상태 변경 - noticeService.updateNoticeStatus(id, InGame.SENDSTATUS.FINISH); - schedulerService.closeTask(runKey); - log.info("Notice One Time Schedule End id: {}", id); - } - } - }; - - // 반복여부 체크 - if(notice.getIsRepeat()){ - // 반복타입 - switch(notice.getRepeatType()){ - // 횟수 - case COUNT ->{ - // 시작일자 - 현재일자 - LocalDateTime startDate = notice.getSendDt(); - long initialDelay = Duration.between(LocalDateTime.now(), startDate).toMillis(); // 시작시간 - long period = LocalTime.parse(notice.getRepeatDt()).toSecondOfDay(); // 반복주기 - - ScheduledFuture schedule = scheduler.scheduleAtFixedRate(taskRunner, initialDelay, period, TimeUnit.MILLISECONDS); - schedulerService.addTask(key, schedule); - noticeService.updateNoticeStatus(notice.getId(), InGame.SENDSTATUS.RUNNING); - } - // 일자 - case DATE -> { - LocalDateTime startDate = notice.getSendDt(); - long initialDelay = Duration.between(LocalDateTime.now(), startDate).toMillis(); // 시작시간 - long period = CommonUtils.intervalToMillis(notice.getRepeatDt()); // 반복주기 - - ScheduledFuture schedule = scheduler.scheduleAtFixedRate(taskRunner, initialDelay, period, TimeUnit.MILLISECONDS); - schedulerService.addTask(key, schedule); - noticeService.updateNoticeStatus(notice.getId(), InGame.SENDSTATUS.RUNNING); - } - // 특정시간 - case TIME -> { - LocalDateTime now_date = LocalDateTime.now(); - LocalDateTime start_date = notice.getSendDt(); - - if(now_date.isAfter(start_date)) { - LocalTime now_time = LocalTime.now(); - LocalTime repeat_time = CommonUtils.stringToTime(notice.getRepeatDt()); - LocalDateTime end_date = notice.getEndDt(); - InGame.SENDSTATUS status = notice.getSendStatus(); - Long id = notice.getId(); - - if(status.equals(InGame.SENDSTATUS.WAIT)) noticeService.updateNoticeStatus(id, InGame.SENDSTATUS.RUNNING); - - if (now_time.equals(repeat_time)) { - log.info("noticeJob noticeSchedule RepeatType: Time run : {}", notice); - boolean is_send = noticeSend(notice); - if (!is_send) { - log.error("Notice Schedule Fail RepeatType: Time, id: {}", id); - } - } - - if(status.equals(InGame.SENDSTATUS.RUNNING) && (now_date.isBefore(end_date) || now_date.isEqual(end_date))){ - noticeService.updateNoticeStatus(id, InGame.SENDSTATUS.FINISH); - log.info("Notice Schedule End RepeatType: Time, id: {}", id); - } - } - } - } - - }else{ - // 시작일자 - 현재일자 - LocalDateTime startDate = notice.getSendDt(); - long initialDelay = Duration.between(LocalDateTime.now(), startDate).toMillis(); - - if(initialDelay < 0) { - log.error("noticeJob noticeSchedule schedule add fail time over"); - noticeService.updateNoticeStatus(notice.getId(), InGame.SENDSTATUS.FAIL); - mailService.setScheduleLog(HISTORYTYPEDETAIL.SCHEDULE_NOTICE_FAIL, "시작일자가 현재일자보다 이전으로 송출 중단."); - return; - } - - log.info("noticeJob noticeSchedule schedule add : {}", notice); - ScheduledFuture schedule = scheduler.schedule(taskRunner, initialDelay, TimeUnit.MILLISECONDS); - schedulerService.addTask(key, schedule); - } - } - }); - }catch (Exception e){ - log.error("noticeSchedule Exception: {}", e.getMessage()); - noticeService.setScheduleLog(HISTORYTYPEDETAIL.SCHEDULE_NOTICE_FAIL, e.getMessage()); - } - } - - private void mailTypeProcess(Mail mail){ - if(mail.getReceiveType().equals(Mail.RECEIVETYPE.SINGLE)){ - boolean is_send = mainSend(mail); - if(is_send) mailService.updateMailStatus(mail.getId(), Mail.SENDSTATUS.FINISH); - } - else{ - List excelList = excelUtils.getExcelListData(mail.getTarget()); - log.info("mailJob mailSchedule schedule run ExcelList : {}", excelList); - boolean is_send; - mailService.updateMailStatus(mail.getId(), Mail.SENDSTATUS.RUNNING); - for(Excel excel : excelList){ - String guid = mailService.getGuid(excel.getUser(), excel.getType()); - mail.setTarget(guid); - is_send = mainSend(mail); - if(!is_send){ - log.error("mailJob mailSchedule Excel fail user : {}", excel.getUser()); - mailService.setScheduleLog(HISTORYTYPEDETAIL.SCHEDULE_MAIL_FAIL, "mail schedule id: " + mail.getId() + " Excel Send Fail User: " + excel.getUser()); - } - else log.info("mailJob mailSchedule Excel send user : {}", excel.getUser()); - } - mailService.updateMailStatus(mail.getId(), Mail.SENDSTATUS.FINISH); - } - } - - // 우편 전송 - private boolean mainSend(Mail mail){ - // 서버정보 가져오기 - try{ - RedisLoginInfo info = redisUserInfoService.getUserLoginSessionInfo(mail.getTarget()); - String server_name = null; - if(info == null){ - server_name = redisUserInfoService.getFirstChannel(); - if(server_name == null){ - log.error("mailJob mainSend serverName is empty"); - mailService.updateMailStatus(mail.getId(), Mail.SENDSTATUS.FAIL); - mailService.setScheduleLog(HISTORYTYPEDETAIL.MAIL_SEND_FAIL, "is null server name"); - return false; - } - }else{ - server_name = info.getCurrentServer(); - } - - // 메시지 처리 - List msgList = mailService.getMailMessageList(mail.getId()); - List titleList = new ArrayList<>(); - List contentList = new ArrayList<>(); - List senderList = new ArrayList<>(); - for(Message msg : msgList){ - LanguageType lang = null; - String langText = msg.getLanguage(); - String sender = null; - - if(langText.equals(LANGUAGETYPE.EN.toString())){ - lang = LanguageType.LanguageType_en; - sender = "Administrator"; - }else if(langText.equals(LANGUAGETYPE.JA.toString())){ - lang = LanguageType.LanguageType_ja; - sender = "アドミニストレーター"; - }else{ - lang = LanguageType.LanguageType_ko; - sender = "시스템 관리자"; - } - titleList.add(OperationSystemMessage.newBuilder() - .setLanguageType(lang) - .setText(CommonUtils.stringToByte(msg.getTitle())).build()); - contentList.add(OperationSystemMessage.newBuilder() - .setLanguageType(lang) - .setText(CommonUtils.stringToByte(msg.getContent())).build()); - senderList.add(OperationSystemMessage.newBuilder() - .setLanguageType(lang) - .setText(CommonUtils.stringToByte(sender)).build()); - } - - // 아이템 처리 - List itemList = mailService.getMailItemList(mail.getId()); - List mailItemList = new ArrayList<>(); - for(Item item : itemList){ - mailItemList.add(MailItem.newBuilder() - .setItemId(CommonUtils.stringToInt(item.getItem())) - .setCount(item.getItemCnt()).build()); - } - - log.info("Send Mail Message : {}, target : {}, type :{}", contentList, mail.getTarget(), mail.getMailType()); - messageHandlerService.sendMailMessage(server_name, mail.getTarget(), mail.getMailType().toString(), titleList, contentList, mailItemList, senderList); - log.info("mailJob mailSend completed"); - return true; - }catch(Exception e){ - log.error("mailSend Exception: {}", e.getMessage()); - mailService.updateMailStatus(mail.getId(), Mail.SENDSTATUS.FAIL); - mailService.setScheduleLog(HISTORYTYPEDETAIL.MAIL_SEND_FAIL, e.getMessage()); - } - return false; - } - - // 공지사항 전송 - private boolean noticeSend(InGame notice){ - try{ - //redis 채널 및 인던 정보 가져오기 - List serverList = redisUserInfoService.getAllServerList(); - if(serverList.isEmpty()){ - log.error("noticeJob noticeSend serverList is empty"); - noticeService.updateNoticeStatus(notice.getId(), InGame.SENDSTATUS.FAIL); - noticeService.setScheduleLog(HISTORYTYPEDETAIL.NOTICE_SEND_FAIL, "is null server name"); - return false; - } - - //메시지 처리 - List msgList = noticeService.getNoticeMessageList(notice.getId()); - List contentList = new ArrayList<>(); - List senderList = new ArrayList<>(); - for(Message msg : Collections.unmodifiableList(msgList)){ - LanguageType lang = null; - String langText = msg.getLanguage(); - String sender = null; - - if(langText.equals(LANGUAGETYPE.EN.toString())){ - lang = LanguageType.LanguageType_en; - sender = "Administrator"; - }else if(langText.equals(LANGUAGETYPE.JA.toString())){ - lang = LanguageType.LanguageType_ja; - sender = "アドミニストレーター"; - }else{ - lang = LanguageType.LanguageType_ko; - sender = "시스템 관리자"; - } - contentList.add(OperationSystemMessage.newBuilder() - .setLanguageType(lang) - .setText(CommonUtils.stringToByte(msg.getContent())).build()); - senderList.add(OperationSystemMessage.newBuilder() - .setLanguageType(lang) - .setText(CommonUtils.stringToByte(sender)).build()); - } - - log.info("Send Notice Message: {}, type: {}", contentList, notice.getMessageType()); - messageHandlerService.sendNoticeMessage(serverList, notice.getMessageType().toString(), contentList, senderList); - log.info("noticeJob noticeSend completed"); - return true; - }catch (Exception e){ - log.error("noticeSend Exception: {}", e.getMessage()); - noticeService.updateNoticeStatus(notice.getId(), InGame.SENDSTATUS.FAIL); - noticeService.setScheduleLog(HISTORYTYPEDETAIL.NOTICE_SEND_FAIL, e.getMessage()); - } - return false; - } - - // 시스템 우편 등록 -// private void systemMailInsert(Event event){ -// try { -// log.info("systemMailInsert Info: {}", event); -// ObjectMapper objectMapper = new ObjectMapper(); -// ArrayNode mailTitleArray = objectMapper.createArrayNode(); -// ArrayNode mailTextArray = objectMapper.createArrayNode(); -// ArrayNode mailSenderArray = objectMapper.createArrayNode(); -// ArrayNode mailItemArray = objectMapper.createArrayNode(); -// -// List msgList = eventService.getMessageList(event.getId()); -// List itemList = eventService.getItemList(event.getId()); -// for (Message msg : msgList) { -// String langText = msg.getLanguage(); -// int lang; -// String sender; -// -// if (langText.equals(LANGUAGETYPE.EN.toString())) { -// lang = LanguageType.LanguageType_en.getNumber(); -// sender = "CALIVERSE"; -// } else if (langText.equals(LANGUAGETYPE.JA.toString())) { -// lang = LanguageType.LanguageType_ja.getNumber(); -// sender = "カリバース"; -// } else { -// lang = LanguageType.LanguageType_ko.getNumber(); -// sender = "칼리버스"; -// } -// SystemMessage titleMessage = SystemMessage.builder().LanguageType(lang).Text(msg.getTitle()).build(); -// SystemMessage textMessage = SystemMessage.builder().LanguageType(lang).Text(msg.getContent()).build(); -// SystemMessage senderMessage = SystemMessage.builder().LanguageType(lang).Text(sender).build(); -// -// mailTitleArray.add(JsonUtils.createSystemMessage(titleMessage)); -// mailTextArray.add(JsonUtils.createSystemMessage(textMessage)); -// mailSenderArray.add(JsonUtils.createSystemMessage(senderMessage)); -// } -// for (Item item : itemList) { -// MailItem mailItem = MailItem.newBuilder().setItemId(CommonUtils.stringToInt(item.getItem())).setCount(item.getItemCnt()).build(); -// mailItemArray.add(JsonUtils.createMAilItem(mailItem)); -// } -// -// eventService.insertSystemMail(event, mailTitleArray, mailTextArray, mailSenderArray, mailItemArray); -// -// }catch (Exception e){ -// log.error("systemMailInsert Exception: {}", e.getMessage()); -// eventService.updateEventStatus(event.getId(), Event.EVENTSTATUS.FAIL); -// historyService.setScheduleLog(HISTORYTYPE.SCHEDULE_EVENT_FAIL, e.getMessage()); -// } -// } - -} diff --git a/src/main/java/com/caliverse/admin/scheduler/OneTimeSchedule.java b/src/main/java/com/caliverse/admin/scheduler/OneTimeSchedule.java index 9599599..30cc1b3 100644 --- a/src/main/java/com/caliverse/admin/scheduler/OneTimeSchedule.java +++ b/src/main/java/com/caliverse/admin/scheduler/OneTimeSchedule.java @@ -1,6 +1,5 @@ package com.caliverse.admin.scheduler; -import com.caliverse.admin.domain.service.DiagnosisService; import com.caliverse.admin.dynamodb.service.DynamodbService; import com.caliverse.admin.global.common.constants.AdminConstants; import com.caliverse.admin.logs.Indicatordomain.StartEndTime; @@ -33,7 +32,7 @@ public class OneTimeSchedule implements CommandLineRunner { @Autowired private IndicatorsUserCreateService userCreateService; @Autowired private IndicatorsUserLoginService userLoginService; @Autowired private IndicatorsCurrencyService currencyService; - @Autowired private DiagnosisService diagnosisService; + @Autowired private IndicatorsItemService itemService; @Autowired private DynamodbService dynamodbService; @@ -53,17 +52,18 @@ public class OneTimeSchedule implements CommandLineRunner { for (LocalDate date = startDate; !date.isAfter(currentDate); date = date.plusDays(1)) { log.info("Processing date: {}", date); - + StartEndTime dayStartEndTime = LogServiceHelper.getCurrentLogSearchEndTime(date, AdminConstants.STAT_DAY_NUM); StartEndTime weekStartEndTime = LogServiceHelper.getCurrentLogSearchEndTime(date, AdminConstants.STAT_WEEK_NUM); StartEndTime monthStartEndTime = LogServiceHelper.getCurrentLogSearchEndTime(date, AdminConstants.STAT_MONTH_NUM); log.info("Date: {}, StartTime: {}, EndTime: {}", date, dayStartEndTime.getStartTime(), dayStartEndTime.getEndTime()); - -// currencyService.collectCurrency(dayStartEndTime.getStartTime(), dayStartEndTime.getEndTime()); -// userLoginService.collectUserLogin(dayStartEndTime.getStartTime(), dayStartEndTime.getEndTime()); +// itemService.collectItem(dayStartEndTime.getStartTime(), dayStartEndTime.getEndTime()); // userCreateService.collectUserCreate(dayStartEndTime.getStartTime(), dayStartEndTime.getEndTime()); +// userLoginService.collectUserLogin(dayStartEndTime.getStartTime(), dayStartEndTime.getEndTime()); + +// currencyService.collectCurrency(dayStartEndTime.getStartTime(), dayStartEndTime.getEndTime()); // metaverseServerService.collectMetaverseServerCount(dayStartEndTime.getStartTime(), dayStartEndTime.getEndTime(), 13); // capacityService.collectDBCapacity(dayStartEndTime.getStartTime(), dayStartEndTime.getEndTime()); //체크 // dauService.collectDailyActiveUser(dayStartEndTime.getStartTime(), dayStartEndTime.getEndTime()); //체크 diff --git a/src/main/java/com/caliverse/admin/scheduler/ScheduleSetter.java b/src/main/java/com/caliverse/admin/scheduler/ScheduleSetter.java deleted file mode 100644 index 76d2de0..0000000 --- a/src/main/java/com/caliverse/admin/scheduler/ScheduleSetter.java +++ /dev/null @@ -1,202 +0,0 @@ -package com.caliverse.admin.scheduler; - -import com.caliverse.admin.domain.service.CaliumService; -import com.caliverse.admin.global.common.utils.CommonUtils; -import com.caliverse.admin.logs.logservice.indicators.*; -import com.caliverse.admin.scheduler.batch.service.LogCompressService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - - -import com.caliverse.admin.global.common.constants.AdminConstants; -import com.caliverse.admin.logs.Indicatordomain.StartEndTime; -import com.caliverse.admin.logs.logservice.LogServiceHelper; -import com.caliverse.admin.redis.service.RedisUserInfoService; - -import lombok.extern.slf4j.Slf4j; - -import java.time.LocalDate; - -@Component -@Slf4j -@EnableScheduling -public class ScheduleSetter { - - @Autowired private IndicatorsAuService auService; - @Autowired private IndicatorsDauService dauService; - @Autowired private IndicatorsWauService wauService; - @Autowired private IndicatorsMauService mauService; - @Autowired private IndicatorsMcuService mcuService; - @Autowired private IndicatorsNruService nruService; - @Autowired private IndicatorsPlayTimeService playTimeService; - @Autowired private IndicatorsDglcService dglcService; - @Autowired private IndicatorsDBCapacityService capacityService; - @Autowired private IndicatorsUgqCreateService ugqCreateService; - @Autowired private IndicatorsMetaverseServerService metaverseServerService; - - @Autowired private IndicatorsNruService statNruService; - @Autowired private RedisUserInfoService userInfoService; - @Autowired private DynamicScheduler dynamicScheduler; - - @Autowired private CaliumService caliumService; - @Autowired private LogCompressService logService; - - @Scheduled(cron = "0 01 0 * * *") // 매일 UTC 기준 00시 01분 00초에 실행 - public void capacityScheduler() { -// log.info("run capacityScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - capacityService.collectDBCapacity(startEndTime.getStartTime(), startEndTime.getEndTime()); -// log.info("end capacityScheduler"); - } - - @Scheduled(cron = "0 02 0 * * *") // 매일 UTC 기준 00시 02분 00초에 실행 - public void metaverServerScheduler() { -// log.info("run metaverServerScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - int serverCount = 13; - metaverseServerService.collectMetaverseServerCount(startEndTime.getStartTime(), startEndTime.getEndTime(), serverCount); -// log.info("end metaverServerScheduler"); - } - - /* - 매일 UTC 기준 00시 50분 00초에 실행, (한국 시간 9시 50분) 30분에 돌릴경우 데이터가 다 넘어 오지 않는 경우 있어서 수정처리 - 이게 가장 먼저 실행 되어야 한다. - 로그가 많을 경우 성능 이슈 있을 수 있음 - */ - @Scheduled(cron = "0 50 0 * * *") - public void auScheduler() { - //이걸 나중에 어떻게 활용할지 생각해보자. -// log.info("run auScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - auService.collectActiveUser(startEndTime.getStartTime(), startEndTime.getEndTime()); -// log.info("end auScheduler"); - } - - @Scheduled(cron = "00 55 0 * * *") // 매일 UTC 기준 00시 55분 00초에 실행 - public void dauScheduler() { -// log.info("run dauScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - dauService.collectDailyActiveUser(startEndTime.getStartTime(), startEndTime.getEndTime()); -// log.info("end dauScheduler"); - } - - @Scheduled(cron = "00 56 0 * * *") // 매일 UTC 기준 00시 56분 00초에 실행 - public void wauScheduler() { -// log.info("run wauScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_WEEK_NUM); - wauService.collectWeeklyActiveUser(startEndTime.getStartTime(), startEndTime.getEndTime()); -// log.info("end wauScheduler"); - } - -// @Scheduled(cron = "00 57 0 * * *") // 매일 UTC 기준 00시 57분 00초에 실행 - @Scheduled(cron = "00 57 0 1 * ?") // 매월 1일 UTC 기준 00시 57분 00초에 실행 - public void mauScheduler() { -// log.info("run mauScheduler"); - int monthLength = CommonUtils.getLengthOfLastMonth(LocalDate.now()); // 지난달 총일수 가져오기 - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(monthLength); - mauService.collectMonthlyActiveUser(startEndTime.getStartTime(), startEndTime.getEndTime()); -// log.info("end mauScheduler"); - } - - @Scheduled(cron = "00 58 0 * * *") // 매일 UTC 기준 00시 58분 00초에 실행 - public void mcuScheduler() { -// log.info("run mcuScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - mcuService.collectMaxCountUser(startEndTime.getStartTime(), startEndTime.getEndTime()); -// log.info("end mcuScheduler"); - } - - @Scheduled(cron = "00 59 0 * * *") // 매일 UTC 기준 00시 59분 00초에 실행 - public void nruScheduler() { -// log.info("run nruScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - nruService.collectCharacterCreateCount(startEndTime.getStartTime(), startEndTime.getEndTime()); -// log.info("end nruScheduler"); - } - - @Scheduled(cron = "00 00 1 * * *") // 매일 UTC 기준 1시 00분 00초에 실행 - public void playTimeScheduler() { -// log.info("run playTimeScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - playTimeService.collectUserPlayTime(startEndTime.getStartTime(), startEndTime.getEndTime()); -// log.info("end playTimeScheduler"); - } - - @Scheduled(cron = "00 01 1 * * *") // 매일 UTC 기준 01시 01분 00초에 실행 - public void dglcScheduler() { -// log.info("run dglcScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - dglcService.collectDailyGameLoginCount(startEndTime.getStartTime(), startEndTime.getEndTime()); -// log.info("end dglcScheduler"); - } - - @Scheduled(cron = "00 00 2 * * *") // 매일 UTC 기준 02시 00분 00초에 실행 (Log 데이터가 늦게 넘어올때가 있기때문에 나중에 실행) - public void ugqCreateScheduler() { -// log.info("run ugqCreateScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - ugqCreateService.collectUGQCreateCount(startEndTime.getStartTime(), startEndTime.getEndTime()); -// log.info("end ugqCreateScheduler"); - } - - - @Scheduled(cron = "0 * * * * *") // 매 분 00초에 실행 - public void runJob() { - //log.info("run runJob"); - } - - @Scheduled(cron = "1 * * * * *") - public void noticeJob(){ -// log.info("run noticeJob"); - dynamicScheduler.noticeSchedule(); -// log.info("end noticeJob"); - } - - @Scheduled(cron = "2 * * * * *") - public void mailJob(){ -// log.info("run mailJob"); - dynamicScheduler.mailSchedule(); -// log.info("end mailJob"); - } - - @Scheduled(cron = "3 * * * * *") - public void blackListJob(){ -// log.info("run blackListJob"); - dynamicScheduler.blackListSchedule(); -// log.info("end blackListJob"); - } - - @Scheduled(cron = "4 * * * * *") - public void eventJob(){ -// log.info("run eventJob"); - dynamicScheduler.eventSchedule(); -// log.info("end eventJob"); - } - - @Scheduled(cron = "5 * * * * *") - public void landAuctionJob(){ -// log.info("run landAuctionJob"); - dynamicScheduler.landAuctionSchedule(); -// log.info("end landAuctionJob"); - } - - @Scheduled(cron = "6 * * * * *") - public void battleEventJob(){ - dynamicScheduler.battleEventSchedule(); - } - - //web3 - @Scheduled(cron = "1 * * * * *") - public void web3Job(){ -// log.info("run web3Job"); - caliumService.getScheduleCaliumRequestList(); -// log.info("end web3Job"); - } - - //log -// @Scheduled(cron = "00 00 00 1 * ?") // 매월 1일에 실행 -// public void logJob(){ -// logService.compressLastMonthLogs(); -// } -} diff --git a/src/main/java/com/caliverse/admin/scheduler/ScheduleSetter.java.bak b/src/main/java/com/caliverse/admin/scheduler/ScheduleSetter.java.bak deleted file mode 100644 index cff644c..0000000 --- a/src/main/java/com/caliverse/admin/scheduler/ScheduleSetter.java.bak +++ /dev/null @@ -1,178 +0,0 @@ -package com.caliverse.admin.scheduler; - -import com.caliverse.admin.domain.service.CaliumService; -import com.caliverse.admin.logs.logservice.indicators.*; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - - -import com.caliverse.admin.global.common.constants.AdminConstants; -import com.caliverse.admin.logs.Indicatordomain.StartEndTime; -import com.caliverse.admin.logs.logservice.LogServiceHelper; -import com.caliverse.admin.redis.service.RedisUserInfoService; - -import lombok.extern.slf4j.Slf4j; - -@Component -@Slf4j -@EnableScheduling -public class ScheduleSetter { - - @Autowired private IndicatorsAuService auService; - @Autowired private IndicatorsDauService dauService; - @Autowired private IndicatorsWauService wauService; - @Autowired private IndicatorsMauService mauService; - @Autowired private IndicatorsMcuService mcuService; - @Autowired private IndicatorsNruService nruService; - @Autowired private IndicatorsPlayTimeService playTimeService; - @Autowired private IndicatorsDglcService dglcService; - @Autowired private IndicatorsDBCapacityService capacityService; - @Autowired private IndicatorsUgqCreateService ugqCreateService; - @Autowired private IndicatorsMetaverseServerService metaverseServerService; - - @Autowired private IndicatorsNruService statNruService; - @Autowired private RedisUserInfoService userInfoService; - @Autowired private DynamicScheduler dynamicScheduler; - - @Autowired private CaliumService caliumService; - - @Scheduled(cron = "0 01 0 * * *") // 매일 UTC 기준 00시 01분 00초에 실행 - public void capacityScheduler() { - log.info("run capacityScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - capacityService.collectDBCapacity(startEndTime.getStartTime(), startEndTime.getEndTime()); - log.info("end capacityScheduler"); - } - - @Scheduled(cron = "0 02 0 * * *") // 매일 UTC 기준 00시 01분 00초에 실행 - public void metaverServerScheduler() { - log.info("run metaverServerScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - int serverCount = 13; - metaverseServerService.collectMetaverseServerCount(startEndTime.getStartTime(), startEndTime.getEndTime(), serverCount); - log.info("end metaverServerScheduler"); - } - - /* - 매일 UTC 기준 00시 50분 00초에 실행, (한국 시간 9시 50분) 30분에 돌릴경우 데이터가 다 넘어 오지 않는 경우 있어서 수정처리 - 이게 가장 먼저 실행 되어야 한다. - 로그가 많을 경우 성능 이슈 있을 수 있음 - */ - @Scheduled(cron = "0 50 0 * * *") - public void auScheduler() { - //이걸 나중에 어떻게 활용할지 생각해보자. - log.info("run auScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - auService.collectActiveUser(startEndTime.getStartTime(), startEndTime.getEndTime()); - log.info("end auScheduler"); - } - - @Scheduled(cron = "00 55 0 * * *") // 매일 UTC 기준 00시 55분 00초에 실행 - public void dauScheduler() { - log.info("run dauScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - dauService.collectDailyActiveUser(startEndTime.getStartTime(), startEndTime.getEndTime()); - log.info("end dauScheduler"); - } - - @Scheduled(cron = "00 56 0 * * *") // 매일 UTC 기준 00시 56분 00초에 실행 - public void wauScheduler() { - log.info("run wauScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_WEEK_NUM); - wauService.collectWeeklyActiveUser(startEndTime.getStartTime(), startEndTime.getEndTime()); - log.info("end wauScheduler"); - } - - @Scheduled(cron = "00 57 0 * * *") // 매일 UTC 기준 00시 57분 00초에 실행 - public void mauScheduler() { - log.info("run mauScheduler"); -// int monthLength = CommonUtils.getLengthOfLastMonth(LocalDate.now()); // 지난달 총일수 가져오기 - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_MONTH_NUM); - mauService.collectMonthlyActiveUser(startEndTime.getStartTime(), startEndTime.getEndTime()); - log.info("end mauScheduler"); - } - - @Scheduled(cron = "00 58 0 * * *") // 매일 UTC 기준 00시 58분 00초에 실행 - public void mcuScheduler() { - log.info("run mcuScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - mcuService.collectMaxCountUser(startEndTime.getStartTime(), startEndTime.getEndTime()); - log.info("end mcuScheduler"); - } - - @Scheduled(cron = "00 59 0 * * *") // 매일 UTC 기준 00시 59분 00초에 실행 - public void nruScheduler() { - log.info("run nruScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - nruService.collectCharacterCreateCount(startEndTime.getStartTime(), startEndTime.getEndTime()); - log.info("end nruScheduler"); - } - - @Scheduled(cron = "00 00 1 * * *") // 매일 UTC 기준 1시 00분 00초에 실행 - public void playTimeScheduler() { - log.info("run playTimeScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - playTimeService.collectUserPlayTime(startEndTime.getStartTime(), startEndTime.getEndTime()); - log.info("end playTimeScheduler"); - } - - @Scheduled(cron = "00 01 1 * * *") // 매일 UTC 기준 01시 01분 00초에 실행 - public void dglcScheduler() { - log.info("run dglcScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - dglcService.collectDailyGameLoginCount(startEndTime.getStartTime(), startEndTime.getEndTime()); - log.info("end dglcScheduler"); - } - - @Scheduled(cron = "00 00 2 * * *") // 매일 UTC 기준 02시 00분 00초에 실행 (Log 데이터가 늦게 넘어올때가 있기때문에 나중에 실행) - public void ugqCreateScheduler() { - log.info("run ugqCreateScheduler"); - StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); - ugqCreateService.collectUGQCreateCount(startEndTime.getStartTime(), startEndTime.getEndTime()); - log.info("end ugqCreateScheduler"); - } - - - @Scheduled(cron = "0 * * * * *") // 매 분 00초에 실행 - public void runJob() { - //log.info("run runJob"); - } - - @Scheduled(cron = "1 * * * * *") - public void noticeJob(){ - log.info("run noticeJob"); - dynamicScheduler.noticeSchedule(); - log.info("end noticeJob"); - } - - @Scheduled(cron = "2 * * * * *") - public void mailJob(){ - log.info("run mailJob"); - dynamicScheduler.mailSchedule(); - log.info("end mailJob"); - } - - @Scheduled(cron = "3 * * * * *") - public void blackListJob(){ - log.info("run blackListJob"); - dynamicScheduler.blackListSchedule(); - log.info("end blackListJob"); - } - - @Scheduled(cron = "4 * * * * *") - public void eventJob(){ - log.info("run eventJob"); - dynamicScheduler.eventSchedule(); - log.info("end eventJob"); - } - - //web3 - @Scheduled(cron = "1 * * * * *") - public void web3Job(){ - log.info("run web3Job"); - caliumService.getScheduleCaliumRequestList(); - log.info("end web3Job"); - } -} diff --git a/src/main/java/com/caliverse/admin/scheduler/SchedulerManager.java b/src/main/java/com/caliverse/admin/scheduler/SchedulerManager.java index c412351..3cfe043 100644 --- a/src/main/java/com/caliverse/admin/scheduler/SchedulerManager.java +++ b/src/main/java/com/caliverse/admin/scheduler/SchedulerManager.java @@ -1,5 +1,7 @@ package com.caliverse.admin.scheduler; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.global.common.annotation.BusinessProcess; import com.caliverse.admin.scheduler.entity.SchedulerType; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/caliverse/admin/scheduler/batch/ScheduleRunnerBatch.java b/src/main/java/com/caliverse/admin/scheduler/batch/ScheduleRunnerBatch.java index dee9d1b..2147477 100644 --- a/src/main/java/com/caliverse/admin/scheduler/batch/ScheduleRunnerBatch.java +++ b/src/main/java/com/caliverse/admin/scheduler/batch/ScheduleRunnerBatch.java @@ -1,6 +1,7 @@ package com.caliverse.admin.scheduler.batch; import com.caliverse.admin.global.common.constants.AdminConstants; +import com.caliverse.admin.global.common.utils.CommonUtils; import com.caliverse.admin.logs.Indicatordomain.StartEndTime; import com.caliverse.admin.logs.logservice.LogServiceHelper; import com.caliverse.admin.logs.logservice.indicators.*; @@ -14,6 +15,8 @@ import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; +import java.time.LocalDate; + @Component @Slf4j @EnableScheduling @@ -30,6 +33,18 @@ public class ScheduleRunnerBatch { @Autowired private IndicatorsCurrencyService currencyService; @Autowired private IndicatorsItemService itemService; + @Autowired private IndicatorsAuService auService; + @Autowired private IndicatorsDauService dauService; + @Autowired private IndicatorsWauService wauService; + @Autowired private IndicatorsMauService mauService; + @Autowired private IndicatorsMcuService mcuService; + @Autowired private IndicatorsNruService nruService; + @Autowired private IndicatorsPlayTimeService playTimeService; + @Autowired private IndicatorsDglcService dglcService; + @Autowired private IndicatorsDBCapacityService capacityService; + @Autowired private IndicatorsUgqCreateService ugqCreateService; + @Autowired private IndicatorsMetaverseServerService metaverseServerService; + //log backup @Scheduled(cron = "00 00 00 1 * ?") // 매월 1일에 실행 public void logJob(){ @@ -66,4 +81,67 @@ public class ScheduleRunnerBatch { itemService.collectItem(startEndTime.getStartTime(), startEndTime.getEndTime()); } + @Scheduled(cron = "0 01 0 * * *") // 매일 UTC 기준 00시 01분 00초에 실행 + public void capacityScheduler() { + StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); + capacityService.collectDBCapacity(startEndTime.getStartTime(), startEndTime.getEndTime()); + } + + @Scheduled(cron = "0 02 0 * * *") // 매일 UTC 기준 00시 02분 00초에 실행 + public void metaverServerScheduler() { + StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); + int serverCount = 13; + metaverseServerService.collectMetaverseServerCount(startEndTime.getStartTime(), startEndTime.getEndTime(), serverCount); + } + + @Scheduled(cron = "00 55 0 * * *") // 매일 UTC 기준 00시 55분 00초에 실행 + public void dauScheduler() { + StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); + dauService.collectDailyActiveUser(startEndTime.getStartTime(), startEndTime.getEndTime()); + } + + @Scheduled(cron = "00 56 0 * * *") // 매일 UTC 기준 00시 56분 00초에 실행 + public void wauScheduler() { + StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_WEEK_NUM); + wauService.collectWeeklyActiveUser(startEndTime.getStartTime(), startEndTime.getEndTime()); + } + + // @Scheduled(cron = "00 57 0 * * *") // 매일 UTC 기준 00시 57분 00초에 실행 + @Scheduled(cron = "00 57 0 1 * ?") // 매월 1일 UTC 기준 00시 57분 00초에 실행 + public void mauScheduler() { + int monthLength = CommonUtils.getLengthOfLastMonth(LocalDate.now()); // 지난달 총일수 가져오기 + StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(monthLength); + mauService.collectMonthlyActiveUser(startEndTime.getStartTime(), startEndTime.getEndTime()); + } + + @Scheduled(cron = "00 58 0 * * *") // 매일 UTC 기준 00시 58분 00초에 실행 + public void mcuScheduler() { + StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); + mcuService.collectMaxCountUser(startEndTime.getStartTime(), startEndTime.getEndTime()); + } + + @Scheduled(cron = "00 59 0 * * *") // 매일 UTC 기준 00시 59분 00초에 실행 + public void nruScheduler() { + StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); + nruService.collectCharacterCreateCount(startEndTime.getStartTime(), startEndTime.getEndTime()); + } + + @Scheduled(cron = "00 00 1 * * *") // 매일 UTC 기준 1시 00분 00초에 실행 + public void playTimeScheduler() { + StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); + playTimeService.collectUserPlayTime(startEndTime.getStartTime(), startEndTime.getEndTime()); + } + + @Scheduled(cron = "00 01 1 * * *") // 매일 UTC 기준 01시 01분 00초에 실행 + public void dglcScheduler() { + StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); + dglcService.collectDailyGameLoginCount(startEndTime.getStartTime(), startEndTime.getEndTime()); + } + + @Scheduled(cron = "00 00 2 * * *") // 매일 UTC 기준 02시 00분 00초에 실행 (Log 데이터가 늦게 넘어올때가 있기때문에 나중에 실행) + public void ugqCreateScheduler() { + StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM); + ugqCreateService.collectUGQCreateCount(startEndTime.getStartTime(), startEndTime.getEndTime()); + } + } diff --git a/src/main/java/com/caliverse/admin/scheduler/polling/ScheduleRunnerPolling.java b/src/main/java/com/caliverse/admin/scheduler/polling/ScheduleRunnerPolling.java index 6fdd7a4..54cc134 100644 --- a/src/main/java/com/caliverse/admin/scheduler/polling/ScheduleRunnerPolling.java +++ b/src/main/java/com/caliverse/admin/scheduler/polling/ScheduleRunnerPolling.java @@ -1,24 +1,14 @@ package com.caliverse.admin.scheduler.polling; -import com.caliverse.admin.domain.response.DataResponse; -import com.caliverse.admin.global.common.code.CommonCode; -import com.caliverse.admin.global.common.code.ErrorCode; import com.caliverse.admin.scheduler.SchedulerManager; import com.caliverse.admin.scheduler.entity.SchedulerType; -import com.caliverse.admin.domain.RabbitMq.MessageHandlerService; import com.caliverse.admin.domain.service.*; -import com.caliverse.admin.global.common.utils.ExcelUtils; -import com.caliverse.admin.logs.logservice.indicators.*; -import com.caliverse.admin.redis.service.RedisUserInfoService; -import com.caliverse.admin.scheduler.DynamicScheduler; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; // import org.springframework.batch.core.JobParameters; // import org.springframework.batch.core.JobParametersBuilder; // import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @@ -31,35 +21,13 @@ import lombok.extern.slf4j.Slf4j; @EnableScheduling @RequiredArgsConstructor public class ScheduleRunnerPolling { - @Autowired private IndicatorsAuService auService; - @Autowired private IndicatorsDauService dauService; - @Autowired private IndicatorsWauService wauService; - @Autowired private IndicatorsMauService mauService; - @Autowired private IndicatorsMcuService mcuService; - @Autowired private IndicatorsNruService statNruService; - - @Autowired private RedisUserInfoService userInfoService; - @Autowired private DynamicScheduler dynamicScheduler; - @Autowired private MailService mailService; - @Autowired private NoticeService noticeService; - @Autowired private BlackListService blackListService; - @Autowired private EventService eventService; - @Autowired - private RedisUserInfoService redisUserInfoService; - @Autowired - private MessageHandlerService messageHandlerService; - @Autowired - private ExcelUtils excelUtils; - private final SchedulerManager schedulerManager; + + @Autowired private CaliumService caliumService; + @Value("${spring.profiles.active}") private String activeProfile; - @Scheduled(cron = "7 * * * * *") - public void landOwnerChangesJob(){ - schedulerManager.executeScheduler(SchedulerType.LAND_OWNER_CHANGES); - } - @Scheduled(cron = "1 * * * * *") public void dataInitializeJob(){ if(activeProfile.equals("live")){ @@ -73,6 +41,46 @@ public class ScheduleRunnerPolling { schedulerManager.executeScheduler(SchedulerType.CLEAN_UP); } + @Scheduled(cron = "1 * * * * *") + public void web3Job(){ + caliumService.getScheduleCaliumRequestList(); + } + + @Scheduled(cron = "1 * * * * *") + public void noticeJob(){ + schedulerManager.executeScheduler(SchedulerType.NOTICE); + } + + @Scheduled(cron = "2 * * * * *") + public void mailJob(){ + schedulerManager.executeScheduler(SchedulerType.MAIL); + } + + @Scheduled(cron = "3 * * * * *") + public void blackListJob(){ + schedulerManager.executeScheduler(SchedulerType.BLACKLIST); + } + + @Scheduled(cron = "4 * * * * *") + public void eventJob(){ + schedulerManager.executeScheduler(SchedulerType.EVENT); + } + + @Scheduled(cron = "5 * * * * *") + public void landAuctionJob(){ + schedulerManager.executeScheduler(SchedulerType.LAND_AUCTION); + } + + @Scheduled(cron = "6 * * * * *") + public void battleEventJob(){ + schedulerManager.executeScheduler(SchedulerType.BATTLE_EVENT); + } + + @Scheduled(cron = "7 * * * * *") + public void landOwnerChangesJob(){ + schedulerManager.executeScheduler(SchedulerType.LAND_OWNER_CHANGES); + } + /* 매일 UTC 기준 00시 50분 00초에 실행, (한국 시간 9시 50분) 30분에 돌릴경우 데이터가 다 넘어 오지 않는 경우 있어서 수정처리 이게 가장 먼저 실행 되어야 한다. diff --git a/src/main/java/com/caliverse/admin/scheduler/polling/service/BattleEventScheduler.java b/src/main/java/com/caliverse/admin/scheduler/polling/service/BattleEventScheduler.java new file mode 100644 index 0000000..0a4569d --- /dev/null +++ b/src/main/java/com/caliverse/admin/scheduler/polling/service/BattleEventScheduler.java @@ -0,0 +1,153 @@ +package com.caliverse.admin.scheduler.polling.service; + +import com.caliverse.admin.domain.entity.BattleEvent; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; +import com.caliverse.admin.domain.service.BattleEventService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; +import com.caliverse.admin.mongodb.service.BusinessLogService; +import com.caliverse.admin.scheduler.CommonScheduler; +import com.caliverse.admin.scheduler.entity.SchedulerType; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +@Slf4j +@Component +public class BattleEventScheduler extends CommonScheduler { + private final BattleEventService battleEventService; + + public BattleEventScheduler(BattleEventService battleEventService, + BusinessLogService businessLogService) { + super(businessLogService); + this.battleEventService = battleEventService; + } + + @BusinessProcess(action = LogAction.SCHEDULE_BATTLE_EVENT) + @Override + protected void executeInternal() { + List eventList = battleEventService.getScheduleBattleEventList(); + + LocalDateTime startTime = LocalDateTime.now(); + List processedEventIds = new ArrayList<>(); + AtomicInteger runningCount = new AtomicInteger(0); + AtomicInteger endCount = new AtomicInteger(0); + AtomicInteger waitCount = new AtomicInteger(0); + AtomicInteger stopCount = new AtomicInteger(0); + + try{ + eventList.forEach(event -> { + BattleEvent.BATTLE_STATUS status = event.getStatus(); + LocalDateTime start_dt = event.getEventStartDt(); + LocalTime startTimeOfDay = start_dt.toLocalTime(); + + LocalDateTime now = LocalDateTime.now(); + LocalTime currentTime = LocalDateTime.now().toLocalTime(); + LocalDateTime end_dt = event.getEventEndDt(); + int operation_time = event.getEventOperationTime(); + + LocalTime endTimeOfDay = startTimeOfDay .plusSeconds(operation_time); + + // 현재시간이 자정을 넘어간 경우(00:00 ~ endTime)라면 전날을 기준으로 + LocalDate baseDate; + if (startTimeOfDay .isAfter(endTimeOfDay)) { // 시작시간이 종료시간보다 늦은 경우 (자정을 걸치는 경우) + if (currentTime.isBefore(endTimeOfDay)) { + // 현재시간이 00:00 ~ endTime 사이면 전날 기준 + baseDate = now.toLocalDate().minusDays(1); + } else if (!currentTime.isBefore(startTimeOfDay )) { + // 현재시간이 startTime 이후면 현재 날짜 기준 + baseDate = now.toLocalDate(); + } else { + baseDate = now.toLocalDate(); + } + } else { + // 자정을 걸치지 않는 일반적인 경우 + baseDate = now.toLocalDate(); + } + + //오늘자 기준 시작, 종료 시간 + LocalDateTime todayStart = LocalDateTime.of(baseDate, startTimeOfDay ); + LocalDateTime todayEnd = todayStart.plusSeconds(operation_time); + + BattleEvent.BATTLE_STATUS change_status = null; + + Map map = new HashMap<>(); + map.put("id", event.getId()); + + if(status.equals(BattleEvent.BATTLE_STATUS.REGISTER) || status.equals(BattleEvent.BATTLE_STATUS.WAIT)){ + if(!now.isBefore(start_dt) && (!now.isBefore(todayStart) && !now.isAfter(todayEnd))){ + log.info("battle event_id: {}, start_dt: {}, todayStart: {}, todayEnd: {} STATUS CHANGE RUNNING", event.getId(), start_dt, todayStart, todayEnd); + change_status = BattleEvent.BATTLE_STATUS.RUNNING; + map.put("status", change_status); + battleEventService.updateBattleEventStatus(map); + + processedEventIds.add(event.getId()); + runningCount.incrementAndGet(); + } + }else if(status.equals(BattleEvent.BATTLE_STATUS.RUNNING) || status.equals(BattleEvent.BATTLE_STATUS.STOP)){ + if(!(!now.isBefore(todayStart) && !now.isAfter(todayEnd))){ + if(!baseDate.isBefore(end_dt.toLocalDate())){ + change_status = BattleEvent.BATTLE_STATUS.END; + endCount.incrementAndGet(); + }else{ + change_status = status.equals(BattleEvent.BATTLE_STATUS.STOP) ? BattleEvent.BATTLE_STATUS.STOP : BattleEvent.BATTLE_STATUS.WAIT; + if (change_status.equals(BattleEvent.BATTLE_STATUS.STOP)) { + stopCount.incrementAndGet(); + } else { + waitCount.incrementAndGet(); + } + } + log.info("battle event_id: {}, start_dt: {}, end_dt: {}, todayStart: {}, todayEnd: {} STATUS CHANGE {}", event.getId(), start_dt, end_dt, todayStart, todayEnd, change_status); + map.put("status", change_status); + battleEventService.updateBattleEventStatus(map); + + processedEventIds.add(event.getId()); + } + } + }); + + if (!processedEventIds.isEmpty()) { + businessLogService.logScheduler( + LogStatus.SUCCESS, + String.format("배틀 이벤트 스케줄 처리 완료: 총 %d건 처리 (시작: %d, 종료: %d, 대기: %d, 중지: %d)", + processedEventIds.size(), + runningCount.get(), + endCount.get(), + waitCount.get(), + stopCount.get()), + "BATTLE_EVENT_SCHEDULER", + startTime, + LocalDateTime.now(), + Map.of( + "totalEventCount", eventList.size(), + "processedCount", processedEventIds.size(), + "processedEventIds", processedEventIds, + "runningCount", runningCount.get(), + "endCount", endCount.get(), + "waitCount", waitCount.get(), + "stopCount", stopCount.get() + ) + ); + + log.info("Battle event scheduler completed: {} items processed out of {} total", + processedEventIds.size(), eventList.size()); + } + }catch(Exception e){ + log.error("battleEventSchedule Exception: {}", e.getMessage()); + throw e; + } + } + + @Override + public SchedulerType getSchedulerType() { + return SchedulerType.BATTLE_EVENT; + } +} diff --git a/src/main/java/com/caliverse/admin/scheduler/polling/service/BlackListScheduler.java b/src/main/java/com/caliverse/admin/scheduler/polling/service/BlackListScheduler.java new file mode 100644 index 0000000..f8d512f --- /dev/null +++ b/src/main/java/com/caliverse/admin/scheduler/polling/service/BlackListScheduler.java @@ -0,0 +1,118 @@ +package com.caliverse.admin.scheduler.polling.service; + +import com.caliverse.admin.domain.entity.BlackList; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; +import com.caliverse.admin.domain.service.BlackListService; +import com.caliverse.admin.domain.service.UserGameSessionService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; +import com.caliverse.admin.mongodb.service.BusinessLogService; +import com.caliverse.admin.scheduler.CommonScheduler; +import com.caliverse.admin.scheduler.entity.SchedulerType; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +@Slf4j +@Component +public class BlackListScheduler extends CommonScheduler { + + private final UserGameSessionService userGameSessionService; + private final BlackListService blackListService; + + public BlackListScheduler(UserGameSessionService userGameSessionService, + BlackListService blackListService, + BusinessLogService businessLogService) { + super(businessLogService); + this.userGameSessionService = userGameSessionService; + this.blackListService = blackListService; + } + + @BusinessProcess(action = LogAction.SCHEDULE_BLACK_LIST) + @Override + protected void executeInternal() { + List blackList = blackListService.getScheduleBlackList(); + + LocalDateTime startTime = LocalDateTime.now(); + List processedBlackListIds = new ArrayList<>(); + AtomicInteger timeoutFailCount = new AtomicInteger(0); + AtomicInteger blockStartedCount = new AtomicInteger(0); + AtomicInteger blockExpiredCount = new AtomicInteger(0); + + try{ + LocalDateTime nowDate = LocalDateTime.now(); + blackList.forEach(blockUser -> { + BlackList.STATUSTYPE status = blockUser.getStatus(); + + // WAIT 상태 처리 + if(status == BlackList.STATUSTYPE.WAIT) { + if(nowDate.isAfter(blockUser.getEndDt())) { + // 만료시간 초과 - FAIL 처리 + blackListService.updateBlackListStatus(blockUser.getId(), BlackList.STATUSTYPE.FAIL); + + processedBlackListIds.add(blockUser.getId()); + timeoutFailCount.incrementAndGet(); + log.error("blackListJob blackListSchedule timeOut Fail id: {}, guid: {}", blockUser.getId(), blockUser.getGuid()); + } else if(!nowDate.isBefore(blockUser.getStartDt())) { + // 시작시간 도달 - INPROGRESS 처리 + userGameSessionService.kickUserSession(blockUser.getGuid(), "user block"); + blackListService.updateScheduleBlockUser(blockUser, BlackList.STATUSTYPE.INPROGRESS); + blackListService.updateBlackListStatus(blockUser.getId(), BlackList.STATUSTYPE.INPROGRESS); + + processedBlackListIds.add(blockUser.getId()); + blockStartedCount.incrementAndGet(); + log.info("blackListJob blackListSchedule block start id: {}, guid: {}", blockUser.getId(), blockUser.getGuid()); + } + } + // INPROGRESS 상태 처리 + else if(status == BlackList.STATUSTYPE.INPROGRESS && !nowDate.isBefore(blockUser.getEndDt())) { + // 만료시간 도달 - EXPIRATION 처리 + blackListService.updateScheduleBlockUser(blockUser, BlackList.STATUSTYPE.EXPIRATION); + blackListService.updateBlackListStatus(blockUser.getId(), BlackList.STATUSTYPE.EXPIRATION); + + processedBlackListIds.add(blockUser.getId()); + blockExpiredCount.incrementAndGet(); + log.info("blackListJob blackListSchedule block end id: {}, guid: {}", blockUser.getId(), blockUser.getGuid()); + } + }); + + if (!processedBlackListIds.isEmpty()) { + businessLogService.logScheduler( + LogStatus.SUCCESS, + String.format("블랙리스트 스케줄 처리 완료: 총 %d건 처리 (타임아웃실패: %d, 제재시작: %d, 제재만료: %d)", + processedBlackListIds.size(), + timeoutFailCount.get(), + blockStartedCount.get(), + blockExpiredCount.get()), + "BLACKLIST_SCHEDULER", + startTime, + LocalDateTime.now(), + Map.of( + "totalBlackListCount", blackList.size(), + "processedCount", processedBlackListIds.size(), + "processedBlackListIds", processedBlackListIds, + "timeoutFailCount", timeoutFailCount.get(), + "blockStartedCount", blockStartedCount.get(), + "blockExpiredCount", blockExpiredCount.get() + ) + ); + + log.info("BlackList scheduler completed: {} items processed out of {} total", + processedBlackListIds.size(), blackList.size()); + } + }catch (Exception e){ + log.error("blackListSchedule Exception: {}", e.getMessage()); + throw e; + } + } + + @Override + public SchedulerType getSchedulerType() { + return SchedulerType.BLACKLIST; + } +} diff --git a/src/main/java/com/caliverse/admin/scheduler/polling/service/DataInitializeScheduler.java b/src/main/java/com/caliverse/admin/scheduler/polling/service/DataInitializeScheduler.java index 8f56f34..4831cc2 100644 --- a/src/main/java/com/caliverse/admin/scheduler/polling/service/DataInitializeScheduler.java +++ b/src/main/java/com/caliverse/admin/scheduler/polling/service/DataInitializeScheduler.java @@ -4,6 +4,7 @@ import com.caliverse.admin.domain.entity.DataInit; import com.caliverse.admin.domain.entity.EInitDataType; import com.caliverse.admin.domain.entity.LandAuction; import com.caliverse.admin.domain.entity.LandOwnerChange; +import com.caliverse.admin.domain.entity.log.LogAction; import com.caliverse.admin.domain.request.LandRequest; import com.caliverse.admin.domain.service.DataService; import com.caliverse.admin.domain.service.LandService; @@ -12,6 +13,8 @@ import com.caliverse.admin.dynamodb.service.DynamodbDataService; import com.caliverse.admin.dynamodb.service.DynamodbLandAuctionService; import com.caliverse.admin.dynamodb.service.DynamodbLandService; import com.caliverse.admin.dynamodb.service.DynamodbService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; +import com.caliverse.admin.mongodb.service.BusinessLogService; import com.caliverse.admin.scheduler.CommonScheduler; import com.caliverse.admin.scheduler.entity.SchedulerType; import lombok.extern.slf4j.Slf4j; @@ -34,13 +37,19 @@ public class DataInitializeScheduler extends CommonScheduler { @Value("${spring.profiles.active}") private String activeProfile; - public DataInitializeScheduler(DataService dataService, DynamodbDataService dynamodbDataService, LandService landService, DynamodbLandAuctionService dynamodbLandAuctionService) { + public DataInitializeScheduler(DataService dataService, + DynamodbDataService dynamodbDataService, + LandService landService, + DynamodbLandAuctionService dynamodbLandAuctionService, + BusinessLogService businessLogService) { + super(businessLogService); this.dataService = dataService; this.dynamodbDataService = dynamodbDataService; this.landService = landService; this.dynamodbLandAuctionService = dynamodbLandAuctionService; } + @BusinessProcess(action = LogAction.SCHEDULE_DATA_INIT) @Override protected void executeInternal() { List scheduleList = dataService.getScheduleDataInitList(); @@ -57,6 +66,7 @@ public class DataInitializeScheduler extends CommonScheduler { }); } + @BusinessProcess(action = LogAction.DATA_INIT) private void initLandAuction(LocalDateTime createDt){ List landAuctions = landService.getAllLandAuctionList(); landAuctions.forEach(landAuction -> { @@ -67,10 +77,12 @@ public class DataInitializeScheduler extends CommonScheduler { dynamodbDataService.InitDataLandAuction(); } + @BusinessProcess(action = LogAction.DATA_INIT) private void initLandDesc(){ dynamodbDataService.InitDataLandDesc(); } + @BusinessProcess(action = LogAction.DATA_INIT) private void initLandOwner(LocalDateTime createDt){ List landOwnerChanges = landService.getAllLandOwnerChangesList(); landOwnerChanges.forEach(dataService::initLandOwned); diff --git a/src/main/java/com/caliverse/admin/scheduler/polling/service/EventScheduler.java b/src/main/java/com/caliverse/admin/scheduler/polling/service/EventScheduler.java new file mode 100644 index 0000000..30ba63a --- /dev/null +++ b/src/main/java/com/caliverse/admin/scheduler/polling/service/EventScheduler.java @@ -0,0 +1,110 @@ +package com.caliverse.admin.scheduler.polling.service; + +import com.caliverse.admin.domain.entity.Event; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; +import com.caliverse.admin.domain.service.EventService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; +import com.caliverse.admin.mongodb.service.BusinessLogService; +import com.caliverse.admin.scheduler.CommonScheduler; +import com.caliverse.admin.scheduler.entity.SchedulerType; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +@Slf4j +@Component +public class EventScheduler extends CommonScheduler { + private final EventService eventService; + + public EventScheduler(EventService eventService, + BusinessLogService businessLogService) { + super(businessLogService); + this.eventService = eventService; + } + + @BusinessProcess(action = LogAction.SCHEDULE_EVENT) + @Override + protected void executeInternal() { + List eventList = eventService.getScheduleMailList(); + + LocalDateTime startTime = LocalDateTime.now(); + List processedEventIds = new ArrayList<>(); + AtomicInteger timeoutCount = new AtomicInteger(0); + AtomicInteger systemMailInsertedCount = new AtomicInteger(0); + AtomicInteger finishedCount = new AtomicInteger(0); + + try{ + eventList.forEach(event -> { + LocalDateTime nowDate = LocalDateTime.now(); + LocalDateTime eventStartTime = event.getStartDt(); + LocalDateTime endTime = event.getEndDt(); + + if(nowDate.isAfter(endTime) && event.getStatus().equals(Event.EVENTSTATUS.WAIT)){ + eventService.updateEventStatus(event.getId(), Event.EVENTSTATUS.FAIL); + + processedEventIds.add(event.getId()); + timeoutCount.incrementAndGet(); + log.error("eventJob eventSchedule timeOut : {}", event); + return; + } + + // 시작시간이 30분 남았을때 게임DB에 insert 해준다(서버에서 캐시 등록) + if (event.getStatus().equals(Event.EVENTSTATUS.WAIT) && Duration.between(nowDate, eventStartTime ).abs().toMinutes() <= 30 && !event.isAddFlag()) { + eventService.insertSystemMail(event); + + processedEventIds.add(event.getId()); + systemMailInsertedCount.incrementAndGet(); + log.info("eventJob eventSchedule dynamoDB Insert & Start: {}", event); + } + + if(!nowDate.isBefore(endTime) && event.getStatus().equals(Event.EVENTSTATUS.RUNNING)){ + eventService.updateEventStatus(event.getId(), Event.EVENTSTATUS.FINISH); + + processedEventIds.add(event.getId()); + finishedCount.incrementAndGet(); + log.info("eventJob eventSchedule block end : {}", event); + } + }); + + if (!processedEventIds.isEmpty()) { + businessLogService.logScheduler( + LogStatus.SUCCESS, + String.format("이벤트 스케줄 처리 완료: 총 %d건 처리 (타임아웃: %d, 시스템메일등록: %d, 종료: %d)", + processedEventIds.size(), + timeoutCount.get(), + systemMailInsertedCount.get(), + finishedCount.get()), + "EVENT_SCHEDULER", + startTime, + LocalDateTime.now(), + Map.of( + "totalEventCount", eventList.size(), + "processedCount", processedEventIds.size(), + "processedEventIds", processedEventIds, + "timeoutCount", timeoutCount.get(), + "systemMailInsertedCount", systemMailInsertedCount.get(), + "finishedCount", finishedCount.get() + ) + ); + + log.info("Event scheduler completed: {} items processed out of {} total", + processedEventIds.size(), eventList.size()); + } + }catch (Exception e){ + log.error("eventSchedule Exception: {}", e.getMessage()); + throw e; + } + } + + @Override + public SchedulerType getSchedulerType() { + return SchedulerType.EVENT; + } +} diff --git a/src/main/java/com/caliverse/admin/scheduler/polling/service/LandAuctionScheduler.java b/src/main/java/com/caliverse/admin/scheduler/polling/service/LandAuctionScheduler.java new file mode 100644 index 0000000..e696776 --- /dev/null +++ b/src/main/java/com/caliverse/admin/scheduler/polling/service/LandAuctionScheduler.java @@ -0,0 +1,173 @@ +package com.caliverse.admin.scheduler.polling.service; + +import com.caliverse.admin.domain.entity.LandAuction; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; +import com.caliverse.admin.domain.service.LandService; +import com.caliverse.admin.dynamodb.domain.atrrib.LandAuctionHighestBidUserAttrib; +import com.caliverse.admin.dynamodb.domain.atrrib.LandAuctionRegistryAttrib; +import com.caliverse.admin.dynamodb.entity.ELandAuctionResult; +import com.caliverse.admin.dynamodb.entity.ELandAuctionState; +import com.caliverse.admin.global.common.annotation.BusinessProcess; +import com.caliverse.admin.global.common.utils.CommonUtils; +import com.caliverse.admin.mongodb.service.BusinessLogService; +import com.caliverse.admin.scheduler.CommonScheduler; +import com.caliverse.admin.scheduler.entity.SchedulerType; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +@Slf4j +@Component +public class LandAuctionScheduler extends CommonScheduler { + private final LandService landService; + + public LandAuctionScheduler(LandService landService, + BusinessLogService businessLogService) { + super(businessLogService); + this.landService = landService; + } + + @BusinessProcess(action = LogAction.SCHEDULE_LAND_AUCTION) + @Override + protected void executeInternal() { + List auctionList = landService.getScheduleLandAuctionList(); + + LocalDateTime startTime = LocalDateTime.now(); + List processedAuctionIds = new ArrayList<>(); + AtomicInteger scheduledCount = new AtomicInteger(0); + AtomicInteger startedCount = new AtomicInteger(0); + AtomicInteger endedSuccessCount = new AtomicInteger(0); + AtomicInteger endedFailCount = new AtomicInteger(0); + AtomicInteger canceledCount = new AtomicInteger(0); + + try{ + auctionList.forEach(auction -> { + LocalDateTime nowDate = LocalDateTime.now(); + LocalDateTime reservationDate = auction.getResvStartDt(); + LocalDateTime auctionStartDate = auction.getAuctionStartDt(); + LocalDateTime auctionEndDate = auction.getAuctionEndDt(); + + LandAuction.AUCTION_STATUS auction_status = auction.getStatus(); + + //예약 시작시간이 되지않으면 체크하지 않는다 + if(nowDate.isBefore(reservationDate)){ + return; + } + + //예약일때 경매 시작시간이 되지않았다면 체크하지 않는다 + if(auction_status.equals(LandAuction.AUCTION_STATUS.RESV_START) && nowDate.isBefore(auctionStartDate)){ + return; + } + + // 비정상종료일때가 있다고 상시체크로 해달라고 함(23.02.18) + // 경매중일때 경매 종료시간이 되지않았다면 체크하지 않는다 +// if(auction_status.equals(LandAuction.AUCTION_STATUS.AUCTION_START) && nowDate.isBefore(auctionEndDate)){ +// return; +// } + + Map map = new HashMap<>(); + map.put("id", auction.getId()); + + LandAuctionRegistryAttrib attrib = landService.getLandAuctionRegistryAttrib(auction.getLandId(), auction.getAuctionSeq()); + if(attrib == null) return; + String dynamodb_auction_state = attrib.getAuctionState(); + LandAuction.AUCTION_STATUS change_status = null; + + if(dynamodb_auction_state.equals(ELandAuctionState.SCHEDULED.getName())){ + change_status = LandAuction.AUCTION_STATUS.RESV_START; + map.put("status", change_status); + landService.updateLandAuctionStatus(map); + + processedAuctionIds.add(auction.getId()); + scheduledCount.incrementAndGet(); + log.info("land_auction id: {} Status Schedule Changed", auction.getId()); + }else if(dynamodb_auction_state.equals(ELandAuctionState.STARTED.getName())){ + change_status = LandAuction.AUCTION_STATUS.AUCTION_START; + map.put("status", change_status); + landService.updateLandAuctionStatus(map); + + processedAuctionIds.add(auction.getId()); + startedCount.incrementAndGet(); + log.info("land_auction id: {} Status Auction Start Changed", auction.getId()); + }else if(dynamodb_auction_state.equals(ELandAuctionState.ENDED.getName())){ + String result = attrib.getAuctionResult(); + + if(result.equals(ELandAuctionResult.SUCCESSED.getName())){ + LandAuctionHighestBidUserAttrib bidUser = landService.getLandAuctionHighestUserAttrib(auction.getLandId(), auction.getAuctionSeq()); + if(bidUser == null) return; + + log.info("land_auction id: {} Status SUCCESS Changed. bidUser: {}", auction.getId(), bidUser); + + String close_dt = CommonUtils.convertIsoByDatetime(attrib.getProcessVersionTime()); + change_status = LandAuction.AUCTION_STATUS.AUCTION_END; + map.put("status", change_status); + map.put("closeEndDt", close_dt); + map.put("bidderGuid", bidUser.getHighestBidUserGuid()); + map.put("bidderNickname", bidUser.getHighestBidUserNickname()); + map.put("closePrice", bidUser.getHighestBidPrice()); + landService.updateLandAuctionStatus(map); + + processedAuctionIds.add(auction.getId()); + endedSuccessCount.incrementAndGet(); + }else{ + processedAuctionIds.add(auction.getId()); + + if(result.equals(ELandAuctionResult.CANCELED.getName())){ + change_status = LandAuction.AUCTION_STATUS.CANCEL; + map.put("status", change_status); + }else{ + change_status = LandAuction.AUCTION_STATUS.FAIL; + map.put("status", change_status); + } + log.info("land_auction id: {} Status {} Changed.", auction.getId(), change_status); + landService.updateLandAuctionStatus(map); + } + } + }); + + if (!processedAuctionIds.isEmpty()) { + businessLogService.logScheduler( + LogStatus.SUCCESS, + String.format("토지 경매 스케줄 처리 완료: 총 %d건 처리 (예약시작: %d, 경매시작: %d, 성공종료: %d, 실패종료: %d, 취소: %d)", + processedAuctionIds.size(), + scheduledCount.get(), + startedCount.get(), + endedSuccessCount.get(), + endedFailCount.get(), + canceledCount.get()), + "LAND_AUCTION_SCHEDULER", + startTime, + LocalDateTime.now(), + Map.of( + "totalAuctionCount", auctionList.size(), + "processedCount", processedAuctionIds.size(), + "processedAuctionIds", processedAuctionIds, + "scheduledCount", scheduledCount.get(), + "startedCount", startedCount.get(), + "endedSuccessCount", endedSuccessCount.get(), + "endedFailCount", endedFailCount.get(), + "canceledCount", canceledCount.get() + ) + ); + + log.info("Land auction scheduler completed: {} items processed out of {} total", + processedAuctionIds.size(), auctionList.size()); + } + } catch (Exception e){ + log.error("landAuctionSchedule Exception: {}", e.getMessage()); + throw e; + } + } + + @Override + public SchedulerType getSchedulerType() { + return SchedulerType.LAND_AUCTION; + } +} diff --git a/src/main/java/com/caliverse/admin/scheduler/polling/service/LandOwnerChangesScheduler.java b/src/main/java/com/caliverse/admin/scheduler/polling/service/LandOwnerChangesScheduler.java index bcb3fc1..ae9f58a 100644 --- a/src/main/java/com/caliverse/admin/scheduler/polling/service/LandOwnerChangesScheduler.java +++ b/src/main/java/com/caliverse/admin/scheduler/polling/service/LandOwnerChangesScheduler.java @@ -1,8 +1,12 @@ package com.caliverse.admin.scheduler.polling.service; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; import com.caliverse.admin.domain.service.UserGameSessionService; import com.caliverse.admin.dynamodb.service.DynamodbMailService; import com.caliverse.admin.dynamodb.service.DynamodbService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; +import com.caliverse.admin.mongodb.service.BusinessLogService; import com.caliverse.admin.scheduler.CommonScheduler; import com.caliverse.admin.scheduler.entity.SchedulerType; import com.caliverse.admin.domain.entity.LandOwnerChange; @@ -13,6 +17,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import java.time.LocalDateTime; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -26,50 +31,90 @@ public class LandOwnerChangesScheduler extends CommonScheduler { private final DynamodbMailService dynamodbMailService; private final UserGameSessionService userGameSessionService; - public LandOwnerChangesScheduler(LandService landService, DynamodbLandService dynamodbLandService, DynamodbMailService dynamodbMailService, UserGameSessionService userGameSessionService) { + public LandOwnerChangesScheduler(LandService landService, + DynamodbLandService dynamodbLandService, + DynamodbMailService dynamodbMailService, + UserGameSessionService userGameSessionService, + BusinessLogService businessLogService) { + super(businessLogService); this.landService = landService; this.dynamodbLandService = dynamodbLandService; this.dynamodbMailService = dynamodbMailService; this.userGameSessionService = userGameSessionService; } + @BusinessProcess(action = LogAction.SCHEDULE_LAND_OWNER_CHANGE) @Override protected void executeInternal() { List scheduleList = landService.getScheduleLandOwnerChangesList(); - scheduleList.forEach(landOwnerChange -> { - LandOwnerChange.CHANGE_STATUS status = landOwnerChange.getStatus(); - LocalDateTime reserve_dt = landOwnerChange.getReservationDt(); - int landId = landOwnerChange.getLandId(); - String guid = landOwnerChange.getUserGuid(); + LocalDateTime startTime = LocalDateTime.now(); + List processedIds = new ArrayList<>(); + List processedLandIds = new ArrayList<>(); - LocalDateTime now = LocalDateTime.now(); + try { + scheduleList.forEach(landOwnerChange -> { + LandOwnerChange.CHANGE_STATUS status = landOwnerChange.getStatus(); + LocalDateTime reserve_dt = landOwnerChange.getReservationDt(); + int landId = landOwnerChange.getLandId(); + String guid = landOwnerChange.getUserGuid(); - if(status.equals(LandOwnerChange.CHANGE_STATUS.WAIT) && reserve_dt.isBefore(now)) { - LandRequest landRequest = LandRequest.builder() - .landId(landId) - .landName(landOwnerChange.getLandName()) - .buildingId(landOwnerChange.getBuildingId()) - .buildingName(landOwnerChange.getBuildingName()) - .userGuid(guid) - .userName(landOwnerChange.getUserName()) - .build(); + LocalDateTime now = LocalDateTime.now(); - //유저킥 - userGameSessionService.kickUserSession(guid, "land owner changes"); + if (status.equals(LandOwnerChange.CHANGE_STATUS.WAIT) && reserve_dt.isBefore(now)) { + LandRequest landRequest = LandRequest.builder() + .landId(landId) + .landName(landOwnerChange.getLandName()) + .buildingId(landOwnerChange.getBuildingId()) + .buildingName(landOwnerChange.getBuildingName()) + .userGuid(guid) + .userName(landOwnerChange.getUserName()) + .build(); - //랜드정보 처리 - dynamodbLandService.ChangesLandOwner(landRequest); + //유저킥 + userGameSessionService.kickUserSession(guid, "land owner changes"); - Map map = new HashMap<>(); - map.put("id", landOwnerChange.getId()); - map.put("status", LandOwnerChange.CHANGE_STATUS.FINISH); - landService.updateLandOwnedChangeStatus(map); + //랜드정보 처리 + dynamodbLandService.ChangesLandOwner(landRequest); - //우편 - dynamodbMailService.insertLandChangesMail(landRequest); + Map map = new HashMap<>(); + map.put("id", landOwnerChange.getId()); + map.put("status", LandOwnerChange.CHANGE_STATUS.FINISH); + landService.updateLandOwnedChangeStatus(map); + + //우편 + dynamodbMailService.insertLandChangesMail(landRequest); + + processedIds.add(landOwnerChange.getId()); + processedLandIds.add(landId); + + log.info("Land owner change processed successfully: id={}, landId={}, userGuid={}", + landOwnerChange.getId(), landId, guid); + } + }); + + if (!processedIds.isEmpty()) { + businessLogService.logScheduler( + LogStatus.SUCCESS, + String.format("토지 소유자 변경 스케줄 처리 완료: %d건 처리", processedIds.size()), + "LAND_OWNER_CHANGES_SCHEDULER", + startTime, + LocalDateTime.now(), + Map.of( + "totalScheduleCount", scheduleList.size(), + "processedCount", processedIds.size(), + "processedIds", processedIds, + "processedLandIds", processedLandIds + ) + ); + + log.info("Land owner changes scheduler completed: {} items processed out of {} total", + processedIds.size(), scheduleList.size()); } - }); + }catch(Exception e){ + log.error("Land owner changes scheduler failed", e); + throw e; + } } @Override diff --git a/src/main/java/com/caliverse/admin/scheduler/polling/service/MailScheduler.java b/src/main/java/com/caliverse/admin/scheduler/polling/service/MailScheduler.java new file mode 100644 index 0000000..9e24960 --- /dev/null +++ b/src/main/java/com/caliverse/admin/scheduler/polling/service/MailScheduler.java @@ -0,0 +1,223 @@ +package com.caliverse.admin.scheduler.polling.service; + +import com.caliverse.admin.domain.RabbitMq.MessageHandlerService; +import com.caliverse.admin.domain.RabbitMq.message.LanguageType; +import com.caliverse.admin.domain.RabbitMq.message.MailItem; +import com.caliverse.admin.domain.RabbitMq.message.OperationSystemMessage; +import com.caliverse.admin.domain.entity.*; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; +import com.caliverse.admin.domain.entity.redis.RedisLoginInfo; +import com.caliverse.admin.domain.service.MailService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; +import com.caliverse.admin.global.common.utils.CommonUtils; +import com.caliverse.admin.global.common.utils.ExcelUtils; +import com.caliverse.admin.mongodb.service.BusinessLogService; +import com.caliverse.admin.redis.service.RedisUserInfoService; +import com.caliverse.admin.scheduler.CommonScheduler; +import com.caliverse.admin.scheduler.ScheduleService; +import com.caliverse.admin.scheduler.entity.SchedulerType; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +@Slf4j +@Component +public class MailScheduler extends CommonScheduler { + private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); + + private final MailService mailService; + private final RedisUserInfoService redisUserInfoService; + private final MessageHandlerService messageHandlerService; + private final ScheduleService schedulerService; + private final ExcelUtils excelUtils; + + public MailScheduler(MailService mailService, + RedisUserInfoService redisUserInfoService, + MessageHandlerService messageHandlerService, + ScheduleService schedulerService, + ExcelUtils excelUtils, + BusinessLogService businessLogService) { + super(businessLogService); + this.mailService = mailService; + this.redisUserInfoService = redisUserInfoService; + this.messageHandlerService = messageHandlerService; + this.schedulerService = schedulerService; + this.excelUtils = excelUtils; + } + + @BusinessProcess(action = LogAction.SCHEDULE_MAIL) + @Override + protected void executeInternal() { + List mailList = mailService.getScheduleMailList(); + + if (mailList.isEmpty()) { + return; + } + + AtomicInteger processedCount = new AtomicInteger(0); + AtomicInteger directSendCount = new AtomicInteger(0); + AtomicInteger scheduledCount = new AtomicInteger(0); + + LocalDateTime startTime = LocalDateTime.now(); + + try{ + mailList.forEach(mail -> { + if(mail.getSendStatus().equals(Mail.SENDSTATUS.WAIT)){ + processedCount.incrementAndGet(); + if(mail.getSendType() == Mail.SENDTYPE.DIRECT_SEND){ + directSendCount.incrementAndGet(); + log.info("mailJob mailSchedule direct run : {}", mail); + mailTypeProcess(mail); + }else { + String key = "mail-" + mail.getId(); + if (!schedulerService.isTaskExist(key)) { + scheduledCount.incrementAndGet(); + Runnable taskRunner = () -> { + log.info("mailJob mailSchedule schedule run : {}", mail); + mailTypeProcess(mail); + // 스케줄 해제 + schedulerService.closeTask(key); + }; + + // 시작일자 - 현재일자 + LocalDateTime startDate = mail.getSendDt(); + long initialDelay = Duration.between(LocalDateTime.now(), startDate).toMillis(); + + log.info("mailJob mailSchedule schedule add : {}", mail); + ScheduledFuture schedule = scheduler.schedule(taskRunner, initialDelay, TimeUnit.MILLISECONDS); + schedulerService.addTask(key, schedule); + } + } + } + }); + + if (processedCount.get() > 0) { + businessLogService.logScheduler( + LogStatus.SUCCESS, + String.format("메일 스케줄 처리 완료: 총 %d건 처리 (즉시발송: %d건, 예약등록: %d건)", + processedCount.get(), directSendCount.get(), scheduledCount.get()), + "MAIL_SCHEDULER", + startTime, + LocalDateTime.now(), + Map.of( + "totalProcessed", processedCount.get(), + "directSend", directSendCount.get(), + "scheduled", scheduledCount.get(), + "totalMailCount", mailList.size() + ) + ); + } + }catch (Exception e){ + log.error("mailSchedule Exception: {}", e.getMessage()); + throw e; + } + } + + private void mailTypeProcess(Mail mail){ + if(mail.getReceiveType().equals(Mail.RECEIVETYPE.SINGLE)){ + boolean is_send = mainSend(mail); + if(is_send) mailService.updateMailStatus(mail.getId(), Mail.SENDSTATUS.FINISH); + } + else{ + List excelList = excelUtils.getExcelListData(mail.getTarget()); + log.info("mailJob mailSchedule schedule run ExcelList : {}", excelList); + boolean is_send; + mailService.updateMailStatus(mail.getId(), Mail.SENDSTATUS.RUNNING); + for(Excel excel : excelList){ + String guid = mailService.getGuid(excel.getUser(), excel.getType()); + mail.setTarget(guid); + is_send = mainSend(mail); + if(!is_send){ + log.error("mailJob mailSchedule Excel fail user : {}", excel.getUser()); + } + else log.info("mailJob mailSchedule Excel send user : {}", excel.getUser()); + } + mailService.updateMailStatus(mail.getId(), Mail.SENDSTATUS.FINISH); + } + } + + // 우편 전송 + private boolean mainSend(Mail mail){ + // 서버정보 가져오기 + try{ + RedisLoginInfo info = redisUserInfoService.getUserLoginSessionInfo(mail.getTarget()); + String server_name = null; + if(info == null){ + server_name = redisUserInfoService.getFirstChannel(); + if(server_name == null){ + log.error("mailJob mainSend serverName is empty"); + mailService.updateMailStatus(mail.getId(), Mail.SENDSTATUS.FAIL); + return false; + } + }else{ + server_name = info.getCurrentServer(); + } + + // 메시지 처리 + List msgList = mailService.getMailMessageList(mail.getId()); + List titleList = new ArrayList<>(); + List contentList = new ArrayList<>(); + List senderList = new ArrayList<>(); + for(Message msg : msgList){ + LanguageType lang = null; + String langText = msg.getLanguage(); + String sender = null; + + if(langText.equals(LANGUAGETYPE.EN.toString())){ + lang = LanguageType.LanguageType_en; + sender = "Administrator"; + }else if(langText.equals(LANGUAGETYPE.JA.toString())){ + lang = LanguageType.LanguageType_ja; + sender = "アドミニストレーター"; + }else{ + lang = LanguageType.LanguageType_ko; + sender = "시스템 관리자"; + } + titleList.add(OperationSystemMessage.newBuilder() + .setLanguageType(lang) + .setText(CommonUtils.stringToByte(msg.getTitle())).build()); + contentList.add(OperationSystemMessage.newBuilder() + .setLanguageType(lang) + .setText(CommonUtils.stringToByte(msg.getContent())).build()); + senderList.add(OperationSystemMessage.newBuilder() + .setLanguageType(lang) + .setText(CommonUtils.stringToByte(sender)).build()); + } + + // 아이템 처리 + List itemList = mailService.getMailItemList(mail.getId()); + List mailItemList = new ArrayList<>(); + for(Item item : itemList){ + mailItemList.add(MailItem.newBuilder() + .setItemId(CommonUtils.stringToInt(item.getItem())) + .setCount(item.getItemCnt()).build()); + } + + log.info("Send Mail Message : {}, target : {}, type :{}", contentList, mail.getTarget(), mail.getMailType()); + messageHandlerService.sendMailMessage(server_name, mail.getTarget(), mail.getMailType().toString(), titleList, contentList, mailItemList, senderList); + log.info("mailJob mailSend completed"); + return true; + }catch(Exception e){ + log.error("mailSend Exception: {}", e.getMessage()); + mailService.updateMailStatus(mail.getId(), Mail.SENDSTATUS.FAIL); + } + return false; + } + + @Override + public SchedulerType getSchedulerType() { + return SchedulerType.MAIL; + } +} diff --git a/src/main/java/com/caliverse/admin/scheduler/polling/service/NoticeScheduler.java b/src/main/java/com/caliverse/admin/scheduler/polling/service/NoticeScheduler.java index 115fba8..f6d11fb 100644 --- a/src/main/java/com/caliverse/admin/scheduler/polling/service/NoticeScheduler.java +++ b/src/main/java/com/caliverse/admin/scheduler/polling/service/NoticeScheduler.java @@ -1,78 +1,267 @@ package com.caliverse.admin.scheduler.polling.service; -import com.caliverse.admin.domain.entity.LandOwnerChange; -import com.caliverse.admin.domain.request.LandRequest; -import com.caliverse.admin.domain.service.LandService; -import com.caliverse.admin.domain.service.UserGameSessionService; -import com.caliverse.admin.dynamodb.service.DynamodbLandService; -import com.caliverse.admin.dynamodb.service.DynamodbMailService; +import com.caliverse.admin.domain.RabbitMq.MessageHandlerService; +import com.caliverse.admin.domain.RabbitMq.message.LanguageType; +import com.caliverse.admin.domain.RabbitMq.message.OperationSystemMessage; +import com.caliverse.admin.domain.entity.*; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.domain.entity.log.LogStatus; +import com.caliverse.admin.domain.service.NoticeService; +import com.caliverse.admin.global.common.annotation.BusinessProcess; +import com.caliverse.admin.global.common.utils.CommonUtils; +import com.caliverse.admin.mongodb.service.BusinessLogService; +import com.caliverse.admin.redis.service.RedisUserInfoService; import com.caliverse.admin.scheduler.CommonScheduler; +import com.caliverse.admin.scheduler.ScheduleService; import com.caliverse.admin.scheduler.entity.SchedulerType; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; +import java.time.Duration; import java.time.LocalDateTime; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.time.LocalTime; +import java.util.*; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; @Slf4j @Component public class NoticeScheduler extends CommonScheduler { + private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); + private final NoticeService noticeService; + private final RedisUserInfoService redisUserInfoService; + private final ScheduleService schedulerService; + private final MessageHandlerService messageHandlerService; - private final LandService landService; - private final DynamodbLandService dynamodbLandService; - private final DynamodbMailService dynamodbMailService; - private final UserGameSessionService userGameSessionService; - - public NoticeScheduler(LandService landService, DynamodbLandService dynamodbLandService, DynamodbMailService dynamodbMailService, UserGameSessionService userGameSessionService) { - this.landService = landService; - this.dynamodbLandService = dynamodbLandService; - this.dynamodbMailService = dynamodbMailService; - this.userGameSessionService = userGameSessionService; + public NoticeScheduler(NoticeService noticeService, + RedisUserInfoService redisUserInfoService, + ScheduleService schedulerService, + MessageHandlerService messageHandlerService, + BusinessLogService businessLogService) { + super(businessLogService); + this.noticeService = noticeService; + this.redisUserInfoService = redisUserInfoService; + this.schedulerService = schedulerService; + this.messageHandlerService = messageHandlerService; } + @BusinessProcess(action = LogAction.SCHEDULE_NOTICE) @Override protected void executeInternal() { - List scheduleList = landService.getScheduleLandOwnerChangesList(); + List noticeList = noticeService.getScheduleNoticeList(); - scheduleList.forEach(landOwnerChange -> { - LandOwnerChange.CHANGE_STATUS status = landOwnerChange.getStatus(); - LocalDateTime reserve_dt = landOwnerChange.getReservationDt(); - int landId = landOwnerChange.getLandId(); - String guid = landOwnerChange.getUserGuid(); + if(noticeList.isEmpty()) return; - LocalDateTime now = LocalDateTime.now(); + AtomicInteger processedCount = new AtomicInteger(0); + AtomicInteger oneTimeCount = new AtomicInteger(0); + AtomicInteger repeatCount = new AtomicInteger(0); + AtomicInteger timeTypeCount = new AtomicInteger(0); + AtomicInteger failedCount = new AtomicInteger(0); - if(status.equals(LandOwnerChange.CHANGE_STATUS.WAIT) && reserve_dt.isBefore(now)) { - LandRequest landRequest = LandRequest.builder() - .landId(landId) - .landName(landOwnerChange.getLandName()) - .buildingId(landOwnerChange.getBuildingId()) - .buildingName(landOwnerChange.getBuildingName()) - .userGuid(guid) - .userName(landOwnerChange.getUserName()) - .build(); + LocalDateTime startTime = LocalDateTime.now(); - //유저킥 - userGameSessionService.kickUserSession(guid, "land owner changes"); + try{ + noticeList.forEach(notice -> { + String key = "notice-" + notice.getId(); + if (!schedulerService.isTaskExist(key)) { + processedCount.incrementAndGet(); - //랜드정보 처리 - dynamodbLandService.ChangesLandOwner(landRequest); + Runnable taskRunner = new Runnable() { + private int count = notice.getSendCnt().intValue(); + private final int repeat_cnt = notice.getRepeatCnt().intValue(); + private final boolean isRepeat = notice.getIsRepeat(); + private final long id = notice.getId(); + private final String runKey = key; + private final InGame.REPEATTYPE repeatType = notice.getRepeatType(); + private final LocalDateTime endDate = notice.getEndDt(); - Map map = new HashMap<>(); - map.put("id", landOwnerChange.getId()); - map.put("status", LandOwnerChange.CHANGE_STATUS.FINISH); - landService.updateLandOwnedChangeStatus(map); + @Override + public void run() { + log.info("noticeJob noticeSchedule schedule run : {}", notice); - //우편 - dynamodbMailService.insertLandChangesMail(landRequest); + boolean is_send = noticeSend(notice); + if(!is_send) return; + noticeService.updateNoticeCount(id); + + // 반복여부 + if(isRepeat){ + // 반복타입 + switch(repeatType){ + // 횟수 + case COUNT -> { + count++; + // 정해진 횟수만큼 돌았으면 종료 + if(count >= repeat_cnt){ + noticeService.updateNoticeStatus(id, InGame.SENDSTATUS.FINISH); + schedulerService.closeTask(runKey); + log.info("Notice Schedule End RepeatType: Count, id: {}", id); + } + } + // 일자 + case DATE -> { + if (LocalDateTime.now().isAfter(endDate)) { + noticeService.updateNoticeStatus(id, InGame.SENDSTATUS.FINISH); + schedulerService.closeTask(runKey); + log.info("Notice Schedule End RepeatType: Date, id: {}", id); + } + } + } + }else{ + // 스케줄 해제 및 상태 변경 + noticeService.updateNoticeStatus(id, InGame.SENDSTATUS.FINISH); + schedulerService.closeTask(runKey); + log.info("Notice One Time Schedule End id: {}", id); + } + } + }; + + // 반복여부 체크 + if(notice.getIsRepeat()){ + repeatCount.incrementAndGet(); + + // 반복타입 + switch(notice.getRepeatType()){ + // 횟수 + case COUNT,DATE ->{ + // 시작일자 - 현재일자 + LocalDateTime startDate = notice.getSendDt(); + long initialDelay = Duration.between(LocalDateTime.now(), startDate).toMillis(); // 시작시간 + long period = LocalTime.parse(notice.getRepeatDt()).toSecondOfDay(); // 반복주기 + + ScheduledFuture schedule = scheduler.scheduleAtFixedRate(taskRunner, initialDelay, period, TimeUnit.MILLISECONDS); + schedulerService.addTask(key, schedule); + noticeService.updateNoticeStatus(notice.getId(), InGame.SENDSTATUS.RUNNING); + } + // 특정시간 + case TIME -> { + timeTypeCount.incrementAndGet(); + + LocalDateTime now_date = LocalDateTime.now(); + LocalDateTime start_date = notice.getSendDt(); + + if(now_date.isAfter(start_date)) { + LocalTime now_time = LocalTime.now(); + LocalTime repeat_time = CommonUtils.stringToTime(notice.getRepeatDt()); + LocalDateTime end_date = notice.getEndDt(); + InGame.SENDSTATUS status = notice.getSendStatus(); + Long id = notice.getId(); + + if(status.equals(InGame.SENDSTATUS.WAIT)) noticeService.updateNoticeStatus(id, InGame.SENDSTATUS.RUNNING); + + if (now_time.equals(repeat_time)) { + log.info("noticeJob noticeSchedule RepeatType: Time run : {}", notice); + boolean is_send = noticeSend(notice); + if (!is_send) { + log.error("Notice Schedule Fail RepeatType: Time, id: {}", id); + } + } + + if(status.equals(InGame.SENDSTATUS.RUNNING) && (now_date.isBefore(end_date) || now_date.isEqual(end_date))){ + noticeService.updateNoticeStatus(id, InGame.SENDSTATUS.FINISH); + log.info("Notice Schedule End RepeatType: Time, id: {}", id); + } + } + } + } + + }else{ + oneTimeCount.incrementAndGet(); + // 시작일자 - 현재일자 + LocalDateTime startDate = notice.getSendDt(); + long initialDelay = Duration.between(LocalDateTime.now(), startDate).toMillis(); + + if(initialDelay < 0) { + failedCount.incrementAndGet(); + log.error("noticeJob noticeSchedule schedule add fail time over"); + noticeService.updateNoticeStatus(notice.getId(), InGame.SENDSTATUS.FAIL); + return; + } + + log.info("noticeJob noticeSchedule schedule add : {}", notice); + ScheduledFuture schedule = scheduler.schedule(taskRunner, initialDelay, TimeUnit.MILLISECONDS); + schedulerService.addTask(key, schedule); + } + } + }); + + if (processedCount.get() > 0) { + businessLogService.logScheduler( + LogStatus.SUCCESS, + String.format("공지사항 스케줄 처리 완료: 총 %d건 처리 (일회성: %d건, 반복: %d건, 특정시간: %d건, 실패: %d건)", + processedCount.get(), oneTimeCount.get(), repeatCount.get(), timeTypeCount.get(), failedCount.get()), + "NOTICE_SCHEDULER", + startTime, + LocalDateTime.now(), + Map.of( + "totalProcessed", processedCount.get(), + "oneTimeNotices", oneTimeCount.get(), + "repeatNotices", repeatCount.get(), + "timeTypeNotices", timeTypeCount.get(), + "failedNotices", failedCount.get(), + "totalNoticeCount", noticeList.size() + ) + ); } - }); + }catch (Exception e){ + log.error("noticeSchedule Exception: {}", e.getMessage()); + throw e; + } + } + + // 공지사항 전송 + private boolean noticeSend(InGame notice){ + try{ + //redis 채널 및 인던 정보 가져오기 + List serverList = redisUserInfoService.getAllServerList(); + if(serverList.isEmpty()){ + log.error("noticeJob noticeSend serverList is empty"); + noticeService.updateNoticeStatus(notice.getId(), InGame.SENDSTATUS.FAIL); + return false; + } + + //메시지 처리 + List msgList = noticeService.getNoticeMessageList(notice.getId()); + List contentList = new ArrayList<>(); + List senderList = new ArrayList<>(); + for(Message msg : Collections.unmodifiableList(msgList)){ + LanguageType lang = null; + String langText = msg.getLanguage(); + String sender = null; + + if(langText.equals(LANGUAGETYPE.EN.toString())){ + lang = LanguageType.LanguageType_en; + sender = "Administrator"; + }else if(langText.equals(LANGUAGETYPE.JA.toString())){ + lang = LanguageType.LanguageType_ja; + sender = "アドミニストレーター"; + }else{ + lang = LanguageType.LanguageType_ko; + sender = "시스템 관리자"; + } + contentList.add(OperationSystemMessage.newBuilder() + .setLanguageType(lang) + .setText(CommonUtils.stringToByte(msg.getContent())).build()); + senderList.add(OperationSystemMessage.newBuilder() + .setLanguageType(lang) + .setText(CommonUtils.stringToByte(sender)).build()); + } + + log.info("Send Notice Message: {}, type: {}", contentList, notice.getMessageType()); + messageHandlerService.sendNoticeMessage(serverList, notice.getMessageType().toString(), contentList, senderList); + log.info("noticeJob noticeSend completed"); + return true; + }catch (Exception e){ + log.error("noticeSend Exception: {}", e.getMessage()); + noticeService.updateNoticeStatus(notice.getId(), InGame.SENDSTATUS.FAIL); + } + return false; } @Override public SchedulerType getSchedulerType() { - return SchedulerType.LAND_OWNER_CHANGES; + return SchedulerType.NOTICE; } } diff --git a/src/main/java/com/caliverse/admin/scheduler/polling/service/cleanupScheduler.java b/src/main/java/com/caliverse/admin/scheduler/polling/service/cleanupScheduler.java index 8c0a00f..8b31920 100644 --- a/src/main/java/com/caliverse/admin/scheduler/polling/service/cleanupScheduler.java +++ b/src/main/java/com/caliverse/admin/scheduler/polling/service/cleanupScheduler.java @@ -1,5 +1,8 @@ package com.caliverse.admin.scheduler.polling.service; +import com.caliverse.admin.domain.entity.log.LogAction; +import com.caliverse.admin.global.common.annotation.BusinessProcess; +import com.caliverse.admin.mongodb.service.BusinessLogService; import com.caliverse.admin.scheduler.CommonScheduler; import com.caliverse.admin.scheduler.ScheduleService; import com.caliverse.admin.scheduler.entity.SchedulerType; @@ -12,10 +15,13 @@ public class cleanupScheduler extends CommonScheduler { private final ScheduleService scheduleService; - public cleanupScheduler(ScheduleService scheduleService) { + public cleanupScheduler(ScheduleService scheduleService, + BusinessLogService businessLogService) { + super(businessLogService); this.scheduleService = scheduleService; } + @BusinessProcess(action = LogAction.SCHEDULE_CLEANUP) @Override protected void executeInternal() { scheduleService.cleanupCompletedTasks(); diff --git a/src/main/resources/mappers/AdminMapper.xml b/src/main/resources/mappers/AdminMapper.xml index 4fa7127..4e5d86b 100644 --- a/src/main/resources/mappers/AdminMapper.xml +++ b/src/main/resources/mappers/AdminMapper.xml @@ -17,10 +17,15 @@ + + + SELECT * FROM diff --git a/src/main/resources/mappers/EventMapper.xml b/src/main/resources/mappers/EventMapper.xml index b0f0bd8..8f15836 100644 --- a/src/main/resources/mappers/EventMapper.xml +++ b/src/main/resources/mappers/EventMapper.xml @@ -226,7 +226,7 @@ SET deleted = 1 ,status = 'DELETE' ,delete_desc = #{desc} - WHERE id = #{mailId} + WHERE id = #{id} diff --git a/src/main/resources/mappers/GroupMapper.xml b/src/main/resources/mappers/GroupMapper.xml index 1cbc1b2..6acb560 100644 --- a/src/main/resources/mappers/GroupMapper.xml +++ b/src/main/resources/mappers/GroupMapper.xml @@ -21,7 +21,7 @@ @@ -69,7 +69,7 @@ and b.group_id = #{groupId} - + INSERT INTO groups (name,description,create_by) values (#{groupNm} ,#{description}, #{createBy}) diff --git a/src/main/resources/mappers/HistoryMapper.xml b/src/main/resources/mappers/HistoryMapper.xml deleted file mode 100644 index 4a12f14..0000000 --- a/src/main/resources/mappers/HistoryMapper.xml +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - - - - - - - - - - - - - - - INSERT INTO admin_log (admin_id,name,mail,type,content) VALUES (#{adminId},#{name},#{mail}, #{type}, #{content}); - - - diff --git a/src/main/resources/mappers/LandMapper.xml b/src/main/resources/mappers/LandMapper.xml index 4732d5c..98b9778 100644 --- a/src/main/resources/mappers/LandMapper.xml +++ b/src/main/resources/mappers/LandMapper.xml @@ -42,11 +42,6 @@ - - - - - SELECT count(*) FROM land_auction a - LEFT JOIN message b ON (a.id = b.target_id - AND b.type = 'LANDAUCTION' - AND - ( - (b.language = 'KO' AND b.language IS NOT NULL) -- KO인 content - OR - (b.language <> 'KO' AND b.language IS NOT NULL AND NOT EXISTS ( - SELECT 1 FROM message m2 - WHERE m2.target_id = a.id AND m2.language IS NOT NULL - ) - ) - ) - ) WHERE 1 = 1 @@ -243,6 +212,7 @@ , a.start_price , a.close_end_dt , a.close_price + , a.deleted , (SELECT email FROM admin WHERE id = a.create_by ) AS create_by , a.create_dt , (SELECT email FROM admin WHERE id = a.update_by ) AS update_by @@ -261,6 +231,7 @@ , a.is_reserve , a.reservation_dt , a.status + , a.deleted , (SELECT email FROM admin WHERE id = a.create_by ) AS create_by , a.create_dt , (SELECT email FROM admin WHERE id = a.update_by ) AS update_by @@ -283,14 +254,6 @@ WHERE a.land_id = #{landId} - - INSERT INTO land_auction (land_id, land_name, land_size, land_socket, auction_seq, resv_start_dt, resv_end_dt, auction_start_dt, auction_end_dt, currency_type, start_price, create_by, update_by) @@ -302,11 +265,6 @@ VALUES (#{landId}, #{landName}, #{buildingId}, #{buildingName}, #{userGuid}, #{userName}, #{isReserve}, #{reservationDt}, #{createBy}, #{updateBy}) - - INSERT INTO message (target_id, type, content, language) - VALUES (#{id}, 'LANDAUCTION', #{content}, #{language}) - - UPDATE land_auction SET resv_start_dt = #{resvStartDt} @@ -329,12 +287,6 @@ WHERE id = #{id} - - DELETE FROM message - WHERE target_id = #{id} - AND type = 'LANDAUCTION' - - UPDATE land_auction SET deleted = 1 diff --git a/src/main/resources/mappers/MailMapper.xml b/src/main/resources/mappers/MailMapper.xml index 6ab3304..3465caf 100644 --- a/src/main/resources/mappers/MailMapper.xml +++ b/src/main/resources/mappers/MailMapper.xml @@ -12,6 +12,7 @@ + @@ -179,13 +180,13 @@ , a.receive_type , a.user_type , a.send_dt + , a.deleted , (SELECT email FROM admin WHERE id = a.create_by ) AS create_by , a.create_dt , (SELECT email FROM admin WHERE id = a.update_by ) AS update_by , a.update_dt FROM mail a WHERE a.id = #{id} - AND deleted = 0