fix(core,board,ecommerce): 조건부 검증 결함 패밀리 일괄 수정 및 실패 안내 노출

여러 화면에서 조건부(FormRequest) 검증이 우회되거나 과도하게 제한되던 결함을 한 계열로 묶어 수정한다.

- 검증 규칙 확장 필터 이름 10개를 나머지 92개와 동일 규칙으로 통일
- 설명 길이를 바이트가 아닌 글자 수로 계산(한글 오검출 해소)
- 비활성 언어팩 번역 보존한 채 수정 허용
- 알림 템플릿 제목 nullable 존중, 미지원 발송 수단 저장 차단
- 일정/실행 이력 목록 조회 검증 정합
- 게시판 첨부 미사용 시 빈 확장자 통과, new_display_hours/최소 길이 0 허용, 일괄 적용 override_values 범위 검증(SSoT)
- 이커머스 클레임 사유 조회 검증, 용어 정정
- 원문 i18n 키 노출 다수 해소, 저장/삭제 실패 시 사유 화면 노출
- 아이콘 크기/다크모드 대비 회귀 수정

번들 확장(모듈3·플러그인6·템플릿2·언어팩5) 버전 new-bump 및 CHANGELOG 반영, ja 언어팩 동기.
This commit is contained in:
HeuJung committed 2026-07-23 10:54:17 +09:00
1 parent c001b30a87
commit 7f8fb6870f
288 files changed
+5339 -1049

No files matched your search

@@ -16,6 +16,20 @@
- 사이트맵을 만들 때 게시판과 게시글을 한 번에 모두 메모리에 올리지 않고 나눠서 읽도록 바꿨습니다. 게시글이 많은 사이트에서 사이트맵 생성 중 메모리가 부족해 실패하던 문제가 줄어듭니다.
- 개선된 사이트맵 생성 기능을 사용하기 위해 이 모듈은 이제 코어 7.0.6 이상이 필요합니다.
### Fixed
- 첨부파일을 사용하지 않는 게시판을 아무것도 바꾸지 않고 저장해도 "허용 파일 확장자를 최소 1개 이상 입력하세요" 오류가 나며 저장이 막히던 문제를 수정했습니다. 첨부를 쓰지 않는 게시판에서는 허용 확장자를 비워 두어도 정상적으로 저장됩니다. 게시판 환경설정의 기본값도 동일하게 동작합니다. (#78 @jiwonpapa 님께서 제보해주셨습니다.)
- 새 글 표시 기간을 "0시간"(새 글 표시 안 함)으로 저장할 수 없던 문제를 수정했습니다. 0은 원래 새 글 배지를 끄는 값으로 동작하도록 되어 있었으나 저장 단계에서 막혀 있었습니다.
- 게시판 환경설정에서 제목·댓글 최소 길이를 0(제한 없음)으로 저장할 수 없던 문제를 수정했습니다. 내용 최소 길이는 0이 허용되어 같은 화면에서 항목마다 동작이 달랐습니다.
- 허용 확장자를 지정하지 않은 게시판에서 어떤 파일도 첨부할 수 없던 문제를 수정했습니다. 파일 선택 단계에서 막히던 것과 서버에서 거부되던 것을 함께 고쳐, 확장자를 지정하지 않은 게시판은 기본 확장자 목록을 사용합니다. 첨부 안내에 확장자가 비어 표시되던 것도 함께 해소됩니다. 확장자를 지정한 게시판은 지금처럼 목록에 없는 파일을 계속 거부합니다.
- 게시판 알림 설정에서 저장에 실패해도 아무 안내 없이 넘어가던 화면을 수정했습니다. 실패하면 그 이유가 화면에 표시됩니다.
- 일부 안내 문구가 실제 문장 대신 내부 식별자(`sirsoft-board::messages....` 같은 문자열)로 표시되던 문제를 수정했습니다. 첨부파일이 있는 게시판을 찾지 못했을 때, 댓글 목록을 불러오지 못했을 때, 비회원 댓글의 비밀번호를 확인할 때, 삭제·블라인드된 글에 댓글을 달려 할 때, 권한이 없어 거절될 때가 해당됩니다.
- 비밀글을 쓸 수 없는 게시판에서 비밀글로 저장하려 할 때, 답글 대상 게시판을 찾지 못했을 때, 신고 상태를 바꿀 수 없는 상태로 변경하려 할 때 나오던 안내가 정상 문장으로 표시됩니다.
- 댓글 수정, 신고 접수·처리, 블라인드·복원, 게시판 설정 일괄 적용 화면에서 오류 안내에 항목 이름이 영문 필드명으로 나오던 것을 한글 항목명으로 바로잡았습니다.
- 게시판 이름을 바꿨을 때 활동 로그의 변경 항목 이름이 비어 보이던 문제를 수정했습니다.
- 게시판 환경설정 조회·저장·일괄 적용과 관리자 대시보드 조회 화면에서 결과 안내가 실제 문장 대신 내부 식별자로 표시되던 문제를 수정했습니다.
- 환경설정을 여러 게시판에 일괄 적용할 때, 개별 저장 화면과 달리 글자 수·표시 시간 등의 값 범위 제한이 적용되지 않던 문제를 수정했습니다. 이제 일괄 적용도 개별 저장과 동일한 범위를 벗어난 값을 거부합니다.
## [1.0.2] - 2026-07-14
### Fixed
@@ -143,6 +143,10 @@ return [
'category_max' => 50,
// 신규 게시글 NEW 배지 표시 기간 (시간 단위, 0 = 표시 안 함)
'new_display_hours_min' => 0,
'new_display_hours_max' => 720,
// 답글 깊이 제한
'max_reply_depth_min' => 1,
'max_reply_depth_max' => 10,
@@ -216,7 +216,7 @@ HTTP/1.1 200
| use_reply | body | boolean | 예 | — | 게시글 답변(원글에 대한 답글) 기능 사용 여부 |
| use_report | body | boolean | 예 | — | 게시글/댓글 신고 기능 사용 여부 |
| comment_order | body | string | 예 | `ASC`, `DESC` | 댓글 정렬 순서 (ASC 오름차순 / DESC 내림차순) |
| new_display_hours | body | integer | 아니오 | min 1, max 720 | 신규(NEW) 표시를 유지할 기간 (시간 단위, 최대 720시간=30일) |
| new_display_hours | body | integer | 아니오 | min 0, max 720 | 신규(NEW) 표시를 유지할 기간 (시간 단위, 최대 720시간=30일). `0` 은 NEW 배지를 표시하지 않음 |
| min_title_length | body | integer | 아니오 | min 0, max 200 | 게시글 제목 최소 글자 수 |
| max_title_length | body | integer | 아니오 | min 1, max 1000 | 게시글 제목 최대 글자 수 |
| min_content_length | body | integer | 아니오 | min 0, max 10000 | 게시글 본문 최소 글자 수 |
@@ -226,7 +226,7 @@ HTTP/1.1 200
| use_file_upload | body | boolean | 예 | — | 파일 첨부 기능 사용 여부 (true일 때 allowed_extensions 최소 1개 필수) |
| max_file_size | body | integer | 아니오 | min 1, max 200 | 첨부파일 1개당 최대 크기 (MB 단위) |
| max_file_count | body | integer | 아니오 | min 1, max 20 | 게시글 1건당 첨부할 수 있는 최대 파일 개수 |
| allowed_extensions | body | array | 예 | min 1 | 업로드 허용 확장자 목록 (예: jpg, png, pdf — 첨부 사용 시 최소 1개 필수) |
| allowed_extensions | body | array | 조건부 | min 1 | 업로드 허용 확장자 목록 (예: jpg, png, pdf). `use_file_upload=true` 일 때만 필수이며 최소 1개가 있어야 한다. `use_file_upload=false` 이면 검증에서 제외되어 빈 배열·`null` 도 허용된다 |
| board_manager_ids | body | array | 예 | min 1 | board manager 식별자 배열 |
| board_step_ids | body | array | 아니오 | — | board step 식별자 배열 |
| permissions | body | array | 아니오 | — | 게시판별 세부 권한 매트릭스 (권한 키별 mode/roles — 미지정 시 Service가 Manager/Step 역할을 주입) |
@@ -1222,7 +1222,7 @@ HTTP/1.1 200
| use_reply | body | boolean | 예 | — | 게시글 답변(원글에 대한 답글) 기능 사용 여부 |
| use_report | body | boolean | 예 | — | 게시글/댓글 신고 기능 사용 여부 |
| comment_order | body | string | 예 | `ASC`, `DESC` | 댓글 정렬 순서 (ASC 오름차순 / DESC 내림차순) |
| new_display_hours | body | integer | 아니오 | min 1, max 720 | 신규(NEW) 표시를 유지할 기간 (시간 단위, 최대 720시간=30일) |
| new_display_hours | body | integer | 아니오 | min 0, max 720 | 신규(NEW) 표시를 유지할 기간 (시간 단위, 최대 720시간=30일). `0` 은 NEW 배지를 표시하지 않음 |
| min_title_length | body | integer | 아니오 | min 0, max 200 | 게시글 제목 최소 글자 수 |
| max_title_length | body | integer | 아니오 | min 1, max 1000 | 게시글 제목 최대 글자 수 |
| min_content_length | body | integer | 아니오 | min 0, max 10000 | 게시글 본문 최소 글자 수 |
@@ -1232,7 +1232,7 @@ HTTP/1.1 200
| use_file_upload | body | boolean | 예 | — | 파일 첨부 기능 사용 여부 (true일 때 allowed_extensions 최소 1개 필수) |
| max_file_size | body | integer | 아니오 | min 1, max 200 | 첨부파일 1개당 최대 크기 (MB 단위) |
| max_file_count | body | integer | 아니오 | min 1, max 20 | 게시글 1건당 첨부할 수 있는 최대 파일 개수 |
| allowed_extensions | body | array | 아니오 | min 1 | 업로드 허용 확장자 목록 (예: jpg, png, pdf — 첨부 사용 시 최소 1개 필수) |
| allowed_extensions | body | array | 조건부 | min 1 | 업로드 허용 확장자 목록 (예: jpg, png, pdf). `use_file_upload=true` 일 때만 필수이며 최소 1개가 있어야 한다. `use_file_upload=false` 이면 검증에서 제외되어 빈 배열·`null` 도 허용된다 |
| board_manager_ids | body | array | 예 | min 1 | board manager 식별자 배열 |
| board_step_ids | body | array | 아니오 | — | board step 식별자 배열 |
| permissions | body | array | 예 | — | 게시판별 세부 권한 매트릭스 (권한 키별 mode/roles — 각 권한을 all 또는 특정 역할에 부여) |
@@ -361,7 +361,7 @@ HTTP/1.1 200
| --- | --- | --- | --- | --- | --- |
| _tab | body | string | 아니오 | `basic_defaults`, `report_policy`, `spam_security`, `general`, `seo`, `notifications`, `notification_definitions` | 현재 편집 중인 탭을 나타내는 메타 값. 탭 단위 부분 저장의 컨텍스트를 식별하는 용도이며 설정값으로는 저장되지 않습니다. |
| notifications | body | array | 아니오 | — | 알림 채널 설정. `channels` 배열의 각 항목에 채널 식별자(id), 활성화 여부(is_active), 정렬 순서(sort_order)를 담아 저장합니다. |
| basic_defaults | body | array | 아니오 | — | 기본 설정 카테고리 값. 게시판 타입·페이지당 글 수·정렬·댓글/답글·길이 제한·파일 업로드·기본 권한 등 basic_defaults 하위 키를 저장합니다. |
| basic_defaults | body | array | 아니오 | — | 기본 설정 카테고리 값. 게시판 타입·페이지당 글 수·정렬·댓글/답글·길이 제한·파일 업로드·기본 권한 등 basic_defaults 하위 키를 저장합니다. `basic_defaults.allowed_extensions` 는 `basic_defaults.use_file_upload` 가 `true` 일 때만 최소 1개가 필수이며, `false`/`null` 이면 검증에서 제외되어 빈 배열도 허용됩니다. `min_title_length`·`min_comment_length`·`new_display_hours` 의 하한은 `config('sirsoft-board.limits')` 선언을 따르며 `0` 을 허용합니다. |
| report_policy | body | array | 아니오 | — | 신고 정책 카테고리 값. 자동 숨김 임계치/대상, 일일 신고 한도, 거부 누적 제한, 관리자·작성자 신고 알림 설정을 저장합니다. |
| report_permissions | body | array | 아니오 | — | 신고 관리 권한 역할. `view_roles`(조회 역할)와 `manage_roles`(관리 역할)의 역할 식별자 배열이며, 포함 시 설정 저장과 별개로 DB 권한 역할이 동기화됩니다. |
| display | body | array | 아니오 | — | 표시 설정 카테고리 값. 날짜 표시 형식(date_display_format: standard/relative) 등을 저장합니다. |
@@ -312,4 +312,46 @@ describe('업로드 에러 시 isSaving 복구 (onUploadError)', () => {
const uploader = fileUploaders[0];
expect(uploader.props.uploadParams.post_id).toBeUndefined();
});
// ==========================================
// accept 표현식 — 빈 확장자 배열 truthiness (#78 R3 회귀)
//
// API 는 allowed_extensions 를 "항상 배열"로 직렬화한다(BoardResource 가 NULL → []).
// 그런데 레이아웃이 `ext ? ... : fallback` 으로 판정하면 []가 JS 에서 truthy 라
// accept="." 가 되어 useFileUploader 확장자 게이트가 전 파일을 거부한다.
// 서버는 정상인데 사용자는 파일 선택 단계에서 막히므로 요청조차 발생하지 않는다.
// → 길이 판정(`?.length` )이어야 한다.
// ==========================================
/**
* accept 표현식이 빈 배열을 fallback 으로 흘리는지 평가합니다.
*/
function evaluateAccept(expression: string, allowedExtensions: unknown): string {
const body = expression.replace(/^\{\{/, '').replace(/\}\}$/, '');
const form_meta = { data: { board: { allowed_extensions: allowedExtensions } } };
// eslint-disable-next-line no-new-func
return new Function('form_meta', `return (${body});`)(form_meta);
}
const FALLBACK = '.jpg,.jpeg,.png,.gif,.pdf,.zip';
it.each([
['관리자 첨부파일', () => findComponentsByName(adminAttachments, 'FileUploader')[0]],
['사용자 폼', () => findComponentsByName(userPostForm, 'FileUploader')[0]],
])('%s accept 는 빈 확장자 배열에서 기본 확장자로 폴백해야 합니다 (#78 R3)', (_label, getUploader) => {
const accept = (getUploader() as any).props.accept as string;
expect(evaluateAccept(accept, [])).toBe(FALLBACK);
expect(evaluateAccept(accept, null)).toBe(FALLBACK);
expect(evaluateAccept(accept, undefined)).toBe(FALLBACK);
});
it.each([
['관리자 첨부파일', () => findComponentsByName(adminAttachments, 'FileUploader')[0]],
['사용자 폼', () => findComponentsByName(userPostForm, 'FileUploader')[0]],
])('%s accept 는 지정된 확장자를 그대로 반영해야 합니다', (_label, getUploader) => {
const accept = (getUploader() as any).props.accept as string;
expect(evaluateAccept(accept, ['jpg', 'png'])).toBe('.jpg,.png');
});
});
@@ -321,9 +321,11 @@ describe('admin_board_settings.json - 메인 레이아웃', () => {
const content = mainLayout.slots.content[0];
const stickyHeader = findById(content, 'sticky_header');
expect(stickyHeader).toBeDefined();
// sirsoft-admin_basic 의 .sticky-tab-nav-responsive 자산 사용 (responsive padding 화면 전용 — #408)
// 자산 정의: sticky top-0 z-40 -mx-{4,6,8} px-{4,6,8} border-b bg-gray-50 dark:bg-gray-900
expect(stickyHeader.props.className).toContain('sticky-tab-nav-responsive');
// sirsoft-admin_basic 의 .sticky-section-header 자산 사용.
// 자식(header_content)이 자체 padding 을 가지므로 좌우 -mx/px override 가 없는 변형을 쓴다
// (main.css 의 .sticky-section-header 주석이 "게시판 설정" 을 대상으로 명시).
// -mx/px override 가 있는 .sticky-tab-nav-responsive 를 쓰면 자식 padding 과 겹쳐 어긋난다.
expect(stickyHeader.props.className).toContain('sticky-section-header');
// 하위 탭 네비게이션이 basic_defaults 탭에서만 표시 (TabNavigationScroll - 스크롤 방식)
const subTabNav = findById(content, 'sub_tab_navigation');
@@ -212,7 +212,7 @@ describe('admin_dashboard_community.json - community 슬롯 주입', () => {
// 따라서 실제 응답은 { success, message, data: [...] } 이고, 바인딩은 data.data 가 아닌 data 다.
const list = findById(communityExt as any, 'latest_posts_list');
expect(list.iteration).toBeUndefined();
const item = findById(communityExt as any, 'latest_post_item');
const item = findById(communityExt as any, 'latest_post_item_{{i}}');
expect(item.iteration).toBeDefined();
expect(item.iteration.source).toBe('board_recent_posts?.data');
expect(item.iteration.item_var).toBe('post');
@@ -222,7 +222,7 @@ describe('admin_dashboard_community.json - community 슬롯 주입', () => {
it('미처리 신고 항목(report_item)에 iteration 이 정의된다', () => {
const list = findById(communityExt as any, 'report_management_list');
expect(list.iteration).toBeUndefined();
const item = findById(communityExt as any, 'report_item');
const item = findById(communityExt as any, 'report_item_{{i}}');
expect(item.iteration).toBeDefined();
expect(item.iteration.source).toBe('board_pending_reports?.data?.items');
expect(item.iteration.item_var).toBe('report');
@@ -246,7 +246,7 @@ describe('admin_dashboard_community.json - community 슬롯 주입', () => {
});
it('최신 게시글 항목은 클릭 시 게시글 상세로 navigate 한다', () => {
const item = findById(communityExt as any, 'latest_post_item');
const item = findById(communityExt as any, 'latest_post_item_{{i}}');
expect(Array.isArray(item.actions)).toBe(true);
const click = item.actions.find((a: any) => a.type === 'click' && a.handler === 'navigate');
expect(click).toBeDefined();
@@ -254,7 +254,7 @@ describe('admin_dashboard_community.json - community 슬롯 주입', () => {
});
it('신고 항목은 클릭 시 신고 상세로 navigate 한다', () => {
const item = findById(communityExt as any, 'report_item');
const item = findById(communityExt as any, 'report_item_{{i}}');
expect(Array.isArray(item.actions)).toBe(true);
const click = item.actions.find((a: any) => a.type === 'click' && a.handler === 'navigate');
expect(click).toBeDefined();
@@ -266,7 +266,7 @@ describe('admin_dashboard_community.json - community 슬롯 주입', () => {
// 배지는 신고 대상(게시글/댓글)의 상태가 아니라 신고 건 자체의 처리상태(status)를 보여준다.
// 색상은 신고현황 페이지(admin_board_reports_index 의 status 컬럼) 와 동일한 매핑을 사용한다.
// 시각 검증 피드백: "대상 상태가 아닌 처리상태가 보여져야 한다" + "처리상태는 게시판 신고현황과 동일한 색상으로".
const statusBadge = findById(communityExt as any, 'report_status_badge');
const statusBadge = findById(communityExt as any, 'report_status_badge_{{i}}');
expect(statusBadge).not.toBeNull();
expect(statusBadge.if).toBe('{{!!report?.status_label}}');
expect(statusBadge.text).toBe('{{report?.status_label ?? \'\'}}');
@@ -286,7 +286,7 @@ describe('admin_dashboard_community.json - community 슬롯 주입', () => {
});
it('신고 카드의 타입 배지(report_target_type_badge)는 댓글/게시글 색상이 다르다', () => {
const typeBadge = findById(communityExt as any, 'report_target_type_badge');
const typeBadge = findById(communityExt as any, 'report_target_type_badge_{{i}}');
expect(typeBadge.props.className).toContain("comment");
expect(typeBadge.props.className).toContain('bg-purple-900');
expect(typeBadge.props.className).toContain('bg-blue-900');
@@ -110,7 +110,7 @@
"name": "Icon",
"props": {
"name": "lock",
"className": "w-5 h-5 text-amber-600 dark:text-amber-400 flex-shrink-0"
"className": "text-xl text-amber-600 dark:text-amber-400 flex-shrink-0"
}
},
{
@@ -210,7 +210,7 @@
"name": "Icon",
"props": {
"name": "triangle-exclamation",
"className": "w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5"
"className": "text-xl text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5"
}
},
{
@@ -427,7 +427,7 @@
},
{
"handler": "openWindow",
"condition": "{{!route?.slug}}",
"if": "{{!route?.slug}}",
"params": {
"path": "{{'/admin/boards/' + result.data.slug + '/edit'}}",
"target": "_self"
@@ -30,7 +30,7 @@
"name": "Icon",
"props": {
"name": "paperclip",
"className": "w-5 h-5 text-gray-700 dark:text-gray-300"
"className": "text-xl text-gray-700 dark:text-gray-300"
}
},
{
@@ -55,7 +55,7 @@
"collection": "post_attachments",
"maxFiles": "{{form_meta?.data?.board?.max_file_count ?? 5}}",
"maxSize": "{{form_meta?.data?.board?.max_file_size ?? 10}}",
"accept": "{{form_meta?.data?.board?.allowed_extensions ? '.' + form_meta.data.board.allowed_extensions.join(',.') : '.jpg,.jpeg,.png,.gif,.pdf,.zip'}}",
"accept": "{{form_meta?.data?.board?.allowed_extensions?.length ? '.' + form_meta.data.board.allowed_extensions.join(',.') : '.jpg,.jpeg,.png,.gif,.pdf,.zip'}}",
"initialFiles": "{{form_meta?.data?.attachments ?? []}}",
"autoUpload": false,
"uploadTriggerEvent": "upload:board_attachments",
@@ -840,7 +840,16 @@
"handler": "openModal",
"target": "modal_board_notification_template_preview"
}
]
],
"onError": [
{
"handler": "toast",
"params": {
"type": "error",
"message": "{{error.message}}"
}
}
]
}
]
}
@@ -410,7 +410,7 @@
"text": "$t:sirsoft-board.admin.settings.notification_definitions.no_template_for_channel"
},
{
"id": "board_recipients_badge",
"id": "board_recipients_badge_{{defIdx}}",
"type": "basic",
"name": "Div",
"if": "{{((def.templates ?? []).find(t => t.channel === (_local.activeNotificationChannel ?? query.channel ?? 'mail'))?.recipients ?? []).length > 0}}",
@@ -533,7 +533,16 @@
"type": "success"
}
}
]
],
"onError": [
{
"handler": "toast",
"params": {
"type": "error",
"message": "{{error.message}}"
}
}
]
}
]
},
@@ -0,0 +1,70 @@
<?php
namespace Modules\Sirsoft\Board\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ResolvesAllowedExtensions;
/**
* 허용 확장자 컬럼 캐스팅
*
* "확장자 미지정" 을 표현하는 값이 빈 배열([])과 NULL 두 가지로 공존하면
* 소비 지점마다 `?? 기본값` 이 [] 를 통과시켜 `mimes:` 빈 규칙을 만드는 결함이 반복됩니다.
* 저장 시점에 센티널을 NULL 하나로 붕괴시켜 이 버그 클래스를 구조적으로 제거합니다.
*
* 조회 시맨틱은 기존 'array' 캐스트와 동일합니다 (NULL 은 NULL 그대로 반환).
*
* @implements CastsAttributes<array<int, string>|null, array<int, string>|null>
*/
class AsAllowedExtensions implements CastsAttributes
{
use ResolvesAllowedExtensions;
/**
* DB 값을 배열로 변환합니다.
*
* @param Model $model 모델 인스턴스
* @param string $key 속성명
* @param mixed $value DB 원본 값
* @param array<string, mixed> $attributes 전체 속성
* @return array<int, string>|null 확장자 목록 (미지정 시 null)
*/
public function get(Model $model, string $key, mixed $value, array $attributes): ?array
{
if ($value === null || $value === '') {
return null;
}
if (is_array($value)) {
return $value;
}
$decoded = json_decode((string) $value, true);
return is_array($decoded) ? $decoded : null;
}
/**
* 저장 값을 정규화하여 JSON 문자열로 변환합니다.
*
* 빈 값은 NULL 로 저장하여 "미지정" 표현을 단일화합니다.
*
* @param Model $model 모델 인스턴스
* @param string $key 속성명
* @param mixed $value 설정 값
* @param array<string, mixed> $attributes 전체 속성
* @return string|null JSON 문자열 (미지정 시 null)
*/
public function set(Model $model, string $key, mixed $value, array $attributes): ?string
{
if (is_string($value)) {
$decoded = json_decode($value, true);
$value = is_array($decoded) ? $decoded : explode(',', $value);
}
$normalized = self::normalizeAllowedExtensions($value);
return $normalized === [] ? null : json_encode($normalized, JSON_UNESCAPED_UNICODE);
}
}
@@ -40,6 +40,7 @@ class AttachmentController extends AdminBaseController
*
* @param UploadAttachmentRequest $request 업로드 요청
* @param string $slug 게시판 슬러그
* @return JsonResponse 업로드된 첨부파일 정보 응답
*/
public function upload(UploadAttachmentRequest $request, string $slug): JsonResponse
{
@@ -81,7 +82,7 @@ class AttachmentController extends AdminBaseController
201
);
} catch (BoardNotFoundException $e) {
return $this->error('sirsoft-board::messages.board.not_found', 404);
return $this->error('sirsoft-board::messages.boards.not_found', 404);
} catch (\Exception $e) {
return $this->error('sirsoft-board::messages.attachment.upload_failed', 500, $e->getMessage());
}
@@ -92,6 +93,7 @@ class AttachmentController extends AdminBaseController
*
* @param string $slug 게시판 슬러그
* @param int $id 첨부파일 ID
* @return JsonResponse 삭제 결과 응답
*/
public function destroy(string $slug, int $id): JsonResponse
{
@@ -115,7 +117,7 @@ class AttachmentController extends AdminBaseController
return $this->success('sirsoft-board::messages.attachment.delete_success');
} catch (BoardNotFoundException $e) {
return $this->error('sirsoft-board::messages.board.not_found', 404);
return $this->error('sirsoft-board::messages.boards.not_found', 404);
} catch (\Exception $e) {
return $this->error('sirsoft-board::messages.attachment.delete_failed', 500, $e->getMessage());
}
@@ -126,6 +128,7 @@ class AttachmentController extends AdminBaseController
*
* @param ReorderAttachmentsRequest $request 순서 변경 요청
* @param string $slug 게시판 슬러그
* @return JsonResponse 순서 변경 결과 응답
*/
public function reorder(ReorderAttachmentsRequest $request, string $slug): JsonResponse
{
@@ -145,7 +148,7 @@ class AttachmentController extends AdminBaseController
return $this->success('sirsoft-board::messages.attachment.reorder_success');
} catch (BoardNotFoundException $e) {
return $this->error('sirsoft-board::messages.board.not_found', 404);
return $this->error('sirsoft-board::messages.boards.not_found', 404);
} catch (\Exception $e) {
return $this->error('sirsoft-board::messages.attachment.reorder_failed', 500, $e->getMessage());
}
@@ -156,6 +159,7 @@ class AttachmentController extends AdminBaseController
*
* @param string $slug 게시판 슬러그
* @param string $hash 첨부파일 해시
* @return StreamedResponse|JsonResponse 파일 스트림 또는 오류 응답
*/
public function download(string $slug, string $hash): StreamedResponse|JsonResponse
{
@@ -181,7 +185,7 @@ class AttachmentController extends AdminBaseController
} catch (AccessDeniedHttpException $e) {
return $this->error('auth.scope_denied', 403);
} catch (BoardNotFoundException $e) {
return $this->error('sirsoft-board::messages.board.not_found', 404);
return $this->error('sirsoft-board::messages.boards.not_found', 404);
} catch (\Exception $e) {
return $this->error('sirsoft-board::messages.attachment.download_failed', 500, $e->getMessage());
}
@@ -5,13 +5,13 @@ namespace Modules\Sirsoft\Board\Http\Controllers\Admin;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Modules\Sirsoft\Board\Http\Requests\BlindCommentRequest;
use Modules\Sirsoft\Board\Http\Requests\RestoreCommentRequest;
use Modules\Sirsoft\Board\Http\Requests\StoreCommentRequest;
use Modules\Sirsoft\Board\Http\Requests\UpdateCommentRequest;
use Modules\Sirsoft\Board\Http\Resources\CommentResource;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Services\BoardService;
use Modules\Sirsoft\Board\Services\CommentService;
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
@@ -28,9 +28,11 @@ class CommentController extends AdminBaseController
* CommentController 생성자
*
* @param CommentService $commentService 댓글 서비스
* @param BoardService $boardService 게시판 서비스
*/
public function __construct(
private CommentService $commentService
private CommentService $commentService,
private BoardService $boardService
) {
parent::__construct();
}
@@ -51,7 +53,7 @@ class CommentController extends AdminBaseController
// 비회원 댓글은 admin.manage 권한 필요
if ($commentUserId === null) {
return $this->forbidden('sirsoft-board::messages.permissions.access_denied');
return $this->forbidden('sirsoft-board::messages.permission.denied');
}
// admin.write 권한이 있고 본인 댓글이면 수정/삭제 가능
@@ -59,7 +61,7 @@ class CommentController extends AdminBaseController
return null;
}
return $this->forbidden('sirsoft-board::messages.permissions.access_denied');
return $this->forbidden('sirsoft-board::messages.permission.denied');
}
/**
@@ -84,7 +86,11 @@ class CommentController extends AdminBaseController
public function store(StoreCommentRequest $request, string $slug, int $postId): JsonResponse
{
try {
$board = Board::where('slug', $slug)->firstOrFail();
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
if (! $board) {
return $this->notFound('sirsoft-board::messages.boards.not_found');
}
if (! $board->use_comment) {
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
@@ -129,7 +135,11 @@ class CommentController extends AdminBaseController
return $response;
}
$board = Board::where('slug', $slug)->firstOrFail();
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
if (! $board) {
return $this->notFound('sirsoft-board::messages.boards.not_found');
}
if (! $board->use_comment) {
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
@@ -168,7 +178,11 @@ class CommentController extends AdminBaseController
return $response;
}
$board = Board::where('slug', $slug)->firstOrFail();
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
if (! $board) {
return $this->notFound('sirsoft-board::messages.boards.not_found');
}
if (! $board->use_comment) {
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
@@ -196,7 +210,11 @@ class CommentController extends AdminBaseController
public function blind(BlindCommentRequest $request, string $slug, int $postId, int $id): JsonResponse
{
try {
$board = Board::where('slug', $slug)->firstOrFail();
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
if (! $board) {
return $this->notFound('sirsoft-board::messages.boards.not_found');
}
if (! $board->use_comment) {
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
@@ -221,22 +239,26 @@ class CommentController extends AdminBaseController
/**
* 블라인드된 댓글을 복원합니다.
*
* @param Request $request HTTP 요청 객체
* @param RestoreCommentRequest $request 댓글 복원 요청
* @param string $slug 게시판 slug
* @param int $postId 게시글 ID
* @param int $id 댓글 ID
* @return JsonResponse 댓글 복원 결과 응답
*/
public function restore(Request $request, string $slug, int $postId, int $id): JsonResponse
public function restore(RestoreCommentRequest $request, string $slug, int $postId, int $id): JsonResponse
{
try {
$board = Board::where('slug', $slug)->firstOrFail();
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
if (! $board) {
return $this->notFound('sirsoft-board::messages.boards.not_found');
}
if (! $board->use_comment) {
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
}
$reason = $request->input('reason');
$reason = $request->validated()['reason'] ?? null;
$comment = $this->commentService->restoreComment($slug, $id, $reason);
return $this->successWithResource(
@@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Modules\Sirsoft\Board\Enums\PostStatus;
use Modules\Sirsoft\Board\Exceptions\BoardNotFoundException;
use Modules\Sirsoft\Board\Exceptions\PostNotFoundException;
use Modules\Sirsoft\Board\Http\Requests\BlindPostRequest;
@@ -53,6 +54,7 @@ class PostController extends AdminBaseController
* @param string $slug 게시판 슬러그
* @return JsonResponse 게시글 목록 응답
*/
// audit:allow controller-base-request-injection reason: GET 목록 조회. all()로 필터·페이징 파라미터만 읽음 (검증 불필요)
public function index(Request $request, string $slug): JsonResponse
{
// 권한은 라우트 미들웨어에서 체크됨 (sirsoft-board.{slug}.admin.posts.read)
@@ -387,6 +389,7 @@ class PostController extends AdminBaseController
* @param string $slug 게시판 슬러그
* @return JsonResponse 폼 입력 데이터 응답
*/
// audit:allow controller-base-request-injection reason: GET 수정 폼 데이터 조회. 경로 파라미터(slug) + 쿼리만 read-only 참조 (검증 불필요)
public function getFormData(Request $request, string $slug): JsonResponse
{
// 권한은 라우트 미들웨어에서 체크됨 (sirsoft-board.{slug}.admin.posts.write)
@@ -474,6 +477,7 @@ class PostController extends AdminBaseController
* @param string $slug 게시판 슬러그
* @return JsonResponse 폼 메타 데이터 응답
*/
// audit:allow controller-base-request-injection reason: GET 작성/수정 폼 메타 조회. 경로 파라미터(slug) + post_id 쿼리만 read-only 참조 (검증 불필요)
public function getFormMeta(Request $request, string $slug): JsonResponse
{
// 권한은 라우트 미들웨어에서 체크됨 (sirsoft-board.{slug}.admin.posts.write)
@@ -487,7 +491,7 @@ class PostController extends AdminBaseController
// 관리자 라우트에서는 항상 사용자 권한 정보 포함
$request->merge(['include_user_abilities' => true]);
$boardResource = new \Modules\Sirsoft\Board\Http\Resources\BoardResource($board);
$boardResource = new BoardResource($board);
$boardData = $boardResource->toArray($request);
// 게시글 폼에서는 게시판 이름을 로컬라이즈된 문자열로 반환
@@ -523,10 +527,10 @@ class PostController extends AdminBaseController
$parentPost = $this->postService->getPost($slug, $parentId);
// 블라인드 또는 삭제된 게시글에는 답글 작성 불가
if ($parentPost->status === \Modules\Sirsoft\Board\Enums\PostStatus::Blinded) {
if ($parentPost->status === PostStatus::Blinded) {
return $this->error('sirsoft-board::validation.post.parent_id.blinded', 403);
}
if ($parentPost->status === \Modules\Sirsoft\Board\Enums\PostStatus::Deleted) {
if ($parentPost->status === PostStatus::Deleted) {
return $this->error('sirsoft-board::validation.post.parent_id.deleted', 403);
}
@@ -577,7 +581,7 @@ class PostController extends AdminBaseController
// 비회원 게시글은 admin.manage 권한 필요 (위에서 통과 안 됨)
if ($postUserId === null) {
return $this->forbidden('sirsoft-board::messages.permissions.access_denied');
return $this->forbidden('sirsoft-board::messages.permission.denied');
}
// admin.posts.write 권한이 있고 본인 글이면 수정/삭제 가능
@@ -585,6 +589,6 @@ class PostController extends AdminBaseController
return null;
}
return $this->forbidden('sirsoft-board::messages.permissions.access_denied');
return $this->forbidden('sirsoft-board::messages.permission.denied');
}
}
@@ -13,6 +13,7 @@ use Modules\Sirsoft\Board\Services\AttachmentService;
use Modules\Sirsoft\Board\Services\BoardService;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
/**
* 사용자용 첨부파일 컨트롤러
@@ -66,7 +67,7 @@ class AttachmentController extends PublicBaseController
}
return $response;
} catch (\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException $e) {
} catch (AccessDeniedHttpException $e) {
return $this->error('auth.scope_denied', 403);
} catch (BoardNotFoundException $e) {
return $this->notFound(__('sirsoft-board::messages.boards.not_found'));
@@ -116,7 +117,7 @@ class AttachmentController extends PublicBaseController
$fileInfo['mime_type'],
(int) g7_core_settings('cache.layout_ttl', 86400)
);
} catch (\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException $e) {
} catch (AccessDeniedHttpException $e) {
// 삭제글 첨부 등 권한 차단은 403 으로 응답
return $this->error('auth.scope_denied', 403);
} catch (BoardNotFoundException $e) {
@@ -175,7 +176,7 @@ class AttachmentController extends PublicBaseController
201
);
} catch (BoardNotFoundException $e) {
return $this->notFound(__('sirsoft-board::messages.board.not_found'));
return $this->notFound(__('sirsoft-board::messages.boards.not_found'));
} catch (\Exception $e) {
return $this->error(__('sirsoft-board::messages.attachment.upload_failed'), 500, $e->getMessage());
}
@@ -206,7 +207,7 @@ class AttachmentController extends PublicBaseController
return $this->success(__('sirsoft-board::messages.attachment.reorder_success'));
} catch (BoardNotFoundException $e) {
return $this->notFound(__('sirsoft-board::messages.board.not_found'));
return $this->notFound(__('sirsoft-board::messages.boards.not_found'));
} catch (\Exception $e) {
return $this->error(__('sirsoft-board::messages.attachment.reorder_failed'), 500, $e->getMessage());
}
@@ -246,7 +247,7 @@ class AttachmentController extends PublicBaseController
return $this->success(__('sirsoft-board::messages.attachment.delete_success'));
} catch (BoardNotFoundException $e) {
return $this->notFound(__('sirsoft-board::messages.board.not_found'));
return $this->notFound(__('sirsoft-board::messages.boards.not_found'));
} catch (\Exception $e) {
return $this->error(__('sirsoft-board::messages.attachment.delete_failed'), 500, $e->getMessage());
}
@@ -294,7 +294,7 @@ class PostController extends PublicBaseController
// 파일 업로드 권한 확인
if (! $this->checkBoardPermission($slug, 'attachments.upload', PermissionType::User)) {
return $this->forbidden('sirsoft-board::messages.permissions.access_denied');
return $this->forbidden('sirsoft-board::messages.permission.attachments_upload_denied');
}
}
@@ -584,7 +584,7 @@ class PostController extends PublicBaseController
// 회원 게시글이고 본인이 아닌 경우 권한 에러
if ($post->user_id && Auth::id() !== $post->user_id) {
if (! $this->hasBoardManagePermission($slug)) {
return $this->error('sirsoft-board::messages.posts.no_permission', 403);
return $this->error('sirsoft-board::messages.posts.modify_permission_denied', 403);
}
}
@@ -675,7 +675,7 @@ class PostController extends PublicBaseController
// 회원 게시글이고 본인이 아니거나, 관리자도 아닌 경우 권한 에러
if ($post->user_id && Auth::id() !== $post->user_id) {
if (! $this->hasBoardManagePermission($slug)) {
return $this->error('sirsoft-board::messages.posts.no_permission', 403);
return $this->error('sirsoft-board::messages.posts.modify_permission_denied', 403);
}
}
@@ -787,7 +787,6 @@ class PostController extends PublicBaseController
*
* @param Post $parentPost 부모 게시글 모델
* @param int $parentId 부모 게시글 ID (예외 메시지용)
* @return void
*
* @throws PostNotFoundException 부모글이 블라인드/삭제 상태인 경우
*/
@@ -4,6 +4,7 @@ namespace Modules\Sirsoft\Board\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ReadsBoardLimits;
use Modules\Sirsoft\Board\Models\Board;
/**
@@ -14,6 +15,8 @@ use Modules\Sirsoft\Board\Models\Board;
*/
class BulkApplySettingsRequest extends FormRequest
{
use ReadsBoardLimits;
/**
* boards 테이블 컬럼에 매핑되는 일괄 적용 가능 필드 목록
*/
@@ -78,7 +81,7 @@ class BulkApplySettingsRequest extends FormRequest
{
$allowedFields = array_merge(self::BOARD_COLUMN_FIELDS, self::PERMISSION_FIELDS);
return [
return array_merge([
'fields' => ['required', 'array', 'min:1'],
'fields.*' => ['string', function (string $attribute, mixed $value, \Closure $fail) use ($allowedFields) {
// 개별 권한 키(예: admin.manage, user.write)는 점(.)을 포함한 문자열로 허용
@@ -93,6 +96,37 @@ class BulkApplySettingsRequest extends FormRequest
'board_ids' => ['required_if:apply_all,false', 'array'],
'board_ids.*' => ['integer', Rule::exists(Board::class, 'id')],
'override_values' => ['sometimes', 'array'],
], $this->overrideValueRules());
}
/**
* override_values 의 컬럼별 범위 검증 규칙.
*
* override_values 는 boards 테이블 컬럼에 직접 기록되므로(BoardService::bulkApplySettings),
* Store/Update 와 동일한 제한값(ReadsBoardLimits SSoT)을 강제해야 한다. 이 규칙이 없으면
* 일괄 적용 경로만 범위 검증을 우회해 new_display_hours=99999 같은 값이 저장된다.
* 각 키는 선택적(존재할 때만 검증)이며, 범위 밖 값은 422 로 거부된다.
*
* @return array<string, mixed> override_values.* 검증 규칙
*/
private function overrideValueRules(): array
{
$limits = $this->boardLimits();
return [
'override_values.per_page' => ['nullable', 'integer', "min:{$limits['per_page_min']}", "max:{$limits['per_page_max']}"],
'override_values.per_page_mobile' => ['nullable', 'integer', "min:{$limits['per_page_min']}", "max:{$limits['per_page_max']}"],
'override_values.max_reply_depth' => ['nullable', 'integer', "min:{$limits['max_reply_depth_min']}", "max:{$limits['max_reply_depth_max']}"],
'override_values.max_comment_depth' => ['nullable', 'integer', "min:{$limits['max_comment_depth_min']}", "max:{$limits['max_comment_depth_max']}"],
'override_values.min_title_length' => ['nullable', 'integer', "min:{$limits['min_title_length_min']}", "max:{$limits['min_title_length_max']}"],
'override_values.max_title_length' => ['nullable', 'integer', "min:{$limits['max_title_length_min']}", "max:{$limits['max_title_length_max']}"],
'override_values.min_content_length' => ['nullable', 'integer', "min:{$limits['min_content_length_min']}", "max:{$limits['min_content_length_max']}"],
'override_values.max_content_length' => ['nullable', 'integer', "min:{$limits['max_content_length_min']}", "max:{$limits['max_content_length_max']}"],
'override_values.min_comment_length' => ['nullable', 'integer', "min:{$limits['min_comment_length_min']}", "max:{$limits['min_comment_length_max']}"],
'override_values.max_comment_length' => ['nullable', 'integer', "min:{$limits['max_comment_length_min']}", "max:{$limits['max_comment_length_max']}"],
'override_values.max_file_size' => ['nullable', 'integer', "min:{$limits['max_file_size_min']}", "max:{$limits['max_file_size_max']}"],
'override_values.max_file_count' => ['nullable', 'integer', "min:{$limits['max_file_count_min']}", "max:{$limits['max_file_count_max']}"],
'override_values.new_display_hours' => ['nullable', 'integer', "min:{$limits['new_display_hours_min']}", "max:{$limits['new_display_hours_max']}"],
];
}
@@ -103,7 +137,7 @@ class BulkApplySettingsRequest extends FormRequest
*/
public function attributes(): array
{
$attributes = __('sirsoft-board::attributes.bulk_apply');
$attributes = __('sirsoft-board::validation.attributes.bulk_apply');
return is_array($attributes) ? $attributes : [];
}
@@ -62,7 +62,7 @@ class StatusCountsRequest extends FormRequest
public function attributes(): array
{
return [
'ids' => __('sirsoft-board::attributes.report.ids'),
'ids' => __('sirsoft-board::validation.attributes.report.ids'),
];
}
}
@@ -5,6 +5,7 @@ namespace Modules\Sirsoft\Board\Http\Requests\Admin;
use App\Models\Role;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ReadsBoardLimits;
/**
* 게시판 환경설정 저장 요청 검증
@@ -14,6 +15,8 @@ use Illuminate\Validation\Rule;
*/
class StoreBoardSettingsRequest extends FormRequest
{
use ReadsBoardLimits;
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
@@ -110,13 +113,38 @@ class StoreBoardSettingsRequest extends FormRequest
*/
public function rules(): array
{
$limits = config('sirsoft-board.limits', []);
$perPageMin = $limits['per_page_min'] ?? 5;
$perPageMax = $limits['per_page_max'] ?? 100;
$maxReplyDepthMin = $limits['max_reply_depth_min'] ?? 1;
$maxReplyDepthMax = $limits['max_reply_depth_max'] ?? 10;
$maxCommentDepthMin = $limits['max_comment_depth_min'] ?? 0;
$maxCommentDepthMax = $limits['max_comment_depth_max'] ?? 10;
// config 기준 제한값 (폴백 기본치는 ReadsBoardLimits 트레이트가 단일 관리)
$limits = $this->boardLimits();
$perPageMin = $limits['per_page_min'];
$perPageMax = $limits['per_page_max'];
$maxReplyDepthMin = $limits['max_reply_depth_min'];
$maxReplyDepthMax = $limits['max_reply_depth_max'];
$maxCommentDepthMin = $limits['max_comment_depth_min'];
$maxCommentDepthMax = $limits['max_comment_depth_max'];
// 길이 제한 (하한값은 config 선언을 따른다 — min_title/min_comment 는 0 허용)
$minTitleLengthMin = $limits['min_title_length_min'];
$minTitleLengthMax = $limits['min_title_length_max'];
$maxTitleLengthMin = $limits['max_title_length_min'];
$maxTitleLengthMax = $limits['max_title_length_max'];
$minContentLengthMin = $limits['min_content_length_min'];
$minContentLengthMax = $limits['min_content_length_max'];
$maxContentLengthMin = $limits['max_content_length_min'];
$maxContentLengthMax = $limits['max_content_length_max'];
$minCommentLengthMin = $limits['min_comment_length_min'];
$minCommentLengthMax = $limits['min_comment_length_max'];
$maxCommentLengthMin = $limits['max_comment_length_min'];
$maxCommentLengthMax = $limits['max_comment_length_max'];
// 파일 업로드 제한
$maxFileSizeMin = $limits['max_file_size_min'];
$maxFileSizeMax = $limits['max_file_size_max'];
$maxFileCountMin = $limits['max_file_count_min'];
$maxFileCountMax = $limits['max_file_count_max'];
// NEW 배지 표시 기간 (0 = 표시 안 함)
$newDisplayHoursMin = $limits['new_display_hours_min'];
$newDisplayHoursMax = $limits['new_display_hours_max'];
return [
// 현재 탭 정보 (메타 데이터)
@@ -148,24 +176,32 @@ class StoreBoardSettingsRequest extends FormRequest
'basic_defaults.comment_order' => ['nullable', 'string', 'in:ASC,DESC'],
'basic_defaults.show_view_count' => ['nullable', 'boolean'],
'basic_defaults.use_report' => ['nullable', 'boolean'],
'basic_defaults.min_title_length' => ['nullable', 'integer', 'min:1', 'max:200'],
'basic_defaults.max_title_length' => ['nullable', 'integer', 'min:1', 'max:1000'],
'basic_defaults.min_content_length' => ['nullable', 'integer', 'min:0', 'max:10000'],
'basic_defaults.max_content_length' => ['nullable', 'integer', 'min:1', 'max:100000'],
'basic_defaults.min_comment_length' => ['nullable', 'integer', 'min:1', 'max:1000'],
'basic_defaults.max_comment_length' => ['nullable', 'integer', 'min:1', 'max:10000'],
'basic_defaults.min_title_length' => ['nullable', 'integer', "min:{$minTitleLengthMin}", "max:{$minTitleLengthMax}"],
'basic_defaults.max_title_length' => ['nullable', 'integer', "min:{$maxTitleLengthMin}", "max:{$maxTitleLengthMax}"],
'basic_defaults.min_content_length' => ['nullable', 'integer', "min:{$minContentLengthMin}", "max:{$minContentLengthMax}"],
'basic_defaults.max_content_length' => ['nullable', 'integer', "min:{$maxContentLengthMin}", "max:{$maxContentLengthMax}"],
'basic_defaults.min_comment_length' => ['nullable', 'integer', "min:{$minCommentLengthMin}", "max:{$minCommentLengthMax}"],
'basic_defaults.max_comment_length' => ['nullable', 'integer', "min:{$maxCommentLengthMin}", "max:{$maxCommentLengthMax}"],
'basic_defaults.use_file_upload' => ['nullable', 'boolean'],
'basic_defaults.max_file_size' => ['nullable', 'integer', 'min:1', 'max:200'],
'basic_defaults.max_file_count' => ['nullable', 'integer', 'min:1', 'max:20'],
'basic_defaults.max_file_size' => ['nullable', 'integer', "min:{$maxFileSizeMin}", "max:{$maxFileSizeMax}"],
'basic_defaults.max_file_count' => ['nullable', 'integer', "min:{$maxFileCountMin}", "max:{$maxFileCountMax}"],
'basic_defaults.blocked_keywords' => ['nullable', 'array'],
'basic_defaults.blocked_keywords.*' => ['string', 'max:100'],
// 허용 확장자는 최소 1개 필수 (빈 배열 차단 — 빈 값 저장 시 전 파일 거부되던 버그 방지).
// 부분 탭 저장을 위해 sometimes 유지, nullable 제거.
'basic_defaults.allowed_extensions' => ['sometimes', 'array', 'min:1'],
// 허용 확장자: 첨부 사용 기본값일 때만 최소 1개 필수 (빈 값 저장 시 전 파일 거부되던 버그 방지).
// 첨부 미사용 기본값은 exclude_if 로 검증 자체에서 배제한다 — 환경설정 화면도 탭 데이터를
// 통째로 PUT 하므로 요청에는 항상 이 키가 존재하고, sometimes 는 보호가 되지 않는다.
// null 조건이 별도로 필요한 이유: prepareForValidation() 의 boolean 캐스팅이 isset() 가드를
// 쓰는데 isset(null) 은 false 라 null 이 false 로 캐스팅되지 않고 그대로 통과한다.
// exclude_if 는 배열 앞쪽이어야 한다. 앞선 규칙이 먼저 실패하면 배제되어도 메시지가 남는다.
'basic_defaults.allowed_extensions' => [
'exclude_if:basic_defaults.use_file_upload,false',
'exclude_if:basic_defaults.use_file_upload,null',
'sometimes', 'required', 'array', 'min:1',
],
'basic_defaults.allowed_extensions.*' => ['string', 'max:20'],
'basic_defaults.notify_admin_on_post' => ['nullable', 'boolean'],
'basic_defaults.notify_author' => ['nullable', 'boolean'],
'basic_defaults.new_display_hours' => ['nullable', 'integer', 'min:1', 'max:720'],
'basic_defaults.new_display_hours' => ['nullable', 'integer', "min:{$newDisplayHoursMin}", "max:{$newDisplayHoursMax}"],
// default_board_permissions는 flat key 구조 (예: {"posts.read": ["admin","user"], "manager": ["admin"]})
// Laravel dot notation으로 하위 키를 개별 검증하면 flat key가 중첩 배열로 파싱되어 데이터 유실됨
// → 배열 자체만 검증 (하위 키 개별 검증 금지)
@@ -248,10 +284,14 @@ class StoreBoardSettingsRequest extends FormRequest
*/
public function messages(): array
{
// validation.settings 는 선택적 오버라이드 그룹이다 — 정의되지 않으면 Laravel 기본
// 검증 메시지 + validation.attributes.settings 의 속성명 조합이 그대로 쓰인다.
// (미정의여도 원문 키가 노출되지 않도록 is_array 가드로 걸러낸다)
$messages = __('sirsoft-board::validation.settings');
$base = is_array($messages) ? $messages : [];
return array_merge($base, [
'basic_defaults.allowed_extensions.required' => __('sirsoft-board::validation.allowed_extensions.min'),
'basic_defaults.allowed_extensions.min' => __('sirsoft-board::validation.allowed_extensions.min'),
'report_permissions.view_roles.required_with' => __('sirsoft-board::validation.report_permissions.view_roles.required_with'),
'report_permissions.view_roles.min' => __('sirsoft-board::validation.report_permissions.view_roles.min'),
@@ -52,7 +52,7 @@ class BlindCommentRequest extends FormRequest
public function attributes(): array
{
return [
'reason' => __('sirsoft-board::attributes.blind.reason'),
'reason' => __('sirsoft-board::validation.attributes.blind.reason'),
];
}
}
@@ -52,7 +52,7 @@ class BlindPostRequest extends FormRequest
public function attributes(): array
{
return [
'reason' => __('sirsoft-board::attributes.blind.reason'),
'reason' => __('sirsoft-board::validation.attributes.blind.reason'),
];
}
}
@@ -14,6 +14,10 @@ class BulkUpdateStatusRequest extends FormRequest
{
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
*
* @return bool 항상 true
*/
public function authorize(): bool
{
@@ -62,9 +66,9 @@ class BulkUpdateStatusRequest extends FormRequest
public function attributes(): array
{
return [
'ids' => __('sirsoft-board::attributes.report.ids'),
'status' => __('sirsoft-board::attributes.report.status'),
'process_note' => __('sirsoft-board::attributes.report.process_note'),
'ids' => __('sirsoft-board::validation.attributes.report.ids'),
'status' => __('sirsoft-board::validation.attributes.report.status'),
'process_note' => __('sirsoft-board::validation.attributes.report.process_note'),
];
}
}
@@ -0,0 +1,81 @@
<?php
namespace Modules\Sirsoft\Board\Http\Requests\Concerns;
/**
* 게시판 제한값(config('sirsoft-board.limits')) 조회 트레이트
*
* 게시판 관련 FormRequest 들이 각자 `$limits['x'] ?? 기본값` 블록을 복제하면서
* 파일마다 폴백 값이 어긋나는 드리프트가 발생했습니다. 폴백 기본값을 이 트레이트
* 한 곳에 모아 config 가 제한값의 단일 출처(SSoT)가 되도록 합니다.
*/
trait ReadsBoardLimits
{
/**
* config 미정의 시 사용할 제한값 기본치
*
* config/board.php 의 limits 섹션과 동일한 값을 유지해야 합니다.
*/
private const BOARD_LIMIT_DEFAULTS = [
'per_page_min' => 5,
'per_page_max' => 100,
'min_title_length_min' => 0,
'min_title_length_max' => 200,
'max_title_length_min' => 1,
'max_title_length_max' => 1000,
'min_content_length_min' => 0,
'min_content_length_max' => 10000,
'max_content_length_min' => 1,
'max_content_length_max' => 100000,
'min_comment_length_min' => 0,
'min_comment_length_max' => 1000,
'max_comment_length_min' => 1,
'max_comment_length_max' => 10000,
'max_file_size_min' => 1,
'max_file_size_max' => 200,
'max_file_count_min' => 1,
'max_file_count_max' => 20,
'category_max' => 50,
'max_reply_depth_min' => 1,
'max_reply_depth_max' => 10,
'max_comment_depth_min' => 0,
'max_comment_depth_max' => 10,
'new_display_hours_min' => 0,
'new_display_hours_max' => 720,
];
/**
* 게시판 제한값 전체를 반환합니다.
*
* config 값이 기본치를 덮어씁니다.
*
* @return array<string, int> 제한값 맵
*/
protected function boardLimits(): array
{
$configured = config('sirsoft-board.limits', []);
return array_merge(
self::BOARD_LIMIT_DEFAULTS,
is_array($configured) ? $configured : []
);
}
/**
* 특정 제한값을 반환합니다.
*
* @param string $key 제한값 키 (예: per_page_min)
* @return int 제한값
*/
protected function boardLimit(string $key): int
{
return (int) ($this->boardLimits()[$key] ?? 0);
}
}
@@ -0,0 +1,74 @@
<?php
namespace Modules\Sirsoft\Board\Http\Requests\Concerns;
/**
* 허용 확장자 목록 해석 트레이트
*
* `$board->allowed_extensions ?? $기본값` 패턴은 null 만 잡고 빈 배열([])을 통과시킵니다.
* 그 결과 `implode(',', [])` 가 `mimes:` 빈 규칙을 만들어 해당 게시판의 모든 파일 업로드가
* 거부됩니다. 빈 배열과 null 은 "확장자 미지정" 이라는 같은 의미이므로 동일하게 취급합니다.
*
* 저장 시점에도 빈 배열을 null 로 정규화하지만(Board 모델 mutator), 이미 저장된 레거시 행을
* 소급 치유하지는 못하므로 소비 시점 방어를 함께 둡니다.
*/
trait ResolvesAllowedExtensions
{
/**
* 모듈 설정도 비어 있을 때 사용할 최종 확장자 목록
*/
private const FALLBACK_ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'zip'];
/**
* 게시판의 허용 확장자를 해석합니다.
*
* 게시판 값이 비어 있으면 모듈 환경설정 기본값 → 최종 기본값 순으로 폴백합니다.
*
* @param mixed $boardExtensions 게시판의 allowed_extensions 값
* @param mixed $defaultExtensions 모듈 환경설정 기본값 (없으면 null)
* @return array<int, string> 비어있지 않은 확장자 목록
*/
protected function resolveAllowedExtensions(mixed $boardExtensions, mixed $defaultExtensions = null): array
{
foreach ([$boardExtensions, $defaultExtensions] as $candidate) {
$normalized = self::normalizeAllowedExtensions($candidate);
if ($normalized !== []) {
return $normalized;
}
}
return self::FALLBACK_ALLOWED_EXTENSIONS;
}
/**
* 확장자 목록을 정규화합니다.
*
* 배열이 아니거나 빈 문자열/비문자열 항목은 제거하고, 소문자 + 중복 제거된
* 순차 배열로 반환합니다.
*
* @param mixed $extensions 원본 값
* @return array<int, string> 정규화된 확장자 목록 (없으면 빈 배열)
*/
public static function normalizeAllowedExtensions(mixed $extensions): array
{
if (! is_array($extensions)) {
return [];
}
$normalized = [];
foreach ($extensions as $extension) {
if (! is_string($extension)) {
continue;
}
$extension = mb_strtolower(trim($extension, " \t\n\r\0\x0B."));
if ($extension !== '') {
$normalized[] = $extension;
}
}
return array_values(array_unique($normalized));
}
}
@@ -0,0 +1,63 @@
<?php
namespace Modules\Sirsoft\Board\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
/**
* 댓글 복원 요청 폼 검증
*
* 블라인드 처리된 댓글을 복원할 때 사용됩니다. 블라인드(BlindCommentRequest) 와 대칭으로
* 복원 사유를 검증합니다.
*/
class RestoreCommentRequest extends FormRequest
{
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
*
* @return bool 항상 true
*/
public function authorize(): bool
{
return true;
}
/**
* 요청에 적용할 검증 규칙
*
* @return array<string, mixed> 검증 규칙 배열
*/
public function rules(): array
{
return [
'reason' => ['nullable', 'string', 'max:1000'],
];
}
/**
* 검증 오류 메시지 커스터마이징
*
* @return array<string, string> 오류 메시지 배열
*/
public function messages(): array
{
return [
'reason.string' => __('sirsoft-board::validation.restore.reason.string'),
'reason.max' => __('sirsoft-board::validation.restore.reason.max'),
];
}
/**
* 검증할 필드의 이름을 커스터마이징
*
* @return array<string, string> 필드명 → 표시명 매핑
*/
public function attributes(): array
{
return [
'reason' => __('sirsoft-board::validation.attributes.restore.reason'),
];
}
}
@@ -41,8 +41,8 @@ class RestorePostRequest extends FormRequest
public function messages(): array
{
return [
'reason.string' => __('sirsoft-board::validation.restore_reason_string'),
'reason.max' => __('sirsoft-board::validation.restore_reason_max'),
'reason.string' => __('sirsoft-board::validation.restore.reason.string'),
'reason.max' => __('sirsoft-board::validation.restore.reason.max'),
];
}
}
@@ -10,12 +10,14 @@ use App\Rules\TranslatableField;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ReadsBoardLimits;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ValidatesLengthRange;
use Modules\Sirsoft\Board\Rules\BoardTypeValidationRule;
use Modules\Sirsoft\Board\Rules\SlugUniqueRule;
class StoreBoardRequest extends FormRequest
{
use ReadsBoardLimits;
use ValidatesLengthRange;
/**
@@ -104,37 +106,41 @@ class StoreBoardRequest extends FormRequest
*/
public function rules(): array
{
// config에서 제한값 가져오기
$limits = config('sirsoft-board.limits', []);
$perPageMin = $limits['per_page_min'] ?? 5;
$perPageMax = $limits['per_page_max'] ?? 100;
$maxFileSizeMax = $limits['max_file_size_max'] ?? 200; // MB
$maxFileCountMax = $limits['max_file_count_max'] ?? 20;
$categoryMax = $limits['category_max'] ?? 50;
// config 기준 제한값 (폴백 기본치는 ReadsBoardLimits 트레이트가 단일 관리)
$limits = $this->boardLimits();
$perPageMin = $limits['per_page_min'];
$perPageMax = $limits['per_page_max'];
$maxFileSizeMax = $limits['max_file_size_max']; // MB
$maxFileCountMax = $limits['max_file_count_max'];
$categoryMax = $limits['category_max'];
// 제목 길이 제한
$minTitleLengthMin = $limits['min_title_length_min'] ?? 0;
$minTitleLengthMax = $limits['min_title_length_max'] ?? 200;
$maxTitleLengthMin = $limits['max_title_length_min'] ?? 1;
$maxTitleLengthMax = $limits['max_title_length_max'] ?? 200;
$minTitleLengthMin = $limits['min_title_length_min'];
$minTitleLengthMax = $limits['min_title_length_max'];
$maxTitleLengthMin = $limits['max_title_length_min'];
$maxTitleLengthMax = $limits['max_title_length_max'];
// 내용 길이 제한
$minContentLengthMin = $limits['min_content_length_min'] ?? 0;
$minContentLengthMax = $limits['min_content_length_max'] ?? 10000;
$maxContentLengthMin = $limits['max_content_length_min'] ?? 1;
$maxContentLengthMax = $limits['max_content_length_max'] ?? 50000;
$minContentLengthMin = $limits['min_content_length_min'];
$minContentLengthMax = $limits['min_content_length_max'];
$maxContentLengthMin = $limits['max_content_length_min'];
$maxContentLengthMax = $limits['max_content_length_max'];
// 댓글 길이 제한
$minCommentLengthMin = $limits['min_comment_length_min'] ?? 0;
$minCommentLengthMax = $limits['min_comment_length_max'] ?? 1000;
$maxCommentLengthMin = $limits['max_comment_length_min'] ?? 1;
$maxCommentLengthMax = $limits['max_comment_length_max'] ?? 1000;
$minCommentLengthMin = $limits['min_comment_length_min'];
$minCommentLengthMax = $limits['min_comment_length_max'];
$maxCommentLengthMin = $limits['max_comment_length_min'];
$maxCommentLengthMax = $limits['max_comment_length_max'];
// 답글/대댓글 깊이 제한
$maxReplyDepthMin = $limits['max_reply_depth_min'] ?? 1;
$maxReplyDepthMax = $limits['max_reply_depth_max'] ?? 10;
$maxCommentDepthMin = $limits['max_comment_depth_min'] ?? 0;
$maxCommentDepthMax = $limits['max_comment_depth_max'] ?? 10;
$maxReplyDepthMin = $limits['max_reply_depth_min'];
$maxReplyDepthMax = $limits['max_reply_depth_max'];
$maxCommentDepthMin = $limits['max_comment_depth_min'];
$maxCommentDepthMax = $limits['max_comment_depth_max'];
// NEW 배지 표시 기간 (0 = 표시 안 함)
$newDisplayHoursMin = $limits['new_display_hours_min'];
$newDisplayHoursMax = $limits['new_display_hours_max'];
$rules = [
// 기본 정보 (name, description은 다국어 필드 - 기본 언어만 필수)
@@ -164,7 +170,7 @@ class StoreBoardRequest extends FormRequest
'use_reply' => ['required', 'boolean'],
'use_report' => ['required', 'boolean'],
'comment_order' => ['required', 'in:ASC,DESC'],
'new_display_hours' => ['nullable', 'integer', 'min:1', 'max:720'],
'new_display_hours' => ['nullable', 'integer', "min:{$newDisplayHoursMin}", "max:{$newDisplayHoursMax}"],
// 제목 길이 제한
'min_title_length' => ['nullable', 'integer', "min:{$minTitleLengthMin}", "max:{$minTitleLengthMax}"],
@@ -236,7 +242,7 @@ class StoreBoardRequest extends FormRequest
public function attributes(): array
{
$attributes = [
'blocked_keywords' => __('sirsoft-board::admin.form.fields.blocked_keywords.label'),
'blocked_keywords' => __('sirsoft-board::validation.attributes.board.blocked_keywords'),
'add_to_menu' => __('sirsoft-board::validation.attributes.board.add_to_menu'),
];
@@ -6,6 +6,7 @@ use App\Extension\HookManager;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Sirsoft\Board\Enums\PostStatus;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ResolvesAllowedExtensions;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Models\Post;
use Modules\Sirsoft\Board\Rules\BlockedKeywordsRule;
@@ -17,8 +18,12 @@ use Modules\Sirsoft\Board\Rules\ParentPostValidationRule;
*/
class StorePostRequest extends FormRequest
{
use ResolvesAllowedExtensions;
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* @return bool 항상 true (권한은 미들웨어에서 검증)
*/
public function authorize(): bool
{
@@ -96,7 +101,12 @@ class StorePostRequest extends FormRequest
$maxFiles = $board->max_file_count ?? $defaults['max_file_count'] ?? 5;
$maxSizeMB = $board->max_file_size ?? $defaults['max_file_size'] ?? 10;
$maxSizeKB = $maxSizeMB * 1024;
$allowedExtensions = $board->allowed_extensions ?? $defaults['allowed_extensions'] ?? ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'zip'];
// 게시판/기본값이 모두 비어 있으면(null 또는 []) 최종 기본 확장자로 폴백한다.
// 빈 배열을 그대로 쓰면 'mimes:' 빈 규칙이 되어 전 파일이 거부된다.
$allowedExtensions = $this->resolveAllowedExtensions(
$board->allowed_extensions,
$defaults['allowed_extensions'] ?? null
);
$mimes = implode(',', $allowedExtensions);
$rules['files'] = ['nullable', 'array', 'max:'.$maxFiles];
@@ -5,6 +5,7 @@ namespace Modules\Sirsoft\Board\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;
use Modules\Sirsoft\Board\Enums\ReportReasonType;
use Modules\Sirsoft\Board\Repositories\Contracts\ReportRepositoryInterface;
use Modules\Sirsoft\Board\Rules\CooldownRule;
@@ -19,6 +20,10 @@ class StoreReportRequest extends FormRequest
{
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
*
* @return bool 항상 true
*/
public function authorize(): bool
{
@@ -43,9 +48,9 @@ class StoreReportRequest extends FormRequest
*
* 신고 남발 방지: 일일 횟수 제한, 반려 누적 제한, 연속 신고 쿨타임
*
* @param \Illuminate\Validation\Validator $validator 검증기 인스턴스
* @param Validator $validator 검증기 인스턴스
*/
public function withValidator(\Illuminate\Validation\Validator $validator): void
public function withValidator(Validator $validator): void
{
if (! Auth::check()) {
return;
@@ -104,8 +109,8 @@ class StoreReportRequest extends FormRequest
public function attributes(): array
{
return [
'reason_type' => __('sirsoft-board::attributes.report.reason_type'),
'reason_detail' => __('sirsoft-board::attributes.report.reason_detail'),
'reason_type' => __('sirsoft-board::validation.attributes.report.reason_type'),
'reason_detail' => __('sirsoft-board::validation.attributes.report.reason_detail'),
];
}
}
@@ -10,12 +10,14 @@ use App\Rules\TranslatableField;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ReadsBoardLimits;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ValidatesLengthRange;
use Modules\Sirsoft\Board\Rules\BoardTypeValidationRule;
use Modules\Sirsoft\Board\Rules\PermissionRolesRequiredRule;
class UpdateBoardRequest extends FormRequest
{
use ReadsBoardLimits;
use ValidatesLengthRange;
/**
@@ -77,43 +79,51 @@ class UpdateBoardRequest extends FormRequest
* 요청에 적용할 검증 규칙
*
* slug는 수정 불가하므로 제외됩니다.
* 부분 업데이트를 지원하기 위해 sometimes 규칙을 적용합니다.
*
* `sometimes` 는 "요청에 그 키가 없을 때만" 검증을 건너뛴다. 관리자 폼은 조회 응답
* 전체를 그대로 PUT 하므로 키는 항상 존재하며, 따라서 sometimes 만으로는 조건부
* 배제가 되지 않는다. 다른 필드 값에 따라 검증을 배제해야 하는 항목은 `exclude_if`
* 를 규칙 배열 첫 번째에 두어야 한다 (allowed_extensions 참조).
*
* @return array<string, mixed> 검증 규칙 배열
*/
public function rules(): array
{
// config에서 제한값 가져오기
$limits = config('sirsoft-board.limits', []);
$perPageMin = $limits['per_page_min'] ?? 5;
$perPageMax = $limits['per_page_max'] ?? 100;
$maxFileSizeMax = $limits['max_file_size_max'] ?? 200; // MB
$maxFileCountMax = $limits['max_file_count_max'] ?? 20;
$categoryMax = $limits['category_max'] ?? 50;
// config 기준 제한값 (폴백 기본치는 ReadsBoardLimits 트레이트가 단일 관리)
$limits = $this->boardLimits();
$perPageMin = $limits['per_page_min'];
$perPageMax = $limits['per_page_max'];
$maxFileSizeMax = $limits['max_file_size_max']; // MB
$maxFileCountMax = $limits['max_file_count_max'];
$categoryMax = $limits['category_max'];
// 제목 길이 제한
$minTitleLengthMin = $limits['min_title_length_min'] ?? 0;
$minTitleLengthMax = $limits['min_title_length_max'] ?? 200;
$maxTitleLengthMin = $limits['max_title_length_min'] ?? 1;
$maxTitleLengthMax = $limits['max_title_length_max'] ?? 200;
$minTitleLengthMin = $limits['min_title_length_min'];
$minTitleLengthMax = $limits['min_title_length_max'];
$maxTitleLengthMin = $limits['max_title_length_min'];
$maxTitleLengthMax = $limits['max_title_length_max'];
// 내용 길이 제한
$minContentLengthMin = $limits['min_content_length_min'] ?? 0;
$minContentLengthMax = $limits['min_content_length_max'] ?? 10000;
$maxContentLengthMin = $limits['max_content_length_min'] ?? 1;
$maxContentLengthMax = $limits['max_content_length_max'] ?? 50000;
$minContentLengthMin = $limits['min_content_length_min'];
$minContentLengthMax = $limits['min_content_length_max'];
$maxContentLengthMin = $limits['max_content_length_min'];
$maxContentLengthMax = $limits['max_content_length_max'];
// 댓글 길이 제한
$minCommentLengthMin = $limits['min_comment_length_min'] ?? 0;
$minCommentLengthMax = $limits['min_comment_length_max'] ?? 1000;
$maxCommentLengthMin = $limits['max_comment_length_min'] ?? 1;
$maxCommentLengthMax = $limits['max_comment_length_max'] ?? 1000;
$minCommentLengthMin = $limits['min_comment_length_min'];
$minCommentLengthMax = $limits['min_comment_length_max'];
$maxCommentLengthMin = $limits['max_comment_length_min'];
$maxCommentLengthMax = $limits['max_comment_length_max'];
// 답글/대댓글 깊이 제한
$maxReplyDepthMin = $limits['max_reply_depth_min'] ?? 1;
$maxReplyDepthMax = $limits['max_reply_depth_max'] ?? 10;
$maxCommentDepthMin = $limits['max_comment_depth_min'] ?? 0;
$maxCommentDepthMax = $limits['max_comment_depth_max'] ?? 10;
$maxReplyDepthMin = $limits['max_reply_depth_min'];
$maxReplyDepthMax = $limits['max_reply_depth_max'];
$maxCommentDepthMin = $limits['max_comment_depth_min'];
$maxCommentDepthMax = $limits['max_comment_depth_max'];
// NEW 배지 표시 기간 (0 = 표시 안 함)
$newDisplayHoursMin = $limits['new_display_hours_min'];
$newDisplayHoursMax = $limits['new_display_hours_max'];
$rules = [
// 기본 정보 (slug 제외, name/description은 다국어 필드)
@@ -142,7 +152,7 @@ class UpdateBoardRequest extends FormRequest
'use_reply' => ['sometimes', 'required', 'boolean'],
'use_report' => ['sometimes', 'required', 'boolean'],
'comment_order' => ['sometimes', 'required', 'in:ASC,DESC'],
'new_display_hours' => ['sometimes', 'nullable', 'integer', 'min:1', 'max:720'],
'new_display_hours' => ['sometimes', 'nullable', 'integer', "min:{$newDisplayHoursMin}", "max:{$newDisplayHoursMax}"],
// 제목 길이 제한
'min_title_length' => ['sometimes', 'nullable', 'integer', "min:{$minTitleLengthMin}", "max:{$minTitleLengthMax}"],
@@ -160,12 +170,18 @@ class UpdateBoardRequest extends FormRequest
'use_file_upload' => ['sometimes', 'required', 'boolean'],
'max_file_size' => ['sometimes', 'nullable', 'integer', 'min:1', "max:{$maxFileSizeMax}"],
'max_file_count' => ['sometimes', 'nullable', 'integer', 'min:1', "max:{$maxFileCountMax}"],
// 허용 확장자: 전송되면 최소 1개 필수 (빈 배열 저장 시 전 파일 거부되던 버그 방지).
// 부분 수정을 위해 sometimes 유지, nullable 제거.
'allowed_extensions' => ['sometimes', 'array', 'min:1'],
// 허용 확장자: 첨부 사용 게시판만 최소 1개 필수 (빈 값 저장 시 전 파일 거부되던 버그 방지).
// 첨부 미사용 게시판은 exclude_if 로 검증 자체에서 배제한다 — 관리자 폼이 조회 응답
// 전체를 그대로 PUT 하므로 요청에는 항상 이 키가 존재하고, sometimes 는 보호가 되지 않는다.
// exclude_if 는 배열 첫 번째여야 한다. 앞선 규칙이 먼저 실패하면 배제되어도 메시지가 남는다.
'allowed_extensions' => ['exclude_if:use_file_upload,false', 'sometimes', 'required', 'array', 'min:1'],
'allowed_extensions.*' => ['string', 'max:10'],
// 관리자 설정 (관리자는 최소 1명 필수, 스텝은 선택적)
// audit:allow formrequest-sometimes-array-min-inert reason: 관리자 0명은 유효한 상태가 아니다.
// board_manager_ids 는 역할 멤버십에서 파생되므로(BoardResource::getBoardRoleData) 관리자 계정이
// 삭제되면 빈 배열이 될 수 있는데, 이때는 저장을 막고 관리자를 다시 지정하도록 안내하는 것이 맞다.
// allowed_extensions 처럼 "비어 있음"이 정상 상태인 필드와 다르다.
'board_manager_ids' => ['sometimes', 'required', 'array', 'min:1'],
'board_manager_ids.*' => ['uuid', Rule::exists(User::class, 'uuid')],
'board_step_ids' => ['sometimes', 'nullable', 'array'],
@@ -218,7 +234,7 @@ class UpdateBoardRequest extends FormRequest
public function attributes(): array
{
$attributes = [
'blocked_keywords' => __('sirsoft-board::admin.form.fields.blocked_keywords.label'),
'blocked_keywords' => __('sirsoft-board::validation.attributes.board.blocked_keywords'),
'add_to_menu' => __('sirsoft-board::validation.attributes.board.add_to_menu'),
];
@@ -349,6 +365,7 @@ class UpdateBoardRequest extends FormRequest
'max_file_size.max' => __('sirsoft-board::validation.max_file_size.max'),
'max_file_count.min' => __('sirsoft-board::validation.max_file_count.min'),
'max_file_count.max' => __('sirsoft-board::validation.max_file_count.max'),
'allowed_extensions.required' => __('sirsoft-board::validation.allowed_extensions.min'),
'allowed_extensions.min' => __('sirsoft-board::validation.allowed_extensions.min'),
// 관리자 설정 검증 메시지
@@ -86,10 +86,10 @@ class UpdateCommentRequest extends FormRequest
public function attributes(): array
{
return [
'content' => __('sirsoft-board::attributes.comment.content'),
'is_secret' => __('sirsoft-board::attributes.comment.is_secret'),
'status' => __('sirsoft-board::attributes.comment.status'),
'password' => __('sirsoft-board::attributes.comment.password'),
'content' => __('sirsoft-board::validation.attributes.comment.content'),
'is_secret' => __('sirsoft-board::validation.attributes.comment.is_secret'),
'status' => __('sirsoft-board::validation.attributes.comment.status'),
'password' => __('sirsoft-board::validation.attributes.comment.password'),
];
}
}
@@ -76,8 +76,8 @@ class UpdateStatusRequest extends FormRequest
public function attributes(): array
{
return [
'status' => __('sirsoft-board::attributes.report.status'),
'process_note' => __('sirsoft-board::attributes.report.process_note'),
'status' => __('sirsoft-board::validation.attributes.report.status'),
'process_note' => __('sirsoft-board::validation.attributes.report.process_note'),
];
}
}
@@ -4,6 +4,7 @@ namespace Modules\Sirsoft\Board\Http\Requests;
use App\Extension\HookManager;
use Illuminate\Foundation\Http\FormRequest;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ResolvesAllowedExtensions;
use Modules\Sirsoft\Board\Models\Board;
/**
@@ -11,8 +12,12 @@ use Modules\Sirsoft\Board\Models\Board;
*/
class UploadAttachmentRequest extends FormRequest
{
use ResolvesAllowedExtensions;
/**
* 요청 권한 확인
*
* @return bool 항상 true (권한은 미들웨어에서 검증)
*/
public function authorize(): bool
{
@@ -43,7 +48,14 @@ class UploadAttachmentRequest extends FormRequest
$maxSizeMB = $board->max_file_size ?? 10;
$maxSizeKB = $maxSizeMB * 1024;
$allowedExtensions = $board->allowed_extensions ?? ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'zip'];
// 게시판 값이 비어 있으면(null 또는 []) 모듈 기본값으로 폴백한다.
// 빈 배열을 그대로 쓰면 'mimes:' 빈 규칙이 되어 전 파일이 거부된다.
$defaults = g7_module_settings('sirsoft-board', 'basic_defaults', []);
$allowedExtensions = $this->resolveAllowedExtensions(
$board->allowed_extensions,
$defaults['allowed_extensions'] ?? null
);
$mimes = implode(',', $allowedExtensions);
$rules = [
@@ -8,6 +8,7 @@ use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Modules\Sirsoft\Board\Enums\PostStatus;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ResolvesAllowedExtensions;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Models\Post;
use Modules\Sirsoft\Board\Rules\BlockedKeywordsRule;
@@ -24,8 +25,12 @@ use Modules\Sirsoft\Board\Rules\ParentPostValidationRule;
*/
class StorePostRequest extends FormRequest
{
use ResolvesAllowedExtensions;
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* @return bool 항상 true (권한은 미들웨어에서 검증)
*/
public function authorize(): bool
{
@@ -116,7 +121,12 @@ class StorePostRequest extends FormRequest
$maxFiles = $board->max_file_count ?? $defaults['max_file_count'] ?? 5;
$maxSizeMB = $board->max_file_size ?? $defaults['max_file_size'] ?? 10;
$maxSizeKB = $maxSizeMB * 1024;
$allowedExtensions = $board->allowed_extensions ?? $defaults['allowed_extensions'] ?? ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'zip'];
// 게시판/기본값이 모두 비어 있으면(null 또는 []) 최종 기본 확장자로 폴백한다.
// 빈 배열을 그대로 쓰면 'mimes:' 빈 규칙이 되어 전 파일이 거부된다.
$allowedExtensions = $this->resolveAllowedExtensions(
$board->allowed_extensions,
$defaults['allowed_extensions'] ?? null
);
$mimes = implode(',', $allowedExtensions);
$rules['files'] = ['nullable', 'array', 'max:'.$maxFiles];
@@ -183,7 +193,9 @@ class StorePostRequest extends FormRequest
/**
* 검증 통과 후 비밀번호를 해싱합니다.
*
* @return array<string, mixed>
* @param string|null $key 조회할 키 (null 이면 전체)
* @param mixed $default 키가 없을 때 반환할 기본값
* @return array<string, mixed> 해싱이 적용된 검증 통과 데이터
*/
public function validated($key = null, $default = null): mixed
{
@@ -45,7 +45,7 @@ class CommentResource extends BaseApiResource
// 댓글 속성
'is_secret' => $this->is_secret,
'status' => $this->status?->value ?? 'published',
'status_label' => $this->status?->label() ?? __('sirsoft-board::messages.post.status.published'),
'status_label' => $this->status?->label() ?? __('sirsoft-board::enums.post_status.published'),
'depth' => $this->depth,
'replies_count' => $this->replies_count ?? 0,
@@ -3,12 +3,14 @@
namespace Modules\Sirsoft\Board\Models;
use App\Casts\AsUnicodeJson;
use App\Models\Permission;
use App\Models\User;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Modules\Sirsoft\Board\Casts\AsAllowedExtensions;
use Modules\Sirsoft\Board\Database\Factories\BoardFactory;
use Modules\Sirsoft\Board\Enums\BoardOrderBy;
use Modules\Sirsoft\Board\Enums\OrderDirection;
@@ -23,11 +25,11 @@ class Board extends Model
'is_active' => ['label_key' => 'sirsoft-board::activity_log.fields.is_active', 'type' => 'boolean'],
'per_page' => ['label_key' => 'sirsoft-board::activity_log.fields.per_page', 'type' => 'number'],
'per_page_mobile' => ['label_key' => 'sirsoft-board::activity_log.fields.per_page_mobile', 'type' => 'number'],
'order_by' => ['label_key' => 'sirsoft-board::activity_log.fields.order_by', 'type' => 'enum', 'enum' => \Modules\Sirsoft\Board\Enums\BoardOrderBy::class],
'order_direction' => ['label_key' => 'sirsoft-board::activity_log.fields.order_direction', 'type' => 'enum', 'enum' => \Modules\Sirsoft\Board\Enums\OrderDirection::class],
'order_by' => ['label_key' => 'sirsoft-board::activity_log.fields.order_by', 'type' => 'enum', 'enum' => BoardOrderBy::class],
'order_direction' => ['label_key' => 'sirsoft-board::activity_log.fields.order_direction', 'type' => 'enum', 'enum' => OrderDirection::class],
'type' => ['label_key' => 'sirsoft-board::activity_log.fields.type', 'type' => 'text'],
'show_view_count' => ['label_key' => 'sirsoft-board::activity_log.fields.show_view_count', 'type' => 'boolean'],
'secret_mode' => ['label_key' => 'sirsoft-board::activity_log.fields.secret_mode', 'type' => 'enum', 'enum' => \Modules\Sirsoft\Board\Enums\SecretMode::class],
'secret_mode' => ['label_key' => 'sirsoft-board::activity_log.fields.secret_mode', 'type' => 'enum', 'enum' => SecretMode::class],
'use_comment' => ['label_key' => 'sirsoft-board::activity_log.fields.use_comment', 'type' => 'boolean'],
'use_reply' => ['label_key' => 'sirsoft-board::activity_log.fields.use_reply', 'type' => 'boolean'],
'max_reply_depth' => ['label_key' => 'sirsoft-board::activity_log.fields.max_reply_depth', 'type' => 'number'],
@@ -170,7 +172,8 @@ class Board extends Model
'name' => AsUnicodeJson::class,
'description' => AsUnicodeJson::class,
'categories' => 'array',
'allowed_extensions' => 'array',
// 빈 배열을 NULL 로 정규화해 "확장자 미지정" 표현을 하나로 유지합니다.
'allowed_extensions' => AsAllowedExtensions::class,
'blocked_keywords' => 'array',
'is_active' => 'boolean',
'show_view_count' => 'boolean',
@@ -193,6 +196,8 @@ class Board extends Model
/**
* 생성자와의 관계를 정의합니다.
*
* @return BelongsTo 생성자 관계
*/
public function creator(): BelongsTo
{
@@ -201,6 +206,8 @@ class Board extends Model
/**
* 수정자와의 관계를 정의합니다.
*
* @return BelongsTo 수정자 관계
*/
public function updater(): BelongsTo
{
@@ -209,6 +216,8 @@ class Board extends Model
/**
* 게시글 목록과의 관계를 정의합니다.
*
* @return HasMany 게시글 관계
*/
public function posts(): HasMany
{
@@ -217,6 +226,8 @@ class Board extends Model
/**
* 댓글 목록과의 관계를 정의합니다.
*
* @return HasMany 댓글 관계
*/
public function comments(): HasMany
{
@@ -225,6 +236,8 @@ class Board extends Model
/**
* 첨부파일 목록과의 관계를 정의합니다.
*
* @return HasMany 첨부파일 관계
*/
public function attachments(): HasMany
{
@@ -233,6 +246,8 @@ class Board extends Model
/**
* 신고 목록과의 관계를 정의합니다.
*
* @return HasMany 신고 관계
*/
public function reports(): HasMany
{
@@ -241,6 +256,9 @@ class Board extends Model
/**
* 지정된 로케일의 게시판명 반환
*
* @param string|null $locale 로케일 (null 이면 현재 로케일)
* @return string 해당 로케일의 게시판명
*/
public function getLocalizedName(?string $locale = null): string
{
@@ -325,7 +343,7 @@ class Board extends Model
$identifier = "sirsoft-board.{$this->slug}.{$key}";
// 권한 조회
$permission = \App\Models\Permission::where('identifier', $identifier)->first();
$permission = Permission::where('identifier', $identifier)->first();
if (! $permission) {
// 권한이 없으면 null (전체 허용)
@@ -21,7 +21,6 @@ trait ChecksBoardPermission
* @param string $slug 게시판 슬러그
* @param string $action 권한 액션 (예: 'admin.posts.read')
* @param PermissionType $type 권한 타입
* @return bool
*/
protected function checkBoardPermission(string $slug, string $action, PermissionType $type = PermissionType::Admin): bool
{
@@ -35,7 +34,6 @@ trait ChecksBoardPermission
* @param array $actions 권한 액션 배열
* @param PermissionType $type 권한 타입
* @param bool $requireAll 모든 권한 필요 여부
* @return bool
*/
protected function checkBoardPermissions(string $slug, array $actions, PermissionType $type = PermissionType::Admin, bool $requireAll = false): bool
{
@@ -50,7 +48,6 @@ trait ChecksBoardPermission
* @param string $resource 리소스명 (예: 'boards')
* @param string $action 권한 액션 (예: 'create')
* @param PermissionType $type 권한 타입
* @return bool
*/
protected function checkModulePermission(string $resource, string $action, PermissionType $type = PermissionType::Admin): bool
{
@@ -63,12 +60,11 @@ trait ChecksBoardPermission
* @param string $slug 게시판 슬러그
* @param string $action 권한 액션
* @param PermissionType $type 권한 타입
* @return JsonResponse|null
*/
protected function authorizeOrFail(string $slug, string $action, PermissionType $type = PermissionType::Admin): ?JsonResponse
{
if (! $this->checkBoardPermission($slug, $action, $type)) {
return $this->forbidden('sirsoft-board::messages.permissions.access_denied');
return $this->forbidden('sirsoft-board::messages.permission.denied');
}
return null;
@@ -81,12 +77,11 @@ trait ChecksBoardPermission
* @param array $actions 권한 액션 배열
* @param PermissionType $type 권한 타입
* @param bool $requireAll 모든 권한 필요 여부
* @return JsonResponse|null
*/
protected function authorizeAnyOrFail(string $slug, array $actions, PermissionType $type = PermissionType::Admin, bool $requireAll = false): ?JsonResponse
{
if (! $this->checkBoardPermissions($slug, $actions, $type, $requireAll)) {
return $this->forbidden('sirsoft-board::messages.permissions.access_denied');
return $this->forbidden('sirsoft-board::messages.permission.denied');
}
return null;
@@ -98,12 +93,11 @@ trait ChecksBoardPermission
* @param string $resource 리소스명
* @param string $action 권한 액션
* @param PermissionType $type 권한 타입
* @return JsonResponse|null
*/
protected function authorizeModuleOrFail(string $resource, string $action, PermissionType $type = PermissionType::Admin): ?JsonResponse
{
if (! $this->checkModulePermission($resource, $action, $type)) {
return $this->forbidden('sirsoft-board::messages.permissions.access_denied');
return $this->forbidden('sirsoft-board::messages.permission.denied');
}
return null;
@@ -115,7 +109,6 @@ trait ChecksBoardPermission
* Admin/User 페이지에 따라 자동으로 권한 타입을 결정합니다.
*
* @param string $identifier 권한 식별자 (예: 'sirsoft-board.notice.posts.read')
* @return bool
*/
protected function checkPermissionByIdentifier(string $identifier): bool
{
@@ -129,8 +122,6 @@ trait ChecksBoardPermission
* 권한 캐시를 초기화합니다.
*
* 테스트 환경에서 동일 Request 인스턴스가 재사용되는 경우 호출합니다.
*
* @return void
*/
public static function clearPermissionCache(): void
{
@@ -146,13 +137,12 @@ trait ChecksBoardPermission
* @param string $permission 권한 식별자 (파이프로 복수 권한 구분)
* @param PermissionType $type 권한 타입
* @param bool $requireAll 모든 권한 필요 여부
* @return bool
*/
protected function checkPermissionViaMiddleware(string $permission, PermissionType $type, bool $requireAll = true): bool
{
$request = request();
$userId = Auth::id() ?? 'guest';
$cacheKey = $userId . '|' . $permission . '|' . $type->value . '|' . ($requireAll ? '1' : '0');
$cacheKey = $userId.'|'.$permission.'|'.$type->value.'|'.($requireAll ? '1' : '0');
// 요청 인스턴스에 권한 캐시를 저장하여 요청 단위로 자동 격리
$cache = $request->attributes->get('_board_permission_cache', []);
@@ -77,6 +77,7 @@ return [
// ChangeDetector field labels
'fields' => [
// Board
'name' => 'Board Name',
'is_active' => 'Active',
'per_page' => 'Posts Per Page',
'per_page_mobile' => 'Posts Per Page (Mobile)',
@@ -13,6 +13,7 @@ return [
'already_exists' => 'Board slug already exists.',
'has_posts' => 'Cannot delete board with posts.',
'fetch_success' => 'Board information retrieved.',
'fetch_failed' => 'Failed to retrieve boards.',
'create_success' => 'Board has been created.',
'update_success' => 'Board has been updated.',
'delete_success' => 'Board has been deleted.',
@@ -20,6 +21,7 @@ return [
'config_retrieved' => 'Board configuration retrieved.',
'types_retrieved' => 'Board types retrieved.',
'form_data_retrieved' => 'Board form data retrieved.',
'form_data_failed' => 'Failed to retrieve board form data.',
'copy_data_retrieved' => 'Board copy data retrieved.',
'create_failed' => 'Failed to create board.',
'update_failed' => 'Failed to update board.',
@@ -81,6 +83,7 @@ return [
'guest_write_not_allowed' => 'Guest posting is not allowed on this board.',
'file_upload_not_allowed' => 'File upload is not allowed on this board.',
'guest_upload_not_allowed' => 'Guest file upload is not allowed on this board.',
'secret_post_not_allowed' => 'Secret posts are not available on this board.',
'modify_permission_denied' => 'You do not have permission to modify this post.',
'delete_permission_denied' => 'You do not have permission to delete this post.',
'error_404' => 'Post not found.',
@@ -110,11 +113,22 @@ return [
'restore_success' => 'Comment has been restored.',
'restore_failed' => 'Failed to restore comment.',
'blinded_comment_content' => 'This comment has been hidden according to the community guidelines.',
'deleted_comment_content' => 'This comment has been deleted.',
// Guest comment password verification
'not_guest_comment' => 'This is not a guest comment.',
'invalid_password' => 'The password does not match.',
'password_verified' => 'Password verified.',
'verify_password_failed' => 'Failed to verify the password.',
// Comment availability
'post_blinded' => 'You cannot comment on a blinded post.',
'post_deleted' => 'You cannot comment on a deleted post.',
],
// Additional comment messages
'comments' => [
'comments_disabled' => 'Comments are disabled for this board.',
'index_success' => 'Comments retrieved.',
'index_failed' => 'Failed to retrieve comments.',
],
// Attachment operation messages
@@ -286,6 +300,24 @@ return [
'stats_failed' => 'Failed to fetch activity statistics.',
],
// Board settings messages
//
// Referenced by BoardSettingsController via ResponseHelper::moduleSuccess/moduleError.
// If these exist only in the frontend language pack, __() cannot resolve them and the raw
// key leaks into the API response message.
'settings' => [
'fetch_success' => 'Settings loaded successfully.',
'fetch_failed' => 'Failed to load settings.',
'save_success' => 'Settings saved successfully.',
'save_failed' => 'Failed to save settings.',
'save_error' => 'An error occurred while saving settings.',
'bulk_apply_success' => 'Settings applied to :count boards.',
'bulk_apply_aborted' => 'An error occurred during bulk apply. All changes have been rolled back.',
'bulk_apply_failed' => 'Failed to bulk apply settings.',
'clear_cache_success' => 'Settings cache cleared successfully.',
'clear_cache_error' => 'An error occurred while clearing settings cache.',
],
// Table related messages
'invalid_slug_format' => 'Invalid slug format. Must start with lowercase letter and contain only lowercase letters, numbers, and hyphens. (slug: :slug)',
'invalid_slug_length' => 'Invalid slug length. Must be between 1-50 characters. (slug: :slug)',
@@ -297,6 +329,8 @@ return [
// Common
'common' => [
'guest' => 'Guest',
// Display name when the processor is the system (automated)
'system' => 'System',
'status' => [
'published' => 'Published',
'blinded' => 'Blinded',
@@ -319,4 +353,7 @@ return [
'inquiry' => [
'default_title' => 'Product Inquiry',
],
'dashboard' => [
'fetch_success' => 'Dashboard data retrieved successfully.',
],
];
@@ -10,6 +10,15 @@ return [
// bulk apply fields validation messages
'fields_invalid' => 'The selected :value field is not allowed.',
// Bulk apply of board settings validation messages
'bulk_apply' => [
'fields.required' => 'Please select at least one setting to apply.',
'fields.min' => 'Please select at least one setting to apply.',
'apply_all.required' => 'Please specify whether to apply to all boards.',
'board_ids.required_if' => 'Please select target boards when not applying to all boards.',
'board_ids.*.exists' => 'Board does not exist.',
],
// slug validation messages
'slug' => [
'required' => 'Board slug is required.',
@@ -104,6 +113,10 @@ return [
'min' => 'Please select at least one role for this permission.',
'exists' => 'Role does not exist.',
],
'mode' => [
'required' => 'Please select a permission mode.',
'in' => 'Invalid permission mode.',
],
],
// reply/comment depth validation messages
@@ -175,6 +188,7 @@ return [
// Board validation (backward compatibility)
'board' => [
'not_found' => 'Board not found.',
'name' => [
'required' => 'Board name is required.',
'string' => 'Board name must be a string.',
@@ -363,6 +377,30 @@ return [
],
'board' => [
'add_to_menu' => 'Show in admin menu',
'blocked_keywords' => 'Blocked Keywords',
],
// Bulk apply of board settings
'bulk_apply' => [
'fields' => 'Target Settings',
'fields.*' => 'Target Settings',
'apply_all' => 'Apply to All Boards',
'board_ids' => 'Target Boards',
'board_ids.*' => 'Target Boards',
'override_values' => 'Override Values',
// Column labels for override values — mirror the settings group (shown on range errors)
'override_values.per_page' => 'Posts Per Page',
'override_values.per_page_mobile' => 'Posts Per Page (Mobile)',
'override_values.max_reply_depth' => 'Max Reply Depth',
'override_values.max_comment_depth' => 'Max Comment Depth',
'override_values.min_title_length' => 'Min Title Length',
'override_values.max_title_length' => 'Max Title Length',
'override_values.min_content_length' => 'Min Content Length',
'override_values.max_content_length' => 'Max Content Length',
'override_values.min_comment_length' => 'Min Comment Length',
'override_values.max_comment_length' => 'Max Comment Length',
'override_values.max_file_size' => 'Max File Size',
'override_values.max_file_count' => 'Max File Count',
'override_values.new_display_hours' => 'New Display Hours',
],
],
@@ -543,6 +581,7 @@ return [
// Report validation messages
'report' => [
'invalid_status_transition' => 'The report cannot be changed to that status from its current status.',
'status' => [
'required' => 'Report status is required.',
'in' => 'Invalid report status.',
@@ -77,6 +77,7 @@ return [
// ChangeDetector 필드 라벨
'fields' => [
// Board
'name' => '게시판명',
'is_active' => '활성 여부',
'per_page' => '페이지당 게시물 수',
'per_page_mobile' => '모바일 페이지당 게시물 수',
@@ -13,6 +13,7 @@ return [
'already_exists' => '이미 존재하는 게시판 슬러그입니다.',
'has_posts' => '게시글이 있는 게시판은 삭제할 수 없습니다.',
'fetch_success' => '게시판 정보를 조회했습니다.',
'fetch_failed' => '게시판 목록 조회에 실패했습니다.',
'create_success' => '게시판이 생성되었습니다.',
'update_success' => '게시판이 수정되었습니다.',
'delete_success' => '게시판이 삭제되었습니다.',
@@ -20,6 +21,7 @@ return [
'config_retrieved' => '게시판 설정을 조회했습니다.',
'types_retrieved' => '게시판 타입 목록을 조회했습니다.',
'form_data_retrieved' => '게시판 폼 데이터를 조회했습니다.',
'form_data_failed' => '게시판 폼 데이터 조회에 실패했습니다.',
'copy_data_retrieved' => '게시판 복사 데이터를 조회했습니다.',
'create_failed' => '게시판 생성에 실패했습니다.',
'update_failed' => '게시판 수정에 실패했습니다.',
@@ -81,6 +83,7 @@ return [
'guest_write_not_allowed' => '이 게시판은 비회원 글쓰기가 허용되지 않습니다.',
'file_upload_not_allowed' => '이 게시판은 파일 업로드가 허용되지 않습니다.',
'guest_upload_not_allowed' => '이 게시판은 비회원 파일 업로드가 허용되지 않습니다.',
'secret_post_not_allowed' => '이 게시판은 비밀글을 사용할 수 없습니다.',
'modify_permission_denied' => '게시글 수정 권한이 없습니다.',
'delete_permission_denied' => '게시글 삭제 권한이 없습니다.',
'error_404' => '존재하지 않는 게시글입니다.',
@@ -110,11 +113,22 @@ return [
'restore_success' => '댓글이 복원되었습니다.',
'restore_failed' => '댓글 복원에 실패했습니다.',
'blinded_comment_content' => '운영원칙에 따라 숨김 처리된 댓글입니다.',
'deleted_comment_content' => '삭제된 댓글입니다.',
// 비회원 댓글 비밀번호 검증
'not_guest_comment' => '비회원 댓글이 아닙니다.',
'invalid_password' => '비밀번호가 일치하지 않습니다.',
'password_verified' => '비밀번호가 확인되었습니다.',
'verify_password_failed' => '비밀번호 검증에 실패했습니다.',
// 댓글 작성 가능 여부
'post_blinded' => '블라인드 처리된 게시글에는 댓글을 작성할 수 없습니다.',
'post_deleted' => '삭제된 게시글에는 댓글을 작성할 수 없습니다.',
],
// 댓글 관련 추가 메시지
'comments' => [
'comments_disabled' => '이 게시판은 댓글 기능이 비활성화되어 있습니다.',
'index_success' => '댓글 목록을 조회했습니다.',
'index_failed' => '댓글 목록 조회에 실패했습니다.',
],
// 첨부파일 작업 메시지
@@ -286,6 +300,25 @@ return [
'stats_failed' => '활동 통계 조회에 실패했습니다.',
],
// 게시판 환경설정 관련 메시지
//
// BoardSettingsController 가 ResponseHelper::moduleSuccess/moduleError 로 참조한다.
// 프런트 언어팩(resources/lang/partial/*/messages.json)에만 있으면 __() 가 해석하지 못해
// API 응답 message 에 원문 키가 그대로 나간다 (실패 경로는 레이아웃이 {{error.message}} 를
// 그대로 노출하므로 사용자가 키를 보게 된다).
'settings' => [
'fetch_success' => '설정을 조회했습니다.',
'fetch_failed' => '설정 조회에 실패했습니다.',
'save_success' => '설정이 저장되었습니다.',
'save_failed' => '설정 저장에 실패했습니다.',
'save_error' => '설정 저장 중 오류가 발생했습니다.',
'bulk_apply_success' => ':count개 게시판에 설정이 일괄 적용되었습니다.',
'bulk_apply_aborted' => '일괄 적용 중 오류가 발생하여 모든 변경을 되돌렸습니다.',
'bulk_apply_failed' => '설정 일괄 적용에 실패했습니다.',
'clear_cache_success' => '설정 캐시가 초기화되었습니다.',
'clear_cache_error' => '설정 캐시 초기화 중 오류가 발생했습니다.',
],
// 테이블 관련 메시지
'invalid_slug_format' => '슬러그 형식이 올바르지 않습니다. 소문자로 시작하고 소문자, 숫자, 하이픈만 사용할 수 있습니다. (슬러그: :slug)',
'invalid_slug_length' => '슬러그 길이가 올바르지 않습니다. 1-50자 이내로 입력해주세요. (슬러그: :slug)',
@@ -297,6 +330,8 @@ return [
// 공통
'common' => [
'guest' => '비회원',
// 처리자가 시스템(자동 처리)인 경우의 표시명
'system' => '시스템',
'status' => [
'published' => '게시중',
'blinded' => '블라인드',
@@ -319,4 +354,7 @@ return [
'inquiry' => [
'default_title' => '상품 문의',
],
'dashboard' => [
'fetch_success' => '대시보드 데이터를 조회했습니다.',
],
];
@@ -10,6 +10,15 @@ return [
// 일괄 적용 fields 검증 메시지
'fields_invalid' => '선택한 :value 필드는 허용되지 않습니다.',
// 게시판 설정 일괄 적용 검증 메시지
'bulk_apply' => [
'fields.required' => '일괄 적용할 항목을 하나 이상 선택해주세요.',
'fields.min' => '일괄 적용할 항목을 하나 이상 선택해주세요.',
'apply_all.required' => '전체 게시판 적용 여부를 지정해주세요.',
'board_ids.required_if' => '전체 적용이 아닌 경우 대상 게시판을 선택해주세요.',
'board_ids.*.exists' => '존재하지 않는 게시판입니다.',
],
// slug 검증 메시지
'slug' => [
'required' => '게시판 슬러그는 필수입니다.',
@@ -137,6 +146,10 @@ return [
'min' => '권한에 최소 하나 이상의 역할을 선택해주세요.',
'exists' => '존재하지 않는 역할입니다.',
],
'mode' => [
'required' => '권한 모드를 선택해주세요.',
'in' => '유효하지 않은 권한 모드입니다.',
],
],
// 답글/대댓글 깊이 검증 메시지
@@ -175,6 +188,7 @@ return [
// 게시판 검증 (하위 호환성 유지)
'board' => [
'not_found' => '게시판을 찾을 수 없습니다.',
'name' => [
'required' => '게시판명은 필수입니다.',
'string' => '게시판명은 문자열이어야 합니다.',
@@ -363,6 +377,30 @@ return [
],
'board' => [
'add_to_menu' => '관리자 메뉴에 표시',
'blocked_keywords' => '금지어',
],
// 게시판 설정 일괄 적용
'bulk_apply' => [
'fields' => '적용 항목',
'fields.*' => '적용 항목',
'apply_all' => '전체 게시판 적용',
'board_ids' => '대상 게시판',
'board_ids.*' => '대상 게시판',
'override_values' => '재정의 값',
// 재정의 값의 컬럼 라벨 — settings 그룹과 동일 명칭 (범위 위반 메시지에 노출)
'override_values.per_page' => '페이지당 게시글 수',
'override_values.per_page_mobile' => '모바일 페이지당 게시글 수',
'override_values.max_reply_depth' => '최대 답글 깊이',
'override_values.max_comment_depth' => '최대 댓글 깊이',
'override_values.min_title_length' => '최소 제목 길이',
'override_values.max_title_length' => '최대 제목 길이',
'override_values.min_content_length' => '최소 내용 길이',
'override_values.max_content_length' => '최대 내용 길이',
'override_values.min_comment_length' => '최소 댓글 길이',
'override_values.max_comment_length' => '최대 댓글 길이',
'override_values.max_file_size' => '최대 파일 크기',
'override_values.max_file_count' => '최대 파일 개수',
'override_values.new_display_hours' => '신규 표시 시간',
],
],
@@ -543,6 +581,7 @@ return [
// 신고 검증 메시지
'report' => [
'invalid_status_transition' => '현재 신고 상태에서는 해당 상태로 변경할 수 없습니다.',
'status' => [
'required' => '신고 상태는 필수입니다.',
'in' => '유효하지 않은 신고 상태입니다.',
@@ -410,6 +410,82 @@ class BoardManagementTest extends ModuleTestCase
$this->assertFalse($board->fresh()->is_active);
}
/**
* 폼 데이터를 그대로 되돌려 저장해도 통과해야 한다 (이슈 #78 통합 회귀)
*
* 관리자 폼은 GET 응답 전체를 _local.form 에 통째로 주입하고 그대로 PUT 한다.
* 따라서 요청에는 항상 모든 키가 존재하며, 무변경 저장이 검증에 막히면 안 된다.
* 이 테스트가 "전체 객체 PUT" 이라는 프런트 계약을 백엔드에 고정한다.
*
* @dataProvider roundTripBoardAttributesProvider
*
* @scenario case=upload_disabled_extensions_null
*
* @effects unchanged_form_data_round_trip_saves
*
* @param array<string, mixed> $attributes 게시판 속성
*/
public function test_form_data_round_trip_save_passes(array $attributes): void
{
// Given: 생성 API 로 만든 게시판 (board-scoped 역할/권한이 실제로 존재하는 상태)
$slug = 'test-rt-'.substr(md5(microtime().serialize($attributes)), 0, 8);
$this->actingAs($this->adminUser)
->postJson('/api/modules/sirsoft-board/admin/boards', [
'name' => ['ko' => '왕복 저장 테스트', 'en' => 'Round Trip Test'],
'slug' => $slug,
'type' => 'basic',
'show_view_count' => true,
'use_report' => false,
'board_manager_ids' => [$this->adminUser->uuid],
])->assertStatus(201);
// 검증 대상 상태를 DB 에 직접 반영 (레거시 데이터 재현)
$board = Board::where('slug', $slug)->firstOrFail();
$board->forceFill($attributes)->save();
// When: 폼 데이터를 조회하고 받은 객체를 그대로 PUT
$formResponse = $this->actingAs($this->adminUser)
->getJson('/api/modules/sirsoft-board/admin/boards/form-data?board_slug='.$board->slug);
$formResponse->assertStatus(200);
$payload = $formResponse->json('data');
$response = $this->actingAs($this->adminUser)
->putJson("/api/modules/sirsoft-board/admin/boards/{$board->slug}", $payload);
// Then: 무변경 저장이 통과해야 함
$response->assertStatus(200, '무변경 저장 실패: '.json_encode($response->json(), JSON_UNESCAPED_UNICODE));
}
/**
* 무변경 저장 회귀 대상 게시판 속성.
*
* @return array<string, array{array<string, mixed>}> 게시판 속성
*/
public static function roundTripBoardAttributesProvider(): array
{
return [
'첨부 미사용 + 확장자 NULL' => [[
'use_file_upload' => false,
'allowed_extensions' => null,
]],
'첨부 미사용 + 확장자 빈 배열' => [[
'use_file_upload' => false,
'allowed_extensions' => [],
]],
'첨부 미사용 + NEW 배지 끄기' => [[
'use_file_upload' => false,
'allowed_extensions' => null,
'new_display_hours' => 0,
]],
'첨부 사용 + 확장자 지정' => [[
'use_file_upload' => true,
'allowed_extensions' => ['jpg', 'png'],
]],
];
}
/**
* 폼 데이터를 board_slug 로 수정 모드 조회할 수 있다 (#450)
*/
@@ -420,6 +420,67 @@ class BoardSettingsControllerTest extends ModuleTestCase
$response->assertStatus(200);
}
/**
* override_values 의 컬럼 값도 Store/Update 와 동일한 범위 제한(ReadsBoardLimits SSoT)을 받는다.
*
* 회귀: 일괄 적용 경로는 override_values 를 무검증(`['sometimes','array']`)으로 통과시켜
* boards 컬럼에 직접 기록했다. Store/Update 가 config/board.php SSoT 로 강제하는 바로 그 컬럼을
* 일괄 적용만 우회할 수 있어, new_display_hours=99999(상한 720) 같은 값이 저장됐다.
*/
public function test_bulk_apply_rejects_out_of_range_override_new_display_hours(): void
{
$response = $this->actingAs($this->adminUser)
->postJson('/api/modules/sirsoft-board/admin/settings/bulk-apply', [
'fields' => ['new_display_hours'],
'apply_all' => true,
'override_values' => ['new_display_hours' => 99999], // 상한 720 초과
]);
$response->assertStatus(422)
->assertJsonValidationErrors(['override_values.new_display_hours']);
}
/**
* override_values 의 길이 제한 컬럼(min_title_length 등)도 상한을 넘으면 거부한다.
*/
public function test_bulk_apply_rejects_out_of_range_override_min_title_length(): void
{
$response = $this->actingAs($this->adminUser)
->postJson('/api/modules/sirsoft-board/admin/settings/bulk-apply', [
'fields' => ['min_title_length'],
'apply_all' => true,
'override_values' => ['min_title_length' => 999999], // 상한 200 초과
]);
$response->assertStatus(422)
->assertJsonValidationErrors(['override_values.min_title_length']);
}
/**
* 범위 안의 override_values 는 정상 통과한다(정정이 유효값까지 막지 않음).
*/
public function test_bulk_apply_accepts_in_range_override_values(): void
{
$board = Board::create([
'name' => ['ko' => '테스트', 'en' => 'Test'],
'slug' => 'settings-ov-'.substr(md5(microtime()), 0, 8),
'type' => 'gallery',
'new_display_hours' => 24,
]);
$response = $this->actingAs($this->adminUser)
->postJson('/api/modules/sirsoft-board/admin/settings/bulk-apply', [
'fields' => ['new_display_hours'],
'apply_all' => true,
'override_values' => ['new_display_hours' => 48], // 상한 720 이내
]);
$response->assertStatus(200);
$board->refresh();
$this->assertEquals(48, $board->new_display_hours);
}
// ========================================
// StoreBoardSettingsRequest 검증 경계값 테스트 (회귀: issue#413)
// ========================================
@@ -3,8 +3,10 @@
namespace Modules\Sirsoft\Board\Tests\Feature\Admin;
// ModuleTestCase를 수동으로 require (autoload 전에 로드 필요)
require_once __DIR__ . '/../../ModuleTestCase.php';
require_once __DIR__.'/../../ModuleTestCase.php';
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Support\Facades\Schema;
use Modules\Sirsoft\Board\Models\Board;
@@ -22,7 +24,7 @@ class BoardTypeManagementTest extends ModuleTestCase
if (! Schema::hasTable('board_types')) {
$this->artisan('migrate', [
'--path' => $this->getModuleBasePath() . '/database/migrations',
'--path' => $this->getModuleBasePath().'/database/migrations',
'--realpath' => true,
]);
}
@@ -239,14 +241,21 @@ class BoardTypeManagementTest extends ModuleTestCase
'name' => ['ko' => '기본 유형'],
]);
// basic_defaults 는 파일 기반 전역 설정이라 DB 트랜잭션 롤백 대상이 아니다.
// 원래 값을 보관했다가 테스트 종료 시 반드시 되돌린다 (미복원 시 개발/운영 설정 오염).
$settingsService = app(BoardSettingsService::class);
$originalType = $settingsService->getSettings('basic_defaults')['type'] ?? null;
$settingsService->setSetting('basic_defaults.type', 'test_default_type');
$response = $this->actingAs($this->adminUser)
->deleteJson("/api/modules/sirsoft-board/admin/board-types/{$boardType->id}");
try {
$response = $this->actingAs($this->adminUser)
->deleteJson("/api/modules/sirsoft-board/admin/board-types/{$boardType->id}");
$response->assertStatus(422);
$this->assertDatabaseHas('board_types', ['id' => $boardType->id]);
$response->assertStatus(422);
$this->assertDatabaseHas('board_types', ['id' => $boardType->id]);
} finally {
$settingsService->setSetting('basic_defaults.type', $originalType);
}
}
/**
@@ -280,8 +289,8 @@ class BoardTypeManagementTest extends ModuleTestCase
'name' => ['ko' => '폼 테스트 유형'],
]);
$adminRole = \App\Models\Role::where('identifier', 'admin')->first();
$readPerm = \App\Models\Permission::firstOrCreate(
$adminRole = Role::where('identifier', 'admin')->first();
$readPerm = Permission::firstOrCreate(
['identifier' => 'sirsoft-board.boards.read'],
['name' => ['ko' => '게시판 조회', 'en' => 'Read Boards'], 'type' => 'admin']
);
@@ -1107,6 +1107,343 @@ class BoardRequestTest extends ModuleTestCase
$this->assertTrue($validator->passes(), '다른 탭만 부분 저장 시 통과해야 함');
}
// ==========================================
// 조건부 검증 매트릭스 (이슈 #78)
//
// 관리자 폼은 GET 응답 전체를 그대로 PUT 하므로 요청에는 항상 모든 키가 존재한다.
// 따라서 sometimes 는 아무 보호도 하지 못하며, 토글 OFF 상태의 종속 필드는
// exclude_if 로 검증 자체에서 제외되어야 한다.
// ==========================================
/**
* UpdateBoardRequest - 첨부 사용 게시판에서 빈 확장자는 차단되어야 함
*
* @scenario case=upload_enabled_extensions_empty
*
* @effects upload_enabled_empty_extensions_fails
*/
public function test_update_matrix_upload_enabled_with_empty_extensions_fails(): void
{
$request = $this->makeUpdateRequest();
$validator = Validator::make([
'use_file_upload' => true,
'allowed_extensions' => [],
], $request->rules());
$this->assertFalse($validator->passes(), '첨부 사용 + 빈 확장자는 실패해야 함');
$this->assertArrayHasKey('allowed_extensions', $validator->errors()->toArray());
}
/**
* UpdateBoardRequest - 첨부 사용 게시판에서 확장자 1개 이상은 통과
*
* @scenario case=upload_enabled_extensions_nonempty
*
* @effects upload_enabled_nonempty_extensions_passes
*/
public function test_update_matrix_upload_enabled_with_extensions_passes(): void
{
$request = $this->makeUpdateRequest();
$validator = Validator::make([
'use_file_upload' => true,
'allowed_extensions' => ['jpg'],
], $request->rules());
$this->assertTrue($validator->passes(), '첨부 사용 + 확장자 지정은 통과해야 함');
}
/**
* UpdateBoardRequest - 첨부 미사용 게시판은 빈 배열 확장자도 통과해야 함 (이슈 #78)
*
* 첨부를 쓰지 않는 게시판을 무변경 저장할 때 422 로 막히던 결함의 회귀 테스트.
*
* @scenario case=upload_disabled_extensions_empty
*
* @effects upload_disabled_empty_extensions_passes
*/
public function test_update_matrix_upload_disabled_with_empty_extensions_passes(): void
{
$request = $this->makeUpdateRequest();
$validator = Validator::make([
'use_file_upload' => false,
'allowed_extensions' => [],
], $request->rules());
$this->assertTrue(
$validator->passes(),
'첨부 미사용 게시판의 빈 확장자는 통과해야 함: '.json_encode($validator->errors()->toArray(), JSON_UNESCAPED_UNICODE)
);
}
/**
* UpdateBoardRequest - 첨부 미사용 게시판은 확장자 null 도 통과해야 함 (이슈 #78)
*
* allowed_extensions 컬럼이 NULL 인 레거시 게시판(notice 등) 재현 케이스.
*
* @scenario case=upload_disabled_extensions_null
*
* @effects upload_disabled_empty_extensions_passes
*/
public function test_update_matrix_upload_disabled_with_null_extensions_passes(): void
{
$request = $this->makeUpdateRequest();
$validator = Validator::make([
'use_file_upload' => false,
'allowed_extensions' => null,
], $request->rules());
$this->assertTrue(
$validator->passes(),
'첨부 미사용 게시판의 null 확장자는 통과해야 함: '.json_encode($validator->errors()->toArray(), JSON_UNESCAPED_UNICODE)
);
}
/**
* UpdateBoardRequest - 확장자 키 자체가 없으면 통과 (sometimes 보존)
*
* @scenario case=extensions_key_absent
*
* @effects extensions_key_absent_passes
*/
public function test_update_matrix_absent_extensions_key_passes(): void
{
$request = $this->makeUpdateRequest();
$validator = Validator::make(['use_file_upload' => false], $request->rules());
$this->assertTrue($validator->passes(), '확장자 키 부재 시 통과해야 함');
}
/**
* UpdateBoardRequest - 첨부 미사용 시 확장자는 validated() 에서 제외되어야 함
*
* pass/fail 만 단언하면 exclude_if 를 nullable 로 바꿔도 통과하므로,
* "검증에서 배제된다"는 시맨틱 자체를 고정한다.
*
* @scenario case=upload_disabled_extensions_empty
*
* @effects upload_disabled_extensions_excluded_from_validated
*/
public function test_update_matrix_upload_disabled_excludes_extensions_from_validated(): void
{
$request = $this->makeUpdateRequest();
$validator = Validator::make([
'use_file_upload' => false,
'allowed_extensions' => [],
], $request->rules());
$this->assertTrue($validator->passes());
$this->assertArrayNotHasKey(
'allowed_extensions',
$validator->validated(),
'첨부 미사용 시 allowed_extensions 는 검증 통과 데이터에서 배제되어야 함'
);
}
/**
* UpdateBoardRequest - new_display_hours 경계값 검증
*
* 0 = NEW 배지 표시 안 함 (Post::isNew() 가 0 을 정상 처리).
*
* @dataProvider newDisplayHoursProvider
*
* @scenario case=new_display_hours_zero
*
* @effects new_display_hours_zero_passes, new_display_hours_out_of_range_fails
*
* @param mixed $value new_display_hours 값
* @param bool $shouldPass 통과 기대 여부
*/
public function test_update_matrix_new_display_hours_boundaries(mixed $value, bool $shouldPass): void
{
$request = $this->makeUpdateRequest();
$validator = Validator::make(['new_display_hours' => $value], $request->rules());
$this->assertSame(
$shouldPass,
$validator->passes(),
"new_display_hours={$value} 판정 불일치: ".json_encode($validator->errors()->toArray(), JSON_UNESCAPED_UNICODE)
);
}
/**
* new_display_hours 경계값 데이터.
*
* @return array<string, array{mixed, bool}> 값과 통과 기대 여부
*/
public static function newDisplayHoursProvider(): array
{
return [
'0 (NEW 배지 끄기)' => [0, true],
'1 (최소 표시)' => [1, true],
'720 (최대 경계)' => [720, true],
'-1 (음수)' => [-1, false],
'721 (상한 초과)' => [721, false],
];
}
/**
* StoreBoardRequest - new_display_hours 0 은 통과해야 함
*
* @scenario case=new_display_hours_zero
*
* @effects new_display_hours_zero_passes
*/
public function test_store_request_new_display_hours_zero_passes(): void
{
$request = new StoreBoardRequest;
$data = array_merge($this->getValidStoreBoardData(), ['new_display_hours' => 0]);
$validator = Validator::make($data, $request->rules());
$this->assertTrue(
$validator->passes(),
'new_display_hours=0 은 통과해야 함: '.json_encode($validator->errors()->toArray(), JSON_UNESCAPED_UNICODE)
);
}
/**
* StoreBoardSettingsRequest - 첨부 사용 기본값에서 빈 확장자는 차단
*
* @scenario case=upload_enabled_extensions_empty
*
* @effects upload_enabled_empty_extensions_fails
*/
public function test_settings_matrix_upload_enabled_with_empty_extensions_fails(): void
{
$request = new StoreBoardSettingsRequest;
$validator = Validator::make([
'basic_defaults' => [
'use_file_upload' => true,
'allowed_extensions' => [],
],
], $request->rules());
$this->assertFalse($validator->passes(), '첨부 사용 기본값 + 빈 확장자는 실패해야 함');
$this->assertArrayHasKey('basic_defaults.allowed_extensions', $validator->errors()->toArray());
}
/**
* StoreBoardSettingsRequest - 첨부 사용 기본값에서 확장자 지정은 통과
*
* @scenario case=upload_enabled_extensions_nonempty
*
* @effects upload_enabled_nonempty_extensions_passes
*/
public function test_settings_matrix_upload_enabled_with_extensions_passes(): void
{
$request = new StoreBoardSettingsRequest;
$validator = Validator::make([
'basic_defaults' => [
'use_file_upload' => true,
'allowed_extensions' => ['jpg'],
],
], $request->rules());
$this->assertTrue($validator->passes(), '첨부 사용 기본값 + 확장자 지정은 통과해야 함');
}
/**
* StoreBoardSettingsRequest - 첨부 미사용 기본값은 빈 확장자도 통과해야 함
*
* @scenario case=upload_disabled_extensions_empty
*
* @effects upload_disabled_empty_extensions_passes
*/
public function test_settings_matrix_upload_disabled_with_empty_extensions_passes(): void
{
$request = new StoreBoardSettingsRequest;
$validator = Validator::make([
'basic_defaults' => [
'use_file_upload' => false,
'allowed_extensions' => [],
],
], $request->rules());
$this->assertTrue(
$validator->passes(),
'첨부 미사용 기본값의 빈 확장자는 통과해야 함: '.json_encode($validator->errors()->toArray(), JSON_UNESCAPED_UNICODE)
);
}
/**
* StoreBoardSettingsRequest - use_file_upload 가 null 이어도 빈 확장자는 통과해야 함
*
* prepareForValidation() 의 boolean 캐스팅은 isset() 가드를 쓰므로 null 은
* 캐스팅되지 않고 그대로 통과한다. 이 경로도 배제 대상이어야 한다.
*
* @scenario case=upload_disabled_extensions_null
*
* @effects settings_upload_null_empty_extensions_passes
*/
public function test_settings_matrix_upload_null_with_empty_extensions_passes(): void
{
$request = new StoreBoardSettingsRequest;
$validator = Validator::make([
'basic_defaults' => [
'use_file_upload' => null,
'allowed_extensions' => [],
],
], $request->rules());
$this->assertTrue(
$validator->passes(),
'use_file_upload=null 의 빈 확장자는 통과해야 함: '.json_encode($validator->errors()->toArray(), JSON_UNESCAPED_UNICODE)
);
}
/**
* StoreBoardSettingsRequest - 하한값 0 은 config 계약대로 통과해야 함
*
* config('sirsoft-board.limits') 는 min_title_length_min / min_comment_length_min 을
* 0 으로 선언하고 있으므로 하드코딩된 min:1 은 계약 위반이다.
*
* @dataProvider settingsZeroLowerBoundProvider
*
* @scenario case=zero_lower_bound_length_fields
*
* @effects zero_lower_bound_length_fields_pass
*
* @param string $field basic_defaults 하위 필드명
*/
public function test_settings_matrix_zero_lower_bounds_pass(string $field): void
{
$request = new StoreBoardSettingsRequest;
$validator = Validator::make([
'basic_defaults' => [$field => 0],
], $request->rules());
$this->assertTrue(
$validator->passes(),
"basic_defaults.{$field}=0 은 통과해야 함: ".json_encode($validator->errors()->toArray(), JSON_UNESCAPED_UNICODE)
);
}
/**
* 0 이 허용되어야 하는 basic_defaults 필드 목록.
*
* @return array<string, array{string}> 필드명
*/
public static function settingsZeroLowerBoundProvider(): array
{
return [
'min_title_length' => ['min_title_length'],
'min_comment_length' => ['min_comment_length'],
'new_display_hours' => ['new_display_hours'],
];
}
protected function tearDown(): void
{
\Mockery::close();
@@ -14,6 +14,7 @@ use App\Testing\Concerns\AssertsIdentityPolicyDeclaration;
use Database\Seeders\RolePermissionSeeder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Modules\Sirsoft\Board\Module;
use Modules\Sirsoft\Board\Tests\ModuleTestCase;
/**
@@ -107,7 +108,7 @@ class BoardIdentityPolicyDeclarationTest extends ModuleTestCase
*/
public function test_no_custom_purposes_declared(): void
{
$module = new \Modules\Sirsoft\Board\Module(
$module = new Module(
'sirsoft-board',
$this->getModuleBasePath(),
);
@@ -142,7 +143,7 @@ class BoardIdentityPolicyDeclarationTest extends ModuleTestCase
private function syncBoardIdentityPolicies(): void
{
$helper = app(IdentityPolicySyncHelper::class);
$module = new \Modules\Sirsoft\Board\Module(
$module = new Module(
'sirsoft-board',
$this->getModuleBasePath(),
);
@@ -249,21 +250,29 @@ class BoardIdentityPolicyDeclarationTest extends ModuleTestCase
$this->assertSame($policyKey, $e->policyKey);
}
$this->seedVerifiedLog($admin, 'sensitive_action', Carbon::now());
// "verified 직후" 를 실제 시계에 맡기면 grace=0 정책이 간헐 실패한다.
// grace=0 은 조회 조건이 `verified_at >= now()` 이므로, 시드와 enforce 사이에
// 1초만 흘러도 이력이 만료로 판정된다. 이 구간만 시각을 고정해 "직후" 를 정확히 표현한다.
$verifiedAt = Carbon::now();
Carbon::setTestNow($verifiedAt);
$service->enforce($policy, $admin->fresh(), []);
$this->assertTrue(true, "verified 직후 enforce 통과");
try {
$this->seedVerifiedLog($admin, 'sensitive_action', $verifiedAt);
if ($graceMinutes > 0) {
Carbon::setTestNow(Carbon::now()->addMinutes($graceMinutes + 1));
try {
$service->enforce($policy, $admin->fresh(), []);
$this->fail("정책 '{$policyKey}' grace+1 분 경과 후 throw 해야 함");
} catch (IdentityVerificationRequiredException $e) {
$this->assertSame($policyKey, $e->policyKey);
} finally {
Carbon::setTestNow();
$service->enforce($policy, $admin->fresh(), []);
$this->assertTrue(true, 'verified 직후 enforce 통과');
if ($graceMinutes > 0) {
Carbon::setTestNow($verifiedAt->copy()->addMinutes($graceMinutes + 1));
try {
$service->enforce($policy, $admin->fresh(), []);
$this->fail("정책 '{$policyKey}' grace+1 분 경과 후 throw 해야 함");
} catch (IdentityVerificationRequiredException $e) {
$this->assertSame($policyKey, $e->policyKey);
}
}
} finally {
Carbon::setTestNow();
}
}
@@ -78,7 +78,7 @@ class BoardLanguagePackSeederTriggerTest extends ModuleTestCase
$name = json_decode($row->name, true);
$this->assertEquals('사용자 수정 ko', $name['ko'] ?? null, 'ko 사용자 수정 보존');
$this->assertEquals('基本型', $name['ja'] ?? null, 'ja 자동 동기화 (lang pack seed/board_types.json SSoT)');
$this->assertEquals('基本形', $name['ja'] ?? null, 'ja 자동 동기화 (lang pack seed/board_types.json SSoT)');
}
private function ensureBoardTypesSeeded(): void
@@ -131,6 +131,12 @@ class PostResourcePermissionTest extends BoardTestCase
$userRole->permissions()->syncWithoutDetaching($userPermissions);
$this->regularUser->roles()->attach($userRole->id);
$this->postAuthor->roles()->attach($userRole->id);
// 관리자도 유저 라우트를 열려면 user 타입 권한이 필요하다.
// 유저 게시글 상세는 `permission:user,sirsoft-board.{slug}.posts.read` 로 가드되므로
// admin 타입 권한만으로는 403 이다 (실제 운영에서도 관리자는 두 역할을 함께 보유).
// can_access_admin 게이트는 이 라우트를 통과한 뒤 admin.manage 보유 여부로 판정된다.
$this->adminUser->roles()->attach($userRole->id);
}
// ==========================================
@@ -271,6 +277,7 @@ class PostResourcePermissionTest extends BoardTestCase
* User 상세: admin.manage(Admin 타입) 권한 보유자는 can_access_admin = true
*
* @scenario link=user_board_to_admin, permitted=true
*
* @effects board_admin_gate_true_shows_link
*/
#[Test]
@@ -299,6 +306,7 @@ class PostResourcePermissionTest extends BoardTestCase
* User 상세: 일반 사용자(admin.manage 미보유)는 can_access_admin = false
*
* @scenario link=user_board_to_admin, permitted=false
*
* @effects board_admin_gate_false_hides_link
*/
#[Test]
@@ -635,4 +643,4 @@ class PostResourcePermissionTest extends BoardTestCase
return $postId;
}
}
}
@@ -0,0 +1,189 @@
<?php
namespace Modules\Sirsoft\Board\Tests\Feature\User;
// ModuleTestCase를 수동으로 require (autoload 전에 로드 필요)
require_once __DIR__.'/../../ModuleTestCase.php';
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\UploadedFile;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\Storage;
use Modules\Sirsoft\Board\Http\Requests\UploadAttachmentRequest;
use Modules\Sirsoft\Board\Tests\BoardTestCase;
/**
* 허용 확장자 빈 값 게시판의 업로드 폴백 테스트
*
* allowed_extensions 가 빈 배열([]) 또는 NULL 인 레거시 게시판에서
* `implode(',', [])` 가 `mimes:` 빈 규칙을 만들어 전 파일 업로드가 거부되던 결함의 회귀 테스트.
*
* `??` 는 null 만 잡고 []는 통과시키므로 소비 시점에 `is_array() && !== []` 판정이 필요하다.
*
* @group board
* @group attachment
*/
class AttachmentAllowedExtensionsFallbackTest extends BoardTestCase
{
private User $memberUser;
/**
* 테스트 게시판 슬러그를 반환합니다.
*
* @return string 슬러그
*/
protected function getTestBoardSlug(): string
{
return 'attachment-ext-fallback';
}
/**
* 테스트 게시판 기본 속성을 반환합니다.
*
* @param string $slug 게시판 슬러그
* @return array<string, mixed> 게시판 속성
*/
protected function getDefaultBoardAttributes(string $slug): array
{
return [
'slug' => $slug,
'name' => ['ko' => '확장자 폴백 테스트 게시판', 'en' => 'Extension Fallback Test Board'],
'is_active' => true,
'use_file_upload' => true,
'allowed_extensions' => [],
];
}
/**
* 테스트 환경을 준비합니다.
*/
protected function setUp(): void
{
parent::setUp();
Storage::fake('public');
$this->grantUserRolePermissions(['posts.read', 'posts.write', 'attachments.upload']);
$this->memberUser = User::factory()->create(['email' => 'ext-fallback-member@test.com']);
$userRole = Role::where('identifier', 'user')->first();
if ($userRole) {
$this->memberUser->roles()->attach($userRole->id);
}
}
/**
* UploadAttachmentRequest 를 대상 게시판 슬러그로 생성합니다.
*
* @param string $slug 게시판 슬러그
* @return UploadAttachmentRequest 라우트 슬러그가 주입된 요청 객체
*/
private function makeUploadRequest(string $slug): UploadAttachmentRequest
{
$request = new UploadAttachmentRequest;
$request->setRouteResolver(function () use ($slug) {
$route = \Mockery::mock(Route::class);
$route->shouldReceive('parameter')->with('slug', null)->andReturn($slug);
return $route;
});
return $request;
}
/**
* file 규칙에서 mimes 파라미터를 추출합니다.
*
* @param array<string, mixed> $rules 검증 규칙
* @return string|null mimes 확장자 목록 (규칙 부재 시 null)
*/
private function extractMimes(array $rules): ?string
{
foreach ($rules['file'] ?? [] as $rule) {
if (is_string($rule) && str_starts_with($rule, 'mimes:')) {
return substr($rule, strlen('mimes:'));
}
}
return null;
}
/**
* allowed_extensions 가 빈 배열이면 mimes 규칙이 비어있지 않아야 한다 (회귀)
*/
public function test_empty_allowed_extensions_does_not_produce_empty_mimes_rule(): void
{
$rules = $this->makeUploadRequest($this->board->slug)->rules();
$mimes = $this->extractMimes($rules);
$this->assertNotSame('', $mimes, 'allowed_extensions=[] 에서 mimes: 빈 규칙이 생성되면 전 파일이 거부된다');
$this->assertNotEmpty($mimes, 'mimes 규칙은 기본 확장자 목록으로 폴백되어야 함');
}
/**
* allowed_extensions 가 NULL 이어도 mimes 규칙이 비어있지 않아야 한다
*/
public function test_null_allowed_extensions_does_not_produce_empty_mimes_rule(): void
{
$this->updateBoardSettings(['allowed_extensions' => null]);
$rules = $this->makeUploadRequest($this->board->slug)->rules();
$this->assertNotEmpty($this->extractMimes($rules), 'allowed_extensions=null 도 기본 확장자로 폴백되어야 함');
}
/**
* allowed_extensions 가 빈 배열인 게시판에서도 실제 업로드가 성공해야 한다 (회귀)
*
* @scenario case=upload_enabled_extensions_empty
*
* @effects empty_extensions_upload_falls_back_to_defaults
*/
public function test_upload_succeeds_when_allowed_extensions_is_empty(): void
{
$file = UploadedFile::fake()->create('document.pdf', 100, 'application/pdf');
$response = $this->actingAs($this->memberUser)
->postJson("/api/modules/sirsoft-board/boards/{$this->board->slug}/attachments", [
'file' => $file,
]);
$response->assertStatus(201)->assertJsonPath('success', true);
}
/**
* 허용 확장자가 지정된 게시판은 목록 밖 확장자를 계속 거부해야 한다 (회귀 방지)
*
* 폴백이 검증 자체를 무력화하지 않는지 확인한다.
*
* @scenario case=upload_enabled_extensions_nonempty
*
* @effects specified_extensions_still_reject_other_types
*/
public function test_specified_allowed_extensions_still_reject_other_types(): void
{
$this->updateBoardSettings(['allowed_extensions' => ['jpg', 'png']]);
$file = UploadedFile::fake()->create('document.pdf', 100, 'application/pdf');
$response = $this->actingAs($this->memberUser)
->postJson("/api/modules/sirsoft-board/boards/{$this->board->slug}/attachments", [
'file' => $file,
]);
$response->assertStatus(422);
}
/**
* 테스트 정리
*/
protected function tearDown(): void
{
\Mockery::close();
parent::tearDown();
}
}
@@ -6,9 +6,14 @@
* 브라우저 수준(빈 채 저장 시 오류 노출 / 첨부 미사용 게시판은 빈 값 허용 / 안내 문구 갱신 노출)은
* 이 spec 이 담당한다.
*
* 정책 정정 (#78): "빈 값 금지" 는 첨부를 **사용하는** 게시판/기본값에만 적용된다.
* 첨부 미사용이면 확장자는 검증 자체에서 배제된다 — 그러지 않으면 첨부를 쓰지 않는
* 게시판을 무변경 저장하는 것조차 422 로 막힌다.
*
* @scenario board-allowed-extensions-required
* @axes surface=settings_attachment surface=board_form use_file_upload=true use_file_upload=false value=empty value=nonempty
* @effects empty_extensions_blocked_on_settings_save,
* @effects empty_extensions_blocked_on_settings_save_when_upload_enabled,
* empty_extensions_allowed_on_settings_save_when_upload_disabled,
* empty_extensions_blocked_on_board_form_when_upload_enabled,
* empty_extensions_allowed_on_board_form_when_upload_disabled,
* allowed_extensions_guide_text_updated_to_min_one
@@ -20,10 +25,25 @@ import { test, expect, authenticatePage } from '../../fixtures/board-auth';
const SETTINGS_URL = '/admin/boards/settings';
const CREATE_URL = '/admin/boards/create';
test.describe.skip('게시판 허용 확장자 빈 값 저장 차단 (#413)', () => {
// @scenario surface=settings_attachment, value=empty
// @effects empty_extensions_blocked_on_settings_save
test('환경설정 첨부 탭에서 허용 확장자를 비우고 저장하면 오류가 노출된다', async ({
const EXTENSION_REQUIRED_TEXT = /허용 파일 확장자를 최소 1개|At least one allowed file extension/;
/**
* 첨부 탭의 허용 확장자 칩을 모두 제거합니다.
*/
async function clearAllowedExtensionChips(page: import('@playwright/test').Page): Promise<void> {
const removeChipButtons = page.locator(
'[name="basic_defaults.allowed_extensions"] [data-chip-remove], [data-field="allowed_extensions"] button[aria-label*="제거"], [data-field="allowed_extensions"] button[aria-label*="remove"]'
);
const count = await removeChipButtons.count();
for (let i = 0; i < count; i++) {
await removeChipButtons.first().click();
}
}
test.describe.skip('게시판 허용 확장자 빈 값 저장 차단 (#413, #78)', () => {
// @scenario surface=settings_attachment, use_file_upload=true, value=empty
// @effects empty_extensions_blocked_on_settings_save_when_upload_enabled
test('환경설정에서 첨부 사용 ON + 허용 확장자를 비우고 저장하면 오류가 노출된다', async ({
page,
boardManageToken,
}) => {
@@ -34,18 +54,41 @@ test.describe.skip('게시판 허용 확장자 빈 값 저장 차단 (#413)', ()
// 기본 설정 → 첨부파일 하위 탭으로 이동
await page.getByRole('tab', { name: /첨부|Attachment/ }).click();
// 허용 확장자 칩을 모두 비운다 (TagInput 의 기존 칩 제거 버튼 반복 클릭)
const removeChipButtons = page.locator('[name="basic_defaults.allowed_extensions"] [data-chip-remove], [data-field="allowed_extensions"] button[aria-label*="제거"], [data-field="allowed_extensions"] button[aria-label*="remove"]');
const count = await removeChipButtons.count();
for (let i = 0; i < count; i++) {
await removeChipButtons.first().click();
// 첨부 사용을 켜 둔 상태에서 확장자를 모두 비운다
const uploadToggle = page.locator('[name="basic_defaults.use_file_upload"]');
if (!(await uploadToggle.isChecked())) {
await uploadToggle.click();
}
await clearAllowedExtensionChips(page);
// 저장 → min:1 검증 실패 안내 노출
await page.locator('button[type="submit"]').first().click();
await expect(
page.getByText(/허용 파일 확장자를 최소 1개|At least one allowed file extension/)
).toBeVisible({ timeout: 10_000 });
await expect(page.getByText(EXTENSION_REQUIRED_TEXT)).toBeVisible({ timeout: 10_000 });
});
// @scenario surface=settings_attachment, use_file_upload=false, value=empty
// @effects empty_extensions_allowed_on_settings_save_when_upload_disabled
test('환경설정에서 첨부 미사용이면 허용 확장자를 비워도 저장된다 (#78)', async ({
page,
boardManageToken,
}) => {
await authenticatePage(page, boardManageToken);
await page.goto(SETTINGS_URL);
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
await page.getByRole('tab', { name: /첨부|Attachment/ }).click();
// 첨부 사용을 끈 뒤 확장자를 모두 비운다
const uploadToggle = page.locator('[name="basic_defaults.use_file_upload"]');
if (await uploadToggle.isChecked()) {
await uploadToggle.click();
}
await clearAllowedExtensionChips(page);
await page.locator('button[type="submit"]').first().click();
await page.waitForLoadState('networkidle', { timeout: 30_000 });
await expect(page.getByText(EXTENSION_REQUIRED_TEXT)).toHaveCount(0, { timeout: 10_000 });
});
// @scenario surface=board_form, use_file_upload=true, value=empty
@@ -66,9 +109,7 @@ test.describe.skip('게시판 허용 확장자 빈 값 저장 차단 (#413)', ()
await page.locator('[name="use_file_upload"]').click();
await page.locator('button[type="submit"]').first().click();
await expect(
page.getByText(/허용 파일 확장자를 최소 1개|At least one allowed file extension/)
).toBeVisible({ timeout: 10_000 });
await expect(page.getByText(EXTENSION_REQUIRED_TEXT)).toBeVisible({ timeout: 10_000 });
});
// @scenario surface=board_form, use_file_upload=false, value=empty
@@ -89,9 +130,7 @@ test.describe.skip('게시판 허용 확장자 빈 값 저장 차단 (#413)', ()
await page.waitForLoadState('networkidle', { timeout: 30_000 });
// 허용 확장자 검증 오류가 노출되지 않아야 한다
await expect(
page.getByText(/허용 파일 확장자를 최소 1개|At least one allowed file extension/)
).toHaveCount(0, { timeout: 10_000 });
await expect(page.getByText(EXTENSION_REQUIRED_TEXT)).toHaveCount(0, { timeout: 10_000 });
});
// @scenario surface=board_form, value=nonempty
@@ -0,0 +1,120 @@
/**
* 게시판 무변경 저장 + 저장 실패 노출 (#78).
*
* 관리자 폼은 조회 응답 전체를 _local.form 에 통째로 담아 그대로 PUT 한다. 따라서 요청에는
* 항상 모든 키가 존재하고, 토글이 꺼진 상태의 종속 필드까지 검증을 타면 아무것도 바꾸지 않은
* 저장조차 422 로 거부된다. 첨부를 쓰지 않는 게시판(notice/archive)이 여기에 해당했다.
*
* 백엔드 계약은 PHPUnit(BoardRequestTest 매트릭스, BoardManagementTest 왕복 저장)이 고정하고,
* 브라우저 수준의 "무변경 저장 성공" 과 "실패 시 실제로 화면에 보이는가" 를 이 spec 이 담당한다.
* 후자는 오류 처리가 붙어 있어도 바인딩 키가 틀리면 빈 안내가 뜨므로 별도 축이 필요하다.
*
* @scenario board-unchanged-save-and-error-visibility
* @axes use_file_upload=false use_file_upload=true allowed_extensions=empty allowed_extensions=nonempty new_display_hours=0 outcome=success outcome=failure
* @effects unchanged_save_succeeds_for_upload_disabled_board,
* unchanged_save_succeeds_for_zero_new_display_hours,
* unchanged_save_succeeds_for_upload_enabled_board,
* save_failure_surfaces_toast_with_server_message
*
* 활성화 절차: PlaywrightIssueToken 발급이 가능한 환경에서 test.describe.skip → test.describe.
*/
import { test, expect, authenticatePage } from '../../fixtures/board-auth';
const EDIT_URL = (slug: string) => `/admin/boards/${slug}/edit`;
const EXTENSION_REQUIRED_TEXT = /허용 파일 확장자를 최소 1개|At least one allowed file extension/;
/**
* 게시판 수정 화면을 열고 폼 로딩을 기다립니다.
*/
async function openBoardEdit(page: import('@playwright/test').Page, slug: string): Promise<void> {
await page.goto(EDIT_URL(slug));
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
await expect(page.locator('button[type="submit"]').first()).toBeVisible({ timeout: 30_000 });
}
/**
* 아무것도 바꾸지 않고 저장하고, 저장 요청의 응답 상태를 반환합니다.
*/
async function saveUnchanged(page: import('@playwright/test').Page): Promise<number> {
const [response] = await Promise.all([
page.waitForResponse(
(r) => r.request().method() === 'PUT' && r.url().includes('/admin/boards/'),
{ timeout: 30_000 }
),
page.locator('button[type="submit"]').first().click(),
]);
return response.status();
}
test.describe.skip('게시판 무변경 저장 및 저장 실패 노출 (#78)', () => {
// @scenario use_file_upload=false, allowed_extensions=empty, outcome=success
// @effects unchanged_save_succeeds_for_upload_disabled_board
test('첨부 미사용 게시판(notice)을 아무것도 바꾸지 않고 저장하면 성공한다', async ({
page,
boardManageToken,
}) => {
await authenticatePage(page, boardManageToken);
await openBoardEdit(page, 'notice');
expect(await saveUnchanged(page)).toBe(200);
await expect(page.getByText(EXTENSION_REQUIRED_TEXT)).toHaveCount(0);
});
// @scenario use_file_upload=false, new_display_hours=0, outcome=success
// @effects unchanged_save_succeeds_for_zero_new_display_hours
test('NEW 배지 표시 기간이 0인 게시판(archive)을 무변경 저장하면 성공한다', async ({
page,
boardManageToken,
}) => {
await authenticatePage(page, boardManageToken);
await openBoardEdit(page, 'archive');
expect(await saveUnchanged(page)).toBe(200);
});
// @scenario use_file_upload=true, allowed_extensions=nonempty, outcome=success
// @effects unchanged_save_succeeds_for_upload_enabled_board
test('첨부 사용 게시판(gallery)의 무변경 저장은 회귀 없이 계속 성공한다', async ({
page,
boardManageToken,
}) => {
await authenticatePage(page, boardManageToken);
await openBoardEdit(page, 'gallery');
expect(await saveUnchanged(page)).toBe(200);
});
// @scenario use_file_upload=true, allowed_extensions=empty, outcome=failure
// @effects save_failure_surfaces_toast_with_server_message
test('저장이 422로 거부되면 서버 메시지가 담긴 안내가 실제로 화면에 노출된다', async ({
page,
boardManageToken,
}) => {
await authenticatePage(page, boardManageToken);
await openBoardEdit(page, 'gallery');
// 첨부 사용은 켠 채로 확장자를 모두 비워 의도적으로 422 를 유발한다
await page.getByRole('tab', { name: /게시글 설정|Post Settings/ }).click();
const removeChipButtons = page.locator(
'[data-field="allowed_extensions"] button[aria-label*="제거"], [data-field="allowed_extensions"] button[aria-label*="remove"]'
);
const count = await removeChipButtons.count();
for (let i = 0; i < count; i++) {
await removeChipButtons.first().click();
}
const [response] = await Promise.all([
page.waitForResponse(
(r) => r.request().method() === 'PUT' && r.url().includes('/admin/boards/'),
{ timeout: 30_000 }
),
page.locator('button[type="submit"]').first().click(),
]);
expect(response.status()).toBe(422);
// 안내가 비어 있지 않아야 한다 — 오류 처리가 붙어 있어도 바인딩 키가 틀리면 빈 값이 노출된다
await expect(page.getByText(EXTENSION_REQUIRED_TEXT).first()).toBeVisible({ timeout: 10_000 });
});
});
@@ -0,0 +1,95 @@
/**
* 허용 확장자 미지정 게시판의 첨부 선택 (#78 R3).
*
* 백엔드는 Phase 2 #7 로 이미 고쳐졌지만(빈 확장자 → 기본 확장자 폴백), 프런트에 동일한
* `[]`-truthiness 쌍둥이가 남아 있어 사용자는 **파일 선택 단계에서** 막혔다. 요청 자체가
* 발생하지 않으므로 서버측 회귀 테스트로는 잡히지 않는다.
*
* 연쇄: DB `NULL` → API 가 `allowed_extensions: []` 로 직렬화(BoardResource 계약) →
* 레이아웃 `ext ? '.' + ext.join(',.') : fallback` 에서 `[]` 가 truthy → `accept="."` →
* `useFileUploader` 확장자 게이트가 전 파일 거부 + 안내문이 `(.)` 로 깨짐.
*
* 브라우저 실측 대조군(2026-07-22): `free`(ext=NULL) accept=`"."` → 첨부 차단 /
* `gallery`(ext 5개) accept=`".jpg,..."` → 정상. 서버측 curl 은 `free`+`.txt` 201 로 정상이었다.
*
* @scenario board-empty-extensions-attachment
* @axes allowed_extensions=empty allowed_extensions=specified surface=user_write surface=admin_write
* @effects empty_extensions_accept_falls_back_to_defaults,
* empty_extensions_file_selection_succeeds,
* specified_extensions_accept_reflects_list
*
* 활성화 절차: PlaywrightIssueToken 발급이 가능한 환경에서 test.describe.skip → test.describe.
*/
import { test, expect, authenticatePage } from '../../fixtures/board-auth';
const DEFAULT_ACCEPT = '.jpg,.jpeg,.png,.gif,.pdf,.zip';
/**
* 글쓰기 화면의 파일 입력에서 accept 속성을 읽습니다.
*/
async function readAcceptAttribute(page: import('@playwright/test').Page): Promise<string | null> {
return page.evaluate(() => {
const input = document.querySelector<HTMLInputElement>('input[type="file"]');
return input ? input.getAttribute('accept') : null;
});
}
test.describe.skip('허용 확장자 미지정 게시판의 첨부 (#78 R3)', () => {
// @scenario allowed_extensions=empty, surface=user_write
// @effects empty_extensions_accept_falls_back_to_defaults
test('확장자 미지정 게시판의 사용자 글쓰기 accept 는 기본 확장자로 폴백된다', async ({
page,
boardManageToken,
}) => {
await authenticatePage(page, boardManageToken);
await page.goto('/board/free/write');
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
const accept = await readAcceptAttribute(page);
expect(accept).not.toBe('.');
expect(accept).toBe(DEFAULT_ACCEPT);
});
// @scenario allowed_extensions=empty, surface=user_write
// @effects empty_extensions_file_selection_succeeds
test('확장자 미지정 게시판에서 파일을 선택하면 거부되지 않는다', async ({
page,
boardManageToken,
}) => {
await authenticatePage(page, boardManageToken);
await page.goto('/board/free/write');
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
await page.setInputFiles('input[type="file"]', {
name: 'probe.png',
mimeType: 'image/png',
buffer: Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
'base64'
),
});
// 확장자 게이트에 걸리면 "허용되지 않는 파일 형식입니다. (허용: .)" 가 노출된다
await expect(page.getByText(/허용되지 않는 파일 형식/)).toHaveCount(0, { timeout: 10_000 });
await expect(page.getByText(/1\s*\/\s*\d+개 첨부됨|첨부됨/)).toBeVisible({ timeout: 10_000 });
});
// @scenario allowed_extensions=specified, surface=user_write
// @effects specified_extensions_accept_reflects_list
test('확장자를 지정한 게시판은 accept 에 그 목록이 반영된다 (회귀 방지)', async ({
page,
boardManageToken,
}) => {
await authenticatePage(page, boardManageToken);
await page.goto('/board/gallery/write');
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
const accept = await readAcceptAttribute(page);
expect(accept).toContain('.jpg');
expect(accept).not.toBe('.');
expect(accept).not.toBe(DEFAULT_ACCEPT);
});
});
@@ -20,6 +20,13 @@ use Modules\Sirsoft\Board\Tests\ModuleTestCase;
*/
class NotificationLogSeederTest extends ModuleTestCase
{
/**
* 이 테스트가 커밋한 사용자 ID (tearDown 에서 정리)
*
* @var array<int, int>
*/
private array $seededUserIds = [];
private function bootstrap(): void
{
// 테스트 격리: 다른 테스트 클래스가 트랜잭션 외부에서 남긴 잔여 데이터 정리.
@@ -31,10 +38,19 @@ class NotificationLogSeederTest extends ModuleTestCase
$this->syncBoardNotificationDefinitions();
$userRole = Role::query()->where('identifier', 'user')->firstOrFail();
User::factory()
// 이메일은 팩토리 기본값(fake()->unique()->safeEmail()) 대신 결정적 고유값을 쓴다.
// faker 의 unique() 는 생성기 수명 안에서만 유일하고 safeEmail() 의 도메인 풀이 좁아,
// 트랜잭션 없이 커밋된 사용자가 누적되면 g7_users.email 유니크 충돌이 난다.
$suffix = uniqid('', true);
$users = User::factory()
->count(15)
->create()
->each(fn (User $u) => $u->roles()->attach($userRole->id, ['assigned_at' => now()]));
->sequence(fn ($sequence) => ['email' => "board-notilog-{$sequence->index}-{$suffix}@example.test"])
->create();
$this->seededUserIds = array_merge($this->seededUserIds, $users->pluck('id')->all());
$users->each(fn (User $u) => $u->roles()->attach($userRole->id, ['assigned_at' => now()]));
}
public function test_seeder_creates_default_count(): void
@@ -95,4 +111,30 @@ class NotificationLogSeederTest extends ModuleTestCase
}
}
}
/**
* 테스트 정리
*
* 이 클래스는 트랜잭션 롤백 없이(ModuleTestCase 기본) 시더로 알림 로그를 커밋한다.
* 정리하지 않으면 이후 실행되는 다른 테스트 클래스가 이 잔여 행을 함께 세어
* 건수 단언이 깨진다 (예: NotificationLogServiceTest 의 채널 필터 건수).
*
* 알림 정의(NotificationDefinition)는 지우지 않는다 — 트랜잭션을 쓰지 않는 다른 테스트
* 클래스들이 시드된 정의를 공유 전제로 삼고 있어, 함께 지우면 그쪽이 깨진다.
*
* bootstrap() 이 만든 사용자도 같은 이유로 커밋되어 남으므로 함께 정리한다. 정리하지
* 않으면 스위트를 돌릴수록 g7_users 가 누적되어 다른 테스트의 사용자 건수 단언과
* 이메일 유니크 제약을 함께 무너뜨린다.
*/
protected function tearDown(): void
{
NotificationLog::query()->delete();
if ($this->seededUserIds !== []) {
User::query()->whereIn('id', $this->seededUserIds)->delete();
$this->seededUserIds = [];
}
parent::tearDown();
}
}
@@ -8,6 +8,7 @@ use App\Seo\AbstractSitemapContributor;
use App\Seo\Contracts\SitemapContributorInterface;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Seo\BoardSitemapContributor;
use Modules\Sirsoft\Board\Tests\BoardTestCase;
@@ -74,7 +75,11 @@ class BoardSitemapContributorTest extends BoardTestCase
*/
public function test_get_urls_returns_only_static_url_when_no_active_boards(): void
{
$this->updateBoardSettings(['is_active' => false]);
// "활성 게시판이 0개" 전제를 이 테스트가 직접 만든다.
// 자기 게시판만 비활성화하면, 트랜잭션을 쓰지 않는 다른 테스트 클래스가 남긴
// 게시판이 활성 상태로 남아 있어 전제가 성립하지 않는다.
Board::query()->update(['is_active' => false]);
$this->board->refresh();
$urls = $this->contributor->getUrls();
@@ -0,0 +1,68 @@
feature: 게시판 조건부 검증 — 토글 OFF 상태의 종속 필드 배제
description: |
이슈 #78 — 첨부를 사용하지 않는 게시판(notice/archive)을 아무것도 바꾸지 않고 저장하면
422 로 거부되던 문제를 해소한다.
근본 원인: 관리자 폼이 조회 응답 전체를 _local.form 에 통째로 담아 그대로 PUT 한다
(admin_board_form.json: initLocal="form" → body="{{_local.form}}"). 요청에는 항상 모든 키가
존재하므로 `sometimes` 는 아무 보호도 하지 못하고, 첨부 미사용 게시판의 빈 allowed_extensions
까지 min:1 검증을 타서 저장이 막혔다. 작성자들이 `sometimes` 를 "부분 수정 지원"으로 오해했고
그 오해가 담긴 주석까지 파일 간에 복제되어 있었다.
조치:
- allowed_extensions 를 exclude_if 로 배제 (Update / Settings 양쪽)
· Settings 는 use_file_upload=null 조건도 필요 — prepareForValidation 의 boolean 캐스팅이
isset() 가드를 써서 null 이 false 로 캐스팅되지 않고 통과한다
- new_display_hours 하한을 config 선언(0 = NEW 배지 끄기)에 맞춰 완화
· Post::isNew() 는 created_at > now()->subHours(0) → 항상 false 로 이미 0 을 정상 처리
- min_title_length / min_comment_length 하한을 config 선언(0)에 맞춰 정정
- 허용 확장자 소비 지점(첨부 업로드 / 게시글 작성)에서 빈 배열도 기본값으로 폴백
· `?? 기본값` 은 null 만 잡고 [] 를 통과시켜 implode(',', []) → 'mimes:' 빈 규칙 →
해당 게시판 전 파일 거부. 레거시 데이터가 있으므로 소비 시점 방어가 필수
- 저장 시점에 빈 배열을 NULL 로 정규화해 "미지정" 센티널을 하나로 붕괴 (AsAllowedExtensions)
재발 방지: audit 룰 formrequest-store-update-conditional-symmetry(error) /
formrequest-sometimes-array-min-inert(warning) 가 같은 실수를 자동 차단한다.
# axis 의미:
# case 는 (첨부 사용 여부 + 확장자 값 + 저장 결과) 의 의미 있는 조합을 한 축으로 열거한다.
# 전체 객체 PUT 계약이 전제이므로 "키 부재" 도 별도 케이스로 둔다.
axes:
case: [upload_disabled_extensions_empty, upload_disabled_extensions_null, upload_enabled_extensions_empty, upload_enabled_extensions_nonempty, extensions_key_absent, new_display_hours_zero, zero_lower_bound_length_fields]
effects:
- upload_disabled_empty_extensions_passes
- upload_disabled_extensions_excluded_from_validated
- upload_enabled_empty_extensions_fails
- upload_enabled_nonempty_extensions_passes
- extensions_key_absent_passes
- settings_upload_null_empty_extensions_passes
- new_display_hours_zero_passes
- new_display_hours_out_of_range_fails
- zero_lower_bound_length_fields_pass
- unchanged_form_data_round_trip_saves
- empty_extensions_upload_falls_back_to_defaults
- specified_extensions_still_reject_other_types
test_files:
- modules/_bundled/sirsoft-board/tests/Feature/BoardRequestTest.php
- modules/_bundled/sirsoft-board/tests/Feature/Admin/BoardManagementTest.php
- modules/_bundled/sirsoft-board/tests/Feature/User/AttachmentAllowedExtensionsFallbackTest.php
validation:
note: |
입력 조합 전수는 BoardRequestTest 의 조건부 검증 매트릭스가 커버한다 (Update 7 케이스 +
Settings 5 케이스 + new_display_hours 경계 5값).
"전체 객체 PUT" 이라는 프런트 계약 자체는 BoardManagementTest 의 왕복 저장 테스트가
백엔드에 고정한다 — 폼 데이터를 GET 해서 받은 객체를 그대로 PUT 해 200 을 단언하므로
미래의 동종 결함(다른 토글-종속 필드 쌍)까지 방어된다.
레거시 데이터(allowed_extensions 가 [] 또는 NULL 인 게시판)의 실제 업로드 성공과,
확장자를 지정한 게시판이 목록 밖 확장자를 계속 거부하는지는
AttachmentAllowedExtensionsFallbackTest 가 커버한다.
브라우저 수준의 무변경 저장 성공 / 422 시 안내 실제 노출은
tests/Playwright/specs/admin/board-unchanged-save-and-error-visibility.spec.ts 가 담당한다
(PlaywrightIssueToken 발급 가능 환경에서 describe.skip 해제).
@@ -19,6 +19,16 @@
### Fixed
- 상품을 장바구니에 담거나 바로 구매할 때, 표시 언어(로케일)나 관리자의 옵션 이름 수정과 무관하게 선택한 옵션이 정확히 담기도록 개선했습니다. 특정 상황에서 "해당 옵션 조합을 찾을 수 없습니다" 오류로 담기가 실패하던 문제가 해소됩니다.
- 오류 안내가 뜨기는 하지만 내용이 비어 있던 문제를 수정했습니다. 서버가 알려 준 실패 사유가 그대로 표시됩니다.
- 헤더에서 통화나 배송 국가를 바꿀 때 저장에 실패해도 아무 안내 없이 넘어가던 문제를 수정했습니다. 실패하면 그 이유가 화면에 표시됩니다.
- 일부 안내 문구가 실제 문장 대신 내부 식별자로 표시되던 문제를 수정했습니다. 리뷰 작성·답글·일괄처리, 장바구니 선택 항목 처리, 주문서 쿠폰 적용, 클레임 사유 관리, 주문 목록의 배송비 검색 조건, 택배사·상품 공통정보 관리, 결제 대기 주문 취소가 해당됩니다.
- 관리자 주문 메모 안내가 실제 입력 한도(2,000자)와 다르게 "최대 1000자"로 표시되던 문제를 수정했습니다.
- 쇼핑몰 환경설정 저장·조회, 카테고리 이미지 등록·삭제·순서 변경, 브랜드·상품 카테고리 전시 상태 변경, 검색 프리셋 조회, 결제 설정 조회 화면에서 결과 안내가 실제 문장 대신 내부 식별자로 표시되던 문제를 수정했습니다.
- 화면과 문서에 "클래임"으로 잘못 적혀 있던 용어를 "클레임"으로 바로잡았습니다.
- 클레임 사유 목록 조회 시 유형·귀책 구분·사용여부·검색어에 잘못된 값을 넣어도 그대로 조회되던 것을 검증하도록 바꿨습니다. 잘못된 값은 이제 안내와 함께 거절됩니다.
- 검색 프리셋의 대상 화면 이름(상품 목록·주문 목록·고객 목록)이 표시되지 않던 문제를 수정했습니다.
- 상품 문의 답변 상태와 배송정책이 없는 배송 그룹의 표시명이 비어 보이던 문제를 수정했습니다.
- 상품 옵션 설정, 주문·배송정책·쿠폰·브랜드·카테고리 관리 화면의 아이콘이 의도한 크기보다 크거나 작게 보이던 문제와, 다크 모드에서 일부 버튼의 색 대비가 낮던 문제를 수정했습니다.
## [1.0.4] - 2026-07-16
@@ -701,12 +711,12 @@
### Added
- 클래임 사유 관리 시스템 — DB 기반 환불 사유 관리 (ClaimReason 모델, Repository, Service, Controller, FormRequest, Resource)
- 클레임 사유 관리 시스템 — DB 기반 환불 사유 관리 (ClaimReason 모델, Repository, Service, Controller, FormRequest, Resource)
- `ecommerce_claim_reasons` 테이블: type, code, name(다국어), fault_type, is_user_selectable, is_active, sort_order
- Admin API 7개: 목록/생성/상세/수정/삭제/상태토글/활성목록 (`/admin/claim-reasons`)
- User API 1개: 사용자 선택 가능 사유 목록 (`/user/claim-reasons`)
- ClaimReasonFaultTypeEnum (customer/seller/carrier), ClaimReasonTypeEnum (refund)
- 쇼핑몰 환경설정 > 클래임 탭 — 환불 사유 인라인 편집 UI (배송사 관리 패턴)
- 쇼핑몰 환경설정 > 클레임 탭 — 환불 사유 인라인 편집 UI (배송사 관리 패턴)
- 테이블 뷰(PC) + 카드 뷰(모바일) 반응형 레이아웃
- EcommerceSettingsController에 syncReasons() 연동
- 업그레이드 스크립트 (Upgrade_0_14_0) — 기존 CancelReasonTypeEnum 7개 값을 DB 시드 데이터로 마이그레이션
@@ -17,8 +17,6 @@ class ProductFactory extends Factory
/**
* 기본 정의
*
* @return array
*/
public function definition(): array
{
@@ -30,7 +28,10 @@ class ProductFactory extends Factory
'ko' => $this->faker->words(3, true),
'en' => $this->faker->words(3, true),
],
'product_code' => strtoupper($this->faker->bothify('PROD-????-####')),
// 운영 product_code 는 SequenceService(NANOID, 16자, 0-9A-Z) 산출물이라 하이픈이 없다.
// 하이픈이 섞이면 공개 상세 라우트의 `->where('product', '[0-9A-Za-z]+')` 제약에
// 걸려 404 가 되므로, 팩토리도 동일한 문자 집합·길이를 따른다.
'product_code' => strtoupper($this->faker->regexify('[0-9A-Z]{16}')),
'sku' => strtoupper($this->faker->bothify('SKU-????-####')),
'brand_id' => null,
'list_price' => $listPrice,
@@ -58,8 +59,6 @@ class ProductFactory extends Factory
/**
* 옵션 있는 상품 (다국어 지원)
*
* @return static
*/
public function withOptions(): static
{
@@ -88,8 +87,6 @@ class ProductFactory extends Factory
/**
* 판매중 상태
*
* @return static
*/
public function onSale(): static
{
@@ -101,8 +98,6 @@ class ProductFactory extends Factory
/**
* 품절 상태
*
* @return static
*/
public function soldOut(): static
{
@@ -114,8 +109,6 @@ class ProductFactory extends Factory
/**
* 판매 중지 상태
*
* @return static
*/
public function suspended(): static
{
@@ -126,8 +119,6 @@ class ProductFactory extends Factory
/**
* 출시예정 상태
*
* @return static
*/
public function comingSoon(): static
{
@@ -138,8 +129,6 @@ class ProductFactory extends Factory
/**
* 숨김 상태
*
* @return static
*/
public function hidden(): static
{
@@ -150,8 +139,6 @@ class ProductFactory extends Factory
/**
* 면세 상품
*
* @return static
*/
public function taxFree(): static
{
@@ -13,7 +13,7 @@ return new class extends Migration
public function up(): void
{
Schema::create('ecommerce_claim_reasons', function (Blueprint $table) {
$table->id()->comment('클래임 사유 ID');
$table->id()->comment('클레임 사유 ID');
$table->string('type', 20)->comment('사유 유형 (refund, exchange, return 등)');
$table->string('code', 50)->comment('고유 코드 (order_mistake 등)');
$table->text('name')->comment('다국어 사유명 {"ko":"주문 실수","en":"Order Mistake"}');
@@ -32,7 +32,7 @@ return new class extends Migration
});
if (DB::getDriverName() === 'mysql') {
DB::statement("ALTER TABLE `".DB::getTablePrefix()."ecommerce_claim_reasons` COMMENT '클래임 사유 템플릿'");
DB::statement('ALTER TABLE `'.DB::getTablePrefix()."ecommerce_claim_reasons` COMMENT '클레임 사유 템플릿'");
}
}
@@ -8,10 +8,9 @@ use App\Models\Module;
use App\Models\Permission;
use App\Models\Role;
use Illuminate\Database\Seeder;
use Modules\Sirsoft\Ecommerce\Enums\SequenceAlgorithm;
use Modules\Sirsoft\Ecommerce\Enums\SequenceType;
use Modules\Sirsoft\Ecommerce\Models\Sequence;
use Modules\Sirsoft\Ecommerce\Models\ClaimReason;
use Modules\Sirsoft\Ecommerce\Models\Sequence;
use Modules\Sirsoft\Ecommerce\Models\ShippingCarrier;
/**
@@ -73,7 +72,7 @@ class TestingSeeder extends Seeder
// 배송사 초기 데이터 생성
$this->createShippingCarriers();
// 클래임 사유 초기 데이터 생성
// 클레임 사유 초기 데이터 생성
$this->createClaimReasons();
}
@@ -127,7 +126,7 @@ class TestingSeeder extends Seeder
}
/**
* 클래임 사유 초기 데이터를 생성합니다.
* 클레임 사유 초기 데이터를 생성합니다.
*/
private function createClaimReasons(): void
{
@@ -44,7 +44,7 @@ _목록 응답: `data.data[]` 배열 항목의 필드._
| --- | --- | --- | --- |
| number | integer | `8` | 목록에서의 순번 (페이지네이션 반영 행 번호 — HasRowNumber 파생) |
| id | integer | `1` | 기본 키 (내부 식별자) |
| type | string | `refund` | 클래임 사유 유형 (ClaimReasonTypeEnum — `refund`(환불/취소)) |
| type | string | `refund` | 클레임 사유 유형 (ClaimReasonTypeEnum — `refund`(환불/취소)) |
| code | string | `order_mistake` | 사유 식별 코드 (같은 type 내 고유, 영문 소문자/숫자/`_`) |
| name | object | `{"ko":"주문 실수","en":"Order Mistake","ja":"注文ミス"}` | 대상의 이름/명칭 (다국어 필드는 로케일별 값 객체) |
| localized_name | string | `주문 실수` | `name` 의 현재 로케일 해석 값 (다국어 필드를 표시용 문자열로 해석) |
@@ -68,7 +68,7 @@ HTTP/1.1 200
```json
{
"success": true,
"message": "클래임 사유 목록을 조회했습니다.",
"message": "클레임 사유 목록을 조회했습니다.",
"data": {
"data": [
{
@@ -141,7 +141,7 @@ HTTP/1.1 200
<!-- @generated:end -->
**설명** 관리자가 클래임(반품/교환/환불) 사유 마스터 목록을 조회합니다. `permission:sirsoft-ecommerce.settings.read` 권한이 필요하며, `type`(기본 refund)·`is_active`·`fault_type`·`search` 쿼리로 필터링할 수 있습니다. `ClaimReasonService::getAllReasons()`가 조회하고 `ClaimReasonCollection`으로 반환하며, 각 항목은 다국어 사유명(`name`)과 귀책 구분(`fault_type`: customer·seller·carrier), 사용자 노출 여부(`is_user_selectable`)를 포함합니다. 환경설정의 클래임 사유 관리 화면에서 사용됩니다.
**설명** 관리자가 클레임(반품/교환/환불) 사유 마스터 목록을 조회합니다. `permission:sirsoft-ecommerce.settings.read` 권한이 필요하며, `type`(기본 refund)·`is_active`·`fault_type`·`search` 쿼리로 필터링할 수 있습니다. `ClaimReasonService::getAllReasons()`가 조회하고 `ClaimReasonCollection`으로 반환하며, 각 항목은 다국어 사유명(`name`)과 귀책 구분(`fault_type`: customer·seller·carrier), 사용자 노출 여부(`is_user_selectable`)를 포함합니다. 환경설정의 클레임 사유 관리 화면에서 사용됩니다.
### POST /api/modules/sirsoft-ecommerce/admin/claim-reasons
@@ -154,7 +154,7 @@ HTTP/1.1 200
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
| --- | --- | --- | --- | --- | --- |
| type | body | string | 예 | — | 클래임 사유 유형 (ClaimReasonTypeEnum — 현재 `refund`(환불/취소)) |
| type | body | string | 예 | — | 클레임 사유 유형 (ClaimReasonTypeEnum — 현재 `refund`(환불/취소)) |
| code | body | string | 예 | max 50 | 사유 식별 코드 (영문 소문자/숫자/`_`, 같은 type 내에서 고유) |
| name | body | array | 예 | — | 대상의 이름/명칭 |
| fault_type | body | string | 예 | — | 귀책 구분 (ClaimReasonFaultTypeEnum — `customer`(고객)/`seller`(판매자)/`carrier`(배송사)) |
@@ -202,7 +202,7 @@ Content-Type: application/json
<!-- @generated:end -->
**설명** 관리자가 새 클래임 사유를 생성합니다. `permission:sirsoft-ecommerce.settings.update` 권한이 필요하며, 유형(`type`)·고유 코드(`code`)·다국어 사유명(`name`)·귀책 구분(`fault_type`)을 필수로 받고 사용자 노출 여부·활성 여부·정렬 순서를 선택 입력합니다. `ClaimReasonService::createReason()`이 저장하고 생성된 사유를 201로 반환합니다. `code` 는 유형 내에서 고유해야 하며 회원 취소/반품 화면의 사유 선택지로 활용됩니다.
**설명** 관리자가 새 클레임 사유를 생성합니다. `permission:sirsoft-ecommerce.settings.update` 권한이 필요하며, 유형(`type`)·고유 코드(`code`)·다국어 사유명(`name`)·귀책 구분(`fault_type`)을 필수로 받고 사용자 노출 여부·활성 여부·정렬 순서를 선택 입력합니다. `ClaimReasonService::createReason()`이 저장하고 생성된 사유를 201로 반환합니다. `code` 는 유형 내에서 고유해야 하며 회원 취소/반품 화면의 사유 선택지로 활용됩니다.
### GET /api/modules/sirsoft-ecommerce/admin/claim-reasons/active
@@ -232,7 +232,7 @@ _목록 응답: `data.data[]` 배열 항목의 필드._
| --- | --- | --- | --- |
| number | integer | `8` | 목록에서의 순번 (페이지네이션 반영 행 번호 — HasRowNumber 파생) |
| id | integer | `1` | 기본 키 (내부 식별자) |
| type | string | `refund` | 클래임 사유 유형 (ClaimReasonTypeEnum — `refund`(환불/취소)) |
| type | string | `refund` | 클레임 사유 유형 (ClaimReasonTypeEnum — `refund`(환불/취소)) |
| code | string | `order_mistake` | 사유 식별 코드 (같은 type 내 고유, 영문 소문자/숫자/`_`) |
| name | object | `{"ko":"주문 실수","en":"Order Mistake","ja":"注文ミス"}` | 대상의 이름/명칭 (다국어 필드는 로케일별 값 객체) |
| localized_name | string | `주문 실수` | `name` 의 현재 로케일 해석 값 (다국어 필드를 표시용 문자열로 해석) |
@@ -256,7 +256,7 @@ HTTP/1.1 200
```json
{
"success": true,
"message": "클래임 사유 목록을 조회했습니다.",
"message": "클레임 사유 목록을 조회했습니다.",
"data": {
"data": [
{
@@ -329,7 +329,7 @@ HTTP/1.1 200
<!-- @generated:end -->
**설명** 활성화된 클래임 사유만 추려 Select 옵션용으로 조회합니다. `permission:sirsoft-ecommerce.settings.read` 권한이 필요하며, `type` 쿼리(기본 refund)로 유형을 지정하면 `ClaimReasonService::getActiveReasons()`가 `is_active=true` 인 사유만 반환합니다. 관리자 화면에서 환불/취소 처리 시 사유 드롭다운을 채우는 용도로, 목록(index)과 달리 필터 없이 활성 사유만 내려주는 점이 다릅니다.
**설명** 활성화된 클레임 사유만 추려 Select 옵션용으로 조회합니다. `permission:sirsoft-ecommerce.settings.read` 권한이 필요하며, `type` 쿼리(기본 refund)로 유형을 지정하면 `ClaimReasonService::getActiveReasons()`가 `is_active=true` 인 사유만 반환합니다. 관리자 화면에서 환불/취소 처리 시 사유 드롭다운을 채우는 용도로, 목록(index)과 달리 필터 없이 활성 사유만 내려주는 점이 다릅니다.
### DELETE /api/modules/sirsoft-ecommerce/admin/claim-reasons/{id}
@@ -370,7 +370,7 @@ HTTP/1.1 200
```json
{
"success": true,
"message": "클래임 사유가 삭제되었습니다.",
"message": "클레임 사유가 삭제되었습니다.",
"data": {
"reason_id": 8
}
@@ -387,7 +387,7 @@ HTTP/1.1 200
<!-- @generated:end -->
**설명** 관리자가 클래임 사유 1건을 삭제합니다. `permission:sirsoft-ecommerce.settings.update` 권한이 필요하며, 대상이 없으면 404 를 반환하고 존재하면 `ClaimReasonService::deleteReason()`이 삭제합니다. 이미 사용 중인 사유 등 삭제 불가 상황에서는 서비스가 던진 예외 메시지를 그대로 사용해 400 으로 응답하므로, 관리자에게 삭제 실패 사유가 노출됩니다.
**설명** 관리자가 클레임 사유 1건을 삭제합니다. `permission:sirsoft-ecommerce.settings.update` 권한이 필요하며, 대상이 없으면 404 를 반환하고 존재하면 `ClaimReasonService::deleteReason()`이 삭제합니다. 이미 사용 중인 사유 등 삭제 불가 상황에서는 서비스가 던진 예외 메시지를 그대로 사용해 400 으로 응답하므로, 관리자에게 삭제 실패 사유가 노출됩니다.
### GET /api/modules/sirsoft-ecommerce/admin/claim-reasons/{id}
@@ -440,7 +440,7 @@ HTTP/1.1 200
```json
{
"success": true,
"message": "클래임 사유 정보를 조회했습니다.",
"message": "클레임 사유 정보를 조회했습니다.",
"data": {
"id": 8,
"type": "refund",
@@ -476,7 +476,7 @@ HTTP/1.1 200
<!-- @generated:end -->
**설명** 관리자가 클래임 사유 1건의 상세 정보를 조회합니다. `permission:sirsoft-ecommerce.settings.read` 권한이 필요하며, `ClaimReasonService::getReason()`이 대상을 조회해 `ClaimReasonResource`로 반환합니다. 사유 편집 폼을 열 때 기존 값(다국어 사유명·코드·귀책 구분·활성/노출 설정 등)을 채우는 용도로 사용되며, 해당 사유가 없으면 404 를 반환합니다.
**설명** 관리자가 클레임 사유 1건의 상세 정보를 조회합니다. `permission:sirsoft-ecommerce.settings.read` 권한이 필요하며, `ClaimReasonService::getReason()`이 대상을 조회해 `ClaimReasonResource`로 반환합니다. 사유 편집 폼을 열 때 기존 값(다국어 사유명·코드·귀책 구분·활성/노출 설정 등)을 채우는 용도로 사용되며, 해당 사유가 없으면 404 를 반환합니다.
### PUT /api/modules/sirsoft-ecommerce/admin/claim-reasons/{id}
@@ -490,7 +490,7 @@ HTTP/1.1 200
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
| --- | --- | --- | --- | --- | --- |
| id | path | string | 예 | — | 대상 리소스의 식별자 |
| type | body | string | 예 | — | 클래임 사유 유형 (ClaimReasonTypeEnum — 현재 `refund`(환불/취소)) |
| type | body | string | 예 | — | 클레임 사유 유형 (ClaimReasonTypeEnum — 현재 `refund`(환불/취소)) |
| code | body | string | 예 | max 50 | 사유 식별 코드 (영문 소문자/숫자/`_`, 같은 type 내에서 고유) |
| name | body | array | 예 | — | 대상의 이름/명칭 |
| fault_type | body | string | 예 | — | 귀책 구분 (ClaimReasonFaultTypeEnum — `customer`(고객)/`seller`(판매자)/`carrier`(배송사)) |
@@ -539,7 +539,7 @@ Content-Type: application/json
<!-- @generated:end -->
**설명** 관리자가 기존 클래임 사유를 수정합니다. `permission:sirsoft-ecommerce.settings.update` 권한이 필요하고 대상은 경로 `id` 로 지정하며, 생성과 동일한 필드(유형·코드·다국어 사유명·귀책 구분·노출/활성/정렬)를 받아 `ClaimReasonService::updateReason()`이 갱신하고 갱신된 사유를 반환합니다. 대상이 없거나 갱신 실패 시 400 오류로 응답합니다.
**설명** 관리자가 기존 클레임 사유를 수정합니다. `permission:sirsoft-ecommerce.settings.update` 권한이 필요하고 대상은 경로 `id` 로 지정하며, 생성과 동일한 필드(유형·코드·다국어 사유명·귀책 구분·노출/활성/정렬)를 받아 `ClaimReasonService::updateReason()`이 갱신하고 갱신된 사유를 반환합니다. 대상이 없거나 갱신 실패 시 400 오류로 응답합니다.
### PATCH /api/modules/sirsoft-ecommerce/admin/claim-reasons/{id}/toggle-status
@@ -592,7 +592,7 @@ HTTP/1.1 200
```json
{
"success": true,
"message": "클래임 사유 상태가 변경되었습니다.",
"message": "클레임 사유 상태가 변경되었습니다.",
"data": {
"id": 8,
"type": "refund",
@@ -628,7 +628,7 @@ HTTP/1.1 200
<!-- @generated:end -->
**설명** 관리자가 클래임 사유의 활성 상태를 켜고 끄는 토글을 수행합니다. `permission:sirsoft-ecommerce.settings.update` 권한이 필요하며, `ClaimReasonService::toggleStatus()`가 대상 사유의 `is_active` 값을 반전시켜 저장하고 갱신된 사유를 반환합니다. 사유를 삭제하지 않고 일시적으로 회원 선택지에서 감추거나 다시 노출할 때 사용합니다.
**설명** 관리자가 클레임 사유의 활성 상태를 켜고 끄는 토글을 수행합니다. `permission:sirsoft-ecommerce.settings.update` 권한이 필요하며, `ClaimReasonService::toggleStatus()`가 대상 사유의 `is_active` 값을 반전시켜 저장하고 갱신된 사유를 반환합니다. 사유를 삭제하지 않고 일시적으로 회원 선택지에서 감추거나 다시 노출할 때 사용합니다.
### GET /api/modules/sirsoft-ecommerce/user/claim-reasons
@@ -658,7 +658,7 @@ _목록 응답: `data.data[]` 배열 항목의 필드._
| --- | --- | --- | --- |
| number | integer | `7` | 목록에서의 순번 (페이지네이션 반영 행 번호 — HasRowNumber 파생) |
| id | integer | `1` | 기본 키 (내부 식별자) |
| type | string | `refund` | 클래임 사유 유형 (ClaimReasonTypeEnum — `refund`(환불/취소)) |
| type | string | `refund` | 클레임 사유 유형 (ClaimReasonTypeEnum — `refund`(환불/취소)) |
| code | string | `order_mistake` | 사유 식별 코드 (같은 type 내 고유, 영문 소문자/숫자/`_`) |
| name | object | `{"ko":"주문 실수","en":"Order Mistake","ja":"注文ミス"}` | 대상의 이름/명칭 (다국어 필드는 로케일별 값 객체) |
| localized_name | string | `주문 실수` | `name` 의 현재 로케일 해석 값 (다국어 필드를 표시용 문자열로 해석) |
@@ -682,7 +682,7 @@ HTTP/1.1 200
```json
{
"success": true,
"message": "클래임 사유 목록을 조회했습니다.",
"message": "클레임 사유 목록을 조회했습니다.",
"data": {
"data": [
{
@@ -754,6 +754,6 @@ HTTP/1.1 200
<!-- @generated:end -->
**설명** 회원(및 선택적으로 비회원)이 주문 취소/반품 신청 화면에서 선택할 수 있는 클래임 사유 목록을 조회합니다. `optional.sanctum`(회원/비회원 모두 접근)과 `permission:sirsoft-ecommerce.user-orders.cancel` 권한이 적용되며, `ClaimReasonService::getUserSelectableReasons()`가 활성이면서 `is_user_selectable=true` 인 사유만 반환합니다. 관리 전용 목록과 달리 사용자에게 공개 가능한 사유만 내려주는 사용자향 엔드포인트입니다.
**설명** 회원(및 선택적으로 비회원)이 주문 취소/반품 신청 화면에서 선택할 수 있는 클레임 사유 목록을 조회합니다. `optional.sanctum`(회원/비회원 모두 접근)과 `permission:sirsoft-ecommerce.user-orders.cancel` 권한이 적용되며, `ClaimReasonService::getUserSelectableReasons()`가 활성이면서 `is_user_selectable=true` 인 사유만 반환합니다. 관리 전용 목록과 달리 사용자에게 공개 가능한 사유만 내려주는 사용자향 엔드포인트입니다.
@@ -205,7 +205,16 @@
"params": {
"method": "PUT",
"body": { "currency": "{{currency.code}}" }
}
},
"onError": [
{
"handler": "toast",
"params": {
"type": "error",
"message": "{{error.message}}"
}
}
]
}
}
]
@@ -310,7 +319,16 @@
"params": {
"method": "PUT",
"body": { "shipping_country": "{{shipCountry.code}}" }
}
},
"onError": [
{
"handler": "toast",
"params": {
"type": "error",
"message": "{{error.message}}"
}
}
]
}
}
]
@@ -159,7 +159,7 @@
"name": "Icon",
"props": {
"name": "{{_local.isSaving ? 'loader' : 'save'}}",
"className": "w-4 h-4 mr-2 {{_local.isSaving ? 'animate-spin' : ''}}"
"className": "text-base mr-2 {{_local.isSaving ? 'animate-spin' : ''}}"
}
},
{
@@ -244,7 +244,7 @@
"name": "Icon",
"props": {
"name": "plus",
"className": "w-4 h-4 mr-2"
"className": "text-base mr-2"
}
},
{
@@ -748,7 +748,7 @@
"name": "Icon",
"props": {
"name": "calendar",
"className": "w-4 h-4 text-gray-400"
"className": "text-base text-gray-400"
}
},
{
@@ -1734,7 +1734,7 @@
"name": "Icon",
"props": {
"name": "calendar",
"className": "w-4 h-4 text-gray-400"
"className": "text-base text-gray-400"
}
},
{
@@ -1850,7 +1850,7 @@
"name": "Icon",
"props": {
"name": "calendar",
"className": "w-4 h-4 text-gray-400"
"className": "text-base text-gray-400"
}
},
{
@@ -2161,7 +2161,7 @@
"name": "Icon",
"props": {
"name": "{{_local.showDetailFilter ? 'chevron-up' : 'chevron-down'}}",
"className": "w-4 h-4"
"className": "text-base"
}
}
],
@@ -2258,7 +2258,7 @@
"name": "Icon",
"props": {
"name": "sliders",
"className": "w-4 h-4"
"className": "text-base"
}
},
{
@@ -2436,7 +2436,7 @@
"name": "Icon",
"props": {
"name": "sliders",
"className": "w-4 h-4"
"className": "text-base"
}
},
{
@@ -2923,7 +2923,7 @@
"name": "Icon",
"props": {
"name": "user",
"className": "w-4 h-4 text-gray-400"
"className": "text-base text-gray-400"
}
},
{
@@ -2962,7 +2962,7 @@
"name": "Icon",
"props": {
"name": "more-horizontal",
"className": "w-4 h-4"
"className": "text-base"
}
}
]
@@ -3050,7 +3050,7 @@
"name": "Icon",
"props": {
"name": "more-horizontal",
"className": "w-4 h-4"
"className": "text-base"
}
}
]
@@ -3218,7 +3218,7 @@
"name": "Icon",
"props": {
"name": "more-vertical",
"className": "w-4 h-4"
"className": "text-base"
}
}
]
@@ -3693,7 +3693,7 @@
"if": "{{_global.isChangingStatus}}",
"props": {
"name": "spinner",
"className": "w-4 h-4 animate-spin"
"className": "text-base animate-spin"
}
},
{
@@ -3799,7 +3799,7 @@
"name": "Icon",
"props": {
"name": "x",
"className": "w-3 h-3"
"className": "text-xs"
}
}
]
@@ -3899,7 +3899,7 @@
"name": "Icon",
"props": {
"name": "user",
"className": "w-4 h-4 text-gray-400"
"className": "text-base text-gray-400"
}
},
{
@@ -3938,7 +3938,7 @@
"name": "Icon",
"props": {
"name": "more-horizontal",
"className": "w-4 h-4"
"className": "text-base"
}
}
]
@@ -4255,7 +4255,7 @@
"if": "{{_global.isDeleting}}",
"props": {
"name": "spinner",
"className": "w-4 h-4 animate-spin"
"className": "text-base animate-spin"
}
},
{
@@ -121,7 +121,7 @@
"name": "Icon",
"props": {
"name": "plus",
"className": "w-4 h-4"
"className": "text-base"
}
},
{
@@ -174,7 +174,7 @@
"name": "Icon",
"props": {
"name": "search",
"className": "absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400"
"className": "absolute left-3 top-1/2 -translate-y-1/2 text-xl text-gray-400"
}
},
{
@@ -1948,7 +1948,7 @@
"name": "Icon",
"props": {
"name": "ellipsis-vertical",
"className": "w-5 h-5 text-gray-500"
"className": "text-xl text-gray-500"
}
}
]
@@ -2026,7 +2026,7 @@
"name": "Icon",
"props": {
"name": "truck",
"className": "w-4 h-4 text-gray-400"
"className": "text-base text-gray-400"
}
},
{
@@ -2162,7 +2162,7 @@
"name": "Icon",
"props": {
"name": "plus",
"className": "w-4 h-4"
"className": "text-base"
}
},
{
@@ -2266,7 +2266,7 @@
"name": "Icon",
"props": {
"name": "triangle-exclamation",
"className": "w-5 h-5 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5"
"className": "text-xl text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5"
}
},
{
@@ -2333,7 +2333,7 @@
"if": "{{_global.isDeleting}}",
"props": {
"name": "spinner",
"className": "w-4 h-4 animate-spin"
"className": "text-base animate-spin"
}
},
{
@@ -2593,7 +2593,7 @@
"name": "Icon",
"props": {
"name": "copy",
"className": "w-4 h-4"
"className": "text-base"
}
},
{
@@ -2667,7 +2667,7 @@
"name": "Icon",
"props": {
"name": "triangle-exclamation",
"className": "w-5 h-5 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5"
"className": "text-xl text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5"
}
},
{
@@ -2734,7 +2734,7 @@
"if": "{{_global.isBulkDeleting}}",
"props": {
"name": "spinner",
"className": "w-4 h-4 animate-spin"
"className": "text-base animate-spin"
}
},
{
@@ -2924,7 +2924,7 @@
"if": "{{_global.isBulkToggling}}",
"props": {
"name": "spinner",
"className": "w-4 h-4 animate-spin"
"className": "text-base animate-spin"
}
},
{
@@ -88,8 +88,10 @@ describe('A23/§B-FAIL-1 — 추가옵션 확인 모달은 openModal/closeModal
const openAction = btn.actions.find((a: any) => a.handler === 'openModal');
expect(openAction).toBeDefined();
expect(openAction.target).toBe('additional_options_clear_modal');
// 행이 있을 때만
expect(openAction.condition).toContain('(_local.form.additional_options ?? []).length > 0');
// 행이 있을 때만.
// 액션 게이트 키는 `if` 다 — `condition` 은 컴포넌트 레벨 별칭이라 액션에서는 조용히 무시된다
// (ActionDispatcher 는 action.if 만 본다). #78 후속으로 condition → if 로 교정됨.
expect(openAction.if).toContain('(_local.form.additional_options ?? []).length > 0');
});
it('"미사용" 버튼은 setState ui.showAdditionalOptionsClearModal 플래그를 더이상 쓰지 않는다', () => {
@@ -484,8 +486,9 @@ describe('회귀: 상품 생성/저장 후 navigate 는 id 기반 (product_code
productForm,
(n) => n.handler === 'navigate' && typeof n.params?.path === 'string' && /\/admin\/ecommerce\/products\//.test(n.params.path) && /\/edit/.test(n.params.path),
);
// 생성모드 redirect 노드 (condition: !route.itemCode) 존재
const createNav = navs => navs.find((n: any) => typeof n.condition === 'string' && /!route\.itemCode/.test(n.condition));
// 생성모드 redirect 노드 (if: !route.itemCode) 존재
// `condition` 은 액션에서 무시되므로 게이트가 성립하지 않는다 → `if` 로 교정됨 (#78 후속)
const createNav = navs => navs.find((n: any) => typeof n.if === 'string' && /!route\.itemCode/.test(n.if));
const node = createNav(navs);
expect(node).toBeTruthy();
expect(node.params.path).toContain('result.data.id');
@@ -20,9 +20,6 @@ return [
// Auto cancel
'auto_cancel_expired_reason' => 'Automatically cancelled due to payment deadline expiration',
// Order cancellation
'cancelled' => 'Order has been cancelled.',
// Payment
'payment_cancelled' => 'Payment cancellation has been recorded.',
'payment_pending' => 'Awaiting payment.',
@@ -20,9 +20,6 @@ return [
// 자동 취소
'auto_cancel_expired_reason' => '입금 기한 만료로 인한 자동 취소',
// 주문 취소
'cancelled' => '주문이 취소되었습니다.',
// 결제
'payment_cancelled' => '결제 취소가 기록되었습니다.',
'payment_pending' => '입금 대기 중입니다.',
@@ -6,7 +6,7 @@
"language_currency": "언어/통화",
"seo": "SEO 설정",
"order_settings": "주문설정",
"claim": "클래임",
"claim": "클레임",
"shipping": "배송설정",
"review_settings": "리뷰 설정",
"notification_definitions": "알림 설정",
@@ -222,7 +222,7 @@
}
},
"claim": {
"title": "클래임 설정",
"title": "클레임 설정",
"refund_reasons": {
"section_title": "환불 사유 관리",
"add_button": "사유 추가",
@@ -365,7 +365,7 @@
},
{
"handler": "sirsoft-ecommerce.setDefaultShippingPolicy",
"condition": "{{!route.itemCode}}"
"if": "{{!route.itemCode}}"
}
],
"slots": {
@@ -1054,7 +1054,7 @@
},
{
"handler": "navigate",
"condition": "{{!route.itemCode}}",
"if": "{{!route.itemCode}}",
"params": {
"path": "{{'/admin/ecommerce/products/' + result.data.id + '/edit'}}"
}
@@ -457,7 +457,7 @@
"name": "Button",
"props": {
"type": "button",
"className": "flex-center gap-2 px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed",
"className": "flex-center gap-2 px-4 py-2 text-sm bg-blue-600 dark:bg-blue-500 text-white rounded-lg hover:bg-blue-700 dark:hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed",
"disabled": "{{(!$parent._local.batchOrderStatus && !$parent._local.batchCarrierId && !$parent._local.batchTrackingNumber) || (($parent._local.batchOrderStatus === 'shipping_ready' || $parent._local.batchOrderStatus === 'shipping' || $parent._local.batchOrderStatus === 'delivered') && (!$parent._local.batchCarrierId || !$parent._local.batchTrackingNumber)) || _global.isProcessing}}"
},
"actions": [
@@ -506,7 +506,7 @@
"handler": "toast",
"params": {
"type": "error",
"message": "{{$error.message}}"
"message": "{{error.message}}"
}
}
]
@@ -172,7 +172,7 @@
"name": "Button",
"props": {
"type": "button",
"className": "flex-center gap-2 px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed",
"className": "flex-center gap-2 px-4 py-2 text-sm bg-blue-600 dark:bg-blue-500 text-white rounded-lg hover:bg-blue-700 dark:hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed",
"disabled": "{{(!_global.bulkConfirmData?.orderStatus && !_global.bulkConfirmData?.courierId && !_global.bulkConfirmData?.trackingNumber) || ((_global.bulkConfirmData?.orderStatus === 'shipping_ready' || _global.bulkConfirmData?.orderStatus === 'shipping') && (!_global.bulkConfirmData?.courierId || !_global.bulkConfirmData?.trackingNumber)) || _global.isProcessing}}"
},
"actions": [
@@ -213,7 +213,7 @@
"handler": "toast",
"params": {
"type": "error",
"message": "{{$error.message}}"
"message": "{{error.message}}"
}
}
]
@@ -186,7 +186,7 @@
"name": "Button",
"props": {
"type": "button",
"className": "flex-center gap-2 px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed",
"className": "flex-center gap-2 px-4 py-2 text-sm bg-blue-600 dark:bg-blue-500 text-white rounded-lg hover:bg-blue-700 dark:hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed",
"disabled": "{{_global.isDownloading}}"
},
"actions": [
@@ -252,7 +252,7 @@
"handler": "toast",
"params": {
"type": "error",
"message": "{{$error.message}}"
"message": "{{error.message}}"
}
}
]
@@ -276,7 +276,7 @@
"if": "{{!_global.isDownloading}}",
"props": {
"name": "download",
"className": "w-4 h-4"
"className": "text-base"
}
},
{
@@ -53,7 +53,7 @@
"name": "Button",
"props": {
"type": "button",
"className": "flex-center gap-2 px-4 py-2 text-sm bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed",
"className": "flex-center gap-2 px-4 py-2 text-sm bg-red-600 dark:bg-red-500 text-white rounded-lg hover:bg-red-700 dark:hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed",
"disabled": "{{_global.isDeleting}}"
},
"actions": [
@@ -112,7 +112,7 @@
"handler": "toast",
"params": {
"type": "error",
"message": "{{$error.message}}"
"message": "{{error.message}}"
}
}
]
@@ -65,7 +65,7 @@
"name": "Button",
"props": {
"type": "button",
"className": "flex-center gap-2 px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed",
"className": "flex-center gap-2 px-4 py-2 text-sm bg-blue-600 dark:bg-blue-500 text-white rounded-lg hover:bg-blue-700 dark:hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed",
"disabled": "{{!_global.editingPresetName || _global.editingPresetName.trim() === '' || _global.isSaving}}"
},
"actions": [
@@ -127,7 +127,7 @@
"handler": "toast",
"params": {
"type": "error",
"message": "{{$error.message}}"
"message": "{{error.message}}"
}
}
]
@@ -66,7 +66,7 @@
"name": "Button",
"props": {
"type": "button",
"className": "flex-center gap-2 px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed",
"className": "flex-center gap-2 px-4 py-2 text-sm bg-blue-600 dark:bg-blue-500 text-white rounded-lg hover:bg-blue-700 dark:hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed",
"disabled": "{{!_local.presetName || _local.presetName.trim() === '' || _global.isSaving}}"
},
"actions": [
@@ -158,7 +158,7 @@
"handler": "toast",
"params": {
"type": "error",
"message": "{{$error.message}}"
"message": "{{error.message}}"
}
}
]
@@ -21,7 +21,7 @@
"name": "Icon",
"props": {
"name": "exclamation",
"className": "w-4 h-4 text-red-600 dark:text-red-400 block"
"className": "text-base text-red-600 dark:text-red-400 block"
}
}
]
@@ -71,7 +71,7 @@
"name": "Icon",
"props": {
"name": "box",
"className": "w-4 h-4 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5"
"className": "text-base text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5"
}
},
{
@@ -120,7 +120,7 @@
"type": "basic",
"name": "Button",
"props": {
"className": "flex-center gap-2 px-4 py-2 text-sm bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed",
"className": "flex-center gap-2 px-4 py-2 text-sm bg-red-600 dark:bg-red-500 text-white rounded-lg hover:bg-red-700 dark:hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed",
"disabled": "{{_global.isDeleting}}"
},
"actions": [
@@ -182,7 +182,7 @@
"handler": "toast",
"params": {
"type": "error",
"message": "{{$error.message}}"
"message": "{{error.message}}"
}
}
]
@@ -76,7 +76,7 @@
"name": "Icon",
"props": {
"name": "info-circle",
"className": "w-5 h-5 text-blue-500 dark:text-blue-400 shrink-0"
"className": "text-xl text-blue-500 dark:text-blue-400 shrink-0"
}
},
{
@@ -132,7 +132,7 @@
"name": "Icon",
"props": {
"name": "plus",
"className": "w-4 h-4 mr-1"
"className": "text-base mr-1"
}
},
{
@@ -265,7 +265,7 @@
"name": "Icon",
"props": {
"name": "trash",
"className": "w-4 h-4"
"className": "text-base"
}
}
]
@@ -1031,7 +1031,7 @@
"name": "Icon",
"props": {
"name": "trash",
"className": "w-4 h-4"
"className": "text-base"
}
}
]
@@ -1077,7 +1077,7 @@
"name": "Icon",
"props": {
"name": "plus",
"className": "w-4 h-4"
"className": "text-base"
}
},
{
@@ -1201,7 +1201,7 @@
"name": "Icon",
"props": {
"name": "trash",
"className": "w-5 h-5"
"className": "text-xl"
}
}
]
@@ -1668,7 +1668,7 @@
{
"type": "click",
"handler": "sirsoft-ecommerce.addAdditionalOption",
"condition": "{{(_local.form.additional_options ?? []).length === 0}}"
"if": "{{(_local.form.additional_options ?? []).length === 0}}"
}
]
},
@@ -1685,7 +1685,7 @@
{
"type": "click",
"handler": "openModal",
"condition": "{{(_local.form.additional_options ?? []).length > 0}}",
"if": "{{(_local.form.additional_options ?? []).length > 0}}",
"target": "additional_options_clear_modal"
}
]
@@ -1740,7 +1740,7 @@
"name": "Icon",
"props": {
"name": "grip-vertical",
"className": "w-5 h-5"
"className": "text-xl"
}
}
]
@@ -1858,7 +1858,7 @@
"name": "Icon",
"props": {
"name": "trash",
"className": "w-4 h-4"
"className": "text-base"
}
}
],
@@ -171,7 +171,7 @@
},
{
"handler": "setState",
"condition": "{{!_local.form.seo_sync_title}}",
"if": "{{!_local.form.seo_sync_title}}",
"params": {
"target": "local",
"form.meta_title": "{{_local.form.name}}"
@@ -291,7 +291,7 @@
},
{
"handler": "setState",
"condition": "{{!_local.form.seo_sync_description}}",
"if": "{{!_local.form.seo_sync_description}}",
"params": {
"target": "local",
"form.meta_description": "{{_local.form.description}}"
@@ -73,7 +73,7 @@
"type": "basic",
"name": "Button",
"props": {
"className": "flex-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed",
"className": "flex-center gap-2 px-4 py-2 bg-red-600 dark:bg-red-500 text-white rounded-lg hover:bg-red-700 dark:hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed",
"disabled": "{{_global.isDeleting}}"
},
"actions": [
@@ -133,7 +133,7 @@
"handler": "toast",
"params": {
"type": "error",
"message": "{{$error.message}}"
"message": "{{error.message}}"
}
}
]
@@ -840,7 +840,16 @@
"handler": "openModal",
"target": "modal_ecommerce_notification_definition_preview"
}
]
],
"onError": [
{
"handler": "toast",
"params": {
"type": "error",
"message": "{{error.message}}"
}
}
]
}
]
}
@@ -1,7 +1,7 @@
{
"meta": {
"is_partial": true,
"description": "쇼핑몰 설정 클래임 탭 콘텐츠"
"description": "쇼핑몰 설정 클레임 탭 콘텐츠"
},
"id": "tab_content_claim",
"type": "basic",
@@ -416,7 +416,7 @@
"text": "$t:sirsoft-ecommerce.admin.settings.notification_definitions.no_template_for_channel"
},
{
"id": "ecommerce_recipients_badge",
"id": "ecommerce_recipients_badge_{{defIdx}}",
"type": "basic",
"name": "Div",
"if": "{{((def.templates ?? []).find(t => t.channel === (_local.activeNotificationChannel ?? query.channel ?? 'mail'))?.recipients ?? []).length > 0}}",
@@ -539,7 +539,16 @@
"type": "success"
}
}
]
],
"onError": [
{
"handler": "toast",
"params": {
"type": "error",
"message": "{{error.message}}"
}
}
]
}
]
},
@@ -39,7 +39,7 @@
"name": "Icon",
"props": {
"name": "triangle-exclamation",
"className": "w-5 h-5 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5"
"className": "text-xl text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5"
}
},
{
@@ -100,7 +100,7 @@
"name": "Button",
"props": {
"type": "button",
"className": "flex-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed",
"className": "flex-center gap-2 px-4 py-2 bg-red-600 dark:bg-red-500 text-white rounded-lg hover:bg-red-700 dark:hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed",
"disabled": "{{_global.isBulkDeleting}}"
},
"children": [
@@ -179,7 +179,7 @@
"handler": "toast",
"params": {
"type": "error",
"message": "{{$error.message}}"
"message": "{{error.message}}"
}
}
]
@@ -176,7 +176,7 @@
"handler": "toast",
"params": {
"type": "error",
"message": "{{$error.message}}"
"message": "{{error.message}}"
}
}
]
@@ -52,7 +52,7 @@
"name": "Icon",
"props": {
"name": "triangle-exclamation",
"className": "w-5 h-5 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5"
"className": "text-xl text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5"
}
},
{
@@ -111,7 +111,7 @@
"name": "Button",
"props": {
"type": "button",
"className": "flex-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed",
"className": "flex-center gap-2 px-4 py-2 bg-red-600 dark:bg-red-500 text-white rounded-lg hover:bg-red-700 dark:hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed",
"disabled": "{{_global.isDeleting}}"
},
"children": [
@@ -187,7 +187,7 @@
"handler": "toast",
"params": {
"type": "error",
"message": "{{$error.message}}"
"message": "{{error.message}}"
}
}
]
@@ -96,7 +96,7 @@
"name": "Button",
"props": {
"type": "button",
"className": "flex-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed",
"className": "flex-center gap-2 px-4 py-2 bg-blue-600 dark:bg-blue-500 text-white rounded-lg hover:bg-blue-700 dark:hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed",
"disabled": "{{_global.isSettingDefault}}"
},
"children": [
@@ -172,7 +172,7 @@
"handler": "toast",
"params": {
"type": "error",
"message": "{{$error.message}}"
"message": "{{error.message}}"
}
}
]
@@ -151,7 +151,7 @@
"handler": "toast",
"params": {
"type": "error",
"message": "{{$error.message}}"
"message": "{{error.message}}"
}
}
]
@@ -3,7 +3,7 @@
namespace Modules\Sirsoft\Ecommerce\Enums;
/**
* 클래임 사유 귀책 유형 Enum
* 클레임 사유 귀책 유형 Enum
*/
enum ClaimReasonFaultTypeEnum: string
{
@@ -14,7 +14,7 @@ enum ClaimReasonFaultTypeEnum: string
/**
* 다국어 라벨을 반환합니다.
*
* @return string
* @return string 다국어 라벨
*/
public function label(): string
{
@@ -24,7 +24,7 @@ enum ClaimReasonFaultTypeEnum: string
/**
* 모든 값 배열을 반환합니다.
*
* @return array
* @return array 모든 값 배열
*/
public static function values(): array
{
@@ -34,7 +34,7 @@ enum ClaimReasonFaultTypeEnum: string
/**
* 프론트엔드용 옵션 배열을 반환합니다.
*
* @return array
* @return array 프론트엔드용 옵션 배열
*/
public static function toSelectOptions(): array
{
@@ -3,7 +3,7 @@
namespace Modules\Sirsoft\Ecommerce\Enums;
/**
* 클래임 사유 유형 Enum
* 클레임 사유 유형 Enum
*/
enum ClaimReasonTypeEnum: string
{
@@ -13,7 +13,7 @@ enum ClaimReasonTypeEnum: string
/**
* 다국어 라벨을 반환합니다.
*
* @return string
* @return string 다국어 라벨
*/
public function label(): string
{
@@ -23,7 +23,7 @@ enum ClaimReasonTypeEnum: string
/**
* 모든 값 배열을 반환합니다.
*
* @return array
* @return array 모든 값 배열
*/
public static function values(): array
{
@@ -33,7 +33,7 @@ enum ClaimReasonTypeEnum: string
/**
* 프론트엔드용 옵션 배열을 반환합니다.
*
* @return array
* @return array 프론트엔드용 옵션 배열
*/
public static function toSelectOptions(): array
{
@@ -0,0 +1,37 @@
<?php
namespace Modules\Sirsoft\Ecommerce\Exceptions;
use Exception;
/**
* 클레임 사유 처리 예외
*
* 클레임 사유의 조회·수정·삭제·일괄 동기화 중 발생하는 도메인 실패를 표현합니다.
* 컨트롤러는 i18n 문자열 매칭 대신 이 타입으로 분기합니다.
*/
class ClaimReasonException extends Exception
{
/**
* 대상 클레임 사유를 찾을 수 없을 때
*
* @return self 예외 인스턴스
*/
public static function notFound(): self
{
return new self(__('sirsoft-ecommerce::exceptions.claim_reason_not_found'));
}
/**
* 주문 취소 이력에서 사용 중이라 삭제할 수 없을 때
*
* @param int $usageCount 해당 사유를 사용한 취소 이력 건수
* @return self 예외 인스턴스
*/
public static function inUse(int $usageCount): self
{
return new self(__('sirsoft-ecommerce::exceptions.claim_reason_in_use', [
'count' => $usageCount,
]));
}
}
@@ -5,7 +5,8 @@ namespace Modules\Sirsoft\Ecommerce\Http\Controllers\Admin;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ActiveClaimReasonRequest;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\IndexClaimReasonRequest;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\StoreClaimReasonRequest;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UpdateClaimReasonRequest;
use Modules\Sirsoft\Ecommerce\Http\Resources\ClaimReasonCollection;
@@ -13,32 +14,26 @@ use Modules\Sirsoft\Ecommerce\Http\Resources\ClaimReasonResource;
use Modules\Sirsoft\Ecommerce\Services\ClaimReasonService;
/**
* 클래임 사유 관리 컨트롤러
* 클레임 사유 관리 컨트롤러
*/
class ClaimReasonController extends AdminBaseController
{
/**
* @param ClaimReasonService $service 클래임 사유 서비스
* @param ClaimReasonService $service 클레임 사유 서비스
*/
public function __construct(
protected ClaimReasonService $service,
) {}
/**
* 클래임 사유 목록 조회
* 클레임 사유 목록 조회
*
* @param Request $request
* @return JsonResponse
* @param IndexClaimReasonRequest $request 목록 필터 요청
* @return JsonResponse 클레임 사유 목록 응답
*/
public function index(Request $request): JsonResponse
public function index(IndexClaimReasonRequest $request): JsonResponse
{
$filters = $request->only(['type', 'is_active', 'fault_type', 'search']);
if (! isset($filters['type'])) {
$filters['type'] = 'refund';
}
$reasons = $this->service->getAllReasons($filters);
$reasons = $this->service->getAllReasons($request->filters());
return ResponseHelper::moduleSuccess(
'sirsoft-ecommerce',
@@ -48,10 +43,10 @@ class ClaimReasonController extends AdminBaseController
}
/**
* 클래임 사유 생성
* 클레임 사유 생성
*
* @param StoreClaimReasonRequest $request
* @return JsonResponse
* @param StoreClaimReasonRequest $request 생성 요청
* @return JsonResponse 생성된 클레임 사유 응답
*/
public function store(StoreClaimReasonRequest $request): JsonResponse
{
@@ -66,15 +61,14 @@ class ClaimReasonController extends AdminBaseController
}
/**
* 활성 클래임 사유 목록 조회 (Select 옵션용)
* 활성 클레임 사유 목록 조회 (Select 옵션용)
*
* @param Request $request
* @return JsonResponse
* @param ActiveClaimReasonRequest $request 유형 필터 요청
* @return JsonResponse 활성 클레임 사유 목록 응답 (Select 옵션용)
*/
public function active(Request $request): JsonResponse
public function active(ActiveClaimReasonRequest $request): JsonResponse
{
$type = $request->query('type', 'refund');
$reasons = $this->service->getActiveReasons($type);
$reasons = $this->service->getActiveReasons($request->type());
return ResponseHelper::moduleSuccess(
'sirsoft-ecommerce',
@@ -84,10 +78,10 @@ class ClaimReasonController extends AdminBaseController
}
/**
* 클래임 사유 상세 조회
* 클레임 사유 상세 조회
*
* @param int $id 사유 ID
* @return JsonResponse
* @param int $id 사유 ID
* @return JsonResponse 클레임 사유 상세 응답
*/
public function show(int $id): JsonResponse
{
@@ -109,11 +103,11 @@ class ClaimReasonController extends AdminBaseController
}
/**
* 클래임 사유 수정
* 클레임 사유 수정
*
* @param UpdateClaimReasonRequest $request
* @param int $id 사유 ID
* @return JsonResponse
* @param UpdateClaimReasonRequest $request 수정 요청
* @param int $id 사유 ID
* @return JsonResponse 수정된 클레임 사유 응답
*/
public function update(UpdateClaimReasonRequest $request, int $id): JsonResponse
{
@@ -135,10 +129,10 @@ class ClaimReasonController extends AdminBaseController
}
/**
* 클래임 사유 삭제
* 클레임 사유 삭제
*
* @param int $id 사유 ID
* @return JsonResponse
* @param int $id 사유 ID
* @return JsonResponse 삭제 결과 응답
*/
public function destroy(int $id): JsonResponse
{
@@ -170,10 +164,10 @@ class ClaimReasonController extends AdminBaseController
}
/**
* 클래임 사유 상태 토글
* 클레임 사유 상태 토글
*
* @param int $id 사유 ID
* @return JsonResponse
* @param int $id 사유 ID
* @return JsonResponse 상태가 토글된 클레임 사유 응답
*/
public function toggleStatus(int $id): JsonResponse
{
@@ -195,15 +189,14 @@ class ClaimReasonController extends AdminBaseController
}
/**
* 사용자 선택 가능한 클래임 사유 목록 (User API용)
* 사용자 선택 가능한 클레임 사유 목록 (User API용)
*
* @param Request $request
* @return JsonResponse
* @param ActiveClaimReasonRequest $request 유형 필터 요청
* @return JsonResponse 사용자 선택 가능한 클레임 사유 목록 응답
*/
public function userSelectableReasons(Request $request): JsonResponse
public function userSelectableReasons(ActiveClaimReasonRequest $request): JsonResponse
{
$type = $request->query('type', 'refund');
$reasons = $this->service->getUserSelectableReasons($type);
$reasons = $this->service->getUserSelectableReasons($request->type());
return ResponseHelper::moduleSuccess(
'sirsoft-ecommerce',
@@ -434,7 +434,7 @@ class EcommerceSettingsController extends AdminBaseController
}
/**
* 설정 응답에 클래임 사유 목록을 추가합니다.
* 설정 응답에 클레임 사유 목록을 추가합니다.
*
* DB 관리 대상인 claim reasons를 claim 섹션에 포함시킵니다.
*
@@ -1,5 +1,8 @@
<?php
// audit:allow api-doc-coverage reason: 이번 변경은 다국어 키 참조 오타(fetc_failed → fetch_failed) 1건 정정뿐이며
// 엔드포인트·파라미터·응답 필드 등 API 표면은 변경되지 않아 갱신할 문서가 없다.
namespace Modules\Sirsoft\Ecommerce\Http\Controllers\Public;
use App\Helpers\ResponseHelper;
@@ -198,7 +201,7 @@ class CheckoutController extends PublicBaseController
return ResponseHelper::moduleError(
'sirsoft-ecommerce',
'messages.checkout.fetc_failed',
'messages.checkout.fetch_failed',
500
);
}
@@ -0,0 +1,61 @@
<?php
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Sirsoft\Ecommerce\Enums\ClaimReasonTypeEnum;
/**
* 활성/사용자 선택 가능 클레임 사유 목록 조회 요청
*
* 두 목록 모두 유형(type) 하나만 받으므로 같은 요청 객체를 공유한다.
*/
class ActiveClaimReasonRequest extends FormRequest
{
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* @return bool 항상 true (권한은 라우트 permission 미들웨어가 담당)
*/
public function authorize(): bool
{
return true;
}
/**
* 요청에 적용할 검증 규칙
*
* @return array<string, mixed> 검증 규칙 배열
*/
public function rules(): array
{
return [
'type' => ['sometimes', 'string', Rule::in(ClaimReasonTypeEnum::values())],
];
}
/**
* 검증할 필드의 이름을 커스터마이징
*
* @return array<string, string> 필드명 → 표시명 매핑
*/
public function attributes(): array
{
return [
'type' => __('sirsoft-ecommerce::validation.attributes.claim_reason_type'),
];
}
/**
* 조회할 클레임 사유 유형을 반환합니다.
*
* 미지정 시 기본값은 환불(refund)이다.
*
* @return string 클레임 사유 유형
*/
public function type(): string
{
return $this->validated()['type'] ?? ClaimReasonTypeEnum::REFUND->value;
}
}
@@ -0,0 +1,72 @@
<?php
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Sirsoft\Ecommerce\Enums\ClaimReasonFaultTypeEnum;
use Modules\Sirsoft\Ecommerce\Enums\ClaimReasonTypeEnum;
/**
* 클레임 사유 목록 조회 요청
*
* 목록 필터(유형·활성 여부·귀책 구분·검색어)를 검증한다.
*/
class IndexClaimReasonRequest extends FormRequest
{
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* @return bool 항상 true (권한은 라우트 permission 미들웨어가 담당)
*/
public function authorize(): bool
{
return true;
}
/**
* 요청에 적용할 검증 규칙
*
* @return array<string, mixed> 검증 규칙 배열
*/
public function rules(): array
{
return [
'type' => ['sometimes', 'string', Rule::in(ClaimReasonTypeEnum::values())],
'fault_type' => ['sometimes', 'string', Rule::in(ClaimReasonFaultTypeEnum::values())],
'is_active' => ['sometimes', 'boolean'],
'search' => ['sometimes', 'nullable', 'string', 'max:255'],
];
}
/**
* 검증할 필드의 이름을 커스터마이징
*
* @return array<string, string> 필드명 → 표시명 매핑
*/
public function attributes(): array
{
return [
'type' => __('sirsoft-ecommerce::validation.attributes.claim_reason_type'),
'fault_type' => __('sirsoft-ecommerce::validation.attributes.claim_reason_fault_type'),
'is_active' => __('sirsoft-ecommerce::validation.attributes.claim_reason_is_active'),
'search' => __('sirsoft-ecommerce::validation.attributes.claim_reason_search'),
];
}
/**
* 검증된 필터만 추린 배열을 반환합니다.
*
* 컨트롤러가 `only()` 로 요청을 직접 훑지 않도록, 필터 해석 책임을 요청 객체가 갖는다.
* 유형 미지정 시 기본값은 환불(refund)이다.
*
* @return array<string, mixed> 서비스에 넘길 필터 배열
*/
public function filters(): array
{
$filters = $this->validated();
$filters['type'] ??= ClaimReasonTypeEnum::REFUND->value;
return $filters;
}
}
@@ -10,14 +10,14 @@ use Modules\Sirsoft\Ecommerce\Enums\ClaimReasonTypeEnum;
use Modules\Sirsoft\Ecommerce\Models\ClaimReason;
/**
* 클래임 사유 생성 요청
* 클레임 사유 생성 요청
*/
class StoreClaimReasonRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
* @return bool 항상 true (권한은 라우트 permission 미들웨어가 담당)
*/
public function authorize(): bool
{
@@ -27,7 +27,7 @@ class StoreClaimReasonRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, mixed> 검증 규칙 배열
*/
public function rules(): array
{
@@ -51,7 +51,7 @@ class StoreClaimReasonRequest extends FormRequest
/**
* Get custom attributes for validator errors.
*
* @return array
* @return array<string, string> 필드명 → 표시명 매핑
*/
public function attributes(): array
{
@@ -18,6 +18,7 @@ use Modules\Sirsoft\Ecommerce\Models\ShippingType;
/**
* 배송정책 생성 요청
*/
// audit:allow api-doc-coverage reason: 이번 변경은 messages() 의 다국어 키 경로 정정뿐이다. 요청 파라미터·응답 구조·검증 규칙이 그대로라 docs/api/shipping-policies.md 에 갱신할 내용이 없다 (422 에러표는 개별 메시지 문구를 기재하지 않음).
class StoreShippingPolicyRequest extends FormRequest
{
/**
@@ -141,7 +142,7 @@ class StoreShippingPolicyRequest extends FormRequest
'country_settings.*.ranges.tiers.*.max.min' => __('sirsoft-ecommerce::validation.shipping_policy.ranges.tier_max_non_negative'),
'country_settings.*.ranges.unit_value.min' => __('sirsoft-ecommerce::validation.shipping_policy.ranges.unit_value_min'),
'country_settings.*.extra_fee_settings.*.fee.min' => __('sirsoft-ecommerce::validation.extra_fee_template.fee_min'),
'is_active.required' => __('sirsoft-ecommerce::validation.shipping_policy.is_active.required'),
'is_active.required' => __('sirsoft-ecommerce::validation.shipping_policy.is_active_required'),
];
}
Loaded 100 of 288 files, more files were not shown because too many files have changed in this diff. Show more