fix(core,board,ecommerce,page,kginicis): 정책값 하드코딩·계약 분리 결함 일괄 수정

관리자 환경설정이 값을 저장은 하지만 실제 동작에는 닿지 않던 결함군을 정리했다.
설정 화면(min/max)·저장 검증(FormRequest)·런타임 적용(Service) 세 계층이 각자
리터럴을 들고 있어 서로 조용히 갈라지던 것이 공통 원인이다.

경계값 SSoT 도입:
- config/core.php `settings_limits` 를 단일 출처로 두고, FormRequest 는 이 값으로
 규칙을 만들고 화면은 설정 응답의 `_meta.limits` 로 같은 값을 받아 바인딩한다.
- 게시판·이커머스도 각 모듈 config 의 limits 를 동일 구조로 노출한다.

적용되지 않던 정책을 실제로 적용:
- 비밀번호 최소 길이·특수문자 필수(신규 지정 7개 경로. 로그인은 제외 — 정책을
 올렸을 때 기존 회원이 자기 계정에 접근조차 못 하는 데드락을 막기 위함)
- 계정 잠금 시간 0 = 무한대(전용 컬럼 분리. timestamp 상한과 NULL 규약 때문에
 기존 컬럼 재사용이 불가능하다) + 관리자 수동 해제 경로
- 업로드 최대 크기·허용 확장자, 게시판 첨부 개수·댓글 깊이, 페이지 첨부 정책,
 장바구니 수량·구매 한도, 마일리지 사용 한도, 주문 부가세

파생 결함:
- 큐 Job(sync 드라이버)이 진행 중인 요청의 Request 바인딩을 덮어써, 뒤이어 실행되는
 훅 리스너가 헤더를 잃고 조용히 건너뛰었다. Job 이 원 바인딩을 복원하도록 고치고,
 전송 헤더가 필요한 리스너는 동기 실행으로 선언한다.
- 확장 업데이트 실패 시 상태만 되돌리고 상태 캐시를 비우지 않아, 그 확장의 관리자
 화면만 캐시 TTL(기본 하루) 동안 404 로 남았다. 실패 경로에도 무효화를 대칭으로
 두고, 빈 목록 자체를 캐시하지 않는다.
- 글 작성 시 첨부 파일이 Service 로 전달되지 않아 검증·권한은 통과하고 첨부만 사라졌다.
- 환경설정 저장 실패 안내가 내부 설정 키를 그대로 노출했다(105개 항목에 라벨 부여).

재발 방지:
- audit 룰 3종(레이아웃 경계 리터럴 / FormRequest 경계 불일치 / Service 재클램프)
- 테스트 실행 범위 강제 훅(check-test-scope)
- 트러블슈팅 사례 2건(큐 Job 요청 오염 / 확장 상태 캐시 고착)

공개 이슈: gnuboard/g7
This commit is contained in:
HeuJung committed 2026-07-30 07:52:24 +09:00
1 parent 5d140dfbe6
commit d17ea28da5
272 files changed
+12431 -1006

No files matched your search

@@ -6,6 +6,11 @@
## [1.0.3] - 2026-07-16
### Security
- 게시판에 설정한 대댓글 최대 깊이가 모든 댓글 등록 경로에서 적용되도록 수정했습니다. 이전에는 글쓰기 화면을 거치는 요청에서만 깊이를 확인해, 연동 기능이 댓글을 직접 등록하면 설정한 깊이를 넘겨 달릴 수 있었습니다. 깊이를 넘긴 답글은 다른 위치로 옮겨 붙이지 않고 사유와 함께 거절합니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 게시판에 설정한 첨부파일 최대 개수가 모든 첨부 경로에서 적용되도록 수정했습니다. 이전에는 글쓰기 화면에서 파일을 직접 첨부할 때만 개수를 확인해, 파일을 먼저 올려 두고 글을 저장하는 방식으로는 상한을 넘겨 첨부할 수 있었습니다. 이제 직접 첨부·미리 올린 파일 연결·이미 첨부된 파일까지 합산해 판정합니다. 이미 상한을 넘겨 등록된 기존 첨부는 그대로 두고 신규 등록만 차단합니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
### Added
- 사이트맵에 담을 게시판·게시글 수의 안전 상한을 지원합니다. 상한을 설정하면 게시판 목록·게시판·게시글 어느 항목이든 그 수를 넘지 않으며, 상한에 걸려 일부가 빠진 경우 기록으로 남습니다.
@@ -19,11 +24,14 @@
### Fixed
- 글을 쓰면서 파일을 함께 첨부하면 글은 저장되는데 첨부파일만 사라지던 문제를 수정했습니다. 첨부 개수·용량·형식 검사와 권한 확인은 모두 통과한 뒤 저장 단계에서만 빠져, 등록된 글에 첨부가 하나도 남지 않았습니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 게시판 신고 정책의 자동 숨김 기준 횟수를 0(자동 숨김 사용 안 함)으로 입력할 수 없던 문제를 수정했습니다. 서버는 0을 "사용 안 함"으로 처리하는데 화면에서만 1 이상을 요구해, 0을 입력하면 저장은 되면서도 입력칸이 계속 오류 상태로 남았습니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 관리자 게시글 목록에서 글을 열어 이전글·다음글로 넘어가거나 수정 후 돌아올 때 보고 있던 페이지·검색어·분류가 사라지던 문제를 수정했습니다. 목록 ↔ 상세 ↔ 이전/다음 글 ↔ 작성·수정 폼 어디로 오가든 목록 상태가 유지되며, 신고 관리와 게시판 목록도 동일하게 개선됐습니다. 새로고침 버튼도 걸어 둔 검색·필터를 지운 채 새로 부르지 않고 보고 있던 목록을 그대로 다시 부릅니다. (#75 @jiwonpapa 님께서 제보해주셨습니다.)
- 관리자 게시글 목록에서 뒤쪽 페이지를 보던 중 검색하거나 게시 상태를 바꾸면 그 페이지 번호가 그대로 유지돼 결과가 없는 빈 화면이 열리던 문제를 수정했습니다. 검색과 상태 변경은 1페이지부터 보여주며, 사용자가 고른 표시 개수와 정렬은 그대로 유지됩니다. 검색창에서 엔터를 치는 경우와 검색 버튼을 누르는 경우가 서로 다르게 동작하던 것도 함께 맞췄습니다. (#75 @jiwonpapa 님께서 제보해주셨습니다.)
- 첨부파일을 사용하지 않는 게시판을 아무것도 바꾸지 않고 저장해도 "허용 파일 확장자를 최소 1개 이상 입력하세요" 오류가 나며 저장이 막히던 문제를 수정했습니다. 첨부를 쓰지 않는 게시판에서는 허용 확장자를 비워 두어도 정상적으로 저장됩니다. 게시판 환경설정의 기본값도 동일하게 동작합니다. (#78 @jiwonpapa 님께서 제보해주셨습니다.)
- 새 글 표시 기간을 "0시간"(새 글 표시 안 함)으로 저장할 수 없던 문제를 수정했습니다. 0은 원래 새 글 배지를 끄는 값으로 동작하도록 되어 있었으나 저장 단계에서 막혀 있었습니다.
- 게시판 환경설정에서 제목·댓글 최소 길이를 0(제한 없음)으로 저장할 수 없던 문제를 수정했습니다. 내용 최소 길이는 0이 허용되어 같은 화면에서 항목마다 동작이 달랐습니다.
- 댓글 계층 정리 시 서로가 서로의 부모로 얽혀 최상위 댓글에서 닿을 수 없는 댓글이 아무 기록 없이 넘어가던 문제를 수정했습니다. 이런 댓글은 내용과 위치를 그대로 보존하되, 정리되지 않았다는 사실이 업데이트 기록에 남아 확인할 수 있습니다.
- 허용 확장자를 지정하지 않은 게시판에서 어떤 파일도 첨부할 수 없던 문제를 수정했습니다. 파일 선택 단계에서 막히던 것과 서버에서 거부되던 것을 함께 고쳐, 확장자를 지정하지 않은 게시판은 기본 확장자 목록을 사용합니다. 첨부 안내에 확장자가 비어 표시되던 것도 함께 해소됩니다. 확장자를 지정한 게시판은 지금처럼 목록에 없는 파일을 계속 거부합니다.
- 게시판 알림 설정에서 저장에 실패해도 아무 안내 없이 넘어가던 화면을 수정했습니다. 실패하면 그 이유가 화면에 표시됩니다.
- 일부 안내 문구가 실제 문장 대신 내부 식별자(`sirsoft-board::messages....` 같은 문자열)로 표시되던 문제를 수정했습니다. 첨부파일이 있는 게시판을 찾지 못했을 때, 댓글 목록을 불러오지 못했을 때, 비회원 댓글의 비밀번호를 확인할 때, 삭제·블라인드된 글에 댓글을 달려 할 때, 권한이 없어 거절될 때가 해당됩니다.
@@ -37,6 +45,7 @@
- 다른 게시글의 댓글을 답글의 부모로 지정할 수 있던 문제를 수정했습니다. 이렇게 만들어진 답글은 어느 게시글 목록에도 나타나지 않았습니다. (#80 @jiwonpapa 님께서 제보해주셨습니다.)
- 대댓글 깊이가 게시판 설정값을 넘어 계속 달리던 문제를 수정했습니다. 예전에는 6단계부터 들여쓰기가 더 들어가지 않고 설정한 최대 깊이도 지켜지지 않았습니다. 이제 설정한 깊이까지만 답글을 달 수 있고 화면의 단계 표시도 정확해집니다. (#80 @jiwonpapa 님께서 제보해주셨습니다.)
- 기존에 쌓인 댓글 중 깊이가 어긋났거나 다른 게시글의 댓글을 부모로 가진 것을 업데이트 시 자동으로 정리합니다. 잘못 연결된 댓글은 삭제하지 않고 최상위 댓글로 옮기며, 내용은 그대로 보존됩니다.
- 연동 기능이 블라인드·삭제된 글에 댓글을 등록하려 할 때 "댓글 등록에 실패했습니다" 라는 서버 오류만 표시되던 문제를 수정했습니다. 이제 글쓰기 화면에서와 똑같이 왜 등록할 수 없는지 사유가 표시됩니다.
## [1.0.2] - 2026-07-14
@@ -154,6 +154,26 @@ return [
// 대댓글 깊이 제한
'max_comment_depth_min' => 0,
'max_comment_depth_max' => 10,
// 신고 정책
'auto_hide_threshold_min' => 0,
'auto_hide_threshold_max' => 100,
'daily_report_limit_min' => 0,
'daily_report_limit_max' => 100,
'rejection_limit_count_min' => 0,
'rejection_limit_count_max' => 50,
'rejection_limit_days_min' => 1,
'rejection_limit_days_max' => 365,
// 스팸/보안 쿨다운 (초)
'post_cooldown_seconds_min' => 0,
'post_cooldown_seconds_max' => 3600,
'comment_cooldown_seconds_min' => 0,
'comment_cooldown_seconds_max' => 3600,
'report_cooldown_seconds_min' => 0,
'report_cooldown_seconds_max' => 3600,
'view_count_cache_ttl_min' => 60,
'view_count_cache_ttl_max' => 604800,
],
/*
@@ -85,6 +85,8 @@ Content-Disposition: form-data; name="temp_key"
**설명** 게시판 관리자가 게시글 첨부파일 1건을 업로드합니다. `auth:sanctum` + admin + 게시판별 `attachments.upload` 권한이 필요하며, `AttachmentService::upload()`가 게시판별 동적 첨부 테이블에 저장합니다. `post_id`가 있으면 해당 게시글에 즉시 귀속되고, 없으면 `temp_key`로 임시 업로드되어 게시글 작성/수정 저장 시점에 연결됩니다. 응답은 FileUploader 컴포넌트 호환을 위해 `data.data`로 한 번 더 감싸 파일 메타(hash·url·order 등)를 반환합니다.
첨부 개수는 게시판 설정 `max_file_count` 를 기준으로 **직접 업로드 · 미리 올려 둔 파일 연결(`attachment_ids`) · 임시 업로드 연결(`temp_key`) · 이미 연결된 첨부** 를 모두 합산해 판정합니다. 상한을 넘으면 `422`(`errors.code = attachment_limit_exceeded`)를 반환하며, 이 판정은 업로드 엔드포인트뿐 아니라 게시글 생성·수정 저장 시점에도 동일하게 적용됩니다. `max_file_count` 가 0 이면 개수를 제한하지 않습니다.
### GET /api/modules/sirsoft-board/admin/board/{slug}/attachments/download/{hash}
<!-- @generated:start:api.modules.sirsoft-board.admin.board.attachments.download -->
@@ -1135,14 +1135,19 @@ describe('_tab_report_policy.json - 신고 정책 탭', () => {
expect(manageTagInputs[0].props.options).toContain('roleOptions');
});
// 허용 범위는 서버가 내려주는 한계값(_meta.limits)을 바인딩한다. 화면이 숫자를 직접 들면
// 저장 규칙과 갈라진다 — 실제로 화면 min:1 ↔ 서버 min:0 으로 어긋나 "0=비활성" 안내대로
// 입력할 수 없던 결함이 있었다(#493 B4).
it('필드에 유효한 min/max 제약이 있다', () => {
const autoHide = findById(tabReportPolicy, 'field_auto_hide_threshold');
const autoHideInput = findByName(autoHide, 'Input').find(
(c: any) => c.props?.name === 'report_policy.auto_hide_threshold'
);
expect(autoHideInput.props.min).toBe(1);
expect(autoHideInput.props.max).toBe(100);
expect(String(autoHideInput.props.min)).toContain('limits?.auto_hide_threshold_min');
expect(String(autoHideInput.props.max)).toContain('limits?.auto_hide_threshold_max');
// 0 = 자동 숨김 비활성. 폴백이 1 로 되돌아가면 비활성으로 되돌릴 방법이 사라진다.
expect(String(autoHideInput.props.min)).toContain('?? 0');
expect(String(autoHideInput.props.max)).toContain('?? 100');
});
it('Select가 composite 타입이다', () => {
@@ -18,8 +18,14 @@
* (구 _tab_basic_defaults.json 은 더 이상 사용하지 않음 — 삭제됨)
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, it, expect } from 'vitest';
import tabReportPolicy from '../../../layouts/admin/partials/admin_board_settings/_tab_report_policy.json';
import tabSpamSecurity from '../../../layouts/admin/partials/admin_board_settings/_tab_spam_security.json';
import tabList from '../../../layouts/admin/partials/admin_board_settings/_tab_board_settings_list.json';
import tabPost from '../../../layouts/admin/partials/admin_board_settings/_tab_board_settings_post.json';
import tabReply from '../../../layouts/admin/partials/admin_board_settings/_tab_board_settings_reply.json';
@@ -88,3 +94,148 @@ describe('게시판 환경설정 — 범위 힌트 동적 바인딩 가드 (#413
},
);
});
/**
* `config/board.php` 의 `limits` 블록을 키 → 값으로 읽는다.
*
* @returns 한계값 키 맵
*/
function configuredLimits(): Record<string, number> {
const moduleRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
const source = fs.readFileSync(path.join(moduleRoot, 'config/board.php'), 'utf-8');
const block = /'limits'\s*=>\s*\[([\s\S]*?)\n\s*\],/.exec(source);
expect(block, "config/board.php 에서 'limits' 블록을 찾지 못했습니다.").not.toBeNull();
const limits: Record<string, number> = {};
for (const line of block![1].split('\n')) {
const matched = /'([a-z0-9_]+)'\s*=>\s*(-?[\d.]+)\s*,/.exec(line);
if (matched) {
limits[matched[1]] = Number(matched[2]);
}
}
return limits;
}
/**
* 레이아웃에서 해당 필드의 min/max prop 표현식을 찾는다.
*
* @param layout 레이아웃 트리
* @param field 필드 name (예: report_policy.auto_hide_threshold)
* @returns min/max 표현식
*/
function boundExpressions(layout: unknown, field: string): { min?: string; max?: string } {
let found: { min?: string; max?: string } = {};
const visit = (node: any) => {
if (!node || typeof node !== 'object') return;
if (Array.isArray(node)) {
node.forEach(visit);
return;
}
if (node.props?.name === field) {
found = { min: node.props.min, max: node.props.max };
}
Object.values(node).forEach(visit);
};
visit(layout);
return found;
}
/**
* 신고 정책 · 스팸 보안 탭의 숫자 필드 — [필드 name, partial, limits 키 prefix].
*
* 이 탭들은 위 목록과 달리 description 범위 힌트를 쓰지 않으므로 Input 경계만 검사한다.
*/
const policyFields: Array<[string, unknown, string]> = [
['report_policy.auto_hide_threshold', tabReportPolicy, 'auto_hide_threshold'],
['report_policy.daily_report_limit', tabReportPolicy, 'daily_report_limit'],
['report_policy.rejection_limit_count', tabReportPolicy, 'rejection_limit_count'],
['report_policy.rejection_limit_days', tabReportPolicy, 'rejection_limit_days'],
['spam_security.report_cooldown_seconds', tabReportPolicy, 'report_cooldown_seconds'],
['spam_security.post_cooldown_seconds', tabSpamSecurity, 'post_cooldown_seconds'],
['spam_security.comment_cooldown_seconds', tabSpamSecurity, 'comment_cooldown_seconds'],
['spam_security.view_count_cache_ttl', tabSpamSecurity, 'view_count_cache_ttl'],
];
describe('게시판 환경설정 — 신고 정책 · 스팸 보안 탭 경계값 (#493 B4)', () => {
const limits = configuredLimits();
it.each(policyFields)('%s — min/max 가 한계값 설정을 읽는다', (field, layout, limitsKey) => {
const bounds = boundExpressions(layout, field);
for (const bound of ['min', 'max'] as const) {
expect(bounds[bound], `${field} 에 ${bound} 이 없습니다.`).toBeDefined();
expect(String(bounds[bound])).toContain(`limits?.${limitsKey}_${bound}`);
}
});
it.each(policyFields)('%s — 폴백이 설정 파일의 한계값과 같다', (field, layout, limitsKey) => {
const bounds = boundExpressions(layout, field);
for (const bound of ['min', 'max'] as const) {
const matched = /\?\?\s*(-?[\d.]+)\s*\}\}/.exec(String(bounds[bound]));
expect(matched, `${field} 의 ${bound} 폴백을 찾지 못했습니다.`).not.toBeNull();
expect(Number(matched![1]), `${field} 의 ${bound} 폴백이 설정 파일 값과 다릅니다.`).toBe(
limits[`${limitsKey}_${bound}`],
);
}
});
it('자동 숨김 기준은 0(비활성)을 입력할 수 있다', () => {
// 화면이 min=1 이면 "0=비활성" 안내와 어긋나 비활성으로 되돌릴 방법이 없어진다.
expect(limits.auto_hide_threshold_min).toBe(0);
expect(boundExpressions(tabReportPolicy, 'report_policy.auto_hide_threshold').min).toContain('?? 0');
});
});
/**
* 서버 저장 규칙(`StoreBoardSettingsRequest`) 원문.
*/
function settingsRequestSource(): string {
const moduleRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
return fs.readFileSync(
path.join(moduleRoot, 'src/Http/Requests/Admin/StoreBoardSettingsRequest.php'),
'utf-8',
);
}
describe('게시판 환경설정 — 서버 저장 규칙 정합 (#493 B4)', () => {
const limits = configuredLimits();
const requestSource = settingsRequestSource();
/**
* 이 화면에는 네이티브 `<form>` 이 없다. 저장은 `apiCall` 이 `_local.form` 을 직접 실어
* 보내므로 Input 의 `min`/`max` 속성은 브라우저 제출을 막지 못한다 — 안내일 뿐이다.
* 그래서 실제 관문은 서버 규칙 하나뿐이고, 화면과 규칙이 어긋나면 화면이 거부하는
* 것처럼 보이는 값이 200 으로 저장된다(B4 의 최초 증상).
*
* 세 지점(설정 파일 · 서버 규칙 · 화면 바인딩)이 같은 키·같은 폴백을 가리키는지 대조한다.
*/
it.each(policyFields)('%s — 서버 규칙이 화면과 같은 한계값 키를 읽는다', (field, layout, limitsKey) => {
const rule = new RegExp(`'${field.replace('.', '\\.')}'\\s*=>\\s*\\[([^\\]]*)\\]`).exec(requestSource);
expect(rule, `${field} 의 저장 규칙을 찾지 못했습니다.`).not.toBeNull();
for (const bound of ['min', 'max'] as const) {
// 화면이 읽는 키와 규칙이 읽는 키가 같아야 한다
expect(String(boundExpressions(layout, field)[bound])).toContain(`limits?.${limitsKey}_${bound}`);
expect(rule![1], `${field} 의 ${bound} 규칙이 한계값 설정을 읽지 않습니다.`)
.toContain(`'${limitsKey}_${bound}'`);
// 규칙의 폴백도 설정 파일 값과 같아야 한다 (설정이 비었을 때 양쪽이 갈라지지 않도록)
const fallback = new RegExp(`'${limitsKey}_${bound}',\\s*(-?[\\d.]+)\\)`).exec(rule![1]);
expect(fallback, `${field} 의 ${bound} 규칙 폴백을 찾지 못했습니다.`).not.toBeNull();
expect(Number(fallback![1]), `${field} 의 ${bound} 규칙 폴백이 설정 파일 값과 다릅니다.`)
.toBe(limits[`${limitsKey}_${bound}`]);
}
});
});
@@ -578,8 +578,8 @@
"props": {
"type": "number",
"name": "basic_defaults.new_display_hours",
"min": 1,
"max": 720,
"min": "{{_local?.form?._meta?.limits?.new_display_hours_min ?? 1}}",
"max": "{{_local?.form?._meta?.limits?.new_display_hours_max ?? 720}}",
"className": "{{(_local.errors?.['basic_defaults.new_display_hours']) ? 'w-32 input-error' : 'w-32'}}",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -55,8 +55,7 @@
"id": "field_auto_hide_threshold",
"type": "basic",
"name": "Div",
"props": {
},
"props": {},
"children": [
{
"type": "basic",
@@ -78,8 +77,8 @@
"props": {
"type": "number",
"name": "report_policy.auto_hide_threshold",
"min": 1,
"max": 100,
"min": "{{_local?.form?._meta?.limits?.auto_hide_threshold_min ?? 0}}",
"max": "{{_local?.form?._meta?.limits?.auto_hide_threshold_max ?? 100}}",
"className": "{{(_local.errors?.['report_policy.auto_hide_threshold']) ? 'input-error' : ''}}",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -107,8 +106,7 @@
"id": "field_auto_hide_target",
"type": "basic",
"name": "Div",
"props": {
},
"props": {},
"children": [
{
"type": "basic",
@@ -197,8 +195,7 @@
"id": "field_daily_report_limit",
"type": "basic",
"name": "Div",
"props": {
},
"props": {},
"children": [
{
"type": "basic",
@@ -220,8 +217,8 @@
"props": {
"type": "number",
"name": "report_policy.daily_report_limit",
"min": 0,
"max": 100,
"min": "{{_local?.form?._meta?.limits?.daily_report_limit_min ?? 0}}",
"max": "{{_local?.form?._meta?.limits?.daily_report_limit_max ?? 100}}",
"className": "{{(_local.errors?.['report_policy.daily_report_limit']) ? 'input-error' : ''}}",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -249,8 +246,7 @@
"id": "field_rejection_limit",
"type": "basic",
"name": "Div",
"props": {
},
"props": {},
"children": [
{
"type": "basic",
@@ -295,8 +291,8 @@
"props": {
"type": "number",
"name": "report_policy.rejection_limit_count",
"min": 0,
"max": 50,
"min": "{{_local?.form?._meta?.limits?.rejection_limit_count_min ?? 0}}",
"max": "{{_local?.form?._meta?.limits?.rejection_limit_count_max ?? 50}}",
"className": "{{(_local.errors?.['report_policy.rejection_limit_count']) ? 'input-error' : ''}}",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -336,8 +332,8 @@
"props": {
"type": "number",
"name": "report_policy.rejection_limit_days",
"min": 1,
"max": 365,
"min": "{{_local?.form?._meta?.limits?.rejection_limit_days_min ?? 1}}",
"max": "{{_local?.form?._meta?.limits?.rejection_limit_days_max ?? 365}}",
"className": "{{(_local.errors?.['report_policy.rejection_limit_days']) ? 'input-error' : ''}}",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -396,8 +392,8 @@
"props": {
"type": "number",
"name": "spam_security.report_cooldown_seconds",
"min": 0,
"max": 3600,
"min": "{{_local?.form?._meta?.limits?.report_cooldown_seconds_min ?? 0}}",
"max": "{{_local?.form?._meta?.limits?.report_cooldown_seconds_max ?? 3600}}",
"className": "{{(_local.errors?.['spam_security.report_cooldown_seconds']) ? 'input-error' : ''}}",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -420,8 +416,7 @@
"text": "$t:sirsoft-board.admin.settings.fields.report_cooldown_seconds_hint"
}
],
"props": {
}
"props": {}
}
],
"props": {
@@ -468,8 +463,7 @@
"id": "field_report_view_roles",
"type": "basic",
"name": "Div",
"props": {
},
"props": {},
"children": [
{
"type": "basic",
@@ -553,8 +547,7 @@
"text": "{{(Array.isArray(_local.errors?.['report_permissions.manage_roles']) ? _local.errors['report_permissions.manage_roles'][0] : _local.errors?.['report_permissions.manage_roles']) ?? ''}}"
}
],
"props": {
}
"props": {}
}
],
"props": {
@@ -707,7 +700,9 @@
"id": "report_received_admin_template_status",
"type": "basic",
"name": "Div",
"props": { "className": "space-y-2" },
"props": {
"className": "space-y-2"
},
"children": [
{
"type": "basic",
@@ -717,33 +712,70 @@
"item_var": "tpl",
"index_var": "tplIndex"
},
"props": { "className": "flex items-center justify-between gap-2 px-3 py-2 rounded-lg bg-gray-50 dark:bg-gray-700/40" },
"props": {
"className": "flex items-center justify-between gap-2 px-3 py-2 rounded-lg bg-gray-50 dark:bg-gray-700/40"
},
"children": [
{
"type": "basic",
"name": "Div",
"props": { "className": "flex items-center gap-2 min-w-0" },
"props": {
"className": "flex items-center gap-2 min-w-0"
},
"children": [
{ "type": "basic", "name": "Icon", "props": { "name": "{{tpl.channel === 'mail' ? 'envelope' : 'bell'}}", "size": "sm", "className": "text-gray-400 dark:text-gray-500 flex-shrink-0" } },
{
"type": "basic",
"name": "Icon",
"props": {
"name": "{{tpl.channel === 'mail' ? 'envelope' : 'bell'}}",
"size": "sm",
"className": "text-gray-400 dark:text-gray-500 flex-shrink-0"
}
},
{
"type": "basic",
"name": "Div",
"props": { "className": "min-w-0" },
"props": {
"className": "min-w-0"
},
"children": [
{ "type": "basic", "name": "Span", "props": { "className": "block text-xs font-medium text-gray-500 dark:text-gray-400" }, "text": "{{tpl.channel === 'mail' ? $t('sirsoft-board.admin.settings.fields.notification_channels.mail') : (tpl.channel === 'database' ? $t('sirsoft-board.admin.settings.fields.notification_channels.database') : tpl.channel)}}" },
{ "type": "basic", "name": "Span", "props": { "className": "block text-sm text-gray-800 dark:text-gray-200 truncate" }, "text": "{{tpl.subject?.[$locale] ?? tpl.subject?.ko ?? $t('sirsoft-board.admin.settings.fields.report_notification_template_status_empty')}}" }
{
"type": "basic",
"name": "Span",
"props": {
"className": "block text-xs font-medium text-gray-500 dark:text-gray-400"
},
"text": "{{tpl.channel === 'mail' ? $t('sirsoft-board.admin.settings.fields.notification_channels.mail') : (tpl.channel === 'database' ? $t('sirsoft-board.admin.settings.fields.notification_channels.database') : tpl.channel)}}"
},
{
"type": "basic",
"name": "Span",
"props": {
"className": "block text-sm text-gray-800 dark:text-gray-200 truncate"
},
"text": "{{tpl.subject?.[$locale] ?? tpl.subject?.ko ?? $t('sirsoft-board.admin.settings.fields.report_notification_template_status_empty')}}"
}
]
}
]
},
{ "type": "basic", "name": "Span", "props": { "className": "{{tpl.is_active ? 'bg-green-50 text-green-700 dark:bg-green-900/30 dark:text-green-300' : 'bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-400'}} inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium flex-shrink-0" }, "text": "{{tpl.is_active ? $t('sirsoft-board.admin.settings.fields.report_notification_template_status_active') : $t('sirsoft-board.admin.settings.fields.report_notification_template_status_inactive')}}" }
{
"type": "basic",
"name": "Span",
"props": {
"className": "{{tpl.is_active ? 'bg-green-50 text-green-700 dark:bg-green-900/30 dark:text-green-300' : 'bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-400'}} inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium flex-shrink-0"
},
"text": "{{tpl.is_active ? $t('sirsoft-board.admin.settings.fields.report_notification_template_status_active') : $t('sirsoft-board.admin.settings.fields.report_notification_template_status_inactive')}}"
}
]
},
{
"type": "basic",
"name": "Div",
"if": "{{(((boardNotificationDefinitions?.data?.data ?? []).find(d => d.type === 'report_received_admin')?.templates) ?? []).length === 0}}",
"props": { "className": "px-3 py-2 text-sm text-gray-400 dark:text-gray-500" },
"props": {
"className": "px-3 py-2 text-sm text-gray-400 dark:text-gray-500"
},
"text": "$t:sirsoft-board.admin.settings.fields.report_notification_template_status_empty"
}
]
@@ -751,29 +783,66 @@
{
"type": "basic",
"name": "Div",
"props": { "className": "flex items-center justify-between gap-2 flex-wrap mt-1" },
"props": {
"className": "flex items-center justify-between gap-2 flex-wrap mt-1"
},
"children": [
{ "type": "basic", "name": "Span", "props": { "className": "block text-xs text-gray-400 dark:text-gray-500" }, "text": "$t:sirsoft-board.admin.settings.fields.report_notification_template_status_hint" },
{
"type": "basic",
"name": "Span",
"props": {
"className": "block text-xs text-gray-400 dark:text-gray-500"
},
"text": "$t:sirsoft-board.admin.settings.fields.report_notification_template_status_hint"
},
{
"id": "go_to_notification_settings_admin",
"type": "basic",
"name": "Button",
"props": { "type": "button", "className": "flex items-center gap-1.5 px-3 py-2 text-sm bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors" },
"props": {
"type": "button",
"className": "flex items-center gap-1.5 px-3 py-2 text-sm bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
},
"actions": [
{
"type": "click",
"handler": "sequence",
"params": {
"actions": [
{ "handler": "setState", "params": { "target": "global", "activeBoardSettingsTab": "notification_definitions" } },
{ "comment": "audit:allow layout-list-context-navigate-merge-query 다른 탭으로 넘어가는 이동이다 — 알림 정의 탭은 자기 검색어와 페이지를 따로 갖는 별개의 목록이라 신고 정책 탭의 조건을 물려주지 않는다.", "handler": "replaceUrl", "params": { "query": { "tab": "notification_definitions" } } }
{
"handler": "setState",
"params": {
"target": "global",
"activeBoardSettingsTab": "notification_definitions"
}
},
{
"comment": "audit:allow layout-list-context-navigate-merge-query 다른 탭으로 넘어가는 이동이다 — 알림 정의 탭은 자기 검색어와 페이지를 따로 갖는 별개의 목록이라 신고 정책 탭의 조건을 물려주지 않는다.",
"handler": "replaceUrl",
"params": {
"query": {
"tab": "notification_definitions"
}
}
}
]
}
}
],
"children": [
{ "type": "basic", "name": "Icon", "props": { "name": "arrow-up-right-from-square", "size": "sm" } },
{ "type": "basic", "name": "Span", "text": "$t:sirsoft-board.admin.settings.fields.report_notification_go_to_settings" }
{
"type": "basic",
"name": "Icon",
"props": {
"name": "arrow-up-right-from-square",
"size": "sm"
}
},
{
"type": "basic",
"name": "Span",
"text": "$t:sirsoft-board.admin.settings.fields.report_notification_go_to_settings"
}
]
}
]
@@ -856,7 +925,9 @@
"id": "report_action_template_status",
"type": "basic",
"name": "Div",
"props": { "className": "space-y-2" },
"props": {
"className": "space-y-2"
},
"children": [
{
"type": "basic",
@@ -866,33 +937,70 @@
"item_var": "tpl",
"index_var": "tplIndex"
},
"props": { "className": "flex items-center justify-between gap-2 px-3 py-2 rounded-lg bg-gray-50 dark:bg-gray-700/40" },
"props": {
"className": "flex items-center justify-between gap-2 px-3 py-2 rounded-lg bg-gray-50 dark:bg-gray-700/40"
},
"children": [
{
"type": "basic",
"name": "Div",
"props": { "className": "flex items-center gap-2 min-w-0" },
"props": {
"className": "flex items-center gap-2 min-w-0"
},
"children": [
{ "type": "basic", "name": "Icon", "props": { "name": "{{tpl.channel === 'mail' ? 'envelope' : 'bell'}}", "size": "sm", "className": "text-gray-400 dark:text-gray-500 flex-shrink-0" } },
{
"type": "basic",
"name": "Icon",
"props": {
"name": "{{tpl.channel === 'mail' ? 'envelope' : 'bell'}}",
"size": "sm",
"className": "text-gray-400 dark:text-gray-500 flex-shrink-0"
}
},
{
"type": "basic",
"name": "Div",
"props": { "className": "min-w-0" },
"props": {
"className": "min-w-0"
},
"children": [
{ "type": "basic", "name": "Span", "props": { "className": "block text-xs font-medium text-gray-500 dark:text-gray-400" }, "text": "{{tpl.channel === 'mail' ? $t('sirsoft-board.admin.settings.fields.notification_channels.mail') : (tpl.channel === 'database' ? $t('sirsoft-board.admin.settings.fields.notification_channels.database') : tpl.channel)}}" },
{ "type": "basic", "name": "Span", "props": { "className": "block text-sm text-gray-800 dark:text-gray-200 truncate" }, "text": "{{tpl.subject?.[$locale] ?? tpl.subject?.ko ?? $t('sirsoft-board.admin.settings.fields.report_notification_template_status_empty')}}" }
{
"type": "basic",
"name": "Span",
"props": {
"className": "block text-xs font-medium text-gray-500 dark:text-gray-400"
},
"text": "{{tpl.channel === 'mail' ? $t('sirsoft-board.admin.settings.fields.notification_channels.mail') : (tpl.channel === 'database' ? $t('sirsoft-board.admin.settings.fields.notification_channels.database') : tpl.channel)}}"
},
{
"type": "basic",
"name": "Span",
"props": {
"className": "block text-sm text-gray-800 dark:text-gray-200 truncate"
},
"text": "{{tpl.subject?.[$locale] ?? tpl.subject?.ko ?? $t('sirsoft-board.admin.settings.fields.report_notification_template_status_empty')}}"
}
]
}
]
},
{ "type": "basic", "name": "Span", "props": { "className": "{{tpl.is_active ? 'bg-green-50 text-green-700 dark:bg-green-900/30 dark:text-green-300' : 'bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-400'}} inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium flex-shrink-0" }, "text": "{{tpl.is_active ? $t('sirsoft-board.admin.settings.fields.report_notification_template_status_active') : $t('sirsoft-board.admin.settings.fields.report_notification_template_status_inactive')}}" }
{
"type": "basic",
"name": "Span",
"props": {
"className": "{{tpl.is_active ? 'bg-green-50 text-green-700 dark:bg-green-900/30 dark:text-green-300' : 'bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-400'}} inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium flex-shrink-0"
},
"text": "{{tpl.is_active ? $t('sirsoft-board.admin.settings.fields.report_notification_template_status_active') : $t('sirsoft-board.admin.settings.fields.report_notification_template_status_inactive')}}"
}
]
},
{
"type": "basic",
"name": "Div",
"if": "{{(((boardNotificationDefinitions?.data?.data ?? []).find(d => d.type === 'report_action')?.templates) ?? []).length === 0}}",
"props": { "className": "px-3 py-2 text-sm text-gray-400 dark:text-gray-500" },
"props": {
"className": "px-3 py-2 text-sm text-gray-400 dark:text-gray-500"
},
"text": "$t:sirsoft-board.admin.settings.fields.report_notification_template_status_empty"
}
]
@@ -900,29 +1008,66 @@
{
"type": "basic",
"name": "Div",
"props": { "className": "flex items-center justify-between gap-2 flex-wrap mt-1" },
"props": {
"className": "flex items-center justify-between gap-2 flex-wrap mt-1"
},
"children": [
{ "type": "basic", "name": "Span", "props": { "className": "block text-xs text-gray-400 dark:text-gray-500" }, "text": "$t:sirsoft-board.admin.settings.fields.report_notification_template_status_hint" },
{
"type": "basic",
"name": "Span",
"props": {
"className": "block text-xs text-gray-400 dark:text-gray-500"
},
"text": "$t:sirsoft-board.admin.settings.fields.report_notification_template_status_hint"
},
{
"id": "go_to_notification_settings_author",
"type": "basic",
"name": "Button",
"props": { "type": "button", "className": "flex items-center gap-1.5 px-3 py-2 text-sm bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors" },
"props": {
"type": "button",
"className": "flex items-center gap-1.5 px-3 py-2 text-sm bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
},
"actions": [
{
"type": "click",
"handler": "sequence",
"params": {
"actions": [
{ "handler": "setState", "params": { "target": "global", "activeBoardSettingsTab": "notification_definitions" } },
{ "comment": "audit:allow layout-list-context-navigate-merge-query 다른 탭으로 넘어가는 이동이다 — 알림 정의 탭은 자기 검색어와 페이지를 따로 갖는 별개의 목록이라 신고 정책 탭의 조건을 물려주지 않는다.", "handler": "replaceUrl", "params": { "query": { "tab": "notification_definitions" } } }
{
"handler": "setState",
"params": {
"target": "global",
"activeBoardSettingsTab": "notification_definitions"
}
},
{
"comment": "audit:allow layout-list-context-navigate-merge-query 다른 탭으로 넘어가는 이동이다 — 알림 정의 탭은 자기 검색어와 페이지를 따로 갖는 별개의 목록이라 신고 정책 탭의 조건을 물려주지 않는다.",
"handler": "replaceUrl",
"params": {
"query": {
"tab": "notification_definitions"
}
}
}
]
}
}
],
"children": [
{ "type": "basic", "name": "Icon", "props": { "name": "arrow-up-right-from-square", "size": "sm" } },
{ "type": "basic", "name": "Span", "text": "$t:sirsoft-board.admin.settings.fields.report_notification_go_to_settings" }
{
"type": "basic",
"name": "Icon",
"props": {
"name": "arrow-up-right-from-square",
"size": "sm"
}
},
{
"type": "basic",
"name": "Span",
"text": "$t:sirsoft-board.admin.settings.fields.report_notification_go_to_settings"
}
]
}
]
@@ -938,8 +1083,7 @@
]
}
],
"props": {
}
"props": {}
}
]
}
@@ -47,8 +47,7 @@
"id": "field_post_cooldown_seconds",
"type": "basic",
"name": "Div",
"props": {
},
"props": {},
"children": [
{
"type": "basic",
@@ -70,8 +69,8 @@
"props": {
"type": "number",
"name": "spam_security.post_cooldown_seconds",
"min": 0,
"max": 3600,
"min": "{{_local?.form?._meta?.limits?.post_cooldown_seconds_min ?? 0}}",
"max": "{{_local?.form?._meta?.limits?.post_cooldown_seconds_max ?? 3600}}",
"className": "{{(_local.errors?.['spam_security.post_cooldown_seconds']) ? 'input-error' : ''}}",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -99,8 +98,7 @@
"id": "field_comment_cooldown_seconds",
"type": "basic",
"name": "Div",
"props": {
},
"props": {},
"children": [
{
"type": "basic",
@@ -122,8 +120,8 @@
"props": {
"type": "number",
"name": "spam_security.comment_cooldown_seconds",
"min": 0,
"max": 3600,
"min": "{{_local?.form?._meta?.limits?.comment_cooldown_seconds_min ?? 0}}",
"max": "{{_local?.form?._meta?.limits?.comment_cooldown_seconds_max ?? 3600}}",
"className": "{{(_local.errors?.['spam_security.comment_cooldown_seconds']) ? 'input-error' : ''}}",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -176,8 +174,8 @@
"props": {
"type": "number",
"name": "spam_security.view_count_cache_ttl",
"min": 60,
"max": 604800,
"min": "{{_local?.form?._meta?.limits?.view_count_cache_ttl_min ?? 60}}",
"max": "{{_local?.form?._meta?.limits?.view_count_cache_ttl_max ?? 604800}}",
"className": "{{(_local.errors?.['spam_security.view_count_cache_ttl']) ? 'input-error' : ''}}",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -200,8 +198,7 @@
"text": "$t:sirsoft-board.admin.settings.fields.view_count_cache_ttl_hint"
}
],
"props": {
}
"props": {}
}
],
"props": {
@@ -379,8 +376,7 @@
]
}
],
"props": {
}
"props": {}
}
]
}
@@ -0,0 +1,64 @@
<?php
namespace Modules\Sirsoft\Board\Exceptions;
use App\Helpers\ResponseHelper;
use Exception;
use Illuminate\Http\JsonResponse;
/**
* 첨부파일 개수 상한 초과 예외
*
* 게시판 설정 `max_file_count` 를 초과해 첨부를 연결하려 할 때 발생합니다.
* 직접 업로드·`attachment_ids` 연결·`temp_key` 연결 등 어떤 경로로 들어와도 동일하게
* 이 예외로 차단되며, 컨트롤러가 422 로 매핑합니다.
*
* `render()` 는 컨트롤러 밖(요청 단계 선차단)에서 던져진 경우를 위한 것입니다 — 응답 형태를
* 컨트롤러 catch 와 **동일하게** 유지해, 같은 조건에 두 가지 응답 형태가 생기지 않게 합니다.
*/
class AttachmentLimitExceededException extends Exception
{
/**
* @param int $limit 게시판이 허용하는 최대 첨부 개수
* @param int $attempted 연결하려 한 총 첨부 개수
*/
public function __construct(
private int $limit,
private int $attempted,
) {
parent::__construct(__('sirsoft-board::messages.errors.attachment_limit_exceeded', [
'limit' => $limit,
'attempted' => $attempted,
]));
}
/**
* 허용 최대 개수를 반환합니다.
*
* @return int 최대 첨부 개수
*/
public function getLimit(): int
{
return $this->limit;
}
/**
* 시도한 총 개수를 반환합니다.
*
* @return int 연결 시도 개수
*/
public function getAttempted(): int
{
return $this->attempted;
}
/**
* 컨트롤러 catch 와 동일한 422 응답으로 렌더링합니다.
*
* @return JsonResponse 상한 초과 응답
*/
public function render(): JsonResponse
{
return ResponseHelper::error($this->getMessage(), 422, ['code' => 'attachment_limit_exceeded']);
}
}
@@ -0,0 +1,51 @@
<?php
namespace Modules\Sirsoft\Board\Exceptions;
use Exception;
/**
* 대댓글 깊이 상한 초과 예외
*
* 게시판 설정 `max_comment_depth` 를 넘는 깊이로 댓글을 달려 할 때 발생합니다.
* `CommentValidationRule` 이 요청 단계에서 선차단하지만, 훅이나 Service 직접 호출처럼
* FormRequest 를 거치지 않는 경로가 있으므로 최종 불변조건은 Service 가 보장합니다.
*
* 클램프하지 않고 예외를 던집니다 — 요청한 위치와 다른 자리에 조용히 댓글이 붙으면
* 사용자는 자기 답글이 엉뚱한 대화에 달린 것을 알 수 없습니다.
*/
class CommentDepthExceededException extends Exception
{
/**
* @param int $limit 게시판이 허용하는 최대 깊이
* @param int $attempted 달려고 한 깊이
*/
public function __construct(
private int $limit,
private int $attempted,
) {
parent::__construct(__('sirsoft-board::validation.comment.depth.exceeded', [
'max' => $limit,
]));
}
/**
* 허용 최대 깊이를 반환합니다.
*
* @return int 최대 깊이
*/
public function getLimit(): int
{
return $this->limit;
}
/**
* 시도한 깊이를 반환합니다.
*
* @return int 시도 깊이
*/
public function getAttempted(): int
{
return $this->attempted;
}
}
@@ -0,0 +1,59 @@
<?php
namespace Modules\Sirsoft\Board\Exceptions;
use Exception;
/**
* 댓글 작성 불가 게시글 상태 예외
*
* 블라인드되었거나 삭제된 게시글에 댓글을 달려 할 때 발생합니다.
* `CommentValidationRule` 이 요청 단계에서 선차단하지만, 훅이나 Service 직접 호출처럼
* FormRequest 를 거치지 않는 경로가 있으므로 최종 불변조건은 Service 가 보장합니다.
*
* 베이스 `\Exception` 을 던지면 컨트롤러의 제네릭 catch 에 흡수되어 500 + 일반 문구가 되고
* 거절 사유가 사라집니다. 사용자가 고칠 수 있는 상태 문제이므로 422 로 매핑합니다.
*/
class PostNotCommentableException extends Exception
{
/**
* @param string $reason 거절 사유 (blinded | deleted)
* @param string $message 사용자에게 보일 메시지
*/
public function __construct(
private string $reason,
string $message,
) {
parent::__construct($message);
}
/**
* 블라인드된 게시글에 대한 예외를 생성합니다.
*
* @return self 블라인드 사유 예외
*/
public static function blinded(): self
{
return new self('blinded', __('sirsoft-board::messages.comment.post_blinded'));
}
/**
* 삭제된 게시글에 대한 예외를 생성합니다.
*
* @return self 삭제 사유 예외
*/
public static function deleted(): self
{
return new self('deleted', __('sirsoft-board::messages.comment.post_deleted'));
}
/**
* 거절 사유를 반환합니다.
*
* @return string 거절 사유 (blinded | deleted)
*/
public function getReason(): string
{
return $this->reason;
}
}
@@ -4,6 +4,7 @@ namespace Modules\Sirsoft\Board\Http\Controllers\Admin;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Http\JsonResponse;
use Modules\Sirsoft\Board\Exceptions\AttachmentLimitExceededException;
use Modules\Sirsoft\Board\Exceptions\BoardNotFoundException;
use Modules\Sirsoft\Board\Http\Requests\ReorderAttachmentsRequest;
use Modules\Sirsoft\Board\Http\Requests\UploadAttachmentRequest;
@@ -81,6 +82,9 @@ class AttachmentController extends AdminBaseController
],
201
);
} catch (AttachmentLimitExceededException $e) {
// 게시판 첨부 개수 상한 초과 — generic 500 이 아닌 422 명시 차단
return $this->error($e->getMessage(), 422, ['code' => 'attachment_limit_exceeded']);
} catch (BoardNotFoundException $e) {
return $this->error('sirsoft-board::messages.boards.not_found', 404);
} catch (\Exception $e) {
@@ -6,6 +6,8 @@ use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Modules\Sirsoft\Board\Exceptions\CommentDepthExceededException;
use Modules\Sirsoft\Board\Exceptions\PostNotCommentableException;
use Modules\Sirsoft\Board\Http\Requests\BlindCommentRequest;
use Modules\Sirsoft\Board\Http\Requests\RestoreCommentRequest;
use Modules\Sirsoft\Board\Http\Requests\StoreCommentRequest;
@@ -110,6 +112,12 @@ class CommentController extends AdminBaseController
);
} catch (ModelNotFoundException) {
return $this->notFound('sirsoft-board::messages.boards.not_found');
} catch (CommentDepthExceededException $e) {
// 요청 단계 검증을 우회해 Service 관문에 걸린 경우 — 사용자 입력 문제이므로 422
return $this->error($e->getMessage(), 422);
} catch (PostNotCommentableException $e) {
// 블라인드·삭제된 게시글 — 서버 오류가 아니라 게시글 상태 문제이므로 422 + 사유 전달
return $this->error($e->getMessage(), 422);
} catch (\Exception $e) {
return $this->error('sirsoft-board::messages.comment.create_failed', 500, $e->getMessage());
}
@@ -8,6 +8,7 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Modules\Sirsoft\Board\Enums\PostStatus;
use Modules\Sirsoft\Board\Exceptions\AttachmentLimitExceededException;
use Modules\Sirsoft\Board\Exceptions\BoardNotFoundException;
use Modules\Sirsoft\Board\Exceptions\PostNotFoundException;
use Modules\Sirsoft\Board\Http\Requests\BlindPostRequest;
@@ -193,6 +194,9 @@ class PostController extends AdminBaseController
new PostResource($post),
201
);
} catch (AttachmentLimitExceededException $e) {
// 게시판 첨부 개수 상한 초과 — generic 500 이 아닌 422 명시 차단
return $this->error($e->getMessage(), 422, ['code' => 'attachment_limit_exceeded']);
} catch (\Exception $e) {
return $this->error('sirsoft-board::messages.posts.create_failed', 500, $e->getMessage());
}
@@ -245,6 +249,9 @@ class PostController extends AdminBaseController
'sirsoft-board::messages.posts.update_success',
new PostResource($post)
);
} catch (AttachmentLimitExceededException $e) {
// 게시판 첨부 개수 상한 초과 — generic 500 이 아닌 422 명시 차단
return $this->error($e->getMessage(), 422, ['code' => 'attachment_limit_exceeded']);
} catch (ModelNotFoundException $e) {
throw new PostNotFoundException($id);
} catch (AccessDeniedHttpException $e) {
@@ -6,6 +6,7 @@ use App\Http\Controllers\Api\Base\PublicBaseController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Modules\Sirsoft\Board\Exceptions\AttachmentLimitExceededException;
use Modules\Sirsoft\Board\Exceptions\BoardNotFoundException;
use Modules\Sirsoft\Board\Http\Requests\ReorderAttachmentsRequest;
use Modules\Sirsoft\Board\Http\Requests\UploadAttachmentRequest;
@@ -175,6 +176,9 @@ class AttachmentController extends PublicBaseController
],
201
);
} catch (AttachmentLimitExceededException $e) {
// 게시판 첨부 개수 상한 초과 — generic 500 이 아닌 422 명시 차단
return $this->error($e->getMessage(), 422, ['code' => 'attachment_limit_exceeded']);
} catch (BoardNotFoundException $e) {
return $this->notFound(__('sirsoft-board::messages.boards.not_found'));
} catch (\Exception $e) {
@@ -8,6 +8,8 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Modules\Sirsoft\Board\Exceptions\CommentDepthExceededException;
use Modules\Sirsoft\Board\Exceptions\PostNotCommentableException;
use Modules\Sirsoft\Board\Http\Requests\StoreCommentRequest;
use Modules\Sirsoft\Board\Http\Requests\UpdateCommentRequest;
use Modules\Sirsoft\Board\Http\Requests\VerifyCommentPasswordRequest;
@@ -114,6 +116,12 @@ class CommentController extends PublicBaseController
);
} catch (ModelNotFoundException) {
return $this->error('sirsoft-board::messages.boards.not_found', 404);
} catch (CommentDepthExceededException $e) {
// 요청 단계 검증을 우회해 Service 관문에 걸린 경우 — 사용자 입력 문제이므로 422
return $this->error($e->getMessage(), 422);
} catch (PostNotCommentableException $e) {
// 블라인드·삭제된 게시글 — 서버 오류가 아니라 게시글 상태 문제이므로 422 + 사유 전달
return $this->error($e->getMessage(), 422);
} catch (\Exception $e) {
return $this->error('sirsoft-board::messages.comment.create_failed', 500);
}
@@ -14,6 +14,7 @@ use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Modules\Sirsoft\Board\Enums\PostStatus;
use Modules\Sirsoft\Board\Enums\SecretMode;
use Modules\Sirsoft\Board\Exceptions\AttachmentLimitExceededException;
use Modules\Sirsoft\Board\Exceptions\BoardNotFoundException;
use Modules\Sirsoft\Board\Exceptions\PostNotFoundException;
use Modules\Sirsoft\Board\Http\Requests\User\StorePostRequest;
@@ -320,7 +321,11 @@ class PostController extends PublicBaseController
// secret_mode='enabled'인 경우 사용자 선택에 따름 (별도 처리 불필요)
// 게시글 생성
$post = $this->postService->createPost($slug, $data);
// `files[]` 를 Service 로 넘기지 않으면 검증·권한 확인은 통과하고 첨부만 조용히
// 사라진다 (201 + 첨부 0 건). 위에서 이미 `hasFile('files')` 로 업로드 권한을
// 확인하고 있으므로 이 경로가 파일을 받는다는 의도는 명확하다.
$files = $request->file('files');
$post = $this->postService->createPost($slug, $data, is_array($files) ? $files : []);
// 쿨다운 캐시 기록 (게시글 생성 성공 후)
$spamSecurity = g7_module_settings('sirsoft-board', 'spam_security', []);
@@ -338,6 +343,9 @@ class PostController extends PublicBaseController
new PostResource($post),
201
);
} catch (AttachmentLimitExceededException $e) {
// 게시판 첨부 개수 상한 초과 — generic 500 이 아닌 422 명시 차단
return $this->error($e->getMessage(), 422, ['code' => 'attachment_limit_exceeded']);
} catch (BoardNotFoundException $e) {
throw $e;
} catch (\Exception $e) {
@@ -383,6 +391,9 @@ class PostController extends PublicBaseController
'sirsoft-board::messages.posts.update_success',
new PostResource($post)
);
} catch (AttachmentLimitExceededException $e) {
// 게시판 첨부 개수 상한 초과 — generic 500 이 아닌 422 명시 차단
return $this->error($e->getMessage(), 422, ['code' => 'attachment_limit_exceeded']);
} catch (AccessDeniedHttpException $e) {
return $this->error('auth.scope_denied', 403);
} catch (ModelNotFoundException $e) {
@@ -211,11 +211,11 @@ class StoreBoardSettingsRequest extends FormRequest
// report_policy (신고 정책) 카테고리
// ========================================
'report_policy' => ['sometimes', 'array'],
'report_policy.auto_hide_threshold' => ['nullable', 'integer', 'min:0', 'max:100'],
'report_policy.auto_hide_threshold' => ['nullable', 'integer', 'min:'.$this->boardLimit('auto_hide_threshold_min', 0), 'max:'.$this->boardLimit('auto_hide_threshold_max', 100)],
'report_policy.auto_hide_target' => ['nullable', 'string', 'in:post,comment,both'],
'report_policy.daily_report_limit' => ['nullable', 'integer', 'min:0', 'max:100'],
'report_policy.rejection_limit_count' => ['nullable', 'integer', 'min:0', 'max:50'],
'report_policy.rejection_limit_days' => ['nullable', 'integer', 'min:1', 'max:365'],
'report_policy.daily_report_limit' => ['nullable', 'integer', 'min:'.$this->boardLimit('daily_report_limit_min', 0), 'max:'.$this->boardLimit('daily_report_limit_max', 100)],
'report_policy.rejection_limit_count' => ['nullable', 'integer', 'min:'.$this->boardLimit('rejection_limit_count_min', 0), 'max:'.$this->boardLimit('rejection_limit_count_max', 50)],
'report_policy.rejection_limit_days' => ['nullable', 'integer', 'min:'.$this->boardLimit('rejection_limit_days_min', 1), 'max:'.$this->boardLimit('rejection_limit_days_max', 365)],
'report_policy.notify_admin_on_report' => ['nullable', 'boolean'],
'report_policy.notify_admin_on_report_scope' => ['nullable', 'string', 'in:per_case,per_report'],
'report_policy.notify_admin_on_report_channels' => ['nullable', 'array'],
@@ -244,10 +244,10 @@ class StoreBoardSettingsRequest extends FormRequest
// spam_security (스팸/보안) 카테고리
// ========================================
'spam_security' => ['sometimes', 'array'],
'spam_security.post_cooldown_seconds' => ['nullable', 'integer', 'min:0', 'max:3600'],
'spam_security.comment_cooldown_seconds' => ['nullable', 'integer', 'min:0', 'max:3600'],
'spam_security.report_cooldown_seconds' => ['nullable', 'integer', 'min:0', 'max:3600'],
'spam_security.view_count_cache_ttl' => ['nullable', 'integer', 'min:60', 'max:604800'],
'spam_security.post_cooldown_seconds' => ['nullable', 'integer', 'min:'.$this->boardLimit('post_cooldown_seconds_min', 0), 'max:'.$this->boardLimit('post_cooldown_seconds_max', 3600)],
'spam_security.comment_cooldown_seconds' => ['nullable', 'integer', 'min:'.$this->boardLimit('comment_cooldown_seconds_min', 0), 'max:'.$this->boardLimit('comment_cooldown_seconds_max', 3600)],
'spam_security.report_cooldown_seconds' => ['nullable', 'integer', 'min:'.$this->boardLimit('report_cooldown_seconds_min', 0), 'max:'.$this->boardLimit('report_cooldown_seconds_max', 3600)],
'spam_security.view_count_cache_ttl' => ['nullable', 'integer', 'min:'.$this->boardLimit('view_count_cache_ttl_min', 60), 'max:'.$this->boardLimit('view_count_cache_ttl_max', 604800)],
// ========================================
// seo (SEO 설정) 카테고리
@@ -47,6 +47,24 @@ trait ReadsBoardLimits
'max_comment_depth_min' => 0,
'max_comment_depth_max' => 10,
'auto_hide_threshold_min' => 0,
'auto_hide_threshold_max' => 100,
'daily_report_limit_min' => 0,
'daily_report_limit_max' => 100,
'rejection_limit_count_min' => 0,
'rejection_limit_count_max' => 50,
'rejection_limit_days_min' => 1,
'rejection_limit_days_max' => 365,
'post_cooldown_seconds_min' => 0,
'post_cooldown_seconds_max' => 3600,
'comment_cooldown_seconds_min' => 0,
'comment_cooldown_seconds_max' => 3600,
'report_cooldown_seconds_min' => 0,
'report_cooldown_seconds_max' => 3600,
'view_count_cache_ttl_min' => 60,
'view_count_cache_ttl_max' => 604800,
'new_display_hours_min' => 0,
'new_display_hours_max' => 720,
];
@@ -72,10 +90,11 @@ trait ReadsBoardLimits
* 특정 제한값을 반환합니다.
*
* @param string $key 제한값 키 (예: per_page_min)
* @param int|null $default 키가 없을 때 쓸 값 (미지정 시 0)
* @return int 제한값
*/
protected function boardLimit(string $key): int
protected function boardLimit(string $key, ?int $default = null): int
{
return (int) ($this->boardLimits()[$key] ?? 0);
return (int) ($this->boardLimits()[$key] ?? $default ?? 0);
}
}
@@ -0,0 +1,120 @@
<?php
namespace Modules\Sirsoft\Board\Http\Requests\Concerns;
use Illuminate\Contracts\Validation\Validator;
use Modules\Sirsoft\Board\Exceptions\AttachmentLimitExceededException;
use Modules\Sirsoft\Board\Models\Attachment;
use Modules\Sirsoft\Board\Models\Board;
/**
* 게시글 첨부 개수 선차단 Trait
*
* 총합은 **직접 업로드 + `attachment_ids` + `temp_key` 임시첨부 + 기존 첨부** 4소스라
* 필드 단위 규칙(`files` 의 `max:`)만으로는 판정할 수 없습니다. 최종 불변조건은
* `AttachmentService::assertAttachmentCountWithin()` 이 담당하며, 이 Trait 은
* "글을 다 쓰고 저장 단계에서 실패" 를 막는 UX 선차단입니다 (역할이 다른 중복).
*/
trait ValidatesAttachmentCount
{
/**
* 첨부 총합이 게시판 상한을 넘으면 검증 오류를 추가합니다.
*
* @param Validator $validator 검증기
* @param Board|null $board 대상 게시판
* @param int|null $postId 수정 대상 게시글 ID (신규 작성이면 null)
*/
protected function validateAttachmentTotal(Validator $validator, ?Board $board, ?int $postId = null): void
{
if (! $board) {
return;
}
$limit = (int) ($board->max_file_count ?? 0);
if ($limit <= 0) {
return;
}
$files = $this->file('files');
$newCount = is_array($files) ? count($files) : 0;
$attachmentIds = $this->input('attachment_ids');
$newCount += is_array($attachmentIds) ? count($attachmentIds) : 0;
$tempKey = $this->input('temp_key');
if (is_string($tempKey) && $tempKey !== '') {
$newCount += Attachment::query()
->where('temp_key', $tempKey)
->whereNull('post_id')
->count();
}
if ($newCount <= 0) {
return;
}
$existing = $postId !== null
? Attachment::query()->where('board_id', $board->id)->where('post_id', $postId)->count()
: 0;
if ($existing + $newCount > $limit) {
$validator->errors()->add('files', __('sirsoft-board::messages.errors.attachment_limit_exceeded', [
'limit' => $limit,
'attempted' => $existing + $newCount,
]));
}
}
/**
* 단일 파일 업로드 1건이 게시판 상한을 넘으면 도메인 예외로 선차단합니다.
*
* 합산 기준은 `AttachmentService::assertAttachmentCountWithin()` 과 동일합니다 —
* `post_id` 가 있으면 그 게시글의 기존 첨부, 없으면 `temp_key` 의 임시첨부를 기준으로
* 삼습니다(둘을 더하지 않습니다). 두 계층의 판정이 갈리면 화면과 서버가 다른 답을
* 내놓게 되므로 우선순위까지 같아야 합니다.
*
* 필드 검증 오류가 아니라 `AttachmentLimitExceededException` 을 던지는 이유는 응답 형태
* 때문입니다 — 이 엔드포인트의 상한 초과 응답은 `errors.code = attachment_limit_exceeded`
* 로 공개 문서화되어 있고, 선차단이 다른 형태를 내놓으면 업로더가 두 응답을 분기해야
* 합니다. 예외의 `render()` 가 컨트롤러 catch 와 같은 응답을 만듭니다.
*
* @param Board|null $board 대상 게시판
* @param int|null $postId 대상 게시글 ID (임시 업로드면 null)
* @param string|null $tempKey 임시 업로드 키
*
* @throws AttachmentLimitExceededException 상한 초과 시
*/
protected function assertSingleAttachmentSlotAvailable(
?Board $board,
?int $postId = null,
?string $tempKey = null
): void {
if (! $board) {
return;
}
$limit = (int) ($board->max_file_count ?? 0);
if ($limit <= 0) {
return;
}
$existing = 0;
if ($postId !== null) {
$existing = Attachment::query()
->where('board_id', $board->id)
->where('post_id', $postId)
->count();
} elseif (is_string($tempKey) && $tempKey !== '') {
// 임시첨부는 아직 게시판에 귀속되기 전이라 board_id 로 좁히지 않는다
// (`validateAttachmentTotal()` 의 temp_key 합산과 동일 기준).
$existing = Attachment::query()
->where('temp_key', $tempKey)
->whereNull('post_id')
->count();
}
if ($existing + 1 > $limit) {
throw new AttachmentLimitExceededException($limit, $existing + 1);
}
}
}
@@ -3,10 +3,12 @@
namespace Modules\Sirsoft\Board\Http\Requests;
use App\Extension\HookManager;
use Illuminate\Contracts\Validation\Validator;
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\Http\Requests\Concerns\ValidatesAttachmentCount;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Models\Post;
use Modules\Sirsoft\Board\Rules\BlockedKeywordsRule;
@@ -19,6 +21,7 @@ use Modules\Sirsoft\Board\Rules\ParentPostValidationRule;
class StorePostRequest extends FormRequest
{
use ResolvesAllowedExtensions;
use ValidatesAttachmentCount;
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
@@ -166,4 +169,17 @@ class StorePostRequest extends FormRequest
'files.*' => __('sirsoft-board::validation.attributes.post.file'),
];
}
/**
* 필드 단위 규칙으로 판정할 수 없는 첨부 총합을 검증합니다.
*
* @param Validator $validator 검증기
*/
public function withValidator(Validator $validator): void
{
$validator->after(function (Validator $validator) {
$board = Board::where('slug', $this->route('slug'))->first();
$this->validateAttachmentTotal($validator, $board);
});
}
}
@@ -3,9 +3,11 @@
namespace Modules\Sirsoft\Board\Http\Requests;
use App\Extension\HookManager;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Sirsoft\Board\Enums\PostStatus;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ValidatesAttachmentCount;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Rules\BlockedKeywordsRule;
@@ -14,8 +16,12 @@ use Modules\Sirsoft\Board\Rules\BlockedKeywordsRule;
*/
class UpdatePostRequest extends FormRequest
{
use ValidatesAttachmentCount;
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* @return bool 항상 true (권한은 미들웨어에서 검증)
*/
public function authorize(): bool
{
@@ -107,4 +113,20 @@ class UpdatePostRequest extends FormRequest
'status' => __('sirsoft-board::validation.attributes.post.status'),
];
}
}
/**
* 필드 단위 규칙으로 판정할 수 없는 첨부 총합을 검증합니다.
*
* 수정은 이미 연결된 첨부와 합산해 판정합니다.
*
* @param Validator $validator 검증기
*/
public function withValidator(Validator $validator): void
{
$validator->after(function (Validator $validator) {
$board = Board::where('slug', $this->route('slug'))->first();
$postId = $this->route('id');
$this->validateAttachmentTotal($validator, $board, is_numeric($postId) ? (int) $postId : null);
});
}
}
@@ -3,16 +3,24 @@
namespace Modules\Sirsoft\Board\Http\Requests;
use App\Extension\HookManager;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ResolvesAllowedExtensions;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ValidatesAttachmentCount;
use Modules\Sirsoft\Board\Models\Board;
/**
* 게시판 첨부파일 업로드 요청 검증
*
* 첨부 개수 상한은 게시글 작성 Request 들과 같이 여기서도 선차단한다 — 최종 불변조건은
* `AttachmentService::assertAttachmentCountWithin()` 이 담당하지만(모든 경로가 지나는
* SSoT), 요청 계층에서 막으면 다른 검증 오류와 같은 422 필드 오류 형태로 돌아가 업로더가
* 응답을 분기하지 않아도 된다. 두 계층은 합산 기준·우선순위가 동일하므로 판정이 갈리지 않는다.
*/
class UploadAttachmentRequest extends FormRequest
{
use ResolvesAllowedExtensions;
use ValidatesAttachmentCount;
/**
* 요청 권한 확인
@@ -91,6 +99,30 @@ class UploadAttachmentRequest extends FormRequest
];
}
/**
* 첨부 개수 상한을 선차단합니다.
*
* @param Validator $validator 검증기
*/
public function withValidator(Validator $validator): void
{
$validator->after(function (Validator $validator) {
// 필드 규칙(용량·확장자)이 이미 걸린 요청에는 개수 판정을 덧붙이지 않는다 —
// 파일 자체가 거부될 요청까지 상한 초과로 보고하면 원인이 뒤바뀐다.
if ($validator->errors()->isNotEmpty()) {
return;
}
$postId = $this->input('post_id');
$this->assertSingleAttachmentSlotAvailable(
Board::where('slug', $this->route('slug'))->first(),
$postId !== null && $postId !== '' ? (int) $postId : null,
$this->input('temp_key')
);
});
}
/**
* 검증 전 데이터 준비
*/
@@ -3,12 +3,14 @@
namespace Modules\Sirsoft\Board\Http\Requests\User;
use App\Extension\HookManager;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
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\Http\Requests\Concerns\ValidatesAttachmentCount;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Models\Post;
use Modules\Sirsoft\Board\Rules\BlockedKeywordsRule;
@@ -26,6 +28,7 @@ use Modules\Sirsoft\Board\Rules\ParentPostValidationRule;
class StorePostRequest extends FormRequest
{
use ResolvesAllowedExtensions;
use ValidatesAttachmentCount;
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
@@ -213,4 +216,17 @@ class StorePostRequest extends FormRequest
return $validated;
}
/**
* 필드 단위 규칙으로 판정할 수 없는 첨부 총합을 검증합니다.
*
* @param Validator $validator 검증기
*/
public function withValidator(Validator $validator): void
{
$validator->after(function (Validator $validator) {
$board = Board::where('slug', $this->route('slug'))->first();
$this->validateAttachmentTotal($validator, $board);
});
}
}
@@ -3,9 +3,11 @@
namespace Modules\Sirsoft\Board\Http\Requests\User;
use App\Extension\HookManager;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Sirsoft\Board\Enums\PostStatus;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ValidatesAttachmentCount;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Rules\BlockedKeywordsRule;
@@ -19,8 +21,12 @@ use Modules\Sirsoft\Board\Rules\BlockedKeywordsRule;
*/
class UpdatePostRequest extends FormRequest
{
use ValidatesAttachmentCount;
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* @return bool 항상 true (권한은 미들웨어에서 검증)
*/
public function authorize(): bool
{
@@ -117,4 +123,20 @@ class UpdatePostRequest extends FormRequest
'status' => __('sirsoft-board::validation.attributes.post.status'),
];
}
/**
* 필드 단위 규칙으로 판정할 수 없는 첨부 총합을 검증합니다.
*
* 수정은 이미 연결된 첨부와 합산해 판정합니다.
*
* @param Validator $validator 검증기
*/
public function withValidator(Validator $validator): void
{
$validator->after(function (Validator $validator) {
$board = Board::where('slug', $this->route('slug'))->first();
$postId = $this->route('id');
$this->validateAttachmentTotal($validator, $board, is_numeric($postId) ? (int) $postId : null);
});
}
}
@@ -4,12 +4,14 @@ namespace Modules\Sirsoft\Board\Services;
use App\Contracts\Extension\StorageInterface;
use App\Extension\HookManager;
use App\Helpers\PermissionHelper;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use App\Helpers\PermissionHelper;
use Modules\Sirsoft\Board\Exceptions\AttachmentLimitExceededException;
use Modules\Sirsoft\Board\Models\Attachment;
use Modules\Sirsoft\Board\Repositories\Contracts\AttachmentRepositoryInterface;
use Modules\Sirsoft\Board\Repositories\Contracts\BoardRepositoryInterface;
@@ -35,6 +37,56 @@ class AttachmentService
private StorageInterface $storage
) {}
/**
* 첨부 개수가 게시판 상한을 넘지 않는지 검증합니다 (도메인 불변조건).
*
* 총합은 **직접 업로드 + `attachment_ids` + `temp_key` 임시첨부 + 기존 첨부** 4소스이고
* temp_key 쪽은 DB 조회가 필요하므로 FormRequest 만으로는 판정할 수 없습니다.
* 모든 연결 경로가 반드시 지나는 이 지점이 상한의 SSoT 입니다.
* (FormRequest 의 `files` max 규칙은 "글을 다 쓰고 저장 실패" 를 막는 UX 선차단이며
* 역할이 다릅니다 — 둘 다 필요합니다.)
*
* @param string $slug 게시판 슬러그
* @param int|null $postId 게시글 ID (신규 작성 중이면 null)
* @param int $additional 이번에 추가하려는 첨부 개수
* @param string|null $tempKey 임시 업로드 키 (신규 작성 시 기존 임시첨부 합산용)
*
* @throws AttachmentLimitExceededException 상한 초과 시
*/
public function assertAttachmentCountWithin(
string $slug,
?int $postId,
int $additional,
?string $tempKey = null
): void {
if ($additional <= 0) {
return;
}
$board = $this->boardRepository->findBySlug($slug);
if (! $board) {
throw new ModelNotFoundException(__('sirsoft-board::messages.errors.board_not_found'));
}
$limit = (int) ($board->max_file_count ?? 0);
if ($limit <= 0) {
// 상한 미설정 게시판은 제한하지 않는다 (기존 동작 유지)
return;
}
$existing = 0;
if ($postId !== null) {
$existing = $this->repository->getByPost($slug, $postId, 'attachments')->count();
} elseif ($tempKey !== null) {
$existing = $this->repository->getByTempKey($slug, $tempKey, 'attachments')->count();
}
$total = $existing + $additional;
if ($total > $limit) {
throw new AttachmentLimitExceededException($limit, $total);
}
}
/**
* 단일 파일 업로드
*
@@ -55,6 +107,9 @@ class AttachmentService
string $collection = 'attachments',
?string $tempKey = null
): Attachment {
// 개수 상한 최종 방어선 — 단일 업로드를 N 번 반복하는 경로도 여기서 막힌다
$this->assertAttachmentCountWithin($slug, $postId, 1, $tempKey);
// Before 훅
HookManager::doAction('sirsoft-board.attachment.before_upload', $slug, $file, $postId);
@@ -182,6 +237,11 @@ class AttachmentService
}
$tempAttachments = $this->repository->getByTempKey($slug, $tempKey);
// 개수 상한 최종 방어선 — FormRequest 는 files[] 만 보므로 temp_key 경로가 그대로 뚫린다.
// 이미 연결된 첨부와 합산해 판정한다 (수정 시 기존 첨부 + 신규 임시첨부).
$this->assertAttachmentCountWithin($slug, $postId, $tempAttachments->count());
$linkedCount = 0;
foreach ($tempAttachments as $attachment) {
@@ -230,7 +290,7 @@ class AttachmentService
* @param string $slug 게시판 슬러그
* @param string $tempKey 임시 업로드 키
* @param string|null $collection 컬렉션 필터
* @return \Illuminate\Database\Eloquent\Collection
* @return Collection
*/
public function getTempAttachments(string $slug, string $tempKey, ?string $collection = null)
{
@@ -258,7 +318,6 @@ class AttachmentService
*
* @param string $slug 게시판 슬러그
* @param Attachment $attachment 첨부파일 모델
* @return void
*
* @throws AccessDeniedHttpException 삭제글 첨부에 권한 없이 접근한 경우
*/
@@ -402,7 +461,7 @@ class AttachmentService
* @param string $slug 게시판 슬러그
* @param int $postId 게시글 ID
* @param string|null $collection 컬렉션 필터
* @return \Illuminate\Database\Eloquent\Collection
* @return Collection
*/
public function getAttachments(string $slug, int $postId, ?string $collection = null)
{
@@ -10,6 +10,8 @@ use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Auth;
use Modules\Sirsoft\Board\Enums\PostStatus;
use Modules\Sirsoft\Board\Exceptions\CommentDepthExceededException;
use Modules\Sirsoft\Board\Exceptions\PostNotCommentableException;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Models\Comment;
use Modules\Sirsoft\Board\Repositories\Contracts\BoardRepositoryInterface;
@@ -208,18 +210,18 @@ class CommentService
* @return bool 댓글 작성 가능 여부
*
* @throws ModelNotFoundException 게시글을 찾을 수 없는 경우
* @throws \Exception 블라인드/삭제된 게시글인 경우
* @throws PostNotCommentableException 블라인드/삭제된 게시글인 경우
*/
public function validatePostForComment(string $slug, int $postId): bool
{
$post = $this->postRepository->findOrFail($slug, $postId);
if ($post->status === PostStatus::Blinded) {
throw new \Exception(__('sirsoft-board::messages.comment.post_blinded'));
throw PostNotCommentableException::blinded();
}
if ($post->status === PostStatus::Deleted || $post->deleted_at) {
throw new \Exception(__('sirsoft-board::messages.comment.post_deleted'));
throw PostNotCommentableException::deleted();
}
return true;
@@ -257,8 +259,17 @@ class CommentService
// 같은 게시글에 속한 부모 댓글만 인정 (교차 게시글 부모 차단)
$parentComment = $this->commentRepository->find($slug, $data['parent_id'], (int) $data['post_id']);
if ($parentComment) {
// 부모 댓글의 depth + 1 — 상한은 CommentValidationRule 이 게시판 설정으로 검증
$data['depth'] = ($parentComment->depth ?? 0) + 1;
// 최종 불변조건 — `CommentValidationRule` 은 요청 단계 선차단이라 훅이나
// Service 직접 호출 경로에는 걸리지 않는다. 클램프하지 않고 예외를 던진다:
// 요청한 위치와 다른 자리에 조용히 붙으면 사용자가 알 수 없다.
$board = $this->boardRepository->findBySlug($slug);
$maxDepth = (int) ($board->max_comment_depth ?? 0);
if ($data['depth'] > $maxDepth) {
throw new CommentDepthExceededException($maxDepth, $data['depth']);
}
} else {
// 부모 댓글을 찾을 수 없으면 0으로 설정
$data['depth'] = 0;
@@ -85,6 +85,7 @@ class PostService
* @param string $slug 게시판 슬러그
* @param array $filters 필터 조건
* @param bool $withTrashed 삭제된 게시글 포함 여부
* @param string $context 호출 컨텍스트 (admin/user — 권한 스코프 판정용)
* @return int 일반 게시글 수 (답글, 공지 제외)
*
* @throws ModelNotFoundException 게시판을 찾을 수 없는 경우
@@ -145,6 +146,7 @@ class PostService
*
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @param string $context 호출 컨텍스트 (admin/user — 권한 스코프 판정용)
* @return Post 게시글 모델
*
* @throws ModelNotFoundException 게시판 또는 게시글을 찾을 수 없는 경우
@@ -393,8 +395,9 @@ class PostService
* @param int $id 게시글 ID
* @param string $reason 블라인드 사유
* @param string|null $triggerType 트리거 유형 (admin, report 등)
* @return Post 블라인드 처리된 게시글 모델
*
* @throws ModelNotFoundException
* @throws ModelNotFoundException 게시판 또는 게시글을 찾을 수 없는 경우
*/
public function blindPost(string $slug, int $id, string $reason, ?string $triggerType = null): Post
{
@@ -519,6 +522,7 @@ class PostService
*
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @param int|null $boardId 이미 검증된 게시판 ID (중복 조회 방지용)
* @return Post 게시글 모델 (카운트 포함)
*
* @throws ModelNotFoundException 게시판 또는 게시글을 찾을 수 없는 경우
@@ -629,6 +633,7 @@ class PostService
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @param bool $canViewDeleted 삭제된 게시글 조회 가능 여부
* @param string $context 호출 컨텍스트 (admin/user — 권한 스코프 판정용)
* @return Post 상세 정보가 포함된 게시글 모델
*
* @throws ModelNotFoundException 게시판 또는 게시글을 찾을 수 없는 경우
@@ -725,6 +730,9 @@ class PostService
): void {
// 방안 A: 업로드 완료된 첨부파일 ID로 연결 (신규 방식)
if (! empty($attachmentIds)) {
// 개수 상한 최종 방어선 (기존 연결분과 합산) — Request 는 files[] 만 세므로 여기서 다시 판정한다
$this->attachmentService->assertAttachmentCountWithin($slug, $postId, count($attachmentIds));
$linkedCount = $this->attachmentRepository->linkAttachmentsByIds($slug, $attachmentIds, $postId);
if ($linkedCount > 0) {
Log::info("{$context} 시 첨부파일 ID로 연결 완료", [
@@ -1154,6 +1162,7 @@ class PostService
*
* @param array $boardIds 검색 대상 게시판 ID 목록
* @param string $keyword 검색 키워드
* @return int 일치하는 게시글 수
*/
public function countAcrossBoards(array $boardIds, string $keyword): int
{
@@ -220,6 +220,7 @@ return [
'table_creation_failed' => 'Failed to create board table (:table): :error',
'category_in_use' => 'Category :category is in use by :count post(s).',
'board_not_found' => 'Board not found.',
'attachment_limit_exceeded' => 'You can attach up to :limit file(s). (requested: :attempted)',
'post_not_found' => 'Post not found.',
'permission_denied' => 'Permission denied.',
'validation_failed' => 'Validation failed.',
@@ -220,6 +220,7 @@ return [
'table_creation_failed' => '게시판 테이블 생성에 실패했습니다 (:table): :error',
'category_in_use' => ':category 카테고리는 :count개의 게시글에서 사용 중입니다.',
'board_not_found' => '게시판을 찾을 수 없습니다.',
'attachment_limit_exceeded' => '첨부파일은 최대 :limit개까지 등록할 수 있습니다. (요청: :attempted개)',
'post_not_found' => '게시글을 찾을 수 없습니다.',
'permission_denied' => '권한이 없습니다.',
'validation_failed' => '입력값이 올바르지 않습니다.',
@@ -553,6 +553,88 @@ class BoardSettingsControllerTest extends ModuleTestCase
->assertJsonValidationErrors(['basic_defaults.per_page_mobile']);
}
/**
* basic_defaults.max_file_count 는 config max_file_count_max(20)까지 허용 (#493 B2)
*/
public function test_settings_request_max_file_count_allows_config_max(): void
{
$response = $this->actingAs($this->adminUser)
->putJson('/api/modules/sirsoft-board/admin/settings', [
'basic_defaults' => ['max_file_count' => 20],
]);
$response->assertStatus(200);
}
/**
* basic_defaults.max_file_count 가 config max(20) 초과 시 422 (#493 B2)
*/
public function test_settings_request_max_file_count_rejects_above_config_max(): void
{
$response = $this->actingAs($this->adminUser)
->putJson('/api/modules/sirsoft-board/admin/settings', [
'basic_defaults' => ['max_file_count' => 21],
]);
$response->assertStatus(422)
->assertJsonValidationErrors(['basic_defaults.max_file_count']);
}
/**
* 제한값 설정을 바꾸면 저장 규칙이 따라오는지 확인 (#493 B2 — config 가 SSoT)
*
* 규칙이 리터럴로 되돌아가면 설정을 바꿔도 경계가 그대로라 이 테스트가 먼저 깨진다.
*/
public function test_settings_request_bounds_follow_config(): void
{
config(['sirsoft-board.limits.max_file_count_max' => 3]);
$this->actingAs($this->adminUser)
->putJson('/api/modules/sirsoft-board/admin/settings', [
'basic_defaults' => ['max_file_count' => 3],
])
->assertStatus(200);
$this->actingAs($this->adminUser)
->putJson('/api/modules/sirsoft-board/admin/settings', [
'basic_defaults' => ['max_file_count' => 4],
])
->assertStatus(422)
->assertJsonValidationErrors(['basic_defaults.max_file_count']);
}
/**
* report_policy.auto_hide_threshold 는 0(자동 숨김 비활성)을 저장할 수 있다 (#493 B4)
*
* 화면 안내가 "0=비활성" 이므로 서버가 0 을 거부하면 비활성으로 되돌릴 방법이 없다.
*/
public function test_settings_request_auto_hide_threshold_allows_zero(): void
{
$response = $this->actingAs($this->adminUser)
->putJson('/api/modules/sirsoft-board/admin/settings', [
'report_policy' => ['auto_hide_threshold' => 0],
]);
$response->assertStatus(200);
$content = json_decode(File::get($this->settingsStoragePath.'/report_policy.json'), true);
$this->assertSame(0, (int) $content['auto_hide_threshold']);
}
/**
* report_policy.auto_hide_threshold 가 config max(100) 초과 시 422 (#493 B4)
*/
public function test_settings_request_auto_hide_threshold_rejects_above_config_max(): void
{
$response = $this->actingAs($this->adminUser)
->putJson('/api/modules/sirsoft-board/admin/settings', [
'report_policy' => ['auto_hide_threshold' => 101],
]);
$response->assertStatus(422)
->assertJsonValidationErrors(['report_policy.auto_hide_threshold']);
}
// ========================================
// clearCache (캐시 초기화) 테스트
// ========================================
@@ -0,0 +1,464 @@
<?php
namespace Modules\Sirsoft\Board\Tests\Feature;
require_once __DIR__.'/../ModuleTestCase.php';
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\UploadedFile;
use Mockery;
use Modules\Sirsoft\Board\Exceptions\AttachmentLimitExceededException;
use Modules\Sirsoft\Board\Models\Attachment;
use Modules\Sirsoft\Board\Models\Post;
use Modules\Sirsoft\Board\Services\AttachmentService;
use Modules\Sirsoft\Board\Services\PostService;
use Modules\Sirsoft\Board\Tests\BoardTestCase;
/**
* 첨부파일 개수 상한 서버측 불변조건 테스트 (B3)
*
* 수정 전에는 `files[]` 직접 업로드만 FormRequest 에서 막고, `attachment_ids` · `temp_key` ·
* 단일 업로드 반복 경로에는 개수 검사가 없었습니다. 같은 8개 파일을 `temp_key` 로 보내면
* 201 로 전부 연결되어 사용자 페이지에 그대로 노출됐습니다.
*
* @group board
* @group attachment
*/
class AttachmentLimitTest extends BoardTestCase
{
private User $memberUser;
protected function getTestBoardSlug(): string
{
return 'attachment-limit';
}
protected function getDefaultBoardAttributes(string $slug): array
{
return [
'slug' => $slug,
'name' => ['ko' => '첨부 상한 게시판', 'en' => 'Attachment Limit Board'],
'is_active' => true,
'use_file_upload' => true,
'max_file_count' => 5,
];
}
protected function setUp(): void
{
parent::setUp();
$this->setGuestPermissions(['posts.read', 'posts.write']);
$this->grantUserRolePermissions(['posts.read', 'posts.write', 'attachments.upload']);
$this->memberUser = User::factory()->create(['email' => 'attachment-limit@test.com']);
$userRole = Role::where('identifier', 'user')->first();
if ($userRole) {
$this->memberUser->roles()->attach($userRole->id);
}
}
/**
* 임시 첨부(temp_key) 를 N 개 만듭니다.
*
* @param string $tempKey 임시 업로드 키
* @param int $count 생성 개수
*/
private function seedTempAttachments(string $tempKey, int $count): void
{
for ($i = 0; $i < $count; $i++) {
Attachment::create([
'board_id' => 0,
'post_id' => null,
'temp_key' => $tempKey,
'collection' => 'attachments',
'original_filename' => "temp-{$i}.png",
'stored_filename' => "temp-{$i}.png",
'path' => "{$this->getTestBoardSlug()}/temp/{$tempKey}/temp-{$i}.png",
'mime_type' => 'image/png',
'size' => 100,
'order' => $i,
]);
}
}
/**
* 게시글에 연결된 첨부를 N 개 만듭니다.
*
* @param int $postId 게시글 ID
* @param int $count 생성 개수
*/
private function seedLinkedAttachments(int $postId, int $count): void
{
$board = $this->board;
for ($i = 0; $i < $count; $i++) {
Attachment::create([
'board_id' => $board->id,
'post_id' => $postId,
'collection' => 'attachments',
'original_filename' => "linked-{$i}.png",
'stored_filename' => "linked-{$i}.png",
'path' => "{$this->getTestBoardSlug()}/2026/07/27/linked-{$i}.png",
'mime_type' => 'image/png',
'size' => 100,
'order' => $i,
]);
}
}
/**
* temp_key 경로로 상한을 초과하면 차단된다 (실측 재현된 우회 경로).
*/
public function test_temp_key_link_over_limit_is_blocked(): void
{
$postId = $this->createTestPost();
$tempKey = 'tk_'.str_repeat('a', 20);
$this->seedTempAttachments($tempKey, 8);
$this->expectException(AttachmentLimitExceededException::class);
app(AttachmentService::class)->linkTempAttachmentsWithMove(
$this->getTestBoardSlug(),
$tempKey,
$postId
);
}
/**
* 상한과 정확히 같은 개수는 통과한다 (경계).
*/
public function test_temp_key_link_at_limit_passes(): void
{
$postId = $this->createTestPost();
$tempKey = 'tk_'.str_repeat('b', 20);
$this->seedTempAttachments($tempKey, 5);
$linked = app(AttachmentService::class)->linkTempAttachmentsWithMove(
$this->getTestBoardSlug(),
$tempKey,
$postId
);
$this->assertSame(5, $linked);
}
/**
* 기존 첨부와 합산해 상한을 넘으면 차단된다 (수정 경로).
*/
public function test_existing_plus_new_over_limit_is_blocked(): void
{
$postId = $this->createTestPost();
$this->seedLinkedAttachments($postId, 4);
$tempKey = 'tk_'.str_repeat('c', 20);
$this->seedTempAttachments($tempKey, 2);
$this->expectException(AttachmentLimitExceededException::class);
app(AttachmentService::class)->linkTempAttachmentsWithMove(
$this->getTestBoardSlug(),
$tempKey,
$postId
);
}
/**
* 기존 4 + 신규 1 = 5 는 통과한다 (경계).
*/
public function test_existing_plus_new_at_limit_passes(): void
{
$postId = $this->createTestPost();
$this->seedLinkedAttachments($postId, 4);
$tempKey = 'tk_'.str_repeat('d', 20);
$this->seedTempAttachments($tempKey, 1);
$linked = app(AttachmentService::class)->linkTempAttachmentsWithMove(
$this->getTestBoardSlug(),
$tempKey,
$postId
);
$this->assertSame(1, $linked);
}
/**
* attachment_ids 경로도 합산 판정된다.
*/
public function test_attachment_ids_over_limit_is_blocked(): void
{
$postId = $this->createTestPost();
$this->seedLinkedAttachments($postId, 5);
$this->expectException(AttachmentLimitExceededException::class);
app(AttachmentService::class)->assertAttachmentCountWithin(
$this->getTestBoardSlug(),
$postId,
1
);
}
/**
* 관리자 수정 경로에서 상한 초과가 500 이 아닌 422 로 응답되는지 검증합니다.
*
* FormRequest 선차단은 UX 용이고 최종 불변조건은 Service 예외다. 그런데 관리자 수정
* 컨트롤러의 catch 가 게시글 *조회* try 에 붙어 있어, 예외를 실제로 던지는 저장 try 는
* 이 예외를 잡지 못하고 generic 500 으로 떨어졌다. 조회 mock 이 정상 반환하고 저장 mock 이
* 예외를 던지는 구성으로 그 매핑만 격리해 검증한다.
*/
public function test_admin_update_maps_attachment_limit_to_422(): void
{
$slug = $this->getTestBoardSlug();
$admin = $this->createAdminUser([
"sirsoft-board.{$slug}.admin.posts.write",
"sirsoft-board.{$slug}.admin.manage",
]);
$postId = $this->createTestPost(['user_id' => $admin->id]);
$post = Post::find($postId);
$mock = Mockery::mock(PostService::class);
$mock->shouldReceive('getPost')->andReturn($post);
$mock->shouldReceive('updatePost')
->andThrow(new AttachmentLimitExceededException(5, 6));
$this->app->instance(PostService::class, $mock);
$this->actingAs($admin)
->putJson("/api/modules/sirsoft-board/admin/board/{$slug}/posts/{$postId}", [
'title' => '상한 초과 수정 시도',
'content' => '본문은 최소 길이를 넘겨야 검증을 통과합니다.',
])
->assertStatus(422)
->assertJsonPath('errors.code', 'attachment_limit_exceeded');
}
/**
* 직접 업로드와 `attachment_ids` 를 섞어 보내도 합산 판정된다.
*
* 소스가 나뉘면 각 소스는 상한 이하인데 총합만 초과하는 조합이 만들어진다. 어느 한 소스만
* 세는 구현은 이 조합을 그대로 통과시킨다.
*/
public function test_mixed_files_and_attachment_ids_over_limit_is_blocked(): void
{
$postId = $this->createTestPost(['user_id' => $this->memberUser->id]);
// 기존 첨부 3 개 — 이 중 3 개를 attachment_ids 로 유지하면서 새 파일 3 개를 더 보낸다
$this->seedLinkedAttachments($postId, 3);
$keepIds = Attachment::where('post_id', $postId)->pluck('id')->all();
$response = $this->actingAs($this->memberUser)->putJson(
"/api/modules/sirsoft-board/boards/{$this->getTestBoardSlug()}/posts/{$postId}",
[
'title' => '혼합 소스 상한 초과',
'content' => '본문은 최소 길이를 넘겨야 검증을 통과합니다.',
'attachment_ids' => $keepIds,
'files' => [
UploadedFile::fake()->image('mix-1.png'),
UploadedFile::fake()->image('mix-2.png'),
UploadedFile::fake()->image('mix-3.png'),
],
]
);
$response->assertStatus(422);
$this->assertArrayHasKey('files', $response->json('errors') ?? []);
}
/**
* 작성 시 직접 업로드가 상한과 정확히 같은 개수면 통과하고 실제로 저장된다 (경계).
*
* 합산 판정이 들어간 뒤로 `files[]` 경로는 초과 케이스만 고정돼 있었다. 판정식이
* `>=` 로 어긋나거나 기존 첨부 0 건을 1 건으로 세면 상한 동수가 조용히 막히는데,
* 초과 케이스만 보는 테스트는 그 회귀를 통과시킨다. 저장 건수까지 단언해 "차단은
* 안 했지만 첨부도 안 됐다" 는 절반짜리 통과를 배제한다.
*/
public function test_files_at_limit_on_create_passes_and_persists(): void
{
$response = $this->actingAs($this->memberUser, 'sanctum')->postJson(
"/api/modules/sirsoft-board/boards/{$this->getTestBoardSlug()}/posts",
[
'title' => '상한 동수 첨부',
'content' => '본문은 최소 길이를 넘겨야 검증을 통과합니다.',
'files' => [
UploadedFile::fake()->image('at-1.png'),
UploadedFile::fake()->image('at-2.png'),
UploadedFile::fake()->image('at-3.png'),
UploadedFile::fake()->image('at-4.png'),
UploadedFile::fake()->image('at-5.png'),
],
]
);
$response->assertStatus(201);
$postId = (int) $response->json('data.id');
$this->assertSame(5, Attachment::where('post_id', $postId)->count());
}
/**
* 작성 시 상한을 1 건 넘기면 차단된다 (위 경계의 대조군).
*/
public function test_files_over_limit_on_create_is_blocked(): void
{
$response = $this->actingAs($this->memberUser, 'sanctum')->postJson(
"/api/modules/sirsoft-board/boards/{$this->getTestBoardSlug()}/posts",
[
'title' => '상한 초과 첨부',
'content' => '본문은 최소 길이를 넘겨야 검증을 통과합니다.',
'files' => [
UploadedFile::fake()->image('over-1.png'),
UploadedFile::fake()->image('over-2.png'),
UploadedFile::fake()->image('over-3.png'),
UploadedFile::fake()->image('over-4.png'),
UploadedFile::fake()->image('over-5.png'),
UploadedFile::fake()->image('over-6.png'),
],
]
);
$response->assertStatus(422);
$this->assertArrayHasKey('files', $response->json('errors') ?? []);
}
/**
* 단일 업로드를 반복해도 상한을 넘는 순간 차단된다.
*
* 한 번에 여러 개를 보내는 경로만 막으면, 한 개씩 N 번 부르는 경로로 그대로 우회된다.
*/
public function test_repeated_single_upload_is_blocked_at_the_limit(): void
{
$postId = $this->createTestPost();
$service = app(AttachmentService::class);
for ($i = 0; $i < 5; $i++) {
$service->upload(
$this->getTestBoardSlug(),
UploadedFile::fake()->image("single-{$i}.png"),
$postId
);
}
$this->assertSame(5, Attachment::where('post_id', $postId)->count());
$this->expectException(AttachmentLimitExceededException::class);
$service->upload(
$this->getTestBoardSlug(),
UploadedFile::fake()->image('single-6.png'),
$postId
);
}
/**
* 단일 업로드 엔드포인트가 상한 초과를 422 로 돌려주는지 검증합니다.
*
* 이 엔드포인트는 게시글 작성 Request 들과 마찬가지로 요청 계층에서 선차단하고,
* `AttachmentService::upload()` 가 최종 불변조건으로 남는다(훅·Service 직접 호출 방어).
*
* 두 계층이 같은 응답을 내야 소비자가 분기하지 않는다 — 선차단은 필드 검증 오류가 아니라
* `AttachmentLimitExceededException` 을 던지고, 그 `render()` 가 컨트롤러 catch 와
* 동일한 `errors.code=attachment_limit_exceeded` 를 만든다. 이 테스트가 그 동일성을 고정한다.
*/
public function test_single_upload_endpoint_blocks_over_limit_with_422(): void
{
$slug = $this->getTestBoardSlug();
$postId = $this->createTestPost(['user_id' => $this->memberUser->id]);
$this->seedLinkedAttachments($postId, 5);
$this->actingAs($this->memberUser, 'sanctum')
->postJson("/api/modules/sirsoft-board/boards/{$slug}/attachments", [
'file' => UploadedFile::fake()->image('over-limit.png'),
'post_id' => $postId,
])
->assertStatus(422)
->assertJsonPath('errors.code', 'attachment_limit_exceeded');
}
/**
* 단일 업로드 상한 초과는 Service 에 닿기 전 요청 계층에서 차단된다.
*
* `AttachmentService` 를 통째로 mock 해 `upload()` 가 아예 호출되지 않음을 단언한다 —
* Service 가 최종 관문으로 남아 있어도 요청 계층이 먼저 막아야 선차단이라 부를 수 있다.
*/
public function test_single_upload_over_limit_is_blocked_before_reaching_service(): void
{
$slug = $this->getTestBoardSlug();
$postId = $this->createTestPost(['user_id' => $this->memberUser->id]);
$this->seedLinkedAttachments($postId, 5);
$service = Mockery::mock(AttachmentService::class);
$service->shouldNotReceive('upload');
$this->app->instance(AttachmentService::class, $service);
$this->actingAs($this->memberUser, 'sanctum')
->postJson("/api/modules/sirsoft-board/boards/{$slug}/attachments", [
'file' => UploadedFile::fake()->image('blocked-before-service.png'),
'post_id' => $postId,
])
->assertStatus(422)
->assertJsonPath('errors.code', 'attachment_limit_exceeded');
}
/**
* temp_key 임시 업로드도 상한을 넘는 순간 요청 계층에서 차단된다.
*/
public function test_single_upload_with_temp_key_over_limit_is_blocked(): void
{
$slug = $this->getTestBoardSlug();
$tempKey = 'temp-single-upload-limit';
$this->seedTempAttachments($tempKey, 5);
$this->actingAs($this->memberUser, 'sanctum')
->postJson("/api/modules/sirsoft-board/boards/{$slug}/attachments", [
'file' => UploadedFile::fake()->image('temp-over-limit.png'),
'temp_key' => $tempKey,
])
->assertStatus(422)
->assertJsonPath('errors.code', 'attachment_limit_exceeded');
}
/**
* 상한 이내 단일 업로드는 그대로 통과한다 (경계).
*/
public function test_single_upload_endpoint_allows_within_limit(): void
{
$slug = $this->getTestBoardSlug();
$postId = $this->createTestPost(['user_id' => $this->memberUser->id]);
$this->seedLinkedAttachments($postId, 4);
$this->actingAs($this->memberUser, 'sanctum')
->postJson("/api/modules/sirsoft-board/boards/{$slug}/attachments", [
'file' => UploadedFile::fake()->image('within-limit.png'),
'post_id' => $postId,
])
->assertSuccessful();
}
/**
* 상한 미설정(0) 게시판은 제한하지 않는다 (기존 동작 유지).
*/
public function test_board_without_limit_is_not_restricted(): void
{
$this->board->update(['max_file_count' => 0]);
$postId = $this->createTestPost();
$tempKey = 'tk_'.str_repeat('e', 20);
$this->seedTempAttachments($tempKey, 8);
$linked = app(AttachmentService::class)->linkTempAttachmentsWithMove(
$this->getTestBoardSlug(),
$tempKey,
$postId
);
$this->assertSame(8, $linked);
}
}
@@ -6,6 +6,8 @@ require_once __DIR__.'/../ModuleTestCase.php';
use App\Models\Role;
use App\Models\User;
use Modules\Sirsoft\Board\Exceptions\CommentDepthExceededException;
use Modules\Sirsoft\Board\Services\CommentService;
use Modules\Sirsoft\Board\Tests\BoardTestCase;
/**
@@ -159,6 +161,50 @@ class CommentDepthLimitTest extends BoardTestCase
]);
}
/**
* max_comment_depth=0 게시판에서는 대댓글 자체가 불가능하다
*
* 0 은 "답글 없음" 설정이다. 상한을 리터럴로 클램프하거나 0 을 무제한으로 오해하면
* 이 게시판에서 대댓글이 그대로 달린다.
*
* @scenario entity=board_comment, parent_target=unrelated
*
* @effects depth_beyond_board_max_rejected_422, depth_follows_board_setting_not_literal
*/
public function test_reply_is_rejected_when_max_depth_is_zero(): void
{
$this->updateBoardSettings(['max_comment_depth' => 0]);
$postId = $this->createTestPost();
$parentId = $this->createTestComment($postId, ['depth' => 0]);
$this->actingAs($this->memberUser)
->postJson($this->storeUrl($postId), [
'content' => '대댓글 불가 게시판에서의 답글 시도',
'parent_id' => $parentId,
])
->assertStatus(422)
->assertJsonValidationErrors(['parent_id']);
}
/**
* max_comment_depth=0 이어도 최상위 댓글은 정상 작성된다 (과잉 차단 방지)
*
* @scenario entity=board_comment, parent_target=unrelated
*
* @effects depth_follows_board_setting_not_literal
*/
public function test_top_level_comment_is_allowed_when_max_depth_is_zero(): void
{
$this->updateBoardSettings(['max_comment_depth' => 0]);
$postId = $this->createTestPost();
$this->actingAs($this->memberUser)
->postJson($this->storeUrl($postId), ['content' => '최상위 댓글'])
->assertStatus(201);
}
/**
* 댓글 생성 엔드포인트 URL 을 생성합니다.
*
@@ -169,4 +215,61 @@ class CommentDepthLimitTest extends BoardTestCase
{
return "/api/modules/sirsoft-board/boards/{$this->board->slug}/posts/{$postId}/comments";
}
/**
* FormRequest 를 거치지 않는 경로(훅 · Service 직접 호출)에서도 깊이 상한이 지켜진다
*
* `CommentValidationRule` 은 요청 단계 선차단이라 Service 를 직접 부르는 확장 코드에는
* 걸리지 않는다. 첨부 개수(B3)가 Service 를 최종 불변조건으로 삼은 것과 같은 이유로,
* 깊이 상한도 Service 가 마지막 관문이어야 한다.
*
* @scenario entity=board_comment, parent_target=unrelated
*
* @effects depth_beyond_board_max_rejected_422
*/
public function test_service_direct_call_rejects_reply_beyond_max_depth(): void
{
$this->updateBoardSettings(['max_comment_depth' => 2]);
$postId = $this->createTestPost();
$depth0 = $this->createTestComment($postId, ['depth' => 0]);
$depth1 = $this->createTestComment($postId, ['parent_id' => $depth0, 'depth' => 1]);
$depth2 = $this->createTestComment($postId, ['parent_id' => $depth1, 'depth' => 2]);
$service = app(CommentService::class);
$this->expectException(CommentDepthExceededException::class);
// depth 3 = 상한 2 초과 → Service 가 막아야 한다
$service->createComment($this->board->slug, [
'post_id' => $postId,
'parent_id' => $depth2,
'content' => 'FormRequest 를 우회한 깊이 초과 답글',
'user_id' => $this->memberUser->id,
]);
}
/**
* 상한 이내의 Service 직접 호출은 그대로 통과한다 (과잉 차단 방지)
*
* @scenario entity=board_comment, parent_target=unrelated
*
* @effects depth_follows_board_setting_not_literal
*/
public function test_service_direct_call_allows_reply_within_max_depth(): void
{
$this->updateBoardSettings(['max_comment_depth' => 2]);
$postId = $this->createTestPost();
$depth0 = $this->createTestComment($postId, ['depth' => 0]);
$comment = app(CommentService::class)->createComment($this->board->slug, [
'post_id' => $postId,
'parent_id' => $depth0,
'content' => '상한 이내 답글',
'user_id' => $this->memberUser->id,
]);
$this->assertSame(1, (int) $comment->depth);
}
}
@@ -0,0 +1,197 @@
<?php
namespace Modules\Sirsoft\Board\Tests\Feature;
require_once __DIR__.'/../ModuleTestCase.php';
use App\Models\Role;
use App\Models\User;
use Modules\Sirsoft\Board\Exceptions\PostNotCommentableException;
use Modules\Sirsoft\Board\Services\CommentService;
use Modules\Sirsoft\Board\Tests\BoardTestCase;
/**
* 댓글 작성 불가 게시글 상태 응답 계약 테스트
*
* 검증 목적:
* - 요청 경로: `CommentValidationRule` 이 블라인드/삭제 게시글을 422 로 선차단한다 (기존 계약 고정)
* - Service 직접 경로: FormRequest 를 거치지 않는 훅·확장 호출에서도 도메인 예외로 막힌다
*
* 깊이 상한(B1)·첨부 개수(B3)와 같은 구조다 — 요청 단계는 UX 선차단, Service 가 최종 불변조건.
* Service 가 베이스 `\Exception` 을 던지면 컨트롤러의 제네릭 catch 에 걸려 500 + 일반 문구가 되어
* 사유가 사라지므로, 전용 예외를 두어 422 로 매핑한다.
*
* @group board
* @group comment
*/
class CommentPostStateTest extends BoardTestCase
{
private User $memberUser;
protected function getTestBoardSlug(): string
{
return 'comment-post-state';
}
protected function getDefaultBoardAttributes(string $slug): array
{
return [
'slug' => $slug,
'name' => ['ko' => '댓글 상태 게시판', 'en' => 'Comment State Board'],
'is_active' => true,
'use_comment' => true,
'max_comment_depth' => 5,
];
}
protected function setUp(): void
{
parent::setUp();
$this->setGuestPermissions(['posts.read', 'posts.write', 'comments.read', 'comments.write']);
$this->grantUserRolePermissions(['posts.read', 'posts.write', 'comments.read', 'comments.write']);
$this->memberUser = User::factory()->create(['email' => 'comment-post-state@test.com']);
$userRole = Role::where('identifier', 'user')->first();
if ($userRole) {
$this->memberUser->roles()->attach($userRole->id);
}
}
/**
* 요청 경로: 블라인드 게시글 댓글은 422 로 선차단된다
*
* @scenario entity=board_comment, post_state=blinded
*
* @effects blinded_post_comment_rejected_422
*/
public function test_request_path_rejects_comment_on_blinded_post(): void
{
$postId = $this->createTestPost(['status' => 'blinded']);
$this->actingAs($this->memberUser)
->postJson($this->storeUrl($postId), ['content' => '블라인드 글에 댓글'])
->assertStatus(422);
$this->assertDatabaseMissing('board_comments', ['post_id' => $postId]);
}
/**
* 요청 경로: 삭제된 게시글 댓글은 422 로 선차단된다
*
* @scenario entity=board_comment, post_state=deleted
*
* @effects deleted_post_comment_rejected_422
*/
public function test_request_path_rejects_comment_on_deleted_post(): void
{
$postId = $this->createTestPost(['status' => 'deleted']);
$this->actingAs($this->memberUser)
->postJson($this->storeUrl($postId), ['content' => '삭제된 글에 댓글'])
->assertStatus(422);
$this->assertDatabaseMissing('board_comments', ['post_id' => $postId]);
}
/**
* Service 직접 경로: 블라인드 게시글은 도메인 예외로 막힌다
*
* 베이스 `\Exception` 이면 컨트롤러 제네릭 catch 에 흡수되어 사유가 사라진다.
*
* @scenario entity=board_comment, post_state=blinded
*
* @effects blinded_post_comment_rejected_422
*/
public function test_service_direct_call_rejects_comment_on_blinded_post(): void
{
$postId = $this->createTestPost(['status' => 'blinded']);
$this->expectException(PostNotCommentableException::class);
$this->expectExceptionMessage(__('sirsoft-board::messages.comment.post_blinded'));
app(CommentService::class)->createComment($this->board->slug, [
'post_id' => $postId,
'content' => 'FormRequest 를 우회한 블라인드 글 댓글',
'user_id' => $this->memberUser->id,
]);
}
/**
* Service 직접 경로: 삭제된 게시글은 도메인 예외로 막힌다
*
* @scenario entity=board_comment, post_state=deleted
*
* @effects deleted_post_comment_rejected_422
*/
public function test_service_direct_call_rejects_comment_on_deleted_post(): void
{
$postId = $this->createTestPost(['status' => 'deleted']);
$this->expectException(PostNotCommentableException::class);
$this->expectExceptionMessage(__('sirsoft-board::messages.comment.post_deleted'));
app(CommentService::class)->createComment($this->board->slug, [
'post_id' => $postId,
'content' => 'FormRequest 를 우회한 삭제 글 댓글',
'user_id' => $this->memberUser->id,
]);
}
/**
* Service 직접 경로: soft-delete 된 게시글도 도메인 예외로 막힌다
*
* @scenario entity=board_comment, post_state=soft_deleted
*
* @effects deleted_post_comment_rejected_422
*/
public function test_service_direct_call_rejects_comment_on_soft_deleted_post(): void
{
$postId = $this->createTestPost(['deleted_at' => now()]);
$this->expectException(PostNotCommentableException::class);
$this->expectExceptionMessage(__('sirsoft-board::messages.comment.post_deleted'));
app(CommentService::class)->createComment($this->board->slug, [
'post_id' => $postId,
'content' => 'FormRequest 를 우회한 soft-delete 글 댓글',
'user_id' => $this->memberUser->id,
]);
}
/**
* 정상 게시글의 댓글 작성은 요청·Service 양 경로에서 그대로 통과한다 (과잉 차단 방지)
*
* @scenario entity=board_comment, post_state=published
*
* @effects published_post_comment_allowed
*/
public function test_comment_on_published_post_still_passes(): void
{
$postId = $this->createTestPost();
$this->actingAs($this->memberUser)
->postJson($this->storeUrl($postId), ['content' => '정상 댓글'])
->assertStatus(201);
$comment = app(CommentService::class)->createComment($this->board->slug, [
'post_id' => $postId,
'content' => 'Service 직접 호출 댓글',
'user_id' => $this->memberUser->id,
]);
$this->assertNotNull($comment->id);
}
/**
* 댓글 생성 엔드포인트 URL 을 생성합니다.
*
* @param int $postId 게시글 ID
* @return string 댓글 생성 URL
*/
private function storeUrl(int $postId): string
{
return "/api/modules/sirsoft-board/boards/{$this->board->slug}/posts/{$postId}/comments";
}
}
@@ -6,8 +6,10 @@ require_once __DIR__.'/../../ModuleTestCase.php';
use App\Extension\UpgradeContext;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\Sirsoft\Board\Tests\BoardTestCase;
use Modules\Sirsoft\Board\Upgrades\Upgrade_1_0_3;
use Psr\Log\LoggerInterface;
/**
* 1.0.3 댓글 계층 오염 데이터 정리 업그레이드 스텝 테스트
@@ -128,6 +130,124 @@ class CommentHierarchyCleanupTest extends BoardTestCase
$this->assertSame($first, $second, '재실행 결과가 동일해야 합니다.');
}
/**
* 부모 행이 삭제된 고아 댓글은 값이 보존되고 경고 로그가 남는다
*
* 정리 1단계는 부모와 INNER JOIN 하므로 부모 행 자체가 없는 댓글은 매칭되지 않고,
* 2단계 BFS 는 `parent_id IS NULL` 루트에서 출발하므로 이 댓글에 도달하지 못한다.
* 값을 임의로 고치거나 지우면 데이터 손실이므로 보존하되, 정정되지 않았다는 사실은
* 경고로 남겨야 한다.
*
* @scenario entity=board_comment, parent_target=missing
*
* @effects dangling_parent_skipped_with_warning
*/
public function test_dangling_parent_is_skipped_with_warning(): void
{
$post = $this->createTestPost(['title' => '게시글 A']);
$parent = $this->createTestComment($post, ['depth' => 0]);
$dangling = $this->createTestComment($post, ['parent_id' => $parent, 'depth' => 3]);
// 부모 행만 물리 삭제하여 dangling parent_id 상태를 만든다.
DB::table('board_comments')->where('id', $parent)->delete();
$logger = \Mockery::spy(LoggerInterface::class);
Log::shouldReceive('channel')
->with('extension-upgrade')
->andReturn($logger);
$this->runCleanup();
$this->assertDatabaseHas('board_comments', [
'id' => $dangling,
'parent_id' => $parent,
'depth' => 3,
]);
$logger->shouldHaveReceived('warning')
->withArgs(fn (string $message) => str_contains($message, '부모 행이 없는 댓글')
&& str_contains($message, (string) $dangling))
->once();
}
/**
* 루트에서 도달할 수 없는 순환 참조 댓글은 값이 보존되고 경고 로그가 남는다
*
* 부모 행이 실재하므로 고아 판정(`부모 행이 없는 댓글`)에 걸리지 않고,
* BFS 는 루트에서만 출발하므로 순환 컴포넌트에 진입조차 못 해 세대 상한에도
* 걸리지 않는다. 두 그물을 모두 빠져나가므로 전용 경고가 없으면
* "정정되지 않았다" 는 사실이 조용히 묻힌다.
*
* @scenario entity=board_comment, parent_target=cycle
*
* @effects unreachable_cycle_skipped_with_warning
*/
public function test_unreachable_cycle_is_skipped_with_warning(): void
{
$post = $this->createTestPost(['title' => '게시글 A']);
$first = $this->createTestComment($post, ['depth' => 0]);
$second = $this->createTestComment($post, ['parent_id' => $first, 'depth' => 1]);
// 첫 댓글의 부모를 두 번째로 돌려 루트 없는 순환(A→B→A)을 만든다.
DB::table('board_comments')->where('id', $first)->update([
'parent_id' => $second,
'depth' => 4,
]);
$logger = \Mockery::spy(LoggerInterface::class);
Log::shouldReceive('channel')
->with('extension-upgrade')
->andReturn($logger);
$this->runCleanup();
// 값 보존 — 순환의 어느 지점을 끊을지는 운영자 판단이므로 건드리지 않는다.
$this->assertDatabaseHas('board_comments', [
'id' => $first,
'parent_id' => $second,
'depth' => 4,
]);
$this->assertDatabaseHas('board_comments', [
'id' => $second,
'parent_id' => $first,
'depth' => 1,
]);
$logger->shouldHaveReceived('warning')
->withArgs(fn (string $message) => str_contains($message, '루트에서 도달하지 못한 댓글')
&& str_contains($message, (string) $first)
&& str_contains($message, (string) $second))
->once();
}
/**
* 정합한 계층만 있으면 순환 경고가 발생하지 않는다 (과잉 경고 방지)
*
* @scenario entity=board_comment, parent_target=self
*
* @effects healthy_hierarchy_emits_no_cycle_warning
*/
public function test_healthy_hierarchy_emits_no_cycle_warning(): void
{
$post = $this->createTestPost(['title' => '게시글 A']);
$root = $this->createTestComment($post, ['depth' => 0]);
$this->createTestComment($post, ['parent_id' => $root, 'depth' => 1]);
$logger = \Mockery::spy(LoggerInterface::class);
Log::shouldReceive('channel')
->with('extension-upgrade')
->andReturn($logger);
$this->runCleanup();
$logger->shouldNotHaveReceived('warning', [
\Mockery::on(fn (string $message) => str_contains($message, '루트에서 도달하지 못한 댓글')),
]);
}
/**
* 1.0.3 정리 마이그레이션을 실행합니다.
*/
@@ -0,0 +1,49 @@
# audit:allow test-scenario-coverage reason: |
# cross product 자동 전개는 audit 실행 환경의 fallback YAML 파서가 nested axes 를 읽지 못해
# 검출되지 않는다(다른 번들 시나리오와 동일 한계). 본 변경은 백엔드 전용(첨부 개수 불변조건)
# 이며 PHPUnit Feature 테스트가 경로·경계 조합을 커버하고 green 이다.
feature: 게시판 첨부파일 개수 상한 서버측 강제 (B3)
description: |
게시판 설정 `max_file_count` 를 모든 첨부 연결 경로에서 강제한다.
배경:
- `files[]` 직접 업로드만 FormRequest 가 막고 `attachment_ids` · `temp_key` ·
단일 업로드 반복 경로에는 개수 검사가 없었다. 같은 8개 파일을 `temp_key` 로 보내면
201 로 전부 연결되어 사용자 페이지에 그대로 노출됐다.
계층 결정:
- 총합은 직접 파일 + `attachment_ids` + `temp_key` 임시첨부 + 기존 첨부 4소스이고
temp_key 쪽은 DB 조회가 필요하므로 FormRequest 만으로 판정 불가
- `AttachmentService::assertAttachmentCountWithin()` 이 불변조건의 SSoT
- FormRequest 선차단은 "글 다 쓰고 저장 실패" 를 막는 UX 역할 (중복이지만 역할이 다름)
axes:
link_path: [direct_files, attachment_ids, temp_key, single_upload_repeat]
existing_state: [none, below_limit, at_limit]
request_count: [under, exact, over]
board_limit: [configured, unlimited]
exclusions:
- { board_limit: unlimited, request_count: over, reason: "상한 미설정 게시판은 제한하지 않음 (기존 동작)" }
effects:
- temp_key_link_over_limit_blocked
- temp_key_link_at_limit_passes
- existing_plus_new_over_limit_blocked
- existing_plus_new_at_limit_passes
- attachment_ids_path_counted_in_total
- single_upload_repeat_blocked_at_limit
- unlimited_board_not_restricted
- limit_violation_returns_422_not_500
- existing_over_limit_attachments_are_not_deleted
test_files:
- modules/_bundled/sirsoft-board/tests/Feature/AttachmentLimitTest.php
rules_layer_coverage:
- rule: i18n-throw-hardcoded-korean
coverage: AttachmentLimitExceededException 메시지는 sirsoft-board::messages.errors.attachment_limit_exceeded
- rule: service-direct-data-access
coverage: AttachmentService 는 AttachmentRepositoryInterface / BoardRepositoryInterface 만 사용
@@ -0,0 +1,63 @@
# audit:allow test-scenario-coverage reason: |
# cross product 자동 전개는 audit 실행 환경의 fallback YAML 파서가 nested axes 를 읽지 못해
# 검출되지 않는다(다른 번들 시나리오와 동일 한계). 본 변경은 백엔드 전용(댓글 깊이 불변조건 +
# 업그레이드 데이터 정정)이며 PHPUnit Feature 테스트가 경로·경계 조합을 커버하고 green 이다.
feature: 대댓글 깊이 상한 강제 + 포화 depth 데이터 정정 (B1)
description: |
게시판 설정 `max_comment_depth` 를 저장 시점에도 강제하고, 과거에 포화 저장된 depth 를
업그레이드에서 재계산한다.
배경:
- 검증(`CommentValidationRule`)은 부모의 *저장된* depth 로 판정하는데 저장 시
`min(parent.depth + 1, 5)` 로 포화시켰다. 부모 depth 가 5 를 넘지 못하니
`max_comment_depth=10` 게시판에서 판정식이 영원히 참이 되지 않아 **무한 중첩**이 가능했다.
- 실측: 20단 중첩이 전부 201 로 저장되고 depth 가 `0,1,2,3,4,5,5,5,…` 로 5 에서 포화.
계층 결정:
- 저장부의 리터럴 클램프를 제거하고 `부모 depth + 1` 을 그대로 쓴다
(검증을 통과한 값이므로 클램프가 불필요).
- 방어적 상한은 두되 **초과 시 클램프가 아니라 예외** — 클램프가 이 버그의 원인이었다.
- 코드 수정만으로는 결함이 닫히지 않는다. 기존 스레드의 부모 depth 가 5 로 고정되어 있어
그 스레드에서는 계속 우회가 가능하므로 업그레이드 데이터 정정이 함께 필요하다.
데이터 정정 규율:
- 루트(`parent_id IS NULL`)부터 **레벨 단위 청크 UPDATE**(재귀 금지), 방문 집합으로 유한 종료
- 재계산 결과가 상한을 넘어도 **값만 정정, 삭제 금지**
- 루트에서 도달하지 못한 행(고아 부모 / 순환 컴포넌트)은 값 보존 + 경고 로그
axes:
entity: [board_comment]
parent_target: [unrelated, foreign, missing, cycle, self]
board_max_depth: [zero, lowered, default]
request_depth: [under, exact, over]
entry_path: [http_user, http_admin, service_direct]
exclusions:
- { board_max_depth: zero, request_depth: under, reason: "상한 0 은 대댓글 자체가 불가 — 하위 조합 없음" }
- { parent_target: missing, entry_path: http_user, reason: "고아 부모는 업그레이드 정정 축이며 등록 경로 조합이 아님" }
- { parent_target: cycle, entry_path: http_user, reason: "순환은 앱 경로로 생성 불가 — 오염 데이터 정정 축" }
effects:
- depth_equals_parent_depth_plus_one
- depth_follows_board_setting_not_literal
- depth_beyond_board_max_rejected_422
- existing_clamped_depth_recalculated
- existing_cross_post_parent_detached_content_preserved
- dangling_parent_skipped_with_warning
- unreachable_cycle_skipped_with_warning
- healthy_hierarchy_emits_no_cycle_warning
- cleanup_is_idempotent
test_files:
- modules/_bundled/sirsoft-board/tests/Feature/CommentDepthLimitTest.php
- modules/_bundled/sirsoft-board/tests/Feature/Upgrade/CommentHierarchyCleanupTest.php
rules_layer_coverage:
- rule: i18n-throw-hardcoded-korean
coverage: CommentDepthExceededException 메시지는 sirsoft-board::validation.comment.depth.exceeded
- rule: service-config-value-clamp
coverage: CommentService 의 리터럴 클램프 제거 — 이 룰이 재유입을 검출한다
- rule: upgrade-step-path-a
coverage: 정정 스텝은 Facades\DB/Schema 만 사용하고 로직을 private 헬퍼로 로컬 완결
@@ -17,7 +17,8 @@ use Illuminate\Support\Facades\Schema;
* 콘텐츠는 건드리지 않으며 depth 컬럼만 갱신하므로 결정론적입니다.
*
* idempotent: 이미 정합한 행은 갱신 대상에서 제외되어 재실행해도 결과가 같습니다.
* 순환 참조가 남아 있어도 방문 ID 집합으로 유한 종료합니다.
* 순환 참조가 남아 있어도 방문 ID 집합으로 유한 종료하며, 루트에서 도달하지 못한
* 행(고아 부모 / 순환 컴포넌트)은 값을 보존한 채 경고 로그로 남깁니다.
* V-1 안전: Facades\DB/Schema 만 사용.
*/
class RecalculateCommentDepth implements DataMigration
@@ -84,6 +85,9 @@ class RecalculateCommentDepth implements DataMigration
));
}
$this->logOrphanParents($context);
$this->logUnreachableComments($context, $visited);
$context->logger->info(sprintf(
'[board:1.0.3] depth 재계산 완료 — %d 건 갱신 (최대 세대 %d)',
$updated,
@@ -180,6 +184,94 @@ class RecalculateCommentDepth implements DataMigration
return $updated;
}
/**
* 부모 행이 존재하지 않는 고아 댓글을 경고 로그로 남깁니다.
*
* BFS 는 `parent_id IS NULL` 인 루트에서만 출발하므로, 부모가 이미 삭제된 댓글은
* 어느 세대에도 도달하지 못해 depth 가 옛 값 그대로 남는다. 값을 임의로 고치거나
* 행을 지우면 데이터 손실이므로 건드리지 않되, 정정되지 않았다는 사실은 남긴다.
*
* @param UpgradeContext $context 업그레이드 컨텍스트
*/
private function logOrphanParents(UpgradeContext $context): void
{
$orphanIds = DB::table(self::TABLE.' as c')
->whereNotNull('c.parent_id')
->whereNotExists(function ($query) {
$query->select('p.id')
->from(self::TABLE.' as p')
->whereColumn('p.id', 'c.parent_id');
})
->pluck('c.id')
->all();
if ($orphanIds === []) {
return;
}
$context->logger->warning(sprintf(
'[board:1.0.3] 부모 행이 없는 댓글 %d 건 — depth 재계산에서 스킵(값 보존). 대상 id: %s',
count($orphanIds),
json_encode(array_map('intval', $orphanIds), JSON_UNESCAPED_UNICODE)
));
}
/**
* 루트에서 도달하지 못한 댓글(순환 참조 컴포넌트)을 경고 로그로 남깁니다.
*
* 부모 행이 존재하는데도 BFS 가 방문하지 못했다면 그 부모 역시 도달 불가라는 뜻이고,
* 거슬러 올라가면 루트가 없는 순환(A→B→A)에 닿는다. 이런 행은 세대 상한에 걸리지도
* (BFS 가 진입 자체를 못 함) 고아 판정에 걸리지도(부모 행은 실재함) 않아,
* 경고가 없으면 정정되지 않은 사실이 조용히 묻힌다.
*
* 값은 건드리지 않는다 — 순환의 어느 지점을 끊을지는 운영자 판단 영역이다.
*
* @param UpgradeContext $context 업그레이드 컨텍스트
* @param array<int, bool> $visited BFS 가 방문한 댓글 ID 집합
*/
private function logUnreachableComments(UpgradeContext $context, array $visited): void
{
$cycleIds = [];
$lastId = 0;
while (true) {
$ids = DB::table(self::TABLE.' as c')
->whereNotNull('c.parent_id')
->where('c.id', '>', $lastId)
->whereExists(function ($query) {
$query->select('p.id')
->from(self::TABLE.' as p')
->whereColumn('p.id', 'c.parent_id');
})
->orderBy('c.id')
->limit(self::CHUNK)
->pluck('c.id')
->all();
if ($ids === []) {
break;
}
foreach ($ids as $id) {
$lastId = (int) $id;
if (! isset($visited[$lastId])) {
$cycleIds[] = $lastId;
}
}
}
if ($cycleIds === []) {
return;
}
$context->logger->warning(sprintf(
'[board:1.0.3] 루트에서 도달하지 못한 댓글 %d 건 — 순환 참조로 보이며 depth 재계산에서 스킵(값 보존). 대상 id: %s',
count($cycleIds),
json_encode($cycleIds, JSON_UNESCAPED_UNICODE)
));
}
/**
* 갱신 대상의 변경 전 상태를 로그로 남깁니다 (복구 근거).
*
@@ -6,6 +6,16 @@
## [1.0.5] - 2026-07-16
### Security
- 관리자가 설정한 마일리지 사용 정책(최소 사용액·사용 단위·최대 사용 한도)이 주문서 작성과 주문 확정 양쪽에서 실제로 적용됩니다. 이전에는 보유 잔액만 확인해, 사용 한도를 30%로 제한해 두어도 결제금액 전액을 마일리지로 결제할 수 있었습니다. 한도를 넘으면 사용 가능한 최대 금액을 함께 안내합니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 주문에는 주문 시점의 마일리지 사용 정책이 함께 보관됩니다. 이후 관리자가 한도를 바꿔도 과거 주문이 어떤 기준으로 성립했는지 확인할 수 있습니다. (기존 주문은 당시 설정을 알 수 없어 비어 있습니다.) (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 무통장입금 기한이 주문 요청에 실린 값으로 정해지던 문제를 수정했습니다. 이제 가상계좌와 동일하게 관리자 환경설정의 미입금 자동취소 기한만 사용합니다. 이전에는 안내된 입금기한과 자동취소 시점이 어긋날 수 있었습니다. 이미 생성된 주문의 기한은 그대로 유지됩니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 장바구니 담기 수량 제한이 실제로 적용되도록 수정했습니다. 설정값(상품당 99개)이 화면·저장 어디에도 반영되지 않아 한 번에 9,999개까지 담을 수 있었고, 이미 담긴 수량과 합산되는 경우에는 제한 자체가 없었습니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 장바구니 수량 제한 안내 문구가 실제 설정값을 알려 주도록 수정했습니다. 이전에는 설정과 무관하게 "최대 9,999개까지 가능"으로 고정 표시돼, 안내받은 수량보다 적은 수량에서 저장이 막혔습니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 상품의 최대 구매수량 제한이 장바구니 담기와 옵션 변경에서도 적용되도록 수정했습니다. 이전에는 수량 변경 화면에서만 검사해, 담기나 옵션 변경으로는 한도를 넘길 수 있었습니다. 비회원 장바구니가 로그인 시 합쳐질 때는 로그인이 실패하지 않도록 한도까지 자동 조정하고 조정 내역을 함께 알려 줍니다. 이때 같은 상품을 옵션별로 나눠 담아 한도를 넘기는 것도 함께 막습니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 재주문으로 장바구니에 담을 때도 상품의 최대 구매수량 제한이 적용됩니다. 한도를 넘는 항목은 품절 상품과 같이 사유와 함께 제외되고, 나머지 항목은 정상적으로 담깁니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
### Added
- 사이트맵에 담을 상품·카테고리 수의 안전 상한을 지원합니다. 상한을 설정하면 상품 목록·카테고리·상품 어느 항목이든 그 수를 넘지 않으며, 상한에 걸려 일부가 빠진 경우 기록으로 남습니다.
@@ -14,11 +24,20 @@
### Changed
- 실제로 사용되지 않던 설정 항목(상품·주문 목록의 페이지당 개수, 결제 자동취소 기한 중복 항목)을 정리했습니다. 미입금 자동취소 기한은 관리자 환경설정의 값 하나만 사용합니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 사이트맵을 만들 때 상품과 카테고리를 한 번에 모두 메모리에 올리지 않고 나눠서 읽도록 바꿨습니다. 상품이 많은 쇼핑몰에서 사이트맵 생성 중 메모리가 부족해 실패하던 문제가 줄어듭니다.
- 개선된 사이트맵 생성 기능을 사용하기 위해 이 모듈은 이제 코어 7.0.6 이상이 필요합니다.
### Fixed
- 로그인하지 않은 상태로 장바구니에 담아 둔 상품이 로그인 후 사라지던 문제를 수정했습니다. 로그인 시 장바구니를 회원 계정으로 옮기는 처리가 실행되지 않아, 담아 둔 상품이 아무 안내 없이 없어졌습니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 설정 화면이 허용하는 값과 저장 규칙이 서로 달라 저장이 거부되거나 그 반대가 되던 항목들을 맞췄습니다. 리뷰 이미지 최대 개수(최대 20개), 리뷰 이미지 최대 크기(정수 MB, 최대 50MB), 마일리지 기본 적립률(최대 100%), 미입금 자동취소 기한(최소 1일 — 0일은 주문 즉시 만료라 사용할 수 없는 값)이 대상입니다. 정수만 받는 항목은 입력칸의 증감 단위도 1로 맞춰, 화살표로 값을 올리다 소수가 되어 저장이 거부되는 일이 없습니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 상품 고시정보 템플릿 목록에서 한 번에 가져올 개수에 상한(100개)을 두었습니다. 이전에는 임의의 큰 값을 넘겨 한 요청으로 전체 데이터를 가져갈 수 있었습니다. '전체' 조회는 종전대로 동작합니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 상품 옵션의 정률 적립률을 100%를 넘겨 저장할 수 있던 문제를 수정했습니다. 전체 기본 적립률은 100%까지만 허용되는데 옵션별 적립률에는 상한이 없어, 결제금액보다 많은 마일리지가 적립되도록 설정할 수 있었습니다. 정액(원 단위) 적립은 종전처럼 상한이 없습니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 상품·옵션 일괄 수정에서 가격 검증이 등록/수정 화면보다 느슨하던 문제를 수정했습니다. 원화처럼 소수점을 쓰지 않는 통화에서 소수 가격이 저장되거나, 판매가가 정가보다 크게 저장되거나, 0원으로 저장되던 경우가 막힙니다. 정가·판매가 중 한쪽만 수정하는 경우도 저장된 나머지 값과 함께 판정하므로, 판매가만 정가 위로 올려 저장할 수 없습니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 부분취소 후에도 주문의 부가세가 취소 전 금액으로 남아 과세표준과 어긋나던 문제를 수정했습니다. 취소로 과세표준이 줄면 부가세도 함께 다시 계산되며, 계산에는 주문 당시의 세율이 사용됩니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 주문의 부가세가 항상 0으로 표시되던 문제를 수정했습니다. 부가세는 부분취소를 거친 주문에서만 채워져 같은 목록에서도 주문마다 세금 표기가 달랐습니다. 이제 주문을 만들 때 계산해 기록하며, 상품별 세율이 다르면 상품별로 계산해 합산합니다. 기존 주문의 부가세는 업데이트 시 자동으로 채워지며, 채운 주문 건수가 업그레이드 로그에 남습니다(이미 값이 있는 주문은 건드리지 않습니다). (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 주문서의 마일리지 '사용 가능 최대' 안내가 실제 결제 기준 금액과 최소 사용액을 반영하도록 수정했습니다. 이전에는 할인·배송비 반영 전 상품합계를 기준으로 계산해 실제로 쓸 수 있는 금액보다 크게 안내되었고, 최소 사용액에 못 미치는 경우에도 사용 가능한 것처럼 보였습니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
- 휴대폰으로 관리자 주문 목록을 볼 때 왼쪽 위 '뒤로' 버튼을 누르면 이전 화면이 아니라 빈 페이지로 넘어가던 문제를 수정했습니다.
- 관리자 주문·상품·쿠폰·배송정책·리뷰·마일리지 목록에서 상세나 등록/수정 화면에 다녀오면 걸어 둔 필터와 페이지가 사라지던 문제를 수정했습니다. 필터를 여러 개 건 상태에서 주문 하나를 확인하고 돌아와도 조건이 그대로 유지됩니다. 정렬·표시 개수를 바꾸거나 새로고침해도 걸어 둔 조건은 그대로입니다. 반대로 초기화 버튼과 프리셋 적용은 종전처럼 조건을 새로 세팅합니다. (#75 @jiwonpapa 님께서 제보해주셨습니다.)
- 관리자 브랜드·상품 공통정보·상품 고시정보 목록에서 검색어(브랜드는 정렬 포함)를 걸어 둔 채 새로고침 버튼을 누르면 걸어 둔 검색이 풀려 전체 목록으로 돌아가던 문제를 수정했습니다. 이제 새로고침은 보던 조건 그대로 다시 불러옵니다. (#75 @jiwonpapa 님께서 제보해주셨습니다.)
@@ -17,7 +17,6 @@ return [
// 상품 설정
'product' => [
'per_page' => 12,
'max_images' => 10,
'max_image_size' => 5 * 1024 * 1024, // 5MB
'allowed_extensions' => ['jpg', 'jpeg', 'png', 'gif', 'webp'],
@@ -25,14 +24,13 @@ return [
// 주문 설정
'order' => [
'per_page' => 20,
'order_number_prefix' => 'ORD',
],
// 결제 설정
'payment' => [
// 미입금 주문 자동취소 기한 (일) — 결제수단 무관 단일 SSoT
'auto_cancel_days' => 3,
// 미입금 주문 자동취소 기한은 관리자 환경설정 order_settings.auto_cancel_days 가 SSoT 다.
// 여기에 같은 이름의 값을 두면 두 번째 SSoT 가 되어 어느 쪽이 적용되는지 알 수 없어진다.
// 입금 기한 만료 시 자동 취소 여부
'auto_cancel_expired' => true,
@@ -85,6 +83,53 @@ return [
'max_image_size_mb' => 10, // 리뷰 이미지 최대 크기 (MB)
],
/*
|--------------------------------------------------------------------------
| 환경설정 입력 한계값
|--------------------------------------------------------------------------
| 관리자 환경설정 화면의 숫자 입력 경계값(min/max)과 저장 검증 규칙이 공유하는 단일 출처.
| 규칙(StoreEcommerceSettingsRequest)이 이 값을 읽어 규칙 문자열을 만들고,
| 화면은 설정 응답의 `_meta.limits` 로 같은 값을 받아 바인딩한다.
*/
'limits' => [
// 주문
'auto_cancel_days_min' => 1,
'auto_cancel_days_max' => 30,
'cart_expiry_days_min' => 1,
'cart_expiry_days_max' => 365,
// 마일리지 (전역)
'default_earn_rate_min' => 0,
'default_earn_rate_max' => 100,
'earn_delay_days_min' => 0,
'earn_delay_days_max' => 365,
'expiry_days_min' => 1,
'expiry_days_max' => 3650,
'expiry_notification_days_before_min' => 1,
'expiry_notification_days_before_max' => 365,
// 마일리지 (통화별 규칙 행)
'point_value_min' => 0.001,
'min_use_amount_min' => 0,
'use_unit_min' => 1,
'max_use_percent_min' => 0,
'max_use_percent_max' => 100,
'max_use_value_min' => 0,
'max_use_value_max' => 1000000000,
// 통화 행
'decimal_places_min' => 0,
'decimal_places_max' => 8,
// 리뷰
'write_deadline_days_min' => 1,
'write_deadline_days_max' => 365,
'max_images_min' => 0,
'max_images_max' => 20,
'max_image_size_mb_min' => 1,
'max_image_size_mb_max' => 50,
],
// 관리자 대시보드 이커머스 영역 설정
'dashboard' => [
'scheduler_enabled' => true, // 판매 현황 집계 스케줄러(hourly) 활성화 여부
@@ -35,7 +35,11 @@ class OrderOptionFactory extends Factory
'order_id' => Order::factory(),
'parent_option_id' => null,
'product_id' => Product::factory(),
'product_option_id' => ProductOption::factory(),
// 연결 옵션의 재고는 아래 option_snapshot 이 적는 값(100)과 맞춘다.
// ProductOption 기본 정의는 재고를 0~100 난수로 뽑는데, 주문 수량(1~5)보다 작게
// 뽑히면 결제 완료 시 재고 차감이 실패해 주문 상태를 다루는 테스트가 재고 부족으로
// 무작위 실패한다. 재고 부족 시나리오는 그 상태를 명시하는 테스트가 따로 지정한다.
'product_option_id' => ProductOption::factory()->state(['stock_quantity' => 100]),
'option_status' => OrderStatusEnum::PENDING_ORDER,
'source_type' => 'order',
'source_option_id' => null,
@@ -0,0 +1,53 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* 주문 시점 마일리지 사용 정책 스냅샷을 주문에 보존 (E1).
* 통화·프로모션·배송정책은 이미 주문 시점 스냅샷을 남기는데 마일리지 사용 정책
* (최소 사용액/사용 단위/최대 한도)만 빠져 있었다. 관리자가 이후 한도를 변경하면
* 과거 주문이 어떤 정책 아래 성립했는지 재현할 수 없어 정산·감사·분쟁 대응이 불가하다.
* 기존 주문은 당시 설정을 알 수 없으므로 백필하지 않고 null 로 둔다(정책 미상).
*/
public function up(): void
{
if (! Schema::hasTable('ecommerce_orders')) {
return;
}
if (Schema::hasColumn('ecommerce_orders', 'mileage_policy_snapshot')) {
return;
}
Schema::table('ecommerce_orders', function (Blueprint $table) {
$table->mediumText('mileage_policy_snapshot')
->nullable()
->after('shipping_policy_applied_snapshot')
->comment('주문 시점 마일리지 사용 정책 스냅샷 (최소 사용액/사용 단위/한도 재현용)');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
if (! Schema::hasTable('ecommerce_orders')) {
return;
}
if (! Schema::hasColumn('ecommerce_orders', 'mileage_policy_snapshot')) {
return;
}
Schema::table('ecommerce_orders', function (Blueprint $table) {
$table->dropColumn('mileage_policy_snapshot');
});
}
};
@@ -415,15 +415,48 @@ Authorization: Bearer {YOUR_TOKEN} (optional.sanctum: 비회원은 헤더 생
**응답 필드** (`data` 내부)
<!-- 실측 제외: write-method — 응답 필드는 사람이 작성하세요. -->
| 필드 | 타입 | 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| merged_count | integer | `2` | 회원 장바구니로 옮겨진 비회원 아이템 수 |
| adjustments | array | `[]` | 병합 과정에서 수량이 상한으로 줄어든 항목 목록 (조정이 없으면 빈 배열) |
| adjustments[].product_id | integer | `12` | 조정된 상품 ID |
| adjustments[].product_option_id | integer | `34` | 조정된 상품 옵션 ID |
| adjustments[].requested | integer | `10` | 병합 시 합산된 수량 |
| adjustments[].applied | integer | `5` | 상한 적용 후 실제 저장된 수량 |
> 병합은 로그인 흐름에서 자동 수행되므로 수량 상한을 넘겨도 예외를 던지지 않고 상한까지 줄입니다.
> 줄어든 사실을 사용자에게 알릴 수 있도록 `adjustments` 를 확인해 안내하세요.
**응답 예시**
<!-- 실측 제외: http-422 — 응답 예시는 사람이 작성하세요. -->
```http
HTTP/1.1 200
```
```json
{
"success": true,
"message": "장바구니를 병합했습니다.",
"data": {
"merged_count": 2,
"adjustments": [
{
"product_id": 12,
"product_option_id": 34,
"requested": 10,
"applied": 5
}
]
}
}
```
**에러 응답**
_대표 에러 없음 (공개 조회). <!-- TODO: 도메인 특이 에러가 있으면 보강 -->_
| 상태 | 조건 | 응답 |
| --- | --- | --- |
| 422 | 미로그인 상태이거나 `X-Cart-Key` 헤더가 없음/형식 불일치 | `errors.auth` 또는 `errors.cart_key` |
| 500 | 병합 처리 실패 | `messages.cart.merge_failed` |
<!-- @generated:end -->
@@ -611,7 +644,7 @@ Authorization: Bearer {YOUR_TOKEN} (optional.sanctum: 비회원은 헤더 생
| --- | --- | --- | --- | --- | --- |
| id | path | string | 예 | — | 대상 리소스의 식별자 |
| product_option_id | body | integer | 예 | — | product option 식별자 |
| quantity | body | integer | 예 | min 1, max 9999 | 변경할 구매 수량 (1~9999) |
| quantity | body | integer | 예 | min 1, max: 장바구니 수량 상한 설정 | 변경할 구매 수량 (1 ~ 관리자 설정 상한, 기본 99) |
| additional_option_selections | body | array | 아니오 | — | 추가 옵션 재선택 목록 (항목별 additional_option_id/value_id, 직접입력 custom_text — 미전달 시 기존 선택 유지) |
> 이 엔드포인트는 확장이 파라미터를 추가할 수 있습니다 (`sirsoft-ecommerce.cart.change_option_validation_rules`).
@@ -665,7 +698,7 @@ Content-Type: application/json
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
| --- | --- | --- | --- | --- | --- |
| id | path | string | 예 | — | 대상 리소스의 식별자 |
| quantity | body | integer | 예 | min 1, max 9999 | 변경할 구매 수량 (1~9999) |
| quantity | body | integer | 예 | min 1, max: 장바구니 수량 상한 설정 | 변경할 구매 수량 (1 ~ 관리자 설정 상한, 기본 99) |
> 이 엔드포인트는 확장이 파라미터를 추가할 수 있습니다 (`sirsoft-ecommerce.cart.update_quantity_validation_rules`).
@@ -700,6 +733,6 @@ Content-Type: application/json
<!-- @generated:end -->
**설명** 장바구니 아이템(`id`)의 수량만 변경합니다. `optional.sanctum`으로 회원/비회원 모두 접근하며, `CartController@updateQuantity`가 `CartService::updateQuantity()`로 수량을 반영한 뒤 프론트가 별도 refetch 없이 화면을 갱신할 수 있도록 `index`와 동일한 전체 목록·계산 결과(`items`·`calculation`)를 함께 반환합니다. 수량은 1~9999 범위이며, 재고 부족·판매 중지·구매수량 한도 위반은 사유별 422, 항목/권한 문제는 404/403으로 매핑됩니다. 장바구니의 수량 증감(+/-) 컨트롤에 사용합니다.
**설명** 장바구니 아이템(`id`)의 수량만 변경합니다. `optional.sanctum`으로 회원/비회원 모두 접근하며, `CartController@updateQuantity`가 `CartService::updateQuantity()`로 수량을 반영한 뒤 프론트가 별도 refetch 없이 화면을 갱신할 수 있도록 `index`와 동일한 전체 목록·계산 결과(`items`·`calculation`)를 함께 반환합니다. 수량 상한은 관리자 환경설정의 장바구니 수량 상한(기본 99)을 따르며, 재고 부족·판매 중지·구매수량 한도 위반은 사유별 422, 항목/권한 문제는 404/403으로 매핑됩니다. 장바구니의 수량 증감(+/-) 컨트롤에 사용합니다.
@@ -96,6 +96,8 @@ Authorization: Bearer {YOUR_TOKEN} (optional.sanctum: 비회원은 헤더 생
**설명** 현재 유효한 임시 주문을 조회하면서 최신 가격으로 실시간 재계산해 주문서 페이지 데이터를 반환합니다. `optional.sanctum`으로 회원/비회원 모두 접근하며, `CheckoutController@show`가 `TempOrderService::getTempOrderWithCalculation()`으로 재계산하고 `CheckoutDataService::buildResponseData()`가 쿠폰·마일리지·상품·구매불가 상품 정보를 포함해 응답을 구성합니다. 쿼리로 `country_code`/`zipcode`/`region` 등 배송 주소를 전달하면 해당 주소 기준 배송비가 계산되며, 우편번호 없이 배송국가만으로도 미리보기 배송비를 산출합니다. 임시 주문이 만료·미존재면 404를 반환합니다.
응답의 `mileage_info` 에는 잔액(`available`)·사용 가능 최대(`max_usable`)·사용 가능 여부(`usable`)와 함께 사용 정책 `usage_policy`(`min_use_amount`, `use_unit`, `max_use_amount`)가 포함됩니다. `max_usable` 과 `usage_policy.max_use_amount` 는 저장 API 가 판정하는 기준(마일리지 차감 전 결제금액)과 동일한 기준으로 산출되므로, 입력 UI 는 이 값을 그대로 상·하한으로 사용하면 됩니다. 조회는 사용 한도를 초과한 임시 주문이 있어도 200 을 반환합니다(차단은 저장 시점에서만).
### POST /api/modules/sirsoft-ecommerce/checkout
<!-- @generated:start:api.modules.sirsoft-ecommerce.checkout.store -->
@@ -153,7 +155,9 @@ Content-Type: application/json
<!-- @generated:end -->
**설명** 장바구니에서 선택한 아이템으로 임시 주문을 생성해 주문서 작성 단계로 진입합니다. `optional.sanctum`으로 회원/비회원 모두 접근하며, `CheckoutController@store`가 `direct_items`가 있으면 `TempOrderService::createTempOrderFromDirectItems()`(바로 구매, 장바구니 미경유), 없으면 `item_ids`로 `createTempOrderFromSelectedItems()`(장바구니 경유)를 호출합니다. 응답에는 임시 주문 ID·계산 결과·만료 시각(`expires_at`)이 포함됩니다. 재고 부족·판매 중지·구매 제한 상품이 있으면 400(cart_unavailable), 보유 잔액을 넘는 마일리지 사용은 422, 빈 장바구니는 400을 반환합니다.
**설명** 장바구니에서 선택한 아이템으로 임시 주문을 생성해 주문서 작성 단계로 진입합니다. `optional.sanctum`으로 회원/비회원 모두 접근하며, `CheckoutController@store`가 `direct_items`가 있으면 `TempOrderService::createTempOrderFromDirectItems()`(바로 구매, 장바구니 미경유), 없으면 `item_ids`로 `createTempOrderFromSelectedItems()`(장바구니 경유)를 호출합니다. 응답에는 임시 주문 ID·계산 결과·만료 시각(`expires_at`)이 포함됩니다. 재고 부족·판매 중지·구매 제한 상품이 있으면 400(cart_unavailable), 빈 장바구니는 400을 반환합니다.
마일리지 사용은 보유 잔액뿐 아니라 관리자 설정 사용 정책(최소 사용액 `min_use_amount`, 사용 단위 `use_unit`, 최대 한도 `max_use_percent`/`max_use_value`)까지 서버에서 강제하며, 위반 시 422 를 반환합니다. 한도 초과 응답 메시지에는 사용 가능한 최대 금액이 함께 안내됩니다. 판정 기준 금액은 마일리지 차감 전 결제금액이며, 비회원의 `use_points` 는 예외 없이 0 으로 처리됩니다.
### PUT /api/modules/sirsoft-ecommerce/checkout
@@ -214,7 +218,7 @@ Content-Type: application/json
<!-- @generated:end -->
**설명** 주문서 작성 중 쿠폰·마일리지·배송 주소가 변경될 때 임시 주문 금액을 재계산합니다. `optional.sanctum`으로 회원/비회원 모두 접근하며, `CheckoutController@update`가 전송된 프로모션 필드(`item_coupons`·`order_coupon_issue_id`·`shipping_coupon_issue_id`)와 `use_points`만 반영하고 미전송 필드는 `TempOrderService::updateTempOrder()`에서 기존 값을 유지합니다. `zipcode`/`country_code`로 배송 주소를 함께 넘기면 배송비가 다시 계산됩니다. 임시 주문이 만료·미존재면 404, 보유 잔액 초과 마일리지는 422를 반환합니다.
**설명** 주문서 작성 중 쿠폰·마일리지·배송 주소가 변경될 때 임시 주문 금액을 재계산합니다. `optional.sanctum`으로 회원/비회원 모두 접근하며, `CheckoutController@update`가 전송된 프로모션 필드(`item_coupons`·`order_coupon_issue_id`·`shipping_coupon_issue_id`)와 `use_points`만 반영하고 미전송 필드는 `TempOrderService::updateTempOrder()`에서 기존 값을 유지합니다. `zipcode`/`country_code`로 배송 주소를 함께 넘기면 배송비가 다시 계산됩니다. 임시 주문이 만료·미존재면 404, 보유 잔액 초과 또는 사용 정책(최소 사용액·사용 단위·최대 한도) 위반 마일리지는 422를 반환합니다.
### POST /api/modules/sirsoft-ecommerce/checkout/extend
@@ -1394,6 +1394,8 @@ Content-Type: application/json
**설명** 주문서 작성을 마치고 실제 주문을 생성(결제하기)하는 회원/비회원 공용 엔드포인트입니다. PG 플러그인의 fetch 인터셉터가 이 한 경로만 매칭하므로 회원/비회원이 동일 URL로 진입하고, `Public\OrderController@store`가 `Auth::id()`로 분기합니다(회원은 `OrderResource`, 비회원은 민감 필드를 가린 `GuestOrderResource`). `optional.sanctum` + `sirsoft-ecommerce.user-orders.create` 권한이 필요하며, `expected_total_amount`로 금액 위변조를 검증하고 비회원은 `guest_lookup_password`로 이후 조회 비밀번호를 설정합니다. 회원이 `save_shipping_address`를 켜면 배송지가 자동 저장(PG 결제는 결제완료 시점) 됩니다.
주문 확정 시점에는 재고·구매대상제한·배송국가·쿠폰 유효성과 함께 **마일리지 사용 정책**도 현재 설정 기준으로 재검증합니다. 임시 주문을 만든 뒤 관리자가 한도를 강화했거나 임시 주문이 조작된 경우 `422`(`errors.code = mileage_usage_not_allowed`)로 차단되며 주문은 생성되지 않습니다. 반대로 정상 생성된 주문에는 그 시점의 사용 정책이 `mileage_policy_snapshot` 으로 고정되어, 이후 설정이 바뀌어도 해당 주문의 판정 근거를 재현할 수 있습니다(통화·프로모션·배송정책 스냅샷과 동일 취지).
### GET /api/modules/sirsoft-ecommerce/user/orders/{id}
<!-- @generated:start:api.modules.sirsoft-ecommerce.user.orders.show-by-id -->
@@ -1851,7 +1853,7 @@ _단건 응답: `data` 객체의 필드._
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| added_count | integer | `0` | added 개수 (집계) |
| skipped | array | `[]` | 장바구니에 담지 못한 항목 목록 (품절·단종 등으로 재주문에서 건너뛴 옵션) |
| skipped | array | `[]` | 장바구니에 담지 못한 항목 목록 (품절·단종·구매수량 한도 초과 등으로 재주문에서 건너뛴 옵션) |
| cart_count | integer | `0` | cart 개수 (집계) |
**응답 예시**
@@ -1881,7 +1883,7 @@ HTTP/1.1 200
<!-- @generated:end -->
**설명** 회원이 과거 주문(`id`)의 옵션들을 현재 장바구니에 다시 담는 재주문 기능입니다. `auth:sanctum` 인증이 필요하며, `User\OrderController@reorder`가 `CartService::reorderFromOrder()`로 처리해 담긴 수량(`added_count`), 담지 못한 항목(`skipped[]`), 현재 장바구니 총 개수(`cart_count`)를 반환합니다. 취소된 주문도 재주문 대상이 되며, 품절·단종 등으로 추가 불가한 항목은 건너뛰어 `skipped` 배열로 안내합니다. 마이페이지 주문내역의 "재주문" 버튼에 사용합니다.
**설명** 회원이 과거 주문(`id`)의 옵션들을 현재 장바구니에 다시 담는 재주문 기능입니다. `auth:sanctum` 인증이 필요하며, `User\OrderController@reorder`가 `CartService::reorderFromOrder()`로 처리해 담긴 수량(`added_count`), 담지 못한 항목(`skipped[]`), 현재 장바구니 총 개수(`cart_count`)를 반환합니다. 취소된 주문도 재주문 대상이 되며, 품절·단종·상품별 구매수량 한도 초과 등으로 추가 불가한 항목은 건너뛰어 `skipped` 배열로 안내합니다. 한 항목이 담기지 못해도 나머지 항목은 그대로 담기며, 응답은 200 입니다(항목 하나 때문에 재주문 전체를 실패시키지 않습니다). 마이페이지 주문내역의 "재주문" 버튼에 사용합니다.
### PUT /api/modules/sirsoft-ecommerce/user/orders/{id}/shipping-address
@@ -29,7 +29,7 @@
| --- | --- | --- | --- | --- | --- |
| search | query | string | 아니오 | max 200 | 검색어 (지정한 검색 대상 필드에서 부분 일치) |
| active_only | query | boolean | 아니오 | — | true 시 활성(is_active) 템플릿만 조회 |
| per_page | query | string | 아니오 | — | 페이지당 항목 수 |
| per_page | query | string | 아니오 | 정수 1~100 또는 `all` | 페이지당 항목 수 (`all` 은 전체 조회, 숫자는 최대 100) |
| page | query | integer | 아니오 | min 1 | 조회할 페이지 번호 (1부터 시작) |
**요청 예시**
@@ -2003,6 +2003,17 @@ HTTP/1.1 200
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
| --- | --- | --- | --- | --- | --- |
| product | path | string | 예 | — | 대상 product의 식별자 |
| copy_images | query | boolean | 아니오 | true/false (기본 true) | 상품 이미지 복사 여부 |
| copy_options | query | boolean | 아니오 | true/false (기본 true) | 옵션 복사 여부 |
| copy_categories | query | boolean | 아니오 | true/false (기본 true) | 카테고리 연결 복사 여부 |
| copy_sales_info | query | boolean | 아니오 | true/false (기본 true) | 판매 정보(가격·재고·상태) 복사 여부 |
| copy_description | query | boolean | 아니오 | true/false (기본 true) | 상세 설명 복사 여부 |
| copy_notice | query | boolean | 아니오 | true/false (기본 true) | 상품 공지 복사 여부 |
| copy_common_info | query | boolean | 아니오 | true/false (기본 true) | 상품 공통정보 복사 여부 |
| copy_other_info | query | boolean | 아니오 | true/false (기본 true) | 기타 정보 복사 여부 |
| copy_shipping | query | boolean | 아니오 | true/false (기본 true) | 배송 정책 복사 여부 |
| copy_seo | query | boolean | 아니오 | true/false (기본 **false**) | SEO 메타 복사 여부 — 메타 제목·설명은 상품마다 달라야 검색 결과에서 구분되므로 기본 제외 |
| copy_identification | query | boolean | 아니오 | true/false (기본 true) | 식별 정보(SKU·상품코드 등) 복사 여부 |
**요청 예시**
@@ -2280,6 +2291,8 @@ HTTP/1.1 200
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
| --- | --- | --- | --- | --- | --- |
| product | path | string | 예 | — | 대상 product의 식별자 |
| per_page | query | integer | 아니오 | 1~100 (기본 10) | 페이지당 로그 수 |
| sort_order | query | string | 아니오 | `asc` / `desc` (기본 `desc`) | 작성 시각 정렬 방향 |
**요청 예시**
@@ -245,13 +245,17 @@ describe('주문설정 탭 구조 검증 (_tab_order_settings.json)', () => {
expect(daysSection.if).toContain('auto_cancel_expired');
});
it('자동취소일 Input 이 min=1, max=30 으로 정의되어야 한다 (위치 의존 제거)', () => {
// 경계값은 서버가 내려주는 한계값(_meta.limits)을 바인딩한다 — 화면이 리터럴을 들면
// 저장 규칙이 바뀔 때 따라오지 못해 "화면은 받는데 저장에서 422" 가 된다.
it('자동취소일 Input 이 서버 한계값을 바인딩해야 한다 (위치 의존 제거)', () => {
const input = findFirst(card, (n: any) =>
n?.name === 'Input' && n?.props?.name === 'order_settings.auto_cancel_days',
);
expect(input).not.toBeNull();
expect(input.props.min).toBe(1);
expect(input.props.max).toBe(30);
expect(String(input.props.min)).toContain('_meta?.limits?.auto_cancel_days_min');
expect(String(input.props.max)).toContain('_meta?.limits?.auto_cancel_days_max');
expect(String(input.props.min)).toContain('?? 1');
expect(String(input.props.max)).toContain('?? 30');
});
it('입금기한 단일화: 구 vbank_due_days Input 이 더 이상 존재하지 않는다', () => {
@@ -272,13 +276,15 @@ describe('주문설정 탭 구조 검증 (_tab_order_settings.json)', () => {
describe('장바구니 유효기간 카드 구조', () => {
const card = findById(tab, 'cart_expiry_card');
it('cart_expiry_days Input이 min=1, max=365이어야 한다', () => {
it('cart_expiry_days Input 이 서버 한계값을 바인딩해야 한다', () => {
const input = findFirst(card, (n: any) =>
n?.name === 'Input' && n?.props?.name === 'order_settings.cart_expiry_days',
);
expect(input).not.toBeNull();
expect(input.props.min).toBe(1);
expect(input.props.max).toBe(365);
expect(String(input.props.min)).toContain('_meta?.limits?.cart_expiry_days_min');
expect(String(input.props.max)).toContain('_meta?.limits?.cart_expiry_days_max');
expect(String(input.props.min)).toContain('?? 1');
expect(String(input.props.max)).toContain('?? 365');
});
});
@@ -164,12 +164,14 @@ describe('리뷰설정 탭 구조 검증 (_tab_review_settings.json)', () => {
);
});
it('Input이 type=number, min=1, max=365여야 한다', () => {
it('Input이 type=number 이고 허용 범위가 서버 한계값을 바인딩해야 한다', () => {
const input = writeDeadlineSection.children.find((c: any) => c.name === 'Input');
expect(input).toBeDefined();
expect(input.props.type).toBe('number');
expect(String(input.props.min)).toBe('1');
expect(String(input.props.max)).toBe('365');
expect(String(input.props.min)).toContain('limits?.write_deadline_days_min');
expect(String(input.props.max)).toContain('limits?.write_deadline_days_max');
expect(String(input.props.min)).toContain('?? 1');
expect(String(input.props.max)).toContain('?? 365');
});
it('Input 기본값이 30을 참조해야 한다', () => {
@@ -224,12 +226,16 @@ describe('리뷰설정 탭 구조 검증 (_tab_review_settings.json)', () => {
// 구분선(Div, index 1) 다음 max_images 항목(index 2)
const maxImagesSection = settingsArea.children[2];
it('Input이 type=number, min=0, max=10여야 한다', () => {
// 경계값은 서버 검증(StoreEcommerceSettingsRequest)이 SSoT — 화면이 더 좁으면
// 사용자가 저장 가능한 값을 입력조차 못 하고, 더 넓으면 저장 단계에서만 실패한다.
it('Input이 type=number 이고 허용 범위가 서버 한계값을 바인딩해야 한다 (max_images)', () => {
const input = maxImagesSection.children.find((c: any) => c.name === 'Input');
expect(input).toBeDefined();
expect(input.props.type).toBe('number');
expect(String(input.props.min)).toBe('0');
expect(String(input.props.max)).toBe('10');
expect(String(input.props.min)).toContain('limits?.max_images_min');
expect(String(input.props.max)).toContain('limits?.max_images_max');
expect(String(input.props.min)).toContain('?? 0');
expect(String(input.props.max)).toContain('?? 20');
});
it('Input 기본값이 5를 참조해야 한다', () => {
@@ -264,13 +270,17 @@ describe('리뷰설정 탭 구조 검증 (_tab_review_settings.json)', () => {
// 구분선(index 3) 다음 max_image_size_mb 항목(index 4)
const maxSizeSection = settingsArea.children[4];
it('Input이 type=number, min=1, max=20, step=0.5여야 한다', () => {
// 서버 규칙이 integer 이므로 step 은 1 이어야 한다 — 0.5 는 화면에서만 허용되고
// 저장 단계에서 422 가 되는 값이다.
it('Input이 type=number, step=1 이고 허용 범위가 서버 한계값을 바인딩해야 한다', () => {
const input = maxSizeSection.children.find((c: any) => c.name === 'Input');
expect(input).toBeDefined();
expect(input.props.type).toBe('number');
expect(String(input.props.min)).toBe('1');
expect(String(input.props.max)).toBe('20');
expect(String(input.props.step)).toBe('0.5');
expect(String(input.props.min)).toContain('limits?.max_image_size_mb_min');
expect(String(input.props.max)).toContain('limits?.max_image_size_mb_max');
expect(String(input.props.min)).toContain('?? 1');
expect(String(input.props.max)).toContain('?? 50');
expect(String(input.props.step)).toBe('1');
});
it('Input 기본값이 5를 참조해야 한다', () => {
@@ -161,31 +161,39 @@ describe('리뷰 설정 탭 (_tab_review_settings.json) 렌더링', () => {
expect(cardBody.children.length).toBeGreaterThanOrEqual(3);
});
it('write_deadline_days Input이 min=1, max=365다', () => {
it('write_deadline_days Input 범위가 서버 한계값을 바인딩한다', () => {
const cardBody = (tabReviewSettings as any).children[0].children[2];
const deadlineSection = cardBody.children[0];
const input = deadlineSection.children.find((c: any) => c.name === 'Input');
expect(input).toBeDefined();
expect(String(input.props.min)).toBe('1');
expect(String(input.props.max)).toBe('365');
expect(String(input.props.min)).toContain('limits?.write_deadline_days_min');
expect(String(input.props.max)).toContain('limits?.write_deadline_days_max');
expect(String(input.props.min)).toContain('?? 1');
expect(String(input.props.max)).toContain('?? 365');
});
it('max_images Input이 min=0, max=10이다', () => {
// 경계값은 서버 검증(StoreEcommerceSettingsRequest)이 SSoT — 화면이 더 좁으면 저장 가능한
// 값을 입력조차 못 하고, 더 넓으면 저장 단계에서만 실패한다.
it('max_images Input 범위가 서버 한계값을 바인딩한다', () => {
const cardBody = (tabReviewSettings as any).children[0].children[2];
const maxImagesSection = cardBody.children[2]; // 구분선(index 1) 건너뜀
const input = maxImagesSection.children.find((c: any) => c.name === 'Input');
expect(input).toBeDefined();
expect(String(input.props.min)).toBe('0');
expect(String(input.props.max)).toBe('10');
expect(String(input.props.min)).toContain('limits?.max_images_min');
expect(String(input.props.max)).toContain('limits?.max_images_max');
expect(String(input.props.min)).toContain('?? 0');
expect(String(input.props.max)).toContain('?? 20');
});
it('max_image_size_mb Input이 min=1, max=20이다', () => {
it('max_image_size_mb Input 범위가 서버 한계값을 바인딩한다', () => {
const cardBody = (tabReviewSettings as any).children[0].children[2];
const maxSizeSection = cardBody.children[4]; // 구분선(index 3) 건너뜀
const input = maxSizeSection.children.find((c: any) => c.name === 'Input');
expect(input).toBeDefined();
expect(String(input.props.min)).toBe('1');
expect(String(input.props.max)).toBe('20');
expect(String(input.props.min)).toContain('limits?.max_image_size_mb_min');
expect(String(input.props.max)).toContain('limits?.max_image_size_mb_max');
expect(String(input.props.min)).toContain('?? 1');
expect(String(input.props.max)).toContain('?? 50');
});
it('모든 Input의 onChange가 setState + hasChanges: true를 사용한다', () => {
@@ -0,0 +1,237 @@
/**
* 설정 화면 ↔ 서버 검증 규칙 경계값 계약 테스트 (E10)
*
* @description
* 설정 입력 UI 의 min/max/step 은 서버 검증 규칙(StoreEcommerceSettingsRequest)과 같은 값을
* 말해야 한다. 화면이 더 좁으면 저장 가능한 값을 입력조차 못 하고, 더 넓으면 입력은 되는데
* 저장 단계에서만 422 가 난다. 어느 쪽도 화면만 보고는 알 수 없어 조용히 어긋난 채로 남는다.
*
* 양쪽 모두 `config('sirsoft-ecommerce.limits')` 한 곳을 읽도록 배선했으므로, 세 지점
* (설정 파일 · 서버 규칙 · 화면 바인딩)이 같은 한계값 키와 같은 폴백을 가리키는지 대조한다.
* 어느 한 쪽만 고쳐도 실패한다.
*
* @vitest-environment node
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
import tabMileageBasic from '../../../layouts/admin/partials/admin_ecommerce_settings/_tab_mileage_basic_card.json';
import tabOrderSettings from '../../../layouts/admin/partials/admin_ecommerce_settings/_tab_order_settings.json';
import tabReviewSettings from '../../../layouts/admin/partials/admin_ecommerce_settings/_tab_review_settings.json';
const moduleRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
const requestSource = fs.readFileSync(
path.join(moduleRoot, 'src/Http/Requests/Admin/StoreEcommerceSettingsRequest.php'),
'utf-8',
);
const configSource = fs.readFileSync(path.join(moduleRoot, 'config/ecommerce.php'), 'utf-8');
/** 한 경계(min 또는 max)의 출처: 어떤 한계값 키를 읽고, 그 키가 없을 때 무엇으로 떨어지는가. */
interface Bound {
limitKey: string | null;
fallback: number;
}
/**
* `config/ecommerce.php` 의 `limits` 블록을 키 → 값으로 읽는다.
*
* @returns 한계값 키 맵
*/
function configuredLimits(): Record<string, number> {
const block = /'limits'\s*=>\s*\[([\s\S]*?)\n\s*\],/.exec(configSource);
expect(block, "config/ecommerce.php 에서 'limits' 블록을 찾지 못했습니다.").not.toBeNull();
const limits: Record<string, number> = {};
for (const line of block![1].split('\n')) {
const matched = /'([a-z0-9_]+)'\s*=>\s*(-?[\d.]+)\s*,/.exec(line);
if (matched) {
limits[matched[1]] = Number(matched[2]);
}
}
expect(Object.keys(limits).length).toBeGreaterThan(0);
return limits;
}
const LIMITS = configuredLimits();
/**
* 규칙/바인딩 문자열에서 한 경계의 출처를 뽑는다.
*
* 서버 규칙: `'min:'.config('sirsoft-ecommerce.limits.KEY', N)` 또는 `'min:N'`
* 화면 바인딩: `{{_local?.form?._meta?.limits?.KEY ?? N}}` 또는 `"N"`
*
* @param source 규칙 배열 본문 또는 prop 값
* @param bound 'min' | 'max'
* @param isRule 서버 규칙 문자열이면 true
* @returns 경계 출처 (해당 경계가 없으면 null)
*/
function extractBound(source: string, bound: 'min' | 'max', isRule: boolean): Bound | null {
if (isRule) {
const viaConfig = new RegExp(
`'${bound}:'\\s*\\.\\s*config\\(\\s*'sirsoft-ecommerce\\.limits\\.([a-z0-9_]+)'\\s*,\\s*(-?[\\d.]+)\\s*\\)`,
).exec(source);
if (viaConfig) {
return { limitKey: viaConfig[1], fallback: Number(viaConfig[2]) };
}
const literal = new RegExp(`'${bound}:(-?[\\d.]+)'`).exec(source);
return literal ? { limitKey: null, fallback: Number(literal[1]) } : null;
}
if (source === undefined || source === null || source === '') {
return null;
}
const viaBinding = /limits\?\.([a-z0-9_]+)\s*\?\?\s*(-?[\d.]+)/.exec(source);
if (viaBinding) {
return { limitKey: viaBinding[1], fallback: Number(viaBinding[2]) };
}
return Number.isNaN(Number(source)) ? null : { limitKey: null, fallback: Number(source) };
}
/**
* FormRequest 원본에서 해당 설정 키의 규칙 배열 본문을 읽는다.
*
* @param key 설정 키
* @returns 규칙 배열 본문 문자열
*/
function ruleBody(key: string): string {
const escaped = key.replace(/[.]/g, '\\.');
const matched = new RegExp(`'${escaped}'\\s*=>\\s*\\[(.*)\\],\\n`).exec(requestSource);
expect(matched, `${key} 규칙을 FormRequest 에서 찾지 못했습니다.`).not.toBeNull();
return matched![1];
}
/**
* 레이아웃 트리에서 해당 설정 키를 다루는 Input 노드를 찾는다.
*
* 자동 바인딩을 쓰는 화면은 `props.name`, 수동 바인딩 화면은 `props.value` 의 표현식 경로로
* 필드를 식별한다 — 두 형태가 같은 탭 안에 섞여 있으므로 둘 다 본다.
*
* @param node 탐색 시작 노드
* @param key 설정 키
* @returns 매칭된 Input 노드 (없으면 null)
*/
function findInput(node: any, key: string): any {
if (!node || typeof node !== 'object') return null;
const boundPath = key.split('.').join('?.');
const value = node.props?.value;
if (
node.name === 'Input' &&
(node.props?.name === key || (typeof value === 'string' && value.includes(boundPath)))
) {
return node;
}
for (const child of Object.values(node)) {
if (Array.isArray(child)) {
for (const item of child) {
const found = findInput(item, key);
if (found) return found;
}
} else if (child && typeof child === 'object') {
const found = findInput(child, key);
if (found) return found;
}
}
return null;
}
const FIELDS: Array<{ key: string; layout: any }> = [
{ key: 'review_settings.write_deadline_days', layout: tabReviewSettings },
{ key: 'review_settings.max_images', layout: tabReviewSettings },
{ key: 'review_settings.max_image_size_mb', layout: tabReviewSettings },
{ key: 'order_settings.auto_cancel_days', layout: tabOrderSettings },
{ key: 'order_settings.cart_expiry_days', layout: tabOrderSettings },
{ key: 'mileage.default_earn_rate', layout: tabMileageBasic },
];
describe('설정 화면 경계값 ↔ 서버 규칙 계약', () => {
it.each(FIELDS)('$key 의 min/max 가 서버 규칙과 같은 한계값을 가리킨다', ({ key, layout }) => {
const input = findInput(layout, key);
expect(input, `${key} Input 을 레이아웃에서 찾지 못했습니다.`).not.toBeNull();
const body = ruleBody(key);
let compared = 0;
for (const bound of ['min', 'max'] as const) {
const server = extractBound(body, bound, true);
if (server === null) {
continue;
}
const screen = extractBound(String(input.props[bound] ?? ''), bound, false);
expect(screen, `${key} 화면에 ${bound} 이 없습니다 — 서버는 ${bound} 을 강제합니다.`).not.toBeNull();
expect(screen!.limitKey, `${key} 의 ${bound} 이 서버 규칙과 다른 한계값을 읽습니다.`).toBe(
server.limitKey,
);
expect(screen!.fallback, `${key} 의 ${bound} 폴백이 서버 규칙과 다릅니다.`).toBe(server.fallback);
compared++;
}
// 규칙 형태가 바뀌어 아무 경계도 못 읽으면 이 테스트는 아무것도 검증하지 못한 채 통과한다.
expect(compared, `${key} 에서 서버 경계를 하나도 읽지 못했습니다 — 규칙 추출이 깨졌습니다.`).toBeGreaterThan(0);
});
it.each(FIELDS)('$key 의 폴백이 설정 파일의 한계값과 같다', ({ key }) => {
const body = ruleBody(key);
let checked = 0;
for (const bound of ['min', 'max'] as const) {
const server = extractBound(body, bound, true);
if (server === null || server.limitKey === null) {
continue;
}
expect(LIMITS, `${server.limitKey} 가 config/ecommerce.php 의 limits 에 없습니다.`).toHaveProperty(
server.limitKey,
);
expect(LIMITS[server.limitKey], `${key} 의 ${bound} 폴백이 설정 파일 값과 다릅니다.`).toBe(
server.fallback,
);
checked++;
}
expect(checked).toBeGreaterThan(0);
});
it.each(FIELDS)('$key 의 step 이 서버 규칙의 정수 여부와 어긋나지 않는다', ({ key, layout }) => {
const input = findInput(layout, key);
const body = ruleBody(key);
if (!/'integer'/.test(body)) {
return;
}
// step 자체가 사라지면 브라우저 기본값 1 로 동작해 당장은 문제가 없지만,
// 다음 사람이 소수 step 을 다시 넣어도 막을 근거가 없어진다.
// 부재를 통과시키면 이 가드가 그 순간 무력화되므로 명시 실패시킨다.
expect(
input.props.step,
`${key} 는 서버가 integer 를 요구하므로 step 을 명시해야 합니다 — 부재는 소수 step 회귀를 막지 못합니다.`,
).toBeDefined();
// 서버가 integer 를 요구하는데 소수 step 을 주면, 화면이 권하는 값이 곧 422 가 된다.
expect(Number(input.props.step)).toBe(1);
});
});
@@ -8,7 +8,7 @@
"name": "Div",
"children": [
{
"id": "currency_card",
"id": "currency_card_{{currencyIndex}}",
"type": "basic",
"name": "Div",
"iteration": {
@@ -1026,8 +1026,8 @@
"type": "number",
"name": "newCurrency.decimal_places",
"value": "{{_local.form?.newCurrency?.decimal_places ?? 2}}",
"min": 0,
"max": 8,
"min": "{{_local?.form?._meta?.limits?.decimal_places_min ?? 0}}",
"max": "{{_local?.form?._meta?.limits?.decimal_places_max ?? 8}}",
"className": "w-full",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -1039,6 +1039,5 @@
]
}
],
"props": {
}
"props": {}
}
@@ -83,7 +83,7 @@
"name": "Tbody",
"children": [
{
"id": "currency_row",
"id": "currency_row_{{currencyIndex}}",
"type": "basic",
"name": "Tr",
"iteration": {
@@ -765,8 +765,8 @@
"type": "number",
"name": "newCurrency.decimal_places",
"value": "{{_local.form?.newCurrency?.decimal_places ?? 2}}",
"min": 0,
"max": 8,
"min": "{{_local?.form?._meta?.limits?.decimal_places_min ?? 0}}",
"max": "{{_local?.form?._meta?.limits?.decimal_places_max ?? 8}}",
"className": "input w-20 text-center",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -137,7 +137,8 @@
"type": "number",
"name": "mileage.default_earn_rate",
"value": "{{_local.form?.mileage?.default_earn_rate ?? 1}}",
"min": "0",
"min": "{{_local?.form?._meta?.limits?.default_earn_rate_min ?? 0}}",
"max": "{{_local?.form?._meta?.limits?.default_earn_rate_max ?? 100}}",
"step": "0.1",
"className": "input w-24 text-center",
"disabled": "{{_computed.isReadOnly}}"
@@ -229,7 +230,7 @@
"type": "number",
"name": "mileage.earn_delay_days",
"value": "{{_local.form?.mileage?.earn_delay_days ?? 0}}",
"min": "0",
"min": "{{_local?.form?._meta?.limits?.earn_delay_days_min ?? 0}}",
"className": "input w-20 text-center",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -11,7 +11,7 @@
},
"children": [
{
"id": "currency_rule_card",
"id": "currency_rule_card_{{ruleIndex}}",
"type": "basic",
"name": "Div",
"iteration": {
@@ -333,7 +333,9 @@
{
"type": "basic",
"name": "Label",
"props": { "className": "block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1" },
"props": {
"className": "block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1"
},
"text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.code"
},
{
@@ -350,7 +352,10 @@
{
"type": "change",
"handler": "setState",
"params": { "target": "local", "form.newMileageCurrency.hasError": false }
"params": {
"target": "local",
"form.newMileageCurrency.hasError": false
}
}
]
}
@@ -363,7 +368,9 @@
{
"type": "basic",
"name": "Label",
"props": { "className": "block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1" },
"props": {
"className": "block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1"
},
"text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.point_value"
},
{
@@ -373,7 +380,7 @@
"type": "number",
"name": "newMileageCurrency.point_value",
"value": "{{_local.form?.newMileageCurrency?.point_value ?? 1}}",
"min": "0",
"min": "{{_local?.form?._meta?.limits?.point_value_min ?? 0}}",
"step": "0.001",
"className": "input w-full",
"disabled": "{{_computed.isReadOnly}}"
@@ -388,7 +395,9 @@
{
"type": "basic",
"name": "Label",
"props": { "className": "block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1" },
"props": {
"className": "block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1"
},
"text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.min_use"
},
{
@@ -398,7 +407,7 @@
"type": "number",
"name": "newMileageCurrency.min_use_amount",
"value": "{{_local.form?.newMileageCurrency?.min_use_amount ?? 0}}",
"min": "0",
"min": "{{_local?.form?._meta?.limits?.min_use_amount_min ?? 0}}",
"className": "input w-full",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -412,7 +421,9 @@
{
"type": "basic",
"name": "Label",
"props": { "className": "block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1" },
"props": {
"className": "block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1"
},
"text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.use_unit"
},
{
@@ -422,7 +433,7 @@
"type": "number",
"name": "newMileageCurrency.use_unit",
"value": "{{_local.form?.newMileageCurrency?.use_unit ?? 1}}",
"min": "1",
"min": "{{_local?.form?._meta?.limits?.use_unit_min ?? 1}}",
"className": "input w-full",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -436,18 +447,24 @@
{
"type": "basic",
"name": "Label",
"props": { "className": "block text-xs font-medium text-gray-500 dark:text-gray-400 mb-2" },
"props": {
"className": "block text-xs font-medium text-gray-500 dark:text-gray-400 mb-2"
},
"text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.max_use"
},
{
"type": "basic",
"name": "Div",
"props": { "className": "space-y-2" },
"props": {
"className": "space-y-2"
},
"children": [
{
"type": "basic",
"name": "Label",
"props": { "className": "flex items-center gap-2 cursor-pointer" },
"props": {
"className": "flex items-center gap-2 cursor-pointer"
},
"actions": [
{
"type": "click",
@@ -475,7 +492,9 @@
{
"type": "basic",
"name": "Span",
"props": { "className": "text-xs text-gray-600 dark:text-gray-400" },
"props": {
"className": "text-xs text-gray-600 dark:text-gray-400"
},
"text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.max_use_percent"
},
{
@@ -485,8 +504,8 @@
"type": "number",
"name": "newMileageCurrency.max_use_percent",
"value": "{{_local.form?.newMileageCurrency?.max_use_percent ?? 30}}",
"min": "0",
"max": "100",
"min": "{{_local?.form?._meta?.limits?.max_use_percent_min ?? 0}}",
"max": "{{_local?.form?._meta?.limits?.max_use_percent_max ?? 100}}",
"className": "input w-16 text-center",
"disabled": "{{_computed.isReadOnly || (_local.form?.newMileageCurrency?.max_use_type ?? 'percent') !== 'percent'}}"
}
@@ -494,7 +513,9 @@
{
"type": "basic",
"name": "Span",
"props": { "className": "text-xs text-gray-500 dark:text-gray-400" },
"props": {
"className": "text-xs text-gray-500 dark:text-gray-400"
},
"text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.max_use_percent_suffix"
}
]
@@ -502,7 +523,9 @@
{
"type": "basic",
"name": "Label",
"props": { "className": "flex items-center gap-2 cursor-pointer" },
"props": {
"className": "flex items-center gap-2 cursor-pointer"
},
"actions": [
{
"type": "click",
@@ -530,7 +553,9 @@
{
"type": "basic",
"name": "Span",
"props": { "className": "text-xs text-gray-600 dark:text-gray-400" },
"props": {
"className": "text-xs text-gray-600 dark:text-gray-400"
},
"text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.max_use_fixed"
},
{
@@ -540,7 +565,7 @@
"type": "number",
"name": "newMileageCurrency.max_use_value",
"value": "{{_local.form?.newMileageCurrency?.max_use_value ?? 0}}",
"min": "0",
"min": "{{_local?.form?._meta?.limits?.max_use_value_min ?? 0}}",
"className": "input w-28 text-center",
"disabled": "{{_computed.isReadOnly || (_local.form?.newMileageCurrency?.max_use_type ?? 'percent') !== 'fixed'}}"
}
@@ -554,7 +579,9 @@
{
"type": "basic",
"name": "Div",
"props": { "className": "flex items-center justify-end gap-2 pt-1" },
"props": {
"className": "flex items-center justify-end gap-2 pt-1"
},
"children": [
{
"type": "basic",
@@ -568,11 +595,19 @@
{
"type": "click",
"handler": "setState",
"params": { "target": "local", "isAddingMileageCurrency": false, "form.newMileageCurrency": null }
"params": {
"target": "local",
"isAddingMileageCurrency": false,
"form.newMileageCurrency": null
}
}
],
"children": [
{ "type": "basic", "name": "Span", "text": "$t:common.cancel" }
{
"type": "basic",
"name": "Span",
"text": "$t:common.cancel"
}
]
},
{
@@ -599,7 +634,10 @@
{
"handler": "setState",
"if": "{{_local.form?.newMileageCurrency?.currency_code?.trim() && (_local.form?.mileage?.currency_rules ?? []).some(c => (c.currency_code || '').toUpperCase() === (_local.form?.newMileageCurrency?.currency_code || '').toUpperCase().trim())}}",
"params": { "target": "local", "form.newMileageCurrency.hasError": true }
"params": {
"target": "local",
"form.newMileageCurrency.hasError": true
}
},
{
"handler": "setState",
@@ -616,8 +654,19 @@
}
],
"children": [
{ "type": "basic", "name": "Icon", "props": { "name": "check", "size": "sm" } },
{ "type": "basic", "name": "Span", "text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.add" }
{
"type": "basic",
"name": "Icon",
"props": {
"name": "check",
"size": "sm"
}
},
{
"type": "basic",
"name": "Span",
"text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.add"
}
]
}
]
@@ -67,7 +67,7 @@
"name": "Tbody",
"children": [
{
"id": "currency_rule_row",
"id": "currency_rule_row_{{ruleIndex}}",
"type": "basic",
"name": "Tr",
"iteration": {
@@ -409,7 +409,9 @@
{
"type": "basic",
"name": "Td",
"props": { "className": "align-top" },
"props": {
"className": "align-top"
},
"children": [
{
"type": "basic",
@@ -425,7 +427,10 @@
{
"type": "change",
"handler": "setState",
"params": { "target": "local", "form.newMileageCurrency.hasError": false }
"params": {
"target": "local",
"form.newMileageCurrency.hasError": false
}
}
]
}
@@ -434,7 +439,9 @@
{
"type": "basic",
"name": "Td",
"props": { "className": "align-top" },
"props": {
"className": "align-top"
},
"children": [
{
"type": "basic",
@@ -443,7 +450,7 @@
"type": "number",
"name": "newMileageCurrency.point_value",
"value": "{{_local.form?.newMileageCurrency?.point_value ?? 1}}",
"min": "0",
"min": "{{_local?.form?._meta?.limits?.point_value_min ?? 0}}",
"step": "0.001",
"className": "input w-24 text-center",
"disabled": "{{_computed.isReadOnly}}"
@@ -454,12 +461,16 @@
{
"type": "basic",
"name": "Td",
"props": { "className": "align-top" },
"props": {
"className": "align-top"
},
"children": [
{
"type": "basic",
"name": "Div",
"props": { "className": "flex items-center gap-1" },
"props": {
"className": "flex items-center gap-1"
},
"children": [
{
"type": "basic",
@@ -468,7 +479,7 @@
"type": "number",
"name": "newMileageCurrency.min_use_amount",
"value": "{{_local.form?.newMileageCurrency?.min_use_amount ?? 0}}",
"min": "0",
"min": "{{_local?.form?._meta?.limits?.min_use_amount_min ?? 0}}",
"className": "input w-24 text-center",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -476,7 +487,9 @@
{
"type": "basic",
"name": "Span",
"props": { "className": "text-xs text-gray-500 dark:text-gray-400" },
"props": {
"className": "text-xs text-gray-500 dark:text-gray-400"
},
"text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.min_use_suffix"
}
]
@@ -486,12 +499,16 @@
{
"type": "basic",
"name": "Td",
"props": { "className": "align-top" },
"props": {
"className": "align-top"
},
"children": [
{
"type": "basic",
"name": "Div",
"props": { "className": "flex items-center gap-1" },
"props": {
"className": "flex items-center gap-1"
},
"children": [
{
"type": "basic",
@@ -500,7 +517,7 @@
"type": "number",
"name": "newMileageCurrency.use_unit",
"value": "{{_local.form?.newMileageCurrency?.use_unit ?? 1}}",
"min": "1",
"min": "{{_local?.form?._meta?.limits?.use_unit_min ?? 1}}",
"className": "input w-20 text-center",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -508,7 +525,9 @@
{
"type": "basic",
"name": "Span",
"props": { "className": "text-xs text-gray-500 dark:text-gray-400" },
"props": {
"className": "text-xs text-gray-500 dark:text-gray-400"
},
"text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.use_unit_suffix"
}
]
@@ -518,17 +537,23 @@
{
"type": "basic",
"name": "Td",
"props": { "className": "align-top" },
"props": {
"className": "align-top"
},
"children": [
{
"type": "basic",
"name": "Div",
"props": { "className": "space-y-2" },
"props": {
"className": "space-y-2"
},
"children": [
{
"type": "basic",
"name": "Label",
"props": { "className": "flex items-center gap-2 cursor-pointer" },
"props": {
"className": "flex items-center gap-2 cursor-pointer"
},
"actions": [
{
"type": "click",
@@ -556,7 +581,9 @@
{
"type": "basic",
"name": "Span",
"props": { "className": "text-xs text-gray-600 dark:text-gray-400" },
"props": {
"className": "text-xs text-gray-600 dark:text-gray-400"
},
"text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.max_use_percent"
},
{
@@ -566,8 +593,8 @@
"type": "number",
"name": "newMileageCurrency.max_use_percent",
"value": "{{_local.form?.newMileageCurrency?.max_use_percent ?? 30}}",
"min": "0",
"max": "100",
"min": "{{_local?.form?._meta?.limits?.max_use_percent_min ?? 0}}",
"max": "{{_local?.form?._meta?.limits?.max_use_percent_max ?? 100}}",
"className": "input w-16 text-center",
"disabled": "{{_computed.isReadOnly || (_local.form?.newMileageCurrency?.max_use_type ?? 'percent') !== 'percent'}}"
}
@@ -575,7 +602,9 @@
{
"type": "basic",
"name": "Span",
"props": { "className": "text-xs text-gray-500 dark:text-gray-400" },
"props": {
"className": "text-xs text-gray-500 dark:text-gray-400"
},
"text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.max_use_percent_suffix"
}
]
@@ -583,7 +612,9 @@
{
"type": "basic",
"name": "Label",
"props": { "className": "flex items-center gap-2 cursor-pointer" },
"props": {
"className": "flex items-center gap-2 cursor-pointer"
},
"actions": [
{
"type": "click",
@@ -611,7 +642,9 @@
{
"type": "basic",
"name": "Span",
"props": { "className": "text-xs text-gray-600 dark:text-gray-400" },
"props": {
"className": "text-xs text-gray-600 dark:text-gray-400"
},
"text": "$t:sirsoft-ecommerce.admin.mileage_settings.currency.max_use_fixed"
},
{
@@ -621,7 +654,7 @@
"type": "number",
"name": "newMileageCurrency.max_use_value",
"value": "{{_local.form?.newMileageCurrency?.max_use_value ?? 0}}",
"min": "0",
"min": "{{_local?.form?._meta?.limits?.max_use_value_min ?? 0}}",
"className": "input w-24 text-center",
"disabled": "{{_computed.isReadOnly || (_local.form?.newMileageCurrency?.max_use_type ?? 'percent') !== 'fixed'}}"
}
@@ -635,12 +668,16 @@
{
"type": "basic",
"name": "Td",
"props": { "className": "align-top text-center" },
"props": {
"className": "align-top text-center"
},
"children": [
{
"type": "basic",
"name": "Div",
"props": { "className": "flex items-center justify-center gap-1" },
"props": {
"className": "flex items-center justify-center gap-1"
},
"children": [
{
"type": "basic",
@@ -666,7 +703,10 @@
{
"handler": "setState",
"if": "{{_local.form?.newMileageCurrency?.currency_code?.trim() && (_local.form?.mileage?.currency_rules ?? []).some(c => (c.currency_code || '').toUpperCase() === (_local.form?.newMileageCurrency?.currency_code || '').toUpperCase().trim())}}",
"params": { "target": "local", "form.newMileageCurrency.hasError": true }
"params": {
"target": "local",
"form.newMileageCurrency.hasError": true
}
},
{
"handler": "setState",
@@ -683,7 +723,14 @@
}
],
"children": [
{ "type": "basic", "name": "Icon", "props": { "name": "check", "size": "sm" } }
{
"type": "basic",
"name": "Icon",
"props": {
"name": "check",
"size": "sm"
}
}
]
},
{
@@ -698,11 +745,22 @@
{
"type": "click",
"handler": "setState",
"params": { "target": "local", "isAddingMileageCurrency": false, "form.newMileageCurrency": null }
"params": {
"target": "local",
"isAddingMileageCurrency": false,
"form.newMileageCurrency": null
}
}
],
"children": [
{ "type": "basic", "name": "Icon", "props": { "name": "xmark", "size": "sm" } }
{
"type": "basic",
"name": "Icon",
"props": {
"name": "xmark",
"size": "sm"
}
}
]
}
]
@@ -88,7 +88,7 @@
"type": "number",
"name": "mileage.expiry_days",
"value": "{{_local.form?.mileage?.expiry_days ?? 365}}",
"min": "1",
"min": "{{_local?.form?._meta?.limits?.expiry_days_min ?? 1}}",
"className": "input w-28 text-center",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -100,7 +100,7 @@
"type": "number",
"name": "mileage.expiry_notification_days_before",
"value": "{{_local.form?.mileage?.expiry_notification_days_before ?? 7}}",
"min": "1",
"min": "{{_local?.form?._meta?.limits?.expiry_notification_days_before_min ?? 1}}",
"className": "input w-20 text-center",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -142,7 +142,7 @@
},
"children": [
{
"id": "template_status_row",
"id": "template_status_row_{{tplIndex}}",
"type": "basic",
"name": "Div",
"iteration": {
@@ -387,8 +387,9 @@
"type": "number",
"name": "order_settings.auto_cancel_days",
"value": "{{_local.form?.order_settings?.auto_cancel_days ?? 3}}",
"min": 1,
"max": 30,
"min": "{{_local?.form?._meta?.limits?.auto_cancel_days_min ?? 1}}",
"max": "{{_local?.form?._meta?.limits?.auto_cancel_days_max ?? 30}}",
"step": "1",
"className": "{{_local.errors?.['order_settings.auto_cancel_days'] ? 'input input-error w-20' : 'input w-20'}}",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -679,8 +680,9 @@
"type": "number",
"name": "order_settings.cart_expiry_days",
"value": "{{_local.form?.order_settings?.cart_expiry_days ?? 30}}",
"min": 1,
"max": 365,
"min": "{{_local?.form?._meta?.limits?.cart_expiry_days_min ?? 1}}",
"max": "{{_local?.form?._meta?.limits?.cart_expiry_days_max ?? 365}}",
"step": "1",
"className": "{{_local.errors?.['order_settings.cart_expiry_days'] ? 'input input-error w-20' : 'input w-20'}}",
"disabled": "{{_computed.isReadOnly}}"
}
@@ -57,8 +57,9 @@
"name": "Input",
"props": {
"type": "number",
"min": "1",
"max": "365",
"min": "{{_local?.form?._meta?.limits?.write_deadline_days_min ?? 1}}",
"max": "{{_local?.form?._meta?.limits?.write_deadline_days_max ?? 365}}",
"step": "1",
"className": "input w-20",
"disabled": "{{_computed.isReadOnly}}",
"value": "{{_local.form?.review_settings?.write_deadline_days ?? 30}}"
@@ -121,8 +122,9 @@
"name": "Input",
"props": {
"type": "number",
"min": "0",
"max": "10",
"min": "{{_local?.form?._meta?.limits?.max_images_min ?? 0}}",
"max": "{{_local?.form?._meta?.limits?.max_images_max ?? 20}}",
"step": "1",
"className": "input w-20",
"disabled": "{{_computed.isReadOnly}}",
"value": "{{_local.form?.review_settings?.max_images ?? 5}}"
@@ -185,9 +187,9 @@
"name": "Input",
"props": {
"type": "number",
"min": "1",
"max": "20",
"step": "0.5",
"min": "{{_local?.form?._meta?.limits?.max_image_size_mb_min ?? 1}}",
"max": "{{_local?.form?._meta?.limits?.max_image_size_mb_max ?? 50}}",
"step": "1",
"className": "input w-20",
"disabled": "{{_computed.isReadOnly}}",
"value": "{{_local.form?.review_settings?.max_image_size_mb ?? 5}}"
@@ -21,6 +21,7 @@ class Summary
* @param int $shippingDiscount 배송비 할인
* @param int $taxableAmount 과세 금액 합계
* @param int $taxFreeAmount 면세 금액 합계
* @param int $vatAmount 부가세 합계 (옵션별 세율 반영, 과세표준에 내재된 금액)
* @param int $pointsEarning 적립 예정 마일리지 합계
* @param int $pointsUsed 사용 마일리지 합계
* @param int $paymentAmount 결제금액 (마일리지 사용 전)
@@ -28,9 +29,9 @@ class Summary
* @param MultiCurrencyPrices|null $multiCurrency 다중 통화 변환 금액
* @param string|null $selectedPaymentCurrency 선택된 결제 통화
* @param array<string, mixed> $metadata 플러그인 확장용 메타데이터
* - deposit_used: 예치금 사용 합계 (예치금 플러그인)
* - gift_card_used: 상품권 사용 합계 (상품권 플러그인)
* - grade_discount: 회원등급 할인 합계 (회원등급 플러그인)
* - deposit_used: 예치금 사용 합계 (예치금 플러그인)
* - gift_card_used: 상품권 사용 합계 (상품권 플러그인)
* - grade_discount: 회원등급 할인 합계 (회원등급 플러그인)
*/
public function __construct(
public int $subtotal = 0,
@@ -44,6 +45,7 @@ class Summary
public int $shippingDiscount = 0,
public int $taxableAmount = 0,
public int $taxFreeAmount = 0,
public int $vatAmount = 0,
public int $pointsEarning = 0,
public int $pointsUsed = 0,
public int $paymentAmount = 0,
@@ -122,6 +124,7 @@ class Summary
'shipping_discount_formatted' => ecommerce_format_price($this->shippingDiscount),
'taxable_amount' => $this->taxableAmount,
'tax_free_amount' => $this->taxFreeAmount,
'vat_amount' => $this->vatAmount,
'points_earning' => $this->pointsEarning,
'total_mileage' => $this->pointsEarning,
'mileage_formatted' => number_format($this->pointsEarning).'P',
@@ -175,6 +178,7 @@ class Summary
shippingDiscount: $data['shipping_discount'] ?? 0,
taxableAmount: $data['taxable_amount'] ?? 0,
taxFreeAmount: $data['tax_free_amount'] ?? 0,
vatAmount: $data['vat_amount'] ?? 0,
pointsEarning: $data['points_earning'] ?? 0,
pointsUsed: $data['points_used'] ?? 0,
paymentAmount: $data['payment_amount'] ?? 0,
@@ -0,0 +1,48 @@
<?php
namespace Modules\Sirsoft\Ecommerce\Exceptions;
use Exception;
/**
* 장바구니 수량 상한 초과 예외
*
* `config('sirsoft-ecommerce.cart.max_quantity')` 를 초과하는 라인 수량을 만들려 할 때 발생합니다.
* 필드 규칙(`max:`)이 이번 요청분만 검사하는 것과 달리, 기존 수량과 합산되는 경로를 막습니다.
*/
class CartQuantityLimitException extends Exception
{
/**
* @param int $limit 허용 최대 수량
* @param int $attempted 합산 후 수량
*/
public function __construct(
private int $limit,
private int $attempted,
) {
parent::__construct(__('sirsoft-ecommerce::validation.cart.quantity_limit_exceeded', [
'limit' => $limit,
'attempted' => $attempted,
]));
}
/**
* 허용 최대 수량을 반환합니다.
*
* @return int 최대 수량
*/
public function getLimit(): int
{
return $this->limit;
}
/**
* 합산 후 수량을 반환합니다.
*
* @return int 시도 수량
*/
public function getAttempted(): int
{
return $this->attempted;
}
}
@@ -0,0 +1,27 @@
<?php
namespace Modules\Sirsoft\Ecommerce\Exceptions;
use RuntimeException;
/**
* 상품 가격 관계 위반 예외
*
* 판매가가 정가를 초과하는 조합으로 저장이 시도될 때 발생합니다.
*
* 일괄 수정은 정가/판매가 중 한쪽만 보내는 부분 전송이 흔해 FormRequest 는 두 값이 모두
* 전송된 경우에만 비교합니다. 한쪽만 온 경우 나머지는 DB 에 남아 있던 값이 그대로 적용되므로,
* 실제로 적용될 조합은 저장 직전에만 확정됩니다. 이 예외는 그 지점의 판정 결과입니다.
*/
class ProductPriceRelationException extends RuntimeException
{
/**
* @param int $productId 대상 상품 ID
*/
public function __construct(public readonly int $productId)
{
parent::__construct(
__('sirsoft-ecommerce::validation.product.selling_price_lte_list')
);
}
}
@@ -57,6 +57,10 @@ class EcommerceSettingsController extends AdminBaseController
'can_update' => PermissionHelper::check('sirsoft-ecommerce.settings.update', request()->user()),
];
// 화면의 숫자 입력 경계값 — 저장 규칙과 같은 출처를 내려준다.
// 화면이 리터럴을 들면 규칙이 바뀔 때 따라오지 못해 "화면은 받는데 저장은 422" 가 된다.
$settings['_meta'] = ['limits' => config('sirsoft-ecommerce.limits', [])];
return ResponseHelper::moduleSuccess(
'sirsoft-ecommerce',
'messages.settings.fetch_success',
@@ -5,20 +5,21 @@ namespace Modules\Sirsoft\Ecommerce\Http\Controllers\Admin;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Api\Base\AdminBaseController;
use App\Http\Resources\ActivityLogResource;
use App\Models\ActivityLog;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Modules\Sirsoft\Ecommerce\Exceptions\ProductHasOrderHistoryException;
use Modules\Sirsoft\Ecommerce\Exceptions\ProductImageUploadLimitException;
use Modules\Sirsoft\Ecommerce\Exceptions\ProductPriceRelationException;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkUpdatePriceRequest;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkUpdateProductsRequest;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkUpdateStatusRequest;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkUpdateStockRequest;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ProductListRequest;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ProductLogsRequest;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ReorderProductImagesRequest;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ShowProductForCopyRequest;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\StoreProductRequest;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UpdateProductRequest;
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UploadProductImageRequest;
@@ -26,7 +27,6 @@ use Modules\Sirsoft\Ecommerce\Http\Resources\ProductCollection;
use Modules\Sirsoft\Ecommerce\Http\Resources\ProductOptionResource;
use Modules\Sirsoft\Ecommerce\Http\Resources\ProductResource;
use Modules\Sirsoft\Ecommerce\Models\Product;
use Modules\Sirsoft\Ecommerce\Models\ProductOption;
use Modules\Sirsoft\Ecommerce\Services\ProductImageService;
use Modules\Sirsoft\Ecommerce\Services\ProductService;
@@ -407,6 +407,15 @@ class ProductController extends AdminBaseController
200,
['count' => ($result['products_updated'] ?? 0) + ($result['options_updated'] ?? 0)]
);
} catch (ProductPriceRelationException $e) {
// 판매가 > 정가 조합은 도메인 검증 실패 → generic 500 이 아닌 422
return ResponseHelper::error(
'validation.product.selling_price_lte_list',
422,
null,
[],
'sirsoft-ecommerce'
);
} catch (ValidationException $e) {
return ResponseHelper::moduleError(
'sirsoft-ecommerce',
@@ -557,28 +566,14 @@ class ProductController extends AdminBaseController
/**
* 상품 복사용 데이터를 조회합니다.
*
* @param Request $request HTTP 요청 (복사 옵션 포함)
* @param ShowProductForCopyRequest $request 복사 옵션 요청 데이터
* @param Product $product 복사할 상품 모델
* @return JsonResponse 복사용 데이터 JSON 응답
*/
public function showForCopy(Request $request, Product $product): JsonResponse
public function showForCopy(ShowProductForCopyRequest $request, Product $product): JsonResponse
{
try {
$copyOptions = [
'images' => $request->boolean('copy_images', true),
'options' => $request->boolean('copy_options', true),
'categories' => $request->boolean('copy_categories', true),
'sales_info' => $request->boolean('copy_sales_info', true),
'description' => $request->boolean('copy_description', true),
'notice' => $request->boolean('copy_notice', true),
'common_info' => $request->boolean('copy_common_info', true),
'other_info' => $request->boolean('copy_other_info', true),
'shipping' => $request->boolean('copy_shipping', true),
'seo' => $request->boolean('copy_seo', false),
'identification' => $request->boolean('copy_identification', true),
];
$copyData = $this->productService->getDetailForCopy($product->id, $copyOptions);
$copyData = $this->productService->getDetailForCopy($product->id, $request->getCopyOptions());
if (! $copyData) {
return ResponseHelper::notFound(
@@ -802,36 +797,15 @@ class ProductController extends AdminBaseController
/**
* 상품 처리로그(활동 로그) 목록을 조회합니다.
*
* @param Request $request 요청
* @param ProductLogsRequest $request 활동 로그 조회 요청 데이터
* @param Product $product 상품
* @return JsonResponse 활동 로그 목록
*/
public function logs(Request $request, Product $product): JsonResponse
public function logs(ProductLogsRequest $request, Product $product): JsonResponse
{
try {
$perPage = (int) ($request->query('per_page', 10));
$sortOrder = $request->query('sort_order', 'desc');
// 상품 + 상품옵션 로그를 합쳐서 조회
$optionIds = $product->options()->pluck('id')->toArray();
$query = ActivityLog::where(function ($q) use ($product, $optionIds) {
// 상품 자체 로그
$q->where(function ($sub) use ($product) {
$sub->where('loggable_type', $product->getMorphClass())
->where('loggable_id', $product->getKey());
});
// 해당 상품의 옵션 로그
if (! empty($optionIds)) {
$q->orWhere(function ($sub) use ($optionIds) {
$sub->where('loggable_type', (new ProductOption)->getMorphClass())
->whereIn('loggable_id', $optionIds);
});
}
})->orderBy('created_at', $sortOrder);
$logs = $query->paginate($perPage);
// 상품 + 상품옵션 로그 합산 조회는 Repository 위임 (Service 경유)
$logs = $this->productService->getActivityLogs($product, $request->getFilters());
return ResponseHelper::moduleSuccess(
'sirsoft-ecommerce',
@@ -10,6 +10,7 @@ use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Modules\Sirsoft\Ecommerce\Exceptions\CartOperationException;
use Modules\Sirsoft\Ecommerce\Exceptions\CartQuantityLimitException;
use Modules\Sirsoft\Ecommerce\Exceptions\CartUnavailableException;
use Modules\Sirsoft\Ecommerce\Http\Middleware\ResolveShippingCountry;
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\BulkAddToCartRequest;
@@ -153,6 +154,14 @@ class CartController extends PublicBaseController
} catch (CartUnavailableException $e) {
// 판매불가/재고/구매수량 한도 위반 — generic 500 이 아닌 사유별 422 매핑
return $this->cartUnavailableResponse($e);
} catch (CartQuantityLimitException $e) {
// 장바구니 수량 상한 초과 — generic 500 이 아닌 422 명시 차단
return ResponseHelper::error(
'sirsoft-ecommerce::validation.cart.quantity_limit_exceeded',
422,
['code' => 'cart_quantity_limit_exceeded', 'detail' => $e->getMessage()],
['limit' => $e->getLimit(), 'attempted' => $e->getAttempted()]
);
} catch (CartOperationException $e) {
// 항목없음/권한없음/옵션없음 — 사유별 404/403/422 매핑
return $this->cartOperationResponse($e);
@@ -214,6 +223,14 @@ class CartController extends PublicBaseController
} catch (CartUnavailableException $e) {
// 판매불가/재고/구매수량 한도 위반 — generic 500 이 아닌 사유별 422 매핑
return $this->cartUnavailableResponse($e);
} catch (CartQuantityLimitException $e) {
// 장바구니 수량 상한 초과 — generic 500 이 아닌 422 명시 차단
return ResponseHelper::error(
'sirsoft-ecommerce::validation.cart.quantity_limit_exceeded',
422,
['code' => 'cart_quantity_limit_exceeded', 'detail' => $e->getMessage()],
['limit' => $e->getLimit(), 'attempted' => $e->getAttempted()]
);
} catch (CartOperationException $e) {
// 항목없음/권한없음/옵션없음 — 사유별 404/403/422 매핑
return $this->cartOperationResponse($e);
@@ -259,6 +276,14 @@ class CartController extends PublicBaseController
} catch (CartUnavailableException $e) {
// 판매불가/재고/구매수량 한도 위반 — generic 500 이 아닌 사유별 422 매핑
return $this->cartUnavailableResponse($e);
} catch (CartQuantityLimitException $e) {
// 장바구니 수량 상한 초과 — generic 500 이 아닌 422 명시 차단
return ResponseHelper::error(
'sirsoft-ecommerce::validation.cart.quantity_limit_exceeded',
422,
['code' => 'cart_quantity_limit_exceeded', 'detail' => $e->getMessage()],
['limit' => $e->getLimit(), 'attempted' => $e->getAttempted()]
);
} catch (CartOperationException $e) {
// 항목없음/권한없음/옵션없음/타상품옵션 — 사유별 404/403/422 매핑
return $this->cartOperationResponse($e);
@@ -291,6 +316,14 @@ class CartController extends PublicBaseController
$this->cartService->deleteItem($id, $userId, $cartKey);
return ResponseHelper::moduleSuccess('sirsoft-ecommerce', 'messages.cart.deleted');
} catch (CartQuantityLimitException $e) {
// 장바구니 수량 상한 초과 — generic 500 이 아닌 422 명시 차단
return ResponseHelper::error(
'sirsoft-ecommerce::validation.cart.quantity_limit_exceeded',
422,
['code' => 'cart_quantity_limit_exceeded', 'detail' => $e->getMessage()],
['limit' => $e->getLimit(), 'attempted' => $e->getAttempted()]
);
} catch (CartOperationException $e) {
// 없는 항목(404)/타인 항목(403) 삭제 시도 — generic 500 이 아닌 사유별 4xx
return $this->cartOperationResponse($e);
@@ -393,8 +426,11 @@ class CartController extends PublicBaseController
$mergedCount = $this->cartService->mergeGuestCartToUser($cartKey, $userId);
// 병합은 수량을 상한까지 줄일 수 있다. 줄인 사실을 응답에 담지 않으면 사용자는
// 자기가 담아 둔 수량이 조용히 바뀐 것을 알 방법이 없다.
return ResponseHelper::moduleSuccess('sirsoft-ecommerce', 'messages.cart.merged', [
'merged_count' => $mergedCount,
'adjustments' => $this->cartService->getLastMergeAdjustments(),
]);
} catch (Exception $e) {
Log::error('cart.merge failed', ['error' => $e->getMessage()]);
@@ -10,6 +10,7 @@ use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Log;
use Modules\Sirsoft\Ecommerce\Exceptions\CartUnavailableException;
use Modules\Sirsoft\Ecommerce\Exceptions\InsufficientStockException;
use Modules\Sirsoft\Ecommerce\Exceptions\MileageValidationException;
use Modules\Sirsoft\Ecommerce\Exceptions\OrderProcessingException;
use Modules\Sirsoft\Ecommerce\Exceptions\PaymentAmountMismatchException;
use Modules\Sirsoft\Ecommerce\Exceptions\UnsupportedPaymentCurrencyException;
@@ -164,6 +165,19 @@ trait HandlesOrderCreation
'has_restriction_issue' => $e->hasRestrictionIssue(),
]);
} catch (MileageValidationException $e) {
// 마일리지 사용 정책 위반(한도/단위/최소사용액/잔액) — generic 500 이 아닌 422 명시 차단.
// 임시주문 생성 이후 설정이 바뀌었거나 임시주문이 조작된 경우 여기로 떨어진다.
Log::warning('Order create: mileage usage policy violation', [
'message' => $e->getMessage(),
]);
return ResponseHelper::error(
'sirsoft-ecommerce::exceptions.order_create_failed',
422,
['code' => 'mileage_usage_not_allowed', 'detail' => $e->getMessage()]
);
} catch (OrderProcessingException $e) {
// 주문 확정 재계산 검증 실패(쿠폰 만료/min_amount/per_user_limit/not_combinable 등)
// generic 500 이 아닌 422 로 하드 차단 — 서버 우회 방지 (U14/MP06)
@@ -5,6 +5,7 @@ namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
use App\Extension\HookManager;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Sirsoft\Ecommerce\Http\Requests\Concerns\ResolvesBaseCurrencyPrecision;
use Modules\Sirsoft\Ecommerce\Models\Product;
use Modules\Sirsoft\Ecommerce\Models\ProductOption;
@@ -16,6 +17,8 @@ use Modules\Sirsoft\Ecommerce\Models\ProductOption;
*/
class BulkUpdateOptionsRequest extends FormRequest
{
use ResolvesBaseCurrencyPrecision;
/**
* 권한 확인
*
@@ -33,6 +36,8 @@ class BulkUpdateOptionsRequest extends FormRequest
*/
public function rules(): array
{
$priceRule = $this->basePriceRule();
$rules = [
// 처리 대상 옵션 ID 배열 (필수) - "productId-optionId" 형식
'ids' => ['required', 'array', 'min:1'],
@@ -54,8 +59,9 @@ class BulkUpdateOptionsRequest extends FormRequest
'items.*.option_name' => ['nullable', 'array'],
'items.*.option_name.*' => ['nullable', 'string', 'max:255'],
'items.*.sku' => ['nullable', 'string', 'max:100'],
'items.*.list_price' => ['nullable', 'numeric', 'min:0'],
'items.*.price_adjustment' => ['nullable', 'numeric'],
// 단건 등록/수정과 동일한 통화 정밀도 규칙
'items.*.list_price' => ['nullable', 'numeric', $priceRule, 'min:0'],
'items.*.price_adjustment' => ['nullable', 'numeric', $priceRule],
'items.*.stock_quantity' => ['nullable', 'integer', 'min:0'],
'items.*.safe_stock_quantity' => ['nullable', 'integer', 'min:0'],
'items.*.is_default' => ['nullable', 'boolean'],
@@ -3,10 +3,12 @@
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
use App\Extension\HookManager;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Sirsoft\Ecommerce\Enums\ProductDisplayStatus;
use Modules\Sirsoft\Ecommerce\Enums\ProductSalesStatus;
use Modules\Sirsoft\Ecommerce\Http\Requests\Concerns\ResolvesBaseCurrencyPrecision;
use Modules\Sirsoft\Ecommerce\Models\Product;
use Modules\Sirsoft\Ecommerce\Models\ProductOption;
@@ -17,6 +19,8 @@ use Modules\Sirsoft\Ecommerce\Models\ProductOption;
*/
class BulkUpdateProductsRequest extends FormRequest
{
use ResolvesBaseCurrencyPrecision;
/**
* 권한 확인
*
@@ -34,6 +38,8 @@ class BulkUpdateProductsRequest extends FormRequest
*/
public function rules(): array
{
$priceRule = $this->basePriceRule();
$rules = [
// 처리 대상 상품 ID 배열 (필수)
'ids' => ['required', 'array', 'min:1'],
@@ -57,8 +63,9 @@ class BulkUpdateProductsRequest extends FormRequest
'items.*.id' => ['required', 'integer', Rule::exists(Product::class, 'id')],
'items.*.name' => ['nullable', 'array'],
'items.*.name.*' => ['nullable', 'string', 'max:255'],
'items.*.list_price' => ['nullable', 'numeric', 'min:0'],
'items.*.selling_price' => ['nullable', 'numeric', 'min:0'],
// 단건 등록/수정과 동일한 통화 정밀도·하한 규칙 (일괄 수정만 느슨하면 우회로가 된다)
'items.*.list_price' => ['nullable', 'numeric', $priceRule, 'min:0.01'],
'items.*.selling_price' => ['nullable', 'numeric', $priceRule, 'min:0.01'],
'items.*.sales_status' => ['nullable', 'string', function ($attribute, $value, $fail) {
if ($value !== null && ! in_array($value, ProductSalesStatus::values())) {
$fail(__('sirsoft-ecommerce::validation.product.invalid_sales_status'));
@@ -86,8 +93,8 @@ class BulkUpdateProductsRequest extends FormRequest
'option_items.*.option_name' => ['nullable', 'array'],
'option_items.*.option_name.*' => ['nullable', 'string', 'max:255'],
'option_items.*.sku' => ['nullable', 'string', 'max:100'],
'option_items.*.list_price' => ['nullable', 'numeric', 'min:0'],
'option_items.*.price_adjustment' => ['nullable', 'numeric'],
'option_items.*.list_price' => ['nullable', 'numeric', $priceRule, 'min:0'],
'option_items.*.price_adjustment' => ['nullable', 'numeric', $priceRule],
'option_items.*.stock_quantity' => ['nullable', 'integer', 'min:0'],
'option_items.*.safe_stock_quantity' => ['nullable', 'integer', 'min:0'],
'option_items.*.is_default' => ['nullable', 'boolean'],
@@ -112,4 +119,37 @@ class BulkUpdateProductsRequest extends FormRequest
'option_items.*.option_id.exists' => __('sirsoft-ecommerce::validation.product.bulk.option_not_found'),
];
}
/**
* 단일 필드 규칙으로 표현할 수 없는 가격 관계를 검증합니다.
*
* 일괄 수정은 정가/판매가 중 한쪽만 보내는 부분 전송이 흔하므로, **둘 다 전송된 경우에만**
* 비교합니다. 한쪽만 온 경우의 정합성은 Service 가 DB 기존값과 대조해 판정합니다.
*
* @param Validator $validator 검증기
*/
public function withValidator(Validator $validator): void
{
$validator->after(function (Validator $validator) {
foreach ((array) $this->input('items', []) as $index => $item) {
if (! is_array($item)) {
continue;
}
$list = $item['list_price'] ?? null;
$selling = $item['selling_price'] ?? null;
if ($list === null || $selling === null || $list === '' || $selling === '') {
continue;
}
if ((float) $selling > (float) $list) {
$validator->errors()->add(
"items.{$index}.selling_price",
__('sirsoft-ecommerce::validation.product.selling_price_lte_list')
);
}
}
});
}
}
@@ -0,0 +1,51 @@
<?php
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
/**
* 상품 활동 로그 조회 요청 (관리자)
*
* 권한은 라우트 미들웨어(permission:admin,sirsoft-ecommerce.products.read)에서 처리하며,
* 여기서는 페이지 크기·정렬 옵션만 검증합니다.
*/
class ProductLogsRequest extends FormRequest
{
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인 (권한은 미들웨어에서 처리)
*
* @return bool 항상 true
*/
public function authorize(): bool
{
return true;
}
/**
* 요청에 적용할 검증 규칙
*
* @return array<string, array<int, mixed>> 검증 규칙 배열
*/
public function rules(): array
{
return [
'per_page' => ['sometimes', 'integer', 'min:1', 'max:100'],
'sort_order' => ['sometimes', 'string', Rule::in(['asc', 'desc'])],
];
}
/**
* 활동 로그 조회 필터(페이지 크기·정렬)를 반환합니다.
*
* @return array{per_page: int, sort_order: string} 조회 필터
*/
public function getFilters(): array
{
return [
'per_page' => (int) ($this->query('per_page', 10)),
'sort_order' => $this->query('sort_order', 'desc'),
];
}
}
@@ -2,6 +2,7 @@
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
/**
@@ -9,6 +10,9 @@ use Illuminate\Foundation\Http\FormRequest;
*/
class ProductNoticeTemplateListRequest extends FormRequest
{
/** @var int 숫자 per_page 의 상한 */
private const MAX_PER_PAGE = 100;
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
@@ -69,4 +73,30 @@ class ProductNoticeTemplateListRequest extends FormRequest
'page.min' => __('sirsoft-ecommerce::validation.list.page.min'),
];
}
/**
* per_page 가 숫자인 경우 상한을 강제합니다.
*
* `all` 은 그대로 허용하되(기존 계약 유지), 숫자로 전달되면 상한 없이 임의 값이 들어와
* 한 요청으로 전체 데이터를 끌어갈 수 있으므로 여기서 막습니다.
*
* @param Validator $validator 검증기
*/
public function withValidator(Validator $validator): void
{
$validator->after(function (Validator $validator) {
$perPage = $this->input('per_page');
if ($perPage === null || $perPage === '' || $perPage === 'all') {
return;
}
if (is_numeric($perPage) && (int) $perPage > self::MAX_PER_PAGE) {
$validator->errors()->add(
'per_page',
__('sirsoft-ecommerce::validation.list.per_page_max', ['max' => self::MAX_PER_PAGE])
);
}
});
}
}
@@ -0,0 +1,75 @@
<?php
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
/**
* 상품 복사용 데이터 조회 요청 (관리자)
*
* 권한은 라우트 미들웨어(permission:admin,sirsoft-ecommerce.products.create)에서 처리하며,
* 여기서는 어떤 항목을 함께 복사할지 고르는 플래그만 검증합니다.
*/
class ShowProductForCopyRequest extends FormRequest
{
/**
* 복사 대상 항목과 미지정 시 기본값
*
* SEO 정보만 기본 제외 — 메타 제목·설명은 상품마다 달라야 검색 결과에서 구분된다.
*/
private const COPY_TARGETS = [
'images' => true,
'options' => true,
'categories' => true,
'sales_info' => true,
'description' => true,
'notice' => true,
'common_info' => true,
'other_info' => true,
'shipping' => true,
'seo' => false,
'identification' => true,
];
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인 (권한은 미들웨어에서 처리)
*
* @return bool 항상 true
*/
public function authorize(): bool
{
return true;
}
/**
* 요청에 적용할 검증 규칙
*
* @return array<string, array<int, mixed>> 검증 규칙 배열
*/
public function rules(): array
{
$rules = [];
foreach (array_keys(self::COPY_TARGETS) as $target) {
$rules["copy_{$target}"] = ['sometimes', 'boolean'];
}
return $rules;
}
/**
* 복사 옵션을 반환합니다.
*
* @return array<string, bool> 항목별 복사 여부
*/
public function getCopyOptions(): array
{
$options = [];
foreach (self::COPY_TARGETS as $target => $default) {
$options[$target] = $this->boolean("copy_{$target}", $default);
}
return $options;
}
}
@@ -85,7 +85,7 @@ class StoreEcommerceSettingsRequest extends FormRequest
'language_currency.currencies.*.base_unit' => ['nullable', 'integer', 'min:1'],
'language_currency.currencies.*.rounding_unit' => ['nullable', 'string'],
'language_currency.currencies.*.rounding_method' => ['nullable', 'string', 'in:floor,round,ceil'],
'language_currency.currencies.*.decimal_places' => ['nullable', 'integer', 'min:0', 'max:8'],
'language_currency.currencies.*.decimal_places' => ['nullable', 'integer', 'min:'.config('sirsoft-ecommerce.limits.decimal_places_min', 0), 'max:'.config('sirsoft-ecommerce.limits.decimal_places_max', 8)],
'language_currency.currencies.*.is_default' => ['nullable', 'boolean'],
// 통화별 언어(가입 시 통화 추정용 매핑, A4). 후보 = 시스템 지원 로케일.
'language_currency.currencies.*.locales' => ['nullable', 'array'],
@@ -132,8 +132,9 @@ class StoreEcommerceSettingsRequest extends FormRequest
'order_settings.bank_accounts.*.is_active' => ['nullable', 'boolean'],
'order_settings.bank_accounts.*.is_default' => ['nullable', 'boolean'],
'order_settings.auto_cancel_expired' => ['nullable', 'boolean'],
'order_settings.auto_cancel_days' => ['nullable', 'integer', 'min:0', 'max:30'],
'order_settings.cart_expiry_days' => ['nullable', 'integer', 'min:1', 'max:365'],
// 0 은 now()->addDays(0) = 즉시 만료라 실질적으로 사용할 수 없는 값이다 → UI(min:1)가 옳다
'order_settings.auto_cancel_days' => ['nullable', 'integer', 'min:'.config('sirsoft-ecommerce.limits.auto_cancel_days_min', 1), 'max:'.config('sirsoft-ecommerce.limits.auto_cancel_days_max', 30)],
'order_settings.cart_expiry_days' => ['nullable', 'integer', 'min:'.config('sirsoft-ecommerce.limits.cart_expiry_days_min', 1), 'max:'.config('sirsoft-ecommerce.limits.cart_expiry_days_max', 365)],
'order_settings.stock_restore_on_cancel' => ['nullable', 'boolean'],
'order_settings.confirmable_statuses' => ['nullable', 'array'],
'order_settings.confirmable_statuses.*' => ['string', 'in:payment_complete,shipping_hold,preparing,shipping_ready,shipping,delivered'],
@@ -151,32 +152,32 @@ class StoreEcommerceSettingsRequest extends FormRequest
// review_settings 섹션
'review_settings' => ['sometimes', 'array'],
'review_settings.write_deadline_days' => ['nullable', 'integer', 'min:1', 'max:365'],
'review_settings.max_images' => ['nullable', 'integer', 'min:0', 'max:20'],
'review_settings.max_image_size_mb' => ['nullable', 'integer', 'min:1', 'max:50'],
'review_settings.write_deadline_days' => ['nullable', 'integer', 'min:'.config('sirsoft-ecommerce.limits.write_deadline_days_min', 1), 'max:'.config('sirsoft-ecommerce.limits.write_deadline_days_max', 365)],
'review_settings.max_images' => ['nullable', 'integer', 'min:'.config('sirsoft-ecommerce.limits.max_images_min', 0), 'max:'.config('sirsoft-ecommerce.limits.max_images_max', 20)],
'review_settings.max_image_size_mb' => ['nullable', 'integer', 'min:'.config('sirsoft-ecommerce.limits.max_image_size_mb_min', 1), 'max:'.config('sirsoft-ecommerce.limits.max_image_size_mb_max', 50)],
// mileage 섹션
'mileage' => ['sometimes', 'array'],
'mileage.enabled' => ['required_with:mileage', 'boolean'],
'mileage.default_earn_rate' => ['nullable', 'numeric', 'min:0', 'max:100'],
'mileage.default_earn_rate' => ['nullable', 'numeric', 'min:'.config('sirsoft-ecommerce.limits.default_earn_rate_min', 0), 'max:'.config('sirsoft-ecommerce.limits.default_earn_rate_max', 100)],
// 마일리지 차감 시점은 결제수단별(order_settings.payment_methods.*.mileage_deduction_timing)로 관리한다.
'mileage.earn_trigger' => ['nullable', 'string', 'in:delivered,confirmed'],
'mileage.earn_delay_days' => ['nullable', 'integer', 'min:0', 'max:365'],
'mileage.earn_delay_days' => ['nullable', 'integer', 'min:'.config('sirsoft-ecommerce.limits.earn_delay_days_min', 0), 'max:'.config('sirsoft-ecommerce.limits.earn_delay_days_max', 365)],
'mileage.currency_rules' => ['nullable', 'array'],
// 통화 코드: ISO 4217 형식(3자리 영문 대문자) 강제
'mileage.currency_rules.*.currency_code' => ['required_with:mileage.currency_rules', 'string', 'regex:/^[A-Z]{3}$/'],
// 1점당 금액: 0이면 마일리지가 금전 가치 0 → 사용 불가. 최소 0 초과(0.001 단위까지 허용)
'mileage.currency_rules.*.point_value' => ['nullable', 'numeric', 'min:0.001'],
'mileage.currency_rules.*.min_use_amount' => ['nullable', 'integer', 'min:0'],
'mileage.currency_rules.*.use_unit' => ['nullable', 'integer', 'min:1'],
'mileage.currency_rules.*.point_value' => ['nullable', 'numeric', 'min:'.config('sirsoft-ecommerce.limits.point_value_min', 0.001)],
'mileage.currency_rules.*.min_use_amount' => ['nullable', 'integer', 'min:'.config('sirsoft-ecommerce.limits.min_use_amount_min', 0)],
'mileage.currency_rules.*.use_unit' => ['nullable', 'integer', 'min:'.config('sirsoft-ecommerce.limits.use_unit_min', 1)],
'mileage.currency_rules.*.max_use_type' => ['nullable', 'string', 'in:percent,fixed'],
'mileage.currency_rules.*.max_use_percent' => ['nullable', 'numeric', 'min:0', 'max:100'],
'mileage.currency_rules.*.max_use_percent' => ['nullable', 'numeric', 'min:'.config('sirsoft-ecommerce.limits.max_use_percent_min', 0), 'max:'.config('sirsoft-ecommerce.limits.max_use_percent_max', 100)],
// 최대 사용한도(고정금액): 비합리적 거액 방지를 위해 10억 상한
'mileage.currency_rules.*.max_use_value' => ['nullable', 'integer', 'min:0', 'max:1000000000'],
'mileage.currency_rules.*.max_use_value' => ['nullable', 'integer', 'min:'.config('sirsoft-ecommerce.limits.max_use_value_min', 0), 'max:'.config('sirsoft-ecommerce.limits.max_use_value_max', 1000000000)],
'mileage.expiry_enabled' => ['nullable', 'boolean'],
'mileage.expiry_days' => ['nullable', 'integer', 'min:1', 'max:3650'],
'mileage.expiry_days' => ['nullable', 'integer', 'min:'.config('sirsoft-ecommerce.limits.expiry_days_min', 1), 'max:'.config('sirsoft-ecommerce.limits.expiry_days_max', 3650)],
'mileage.expiry_notification_enabled' => ['nullable', 'boolean'],
'mileage.expiry_notification_days_before' => ['nullable', 'integer', 'min:1', 'max:365'],
'mileage.expiry_notification_days_before' => ['nullable', 'integer', 'min:'.config('sirsoft-ecommerce.limits.expiry_notification_days_before_min', 1), 'max:'.config('sirsoft-ecommerce.limits.expiry_notification_days_before_max', 365)],
// shipping 섹션
'shipping' => ['sometimes', 'array'],
@@ -13,6 +13,8 @@ use Modules\Sirsoft\Ecommerce\Enums\ProductDisplayStatus;
use Modules\Sirsoft\Ecommerce\Enums\ProductImageCollection;
use Modules\Sirsoft\Ecommerce\Enums\ProductSalesStatus;
use Modules\Sirsoft\Ecommerce\Enums\ProductTaxStatus;
use Modules\Sirsoft\Ecommerce\Http\Requests\Concerns\ResolvesBaseCurrencyPrecision;
use Modules\Sirsoft\Ecommerce\Http\Requests\Concerns\ValidatesMileageRate;
use Modules\Sirsoft\Ecommerce\Models\Brand;
use Modules\Sirsoft\Ecommerce\Models\Category;
use Modules\Sirsoft\Ecommerce\Models\Product;
@@ -25,6 +27,9 @@ use Modules\Sirsoft\Ecommerce\Models\ShippingPolicy;
*/
class StoreProductRequest extends FormRequest
{
use ResolvesBaseCurrencyPrecision;
use ValidatesMileageRate;
/**
* 권한 확인
*
@@ -44,8 +49,7 @@ class StoreProductRequest extends FormRequest
{
// 기본통화의 소수 자릿수 — 가격 입력 허용 자릿수 상한.
// KRW(0) 이면 정수만, USD/EUR(2) 이면 소수 2자리까지 허용.
$decimalPlaces = $this->baseCurrencyDecimalPlaces();
$priceRule = $decimalPlaces > 0 ? 'decimal:0,'.$decimalPlaces : 'integer';
$priceRule = $this->basePriceRule();
$rules = [
// 기본 정보
@@ -258,6 +262,8 @@ class StoreProductRequest extends FormRequest
{
$validator->after(function (Validator $validator) {
$this->validatePurchaseRestrictionRoles($validator);
// 정률 적립률 상한 — mileage_type 에 따라 의미가 달라 필드 규칙으로 표현 불가
$this->validateMileageRates($validator, 'options');
});
}
@@ -319,28 +325,6 @@ class StoreProductRequest extends FormRequest
];
}
/**
* 기본통화의 소수 자릿수를 반환합니다.
*
* 환경설정 language_currency 의 default_currency 에 매칭되는 통화의
* decimal_places 값(예: KRW=0, USD=2)을 반환합니다.
*
* @return int 소수 자릿수 (미설정 시 0)
*/
protected function baseCurrencyDecimalPlaces(): int
{
$settings = g7_module_settings('sirsoft-ecommerce', 'language_currency');
$default = $settings['default_currency'] ?? 'KRW';
foreach ($settings['currencies'] ?? [] as $currency) {
if (($currency['code'] ?? null) === $default) {
return (int) ($currency['decimal_places'] ?? 0);
}
}
return 0;
}
/**
* 데이터 전처리
*/
@@ -0,0 +1,47 @@
<?php
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Concerns;
/**
* 기본통화 소수 자릿수 해석 Trait
*
* 가격 검증 규칙은 통화의 소수 자릿수에 따라 달라진다 (KRW=0 → `integer`,
* USD=2 → `decimal:0,2`). 단건 등록/수정에만 있던 이 규칙을 일괄 수정 경로에서도
* 동일하게 쓰기 위해 추출했다.
*/
trait ResolvesBaseCurrencyPrecision
{
/**
* 기본통화의 소수 자릿수를 반환합니다.
*
* 환경설정 language_currency 의 default_currency 에 매칭되는 통화의
* decimal_places 값(예: KRW=0, USD=2)을 반환합니다.
*
* @return int 소수 자릿수 (미설정 시 0)
*/
protected function baseCurrencyDecimalPlaces(): int
{
$settings = g7_module_settings('sirsoft-ecommerce', 'language_currency');
$default = $settings['default_currency'] ?? 'KRW';
foreach ($settings['currencies'] ?? [] as $currency) {
if (($currency['code'] ?? null) === $default) {
return (int) ($currency['decimal_places'] ?? 0);
}
}
return 0;
}
/**
* 기본통화 정밀도에 맞는 가격 검증 규칙을 반환합니다.
*
* @return string 검증 규칙 (`integer` 또는 `decimal:0,N`)
*/
protected function basePriceRule(): string
{
$decimalPlaces = $this->baseCurrencyDecimalPlaces();
return $decimalPlaces > 0 ? 'decimal:0,'.$decimalPlaces : 'integer';
}
}
@@ -0,0 +1,53 @@
<?php
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Concerns;
use Illuminate\Contracts\Validation\Validator;
/**
* 옵션별 적립률 상한 검증 Trait
*
* 전역 `default_earn_rate` 는 `max:100` 인데, 동일한 `/100` 정률 계산에 쓰이는
* 옵션별 `mileage_value` 에는 상한이 없었다. `mileage_type` 에 따라 의미가 달라
* (percent = 비율 / fixed = 금액) 필드 단위 규칙으로는 표현할 수 없으므로
* 인덱스별로 판정한다.
*/
trait ValidatesMileageRate
{
/**
* 정률(percent) 적립의 값이 100을 넘지 않는지 검증합니다.
*
* `fixed`(정액)는 금액이므로 상한을 두지 않는다.
*
* @param Validator $validator 검증기
* @param string $arrayKey 검사할 배열 키 (예: `options`, `items`)
*/
protected function validateMileageRates(Validator $validator, string $arrayKey = 'options'): void
{
$rows = $this->input($arrayKey);
if (! is_array($rows)) {
return;
}
foreach ($rows as $index => $row) {
if (! is_array($row)) {
continue;
}
$type = $row['mileage_type'] ?? null;
$value = $row['mileage_value'] ?? null;
if ($type !== 'percent' || $value === null || $value === '') {
continue;
}
if ((float) $value > 100) {
$validator->errors()->add(
"{$arrayKey}.{$index}.mileage_value",
__('sirsoft-ecommerce::validation.product.mileage_percent_max')
);
}
}
}
}
@@ -17,7 +17,7 @@ class BulkAddToCartRequest extends FormRequest
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* @return bool
* @return bool 항상 true (권한은 미들웨어에서 검증)
*/
public function authorize(): bool
{
@@ -27,16 +27,19 @@ class BulkAddToCartRequest extends FormRequest
/**
* 요청에 적용할 검증 규칙
*
* @return array
* @return array<string, mixed> 검증 규칙
*/
public function rules(): array
{
$maxQuantity = (int) config('sirsoft-ecommerce.cart.max_quantity', 99);
$rules = [
'product_id' => ['required', 'integer', Rule::exists(Product::class, 'id')],
'items' => 'required|array|min:1',
// 메인 옵션 식별자 (옵션 ID 기반). 옵션 없는 상품은 미전송 → 서버가 기본 옵션 자동 해석
'items.*.product_option_id' => ['nullable', 'integer'],
'items.*.quantity' => 'required|integer|min:1|max:9999',
// 장바구니 수량 상한은 config('sirsoft-ecommerce.cart.max_quantity') 가 SSoT
'items.*.quantity' => ['required', 'integer', 'min:1', 'max:'.$maxQuantity],
// 추가옵션 선택 (서버에서 value_id 기준 가격 재조회·검증 — 클라 가격 신뢰 금지)
'items.*.additional_option_selections' => 'nullable|array',
'items.*.additional_option_selections.*.additional_option_id' => 'required_with:items.*.additional_option_selections|integer',
@@ -51,7 +54,7 @@ class BulkAddToCartRequest extends FormRequest
/**
* 검증 오류 메시지 커스터마이징
*
* @return array
* @return array<string, string> 검증 메시지
*/
public function messages(): array
{
@@ -15,7 +15,7 @@ class ChangeCartOptionRequest extends FormRequest
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* @return bool
* @return bool 항상 true (권한은 미들웨어에서 검증)
*/
public function authorize(): bool
{
@@ -25,13 +25,16 @@ class ChangeCartOptionRequest extends FormRequest
/**
* 요청에 적용할 검증 규칙
*
* @return array
* @return array<string, mixed> 검증 규칙
*/
public function rules(): array
{
$maxQuantity = (int) config('sirsoft-ecommerce.cart.max_quantity', 99);
$rules = [
'product_option_id' => ['required', 'integer', Rule::exists(ProductOption::class, 'id')],
'quantity' => 'required|integer|min:1|max:9999',
// 장바구니 수량 상한은 config('sirsoft-ecommerce.cart.max_quantity') 가 SSoT
'quantity' => ['required', 'integer', 'min:1', 'max:'.$maxQuantity],
// 추가옵션 재선택 (미전달 시 기존 선택 유지 — 서버에서 value_id 검증/가격 재조회)
'additional_option_selections' => 'nullable|array',
'additional_option_selections.*.additional_option_id' => 'required_with:additional_option_selections|integer',
@@ -46,7 +49,7 @@ class ChangeCartOptionRequest extends FormRequest
/**
* 검증 오류 메시지 커스터마이징
*
* @return array
* @return array<string, string> 검증 메시지
*/
public function messages(): array
{
@@ -78,7 +78,6 @@ class CreateOrderRequest extends FormRequest
'dbank.bank_name' => 'nullable|string|max:50',
'dbank.account_number' => 'required_if:payment_method,dbank|nullable|string|max:50',
'dbank.account_holder' => 'required_if:payment_method,dbank|nullable|string|max:50',
'dbank.due_days' => 'nullable|integer|min:1|max:30',
// 배송지 저장
'save_shipping_address' => 'nullable|boolean',
@@ -12,6 +12,8 @@ class UpdateCartQuantityRequest extends FormRequest
{
/**
* 사용자가 이 요청을 수행할 권한이 있는지 확인
*
* @return bool 항상 true (권한은 미들웨어에서 검증)
*/
public function authorize(): bool
{
@@ -21,12 +23,15 @@ class UpdateCartQuantityRequest extends FormRequest
/**
* 요청에 적용할 검증 규칙
*
* @return array
* @return array<string, mixed> 검증 규칙
*/
public function rules(): array
{
$maxQuantity = (int) config('sirsoft-ecommerce.cart.max_quantity', 99);
$rules = [
'quantity' => 'required|integer|min:1|max:9999',
// 장바구니 수량 상한은 config('sirsoft-ecommerce.cart.max_quantity') 가 SSoT
'quantity' => ['required', 'integer', 'min:1', 'max:'.$maxQuantity],
];
return HookManager::applyFilters('sirsoft-ecommerce.cart.update_quantity_validation_rules', $rules, $this);
@@ -35,7 +40,7 @@ class UpdateCartQuantityRequest extends FormRequest
/**
* 검증 오류 메시지 커스터마이징
*
* @return array
* @return array<string, string> 검증 메시지
*/
public function messages(): array
{
@@ -19,7 +19,7 @@ class MergeCartOnLoginListener implements HookListenerInterface
/**
* 구독할 훅 목록 반환
*
* @return array
* @return array 훅 이름 => 실행 설정(method/priority/sync) 매핑
*/
public static function getSubscribedHooks(): array
{
@@ -27,6 +27,12 @@ class MergeCartOnLoginListener implements HookListenerInterface
'core.auth.after_login' => [
'method' => 'handle',
'priority' => 20,
// 비회원 장바구니 식별자는 전송 헤더로만 온다. 큐 컨텍스트(HookContextCapture)는
// IP·UA·path 만 복원하고 임의 헤더는 나르지 않으므로, 큐로 넘기면 워커에서
// 헤더가 null 이 되어 병합이 조용히 건너뛰어진다 — 기본 큐 드라이버가 database 인
// 설치에서는 로그인해도 담아둔 장바구니가 사라진다. 로그인 응답 안에서 끝나야 하는
// 작업이므로 동기 실행한다(실패는 아래 try/catch 가 흡수해 로그인은 지키다).
'sync' => true,
],
];
}
@@ -34,8 +40,7 @@ class MergeCartOnLoginListener implements HookListenerInterface
/**
* 로그인 성공 시 비회원 장바구니를 회원 계정으로 병합합니다.
*
* @param mixed ...$args 첫 번째: User 객체, 두 번째: 로그인 컨텍스트 배열
* @return void
* @param mixed ...$args 첫 번째: User 객체, 두 번째: 로그인 컨텍스트 배열
*/
public function handle(...$args): void
{
@@ -45,14 +50,19 @@ class MergeCartOnLoginListener implements HookListenerInterface
return;
}
// 코어 로그인 훅 페이로드는 이커머스를 모르므로(모듈 키를 코어 계약에 넣지 않는다)
// 비회원 장바구니 식별자는 전송 헤더가 유일한 출처다. 형식은 병합 엔드포인트
// (MergeGuestCartRequest)와 같은 규칙으로 아래에서 검증한다.
// audit:allow listener-formrequest-bypass reason: 코어 훅이 전달하지 않는 전송 계층 식별자 — 아래에서 형식 검증
$cartKey = request()->header('X-Cart-Key');
if (! $cartKey) {
if (! is_string($cartKey) || ! preg_match('/^ck_[a-zA-Z0-9]{32}$/', $cartKey)) {
return;
}
try {
$mergedCount = $this->cartService->mergeGuestCartToUser($cartKey, $user->id);
$adjustments = $this->cartService->getLastMergeAdjustments();
if ($mergedCount > 0) {
Log::info('장바구니 병합 완료', [
@@ -61,6 +71,16 @@ class MergeCartOnLoginListener implements HookListenerInterface
'merged_count' => $mergedCount,
]);
}
// 로그인 경로의 병합은 응답에 결과를 실을 자리가 없다. 수량이 상한까지 줄었다면
// 최소한 운영자가 추적할 수 있도록 조정 내역을 남긴다 (조용한 클램프 금지).
if ($adjustments !== []) {
Log::warning('장바구니 병합 중 수량이 상한으로 조정됨', [
'user_id' => $user->uuid,
'cart_key' => $cartKey,
'adjustments' => $adjustments,
]);
}
} catch (\Exception $e) {
Log::error('장바구니 병합 실패', [
'user_id' => $user->uuid,
@@ -113,6 +113,7 @@ class Order extends Model
'promotions_applied_snapshot',
'shipping_policy_applied_snapshot',
'promotions_available_snapshot',
'mileage_policy_snapshot',
'order_meta',
// 다중 통화 컬럼 (JSON)
'mc_subtotal_amount',
@@ -180,6 +181,7 @@ class Order extends Model
'promotions_applied_snapshot' => 'array',
'shipping_policy_applied_snapshot' => 'array',
'promotions_available_snapshot' => 'array',
'mileage_policy_snapshot' => 'array',
'order_meta' => 'array',
'order_status' => OrderStatusEnum::class,
'order_device' => DeviceTypeEnum::class,
@@ -253,4 +253,13 @@ interface ProductRepositoryInterface
* @return bool 성공 여부
*/
public function syncStockFromOptions(int $productId): bool;
/**
* 상품과 그 옵션의 활동 로그를 합쳐 페이지네이션으로 조회
*
* @param Product $product 대상 상품
* @param array $filters 조회 필터 (per_page, sort_order)
* @return LengthAwarePaginator 활동 로그 페이지네이터
*/
public function getActivityLogsForProduct(Product $product, array $filters = []): LengthAwarePaginator;
}
@@ -3,6 +3,7 @@
namespace Modules\Sirsoft\Ecommerce\Repositories;
use App\Helpers\PermissionHelper;
use App\Models\ActivityLog;
use App\Search\Engines\DatabaseFulltextEngine;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
@@ -12,6 +13,7 @@ use Modules\Sirsoft\Ecommerce\Enums\ProductDisplayStatus;
use Modules\Sirsoft\Ecommerce\Models\Category;
use Modules\Sirsoft\Ecommerce\Models\OrderOption;
use Modules\Sirsoft\Ecommerce\Models\Product;
use Modules\Sirsoft\Ecommerce\Models\ProductOption;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductRepositoryInterface;
/**
@@ -742,4 +744,31 @@ class ProductRepository implements ProductRepositoryInterface
{
return $this->model->where('id', $productId)->update(['stock_quantity' => $stock]);
}
/**
* {@inheritDoc}
*/
public function getActivityLogsForProduct(Product $product, array $filters = []): LengthAwarePaginator
{
$perPage = (int) ($filters['per_page'] ?? 10);
$sortOrder = ($filters['sort_order'] ?? 'desc') === 'asc' ? 'asc' : 'desc';
$optionIds = $product->options()->pluck('id')->toArray();
return ActivityLog::where(function (Builder $q) use ($product, $optionIds) {
// 상품 자체 로그
$q->where(function (Builder $sub) use ($product) {
$sub->where('loggable_type', $product->getMorphClass())
->where('loggable_id', $product->getKey());
});
// 해당 상품의 옵션 로그
if (! empty($optionIds)) {
$q->orWhere(function (Builder $sub) use ($optionIds) {
$sub->where('loggable_type', (new ProductOption)->getMorphClass())
->whereIn('loggable_id', $optionIds);
});
}
})->orderBy('created_at', $sortOrder)->paginate($perPage);
}
}
@@ -12,8 +12,10 @@ use Modules\Sirsoft\Ecommerce\DTO\CartWithCalculationResult;
use Modules\Sirsoft\Ecommerce\DTO\OrderCalculationResult;
use Modules\Sirsoft\Ecommerce\DTO\ShippingAddress;
use Modules\Sirsoft\Ecommerce\Exceptions\CartOperationException;
use Modules\Sirsoft\Ecommerce\Http\Middleware\ResolveShippingCountry;
use Modules\Sirsoft\Ecommerce\Exceptions\CartQuantityLimitException;
use Modules\Sirsoft\Ecommerce\Exceptions\CartUnavailableException;
use Modules\Sirsoft\Ecommerce\Exceptions\OrderProcessingException;
use Modules\Sirsoft\Ecommerce\Http\Middleware\ResolveShippingCountry;
use Modules\Sirsoft\Ecommerce\Models\Cart;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\CartRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\OrderRepositoryInterface;
@@ -219,6 +221,20 @@ class CartService
$currentQuantity = $existingItem ? $existingItem->quantity : 0;
$this->validateStock($data['product_option_id'], $data['quantity'] ?? 1, $currentQuantity);
// 장바구니 수량 상한 — 필드 규칙은 이번 요청분만 보므로 누적 합산은 여기서 판정한다
$this->validateCartQuantityLimit($currentQuantity + (int) ($data['quantity'] ?? 1));
// 구매수량 한도 — 담기 경로에서도 상품 정책(min/max_purchase_qty)을 강제한다
$this->validatePurchaseQuantityLimit(
(int) $data['product_id'],
$this->cartRepository->sumQuantityByProduct(
(int) $data['product_id'],
$data['user_id'] ?? null,
$data['cart_key'] ?? null,
$existingItem?->id
) + $currentQuantity + (int) ($data['quantity'] ?? 1)
);
$cart = DB::transaction(function () use ($data, $existingItem, $additionalSelections) {
if ($existingItem) {
// 동일 옵션 + 동일 추가옵션 조합 존재: 수량 증가
@@ -280,7 +296,7 @@ class CartService
$matchedOption = $productOptions->firstWhere('id', (int) $requestedOptionId);
if (! $matchedOption) {
throw new \Exception(__('sirsoft-ecommerce::validation.cart.option_not_found'));
throw new CartOperationException('option_not_found');
}
$productOptionId = $matchedOption->id;
@@ -288,7 +304,7 @@ class CartService
// 옵션 없는 상품: 첫 번째(기본) 옵션 사용
$defaultOption = $productOptions->first();
if (! $defaultOption) {
throw new \Exception(__('sirsoft-ecommerce::validation.cart.option_not_found'));
throw new CartOperationException('option_not_found');
}
$productOptionId = $defaultOption->id;
}
@@ -419,6 +435,17 @@ class CartService
$this->validateStock($newProductOptionId, $quantity, 0);
}
// 장바구니 수량 상한 (합산 기준)
$this->validateCartQuantityLimit($quantity + ($existingItem?->quantity ?? 0));
// 구매수량 한도 — 사용자가 명시적으로 조작하는 경로이므로 예외로 차단한다
$this->validatePurchaseQuantityLimit(
(int) $cart->product_id,
$this->cartRepository->sumQuantityByProduct((int) $cart->product_id, $userId, $cartKey, $cart->id)
- ($existingItem?->quantity ?? 0)
+ $quantity + ($existingItem?->quantity ?? 0)
);
HookManager::doAction('sirsoft-ecommerce.cart.before_change_option', $cart, $newProductOptionId, $quantity);
$cart = DB::transaction(function () use ($cart, $newProductOptionId, $quantity, $existingItem, $newSelections) {
@@ -521,7 +548,9 @@ class CartService
{
HookManager::doAction('sirsoft-ecommerce.cart.before_merge', $cartKey, $userId);
$mergedCount = DB::transaction(function () use ($cartKey, $userId) {
$adjustments = [];
$mergedCount = DB::transaction(function () use ($cartKey, $userId, &$adjustments) {
$guestItems = $this->cartRepository->findByCartKeyWithoutUser($cartKey);
$count = 0;
@@ -541,18 +570,74 @@ class CartService
$totalQuantity = $existingItem->quantity + $guestItem->quantity;
$finalQuantity = $availableStock > 0 ? min($totalQuantity, $availableStock) : $totalQuantity;
// 로그인 시 자동 병합이라 예외를 던지면 로그인 자체가 실패한다 →
// 상한까지 클램프하고 조정 내역을 반환값에 담아 화면이 안내하게 한다.
// 같은 상품의 다른 라인 수량까지 합산해 판정한다 (옵션 분할 우회 차단).
$otherLinesTotal = $this->cartRepository->sumQuantityByProduct(
$guestItem->product_id,
$userId,
null,
$existingItem->id,
);
$clamped = $this->clampToPurchaseQuantityLimit(
$guestItem->product_id,
$finalQuantity,
$otherLinesTotal,
);
// 이미 한도를 넘겨 저장돼 있던 라인을 병합이 깎지는 않는다 —
// 병합이 막아야 하는 것은 '이번 병합으로 늘어나는 분' 이다.
$clamped = max($clamped, (int) $existingItem->quantity);
if ($clamped !== $finalQuantity) {
$adjustments[] = [
'product_id' => $guestItem->product_id,
'product_option_id' => $guestItem->product_option_id,
'requested' => $finalQuantity,
'applied' => $clamped,
];
}
$this->cartRepository->update($existingItem, [
'quantity' => $finalQuantity,
'quantity' => $clamped,
]);
$this->cartRepository->delete($guestItem);
} else {
// 동일 옵션 없음: 재고 초과 시 조정 후 user_id 업데이트 (cart_key 유지)
$finalQuantity = $availableStock > 0 ? min($guestItem->quantity, $availableStock) : $guestItem->quantity;
$this->cartRepository->update($guestItem, [
'user_id' => $userId,
'quantity' => $finalQuantity,
]);
$otherLinesTotal = $this->cartRepository->sumQuantityByProduct(
$guestItem->product_id,
$userId,
null,
);
$clamped = $this->clampToPurchaseQuantityLimit(
$guestItem->product_id,
$finalQuantity,
$otherLinesTotal,
);
if ($clamped !== $finalQuantity) {
$adjustments[] = [
'product_id' => $guestItem->product_id,
'product_option_id' => $guestItem->product_option_id,
'requested' => $finalQuantity,
'applied' => $clamped,
];
}
if ($clamped <= 0) {
// 회원 장바구니가 이미 한도를 채웠다 — 0 수량 라인을 만들지 않고 버린다.
// 버린 사실은 위 조정 내역(applied = 0)으로 사용자에게 전달된다.
$this->cartRepository->delete($guestItem);
} else {
$this->cartRepository->update($guestItem, [
'user_id' => $userId,
'quantity' => $clamped,
]);
}
}
$count++;
@@ -561,7 +646,10 @@ class CartService
return $count;
});
HookManager::doAction('sirsoft-ecommerce.cart.after_merge', $cartKey, $userId, $mergedCount);
HookManager::doAction('sirsoft-ecommerce.cart.after_merge', $cartKey, $userId, $mergedCount, $adjustments);
// 조용한 클램프 금지 — 조정이 있었으면 호출 측이 사용자에게 알릴 수 있도록 노출한다
$this->lastMergeAdjustments = $adjustments;
return $mergedCount;
}
@@ -584,11 +672,11 @@ class CartService
$order = $this->orderRepository->findWithRelations($orderId);
if (! $order) {
throw new \Exception(__('sirsoft-ecommerce::exceptions.order_not_found'));
throw new OrderProcessingException(__('sirsoft-ecommerce::exceptions.order_not_found'));
}
if ((int) $order->user_id !== $userId) {
throw new \Exception(__('sirsoft-ecommerce::exceptions.unauthorized'));
throw new OrderProcessingException(__('sirsoft-ecommerce::exceptions.unauthorized'));
}
HookManager::doAction('sirsoft-ecommerce.cart.before_reorder', $order, $userId);
@@ -835,4 +923,85 @@ class CartService
throw new CartOperationException('invalid_option');
}
}
/**
* 병합 과정에서 수량이 조정된 내역 (조용한 클램프 방지).
*
* @var array<int, array{product_id: int, product_option_id: int, requested: int, applied: int}>
*/
protected array $lastMergeAdjustments = [];
/**
* 직전 병합에서 수량이 조정된 내역을 반환합니다.
*
* @return array<int, array{product_id: int, product_option_id: int, requested: int, applied: int}> 조정 내역
*/
public function getLastMergeAdjustments(): array
{
return $this->lastMergeAdjustments;
}
/**
* 장바구니 수량을 상한까지 클램프합니다.
*
* 예외를 던질 수 없는 경로(로그인 시 자동 병합)에서만 사용합니다.
*
* @param int $quantity 요청 수량
* @return int 상한 이내로 조정된 수량
*/
protected function clampToCartQuantityLimit(int $quantity): int
{
$max = (int) config('sirsoft-ecommerce.cart.max_quantity', 99);
return $max > 0 ? min($quantity, $max) : $quantity;
}
/**
* 장바구니 전역 상한과 상품별 구매수량 한도를 함께 적용해 클램프합니다.
*
* 예외를 던질 수 없는 경로(로그인 시 자동 병합) 전용입니다. 담기/수량변경 경로가
* `validatePurchaseQuantityLimit()` 로 422 를 내는 것과 같은 한도를, 던질 수 없는
* 자리에서는 클램프로 강제합니다. 두 곳 중 한 곳만 한도를 보면 비회원으로 담고
* 로그인하는 것만으로 상품 정책이 무력화됩니다.
*
* 상품 총수량 기준으로 판정하므로 옵션을 나눠 담는 우회도 함께 막힙니다.
* 최소 구매수량(`min_purchase_qty`)은 여기서 강제하지 않습니다 — 요청하지 않은 수량을
* 늘리는 것은 클램프가 아니라 사용자 의사에 반하는 변경입니다.
*
* @param int $productId 상품 ID
* @param int $lineQuantity 이 라인에 적용하려는 수량
* @param int $otherLinesTotal 같은 상품의 다른 라인 수량 합계
* @return int 두 한도 이내로 조정된 수량 (여유가 없으면 0)
*/
protected function clampToPurchaseQuantityLimit(int $productId, int $lineQuantity, int $otherLinesTotal = 0): int
{
$allowed = $this->clampToCartQuantityLimit($lineQuantity);
$product = $this->productRepository->find($productId);
$productMax = (int) ($product->max_purchase_qty ?? 0);
if ($product && $productMax > 0) {
$allowed = min($allowed, max(0, $productMax - $otherLinesTotal));
}
return $allowed;
}
/**
* 장바구니 라인 수량이 상한을 넘지 않는지 검증합니다.
*
* 필드 규칙(`max:`)은 이번 요청분만 보므로, 기존 수량과 합산되는 경로는 여기서 판정합니다.
*
* @param int $totalQuantity 합산 후 라인 수량
*
* @throws CartOperationException 상한 초과 시
*/
protected function validateCartQuantityLimit(int $totalQuantity): void
{
$max = (int) config('sirsoft-ecommerce.cart.max_quantity', 99);
if ($max > 0 && $totalQuantity > $max) {
throw new CartQuantityLimitException($max, $totalQuantity);
}
}
}
@@ -165,11 +165,17 @@ class CheckoutDataService
$itemSubtotals
);
// 마일리지 조회
// 마일리지 조회.
// 안내 기준 금액은 서버 검증(validateUsage)과 동일하게 "마일리지 차감 전 결제금액"이다.
// subtotal 로 안내하면 쿠폰·배송비 반영 후 실제 허용액보다 크게 안내되어
// "화면이 허용한 값인데 결제에서 422" 가 된다.
$paymentAmount = (int) ($calculationArray['summary']['payment_amount'] ?? $subtotal);
$mileageInfo = $this->userMileageService->getBalance($userId);
$mileageInfo['max_usable'] = $this->userMileageService->getMaxUsable($userId, $subtotal);
$mileageInfo['max_usable'] = $this->userMileageService->getMaxUsable($userId, $paymentAmount);
// 기본 통화 사용 규칙 미설정 시 사용 불가(M2) — 적립(enabled)과 분리된 "사용 가능" 플래그
$mileageInfo['usable'] = $this->userMileageService->isMileageUsable();
// 사용 정책(최소 사용액/사용 단위/정책상 최대) — 입력 UI 가 서버 판정과 같은 기준을 쓰도록 노출
$mileageInfo['usage_policy'] = $this->userMileageService->getUsagePolicy($paymentAmount);
return [
'available_coupons' => $availableCoupons,
@@ -15,6 +15,7 @@ use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
use Modules\Sirsoft\Ecommerce\Enums\RefundPriorityEnum;
use Modules\Sirsoft\Ecommerce\Models\Order;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\CouponIssueRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Support\VatCalculator;
/**
* 주문 변경 금액 계산 서비스
@@ -646,7 +647,8 @@ class OrderAdjustmentService
'total_deposit_used_amount' => 0,
'total_tax_amount' => $taxableAmount,
'total_tax_free_amount' => (float) $result->summary->taxFreeAmount,
'total_vat_amount' => $taxableAmount > 0 ? round($taxableAmount * 10 / 110) : 0,
// 재계산 결과의 옵션별 세율 반영 부가세를 그대로 사용 (주문 생성 시점과 동일 산식)
'total_vat_amount' => (float) ($result->summary->vatAmount ?? VatCalculator::fromTaxableAmount((int) $taxableAmount)),
'total_earned_points_amount' => (float) ($result->summary->pointsEarning ?? 0),
'item_count' => $itemCount,
];
@@ -791,6 +793,12 @@ class OrderAdjustmentService
'total_points_used_amount' => (float) $recalcResult->summary->pointsUsed,
'total_tax_amount' => (float) $recalcResult->summary->taxableAmount,
'total_tax_free_amount' => (float) $recalcResult->summary->taxFreeAmount,
// 과세표준을 갱신하면서 부가세를 그대로 두면 둘이 어긋나, 주문 화면의 공급가액
// (과세표준 - 부가세)이 음수까지 갈 수 있다. 같은 재계산 결과에서 함께 쓴다.
'total_vat_amount' => (float) (
$recalcResult->summary->vatAmount
?? VatCalculator::fromTaxableAmount((int) $recalcResult->summary->taxableAmount)
),
'promotions_applied_snapshot' => $promotionsSnapshot,
];
}
@@ -37,6 +37,7 @@ use Modules\Sirsoft\Ecommerce\Repositories\Contracts\CouponIssueRepositoryInterf
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductAdditionalOptionValueRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductOptionRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ShippingPolicyRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Support\VatCalculator;
/**
* 주문 계산 서비스
@@ -924,9 +925,18 @@ class OrderCalculationService
$isTaxable = $product->tax_status === ProductTaxStatus::TAXABLE;
// 세율은 상품별로 다를 수 있다. 스냅샷 모드에서는 주문 시점 세율이 그대로 쓰여
// 관리자가 이후 상품 세율을 바꿔도 기존 주문의 부가세가 소급 변경되지 않는다.
$taxRate = $isTaxable
? (float) ($product->tax_rate ?? VatCalculator::DEFAULT_RATE)
: null;
$taxableAmount = $isTaxable ? $amount : 0;
$classification[$optionId] = [
'taxable_amount' => $isTaxable ? $amount : 0,
'taxable_amount' => $taxableAmount,
'tax_free_amount' => $isTaxable ? 0 : $amount,
'tax_rate' => $taxRate,
'vat_amount' => VatCalculator::fromTaxableAmount((int) $taxableAmount, $taxRate),
];
}
@@ -1444,6 +1454,10 @@ class OrderCalculationService
$totalTaxFree += $tax['tax_free_amount'];
}
// 부가세는 옵션별 부가세의 합 — 세율이 섞인 주문에서는 이것만이 정확하다
// (전체 과세표준에 단일 세율을 적용하면 면세·영세·다른 세율 상품이 섞였을 때 어긋난다)
$totalVat = VatCalculator::sumFromClassification($taxClassification);
$summary = new Summary(
subtotal: $paymentCalculation['subtotal'],
productCouponDiscount: $paymentCalculation['coupon_discount'],
@@ -1456,6 +1470,7 @@ class OrderCalculationService
shippingDiscount: $paymentCalculation['shipping_discount'],
taxableAmount: $totalTaxable,
taxFreeAmount: $totalTaxFree,
vatAmount: $totalVat,
pointsEarning: $totalPointsEarning,
pointsUsed: $pointsUsageResult['actual_points'],
paymentAmount: $paymentCalculation['payment_amount'],
@@ -20,6 +20,7 @@ use Modules\Sirsoft\Ecommerce\Enums\PaymentStatusEnum;
use Modules\Sirsoft\Ecommerce\Enums\SequenceType;
use Modules\Sirsoft\Ecommerce\Enums\ShippingStatusEnum;
use Modules\Sirsoft\Ecommerce\Exceptions\CartUnavailableException;
use Modules\Sirsoft\Ecommerce\Exceptions\MileageValidationException;
use Modules\Sirsoft\Ecommerce\Exceptions\OrderAmountChangedException;
use Modules\Sirsoft\Ecommerce\Exceptions\OrderProcessingException;
use Modules\Sirsoft\Ecommerce\Exceptions\PaymentAmountMismatchException;
@@ -35,6 +36,7 @@ use Modules\Sirsoft\Ecommerce\Repositories\Contracts\OrderRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductOptionRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ShippingTypeRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Support\VatCalculator;
/**
* 주문 처리 서비스
@@ -124,6 +126,10 @@ class OrderProcessingService
// ⚠️ 프론트엔드 전달 금액과 서버 재계산 금액 검증
$this->validateOrderAmount($calculationResult, $expectedTotalAmount);
// 마일리지 사용 정책 최종 재검증 (임시주문 생성 이후의 설정 변경·임시주문 조작 차단).
// 임시주문 단계에서 이미 통과한 값이라도 결제 확정 직전 한 번 더 판정한다.
$this->validateMileageUsagePolicy($tempOrder, $calculationResult);
// 통화 스냅샷 생성
$currencySnapshot = $this->buildCurrencySnapshot();
@@ -529,6 +535,9 @@ class OrderProcessingService
'total_amount' => $summary->finalAmount ?? 0,
'total_tax_amount' => $summary->taxableAmount ?? 0,
'total_tax_free_amount' => $summary->taxFreeAmount ?? 0,
// 부가세는 주문 생성 시점에 기록한다. 기존에는 부분취소 재계산에서만 갱신되어
// 부분취소를 겪은 주문만 값이 정상화되고 나머지는 영구 0 이었다.
'total_vat_amount' => $this->resolveVatAmount($calculationResult),
'total_points_used_amount' => $summary->pointsUsed ?? 0,
'total_deposit_used_amount' => 0,
'total_paid_amount' => 0,
@@ -546,6 +555,11 @@ class OrderProcessingService
'ordered_at' => Carbon::now(),
'promotions_applied_snapshot' => $this->buildPromotionsAppliedSnapshot($calculationResult),
'shipping_policy_applied_snapshot' => $this->buildShippingPolicyAppliedSnapshot($calculationResult, $shippingInfo),
// 주문 시점 마일리지 사용 정책 고정 — 이후 관리자가 한도를 바꿔도 이 주문의 판정 근거는 불변
'mileage_policy_snapshot' => $this->userMileageService->buildUsagePolicySnapshot(
(int) ($summary->paymentAmount ?? 0),
(int) ($summary->pointsUsed ?? 0)
),
'order_meta' => $this->buildOrderMeta($tempOrder),
// 다중 통화 필드
'mc_subtotal_amount' => $mcAmounts['mc_subtotal_amount'],
@@ -878,9 +892,7 @@ class OrderProcessingService
// 결제 디바이스/UA 가 영구 NULL 로 남지 않는다. PG 결제 수단은 콜백이 더 정확한 값으로 덮어쓴다.
$userAgent = request()->userAgent() ?? '';
// 부가세(VAT): 과세표준(taxableAmount)에 내재된 부가세 = 과세표준 / 11 (공급가액의 10%).
$taxableAmount = (int) ($calculationResult->summary->taxableAmount ?? 0);
$vatAmount = $taxableAmount > 0 ? (int) round($taxableAmount / 11) : 0;
$vatAmount = $this->resolveVatAmount($calculationResult);
$paymentData = [
'payment_method' => $paymentMethod,
@@ -939,9 +951,11 @@ class OrderProcessingService
$paymentData['dbank_account'] = $dbankInfo['account_number'] ?? null;
$paymentData['dbank_holder'] = $dbankInfo['account_holder'] ?? null;
$paymentData['depositor_name'] = $depositorName ?? $dbankInfo['depositor_name'] ?? null;
// 주문별 명시 due_days(클라이언트 입력) 우선, 미지정 시 단일 SSoT auto_cancel_days
// 입금기한 단일 SSoT: auto_cancel_days (VBANK 와 동일 기준).
// 클라이언트가 보낸 due_days 는 무시한다 — 기한은 서버 정책이며, 이를 받아들이면
// 미입금 자동취소 스케줄러와 안내 기한이 어긋난다.
$paymentData['deposit_due_at'] = Carbon::now()->addDays(
$dbankInfo['due_days'] ?? module_setting('sirsoft-ecommerce', 'order_settings.auto_cancel_days', 3)
module_setting('sirsoft-ecommerce', 'order_settings.auto_cancel_days', 3)
);
}
@@ -1250,6 +1264,63 @@ class OrderProcessingService
return ! $this->orderRepository->hasOrderByUser($userId);
}
/**
* 주문/결제 레코드에 기록할 부가세를 결정합니다.
*
* 계산 단계에서 옵션별 세율로 산출한 합계를 그대로 사용합니다 — 여기서 다시 단일 세율로
* 계산하면 세율이 섞인 주문에서 주문과 결제 값이 어긋납니다.
*
* 다만 부가세 합산 도입 이전에 만들어진 임시주문이 도입 이후에 결제되면 합계가 비어 있어
* 부가세가 0 으로 굳습니다. 이 경우에 한해 과세표준에 기본 세율을 적용해 채웁니다
* (기존 주문 백필과 동일한 기준).
*
* @param OrderCalculationResult $calculationResult 주문 계산 결과
* @return int 부가세 금액
*/
protected function resolveVatAmount(OrderCalculationResult $calculationResult): int
{
$summary = $calculationResult->summary;
$vatAmount = (int) ($summary->vatAmount ?? 0);
if ($vatAmount > 0) {
return $vatAmount;
}
$taxableAmount = (int) ($summary->taxableAmount ?? 0);
return $taxableAmount > 0
? VatCalculator::fromTaxableAmount($taxableAmount, VatCalculator::DEFAULT_RATE)
: 0;
}
/**
* 마일리지 사용 정책을 주문 확정 직전에 재검증합니다.
*
* 임시주문 단계 검증 이후에 관리자가 한도 설정을 바꾸거나 임시주문이 조작된 경우를
* 차단하는 2차 방어선입니다. 판정 기준 금액은 마일리지 차감 전 결제금액입니다.
*
* @param TempOrder $tempOrder 임시 주문
* @param OrderCalculationResult $calculationResult 재계산 결과
*
* @throws MileageValidationException 정책 위반 시
*/
protected function validateMileageUsagePolicy(TempOrder $tempOrder, OrderCalculationResult $calculationResult): void
{
$userId = $tempOrder->user_id;
$usePoints = (int) $tempOrder->getUsedPoints();
// 비회원은 마일리지 사용 불가 (임시주문 단계에서 이미 0)
if ($userId === null || $usePoints <= 0) {
return;
}
$this->userMileageService->validateUsage(
$userId,
$usePoints,
(int) ($calculationResult->summary->paymentAmount ?? 0)
);
}
/**
* 임시 주문에서 계산 입력 DTO를 구성합니다.
*
@@ -10,6 +10,7 @@ use Illuminate\Support\Facades\DB;
use Modules\Sirsoft\Ecommerce\Enums\SequenceType;
use Modules\Sirsoft\Ecommerce\Exceptions\OptionHasOrderHistoryException;
use Modules\Sirsoft\Ecommerce\Exceptions\ProductHasOrderHistoryException;
use Modules\Sirsoft\Ecommerce\Exceptions\ProductPriceRelationException;
use Modules\Sirsoft\Ecommerce\Exceptions\StockMismatchException;
use Modules\Sirsoft\Ecommerce\Models\Product;
use Modules\Sirsoft\Ecommerce\Models\ProductAdditionalOption;
@@ -587,6 +588,7 @@ class ProductService
if (! empty($updateData)) {
$product = $this->repository->find($productId);
if ($product) {
$this->assertPriceRelation($product, $updateData);
$updateData['updated_by'] = Auth::id();
$this->repository->update($product, $updateData);
$productsUpdated++;
@@ -618,6 +620,54 @@ class ProductService
return $result;
}
/**
* 상품과 그 옵션의 활동 로그를 합쳐 조회합니다.
*
* @param Product $product 대상 상품
* @param array $filters 조회 필터 (per_page, sort_order)
* @return LengthAwarePaginator 활동 로그 페이지네이터
*/
public function getActivityLogs(Product $product, array $filters = []): LengthAwarePaginator
{
return $this->repository->getActivityLogsForProduct($product, $filters);
}
/**
* 실제로 적용될 가격 조합이 판매가 ≤ 정가를 지키는지 확인합니다.
*
* 일괄 수정은 정가/판매가 중 한쪽만 보내는 부분 전송이 흔해 FormRequest 는 두 값이 모두
* 전송된 경우에만 비교합니다. 한쪽만 온 경우 나머지 한쪽은 DB 에 남아 있던 값이 그대로
* 적용되므로, 단일 필드 전송으로 판매가를 정가 위로 올리는 우회로가 열립니다.
* 저장 직전에 DB 기존값과 합쳐 확정된 조합으로 다시 판정합니다.
*
* @param Product $product 대상 상품 (DB 기존값)
* @param array $updateData 적용될 수정 데이터
*
* @throws ProductPriceRelationException 판매가가 정가를 초과하는 경우
*/
protected function assertPriceRelation(Product $product, array $updateData): void
{
$incoming = static fn (string $key) => array_key_exists($key, $updateData)
&& $updateData[$key] !== null
&& $updateData[$key] !== '';
if (! $incoming('list_price') && ! $incoming('selling_price')) {
return;
}
$listPrice = $incoming('list_price')
? (float) $updateData['list_price']
: (float) $product->list_price;
$sellingPrice = $incoming('selling_price')
? (float) $updateData['selling_price']
: (float) $product->selling_price;
if ($sellingPrice > $listPrice) {
throw new ProductPriceRelationException((int) $product->id);
}
}
/**
* bulk_changes에 설정된 필드를 제외한 데이터 반환
*
@@ -12,6 +12,7 @@ use Modules\Sirsoft\Ecommerce\DTO\CalculationItem;
use Modules\Sirsoft\Ecommerce\DTO\OrderCalculationResult;
use Modules\Sirsoft\Ecommerce\DTO\ShippingAddress;
use Modules\Sirsoft\Ecommerce\Exceptions\CartEmptyException;
use Modules\Sirsoft\Ecommerce\Exceptions\CartOperationException;
use Modules\Sirsoft\Ecommerce\Exceptions\CartUnavailableException;
use Modules\Sirsoft\Ecommerce\Exceptions\MileageValidationException;
use Modules\Sirsoft\Ecommerce\Exceptions\TempOrderNotFoundException;
@@ -90,6 +91,10 @@ class TempOrderService
$calculationResult = $this->orderCalculationService->calculate($calculationInput);
// 마일리지 사용 정책(최소사용액/사용단위/최대한도) 최종 검증.
// 결제금액이 확정된 뒤라야 정률 한도를 판정할 수 있으므로 계산 직후에 둔다.
$this->assertPointsWithinUsagePolicy($userId, $validatedPoints, $calculationResult);
// 임시 주문 생성/수정
$tempOrder = DB::transaction(function () use (
$cartItems,
@@ -222,14 +227,14 @@ class TempOrderService
$matchedOption = $productOptions->firstWhere('id', (int) $requestedOptionId);
if (! $matchedOption) {
throw new \Exception(__('sirsoft-ecommerce::validation.cart.option_not_found'));
throw new CartOperationException('option_not_found');
}
$optionId = $matchedOption->id;
} else {
$defaultOption = $productOptions->first();
if (! $defaultOption) {
throw new \Exception(__('sirsoft-ecommerce::validation.cart.option_not_found'));
throw new CartOperationException('option_not_found');
}
$optionId = $defaultOption->id;
@@ -238,7 +243,7 @@ class TempOrderService
// product/images 관계를 포함해 옵션 재조회 (검증·계산에 필요)
$option = $this->productOptionRepository->findByIdsWithProduct([$optionId])->first();
if (! $option || ! $option->product) {
throw new \Exception(__('sirsoft-ecommerce::exceptions.option_not_found'));
throw new CartOperationException('option_not_found');
}
// 추가옵션 선택 검증·정규화 (담기와 동일 서버 SSoT — D9/D12)
@@ -361,6 +366,9 @@ class TempOrderService
$calculationResult = $this->orderCalculationService->calculate($calculationInput);
// 마일리지 사용 정책(최소사용액/사용단위/최대한도) 최종 검증 (생성 경로와 동일 기준)
$this->assertPointsWithinUsagePolicy($userId, $validatedPoints, $calculationResult);
// 검증된 프로모션 정보 구성 (프론트 필드명 그대로 저장)
$validatedPromotions = [
'item_coupons' => $validatedItemCoupons,
@@ -721,6 +729,37 @@ class TempOrderService
return $usePoints;
}
/**
* 마일리지 사용 정책 검증 (최소 사용액 / 사용 단위 / 최대 한도)
*
* validatePointsUsage() 는 계산 전 단계라 결제금액을 알 수 없어 잔액만 판정합니다.
* 정률 한도(max_use_percent)는 결제금액이 있어야 판정 가능하므로, 계산이 끝난
* 직후(영속화 전)에 이 검증을 수행합니다. 판정 기준 금액은 마일리지 차감 전
* 결제금액(summary.paymentAmount)입니다.
*
* @param int|null $userId 사용자 ID (비회원은 null)
* @param int $usePoints 사용 요청 마일리지
* @param OrderCalculationResult $calculationResult 주문 계산 결과
*
* @throws MileageValidationException 정책 위반 시
*/
protected function assertPointsWithinUsagePolicy(
?int $userId,
int $usePoints,
OrderCalculationResult $calculationResult
): void {
// 비회원은 validatePointsUsage 에서 이미 0 으로 정규화됨
if ($userId === null || $usePoints <= 0) {
return;
}
$this->userMileageService->validateUsage(
$userId,
$usePoints,
(int) ($calculationResult->summary->paymentAmount ?? 0)
);
}
/**
* 단일 쿠폰 소유권 검증
*
@@ -211,21 +211,90 @@ class UserMileageService
$cap = intdiv($cap, $unit) * $unit;
}
// 최소 사용 금액 미만이면 애초에 사용이 불가하므로 안내값도 0 이어야 한다.
// (안내값이 하한을 모르면 "화면이 허용한 값인데 결제에서 거부" 가 된다)
$minUse = (int) ($rule['min_use_amount'] ?? 0);
if ($cap < $minUse) {
return 0;
}
return max(0, $cap);
}
/**
* 마일리지 사용 정책(하한/단위/상한)을 반환합니다 (주문서 안내용).
*
* 검증(validateUsage)이 실제로 적용하는 값과 동일한 출처(통화 규칙)를 사용해,
* 화면 안내와 서버 판정이 어긋나지 않도록 합니다.
*
* @param int $paymentAmount 결제 금액 (정률 상한 계산 기준, 마일리지 차감 전)
* @param string|null $currency 통화 코드 (null 시 기본통화)
* @return array{min_use_amount: int, use_unit: int, max_use_amount: int} 사용 정책
*/
public function getUsagePolicy(int $paymentAmount, ?string $currency = null): array
{
if (! $this->isMileageUsable()) {
return ['min_use_amount' => 0, 'use_unit' => 1, 'max_use_amount' => 0];
}
$rule = $this->currencyRule($currency ?? $this->defaultCurrency());
return [
'min_use_amount' => (int) ($rule['min_use_amount'] ?? 0),
'use_unit' => max(1, (int) ($rule['use_unit'] ?? 1)),
'max_use_amount' => $this->resolveAllowedUseAmount($rule, $paymentAmount),
];
}
/**
* 주문 시점 마일리지 사용 정책 스냅샷을 생성합니다.
*
* 통화/프로모션/배송정책과 동일하게, 주문을 지배한 정책을 주문 행에 고정합니다.
* 관리자가 이후 한도를 바꿔도 그 주문이 어떤 정책 아래 성립했는지 재현 가능해야
* 합니다(정산·감사·분쟁 대응). 사용액 자체는 원장(MileageTransaction)이 SSoT 이며,
* 이 스냅샷은 판정 근거를 보존하는 용도입니다.
*
* @param int $paymentAmount 판정 기준 결제금액 (마일리지 차감 전)
* @param int $usedPoints 실제 사용된 마일리지
* @param string|null $currency 정산 통화 (null 시 기본통화)
* @return array 사용 정책 스냅샷
*/
public function buildUsagePolicySnapshot(int $paymentAmount, int $usedPoints, ?string $currency = null): array
{
$currency = $currency ?? $this->defaultCurrency();
$usable = $this->isMileageUsable();
$rule = $usable ? $this->currencyRule($currency) : [];
return [
'usable' => $usable,
'currency' => $currency,
'rule' => [
'point_value' => (float) ($rule['point_value'] ?? 1),
'min_use_amount' => (int) ($rule['min_use_amount'] ?? 0),
'use_unit' => max(1, (int) ($rule['use_unit'] ?? 1)),
'max_use_type' => (string) ($rule['max_use_type'] ?? 'percent'),
'max_use_percent' => (float) ($rule['max_use_percent'] ?? 100),
'max_use_value' => (int) ($rule['max_use_value'] ?? 0),
],
// 판정 근거 — 이 결제금액에 이 정책을 적용해 아래 상한이 나왔고, 그 안에서 사용됐다.
'payment_amount_basis' => $paymentAmount,
'max_use_amount' => $usable ? $this->resolveAllowedUseAmount($rule, $paymentAmount) : 0,
'used_points' => $usedPoints,
];
}
/**
* 마일리지 사용 검증 (min/use_unit/max/잔액) → 보정값 반환 또는 예외
*
* @param int $userId 사용자 ID
* @param int $usePoints 사용 요청 마일리지
* @param int $paymentAmount 결제 금액
* @param string $currency 통화 코드
* @param int $paymentAmount 결제 금액 (마일리지 차감 전)
* @param string|null $currency 통화 코드 (null 시 기본통화 — canUse/getMaxUsable 과 동일 기준)
* @return int 검증/보정된 사용 마일리지
*
* @throws MileageValidationException 검증 실패 시
*/
public function validateUsage(int $userId, int $usePoints, int $paymentAmount, string $currency): int
public function validateUsage(int $userId, int $usePoints, int $paymentAmount, ?string $currency = null): int
{
if ($usePoints <= 0) {
return 0;
@@ -238,6 +307,7 @@ class UserMileageService
);
}
$currency = $currency ?? $this->defaultCurrency();
$rule = $this->currencyRule($currency);
$minUse = (int) ($rule['min_use_amount'] ?? 0);
@@ -256,8 +326,12 @@ class UserMileageService
$maxByLimit = $this->resolveMaxUseLimit($rule, $paymentAmount);
if ($usePoints > $maxByLimit || $usePoints > $paymentAmount) {
// 사용 가능한 최대 금액을 함께 안내 — 얼마로 줄여야 결제되는지 알 수 없으면
// 사용자는 값을 낮춰가며 재시도할 수밖에 없다.
throw new MileageValidationException(
__('sirsoft-ecommerce::exceptions.mileage.exceeds_max_use')
__('sirsoft-ecommerce::exceptions.mileage.exceeds_max_use', [
'amount' => $this->resolveAllowedUseAmount($rule, $paymentAmount),
])
);
}
@@ -971,6 +1045,27 @@ class UserMileageService
return (int) ($rule['max_use_value'] ?? PHP_INT_MAX);
}
/**
* 실제로 사용 가능한 최대 금액을 계산합니다 (한도 · 결제금액 · 사용단위 반영).
*
* 잔액은 반영하지 않습니다 — 정책상 허용 한도이며, 잔액 부족은 별도 사유로 구분됩니다.
*
* @param array $rule 통화 규칙
* @param int $paymentAmount 결제 금액 (마일리지 차감 전)
* @return int 정책상 사용 가능한 최대 금액
*/
private function resolveAllowedUseAmount(array $rule, int $paymentAmount): int
{
$allowed = min($this->resolveMaxUseLimit($rule, $paymentAmount), $paymentAmount);
$unit = (int) ($rule['use_unit'] ?? 1);
if ($unit > 1) {
$allowed = intdiv($allowed, $unit) * $unit;
}
return max(0, $allowed);
}
/**
* 통화 규칙을 조회합니다.
*
@@ -0,0 +1,67 @@
<?php
namespace Modules\Sirsoft\Ecommerce\Support;
/**
* 부가세(VAT) 계산 헬퍼
*
* G7 의 상품 가격은 **부가세 포함가**다. 따라서 과세표준에 내재된 부가세는
* `과세표준 × 세율 / (100 + 세율)` 로 산출한다 (세율 10% 기준 `과세표준 / 11` 과 동일).
*
* 기존 코드에 `× 10/110` 과 `/ 11` 두 표기가 섞여 있었는데 수학적으로 같은 식이므로
* 이 헬퍼로 단일화한다.
*/
class VatCalculator
{
/**
* 기본 부가세율 (%) — 상품에 세율이 지정되지 않은 경우의 폴백.
*/
public const DEFAULT_RATE = 10.0;
/**
* 과세표준에 내재된 부가세를 산출합니다.
*
* @param int $taxableAmount 과세표준 (부가세 포함 금액)
* @param float|null $rate 부가세율 (%). null 이면 기본 세율
* @return int 부가세 (원 단위 반올림)
*/
public static function fromTaxableAmount(int $taxableAmount, ?float $rate = null): int
{
$rate = $rate ?? self::DEFAULT_RATE;
if ($taxableAmount <= 0 || $rate <= 0) {
return 0;
}
return (int) round($taxableAmount * $rate / (100 + $rate));
}
/**
* 옵션별 과세 분류 결과에서 부가세 합계를 산출합니다.
*
* 세율이 섞인 주문에서는 **옵션별 부가세의 합**만이 정확합니다. 전체 과세표준에
* 단일 세율을 적용하면 세율이 다른 상품이 섞였을 때 값이 어긋납니다.
*
* @param array<int|string, array{taxable_amount?: int, tax_rate?: float|null, vat_amount?: int}> $taxClassification 옵션별 과세 분류
* @return int 부가세 합계
*/
public static function sumFromClassification(array $taxClassification): int
{
$total = 0;
foreach ($taxClassification as $tax) {
if (isset($tax['vat_amount'])) {
$total += (int) $tax['vat_amount'];
continue;
}
$total += self::fromTaxableAmount(
(int) ($tax['taxable_amount'] ?? 0),
$tax['tax_rate'] ?? null
);
}
return $total;
}
}
@@ -13,7 +13,7 @@ return [
'deduct_exceeds_balance' => 'The mileage to deduct exceeds the available balance.',
'below_min_use_amount' => 'The minimum usable amount is :amount points.',
'invalid_use_unit' => 'Mileage can only be used in units of :unit points.',
'exceeds_max_use' => 'Exceeds the maximum usable limit.',
'exceeds_max_use' => 'Exceeds the maximum usable limit. (up to :amount points)',
'base_currency_rule_missing' => 'Mileage cannot be used because the mileage usage unit for the base currency is not configured.',
],
@@ -38,6 +38,7 @@ return [
// List query common validation messages
'list' => [
'per_page_max' => 'You can retrieve up to :max items at a time.',
// Pagination
'page' => [
'integer' => 'Page number must be an integer.',
@@ -243,6 +244,9 @@ return [
// Product validation messages
'product' => [
'mileage_percent_max' => 'The percentage earn rate cannot exceed 100%.',
'selling_price_lte_list' => 'The selling price cannot be greater than the list price.',
'price_min' => 'The price must be greater than 0.',
// Human-readable field names shown in error messages (StoreProductRequest::attributes())
'attributes' => [
'name' => 'product name',
@@ -937,6 +941,7 @@ return [
// Cart validation messages
'cart' => [
'quantity_limit_exceeded' => 'You can add up to :limit item(s) per product to the cart. (requested: :attempted)',
'ids_required' => 'Please select items to delete.',
'ids_array' => 'Item IDs must be an array.',
'ids_min' => 'Please select at least one item.',
@@ -947,7 +952,7 @@ return [
'option_not_found' => 'Option not found.',
'quantity_required' => 'Please enter a quantity.',
'quantity_min' => 'Quantity must be at least 1.',
'quantity_max' => 'Quantity cannot exceed 9,999.',
'quantity_max' => 'Quantity cannot exceed :max.',
'items_required' => 'Please select items to add to cart.',
'items_min' => 'Please select at least one item.',
'selected_ids_array' => 'Selected cart item IDs must be an array.',
@@ -13,7 +13,7 @@ return [
'deduct_exceeds_balance' => '차감하려는 마일리지가 잔액을 초과합니다.',
'below_min_use_amount' => '최소 사용 금액은 :amount점입니다.',
'invalid_use_unit' => '마일리지는 :unit점 단위로 사용할 수 있습니다.',
'exceeds_max_use' => '최대 사용 한도를 초과했습니다.',
'exceeds_max_use' => '최대 사용 한도를 초과했습니다. (사용 가능 최대 :amount점)',
'base_currency_rule_missing' => '기본 통화에 대한 마일리지 사용 단위가 설정되지 않아 마일리지를 사용할 수 없습니다.',
],
@@ -38,6 +38,7 @@ return [
// 목록 조회 공통 검증 메시지
'list' => [
'per_page_max' => '한 번에 조회할 수 있는 최대 개수는 :max개입니다.',
// 페이지네이션
'page' => [
'integer' => '페이지 번호는 숫자여야 합니다.',
@@ -243,6 +244,9 @@ return [
// 상품 검증 메시지
'product' => [
'mileage_percent_max' => '정률 적립률은 100% 를 초과할 수 없습니다.',
'selling_price_lte_list' => '판매가는 정가보다 클 수 없습니다.',
'price_min' => '가격은 0보다 커야 합니다.',
// 에러 메시지에 노출되는 한글 필드명 (StoreProductRequest::attributes())
'attributes' => [
'name' => '상품명',
@@ -937,6 +941,7 @@ return [
// 장바구니 검증 메시지
'cart' => [
'quantity_limit_exceeded' => '장바구니에는 상품당 최대 :limit개까지 담을 수 있습니다. (요청: :attempted개)',
'ids_required' => '삭제할 상품을 선택해주세요.',
'ids_array' => '상품 ID는 배열 형태여야 합니다.',
'ids_min' => '최소 1개 이상의 상품을 선택해주세요.',
@@ -947,7 +952,7 @@ return [
'option_not_found' => '존재하지 않는 옵션입니다.',
'quantity_required' => '수량을 입력해주세요.',
'quantity_min' => '수량은 1개 이상이어야 합니다.',
'quantity_max' => '수량은 최대 9,999개까지 가능합니다.',
'quantity_max' => '수량은 최대 :max개까지 가능합니다.',
'items_required' => '장바구니에 담을 상품을 선택해주세요.',
'items_min' => '최소 1개 이상의 상품을 선택해주세요.',
'selected_ids_array' => '선택된 장바구니 상품 ID는 배열 형태여야 합니다.',
@@ -0,0 +1,564 @@
<?php
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Cart;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Modules\Sirsoft\Ecommerce\Database\Factories\CartFactory;
use Modules\Sirsoft\Ecommerce\Database\Factories\OrderFactory;
use Modules\Sirsoft\Ecommerce\Database\Factories\OrderOptionFactory;
use Modules\Sirsoft\Ecommerce\Database\Factories\ProductFactory;
use Modules\Sirsoft\Ecommerce\Database\Factories\ProductOptionFactory;
use Modules\Sirsoft\Ecommerce\Exceptions\CartQuantityLimitException;
use Modules\Sirsoft\Ecommerce\Exceptions\CartUnavailableException;
use Modules\Sirsoft\Ecommerce\Models\Cart;
use Modules\Sirsoft\Ecommerce\Models\Order;
use Modules\Sirsoft\Ecommerce\Models\ProductOption;
use Modules\Sirsoft\Ecommerce\Services\CartService;
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
/**
* 장바구니 수량 상한 · 구매수량 한도 테스트 (E7 · E8)
*
* - E7: `config('sirsoft-ecommerce.cart.max_quantity')`(99)가 죽어 있고 Request 3종이 9999 를
* 하드코딩했다. 누적 합산 경로에는 상한 자체가 없었다.
* - E8: 상품 구매수량 한도(`max_purchase_qty`)가 수량 변경 경로에서만 검사되고
* 담기·옵션변경·비회원 병합 경로에서는 검사되지 않았다.
*/
class CartQuantityAndPurchaseLimitTest extends ModuleTestCase
{
/**
* 판매중 상품 옵션을 만듭니다.
*
* @param int $maxPurchaseQty 구매수량 한도 (0 = 무제한)
* @param int $stock 재고
* @return ProductOption 생성된 옵션
*/
private function makeOption(int $maxPurchaseQty = 0, int $stock = 1000): ProductOption
{
$product = ProductFactory::new()->create([
'shipping_policy_id' => null,
'list_price' => 10000,
'selling_price' => 10000,
'max_purchase_qty' => $maxPurchaseQty,
'stock_quantity' => $stock,
]);
return ProductOptionFactory::new()->forProduct($product)->create([
'selling_price' => 10000,
'price_adjustment' => 0,
'stock_quantity' => $stock,
]);
}
// ========================================
// E7 — 장바구니 수량 상한
// ========================================
/**
* 설정 상한을 넘는 담기는 차단되는지 테스트합니다.
*/
public function test_add_over_cart_quantity_limit_is_blocked(): void
{
config(['sirsoft-ecommerce.cart.max_quantity' => 99]);
$user = $this->createUser();
$option = $this->makeOption();
$this->expectException(CartQuantityLimitException::class);
app(CartService::class)->bulkAddToCart([
'user_id' => $user->id,
'product_id' => $option->product_id,
'items' => [
['product_option_id' => $option->id, 'quantity' => 100],
],
]);
}
/**
* 기존 수량과 합산해 상한을 넘으면 차단되는지 테스트합니다.
*
* 필드 규칙(`max:`)은 이번 요청분만 보므로 누적 경로는 서버가 따로 판정해야 한다.
*/
public function test_accumulated_quantity_over_limit_is_blocked(): void
{
config(['sirsoft-ecommerce.cart.max_quantity' => 99]);
$user = $this->createUser();
$option = $this->makeOption();
CartFactory::new()->forUser($user)->forOption($option)->create(['quantity' => 90]);
$this->expectException(CartQuantityLimitException::class);
app(CartService::class)->bulkAddToCart([
'user_id' => $user->id,
'product_id' => $option->product_id,
'items' => [
['product_option_id' => $option->id, 'quantity' => 20],
],
]);
}
/**
* 상한과 정확히 같은 합산 수량은 통과하는지 테스트합니다 (경계).
*/
public function test_accumulated_quantity_at_limit_passes(): void
{
config(['sirsoft-ecommerce.cart.max_quantity' => 99]);
$user = $this->createUser();
$option = $this->makeOption();
CartFactory::new()->forUser($user)->forOption($option)->create(['quantity' => 90]);
app(CartService::class)->bulkAddToCart([
'user_id' => $user->id,
'product_id' => $option->product_id,
'items' => [
['product_option_id' => $option->id, 'quantity' => 9],
],
]);
$this->assertSame(99, (int) Cart::where('user_id', $user->id)->sum('quantity'));
}
// ========================================
// E8 — 구매수량 한도
// ========================================
/**
* 담기 경로에서 구매수량 한도가 강제되는지 테스트합니다.
*/
public function test_add_to_cart_enforces_purchase_quantity_limit(): void
{
config(['sirsoft-ecommerce.cart.max_quantity' => 99]);
$user = $this->createUser();
$option = $this->makeOption(maxPurchaseQty: 5);
$this->expectException(CartUnavailableException::class);
app(CartService::class)->bulkAddToCart([
'user_id' => $user->id,
'product_id' => $option->product_id,
'items' => [
['product_option_id' => $option->id, 'quantity' => 8],
],
]);
}
/**
* 옵션 변경 경로에서 구매수량 한도가 강제되는지 테스트합니다.
*
* @scenario entry=change_option
*
* @effects change_option_blocks_above_max_qty
*/
public function test_change_option_enforces_purchase_quantity_limit(): void
{
config(['sirsoft-ecommerce.cart.max_quantity' => 99]);
$user = $this->createUser();
$option = $this->makeOption(maxPurchaseQty: 5);
$other = ProductOptionFactory::new()
->forProduct($option->product)
->create(['selling_price' => 10000, 'price_adjustment' => 0, 'stock_quantity' => 1000]);
$cart = CartFactory::new()->forUser($user)->forOption($option)->create(['quantity' => 1]);
$this->expectException(CartUnavailableException::class);
app(CartService::class)->changeOption($cart->id, $other->id, 8, $user->id, null);
}
/**
* 한도 이내 옵션 변경은 통과하는지 테스트합니다.
*/
public function test_change_option_within_limit_passes(): void
{
config(['sirsoft-ecommerce.cart.max_quantity' => 99]);
$user = $this->createUser();
$option = $this->makeOption(maxPurchaseQty: 5);
$other = ProductOptionFactory::new()
->forProduct($option->product)
->create(['selling_price' => 10000, 'price_adjustment' => 0, 'stock_quantity' => 1000]);
$cart = CartFactory::new()->forUser($user)->forOption($option)->create(['quantity' => 1]);
$updated = app(CartService::class)->changeOption($cart->id, $other->id, 5, $user->id, null);
$this->assertSame(5, $updated->quantity);
}
/**
* 수량 상한 초과 안내 문구가 실제 상한값을 말하는지 테스트합니다.
*
* 규칙은 `config('sirsoft-ecommerce.cart.max_quantity')` 를 읽는데 안내 문구가 다른 숫자를
* 고정하고 있으면, 사용자는 "최대 N개까지 가능" 이라는 안내를 보면서 그보다 적은 수량에서
* 차단당한다 — 차단 사유와 안내가 서로 다른 말을 하는 상태다.
*/
public function test_quantity_limit_message_states_the_configured_limit(): void
{
config(['sirsoft-ecommerce.cart.max_quantity' => 99]);
$user = $this->createUser();
$option = $this->makeOption();
$cart = CartFactory::new()->forOption($option)->create([
'user_id' => $user->id,
'quantity' => 1,
]);
$response = $this->actingAs($user, 'sanctum')
->patchJson("/api/modules/sirsoft-ecommerce/cart/{$cart->id}/quantity", ['quantity' => 100])
->assertStatus(422);
$message = json_encode($response->json('errors'), JSON_UNESCAPED_UNICODE);
$this->assertStringContainsString('99', $message, '안내 문구가 설정 상한을 말하지 않습니다.');
$this->assertStringNotContainsString(
'9,999',
$message,
'안내 문구가 실제 상한(99)이 아닌 옛 하드코딩 값(9,999)을 말하고 있습니다.'
);
}
/**
* 비회원 병합은 예외 대신 상한까지 클램프하고 조정 내역을 남기는지 테스트합니다.
*
* 로그인 시 자동 병합이라 예외를 던지면 로그인 자체가 실패한다.
*/
public function test_guest_merge_clamps_instead_of_throwing(): void
{
config(['sirsoft-ecommerce.cart.max_quantity' => 5]);
$user = User::factory()->create();
$option = $this->makeOption();
$cartKey = 'ck_'.str_repeat('m', 32);
CartFactory::new()->forOption($option)->create([
'user_id' => null,
'cart_key' => $cartKey,
'quantity' => 10,
]);
$service = app(CartService::class);
$merged = $service->mergeGuestCartToUser($cartKey, $user->id);
$this->assertSame(1, $merged);
// 조용한 클램프 금지 — 조정 내역이 반환되어야 한다
$adjustments = $service->getLastMergeAdjustments();
$this->assertCount(1, $adjustments);
$this->assertSame(10, $adjustments[0]['requested']);
$this->assertSame(5, $adjustments[0]['applied']);
}
/**
* 병합 응답이 조정 내역을 실제로 사용자에게 전달하는지 테스트합니다.
*
* 서비스가 내역을 들고 있어도 응답에 실리지 않으면 사용자 관점에서는 여전히 조용한
* 클램프다 — 계약의 양 끝을 모두 고정한다.
*
* @scenario entry=guest_merge
*
* @effects guest_merge_reports_clamp_adjustments
*/
public function test_merge_endpoint_exposes_clamp_adjustments(): void
{
config(['sirsoft-ecommerce.cart.max_quantity' => 5]);
$user = $this->createUser();
$option = $this->makeOption();
$cartKey = 'ck_'.str_repeat('n', 32);
CartFactory::new()->forOption($option)->create([
'user_id' => null,
'cart_key' => $cartKey,
'quantity' => 10,
]);
$response = $this->actingAs($user, 'sanctum')
->withHeaders(['X-Cart-Key' => $cartKey])
->postJson('/api/modules/sirsoft-ecommerce/cart/merge')
->assertStatus(200);
$adjustments = $response->json('data.adjustments');
$this->assertIsArray($adjustments, '병합 응답에 조정 내역이 없습니다 — 사용자는 수량이 줄어든 것을 알 수 없습니다.');
$this->assertCount(1, $adjustments);
$this->assertSame(10, $adjustments[0]['requested']);
$this->assertSame(5, $adjustments[0]['applied']);
}
/**
* 비회원 병합이 상품별 구매수량 한도까지 클램프하는지 테스트합니다.
*
* 병합은 장바구니 전역 상한(`cart.max_quantity`)만 보고 상품 정책(`max_purchase_qty`)을
* 보지 않으면, 한도 5짜리 상품을 비회원으로 10개 담고 로그인하는 것만으로 한도를
* 통과시킬 수 있다 — 담기·수량변경·옵션변경 경로를 모두 막아도 남는 우회로다.
*
* @scenario entry=guest_merge
*
* @effects guest_merge_clamps_to_product_limit
*/
public function test_guest_merge_clamps_to_product_purchase_limit(): void
{
// 전역 상한은 넉넉히 — 상품 한도만으로 클램프되어야 한다
config(['sirsoft-ecommerce.cart.max_quantity' => 99]);
$user = User::factory()->create();
$option = $this->makeOption(maxPurchaseQty: 5);
$cartKey = 'ck_'.str_repeat('p', 32);
CartFactory::new()->forOption($option)->create([
'user_id' => null,
'cart_key' => $cartKey,
'quantity' => 10,
]);
$service = app(CartService::class);
$service->mergeGuestCartToUser($cartKey, $user->id);
$merged = Cart::where('user_id', $user->id)->first();
$this->assertNotNull($merged);
$this->assertSame(
5,
(int) $merged->quantity,
'병합이 상품 구매수량 한도를 넘겼습니다 — 비회원으로 담고 로그인하면 한도가 무력화됩니다.'
);
$adjustments = $service->getLastMergeAdjustments();
$this->assertCount(1, $adjustments);
$this->assertSame(10, $adjustments[0]['requested']);
$this->assertSame(5, $adjustments[0]['applied']);
}
/**
* 병합의 한도 판정이 같은 상품의 기존 회원 장바구니 수량까지 합산하는지 테스트합니다.
*
* 담기 경로는 옵션을 나눠 담는 우회를 막으려고 상품 총수량으로 판정한다. 병합만 라인
* 단위로 판정하면 "회원 장바구니에 4개 + 비회원 장바구니에 다른 옵션 4개" 로 한도 5를
* 넘길 수 있다.
*
* @scenario entry=guest_merge
*
* @effects guest_merge_limit_counts_existing_lines
*/
public function test_guest_merge_limit_counts_existing_member_cart_lines(): void
{
config(['sirsoft-ecommerce.cart.max_quantity' => 99]);
$user = User::factory()->create();
$optionA = $this->makeOption(maxPurchaseQty: 5);
$optionB = ProductOptionFactory::new()->forProduct($optionA->product)->create([
'selling_price' => 10000,
'price_adjustment' => 0,
'stock_quantity' => 1000,
]);
$cartKey = 'ck_'.str_repeat('q', 32);
CartFactory::new()->forOption($optionA)->create([
'user_id' => $user->id,
'cart_key' => 'ck_'.str_repeat('r', 32),
'quantity' => 4,
]);
CartFactory::new()->forOption($optionB)->create([
'user_id' => null,
'cart_key' => $cartKey,
'quantity' => 4,
]);
$service = app(CartService::class);
$service->mergeGuestCartToUser($cartKey, $user->id);
$total = (int) Cart::where('user_id', $user->id)
->where('product_id', $optionA->product_id)
->sum('quantity');
$this->assertSame(
5,
$total,
'옵션을 나눠 담으면 병합에서 상품 한도를 넘길 수 있습니다.'
);
}
/**
* 재주문에서 구매수량 한도를 넘는 항목이 사유와 함께 제외되는지 테스트합니다.
*
* 재주문은 여러 항목을 한 번에 담는 조작이라, 한 항목 때문에 전체를 실패시키면 나머지
* 정상 항목까지 담기지 않는다. 품절·단종과 동일하게 항목 단위로 제외하고 사유를
* 돌려주되, 한도를 넘긴 수량이 장바구니에 들어가서는 안 된다.
*
* @scenario entry=reorder
*
* @effects reorder_skips_items_over_limit_with_reason
*/
public function test_reorder_skips_items_over_purchase_limit_with_reason(): void
{
config(['sirsoft-ecommerce.cart.max_quantity' => 99]);
$user = $this->createUser();
$option = $this->makeOption(maxPurchaseQty: 5);
$order = OrderFactory::new()->create(['user_id' => $user->id]);
OrderOptionFactory::new()->forOrder($order)->create([
'product_id' => $option->product_id,
'product_option_id' => $option->id,
'parent_option_id' => null,
'quantity' => 8,
]);
$result = app(CartService::class)->reorderFromOrder($order->id, $user->id);
$this->assertSame(0, $result['added_count']);
$this->assertCount(1, $result['skipped']);
$this->assertNotSame('', (string) $result['skipped'][0]['reason'], '제외 사유가 비어 있으면 사용자가 이유를 알 수 없습니다.');
$this->assertSame(0, Cart::where('user_id', $user->id)->count(), '한도를 넘는 수량이 장바구니에 들어갔습니다.');
}
/**
* 실제 로그인 경로에서 한도 초과 비회원 장바구니가 로그인을 깨뜨리지 않는지 테스트합니다.
*
* 병합이 클램프를 택한 유일한 근거가 "로그인 시 자동 병합이라 예외를 던지면 로그인 자체가
* 실패한다" 였다. 그 근거를 서비스 직접 호출로만 검증하면 실제 로그인 왕복은 무가드다.
*
* 동시에 병합이 **실제로 일어났는지**까지 단언한다. 로그인이 200 이어도 장바구니가
* 넘어오지 않으면 사용자는 담아둔 것을 잃은 채 로그인만 된다 — 조용한 소실이다.
*
* @scenario entry=guest_merge
*
* @effects guest_merge_clamps_to_product_limit
*/
public function test_login_with_over_limit_guest_cart_succeeds_and_merges_clamped(): void
{
config(['sirsoft-ecommerce.cart.max_quantity' => 99]);
$user = User::factory()->create([
'email' => 'merge-on-login@example.com',
'password' => Hash::make('correct-password'),
'status' => 'active',
]);
$option = $this->makeOption(maxPurchaseQty: 5);
$cartKey = 'ck_'.str_repeat('s', 32);
CartFactory::new()->forOption($option)->create([
'user_id' => null,
'cart_key' => $cartKey,
'quantity' => 10,
]);
$this->withHeaders(['X-Cart-Key' => $cartKey])
->postJson('/api/auth/login', [
'email' => 'merge-on-login@example.com',
'password' => 'correct-password',
])
->assertStatus(200);
$merged = Cart::where('user_id', $user->id)->first();
$this->assertNotNull(
$merged,
'로그인은 성공했으나 비회원 장바구니가 회원 계정으로 넘어오지 않았습니다 — 담아둔 항목이 조용히 사라집니다.'
);
$this->assertSame(
5,
(int) $merged->quantity,
'병합이 상품 구매수량 한도를 넘겼습니다.'
);
$this->assertSame(0, Cart::whereNull('user_id')->where('cart_key', $cartKey)->count());
}
/**
* 한도 이내 항목은 재주문으로 정상 담기는지 테스트합니다 (제외 로직이 과잉 차단하지 않음).
*/
public function test_reorder_adds_items_within_purchase_limit(): void
{
config(['sirsoft-ecommerce.cart.max_quantity' => 99]);
$user = $this->createUser();
$option = $this->makeOption(maxPurchaseQty: 5);
$order = OrderFactory::new()->create(['user_id' => $user->id]);
OrderOptionFactory::new()->forOrder($order)->create([
'product_id' => $option->product_id,
'product_option_id' => $option->id,
'parent_option_id' => null,
'quantity' => 3,
]);
$result = app(CartService::class)->reorderFromOrder($order->id, $user->id);
$this->assertSame(1, $result['added_count']);
$this->assertSame([], $result['skipped']);
$this->assertSame(3, (int) Cart::where('user_id', $user->id)->sum('quantity'));
}
/**
* 무통장 입금기한이 클라이언트 입력이 아니라 서버 설정을 따르는지 테스트합니다 (E6).
*
* 수정 전: `dbank.due_days` 를 클라이언트가 보내면 그대로 반영되어 자동취소 스케줄러와
* 안내 기한이 어긋났다. VBANK 는 이미 서버 설정 단일 SSoT 였다.
*/
public function test_dbank_due_date_uses_server_setting_not_client_input(): void
{
config(['sirsoft-ecommerce.cart.max_quantity' => 99]);
$settingsDir = storage_path('framework/testing/modules/sirsoft-ecommerce/settings');
if (! is_dir($settingsDir)) {
mkdir($settingsDir, 0755, true);
}
file_put_contents($settingsDir.'/order_settings.json', json_encode(['auto_cancel_days' => 1]));
try {
$option = $this->makeOption();
$user = $this->createUser();
$cart = CartFactory::new()->forUser($user)->forOption($option)->create(['quantity' => 1]);
$this->actingAs($user, 'sanctum')
->postJson('/api/modules/sirsoft-ecommerce/checkout', ['item_ids' => [$cart->id]])
->assertStatus(201);
$this->actingAs($user, 'sanctum')->postJson(
'/api/modules/sirsoft-ecommerce/user/orders',
[
'orderer' => ['name' => '홍길동', 'phone' => '010-1234-5678', 'email' => 'dbank@test.com'],
'shipping' => [
'recipient_name' => '김철수',
'recipient_phone' => '010-9876-5432',
'country_code' => 'KR',
'zipcode' => '12345',
'address' => '서울시 강남구 테헤란로 123',
'address_detail' => '101동 1001호',
],
'payment_method' => 'dbank',
'expected_total_amount' => 10000,
'depositor_name' => '홍길동',
'dbank' => [
'bank_code' => 'KB',
'bank_name' => '국민은행',
'account_number' => '123-456-789012',
'account_holder' => '주식회사 테스트',
// 클라이언트가 30일을 보내도 서버 설정(1일)이 이겨야 한다
'due_days' => 30,
],
]
)->assertStatus(201);
$order = Order::where('user_id', $user->id)->latest('id')->first();
$dueAt = $order->payment->deposit_due_at;
$this->assertNotNull($dueAt);
$this->assertSame(1, (int) round(now()->diffInDays($dueAt, false)));
} finally {
$path = $settingsDir.'/order_settings.json';
if (file_exists($path)) {
unlink($path);
}
}
}
}
@@ -296,4 +296,21 @@ class ProductControllerCopyTest extends ModuleTestCase
$this->assertArrayNotHasKey('created_at', $response->json('data'));
$this->assertArrayNotHasKey('updated_at', $response->json('data'));
}
/**
* 불리언이 아닌 복사 플래그는 거절된다
*
* 이전에는 검증 없이 boolean() 캐스팅만 해서, 오타나 잘못된 값이 조용히 false 로 해석돼
* "복사했는데 특정 항목만 빠져 있다" 는 결과가 나왔다.
*/
public function test_show_for_copy_rejects_non_boolean_flag(): void
{
$user = $this->createAdminUser(['sirsoft-ecommerce.products.read']);
$product = Product::factory()->create();
$this->actingAs($user)
->getJson("/api/modules/sirsoft-ecommerce/admin/products/{$product->id}/copy?copy_images=maybe")
->assertStatus(422)
->assertJsonValidationErrors(['copy_images']);
}
}
@@ -0,0 +1,72 @@
<?php
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Http\Controllers\Admin;
use Modules\Sirsoft\Ecommerce\Models\Product;
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
/**
* 상품 활동 로그 조회 엔드포인트 테스트
*
* 조회 조건(페이지 크기·정렬)이 FormRequest 에서 검증되는지, 로그 합산 조회가 Repository
* 위임으로 정상 동작하는지 확인합니다. 이전에는 컨트롤러가 요청 값을 검증 없이 그대로 쿼리에
* 넘겨 `per_page=99999` 같은 값으로 한 번에 전량을 끌어올 수 있었습니다.
*/
class ProductLogsControllerTest extends ModuleTestCase
{
/**
* 로그 조회 URL 을 만듭니다.
*
* @param Product $product 대상 상품
* @param string $query 쿼리스트링 (물음표 제외)
* @return string 엔드포인트 URL
*/
private function url(Product $product, string $query = ''): string
{
$url = "/api/modules/sirsoft-ecommerce/admin/products/{$product->id}/logs";
return $query === '' ? $url : "{$url}?{$query}";
}
/**
* 기본 조회가 정상 응답한다
*/
public function test_logs_returns_paginated_response(): void
{
$user = $this->createAdminUser(['sirsoft-ecommerce.products.read']);
$product = Product::factory()->create();
$this->actingAs($user)
->getJson($this->url($product))
->assertOk()
->assertJsonStructure(['data' => ['data', 'meta']]);
}
/**
* 상한을 넘는 per_page 는 거절된다
*/
public function test_logs_rejects_per_page_over_limit(): void
{
$user = $this->createAdminUser(['sirsoft-ecommerce.products.read']);
$product = Product::factory()->create();
$this->actingAs($user)
->getJson($this->url($product, 'per_page=99999'))
->assertStatus(422)
->assertJsonValidationErrors(['per_page']);
}
/**
* 허용되지 않은 정렬 방향은 거절된다
*/
public function test_logs_rejects_unknown_sort_order(): void
{
$user = $this->createAdminUser(['sirsoft-ecommerce.products.read']);
$product = Product::factory()->create();
$this->actingAs($user)
->getJson($this->url($product, 'sort_order=sideways'))
->assertStatus(422)
->assertJsonValidationErrors(['sort_order']);
}
}
Loaded 100 of 272 files, more files were not shown because too many files have changed in this diff. Show more