Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 86 additions & 88 deletions src/admin/pages/promotion/Promotion.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,22 @@ import AdminCarousel from "@admin/pages/promotion/components/AdminCarousel/Admin
import AdminBanner from "@admin/pages/promotion/components/AdminBanner/AdminBanner";
import { useGetCarouselPresignedUrl } from "@apis/domains/files/queries";
import { usePutS3Upload } from "@apis/domains/files/queries";
import { CarouselPresignedResponse } from "@apis/domains/files/api";
import { updateCarousel } from "@apis/domains/admins/api";
import { useModal } from "@hooks";

interface PendingCarouselUpload {
fileName: string;
objectUrl: string;
}

const isBlobUrl = (url?: string) => url?.startsWith("blob:") ?? false;

const Promotion = () => {
const { openAlert } = useModal();
const [tab, setTab] = useState("carousel");

const [carouselData, setCarouselData] = useState([]);
const [carouselImage, setCarouselImages] = useState<string[]>([]); // presigned 보낼 state
const [carouselUploads, setCarouselUploads] = useState<PendingCarouselUpload[]>([]);
const [initPromoNum, setInitPromoNum] = useState<number[]>([]); // 초기 promotionId

const handleTab = (value) => {
Expand All @@ -29,115 +35,107 @@ const Promotion = () => {
const saveCarouselData = (value) => {
setCarouselData(value);

const tempPresigned = carouselData?.map((item, index) => {
if (item.promotionPhoto?.indexOf("amazonaws") === -1) {
return `carousel-${index + 1}-${new Date().getTime()}`;
}
});

const filtered = tempPresigned.filter((element) => element !== undefined);

setCarouselImages(filtered);
const timestamp = Date.now();
setCarouselUploads(
value.flatMap((item, index) =>
isBlobUrl(item.promotionPhoto)
? [{ fileName: `carousel-${index + 1}-${timestamp}`, objectUrl: item.promotionPhoto }]
: []
)
);
};

const params = { carouselImages: carouselImage };
const params = { carouselImages: carouselUploads.map(({ fileName }) => fileName) };

const { data, refetch } = useGetCarouselPresignedUrl(params);
const { mutate } = usePutS3Upload();
const { refetch } = useGetCarouselPresignedUrl(params);
const { mutateAsync: uploadToS3 } = usePutS3Upload();

// 캐러셀 저장
const handleCarouselSave = async () => {
const { data, isSuccess } = await refetch();
try {
const uploadedImageKeys = new Map<string, string>();

if (isSuccess) {
const extractUrls = (data: CarouselPresignedResponse) => {
return Object.values(data.data.carouselPresignedUrls).map(
(url) => (url as string).split("?")[0]
);
};

const S3Urls = extractUrls(data);

const files = carouselData
.filter((item) => item.promotionPhoto && item.promotionPhoto.includes("blob"))
.map((item) => item.promotionPhoto);
if (carouselUploads.length > 0) {
const { data, isSuccess } = await refetch();
if (!isSuccess || !data) {
throw new Error("캐러셀 이미지 업로드 URL을 발급하지 못했습니다.");
}

try {
await Promise.all(
S3Urls.map(async (url, index) => {
const file = files[index];
carouselUploads.map(async ({ fileName, objectUrl }) => {
const upload = data.data.carouselPresignedUploads[fileName];
if (!upload) {
throw new Error("캐러셀 이미지 업로드 정보를 찾을 수 없습니다.");
}

const response = await fetch(objectUrl);
if (!response.ok) {
throw new Error("캐러셀 이미지 파일을 읽지 못했습니다.");
}

const response = await fetch(file);
const blob = await response.blob();
const newFile = new File([blob], `fileName-${new Date()}`, { type: blob.type });
const file = new File([blob], fileName, { type: blob.type });
const uploadResponse = await uploadToS3({ url: upload.uploadUrl, file });
if (!uploadResponse) {
throw new Error("캐러셀 이미지 업로드에 실패했습니다.");
}

return mutate({ url, file: newFile });
uploadedImageKeys.set(objectUrl, upload.imageKey);
})
);
}

let idxCnt = 0;
const tempCarouselData = carouselData.map((item) => ({
...item,
promotionPhoto: uploadedImageKeys.get(item.promotionPhoto) ?? item.promotionPhoto,
}));

const tempCarouselData = carouselData.map((item) => {
if (item.promotionPhoto?.indexOf("amazonaws") === -1) {
idxCnt += 1;
return { ...item, promotionPhoto: S3Urls[idxCnt - 1] };
}
return item;
});
const carouselNum = ["ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN"];

const carouselNum = ["ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN"];
const formData = {
carousels: tempCarouselData.map((item, index) => {
const { promotionPhoto, promotionId, ...rest } = item;

const formData = {
carousels: tempCarouselData.map((item, index) => {
const { promotionPhoto, promotionId, ...rest } = item;
const carouselItem = {
...rest,
type: initPromoNum.indexOf(item.promotionId) === -1 ? "generate" : "modify",
carouselNumber: carouselNum[index],
newImageUrl: item.promotionPhoto,
};

const carouselItem = {
...rest,
type: initPromoNum.indexOf(item.promotionId) === -1 ? "generate" : "modify",
carouselNumber: carouselNum[index],
newImageUrl: item.promotionPhoto,
};
if (initPromoNum.indexOf(item.promotionId) === -1) {
return carouselItem;
}
return { ...carouselItem, promotionId: item.promotionId };
}),
};

// promotionId가 initPromoNum에 없을 때 (새로 생성되었을 때)만 추가
if (initPromoNum.indexOf(item.promotionId) === -1) {
return carouselItem;
}
return { ...carouselItem, promotionId: item.promotionId };
}),
};
const allValid = formData.carousels.every(
(item) => Boolean(item.newImageUrl) && Boolean(item.redirectUrl)
);

const allValid = formData.carousels.every(
(item) => item.newImageUrl !== null && item.redirectUrl !== null
);
if (allValid && formData.carousels.length !== 0) {
await updateCarousel(formData);

console.log(formData);

if (allValid && formData.carousels.length !== 0) {
const res = await updateCarousel(formData);
console.log(res);
await console.log(formData);

await openAlert({
title: "캐러셀 수정이 완료되었습니다.",
okCallback: () => {
location.reload();
},
});
} else {
formData.carousels.forEach((item) => {
if (!item.newImageUrl && !item.redirectUrl) {
openAlert({ title: "정보가 없는 캐러셀은 삭제해 주세요." });
} else if (!item.newImageUrl) {
openAlert({ title: "모든 이미지를 삽입해 주세요." });
} else if (!item.redirectUrl) {
openAlert({ title: "모든 링크를 삽입해 주세요." });
}
});
}
} catch (err) {
console.error("Error during file upload or carousel update:", err);
openAlert({ title: "캐러셀 수정 혹은 이미지 저장을 실패했습니다.\n 다시 시도해주세요." });
await openAlert({
title: "캐러셀 수정이 완료되었습니다.",
okCallback: () => {
location.reload();
},
});
} else {
formData.carousels.forEach((item) => {
if (!item.newImageUrl && !item.redirectUrl) {
openAlert({ title: "정보가 없는 캐러셀은 삭제해 주세요." });
} else if (!item.newImageUrl) {
openAlert({ title: "모든 이미지를 삽입해 주세요." });
} else if (!item.redirectUrl) {
openAlert({ title: "모든 링크를 삽입해 주세요." });
}
});
}
Comment on lines +117 to 136

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

캐러셀을 전부 삭제한 뒤 저장하면 아무 반응이 없습니다.

formData.carousels.length === 0이면 updateCarousel도 호출되지 않고 else 분기의 forEach도 순회 대상이 없어 알림이 뜨지 않습니다. 사용자는 저장이 됐는지 알 수 없습니다. 빈 목록에 대한 처리(전체 삭제 저장을 허용하거나, 최소 1개 필요 안내)를 추가해 주세요.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/admin/pages/promotion/Promotion.tsx` around lines 117 - 136, Handle the
empty formData.carousels case in the save flow so deleting all carousels
produces an explicit outcome. Update the condition around updateCarousel and
validation to either allow saving the empty list and show the existing
completion alert, or show a clear minimum-one-carousel alert; ensure the empty
list does not fall through to a no-op forEach.

} catch {
openAlert({ title: "캐러셀 수정 혹은 이미지 저장을 실패했습니다.\n 다시 시도해주세요." });
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,17 @@ const AdminCarousel = ({ saveCarouselData, saveCarouselNum }) => {

useEffect(() => {
setCarouselList(data?.promotionList);
saveCarouselData(data?.promotionList ?? []);
saveCarouselNum(
data?.promotionList.map((item) => {
return item.promotionId;
})
}) ?? []
);
Comment on lines 30 to 34

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

promotionList가 없는 응답에서 .map 호출로 터집니다.

옵셔널 체이닝이 data?.promotionList까지만 적용되어 있어, data는 있고 promotionList가 undefined인 경우 .map에서 TypeError가 납니다(HomeFindAllResponse.promotionList는 스키마상 optional). ?? []는 이 경우를 막지 못합니다.

🐛 제안 수정
     saveCarouselNum(
-      data?.promotionList.map((item) => {
+      data?.promotionList?.map((item) => {
         return item.promotionId;
       }) ?? []
     );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
saveCarouselNum(
data?.promotionList.map((item) => {
return item.promotionId;
})
}) ?? []
);
saveCarouselNum(
data?.promotionList?.map((item) => {
return item.promotionId;
}) ?? []
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/admin/pages/promotion/components/AdminCarousel/AdminCarousel.tsx` around
lines 30 - 34, Update the saveCarouselNum call in AdminCarousel so the optional
promotionList is defaulted to an empty array before invoking map. Preserve the
existing promotionId extraction and ensure both missing data and missing
promotionList produce [] without throwing.


console.log(data?.promotionList, [
data?.promotionList.map((item) => {
return item.promotionId;
}),
]);
}, [data]);

const addCarousel = () => {
const newCarousel = {
promotionId: carouselList.length,
promotionId: -(Date.now() + carouselList.length),
promotionPhoto: null,
performanceId: null,
isExternal: false,
Expand All @@ -51,6 +46,7 @@ const AdminCarousel = ({ saveCarouselData, saveCarouselNum }) => {
const updatedCarouselList = [...carouselList, newCarousel];

setCarouselList(updatedCarouselList);
saveCarouselData(updatedCarouselList);
};

const deleteCarousel = (idx: number) => {
Expand Down
26 changes: 17 additions & 9 deletions src/apis/domains/files/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,23 @@
}

export interface PresignedResponse {
poster: ImageInterface;
cast: ImageInterface;
staff: ImageInterface;
performance: ImageInterface;
poster: Record<string, ImagePresignedUpload>;
cast: Record<string, ImagePresignedUpload>;
staff: Record<string, ImagePresignedUpload>;
performance: Record<string, ImagePresignedUpload>;
}

export interface ImagePresignedUpload {
uploadUrl: string;
imageKey: string;
}

export interface PresignedAllResponse {
status: number;
message: string;
data: {
performanceMakerPresignedUrls: PresignedResponse;
performanceMakerPresignedUrls: Record<string, ImageInterface>;
performanceMakerPresignedUploads: PresignedResponse;
Comment on lines +9 to +25

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# 스키마 정의와 수동 타입 선언 비교
rg -n -A4 'ImagePresignedUpload:|CarouselPresignedUploadResponse:|BannerPresignedUploadResponse:' src/typings/api/schema/index.ts
rg -n -B2 -A6 'interface ImagePresignedUpload' src
# uploadUrl 사용처
rg -n '\.uploadUrl' src

Repository: TEAM-BEAT/BEAT-Client

Length of output: 1813


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '--- src/apis/domains/files/api.ts lines 1-120 ---\n'
sed -n '1,120p' src/apis/domains/files/api.ts

printf '\n--- src/apis/domains/files/api.ts usages around presigned all response ---\n'
rg -n -B5 -A25 'PresignedAllResponse|getPresignedA|presigned|upload.*ImagePresignedUpload|data:.*ImagePresignedUpload' src/apis/domains/files/api.ts

printf '\n--- Register.tsx upload checks and calls ---\n'
sed -n '160,270p' src/pages/register/Register.tsx

printf '\n--- ModifyManage.tsx upload checks and calls ---\n'
sed -n '320,365p' src/pages/modifyManage/ModifyManage.tsx

printf '\n--- Promotion.tsx upload checks and calls ---\n'
sed -n '60,90p' src/admin/pages/promotion/Promotion.tsx

Repository: TEAM-BEAT/BEAT-Client

Length of output: 250


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '--- src/apis/domains/files/api.ts lines 1-120 ---\n'
sed -n '1,120p' src/apis/domains/files/api.ts

printf '\n--- src/apis/domains/files/api.ts usages around presigned all response ---\n'
rg -n -B5 -A25 'PresignedAllResponse|getPresignedA|presigned|upload.*ImagePresignedUpload|data:.*ImagePresignedUpload' src/apis/domains/files/api.ts

printf '\n--- Register.tsxo upload checks and calls ---\n'
sed -n '160,270p' src/pages/register/Register.tsx

printf '\n--- ModifyManage.tsx upload checks and calls ---\n'
sed -n '320,365p' src/pages/modifyManage/ModifyManage.tsx

printf '\n--- Promotion.tsx upload checks and calls ---\n'
sed -n '60,90p' src/admin/pages/promotion/Promotion.tsx

Repository: TEAM-BEAT/BEAT-Client

Length of output: 250


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- src/apis/domains/files/api.ts lines 1-120 ---'
sed -n '1,120p' src/apis/domains/files/api.ts

echo
echo '--- src/apis/domains/files/api.ts usages around presigned all response ---'
rg -n -B5 -A25 'PresignedAllResponse|getPresignedA|presigned|upload.*ImagePresignedUpload|data:.*ImagePresignedUpload' src/apis/domains/files/api.ts

echo
echo '--- Register.tsx upload checks and calls ---'
sed -n '160,270p' src/pages/register/Register.tsx

echo
echo '--- ModifyManage.tsx upload checks and calls ---'
sed -n '320,365p' src/pages/modifyManage/ModifyManage.tsx

echo
echo '--- Promotion.tsx upload checks and calls ---'
sed -n '60,90p' src/admin/pages/promotion/Promotion.tsx

Repository: TEAM-BEAT/BEAT-Client

Length of output: 12733


ImagePresignedUpload 필드는 optional로 맞춰 타입 계약을 맞춰주세요.

src/typings/api/schema/index.ts의 생성 스키마는 uploadUrl?: string; imageKey?: string;, 그리고 캐러셀 스키마도 동일합니다. 현재 필수 필드 선언은 실제 응답과 불일치하며, !upload 체크는 존재하는 객체의 uploadUrl/imageKey 누락을 걸지 못합니다. 필드를 optional로 두고 각 호출부에서 값을 검증한 뒤 S3 PUT을 진행하면 안전합니다.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/apis/domains/files/api.ts` around lines 9 - 25, Update the
ImagePresignedUpload interface so uploadUrl and imageKey are optional, matching
the generated schema contract. Then update each call site using
ImagePresignedUpload to validate both values before initiating the S3 PUT,
including cases where the upload object exists but either field is missing.

};
}

Expand Down Expand Up @@ -56,7 +62,7 @@
},
});

return response.data.data.performanceMakerPresignedUrls;
return response.data.data.performanceMakerPresignedUploads;
} catch (error) {
console.error("error", error);
return null;
Expand Down Expand Up @@ -88,16 +94,19 @@
export interface CarouselPresignedResponse {
data: {
carouselPresignedUrls: ImageInterface;
carouselPresignedUploads: Record<string, CarouselPresignedUpload>;
};
}

export type CarouselPresignedUpload = ImagePresignedUpload;

export interface GetCarouselPresignedUrlParams {
carouselImages: string[];
}

export const getCarouselPresignedUrl = async (
params: GetCarouselPresignedUrlParams
): Promise<CarouselPresignedResponse | null> => {
): Promise<CarouselPresignedResponse> => {
try {
const paramsWithEmptyArrays = {
...params,
Expand Down Expand Up @@ -126,8 +135,7 @@
);

return response.data;
} catch (error) {

Check warning on line 138 in src/apis/domains/files/api.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Add logic to this catch clause or eliminate it and rethrow the exception automatically.

See more on https://sonarcloud.io/project/issues?id=TEAM-BEAT_BEAT-Client&issues=AZ-j0s404Ln9rv4-Br6a&open=AZ-j0s404Ln9rv4-Br6a&pullRequest=523
console.error("error", error);
return null;
throw error;
}
};
32 changes: 0 additions & 32 deletions src/apis/domains/register/index.ts

This file was deleted.

Loading
Loading