From faac85ddfd79e4b52697e57669779b3882d3b61d Mon Sep 17 00:00:00 2001 From: moonseonghui Date: Fri, 24 Nov 2023 17:42:17 +0900 Subject: [PATCH 1/8] =?UTF-8?q?[FE]=20ETC:=20=EB=82=B4=20=EC=82=AC?= =?UTF-8?q?=EB=AC=BC=ED=95=A8=20session=20=EB=94=94=EC=9E=90=EC=9D=B8=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/components/CabinetInfoArea/CabinetInfoArea.tsx | 1 - .../CabinetList/CabinetListItem/AdminCabinetListItem.tsx | 4 +--- .../CabinetList/CabinetListItem/CabinetListItem.tsx | 3 +-- 3 files changed, 2 insertions(+), 6 deletions(-) diff --git a/frontend/src/components/CabinetInfoArea/CabinetInfoArea.tsx b/frontend/src/components/CabinetInfoArea/CabinetInfoArea.tsx index a21b47ece..b2fd1ad92 100644 --- a/frontend/src/components/CabinetInfoArea/CabinetInfoArea.tsx +++ b/frontend/src/components/CabinetInfoArea/CabinetInfoArea.tsx @@ -338,7 +338,6 @@ const CabinetRectangleStyled = styled.div<{ ${({ cabinetStatus, isMine }) => cabinetStatus === "IN_SESSION" && - !isMine && css` border: 2px solid var(--main-color); `} diff --git a/frontend/src/components/CabinetList/CabinetListItem/AdminCabinetListItem.tsx b/frontend/src/components/CabinetList/CabinetListItem/AdminCabinetListItem.tsx index 62eff4cff..3978cc621 100644 --- a/frontend/src/components/CabinetList/CabinetListItem/AdminCabinetListItem.tsx +++ b/frontend/src/components/CabinetList/CabinetListItem/AdminCabinetListItem.tsx @@ -29,7 +29,6 @@ const AdminCabinetListItem = (props: CabinetPreviewInfo): JSX.Element => { selectedTypeOnSearchState ); const { openCabinet, closeCabinet } = useMenu(); - // const isMine = MY_INFO ? MY_INFO.cabinetId === props.cabinetId : false; const { isMultiSelect, clickCabinetOnMultiSelectMode, containsCabinet } = useMultiSelect(); @@ -171,9 +170,8 @@ const CabinetListItemStyled = styled.div<{ border: 5px double var(--white); `} - ${({ status, isMine }) => + ${({ status }) => status === "IN_SESSION" && - !isMine && css` border: 2px solid var(--main-color); `} diff --git a/frontend/src/components/CabinetList/CabinetListItem/CabinetListItem.tsx b/frontend/src/components/CabinetList/CabinetListItem/CabinetListItem.tsx index a12a360f6..5cabb4e43 100644 --- a/frontend/src/components/CabinetList/CabinetListItem/CabinetListItem.tsx +++ b/frontend/src/components/CabinetList/CabinetListItem/CabinetListItem.tsx @@ -176,8 +176,7 @@ const CabinetListItemStyled = styled.div<{ ${({ status, isMine }) => status === "IN_SESSION" && - !isMine && - css` + css` border: 2px solid var(--main-color); `} From 03734c4e84b4d4aec8e8a2d844fd31d0b25b179b Mon Sep 17 00:00:00 2001 From: moonseonghui Date: Sat, 25 Nov 2023 15:50:32 +0900 Subject: [PATCH 2/8] =?UTF-8?q?[FE]=20FIX:=20=EC=82=AC=EB=AC=BC=ED=95=A8?= =?UTF-8?q?=20=ED=81=B4=EB=A6=AD=ED=96=88=EC=9D=84=20=EB=95=8C=20=EC=82=AC?= =?UTF-8?q?=EB=AC=BC=ED=95=A8=20=EC=83=81=ED=83=9C=EA=B0=80=20=EB=8B=A4?= =?UTF-8?q?=EB=A5=B4=EB=A9=B4=20api=20=EC=97=85=EB=8D=B0=EC=9D=B4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CabinetListItem/CabinetListItem.tsx | 42 ++++++++++++++++--- .../InvitationCodeModal.container.tsx | 41 +++--------------- 2 files changed, 42 insertions(+), 41 deletions(-) diff --git a/frontend/src/components/CabinetList/CabinetListItem/CabinetListItem.tsx b/frontend/src/components/CabinetList/CabinetListItem/CabinetListItem.tsx index 5cabb4e43..529a7886a 100644 --- a/frontend/src/components/CabinetList/CabinetListItem/CabinetListItem.tsx +++ b/frontend/src/components/CabinetList/CabinetListItem/CabinetListItem.tsx @@ -2,7 +2,10 @@ import { useState } from "react"; import { useRecoilState, useRecoilValue, useSetRecoilState } from "recoil"; import styled, { css, keyframes } from "styled-components"; import { + currentBuildingNameState, currentCabinetIdState, + currentFloorCabinetState, + currentFloorNumberState, myCabinetInfoState, targetCabinetInfoState, } from "@/recoil/atoms"; @@ -20,7 +23,11 @@ import { } from "@/types/dto/cabinet.dto"; import CabinetStatus from "@/types/enum/cabinet.status.enum"; import CabinetType from "@/types/enum/cabinet.type.enum"; -import { axiosCabinetById } from "@/api/axios/axios.custom"; +import { + axiosCabinetByBuildingFloor, + axiosCabinetById, + axiosMyLentInfo, +} from "@/api/axios/axios.custom"; import useMenu from "@/hooks/useMenu"; const CabinetListItem = (props: CabinetPreviewInfo): JSX.Element => { @@ -29,9 +36,11 @@ const CabinetListItem = (props: CabinetPreviewInfo): JSX.Element => { const [currentCabinetId, setCurrentCabinetId] = useRecoilState( currentCabinetIdState ); + const setTargetCabinetInfo = useSetRecoilState( targetCabinetInfoState ); + const [showUnavailableModal, setShowUnavailableModal] = useState(false); const { openCabinet, closeCabinet } = useMenu(); @@ -40,6 +49,8 @@ const CabinetListItem = (props: CabinetPreviewInfo): JSX.Element => { props.status !== "AVAILABLE" : false; + const setMyLentInfo = + useSetRecoilState(myCabinetInfoState); let cabinetLabelText = ""; if ( @@ -67,17 +78,38 @@ const CabinetListItem = (props: CabinetPreviewInfo): JSX.Element => { setShowUnavailableModal(false); }; + const currentBuilding = useRecoilValue(currentBuildingNameState); + const currentFloor = useRecoilValue(currentFloorNumberState); + const setCurrentFloorData = useSetRecoilState(currentFloorCabinetState); + const selectCabinetOnClick = (status: CabinetStatus, cabinetId: number) => { if (currentCabinetId === cabinetId) { closeCabinet(); return; } - setCurrentCabinetId(cabinetId); + async function getData(cabinetId: number) { try { - const { data } = await axiosCabinetById(cabinetId); - setTargetCabinetInfo(data); + const { data: selectCabinetData } = await axiosCabinetById(cabinetId); + setTargetCabinetInfo(selectCabinetData); + + if ( + status !== selectCabinetData.status && + myCabinetInfo.cabinetId !== cabinetId + ) { + const { data: floorData } = await axiosCabinetByBuildingFloor( + currentBuilding, + currentFloor + ); + setCurrentFloorData(floorData); + } else if ( + myCabinetInfo.cabinetId === cabinetId && + status !== selectCabinetData.status + ) { + const { data: myCabinetData } = await axiosMyLentInfo(); + setMyLentInfo(myCabinetData); + } } catch (error) { console.log(error); } @@ -174,7 +206,7 @@ const CabinetListItemStyled = styled.div<{ border: 5px double var(--white); `} - ${({ status, isMine }) => + ${({ status }) => status === "IN_SESSION" && css` border: 2px solid var(--main-color); diff --git a/frontend/src/components/Modals/InvitationCodeModal/InvitationCodeModal.container.tsx b/frontend/src/components/Modals/InvitationCodeModal/InvitationCodeModal.container.tsx index b0772624c..fcc2189ae 100644 --- a/frontend/src/components/Modals/InvitationCodeModal/InvitationCodeModal.container.tsx +++ b/frontend/src/components/Modals/InvitationCodeModal/InvitationCodeModal.container.tsx @@ -39,34 +39,6 @@ const InvitationCodeModalContainer: React.FC<{ const setMyLentInfo = useSetRecoilState(myCabinetInfoState); - const loadSharedWrongCodeCounts = () => { - const savedData = localStorage.getItem("wrongCodeCounts"); - if (savedData) { - try { - const { data, expirationTime } = JSON.parse(savedData); - const ExpirationTime = new Date(expirationTime); - if (ExpirationTime > new Date()) { - return data; - } else { - localStorage.removeItem("wrongCodeCounts"); - } - } catch (error) { - console.error("WrongCodeCounts:", error); - } - } - return {}; - }; - - const saveSharedWrongCodeCounts = (data: any) => { - const expirationTime = new Date( - new Date().getTime() + 10 * 60 * 1000 - ).toString(); - const dataToSave = JSON.stringify({ data, expirationTime }); - localStorage.setItem("wrongCodeCounts", dataToSave); - }; - - const [sharedWrongCodeCounts] = useState(loadSharedWrongCodeCounts); - const onChange = (e: React.ChangeEvent) => { const regex = /^[0-9]{0,4}$/; if (!regex.test(e.target.value)) { @@ -76,12 +48,6 @@ const InvitationCodeModalContainer: React.FC<{ setCode(e.target.value); }; - const updatedCounts = { - ...sharedWrongCodeCounts, - [String(props.cabinetId)]: - (sharedWrongCodeCounts[String(props.cabinetId)] || 0) + 1, - }; - const tryLentRequest = async () => { try { await axiosLentShareId(currentCabinetId, code); @@ -100,7 +66,6 @@ const InvitationCodeModalContainer: React.FC<{ const errorMessage = error.response.data.message; setModalTitle(errorMessage); setHasErrorOnResponse(true); - saveSharedWrongCodeCounts(updatedCounts); } finally { setShowResponseModal(true); } @@ -115,7 +80,11 @@ const InvitationCodeModalContainer: React.FC<{ proceedBtnText: modalPropsMap["MODAL_INVITATION_CODE"].confirmMessage, onClickProceed: tryLentRequest, renderAdditionalComponent: () => ( - + ), closeModal: props.onClose, iconType: IconType.CHECKICON, From 05a21e4679578a1a226136172aa4d75a3b68fa0a Mon Sep 17 00:00:00 2001 From: moonseonghui Date: Sat, 25 Nov 2023 16:13:40 +0900 Subject: [PATCH 3/8] =?UTF-8?q?[FE]=20REFACTOR:=20=EC=82=AC=EB=AC=BC?= =?UTF-8?q?=ED=95=A8=20=EC=83=81=ED=83=9C=EA=B0=80=20=EB=8B=A4=EB=A5=BC=20?= =?UTF-8?q?=EB=95=8C=20api=ED=98=B8=EC=B6=9C=20=ED=95=98=EB=8A=94=20?= =?UTF-8?q?=EB=B6=80=EB=B6=84=20=EB=A6=AC=ED=8C=A9=ED=86=A0=EB=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CabinetListItem/CabinetListItem.tsx | 27 ++++++++----------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/frontend/src/components/CabinetList/CabinetListItem/CabinetListItem.tsx b/frontend/src/components/CabinetList/CabinetListItem/CabinetListItem.tsx index 529a7886a..ebfad0ed4 100644 --- a/frontend/src/components/CabinetList/CabinetListItem/CabinetListItem.tsx +++ b/frontend/src/components/CabinetList/CabinetListItem/CabinetListItem.tsx @@ -93,22 +93,17 @@ const CabinetListItem = (props: CabinetPreviewInfo): JSX.Element => { try { const { data: selectCabinetData } = await axiosCabinetById(cabinetId); setTargetCabinetInfo(selectCabinetData); - - if ( - status !== selectCabinetData.status && - myCabinetInfo.cabinetId !== cabinetId - ) { - const { data: floorData } = await axiosCabinetByBuildingFloor( - currentBuilding, - currentFloor - ); - setCurrentFloorData(floorData); - } else if ( - myCabinetInfo.cabinetId === cabinetId && - status !== selectCabinetData.status - ) { - const { data: myCabinetData } = await axiosMyLentInfo(); - setMyLentInfo(myCabinetData); + if (status !== selectCabinetData.status) { + if (myCabinetInfo.cabinetId === cabinetId) { + const { data: myCabinetData } = await axiosMyLentInfo(); + setMyLentInfo(myCabinetData); + } else { + const { data: floorData } = await axiosCabinetByBuildingFloor( + currentBuilding, + currentFloor + ); + setCurrentFloorData(floorData); + } } } catch (error) { console.log(error); From ab8db4a0a20db7cf9749e3d02763501efce885ce Mon Sep 17 00:00:00 2001 From: moonseonghui Date: Sat, 25 Nov 2023 16:29:02 +0900 Subject: [PATCH 4/8] =?UTF-8?q?[FE]=20FIX=20:=20=EC=B4=88=EB=8C=80?= =?UTF-8?q?=EC=BD=94=EB=93=9C=20=EC=8B=9C=EA=B0=84=20=EB=94=9C=EB=A0=88?= =?UTF-8?q?=EC=9D=B4=202=EC=B4=88=20=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CabinetInfoArea/CountTime/CountTime.container.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/components/CabinetInfoArea/CountTime/CountTime.container.tsx b/frontend/src/components/CabinetInfoArea/CountTime/CountTime.container.tsx index 69ccc81c9..d971f5cd0 100644 --- a/frontend/src/components/CabinetInfoArea/CountTime/CountTime.container.tsx +++ b/frontend/src/components/CabinetInfoArea/CountTime/CountTime.container.tsx @@ -29,7 +29,7 @@ const CountTimeContainer = ({ isMine }: { isMine: boolean }) => { const currentTime = new Date().getTime(); const targetTime = targetDate.getTime(); if (targetTime <= currentTime) return 0; - return targetTime - currentTime + 2000; + return targetTime - currentTime; }; const [targetCabinetInfo, setTargetCabinetInfo] = useRecoilState( From 1c4bc4dbc248d64f45317fbf3affdafa9f1abc9c Mon Sep 17 00:00:00 2001 From: Woo Joo Chae Date: Sat, 25 Nov 2023 17:33:11 +0900 Subject: [PATCH 5/8] =?UTF-8?q?[BE]=20REFACTOR:=20=EA=B3=B5=EC=9C=A0?= =?UTF-8?q?=EC=82=AC=EB=AC=BC=ED=95=A8=20in=20Session=20=EC=83=81=ED=83=9C?= =?UTF-8?q?=EC=9D=98=20cabinet=20=EC=A0=95=EB=B3=B4=20=EA=B0=80=EC=A0=B8?= =?UTF-8?q?=EC=98=AC=EB=95=8C,=20cabinetID=20=EB=8F=84=20=EA=B0=80?= =?UTF-8?q?=EC=A0=B8=EC=98=A4=EB=8F=84=EB=A1=9D=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/CabinetFacadeServiceImpl.java | 952 +++++++++--------- 1 file changed, 476 insertions(+), 476 deletions(-) diff --git a/backend/src/main/java/org/ftclub/cabinet/cabinet/service/CabinetFacadeServiceImpl.java b/backend/src/main/java/org/ftclub/cabinet/cabinet/service/CabinetFacadeServiceImpl.java index 4c1142076..e88cef02f 100644 --- a/backend/src/main/java/org/ftclub/cabinet/cabinet/service/CabinetFacadeServiceImpl.java +++ b/backend/src/main/java/org/ftclub/cabinet/cabinet/service/CabinetFacadeServiceImpl.java @@ -47,426 +47,426 @@ @Log4j2 public class CabinetFacadeServiceImpl implements CabinetFacadeService { - private final CabinetService cabinetService; - private final CabinetOptionalFetcher cabinetOptionalFetcher; - private final LentOptionalFetcher lentOptionalFetcher; - private final CabinetMapper cabinetMapper; - private final LentMapper lentMapper; - private final LentRedis lentRedis; - private final UserOptionalFetcher userOptionalFetcher; - - /*-------------------------------------------READ-------------------------------------------*/ - - /** - * {@inheritDoc} - *

- * 존재하는 모든 건물들을 가져오고, 각 건물별 층 정보들을 가져옵니다. - */ - @Override - @Transactional(readOnly = true) - public List getBuildingFloorsResponse() { - log.debug("getBuildingFloorsResponse"); - return cabinetOptionalFetcher.findAllBuildings().stream() - .map(building -> { - List floors = cabinetOptionalFetcher.findAllFloorsByBuilding(building); - return cabinetMapper.toBuildingFloorsDto(building, floors); - }) - .collect(Collectors.toList()); - } - - /** - * {@inheritDoc} - */ - @Override - @Transactional(readOnly = true) - public CabinetInfoResponseDto getCabinetInfo(Long cabinetId) { - log.debug("getCabinetInfo"); - List lentDtos = new ArrayList<>(); - List lentHistories = lentOptionalFetcher.findAllActiveLentByCabinetId( - cabinetId); - if (lentHistories.isEmpty()) { + private final CabinetService cabinetService; + private final CabinetOptionalFetcher cabinetOptionalFetcher; + private final LentOptionalFetcher lentOptionalFetcher; + private final CabinetMapper cabinetMapper; + private final LentMapper lentMapper; + private final LentRedis lentRedis; + private final UserOptionalFetcher userOptionalFetcher; + + /*-------------------------------------------READ-------------------------------------------*/ + + /** + * {@inheritDoc} + *

+ * 존재하는 모든 건물들을 가져오고, 각 건물별 층 정보들을 가져옵니다. + */ + @Override + @Transactional(readOnly = true) + public List getBuildingFloorsResponse() { + log.debug("getBuildingFloorsResponse"); + return cabinetOptionalFetcher.findAllBuildings().stream() + .map(building -> { + List floors = cabinetOptionalFetcher.findAllFloorsByBuilding(building); + return cabinetMapper.toBuildingFloorsDto(building, floors); + }) + .collect(Collectors.toList()); + } + + /** + * {@inheritDoc} + */ + @Override + @Transactional(readOnly = true) + public CabinetInfoResponseDto getCabinetInfo(Long cabinetId) { + log.debug("getCabinetInfo"); + List lentDtos = new ArrayList<>(); + List lentHistories = lentOptionalFetcher.findAllActiveLentByCabinetId( + cabinetId); + if (lentHistories.isEmpty()) { // ArrayList users = ticketingSharedCabinet.findUsersInSessionByCabinetIdFromRedis( // cabinetId); - ArrayList users = lentRedis.getUserIdsByCabinetIdInRedis( - cabinetId.toString()); - for (String user : users) { - String userName = userOptionalFetcher.findUser(Long.valueOf(user)).getName(); - lentDtos.add(new LentDto(null, userName, null, null, null)); - } - } - for (LentHistory lentHistory : lentHistories) { - User findUser = lentHistory.getUser(); - lentDtos.add(lentMapper.toLentDto(findUser, lentHistory)); - } - return cabinetMapper.toCabinetInfoResponseDto(cabinetOptionalFetcher.findCabinet(cabinetId), - lentDtos, lentRedis.getSessionExpiredAtInRedis(cabinetId)); - } - - /** - * {@inheritDoc} - */ - @Override - @Transactional(readOnly = true) - public CabinetSimplePaginationDto getCabinetsSimpleInfoByVisibleNum(Integer visibleNum) { - log.debug("getCabinetsSimpleInfoByVisibleNum"); - PageRequest page = PageRequest.of(0, Integer.MAX_VALUE); - Page allCabinetsByVisibleNum = cabinetOptionalFetcher.findPaginationByVisibleNum( - visibleNum, page); - List cabinetsSimple = allCabinetsByVisibleNum.stream().map( - cabinetMapper::toCabinetSimpleDto).collect(Collectors.toList()); - return new CabinetSimplePaginationDto(cabinetsSimple, - allCabinetsByVisibleNum.getTotalElements()); - } - - /** - * {@inheritDoc} - */ - @Override - @Transactional(readOnly = true) - public List getCabinetsPerSection(String building, - Integer floor) { - log.debug("getCabinetsPerSection"); - List currentLentCabinets = cabinetOptionalFetcher.findCabinetsActiveLentHistoriesByBuildingAndFloor( - building, floor); - List allCabinetsByBuildingAndFloor = cabinetOptionalFetcher.findAllCabinetsByBuildingAndFloor( - building, floor); - - Map> cabinetLentHistories = currentLentCabinets.stream(). - collect(Collectors.groupingBy(ActiveCabinetInfoEntities::getCabinet, - Collectors.mapping(ActiveCabinetInfoEntities::getLentHistory, - Collectors.toList()))); - - Map> cabinetPreviewsBySection = new HashMap<>(); - cabinetLentHistories.forEach((cabinet, lentHistories) -> { - String section = cabinet.getCabinetPlace().getLocation().getSection(); - CabinetPreviewDto preview = createCabinetPreviewDto(cabinet, lentHistories); - if (cabinetPreviewsBySection.containsKey(section)) { - cabinetPreviewsBySection.get(section).add(preview); - } else { - List previews = new ArrayList<>(); - previews.add(preview); - cabinetPreviewsBySection.put(section, previews); - } - }); - allCabinetsByBuildingAndFloor.forEach(cabinet -> { - if (!cabinetLentHistories.containsKey(cabinet)) { - String section = cabinet.getCabinetPlace().getLocation().getSection(); - CabinetPreviewDto preview = createCabinetPreviewDto(cabinet, - Collections.emptyList()); - if (cabinetPreviewsBySection.containsKey(section)) { - cabinetPreviewsBySection.get(section).add(preview); - } else { - List previews = new ArrayList<>(); - previews.add(preview); - cabinetPreviewsBySection.put(section, previews); - } - } - }); - cabinetPreviewsBySection.values().forEach(cabinetList -> cabinetList.sort( - Comparator.comparing(CabinetPreviewDto::getVisibleNum))); - return cabinetPreviewsBySection.entrySet().stream() - .sorted(Comparator.comparing(entry -> entry.getValue().get(0).getVisibleNum())) - .map(entry -> cabinetMapper.toCabinetsPerSectionResponseDto(entry.getKey(), - entry.getValue())) - .collect(Collectors.toList()); - } - - @Override - public List getCabinetsPerSectionRefactor(String building, - Integer floor) { - List cabinets = cabinetOptionalFetcher.findAllCabinetsByBuildingAndFloor(building, - floor); - Map> map = new HashMap<>(); - cabinets.forEach(cabinet -> { - List lentHistories = lentOptionalFetcher - .findActiveLentByCabinetIdWithUser(cabinet.getCabinetId()); - String section = cabinet.getCabinetPlace().getLocation().getSection(); - if (map.containsKey(section)) { - map.get(section) - .add(cabinetMapper.toCabinetPreviewDto(cabinet, lentHistories.size(), - lentHistories.isEmpty() ? null - : lentHistories.get(0).getUser().getName())); - } else { - List cabinetPreviewDtoList = new ArrayList<>(); - cabinetPreviewDtoList.add( - cabinetMapper.toCabinetPreviewDto(cabinet, lentHistories.size(), - lentHistories.isEmpty() ? null - : lentHistories.get(0).getUser().getName())); - map.put(section, cabinetPreviewDtoList); - } - }); - map.forEach( - (key, value) -> value.sort(Comparator.comparing(CabinetPreviewDto::getVisibleNum))); - return map.entrySet().stream() - .sorted(Comparator.comparing(entry -> entry.getValue().get(0).getVisibleNum())) - .map(entry -> cabinetMapper.toCabinetsPerSectionResponseDto(entry.getKey(), - entry.getValue())) - .collect(Collectors.toList()); - } - - private CabinetPreviewDto createCabinetPreviewDto(Cabinet cabinet, - List lentHistories) { - String lentUserName = null; - if (!lentHistories.isEmpty() && lentHistories.get(0).getUser() != null) { - lentUserName = lentHistories.get(0).getUser().getName(); - } - return cabinetMapper.toCabinetPreviewDto(cabinet, lentHistories.size(), lentUserName); - } - - @Override - public List getCabinetsPerSectionDSL(String building, - Integer floor) { - log.debug("getCabinetsPerSection"); - List currentLentCabinets = cabinetOptionalFetcher.findCabinetsActiveLentHistoriesByBuildingAndFloor2( - building, floor); - List allCabinetsByBuildingAndFloor = cabinetOptionalFetcher.findAllCabinetsByBuildingAndFloor( - building, floor); - - Map> cabinetLentHistories = currentLentCabinets.stream(). - collect(Collectors.groupingBy(ActiveCabinetInfoEntities::getCabinet, - Collectors.mapping(ActiveCabinetInfoEntities::getLentHistory, - Collectors.toList()))); - - Map> cabinetPreviewsBySection = new HashMap<>(); - cabinetLentHistories.forEach((cabinet, lentHistories) -> { - String section = cabinet.getCabinetPlace().getLocation().getSection(); - CabinetPreviewDto preview = createCabinetPreviewDto(cabinet, lentHistories); - if (cabinetPreviewsBySection.containsKey(section)) { - cabinetPreviewsBySection.get(section).add(preview); - } else { - List previews = new ArrayList<>(); - previews.add(preview); - cabinetPreviewsBySection.put(section, previews); - } - }); - allCabinetsByBuildingAndFloor.forEach(cabinet -> { - if (!cabinetLentHistories.containsKey(cabinet)) { - String section = cabinet.getCabinetPlace().getLocation().getSection(); - CabinetPreviewDto preview = createCabinetPreviewDto(cabinet, - Collections.emptyList()); - if (cabinetPreviewsBySection.containsKey(section)) { - cabinetPreviewsBySection.get(section).add(preview); - } else { - List previews = new ArrayList<>(); - previews.add(preview); - cabinetPreviewsBySection.put(section, previews); - } - } - }); - cabinetPreviewsBySection.values().forEach(cabinetList -> cabinetList.sort( - Comparator.comparing(CabinetPreviewDto::getVisibleNum))); - return cabinetPreviewsBySection.entrySet().stream() - .sorted(Comparator.comparing(entry -> entry.getValue().get(0).getVisibleNum())) - .map(entry -> cabinetMapper.toCabinetsPerSectionResponseDto(entry.getKey(), - entry.getValue())) - .collect(Collectors.toList()); - } - - /** - * {@inheritDoc} - */ - @Override - @Transactional(readOnly = true) - public CabinetPaginationDto getCabinetPaginationByLentType(LentType lentType, Integer page, - Integer size) { - log.debug("getCabinetPaginationByLentType"); - if (size <= 0) { - size = Integer.MAX_VALUE; - } - PageRequest pageable = PageRequest.of(page, size); - Page cabinets = cabinetOptionalFetcher.findPaginationByLentType(lentType, - pageable); - List cabinetDtos = cabinets.toList().stream() - .map((cabinet) -> cabinetMapper.toCabinetDto(cabinet)) - .collect(Collectors.toList()); - return cabinetMapper.toCabinetPaginationDtoList(cabinetDtos, - cabinets.getTotalElements()); - } - - /** - * {@inheritDoc} - */ - @Override - @Transactional(readOnly = true) - public CabinetPaginationDto getCabinetPaginationByStatus(CabinetStatus status, Integer page, - Integer size) { - log.debug("getCabinetPaginationByStatus"); - if (size <= 0) { - size = Integer.MAX_VALUE; - } - PageRequest pageable = PageRequest.of(page, size); - Page cabinets = cabinetOptionalFetcher.findPaginationByStatus(status, pageable); - List cabinetDtos = cabinets.toList().stream() - .map((cabinet) -> cabinetMapper.toCabinetDto(cabinet)) - .collect(Collectors.toList()); - return cabinetMapper.toCabinetPaginationDtoList(cabinetDtos, - cabinets.getTotalElements()); - } - - /** - * {@inheritDoc} - */ - @Override - @Transactional(readOnly = true) - public CabinetPaginationDto getCabinetPaginationByVisibleNum(Integer visibleNum, Integer page, - Integer size) { - log.debug("getCabinetPaginationByVisibleNum"); - if (size <= 0) { - size = Integer.MAX_VALUE; - } - PageRequest pageable = PageRequest.of(page, size); - Page cabinets = cabinetOptionalFetcher.findPaginationByVisibleNum(visibleNum, - pageable); - List cabinetDtos = cabinets.toList().stream() - .map((cabinet) -> cabinetMapper.toCabinetDto(cabinet)) - .collect(Collectors.toList()); - return cabinetMapper.toCabinetPaginationDtoList(cabinetDtos, - cabinets.getTotalElements()); - } - - /** - * {@inheritDoc} - */ - @Override - @Transactional(readOnly = true) - public LentHistoryPaginationDto getCabinetLentHistoriesPagination(Long cabinetId, Integer page, - Integer size) { - log.debug("getCabinetLentHistoriesPagination"); - if (size <= 0) { - size = Integer.MAX_VALUE; - } - PageRequest pageable = PageRequest.of(page, size, - Sort.by(Sort.Direction.DESC, "startedAt")); - Page lentHistories = lentOptionalFetcher.findPaginationByCabinetId(cabinetId, - pageable); - return lentMapper.toLentHistoryPaginationDto( - generateLentHistoryDtoList(lentHistories.toList()), - lentHistories.getTotalElements()); - } - - /** - * 사물함들의 정보와 각각의 대여 정보들을 가져옵니다. - * - * @param cabinetIds 사물함 id 리스트 - * @return 사물함 정보 리스트 - */ - @Transactional(readOnly = true) - public List getCabinetInfoBundle(List cabinetIds) { - log.debug("getCabinetInfoBundle"); - List result = new ArrayList<>(); - for (Long cabinetId : cabinetIds) { - CabinetInfoResponseDto cabinetInfo = getCabinetInfo(cabinetId); - if (CabinetInfoResponseDto.isValid(cabinetInfo)) { - result.add(cabinetInfo); - } - } - // Sorting ASC by Cabinet Floor - Comparator floorComparator = Comparator.comparing( - dto -> dto.getLocation().getFloor()); - - Collections.sort(result, floorComparator); - return result; - } - - @Override - @Transactional(readOnly = true) - public CabinetInfoPaginationDto getCabinetsInfo(Integer visibleNum) { - log.debug("getCabinetsInfo"); - PageRequest page = PageRequest.of(0, Integer.MAX_VALUE); - Page allCabinetsByVisibleNum = cabinetOptionalFetcher.findPaginationByVisibleNum( - visibleNum, page); - List collect = allCabinetsByVisibleNum.map(cabinet -> cabinet.getCabinetId()) - .stream().collect(Collectors.toList()); - return new CabinetInfoPaginationDto(getCabinetInfoBundle(collect), - allCabinetsByVisibleNum.getTotalElements()); - } - - /** - * LentHistory를 이용해 LentHistoryDto로 매핑하여 반환합니다. - * ToDo : new -> mapper 쓰기 + query service 분리 - * - * @param lentHistories 대여 기록 리스트 - * @return LentHistoryDto 리스트 - */ - private List generateLentHistoryDtoList( - List lentHistories) { - log.debug("generateLentHistoryDtoList"); - return lentHistories.stream() - .map(e -> lentMapper.toLentHistoryDto(e, - e.getUser(), - e.getCabinet())) - .collect(Collectors.toList()); - } - - /*--------------------------------------------CUD--------------------------------------------*/ - - /** - * {@inheritDoc} - */ - @Override - @Transactional - public void updateCabinetStatusNote(Long cabinetId, String statusNote) { - cabinetService.updateStatusNote(cabinetId, statusNote); - } - - /** - * {@inheritDoc} - */ - @Override - @Transactional - public void updateCabinetTitle(Long cabinetId, String title) { - cabinetService.updateTitle(cabinetId, title); - } - - /** - * {@inheritDoc} - */ - @Override - @Transactional - public void updateCabinetGrid(Long cabinetId, Integer row, Integer col) { - cabinetService.updateGrid(cabinetId, Grid.of(row, col)); - } - - /** - * {@inheritDoc} - */ - @Override - @Transactional - public void updateCabinetVisibleNum(Long cabinetId, Integer visibleNum) { - cabinetService.updateVisibleNum(cabinetId, visibleNum); - } - - /** - * {@inheritDoc} - */ - @Override - @Transactional - public void updateCabinetBundleStatus(CabinetStatusRequestDto cabinetStatusRequestDto) { - CabinetStatus status = cabinetStatusRequestDto.getStatus(); - LentType lentType = cabinetStatusRequestDto.getLentType(); - for (Long cabinetId : cabinetStatusRequestDto.getCabinetIds()) { - if (status != null) { - cabinetService.updateStatus(cabinetId, cabinetStatusRequestDto.getStatus()); - } - if (lentType != null) { - cabinetService.updateLentType(cabinetId, cabinetStatusRequestDto.getLentType()); - } - } - } - - - /** - * 사물함에 동아리 유저를 대여 시킵니다. - * - * @param cabinetClubStatusRequestDto - */ - @Override - @Transactional - public void updateCabinetClubStatus(CabinetClubStatusRequestDto cabinetClubStatusRequestDto) { - cabinetService.updateClub(cabinetClubStatusRequestDto.getCabinetId(), - cabinetClubStatusRequestDto.getUserId(), - cabinetClubStatusRequestDto.getStatusNote()); - } + ArrayList users = lentRedis.getUserIdsByCabinetIdInRedis( + cabinetId.toString()); + for (String user : users) { + String userName = userOptionalFetcher.findUser(Long.valueOf(user)).getName(); + lentDtos.add(new LentDto(Long.valueOf(user), userName, null, null, null)); + } + } + for (LentHistory lentHistory : lentHistories) { + User findUser = lentHistory.getUser(); + lentDtos.add(lentMapper.toLentDto(findUser, lentHistory)); + } + return cabinetMapper.toCabinetInfoResponseDto(cabinetOptionalFetcher.findCabinet(cabinetId), + lentDtos, lentRedis.getSessionExpiredAtInRedis(cabinetId)); + } + + /** + * {@inheritDoc} + */ + @Override + @Transactional(readOnly = true) + public CabinetSimplePaginationDto getCabinetsSimpleInfoByVisibleNum(Integer visibleNum) { + log.debug("getCabinetsSimpleInfoByVisibleNum"); + PageRequest page = PageRequest.of(0, Integer.MAX_VALUE); + Page allCabinetsByVisibleNum = cabinetOptionalFetcher.findPaginationByVisibleNum( + visibleNum, page); + List cabinetsSimple = allCabinetsByVisibleNum.stream().map( + cabinetMapper::toCabinetSimpleDto).collect(Collectors.toList()); + return new CabinetSimplePaginationDto(cabinetsSimple, + allCabinetsByVisibleNum.getTotalElements()); + } + + /** + * {@inheritDoc} + */ + @Override + @Transactional(readOnly = true) + public List getCabinetsPerSection(String building, + Integer floor) { + log.debug("getCabinetsPerSection"); + List currentLentCabinets = cabinetOptionalFetcher.findCabinetsActiveLentHistoriesByBuildingAndFloor( + building, floor); + List allCabinetsByBuildingAndFloor = cabinetOptionalFetcher.findAllCabinetsByBuildingAndFloor( + building, floor); + + Map> cabinetLentHistories = currentLentCabinets.stream(). + collect(Collectors.groupingBy(ActiveCabinetInfoEntities::getCabinet, + Collectors.mapping(ActiveCabinetInfoEntities::getLentHistory, + Collectors.toList()))); + + Map> cabinetPreviewsBySection = new HashMap<>(); + cabinetLentHistories.forEach((cabinet, lentHistories) -> { + String section = cabinet.getCabinetPlace().getLocation().getSection(); + CabinetPreviewDto preview = createCabinetPreviewDto(cabinet, lentHistories); + if (cabinetPreviewsBySection.containsKey(section)) { + cabinetPreviewsBySection.get(section).add(preview); + } else { + List previews = new ArrayList<>(); + previews.add(preview); + cabinetPreviewsBySection.put(section, previews); + } + }); + allCabinetsByBuildingAndFloor.forEach(cabinet -> { + if (!cabinetLentHistories.containsKey(cabinet)) { + String section = cabinet.getCabinetPlace().getLocation().getSection(); + CabinetPreviewDto preview = createCabinetPreviewDto(cabinet, + Collections.emptyList()); + if (cabinetPreviewsBySection.containsKey(section)) { + cabinetPreviewsBySection.get(section).add(preview); + } else { + List previews = new ArrayList<>(); + previews.add(preview); + cabinetPreviewsBySection.put(section, previews); + } + } + }); + cabinetPreviewsBySection.values().forEach(cabinetList -> cabinetList.sort( + Comparator.comparing(CabinetPreviewDto::getVisibleNum))); + return cabinetPreviewsBySection.entrySet().stream() + .sorted(Comparator.comparing(entry -> entry.getValue().get(0).getVisibleNum())) + .map(entry -> cabinetMapper.toCabinetsPerSectionResponseDto(entry.getKey(), + entry.getValue())) + .collect(Collectors.toList()); + } + + @Override + public List getCabinetsPerSectionRefactor(String building, + Integer floor) { + List cabinets = cabinetOptionalFetcher.findAllCabinetsByBuildingAndFloor(building, + floor); + Map> map = new HashMap<>(); + cabinets.forEach(cabinet -> { + List lentHistories = lentOptionalFetcher + .findActiveLentByCabinetIdWithUser(cabinet.getCabinetId()); + String section = cabinet.getCabinetPlace().getLocation().getSection(); + if (map.containsKey(section)) { + map.get(section) + .add(cabinetMapper.toCabinetPreviewDto(cabinet, lentHistories.size(), + lentHistories.isEmpty() ? null + : lentHistories.get(0).getUser().getName())); + } else { + List cabinetPreviewDtoList = new ArrayList<>(); + cabinetPreviewDtoList.add( + cabinetMapper.toCabinetPreviewDto(cabinet, lentHistories.size(), + lentHistories.isEmpty() ? null + : lentHistories.get(0).getUser().getName())); + map.put(section, cabinetPreviewDtoList); + } + }); + map.forEach( + (key, value) -> value.sort(Comparator.comparing(CabinetPreviewDto::getVisibleNum))); + return map.entrySet().stream() + .sorted(Comparator.comparing(entry -> entry.getValue().get(0).getVisibleNum())) + .map(entry -> cabinetMapper.toCabinetsPerSectionResponseDto(entry.getKey(), + entry.getValue())) + .collect(Collectors.toList()); + } + + private CabinetPreviewDto createCabinetPreviewDto(Cabinet cabinet, + List lentHistories) { + String lentUserName = null; + if (!lentHistories.isEmpty() && lentHistories.get(0).getUser() != null) { + lentUserName = lentHistories.get(0).getUser().getName(); + } + return cabinetMapper.toCabinetPreviewDto(cabinet, lentHistories.size(), lentUserName); + } + + @Override + public List getCabinetsPerSectionDSL(String building, + Integer floor) { + log.debug("getCabinetsPerSection"); + List currentLentCabinets = cabinetOptionalFetcher.findCabinetsActiveLentHistoriesByBuildingAndFloor2( + building, floor); + List allCabinetsByBuildingAndFloor = cabinetOptionalFetcher.findAllCabinetsByBuildingAndFloor( + building, floor); + + Map> cabinetLentHistories = currentLentCabinets.stream(). + collect(Collectors.groupingBy(ActiveCabinetInfoEntities::getCabinet, + Collectors.mapping(ActiveCabinetInfoEntities::getLentHistory, + Collectors.toList()))); + + Map> cabinetPreviewsBySection = new HashMap<>(); + cabinetLentHistories.forEach((cabinet, lentHistories) -> { + String section = cabinet.getCabinetPlace().getLocation().getSection(); + CabinetPreviewDto preview = createCabinetPreviewDto(cabinet, lentHistories); + if (cabinetPreviewsBySection.containsKey(section)) { + cabinetPreviewsBySection.get(section).add(preview); + } else { + List previews = new ArrayList<>(); + previews.add(preview); + cabinetPreviewsBySection.put(section, previews); + } + }); + allCabinetsByBuildingAndFloor.forEach(cabinet -> { + if (!cabinetLentHistories.containsKey(cabinet)) { + String section = cabinet.getCabinetPlace().getLocation().getSection(); + CabinetPreviewDto preview = createCabinetPreviewDto(cabinet, + Collections.emptyList()); + if (cabinetPreviewsBySection.containsKey(section)) { + cabinetPreviewsBySection.get(section).add(preview); + } else { + List previews = new ArrayList<>(); + previews.add(preview); + cabinetPreviewsBySection.put(section, previews); + } + } + }); + cabinetPreviewsBySection.values().forEach(cabinetList -> cabinetList.sort( + Comparator.comparing(CabinetPreviewDto::getVisibleNum))); + return cabinetPreviewsBySection.entrySet().stream() + .sorted(Comparator.comparing(entry -> entry.getValue().get(0).getVisibleNum())) + .map(entry -> cabinetMapper.toCabinetsPerSectionResponseDto(entry.getKey(), + entry.getValue())) + .collect(Collectors.toList()); + } + + /** + * {@inheritDoc} + */ + @Override + @Transactional(readOnly = true) + public CabinetPaginationDto getCabinetPaginationByLentType(LentType lentType, Integer page, + Integer size) { + log.debug("getCabinetPaginationByLentType"); + if (size <= 0) { + size = Integer.MAX_VALUE; + } + PageRequest pageable = PageRequest.of(page, size); + Page cabinets = cabinetOptionalFetcher.findPaginationByLentType(lentType, + pageable); + List cabinetDtos = cabinets.toList().stream() + .map((cabinet) -> cabinetMapper.toCabinetDto(cabinet)) + .collect(Collectors.toList()); + return cabinetMapper.toCabinetPaginationDtoList(cabinetDtos, + cabinets.getTotalElements()); + } + + /** + * {@inheritDoc} + */ + @Override + @Transactional(readOnly = true) + public CabinetPaginationDto getCabinetPaginationByStatus(CabinetStatus status, Integer page, + Integer size) { + log.debug("getCabinetPaginationByStatus"); + if (size <= 0) { + size = Integer.MAX_VALUE; + } + PageRequest pageable = PageRequest.of(page, size); + Page cabinets = cabinetOptionalFetcher.findPaginationByStatus(status, pageable); + List cabinetDtos = cabinets.toList().stream() + .map((cabinet) -> cabinetMapper.toCabinetDto(cabinet)) + .collect(Collectors.toList()); + return cabinetMapper.toCabinetPaginationDtoList(cabinetDtos, + cabinets.getTotalElements()); + } + + /** + * {@inheritDoc} + */ + @Override + @Transactional(readOnly = true) + public CabinetPaginationDto getCabinetPaginationByVisibleNum(Integer visibleNum, Integer page, + Integer size) { + log.debug("getCabinetPaginationByVisibleNum"); + if (size <= 0) { + size = Integer.MAX_VALUE; + } + PageRequest pageable = PageRequest.of(page, size); + Page cabinets = cabinetOptionalFetcher.findPaginationByVisibleNum(visibleNum, + pageable); + List cabinetDtos = cabinets.toList().stream() + .map((cabinet) -> cabinetMapper.toCabinetDto(cabinet)) + .collect(Collectors.toList()); + return cabinetMapper.toCabinetPaginationDtoList(cabinetDtos, + cabinets.getTotalElements()); + } + + /** + * {@inheritDoc} + */ + @Override + @Transactional(readOnly = true) + public LentHistoryPaginationDto getCabinetLentHistoriesPagination(Long cabinetId, Integer page, + Integer size) { + log.debug("getCabinetLentHistoriesPagination"); + if (size <= 0) { + size = Integer.MAX_VALUE; + } + PageRequest pageable = PageRequest.of(page, size, + Sort.by(Sort.Direction.DESC, "startedAt")); + Page lentHistories = lentOptionalFetcher.findPaginationByCabinetId(cabinetId, + pageable); + return lentMapper.toLentHistoryPaginationDto( + generateLentHistoryDtoList(lentHistories.toList()), + lentHistories.getTotalElements()); + } + + /** + * 사물함들의 정보와 각각의 대여 정보들을 가져옵니다. + * + * @param cabinetIds 사물함 id 리스트 + * @return 사물함 정보 리스트 + */ + @Transactional(readOnly = true) + public List getCabinetInfoBundle(List cabinetIds) { + log.debug("getCabinetInfoBundle"); + List result = new ArrayList<>(); + for (Long cabinetId : cabinetIds) { + CabinetInfoResponseDto cabinetInfo = getCabinetInfo(cabinetId); + if (CabinetInfoResponseDto.isValid(cabinetInfo)) { + result.add(cabinetInfo); + } + } + // Sorting ASC by Cabinet Floor + Comparator floorComparator = Comparator.comparing( + dto -> dto.getLocation().getFloor()); + + Collections.sort(result, floorComparator); + return result; + } + + @Override + @Transactional(readOnly = true) + public CabinetInfoPaginationDto getCabinetsInfo(Integer visibleNum) { + log.debug("getCabinetsInfo"); + PageRequest page = PageRequest.of(0, Integer.MAX_VALUE); + Page allCabinetsByVisibleNum = cabinetOptionalFetcher.findPaginationByVisibleNum( + visibleNum, page); + List collect = allCabinetsByVisibleNum.map(cabinet -> cabinet.getCabinetId()) + .stream().collect(Collectors.toList()); + return new CabinetInfoPaginationDto(getCabinetInfoBundle(collect), + allCabinetsByVisibleNum.getTotalElements()); + } + + /** + * LentHistory를 이용해 LentHistoryDto로 매핑하여 반환합니다. + * ToDo : new -> mapper 쓰기 + query service 분리 + * + * @param lentHistories 대여 기록 리스트 + * @return LentHistoryDto 리스트 + */ + private List generateLentHistoryDtoList( + List lentHistories) { + log.debug("generateLentHistoryDtoList"); + return lentHistories.stream() + .map(e -> lentMapper.toLentHistoryDto(e, + e.getUser(), + e.getCabinet())) + .collect(Collectors.toList()); + } + + /*--------------------------------------------CUD--------------------------------------------*/ + + /** + * {@inheritDoc} + */ + @Override + @Transactional + public void updateCabinetStatusNote(Long cabinetId, String statusNote) { + cabinetService.updateStatusNote(cabinetId, statusNote); + } + + /** + * {@inheritDoc} + */ + @Override + @Transactional + public void updateCabinetTitle(Long cabinetId, String title) { + cabinetService.updateTitle(cabinetId, title); + } + + /** + * {@inheritDoc} + */ + @Override + @Transactional + public void updateCabinetGrid(Long cabinetId, Integer row, Integer col) { + cabinetService.updateGrid(cabinetId, Grid.of(row, col)); + } + + /** + * {@inheritDoc} + */ + @Override + @Transactional + public void updateCabinetVisibleNum(Long cabinetId, Integer visibleNum) { + cabinetService.updateVisibleNum(cabinetId, visibleNum); + } + + /** + * {@inheritDoc} + */ + @Override + @Transactional + public void updateCabinetBundleStatus(CabinetStatusRequestDto cabinetStatusRequestDto) { + CabinetStatus status = cabinetStatusRequestDto.getStatus(); + LentType lentType = cabinetStatusRequestDto.getLentType(); + for (Long cabinetId : cabinetStatusRequestDto.getCabinetIds()) { + if (status != null) { + cabinetService.updateStatus(cabinetId, cabinetStatusRequestDto.getStatus()); + } + if (lentType != null) { + cabinetService.updateLentType(cabinetId, cabinetStatusRequestDto.getLentType()); + } + } + } + + + /** + * 사물함에 동아리 유저를 대여 시킵니다. + * + * @param cabinetClubStatusRequestDto + */ + @Override + @Transactional + public void updateCabinetClubStatus(CabinetClubStatusRequestDto cabinetClubStatusRequestDto) { + cabinetService.updateClub(cabinetClubStatusRequestDto.getCabinetId(), + cabinetClubStatusRequestDto.getUserId(), + cabinetClubStatusRequestDto.getStatusNote()); + } // /** // * {@inheritDoc} @@ -478,62 +478,62 @@ public void updateCabinetClubStatus(CabinetClubStatusRequestDto cabinetClubStatu // } // } - /** - * CACHE 적용되어 사용될 코드 - @Transactional(readOnly = true) - public List getCabinetsPerSection2(String building, - Integer floor) { - log.debug("getCabinetsPerSection2"); - List cabinetsByBuildingAndFloor2 = cabinetOptionalFetcher.findCabinetsByBuildingAndFloor2( - building, floor); - List currentLentCabinets = cabinetOptionalFetcher.findCabinetsActiveLentHistoriesByBuildingAndFloor2( - building, floor); - // List currentLentCabinets = cabinetOptionalFetcher.findCabinetsActiveLentHistoriesByBuildingAndFloor(building, floor); - List allCabinetsByBuildingAndFloor = cabinetOptionalFetcher.findAllCabinetsByBuildingAndFloor( - building, floor); - - // 층별 / 건물로 가져온 Cabinet 은 cache - // Cabinet 기준으로 lentHistory 를 조회 - // LentHistory와 연결된 User 조회 - - Map> cabinetLentHistories = currentLentCabinets.stream(). - collect(Collectors.groupingBy(ActiveCabinetInfoEntities::getCabinet, - Collectors.mapping(ActiveCabinetInfoEntities::getLentHistory, - Collectors.toList()))); - - Map> cabinetPreviewsBySection = new HashMap<>(); - cabinetLentHistories.forEach((cabinet, lentHistories) -> { - String section = cabinet.getCabinetPlace().getLocation().getSection(); - CabinetPreviewDto preview = createCabinetPreviewDto(cabinet, lentHistories); - if (cabinetPreviewsBySection.containsKey(section)) { - cabinetPreviewsBySection.get(section).add(preview); - } else { - List previews = new ArrayList<>(); - previews.add(preview); - cabinetPreviewsBySection.put(section, previews); - } - }); - allCabinetsByBuildingAndFloor.forEach(cabinet -> { - if (!cabinetLentHistories.containsKey(cabinet)) { - String section = cabinet.getCabinetPlace().getLocation().getSection(); - CabinetPreviewDto preview = createCabinetPreviewDto(cabinet, - Collections.emptyList()); - if (cabinetPreviewsBySection.containsKey(section)) { - cabinetPreviewsBySection.get(section).add(preview); - } else { - List previews = new ArrayList<>(); - previews.add(preview); - cabinetPreviewsBySection.put(section, previews); - } - } - }); - cabinetPreviewsBySection.values().forEach(cabinetList -> cabinetList.sort( - Comparator.comparing(CabinetPreviewDto::getVisibleNum))); - return cabinetPreviewsBySection.entrySet().stream() - .sorted(Comparator.comparing(entry -> entry.getValue().get(0).getVisibleNum())) - .map(entry -> cabinetMapper.toCabinetsPerSectionResponseDto(entry.getKey(), - entry.getValue())) - .collect(Collectors.toList()); - } - **/ + /** + * CACHE 적용되어 사용될 코드 + @Transactional(readOnly = true) + public List getCabinetsPerSection2(String building, + Integer floor) { + log.debug("getCabinetsPerSection2"); + List cabinetsByBuildingAndFloor2 = cabinetOptionalFetcher.findCabinetsByBuildingAndFloor2( + building, floor); + List currentLentCabinets = cabinetOptionalFetcher.findCabinetsActiveLentHistoriesByBuildingAndFloor2( + building, floor); + // List currentLentCabinets = cabinetOptionalFetcher.findCabinetsActiveLentHistoriesByBuildingAndFloor(building, floor); + List allCabinetsByBuildingAndFloor = cabinetOptionalFetcher.findAllCabinetsByBuildingAndFloor( + building, floor); + + // 층별 / 건물로 가져온 Cabinet 은 cache + // Cabinet 기준으로 lentHistory 를 조회 + // LentHistory와 연결된 User 조회 + + Map> cabinetLentHistories = currentLentCabinets.stream(). + collect(Collectors.groupingBy(ActiveCabinetInfoEntities::getCabinet, + Collectors.mapping(ActiveCabinetInfoEntities::getLentHistory, + Collectors.toList()))); + + Map> cabinetPreviewsBySection = new HashMap<>(); + cabinetLentHistories.forEach((cabinet, lentHistories) -> { + String section = cabinet.getCabinetPlace().getLocation().getSection(); + CabinetPreviewDto preview = createCabinetPreviewDto(cabinet, lentHistories); + if (cabinetPreviewsBySection.containsKey(section)) { + cabinetPreviewsBySection.get(section).add(preview); + } else { + List previews = new ArrayList<>(); + previews.add(preview); + cabinetPreviewsBySection.put(section, previews); + } + }); + allCabinetsByBuildingAndFloor.forEach(cabinet -> { + if (!cabinetLentHistories.containsKey(cabinet)) { + String section = cabinet.getCabinetPlace().getLocation().getSection(); + CabinetPreviewDto preview = createCabinetPreviewDto(cabinet, + Collections.emptyList()); + if (cabinetPreviewsBySection.containsKey(section)) { + cabinetPreviewsBySection.get(section).add(preview); + } else { + List previews = new ArrayList<>(); + previews.add(preview); + cabinetPreviewsBySection.put(section, previews); + } + } + }); + cabinetPreviewsBySection.values().forEach(cabinetList -> cabinetList.sort( + Comparator.comparing(CabinetPreviewDto::getVisibleNum))); + return cabinetPreviewsBySection.entrySet().stream() + .sorted(Comparator.comparing(entry -> entry.getValue().get(0).getVisibleNum())) + .map(entry -> cabinetMapper.toCabinetsPerSectionResponseDto(entry.getKey(), + entry.getValue())) + .collect(Collectors.toList()); + } + **/ } From 1cac9910b59a4a712b3414863c767de1a6282105 Mon Sep 17 00:00:00 2001 From: Woo Joo Chae Date: Sat, 25 Nov 2023 20:36:43 +0900 Subject: [PATCH 6/8] =?UTF-8?q?[BE]=20REFACTOR:=20ActiveLentExtension=20?= =?UTF-8?q?=EA=B4=80=EB=A0=A8=20=EB=A1=9C=EC=A7=81=EC=88=98=EC=A0=95=20-?= =?UTF-8?q?=20=ED=94=BC=EB=93=9C=EB=B0=B1=20=EB=B0=98=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/controller/UserController.java | 2 +- .../user/service/UserFacadeService.java | 362 +++++++++--------- .../user/service/UserFacadeServiceImpl.java | 32 +- 3 files changed, 203 insertions(+), 193 deletions(-) diff --git a/backend/src/main/java/org/ftclub/cabinet/user/controller/UserController.java b/backend/src/main/java/org/ftclub/cabinet/user/controller/UserController.java index c5487b537..ea9eecc90 100644 --- a/backend/src/main/java/org/ftclub/cabinet/user/controller/UserController.java +++ b/backend/src/main/java/org/ftclub/cabinet/user/controller/UserController.java @@ -62,7 +62,7 @@ public LentExtensionPaginationDto getMyLentExtension( public LentExtensionPaginationDto getMyActiveLentExtension( @UserSession UserSessionDto userSessionDto) { log.info("Called getMyActiveLentExtension: {}", userSessionDto.getName()); - return userFacadeService.getMyActiveLentExtension(userSessionDto); + return userFacadeService.getMyActiveLentExtensionPage(userSessionDto); } /** diff --git a/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeService.java b/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeService.java index 67f9c0b9e..55bad8521 100644 --- a/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeService.java +++ b/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeService.java @@ -17,185 +17,185 @@ public interface UserFacadeService { - /** - * 현재 로그인한 유저의 프로필을 반환합니다. 대여한 사물함 아이디 정보가 포합됩니다. - * - * @param user 로그인한 유저의 정보 - * @return {@link MyProfileResponseDto} 현재 로그인한 유저의 정보 - */ - MyProfileResponseDto getMyProfile(UserSessionDto user); - - /** - * 모든 정지 유저를 반환합니다. - * - * @param page 페이지 번호 - * @param size 페이지 당 길이 - * @param now 현재 시간 - * @return {@link BlockedUserPaginationDto} 모든 정지 유저 - */ - /* 기존 searchByBanUser와 동일한 역할을 합니다. */ - BlockedUserPaginationDto getAllBanUsers(Integer page, Integer size, LocalDateTime now); - - /** - * 유저 이름의 일부를 입력받아 해당하는 유저들의 프로필을 받아옵니다. - * - * @param name 유저 이름의 일부 - * @param page 페이지 번호 - * @param size 페이지 당 길이 - * @return {@link UserProfilePaginationDto} 해당하는 유저들의 프로필 - */ - /*기존 searchByIntraId 메서드와 동일한 역할을 합니다.*/ - UserProfilePaginationDto getUserProfileListByPartialName(String name, Integer page, - Integer size); - - /** - * 유저 이름의 일부를 입력받아 해당 유저들의 캐비넷 정보를 반환합니다. - * - * @param name 유저 이름의 일부 - * @param page 페이지 번호 - * @param size 페이지 당 길이 - * @return {@link UserCabinetPaginationDto} 해당하는 유저들의 캐비넷 정보 - */ - UserCabinetPaginationDto findUserCabinetListByPartialName(String name, Integer page, - Integer size); - - /** - * 모든 유저의 정보를 가져옵니다. - * - * @return 모든 유저의 정보를 가져옵니다. - */ - List getAllUsers(); - - /** - * 유저가 존재하는지 확인합니다. - * - * @param name 유저 이름 - * @return 유저가 존재하면 true, 아니면 false - */ - boolean checkUserExists(String name); - - /** - * 유저를 생성합니다. - * - * @param name 유저 이름 - * @param email 유저 이메일 - * @param blackholedAt 유저 블랙홀 날짜 - * @param role 유저 역할 - */ - void createUser(String name, String email, LocalDateTime blackholedAt, UserRole role); - - /** - * @param clubName 동아리 유저 이름 - */ - void createClubUser(String clubName); - - /** - * 관리자가 존재하는지 확인합니다. - * - * @param email 관리자 이메일 - * @return 관리자가 존재하면 true, 아니면 false - */ - boolean checkAdminUserExists(String email); - - /** - * 관리자를 생성합니다. - * - * @param email 관리자 이메일 - */ - void createAdminUser(String email); - - /** - * 유저를 삭제합니다. - * - * @param userId 유저 고유 아이디 - * @param deletedAt 유저 삭제 날짜 - */ - void deleteUser(Long userId, LocalDateTime deletedAt); - - /** - * 관리자를 삭제합니다. - * - * @param adminUserId 관리자 고유 아이디 - */ - void deleteAdminUser(Long adminUserId); - - /** - * 유저의 권한을 변경합니다. - * - * @param adminUserId 관리자 고유 아이디 - * @param role 관리자 권한 - */ - void updateAdminUserRole(Long adminUserId, AdminRole role); - - /** - * 유저를 어드민으로 승격시킵니다. - * - * @param email 유저 이메일 - */ - void promoteUserToAdmin(String email); - - /** - * 유저의 블랙홀 시간을 변경합니다. - * - * @param userId 유저 고유 아이디 - * @param newBlackholedAt 새로운 유저 블랙홀 시간 - */ - void updateUserBlackholedAt(Long userId, LocalDateTime newBlackholedAt); - - /** - * 유저를 정지시킵니다. - * - * @param userId 유저 고유 아이디 - * @param lentType 현재 대여 타입 - * @param startedAt 대여 시작 날짜 - * @param endedAt 대여 종료 날짜 - * @param expiredAt 대여 만료 날짜 - */ - void banUser(Long userId, LentType lentType, LocalDateTime startedAt, LocalDateTime endedAt, - LocalDateTime expiredAt); - - /** - * 유저의 정지를 해제합니다. - * - * @param userId 유저 고유 아이디 - * @param today 현재 날짜 - */ - void deleteRecentBanHistory(Long userId, LocalDateTime today); - - /** - * 연체 중인 유저 리스트를 반환합니다. - * - * @param page 페이지 번호 - * @param size 페이지 당 길이 - */ - OverdueUserCabinetPaginationDto getOverdueUserList(Integer page, Integer size); - - /** - * 동아리 유저 리스트DTO를 반환합니다. - * - * @param page 페이지 번호 - * @param size 페이지 당 길이 - * @return - */ - ClubUserListDto findAllClubUser(Integer page, Integer size); - - - /** - * 동아리 유저를 삭제합니다. - * - * @param clubId 동아리 고유 아이디 - */ - void deleteClubUser(Long clubId); - - void updateClubUser(Long clubId, String clubName); - - LentExtensionPaginationDto getAllLentExtension(Integer page, Integer size); - - LentExtensionPaginationDto getAllActiveLentExtension(Integer page, Integer size); - - LentExtensionPaginationDto getMyLentExtension(UserSessionDto userSessionDto); - - LentExtensionPaginationDto getMyActiveLentExtension(UserSessionDto userSessionDto); - - void useLentExtension(UserSessionDto userSessionDto); + /** + * 현재 로그인한 유저의 프로필을 반환합니다. 대여한 사물함 아이디 정보가 포합됩니다. + * + * @param user 로그인한 유저의 정보 + * @return {@link MyProfileResponseDto} 현재 로그인한 유저의 정보 + */ + MyProfileResponseDto getMyProfile(UserSessionDto user); + + /** + * 모든 정지 유저를 반환합니다. + * + * @param page 페이지 번호 + * @param size 페이지 당 길이 + * @param now 현재 시간 + * @return {@link BlockedUserPaginationDto} 모든 정지 유저 + */ + /* 기존 searchByBanUser와 동일한 역할을 합니다. */ + BlockedUserPaginationDto getAllBanUsers(Integer page, Integer size, LocalDateTime now); + + /** + * 유저 이름의 일부를 입력받아 해당하는 유저들의 프로필을 받아옵니다. + * + * @param name 유저 이름의 일부 + * @param page 페이지 번호 + * @param size 페이지 당 길이 + * @return {@link UserProfilePaginationDto} 해당하는 유저들의 프로필 + */ + /*기존 searchByIntraId 메서드와 동일한 역할을 합니다.*/ + UserProfilePaginationDto getUserProfileListByPartialName(String name, Integer page, + Integer size); + + /** + * 유저 이름의 일부를 입력받아 해당 유저들의 캐비넷 정보를 반환합니다. + * + * @param name 유저 이름의 일부 + * @param page 페이지 번호 + * @param size 페이지 당 길이 + * @return {@link UserCabinetPaginationDto} 해당하는 유저들의 캐비넷 정보 + */ + UserCabinetPaginationDto findUserCabinetListByPartialName(String name, Integer page, + Integer size); + + /** + * 모든 유저의 정보를 가져옵니다. + * + * @return 모든 유저의 정보를 가져옵니다. + */ + List getAllUsers(); + + /** + * 유저가 존재하는지 확인합니다. + * + * @param name 유저 이름 + * @return 유저가 존재하면 true, 아니면 false + */ + boolean checkUserExists(String name); + + /** + * 유저를 생성합니다. + * + * @param name 유저 이름 + * @param email 유저 이메일 + * @param blackholedAt 유저 블랙홀 날짜 + * @param role 유저 역할 + */ + void createUser(String name, String email, LocalDateTime blackholedAt, UserRole role); + + /** + * @param clubName 동아리 유저 이름 + */ + void createClubUser(String clubName); + + /** + * 관리자가 존재하는지 확인합니다. + * + * @param email 관리자 이메일 + * @return 관리자가 존재하면 true, 아니면 false + */ + boolean checkAdminUserExists(String email); + + /** + * 관리자를 생성합니다. + * + * @param email 관리자 이메일 + */ + void createAdminUser(String email); + + /** + * 유저를 삭제합니다. + * + * @param userId 유저 고유 아이디 + * @param deletedAt 유저 삭제 날짜 + */ + void deleteUser(Long userId, LocalDateTime deletedAt); + + /** + * 관리자를 삭제합니다. + * + * @param adminUserId 관리자 고유 아이디 + */ + void deleteAdminUser(Long adminUserId); + + /** + * 유저의 권한을 변경합니다. + * + * @param adminUserId 관리자 고유 아이디 + * @param role 관리자 권한 + */ + void updateAdminUserRole(Long adminUserId, AdminRole role); + + /** + * 유저를 어드민으로 승격시킵니다. + * + * @param email 유저 이메일 + */ + void promoteUserToAdmin(String email); + + /** + * 유저의 블랙홀 시간을 변경합니다. + * + * @param userId 유저 고유 아이디 + * @param newBlackholedAt 새로운 유저 블랙홀 시간 + */ + void updateUserBlackholedAt(Long userId, LocalDateTime newBlackholedAt); + + /** + * 유저를 정지시킵니다. + * + * @param userId 유저 고유 아이디 + * @param lentType 현재 대여 타입 + * @param startedAt 대여 시작 날짜 + * @param endedAt 대여 종료 날짜 + * @param expiredAt 대여 만료 날짜 + */ + void banUser(Long userId, LentType lentType, LocalDateTime startedAt, LocalDateTime endedAt, + LocalDateTime expiredAt); + + /** + * 유저의 정지를 해제합니다. + * + * @param userId 유저 고유 아이디 + * @param today 현재 날짜 + */ + void deleteRecentBanHistory(Long userId, LocalDateTime today); + + /** + * 연체 중인 유저 리스트를 반환합니다. + * + * @param page 페이지 번호 + * @param size 페이지 당 길이 + */ + OverdueUserCabinetPaginationDto getOverdueUserList(Integer page, Integer size); + + /** + * 동아리 유저 리스트DTO를 반환합니다. + * + * @param page 페이지 번호 + * @param size 페이지 당 길이 + * @return + */ + ClubUserListDto findAllClubUser(Integer page, Integer size); + + + /** + * 동아리 유저를 삭제합니다. + * + * @param clubId 동아리 고유 아이디 + */ + void deleteClubUser(Long clubId); + + void updateClubUser(Long clubId, String clubName); + + LentExtensionPaginationDto getAllLentExtension(Integer page, Integer size); + + LentExtensionPaginationDto getAllActiveLentExtension(Integer page, Integer size); + + LentExtensionPaginationDto getMyLentExtension(UserSessionDto userSessionDto); + + LentExtensionPaginationDto getMyActiveLentExtensionPage(UserSessionDto userSessionDto); + + void useLentExtension(UserSessionDto userSessionDto); } diff --git a/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeServiceImpl.java b/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeServiceImpl.java index f94b7e6a0..a086eb579 100644 --- a/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeServiceImpl.java +++ b/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeServiceImpl.java @@ -54,16 +54,32 @@ public class UserFacadeServiceImpl implements UserFacadeService { private final LentExtensionService lentExtensionService; private final LentExtensionOptionalFetcher lentExtensionOptionalFetcher; + private List getMyActiveLentExtension(UserSessionDto userSessionDto) { + log.debug("Called getMyActiveLentExtension"); + return lentExtensionOptionalFetcher.findLentExtensionByUserId(userSessionDto.getUserId()) + .parallelStream() + .filter(lentExtension -> lentExtension.getUsedAt() == null && + lentExtension.getExpiredAt().isAfter(LocalDateTime.now())) + .map(userMapper::toLentExtensionResponseDto) + .collect(Collectors.toList()); + } + @Override public MyProfileResponseDto getMyProfile(UserSessionDto user) { log.debug("Called getMyProfile: {}", user.getName()); + Cabinet cabinet = lentOptionalFetcher.findActiveLentCabinetByUserId(user.getUserId()); BanHistory banHistory = userOptionalFetcher.findRecentActiveBanHistory(user.getUserId(), LocalDateTime.now()); - List lentExtensionResponseDtos = getMyActiveLentExtension(user).getResult(); - if (lentExtensionResponseDtos.isEmpty()) + + List lentExtensionResponseDtos = getMyActiveLentExtension(user); + + if (lentExtensionResponseDtos.isEmpty()) { return userMapper.toMyProfileResponseDto(user, cabinet, banHistory, null); - return userMapper.toMyProfileResponseDto(user, cabinet, banHistory, lentExtensionResponseDtos.get(0)); + } + + return userMapper.toMyProfileResponseDto(user, cabinet, banHistory, + lentExtensionResponseDtos.get(0)); } @Override @@ -283,15 +299,9 @@ public LentExtensionPaginationDto getMyLentExtension(UserSessionDto userSessionD } @Override - public LentExtensionPaginationDto getMyActiveLentExtension(UserSessionDto userSessionDto) { + public LentExtensionPaginationDto getMyActiveLentExtensionPage(UserSessionDto userSessionDto) { log.debug("Called getMyActiveLentExtension"); - List result = - lentExtensionOptionalFetcher.findLentExtensionByUserId(userSessionDto.getUserId()) - .parallelStream() - .filter(lentExtension -> lentExtension.getUsedAt() == null && - lentExtension.getExpiredAt().isAfter(LocalDateTime.now())) - .map(userMapper::toLentExtensionResponseDto) - .collect(Collectors.toList()); + List result = getMyActiveLentExtension(userSessionDto); return userMapper.toLentExtensionPaginationDto(result, (long) result.size()); } From f44d8db06e619d700f93ab7d8d878c9e9a5071fd Mon Sep 17 00:00:00 2001 From: Woo Joo Chae Date: Sat, 25 Nov 2023 20:45:20 +0900 Subject: [PATCH 7/8] =?UTF-8?q?[BE]=20REFACTOR:=20getActiveLentExtensionLi?= =?UTF-8?q?st=20=EB=A9=94=EC=86=8C=EB=93=9C,=20LentExtensionService=20?= =?UTF-8?q?=EC=AA=BD=EC=9C=BC=EB=A1=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/service/LentExtensionService.java | 4 +++ .../service/LentExtensionServiceImpl.java | 29 +++++++++++++++---- .../user/service/UserFacadeServiceImpl.java | 18 ++++-------- 3 files changed, 32 insertions(+), 19 deletions(-) diff --git a/backend/src/main/java/org/ftclub/cabinet/user/service/LentExtensionService.java b/backend/src/main/java/org/ftclub/cabinet/user/service/LentExtensionService.java index f0a900bcb..03ea19898 100644 --- a/backend/src/main/java/org/ftclub/cabinet/user/service/LentExtensionService.java +++ b/backend/src/main/java/org/ftclub/cabinet/user/service/LentExtensionService.java @@ -1,5 +1,7 @@ package org.ftclub.cabinet.user.service; +import java.util.List; +import org.ftclub.cabinet.dto.LentExtensionResponseDto; import org.ftclub.cabinet.dto.UserSessionDto; public interface LentExtensionService { @@ -12,4 +14,6 @@ public interface LentExtensionService { void assignLentExtension(String username); + List getActiveLentExtensionList(UserSessionDto userSessionDto); + } diff --git a/backend/src/main/java/org/ftclub/cabinet/user/service/LentExtensionServiceImpl.java b/backend/src/main/java/org/ftclub/cabinet/user/service/LentExtensionServiceImpl.java index 1e76dde59..a7f2794c3 100644 --- a/backend/src/main/java/org/ftclub/cabinet/user/service/LentExtensionServiceImpl.java +++ b/backend/src/main/java/org/ftclub/cabinet/user/service/LentExtensionServiceImpl.java @@ -7,11 +7,14 @@ import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j2; import org.ftclub.cabinet.config.CabinetProperties; +import org.ftclub.cabinet.dto.LentExtensionResponseDto; import org.ftclub.cabinet.dto.UserMonthDataDto; +import org.ftclub.cabinet.dto.UserSessionDto; import org.ftclub.cabinet.exception.ExceptionStatus; import org.ftclub.cabinet.exception.ServiceException; import org.ftclub.cabinet.lent.domain.LentHistory; import org.ftclub.cabinet.lent.repository.LentOptionalFetcher; +import org.ftclub.cabinet.mapper.UserMapper; import org.ftclub.cabinet.occupiedtime.OccupiedTimeManager; import org.ftclub.cabinet.user.domain.LentExtension; import org.ftclub.cabinet.user.domain.LentExtensionType; @@ -33,6 +36,7 @@ public class LentExtensionServiceImpl implements LentExtensionService { private final UserOptionalFetcher userOptionalFetcher; private final CabinetProperties cabinetProperties; private final OccupiedTimeManager occupiedTimeManager; + private final UserMapper userMapper; @Override @Scheduled(cron = "${spring.schedule.cron.extension-issue-time}") @@ -67,6 +71,18 @@ public void assignLentExtension(String username) { lentExtensionRepository.save(lentExtension); } + @Override + public List getActiveLentExtensionList( + UserSessionDto userSessionDto) { + log.debug("Called getLentExtensionList {}", userSessionDto.getName()); + return lentExtensionOptionalFetcher.findLentExtensionByUserId(userSessionDto.getUserId()) + .parallelStream() + .filter(lentExtension -> lentExtension.getUsedAt() == null && + lentExtension.getExpiredAt().isAfter(LocalDateTime.now())) + .map(userMapper::toLentExtensionResponseDto) + .collect(Collectors.toList()); + } + @Override @Scheduled(cron = "${spring.schedule.cron.extension-delete-time}") public void deleteLentExtension() { @@ -80,18 +96,19 @@ public void useLentExtension(Long userId, String username) { List findLentExtension = lentExtensionOptionalFetcher.findLentExtensionByUserId(userId) - .stream() - .filter(lentExtension -> - lentExtension.getExpiredAt().isAfter(LocalDateTime.now()) - && lentExtension.getUsedAt() == null) - .collect(Collectors.toList()); + .stream() + .filter(lentExtension -> + lentExtension.getExpiredAt().isAfter(LocalDateTime.now()) + && lentExtension.getUsedAt() == null) + .collect(Collectors.toList()); if (findLentExtension.isEmpty()) { throw new ServiceException(ExceptionStatus.EXTENSION_NOT_FOUND); } LentExtension lentExtension = findLentExtension.get(0); LentHistory lentHistory = lentOptionalFetcher.getActiveLentHistoryWithUserId(userId); lentExtension.use(); - lentHistory.setExpiredAt(lentHistory.getExpiredAt().plusDays(lentExtension.getExtensionPeriod())); + lentHistory.setExpiredAt( + lentHistory.getExpiredAt().plusDays(lentExtension.getExtensionPeriod())); } } diff --git a/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeServiceImpl.java b/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeServiceImpl.java index a086eb579..97a8123a8 100644 --- a/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeServiceImpl.java +++ b/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeServiceImpl.java @@ -54,16 +54,6 @@ public class UserFacadeServiceImpl implements UserFacadeService { private final LentExtensionService lentExtensionService; private final LentExtensionOptionalFetcher lentExtensionOptionalFetcher; - private List getMyActiveLentExtension(UserSessionDto userSessionDto) { - log.debug("Called getMyActiveLentExtension"); - return lentExtensionOptionalFetcher.findLentExtensionByUserId(userSessionDto.getUserId()) - .parallelStream() - .filter(lentExtension -> lentExtension.getUsedAt() == null && - lentExtension.getExpiredAt().isAfter(LocalDateTime.now())) - .map(userMapper::toLentExtensionResponseDto) - .collect(Collectors.toList()); - } - @Override public MyProfileResponseDto getMyProfile(UserSessionDto user) { log.debug("Called getMyProfile: {}", user.getName()); @@ -72,12 +62,13 @@ public MyProfileResponseDto getMyProfile(UserSessionDto user) { BanHistory banHistory = userOptionalFetcher.findRecentActiveBanHistory(user.getUserId(), LocalDateTime.now()); - List lentExtensionResponseDtos = getMyActiveLentExtension(user); + List lentExtensionResponseDtos = lentExtensionService.getActiveLentExtensionList( + user); if (lentExtensionResponseDtos.isEmpty()) { return userMapper.toMyProfileResponseDto(user, cabinet, banHistory, null); } - + return userMapper.toMyProfileResponseDto(user, cabinet, banHistory, lentExtensionResponseDtos.get(0)); } @@ -301,7 +292,8 @@ public LentExtensionPaginationDto getMyLentExtension(UserSessionDto userSessionD @Override public LentExtensionPaginationDto getMyActiveLentExtensionPage(UserSessionDto userSessionDto) { log.debug("Called getMyActiveLentExtension"); - List result = getMyActiveLentExtension(userSessionDto); + List result = lentExtensionService.getActiveLentExtensionList( + userSessionDto); return userMapper.toLentExtensionPaginationDto(result, (long) result.size()); } From 13c87b5c2da24c2ad994d581f94d5f7ca50eb38d Mon Sep 17 00:00:00 2001 From: Woo Joo Chae Date: Sat, 25 Nov 2023 21:12:24 +0900 Subject: [PATCH 8/8] =?UTF-8?q?[BE]=20REFACTOR:=20getMyProfile=20=EC=97=90?= =?UTF-8?q?=EC=84=9C,=20LentExtension=20=ED=95=98=EB=82=98=EB=A7=8C=20?= =?UTF-8?q?=EA=B0=80=EC=A0=B8=EC=98=A4=EB=8F=84=EB=A1=9D=20=EB=A9=94?= =?UTF-8?q?=EC=86=8C=EB=93=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../repository/LentExtensionOptionalFetcher.java | 7 +++++-- .../user/repository/LentExtensionRepository.java | 3 ++- .../cabinet/user/service/UserFacadeServiceImpl.java | 13 ++++++------- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/backend/src/main/java/org/ftclub/cabinet/user/repository/LentExtensionOptionalFetcher.java b/backend/src/main/java/org/ftclub/cabinet/user/repository/LentExtensionOptionalFetcher.java index a83344b59..7c391f09d 100644 --- a/backend/src/main/java/org/ftclub/cabinet/user/repository/LentExtensionOptionalFetcher.java +++ b/backend/src/main/java/org/ftclub/cabinet/user/repository/LentExtensionOptionalFetcher.java @@ -3,8 +3,6 @@ import java.util.List; import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j2; -import org.ftclub.cabinet.exception.ExceptionStatus; -import org.ftclub.cabinet.exception.ServiceException; import org.ftclub.cabinet.user.domain.LentExtension; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -33,4 +31,9 @@ public Page findAllNotExpired(PageRequest pageable) { public List findLentExtensionByUserId(Long userId) { return lentExtensionRepository.findAllByUserId(userId); } + + @Transactional(readOnly = true) + public LentExtension findActiveLentExtensionByUserId(Long userId) { + return lentExtensionRepository.findByUserId(userId); + } } diff --git a/backend/src/main/java/org/ftclub/cabinet/user/repository/LentExtensionRepository.java b/backend/src/main/java/org/ftclub/cabinet/user/repository/LentExtensionRepository.java index 387f02d63..642113434 100644 --- a/backend/src/main/java/org/ftclub/cabinet/user/repository/LentExtensionRepository.java +++ b/backend/src/main/java/org/ftclub/cabinet/user/repository/LentExtensionRepository.java @@ -1,7 +1,6 @@ package org.ftclub.cabinet.user.repository; import java.util.List; -import java.util.Optional; import org.ftclub.cabinet.user.domain.LentExtension; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -26,4 +25,6 @@ public interface LentExtensionRepository extends JpaRepository findAllByUserId(@Param("userId") Long userId); + + LentExtension findByUserId(@Param("userId") Long userId); } diff --git a/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeServiceImpl.java b/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeServiceImpl.java index 97a8123a8..1b5b3d4a6 100644 --- a/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeServiceImpl.java +++ b/backend/src/main/java/org/ftclub/cabinet/user/service/UserFacadeServiceImpl.java @@ -62,15 +62,14 @@ public MyProfileResponseDto getMyProfile(UserSessionDto user) { BanHistory banHistory = userOptionalFetcher.findRecentActiveBanHistory(user.getUserId(), LocalDateTime.now()); - List lentExtensionResponseDtos = lentExtensionService.getActiveLentExtensionList( - user); - - if (lentExtensionResponseDtos.isEmpty()) { - return userMapper.toMyProfileResponseDto(user, cabinet, banHistory, null); - } + LentExtensionResponseDto lentExtensionResponseDto = + userMapper.toLentExtensionResponseDto( + lentExtensionOptionalFetcher.findActiveLentExtensionByUserId( + user.getUserId()) + ); return userMapper.toMyProfileResponseDto(user, cabinet, banHistory, - lentExtensionResponseDtos.get(0)); + lentExtensionResponseDto); } @Override