Compare commits

..
88 Commits
Author SHA1 Message Date
klaus 4baf253b7e Merge pull request '회원 통계 페이지에 애플 가입 수 추가' (#89) from test into main
Reviewed-on: #89
2026-02-08 07:52:06 +00:00
klaus e0c63df2a6 Merge pull request '콘텐츠 수정 - 커버 이미지 수정 기능 추가' (#88) from test into main
Reviewed-on: #88
2026-02-06 05:13:01 +00:00
klaus 892923becc Merge pull request 'test' (#87) from test into main
Reviewed-on: #87
2026-02-04 14:00:37 +00:00
klaus d3ea703204 Merge pull request '캔 환율관리 - 페이징 없이 모든 데이터 표시되도록 수정' (#86) from test into main
Reviewed-on: #86
2026-01-13 05:11:30 +00:00
klaus 70298b8f8f Merge pull request 'feat(admin-series): 시리즈 리스트에 연재요일 표시' (#85) from test into main
Reviewed-on: #85
2025-11-14 08:21:07 +00:00
klaus 9fa9f3e699 Merge pull request 'test' (#84) from test into main
Reviewed-on: #84
2025-11-13 20:18:27 +00:00
klaus d82531583c Merge pull request 'fix(admin-series): 시리즈 수정 기능 추가' (#83) from test into main
Reviewed-on: #83
2025-11-13 19:51:42 +00:00
klaus 6240a285c2 Merge pull request 'fix(admin-can): 닉네임 검색 시 선택 칩이 사라지는 문제 수정' (#82) from test into main
Reviewed-on: #82
2025-11-10 08:05:25 +00:00
klaus f577ab575e Merge pull request 'feat(admin-can): 캔 지급 화면에 닉네임 검색·다중 회원번호 입력 및 다중 지급 지원' (#81) from test into main
Reviewed-on: #81
2025-11-10 07:08:25 +00:00
klaus 0c3e3fc3fd Merge pull request 'feat(admin-can-status): 화폐단위 추가, 충전금액에 NumberFormat style: currency 적용하여 화폐단위 표시' (#80) from test into main
Reviewed-on: #80
2025-10-10 21:00:42 +00:00
klaus 6886c372aa Merge pull request 'feat(can): 소수점이 잘못 표기되던 버그 수정' (#79) from test into main
Reviewed-on: #79
2025-10-10 08:58:35 +00:00
klaus 8dd3dcb770 Merge pull request 'test' (#78) from test into main
Reviewed-on: #78
2025-10-10 08:25:15 +00:00
klaus 1a435b6074 Merge pull request 'test' (#77) from test into main
Reviewed-on: #77
2025-09-18 19:42:41 +00:00
klaus 492859dae3 Merge pull request 'test' (#76) from test into main
Reviewed-on: #76
2025-09-16 06:16:32 +00:00
klaus 18b59b5598 Merge pull request 'test' (#75) from test into main
Reviewed-on: #75
2025-09-14 09:04:57 +00:00
klaus 5fcdd7f06d Merge pull request '캐릭터 챗봇' (#74) from test into main
Reviewed-on: #74
2025-09-10 06:26:02 +00:00
klaus 1e149f7e41 Merge pull request '쿠폰생성 - 쿠폰타입(포인트, 캔) 선택 추가' (#73) from test into main
Reviewed-on: #73
2025-06-10 11:01:52 +00:00
klaus aca3767a24 Merge pull request 'test' (#72) from test into main
Reviewed-on: #72
2025-05-20 07:21:28 +00:00
klaus d51655f15e Merge pull request '포인트 정책 등록/수정 페이지 추가' (#71) from test into main
Reviewed-on: #71
2025-04-24 03:28:52 +00:00
klaus 47dd32939f Merge pull request '일별 전체 회원 수 - 이메일, 구글, 카카오 회원 수 추가' (#70) from test into main
Reviewed-on: #70
2025-04-10 02:35:33 +00:00
klaus 2e1891ab08 Merge pull request '회원리스트 - 로그인 타입 필드 추가' (#69) from test into main
Reviewed-on: #69
2025-04-09 10:44:30 +00:00
klaus 99d70cc8f7 Merge pull request '이벤트 배너 수정 - 링크 지우기 추가' (#68) from test into main
Reviewed-on: #68
2025-04-07 14:48:10 +00:00
klaus 9f1675e82d Merge pull request '광고통계 - 로그인 수를 가장 오른쪽으로 이동' (#67) from test into main
Reviewed-on: #67
2025-04-02 02:11:35 +00:00
klaus c2838be2ed Merge pull request '일별 전체 회원 수 통계' (#66) from test into main
Reviewed-on: #66
2025-03-31 03:54:56 +00:00
klaus b5c2941c0d Merge pull request '앱 실행 수 추가' (#65) from test into main
Reviewed-on: #65
2025-03-28 05:58:43 +00:00
klaus d5c01d8d23 Merge pull request '광고통계 - 빠른검색 (날짜 지정) 추가' (#64) from test into main
Reviewed-on: #64
2025-03-17 04:58:02 +00:00
klaus 7118b0649a Merge pull request '비밀번호 재설정 기능 추가' (#63) from test into main
Reviewed-on: #63
2025-03-17 03:09:41 +00:00
klaus 8f5346581e Merge pull request '일별 전체 회원 수 페이지 추가' (#62) from test into main
Reviewed-on: #62
2025-03-14 16:08:06 +00:00
klaus e43f2e30be Merge pull request '충전 이벤트, 이벤트 배너 - 기간 설정에 시간 추가' (#61) from test into main
Reviewed-on: #61
2025-03-14 03:34:42 +00:00
klaus 397fd267e0 Merge pull request 'test' (#60) from test into main
Reviewed-on: #60
2025-03-11 08:07:48 +00:00
klaus fe4b88350b Merge pull request '광고 통계 페이지' (#59) from test into main
Reviewed-on: #59
2025-03-05 13:53:32 +00:00
klaus 537474e162 Merge pull request '마케팅 - 매체 파트너 코드 페이지 추가' (#58) from test into main
Reviewed-on: #58
2025-03-05 09:54:31 +00:00
klaus b5abdf3cf5 Merge pull request 'test' (#57) from test into main
Reviewed-on: #57
2025-02-18 15:12:52 +00:00
klaus a2e457b5e8 Merge pull request 'test' (#56) from test into main
Reviewed-on: #56
2025-02-09 13:25:35 +00:00
klaus 05ddd417cd Merge pull request '콘텐츠 배너 등록/수정' (#54) from test into main
Reviewed-on: #54
2025-01-17 16:46:45 +00:00
klaus e70426af68 Merge pull request 'test' (#53) from test into main
Reviewed-on: #53
2025-01-17 06:00:59 +00:00
klaus 81b33e1322 Merge pull request '오디션 지원 취소기능 적용' (#52) from test into main
Reviewed-on: #52
2025-01-08 06:34:54 +00:00
klaus 588fcfbe90 Merge pull request '오디션 지원자 연락처 표시' (#51) from test into main
Reviewed-on: #51
2025-01-07 20:10:23 +00:00
klaus ff2c126382 Merge pull request '오디션 메뉴 추가' (#50) from test into main
Reviewed-on: #50
2025-01-07 17:20:32 +00:00
klaus 702daca29f Merge pull request '소다라이브 -> 보이스온' (#49) from test into main
Reviewed-on: #49
2024-11-21 12:59:05 +00:00
klaus 8e9008a3c1 Merge pull request '이벤트 기간 추가' (#48) from test into main
Reviewed-on: #48
2024-10-31 03:17:44 +00:00
klaus 5c0c00aad4 Merge pull request '크리에이터 리스트 - 프로필 이미지 다운로드 버튼 추가' (#47) from test into main
Reviewed-on: #47
2024-10-24 03:07:00 +00:00
klaus e0949c6d73 Merge pull request 'test' (#46) from test into main
Reviewed-on: #46
2024-10-16 04:18:55 +00:00
klaus 0449bac8d5 Merge pull request '전체 개수 추가' (#45) from test into main
Reviewed-on: #45
2024-10-15 04:18:01 +00:00
klaus d412c15c9d Merge pull request '시리즈 리스트 - 작품 개수 추가' (#44) from test into main
Reviewed-on: #44
2024-10-14 15:43:15 +00:00
klaus ed16a6ddad Merge pull request '시리즈 리스트 페이지 추가' (#43) from test into main
Reviewed-on: #43
2024-10-14 10:14:19 +00:00
klaus f06e2d41e0 Merge pull request '전체 크리에이터 수 추가' (#42) from test into main
Reviewed-on: #42
2024-09-26 11:38:53 +00:00
klaus 7505269db3 Merge pull request '크리에이터별 정산 - 페이징 추가' (#41) from test into main
Reviewed-on: #41
2024-08-01 05:16:04 +00:00
klaus 15eeb6943d Merge pull request '크리에이터 기준 라이브, 콘텐츠, 커뮤니티 합계 정산 페이지 추가' (#40) from test into main
Reviewed-on: #40
2024-07-08 14:41:28 +00:00
klaus 7e7ed46cea Merge pull request '크리에이터 기준 라이브, 콘텐츠, 커뮤니티 합계 정산 페이지 추가' (#39) from test into main
Reviewed-on: #39
2024-07-08 14:37:08 +00:00
klaus fd01786649 Merge pull request 'test' (#38) from test into main
Reviewed-on: #38
2024-07-08 14:22:01 +00:00
klaus c48c1c2f09 Merge pull request '크리에이터 정산비율 등록페이지 추가' (#37) from test into main
Reviewed-on: #37
2024-06-11 08:11:57 +00:00
klaus 9bcf3a3cdb Merge pull request '커뮤니티 정산' (#36) from test into main
Reviewed-on: #36
2024-06-06 14:59:58 +00:00
klaus 4c5b987d98 Merge pull request 'test' (#35) from test into main
Reviewed-on: #35
2024-06-03 22:24:23 +00:00
klaus f168403048 Merge pull request '라이브 리스트 - 현재참여인원 추가' (#34) from test into main
Reviewed-on: #34
2024-05-28 18:16:18 +00:00
klaus 82ee1584e7 Merge pull request '커뮤니티 정산 페이지 추가' (#33) from test into main
Reviewed-on: #33
2024-05-28 16:13:16 +00:00
klaus 65cb918389 Merge pull request '시그니처 관리 - 재생 시간 등록/수정 기능 추가' (#32) from test into main
Reviewed-on: #32
2024-05-02 07:17:34 +00:00
klaus 784baf9a2f Merge pull request '시리즈 장르 - 등록/삭제 페이지 추가' (#31) from test into main
Reviewed-on: #31
2024-04-26 19:06:32 +00:00
klaus 7a85ac41cc Merge pull request '관리자 - 캔 충전현황' (#30) from test into main
Reviewed-on: #30
2024-04-01 11:34:15 +00:00
klaus 9d4c9437cf Merge pull request '관리자 - 캔 충전현황' (#29) from test into main
Reviewed-on: #29
2024-04-01 11:27:14 +00:00
klaus 68845aeae1 Merge pull request '콘텐츠 리스트 한정판 표시' (#28) from test into main
Reviewed-on: #28
2024-03-29 05:00:01 +00:00
klaus bbdca29337 Merge pull request '콘텐츠 리스트' (#27) from test into main
Reviewed-on: #27
2024-03-28 06:43:25 +00:00
klaus c14c041daa Merge pull request 'test' (#26) from test into main
Reviewed-on: #26
2024-03-19 07:50:16 +00:00
klaus a515a144eb Merge pull request 'test' (#25) from test into main
Reviewed-on: #25
2024-03-13 11:42:23 +00:00
klaus 54a6773905 Merge pull request 'test' (#24) from test into main
Reviewed-on: #24
2024-03-12 07:54:10 +00:00
klaus d97087b4e9 Merge pull request '시그니처 캔 등록 페이지 추가' (#23) from test into main
Reviewed-on: #23
2024-03-08 13:59:51 +00:00
klaus ddb2449053 Merge pull request '파비콘 변경' (#22) from test into main
Reviewed-on: #22
2024-02-17 14:56:25 +00:00
klaus 8aca07cdf7 Merge pull request '콘텐츠 수정' (#21) from test into main
Reviewed-on: #21
2024-02-08 18:25:50 +00:00
klaus 0ba845d95a Merge pull request '콘텐츠 리스트 - 오픈예정일 추가' (#20) from test into main
Reviewed-on: #20
2024-01-11 09:27:25 +00:00
klaus 64b1fd5395 Merge pull request '수정 기능 추가' (#19) from test into main
Reviewed-on: #19
2024-01-03 15:25:28 +00:00
klaus 639bea70fa Merge pull request '쿠폰 관리 페이지 추가' (#18) from test into main
Reviewed-on: #18
2024-01-03 10:33:23 +00:00
klaus 6a89ba059b Merge pull request '푸시 발송 대상 지정 UI 추가' (#17) from test into main
Reviewed-on: #17
2023-11-24 07:01:10 +00:00
klaus ff83041585 Merge pull request '연령제한 표시 추가' (#16) from test into main
Reviewed-on: #16
2023-11-21 16:25:21 +00:00
klaus e660be0bf4 Merge pull request '일자별 콘텐츠 후원 페이지 - 유/무료 구분 추가' (#15) from test into main
Reviewed-on: #15
2023-11-14 13:36:49 +00:00
klaus 62cdd57069 Merge pull request '일자별 콘텐츠 후원 페이지 - 유/무료 구분 추가' (#14) from test into main
Reviewed-on: #14
2023-11-14 13:34:37 +00:00
klaus f8346ed5ef Merge pull request '일자별 콘텐츠 후원 페이지 - 유/무료 구분 추가' (#13) from test into main
Reviewed-on: #13
2023-11-14 13:19:50 +00:00
klaus 9656b9a9d1 Merge pull request '일자별 콘텐츠 후원 페이지 추가' (#12) from test into main
Reviewed-on: #12
2023-11-14 08:57:15 +00:00
klaus 97a58266bb Merge pull request 'orderType 추가, 판매수 -> 누적 판매수 로 변경' (#11) from test into main
Reviewed-on: #11
2023-11-13 14:52:38 +00:00
klaus 8fc0cfa345 Merge pull request '콘텐츠별 누적 현황 페이지 - 총 콘텐츠 개수 표시' (#10) from test into main
Reviewed-on: #10
2023-11-13 14:08:26 +00:00
klaus 22f9c2287d Merge pull request '콘텐츠별 누적 현황 페이지 추가' (#9) from test into main
Reviewed-on: #9
2023-11-13 13:46:19 +00:00
klaus 9284f7d5c3 Merge pull request '콘텐츠 정산 - 엑셀 다운로드 추가' (#8) from test into main
Reviewed-on: #8
2023-11-13 08:46:43 +00:00
klaus e6f27a4529 Merge pull request '콘텐츠 정산 - 헤더 순서 변경' (#7) from test into main
Reviewed-on: #7
2023-11-10 13:56:50 +00:00
klaus 6a33d1c024 Merge pull request '콘텐츠 정산 페이지 추가' (#6) from test into main
Reviewed-on: #6
2023-11-10 10:51:32 +00:00
klaus 3b83789c15 Merge pull request 'test' (#5) from test into main
Reviewed-on: #5
2023-10-06 15:09:02 +00:00
klaus 55f0ab9af3 Merge pull request '크리에이터 라이브 정산 - 인원 추가, 코인 -> 캔' (#4) from test into main
Reviewed-on: #4
2023-10-03 12:15:25 +00:00
klaus 9b168a6112 Merge pull request '크리에이터 라이브 정산 페이지 추가' (#3) from test into main
Reviewed-on: #3
2023-10-03 09:25:39 +00:00
klaus c47937933e Merge pull request 'test' (#2) from test into main
Reviewed-on: #2
2023-08-25 07:50:32 +00:00
klaus 4744fe7d9a Merge pull request '채널공유 - 파이어베이스 링크, 도메인, 프로젝트명 변경' (#1) from test into main
Reviewed-on: #1
2023-08-22 03:39:44 +00:00
68 changed files with 23193 additions and 18266 deletions
+1 -4
View File
@@ -1,11 +1,8 @@
# soda-live-admin
## Project setup
Use Node.js 24.x for this project. Install dependencies from the lock file with:
```
npm ci
npm install
```
### Compiles and hot-reloads for development
+22609 -7174
View File
File diff suppressed because it is too large Load Diff
+11 -23
View File
@@ -2,17 +2,11 @@
"name": "soda-live-admin",
"version": "0.1.0",
"private": true,
"engines": {
"node": "^24.0.0"
},
"scripts": {
"serve_local": "vue-cli-service serve --mode local --port 8888",
"serve": "vue-cli-service serve --port 8888",
"build": "vue-cli-service build",
"build_development": "vue-cli-service build --mode development",
"test:gift": "node tests/gift.test.js && node tests/gift_category.test.js && node tests/gift_size.test.js && node tests/gift_mailbox.test.js",
"test:banner": "node tests/audio_content_banner.test.js",
"test:sub-banner": "node tests/sub_banner.test.js",
"lint": "vue-cli-service lint"
},
"dependencies": {
@@ -20,7 +14,7 @@
"cropperjs": "^1.5.13",
"file-saver": "^2.0.5",
"lodash": "^4.17.21",
"vue": "2.6.14",
"vue": "^2.6.11",
"vue-excel-xlsx": "^1.2.2",
"vue-router": "^3.2.0",
"vue-show-more-text": "^2.0.2",
@@ -35,21 +29,21 @@
"vuex": "^3.4.0"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~5.0.0",
"@vue/cli-plugin-eslint": "~5.0.0",
"@vue/cli-plugin-router": "~5.0.0",
"@vue/cli-plugin-vuex": "~5.0.0",
"@vue/cli-service": "~5.0.0",
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-plugin-router": "~4.5.0",
"@vue/cli-plugin-vuex": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"axios": "0.21.2",
"babel-eslint": "^10.1.0",
"eslint": "^7.32.0",
"eslint-plugin-vue": "^7.20.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^6.2.2",
"sass": "~1.32.0",
"sass-loader": "^10.0.0",
"vue-cli-plugin-axios": "~0.0.4",
"vue-cli-plugin-vuetify": "~2.4.5",
"vue-template-compiler": "2.6.14",
"vuetify-loader": "1.7.3"
"vue-template-compiler": "^2.6.11",
"vuetify-loader": "^1.7.0"
},
"eslintConfig": {
"root": true,
@@ -64,13 +58,7 @@
"parser": "babel-eslint"
},
"rules": {
"no-unused-vars": "off",
"vue/valid-v-slot": [
"error",
{
"allowModifiers": true
}
]
"no-unused-vars": "off"
}
},
"browserslist": [
-145
View File
@@ -1,145 +0,0 @@
import Vue from 'vue'
// 공통: 페이지 파라미터 변환(1-based UI → 0-based Spring Pageable)
function toZeroBased(page) {
const p = Number(page || 1)
return Math.max(0, p - 1)
}
// 에이전트 리스트 조회
// 서버 스펙에 페이지네이션이 없다면 단순 GET으로 사용
// 추후 필요 시 params(page,size) 확장 가능
async function getAgentList() {
return Vue.axios.get('/admin/partner/agent/list')
}
// 에이전트 정산 비율 목록 조회
async function getAgentSettlementRatioList() {
return Vue.axios.get('/admin/partner/agent/ratio')
}
// 에이전트 정산 비율 등록
// payload: { memberId: number, settlementRatio: number, effectiveFrom: string(yyyy-MM-ddTHH:mm:ss) }
async function createAgentSettlementRatio(payload) {
return Vue.axios.post('/admin/partner/agent/ratio', payload)
}
// 에이전트 정산 비율 수정
// payload: { memberId: number, settlementRatio: number, effectiveFrom: string(yyyy-MM-ddTHH:mm:ss) }
async function updateAgentSettlementRatio(payload) {
return Vue.axios.post('/admin/partner/agent/ratio/update', payload)
}
// 에이전트 닉네임 검색
// 반환: [{ id, nickname }]
async function searchAgentByNickname(query) {
try {
const res = await Vue.axios.get('/admin/partner/agent/search-by-nickname', {
params: { nickname: query, search_word: query }
})
if (res && Array.isArray(res.data)) return res.data
if (res && res.data && Array.isArray(res.data.data)) return res.data.data
return []
} catch (e) {
return []
}
}
// 에이전트 소속 크리에이터 목록 조회
// GET /admin/partner/agent/{agentId}/creator/list
// params: { page, size }
async function getAgentAssignedCreatorList(agentId, page = 1, size = 20) {
// Spring Pageable은 일반적으로 0-based page index를 사용
const zeroBasedPage = Math.max(0, Number(page || 1) - 1)
return Vue.axios.get(`/admin/partner/agent/${agentId}/creator/list`, {
params: { page: zeroBasedPage, size }
})
}
// 추가 가능한 크리에이터 검색
// GET /admin/partner/agent/creator/search?search_word=...
async function searchAdminAgentAssignableCreators(search_word) {
return Vue.axios.get('/admin/partner/agent/creator/search', {
params: { search_word }
})
}
// 에이전트에 크리에이터 소속 시키기
// POST /admin/partner/agent/assignment
// payload: { agentId, creatorId, assignedAt } // assignedAt: LocalDateTime string (yyyy-MM-ddTHH:mm:ss)
async function assignAgentCreator(payload) {
return Vue.axios.post('/admin/partner/agent/assignment', payload)
}
// 크리에이터 소속 해제
// POST /admin/partner/agent/assignment/remove
// payload: { creatorId, unassignedAt } // unassignedAt: LocalDateTime string
async function removeAgentCreator(payload) {
return Vue.axios.post('/admin/partner/agent/assignment/remove', payload)
}
// =========================
// 정산 상세 - 에이전트별(크리에이터 기준 집계)
// 공통 Request: startDateStr, endDateStr, Spring Pageable(page,size,sort)
// 공통 Response: ApiResponse<GetAgentSettlementByCreatorResponse>
// { success, message, data: { totalCount, total:{...}, items:[...] } }
function buildSettlementParams({ startDateStr, endDateStr, page = 1, size = 20, sort }) {
const params = {
startDateStr,
endDateStr,
page: toZeroBased(page),
size
}
if (sort) params.sort = sort
return params
}
async function getAgentLiveSettlementByCreator(agentId, { startDateStr, endDateStr, page = 1, size = 20, sort } = {}) {
return Vue.axios.get(`/admin/partner/agent/${agentId}/calculate/live-by-creator`, {
params: buildSettlementParams({ startDateStr, endDateStr, page, size, sort })
})
}
async function getAgentContentSettlementByCreator(agentId, { startDateStr, endDateStr, page = 1, size = 20, sort } = {}) {
return Vue.axios.get(`/admin/partner/agent/${agentId}/calculate/content-by-creator`, {
params: buildSettlementParams({ startDateStr, endDateStr, page, size, sort })
})
}
async function getAgentCommunitySettlementByCreator(agentId, { startDateStr, endDateStr, page = 1, size = 20, sort } = {}) {
return Vue.axios.get(`/admin/partner/agent/${agentId}/calculate/community-by-creator`, {
params: buildSettlementParams({ startDateStr, endDateStr, page, size, sort })
})
}
async function getAgentContentDonationSettlementByCreator(agentId, { startDateStr, endDateStr, page = 1, size = 20, sort } = {}) {
return Vue.axios.get(`/admin/partner/agent/${agentId}/calculate/content-donation-by-creator`, {
params: buildSettlementParams({ startDateStr, endDateStr, page, size, sort })
})
}
async function getAgentChannelDonationSettlementByCreator(agentId, { startDateStr, endDateStr, page = 1, size = 20, sort } = {}) {
return Vue.axios.get(`/admin/partner/agent/${agentId}/calculate/channel-donation-by-creator`, {
params: buildSettlementParams({ startDateStr, endDateStr, page, size, sort })
})
}
export {
getAgentList,
getAgentSettlementRatioList,
createAgentSettlementRatio,
updateAgentSettlementRatio,
searchAgentByNickname,
// 에이전트 상세 - 소속 크리에이터 관리
getAgentAssignedCreatorList,
searchAdminAgentAssignableCreators,
assignAgentCreator,
removeAgentCreator,
// 에이전트 정산 상세 (크리에이터 기준)
getAgentLiveSettlementByCreator,
getAgentContentSettlementByCreator,
getAgentCommunitySettlementByCreator,
getAgentContentDonationSettlementByCreator,
getAgentChannelDonationSettlementByCreator,
}
+1 -1
View File
@@ -43,7 +43,7 @@ async function getSeriesBannerList(page = 1, size = 20) {
async function createSeriesBanner(bannerData) {
const formData = new FormData();
if (bannerData.image) formData.append("image", bannerData.image);
const requestData = { seriesId: bannerData.seriesId, lang: bannerData.lang };
const requestData = { seriesId: bannerData.seriesId };
formData.append("request", JSON.stringify(requestData));
return Vue.axios.post("/admin/audio-content/series/banner/register", formData, {
headers: { "Content-Type": "multipart/form-data" }
+7 -94
View File
@@ -1,19 +1,19 @@
import Vue from 'vue';
async function getCalculateLive(startDate, endDate, page, size) {
return Vue.axios.get('/admin/calculate/live?startDateStr=' + startDate + '&endDateStr=' + endDate + '&page=' + (page - 1) + '&size=' + size);
async function getCalculateLive(startDate, endDate) {
return Vue.axios.get('/admin/calculate/live?startDateStr=' + startDate + '&endDateStr=' + endDate);
}
async function getCalculateContent(startDate, endDate, page, size) {
return Vue.axios.get('/admin/calculate/content-list?startDateStr=' + startDate + '&endDateStr=' + endDate + '&page=' + (page - 1) + '&size=' + size);
async function getCalculateContent(startDate, endDate) {
return Vue.axios.get('/admin/calculate/content-list?startDateStr=' + startDate + '&endDateStr=' + endDate);
}
async function getCumulativeSalesByContent(page, size) {
return Vue.axios.get('/admin/calculate/cumulative-sales-by-content?page=' + (page - 1) + "&size=" + size);
}
async function getCalculateContentDonation(startDate, endDate, page, size) {
return Vue.axios.get('/admin/calculate/content-donation-list?startDateStr=' + startDate + '&endDateStr=' + endDate + '&page=' + (page - 1) + '&size=' + size);
async function getCalculateContentDonation(startDate, endDate) {
return Vue.axios.get('/admin/calculate/content-donation-list?startDateStr=' + startDate + '&endDateStr=' + endDate);
}
async function getCalculateCommunityPost(startDate, endDate, page, size) {
@@ -57,72 +57,6 @@ async function getCalculateCommunityByCreator(startDate, endDate, page, size) {
)
}
async function getCalculateChannelDonationByCreator(startDate, endDate, page, size) {
return Vue.axios.get('/admin/calculate/channel-donation-by-creator?startDateStr=' +
startDate + '&endDateStr=' + endDate + '&page=' + (page - 1) + '&size=' + size
)
}
async function getCalculateChannelDonationByDate(startDate, endDate, page, size) {
return Vue.axios.get('/admin/calculate/channel-donation-by-date?startDateStr=' +
startDate + '&endDateStr=' + endDate + '&page=' + (page - 1) + '&size=' + size
)
}
async function downloadCalculateChannelDonationByCreatorExcel(startDate, endDate) {
return Vue.axios.get('/admin/calculate/channel-donation-by-creator/excel?startDateStr=' + startDate + '&endDateStr=' + endDate, {
responseType: 'blob'
});
}
async function downloadCalculateLiveExcel(startDate, endDate) {
return Vue.axios.get('/admin/calculate/live/excel?startDateStr=' + startDate + '&endDateStr=' + endDate, {
responseType: 'blob'
});
}
async function downloadCalculateContentExcel(startDate, endDate) {
return Vue.axios.get('/admin/calculate/content-list/excel?startDateStr=' + startDate + '&endDateStr=' + endDate, {
responseType: 'blob'
});
}
async function downloadCalculateContentDonationExcel(startDate, endDate) {
return Vue.axios.get('/admin/calculate/content-donation-list/excel?startDateStr=' + startDate + '&endDateStr=' + endDate, {
responseType: 'blob'
});
}
async function downloadCalculateCommunityPostExcel(startDate, endDate) {
return Vue.axios.get('/admin/calculate/community-post/excel?startDateStr=' + startDate + '&endDateStr=' + endDate, {
responseType: 'blob'
});
}
async function downloadCalculateLiveByCreatorExcel(startDate, endDate) {
return Vue.axios.get('/admin/calculate/live-by-creator/excel?startDateStr=' + startDate + '&endDateStr=' + endDate, {
responseType: 'blob'
});
}
async function downloadCalculateContentByCreatorExcel(startDate, endDate) {
return Vue.axios.get('/admin/calculate/content-by-creator/excel?startDateStr=' + startDate + '&endDateStr=' + endDate, {
responseType: 'blob'
});
}
async function downloadCalculateCommunityByCreatorExcel(startDate, endDate) {
return Vue.axios.get('/admin/calculate/community-by-creator/excel?startDateStr=' + startDate + '&endDateStr=' + endDate, {
responseType: 'blob'
});
}
async function downloadCalculateChannelDonationByDateExcel(startDate, endDate) {
return Vue.axios.get('/admin/calculate/channel-donation-by-date/excel?startDateStr=' + startDate + '&endDateStr=' + endDate, {
responseType: 'blob'
});
}
async function updateCreatorSettlementRatio(creatorSettlementRatio) {
const request = {
memberId: creatorSettlementRatio.creator_id,
@@ -138,15 +72,6 @@ async function deleteCreatorSettlementRatio(memberId) {
return Vue.axios.post('/admin/calculate/ratio/delete/' + memberId);
}
async function refundLive(roomId, canUsageStr) {
const request = {
roomId: roomId,
canUsageStr: canUsageStr
};
return Vue.axios.post('/admin/calculate/live/refund', request);
}
export {
getCalculateLive,
getCalculateContent,
@@ -157,19 +82,7 @@ export {
createCreatorSettlementRatio,
updateCreatorSettlementRatio,
deleteCreatorSettlementRatio,
refundLive,
getCalculateLiveByCreator,
getCalculateContentByCreator,
getCalculateCommunityByCreator,
getCalculateChannelDonationByCreator,
getCalculateChannelDonationByDate,
downloadCalculateChannelDonationByCreatorExcel,
downloadCalculateLiveExcel,
downloadCalculateContentExcel,
downloadCalculateContentDonationExcel,
downloadCalculateCommunityPostExcel,
downloadCalculateLiveByCreatorExcel,
downloadCalculateContentByCreatorExcel,
downloadCalculateCommunityByCreatorExcel,
downloadCalculateChannelDonationByDateExcel
getCalculateCommunityByCreator
}
+2 -3
View File
@@ -115,10 +115,9 @@ async function createCharacterBanner(bannerData) {
// 이미지 FormData에 추가
if (bannerData.image) formData.append('image', bannerData.image)
// 캐릭터 ID와 언어 코드를 JSON 문자열로 변환하여 request 필드에 추가
// 캐릭터 ID를 JSON 문자열로 변환하여 request 필드에 추가
const requestData = {
characterId: bannerData.characterId,
lang: bannerData.lang
characterId: bannerData.characterId
}
formData.append('request', JSON.stringify(requestData))
+1 -5
View File
@@ -11,8 +11,4 @@ async function getChargeStatusDetail(startDate, paymentGateway, currency) {
);
}
async function refundCharge(chargeId) {
return Vue.axios.post('/admin/charge/refund', { chargeId });
}
export { getChargeStatus, getChargeStatusDetail, refundCharge }
export { getChargeStatus, getChargeStatusDetail }
-44
View File
@@ -1,44 +0,0 @@
import Vue from 'vue';
const baseUrl = '/api/v2/admin/gifts'
async function getGifts({ status, applicationNo, nickname, page = 0, size = 20 } = {}) {
const params = { page, size }
if (status) params.status = status
if (applicationNo) params.applicationNo = applicationNo
if (nickname) params.nickname = nickname
const response = await Vue.axios.get(baseUrl, { params })
return response.data
}
async function getGift(applicationNo) {
const response = await Vue.axios.get(`${baseUrl}/${encodeURIComponent(applicationNo)}`)
return response.data
}
async function arriveMailbox(applicationNo) {
const response = await Vue.axios.post(`${baseUrl}/${encodeURIComponent(applicationNo)}/arrive-mailbox`)
return response.data
}
async function completeInspection(applicationNo) {
const response = await Vue.axios.post(`${baseUrl}/${encodeURIComponent(applicationNo)}/complete-inspection`)
return response.data
}
async function completeDelivery(applicationNo) {
const response = await Vue.axios.post(`${baseUrl}/${encodeURIComponent(applicationNo)}/complete-delivery`)
return response.data
}
async function markUndeliverable(applicationNo, reason) {
const response = await Vue.axios.post(`${baseUrl}/${encodeURIComponent(applicationNo)}/mark-undeliverable`, { reason })
return response.data
}
async function cancelGift(applicationNo) {
const response = await Vue.axios.post(`${baseUrl}/${encodeURIComponent(applicationNo)}/cancel`)
return response.data
}
export { getGifts, getGift, arriveMailbox, completeInspection, completeDelivery, markUndeliverable, cancelGift }
-26
View File
@@ -1,26 +0,0 @@
import Vue from 'vue';
import { buildGiftCategoryRequest } from '@/utils/gift_category'
const baseUrl = '/api/v2/admin/gift-categories'
async function getGiftCategories() {
const response = await Vue.axios.get(baseUrl)
return response.data
}
async function createGiftCategory(form) {
const response = await Vue.axios.post(baseUrl, buildGiftCategoryRequest(form))
return response.data
}
async function updateGiftCategory(categoryId, form) {
const response = await Vue.axios.put(`${baseUrl}/${encodeURIComponent(categoryId)}`, buildGiftCategoryRequest(form))
return response.data
}
async function deactivateGiftCategory(categoryId) {
const response = await Vue.axios.delete(`${baseUrl}/${encodeURIComponent(categoryId)}`)
return response.data
}
export { getGiftCategories, createGiftCategory, updateGiftCategory, deactivateGiftCategory }
-15
View File
@@ -1,15 +0,0 @@
import Vue from 'vue';
const baseUrl = '/api/v2/admin/gift-mailbox'
async function getGiftMailbox() {
const response = await Vue.axios.get(baseUrl)
return response.data
}
async function updateGiftMailbox(request) {
const response = await Vue.axios.put(baseUrl, request)
return response.data
}
export { getGiftMailbox, updateGiftMailbox }
-17
View File
@@ -1,17 +0,0 @@
import Vue from 'vue';
import { giftSizes, buildGiftSizeRequest } from '@/utils/gift_size'
const baseUrl = '/api/v2/admin/gift-size-prices'
async function getGiftSizePrices() {
const response = await Vue.axios.get(baseUrl)
return response.data
}
async function updateGiftSizePrice(sizeCode, form) {
if (!giftSizes.includes(sizeCode)) throw new Error('올바른 선물 사이즈가 아닙니다.')
const response = await Vue.axios.put(`${baseUrl}/${sizeCode}`, buildGiftSizeRequest(form))
return response.data
}
export { getGiftSizePrices, updateGiftSizePrice }
+5 -19
View File
@@ -1,7 +1,7 @@
import Vue from 'vue';
async function login(email, password) {
return Vue.axios.post('/admin/member/login', {
return Vue.axios.post('/member/login', {
email,
password,
isAdmin: true,
@@ -43,13 +43,6 @@ async function updateMember(id, user_type) {
return Vue.axios.put("/admin/member", request)
}
async function updateCreatorLocalizedNameJa(creatorId, displayName) {
return Vue.axios.put(
"/api/v2/admin/creators/" + creatorId + "/localized-names/ja",
{displayName}
)
}
async function getCreatorAllList() {
return Vue.axios.get("/admin/member/creator/all/list")
}
@@ -59,11 +52,6 @@ async function resetPassword(id) {
return Vue.axios.post("/admin/member/password/reset", request)
}
async function blockMember(memberId, reason) {
const request = {memberId, reason}
return Vue.axios.post("/admin/member/block", request)
}
/**
* 닉네임으로 회원 검색 API
* - 서버 구현 차이를 흡수하기 위해 nickname, search_word 두 파라미터 모두 전송
@@ -96,10 +84,8 @@ export {
searchMember,
getCreatorList,
searchCreator,
updateMember,
updateCreatorLocalizedNameJa,
getCreatorAllList,
resetPassword,
blockMember,
searchMembersByNickname
updateMember,
getCreatorAllList,
resetPassword,
searchMembersByNickname
}
+7 -18
View File
@@ -1,33 +1,21 @@
import Vue from 'vue';
async function save(title, content, publishAt) {
async function save(title, content) {
const request = {title: title, content: content}
// publishAt 생략 또는 null 은 즉시 공개
if (publishAt != null) {
request.publishAt = publishAt
}
return Vue.axios.post("/notice", request)
}
async function modify(id, title, content, publishAt) {
async function modify(id, title, content) {
const request = {id: id}
if (title != null && title.trim().length > 0) {
if (title.trim().length > 0) {
request.title = title
}
if (content != null && content.trim().length > 0) {
if (content.trim().length > 0) {
request.content = content
}
// undefined 는 기존 예약 상태 보존(생략),
// null 은 사용자가 즉시 공개 전환을 명시한 경우에만 전송
if (publishAt !== undefined) {
request.publishAt = publishAt
}
return Vue.axios.put("/notice", request)
}
@@ -37,8 +25,9 @@ async function deleteNotice(id) {
async function getNotices(page) {
return Vue.axios.get(
"/api/v2/admin/notices?page=" + (page - 1) +
"&size=20"
"/notice?page=" + (page - 1) +
"&size=20" +
"&timezone=" + Intl.DateTimeFormat().resolvedOptions().timeZone
)
}
-37
View File
@@ -1,37 +0,0 @@
import Vue from 'vue';
// 소지 유저 조회
async function getOwners() {
return Vue.axios.get('/admin/calculate/original-series/owners');
}
// 정산 내역 조회 (page는 1부터 시작하는 UI 기준, 서버에는 0부터 전달)
async function getSettlementDetails({ startDate, endDate, creatorId, page = 1, size = 10 }) {
const params = new URLSearchParams();
// 서버 파라미터 스펙 변경: start_date, end_date, creator_id
if (startDate) params.append('start_date', startDate);
if (endDate) params.append('end_date', endDate);
if (creatorId != null) params.append("creator_id", creatorId);
params.append('page', Math.max(0, (page || 1) - 1));
params.append('size', size || 10);
return Vue.axios.get(`/admin/calculate/original-series/settlement-details?${params.toString()}`);
}
// 엑셀 다운로드 (xlsx 바이너리)
async function downloadSettlementExcel({ startDate, endDate }) {
const params = new URLSearchParams();
// 서버 파라미터 스펙 변경: start_date, end_date
if (startDate) params.append('start_date', startDate);
if (endDate) params.append('end_date', endDate);
return Vue.axios.get(`/admin/calculate/original-series/settlement-details/excel?${params.toString()}` , {
responseType: 'blob'
});
}
export {
getOwners,
getSettlementDetails,
downloadSettlementExcel,
};
-27
View File
@@ -1,27 +0,0 @@
import Vue from 'vue';
async function getSubBanners(placement) {
return Vue.axios.get('/admin/sub-banners', {params: {placement}})
}
async function saveSubBanner(formData) {
return Vue.axios.post('/admin/sub-banners', formData, {
headers: {
"Content-Type": "multipart/form-data",
},
});
}
async function modifySubBanner(id, formData) {
return Vue.axios.put('/admin/sub-banners/' + id, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
});
}
async function deleteSubBanner(id) {
return Vue.axios.delete('/admin/sub-banners/' + id)
}
export {getSubBanners, saveSubBanner, modifySubBanner, deleteSubBanner}
+48 -176
View File
@@ -94,189 +94,61 @@ export default {
this.isLoading = true
try {
let res = await api.getMenus();
if (res.status === 200 && res.data.success === true) {
// 기본 메뉴 설정 (API 결과가 비어있을 수 있음)
this.items = Array.isArray(res.data.data) ? res.data.data : []
if (res.status === 200 && res.data.success === true && res.data.data.length > 0) {
this.items = res.data.data
// 현재 사용자 역할 확인
const role = (this.$store && this.$store.state && this.$store.state.accountStore && this.$store.state.accountStore.role)
|| localStorage.role
// ADMIN 권한 전용 추가 메뉴들
if (role === 'ADMIN') {
const giftMenu = this.items.find(m => m && m.title === '선물함 관리')
if (giftMenu) {
if (!Array.isArray(giftMenu.items)) {
this.$set(giftMenu, 'items', giftMenu.items ? [].concat(giftMenu.items) : [])
// '시리즈 관리' 메뉴에 '배너 등록' 하위 메뉴 추가
try {
const seriesMenu = this.items.find(m => m && m.title === '시리즈 관리')
if (seriesMenu) {
if (!Array.isArray(seriesMenu.items)) {
seriesMenu.items = seriesMenu.items ? [].concat(seriesMenu.items) : []
}
if (!giftMenu.items.some(item => item && item.route === '/gift/list')) {
giftMenu.items.push({ title: '선물함 리스트', route: '/gift/list', items: null })
}
if (!giftMenu.items.some(item => item && item.route === '/gift/category')) {
giftMenu.items.push({ title: '선물 카테고리', route: '/gift/category', items: null })
}
if (!giftMenu.items.some(item => item && item.route === '/gift/size')) {
giftMenu.items.push({ title: '선물 사이즈', route: '/gift/size', items: null })
}
if (!giftMenu.items.some(item => item && item.route === '/gift/mailbox')) {
giftMenu.items.push({ title: '받을 주소', route: '/gift/mailbox', items: null })
}
} else {
this.items.push({
title: '선물함 관리',
route: null,
icon: 'mdi-gift',
items: [
{ title: '선물함 리스트', route: '/gift/list', items: null },
{ title: '선물 카테고리', route: '/gift/category', items: null },
{ title: '선물 사이즈', route: '/gift/size', items: null },
{ title: '받을 주소', route: '/gift/mailbox', items: null }
]
})
}
// '시리즈 관리' 메뉴에 '배너 등록' 하위 메뉴 추가
try {
const seriesMenu = this.items.find(m => m && m.title === '시리즈 관리')
if (seriesMenu) {
if (!Array.isArray(seriesMenu.items)) {
seriesMenu.items = seriesMenu.items ? [].concat(seriesMenu.items) : []
}
const exists = seriesMenu.items.some(ci => ci && ci.route === '/content/series/banner')
if (!exists) {
seriesMenu.items.push({
title: '배너 등록',
route: '/content/series/banner',
items: null
})
}
}
} catch (e) {
// ignore
}
// 프로모션 메뉴에 '가로형 서브 배너' 하위 메뉴 추가
try {
const promotionMenu = this.items.find(m => m && Array.isArray(m.items)
&& m.items.some(ci => ci && ci.route === '/promotion/event'))
const subBannerItem = { title: '가로형 서브 배너', route: '/promotion/sub-banner', items: null }
if (promotionMenu) {
if (!promotionMenu.items.some(ci => ci && ci.route === subBannerItem.route)) {
promotionMenu.items.push(subBannerItem)
}
} else {
this.items.push({
title: '프로모션 관리',
route: null,
icon: 'mdi-bullhorn',
items: [subBannerItem]
const exists = seriesMenu.items.some(ci => ci && ci.route === '/content/series/banner')
if (!exists) {
seriesMenu.items.push({
title: '배너 등록',
route: '/content/series/banner',
items: null
})
}
} catch (e) {
// ignore
}
// 캐릭터 챗봇 메뉴 추가
this.items.push({
title: '캐릭터 챗봇',
route: null,
items: [
{
title: '배너 등록',
route: '/character/banner',
items: null
},
{
title: '캐릭터 리스트',
route: '/character',
items: null
},
{
title: '큐레이션',
route: '/character/curation',
items: null
},
{
title: '정산',
route: '/character/calculate',
items: null
},
{
title: '원작',
route: '/original-work',
items: null
},
]
})
// 에이전트 관리 메뉴를 '크리에이터 관리' 바로 아래에 추가
try {
const insertAfterTitle = '크리에이터 관리'
const agentMenu = {
title: '에이전트 관리',
route: null,
items: [
{ title: '에이전트 리스트', route: '/agent/list', items: null },
{ title: '에이전트 정산 비율', route: '/agent/settlement-ratio', items: null },
]
}
const idx = this.items.findIndex(m => m && m.title === insertAfterTitle)
if (idx >= 0) {
this.items.splice(idx + 1, 0, agentMenu)
} else {
// 기준 메뉴가 없으면 하단에 추가
this.items.push(agentMenu)
}
} catch (e) {
// ignore
}
// 정산현황 메뉴에 '채널 후원 정산' 및 '오리지널 시리즈 정산' 추가
try {
const calculateMenu = this.items.find(m => m && m.title === '정산현황')
if (calculateMenu) {
if (!Array.isArray(calculateMenu.items)) {
calculateMenu.items = calculateMenu.items ? [].concat(calculateMenu.items) : []
}
const exists = calculateMenu.items.some(ci => ci && ci.route === '/calculate/channel-donation')
if (!exists) {
calculateMenu.items.push({
title: '채널 후원 정산',
route: '/calculate/channel-donation',
items: null
})
}
const existsOriginal = calculateMenu.items.some(ci => ci && ci.route === '/calculate/original-series')
if (!existsOriginal) {
calculateMenu.items.push({
title: '오리지널 시리즈 정산',
route: '/calculate/original-series',
items: null
})
}
}
} catch (e) {
// ignore
}
} catch (e) {
// ignore
}
// 조회한 메뉴가 비어 있고, 콘텐츠 매니저라면 기본 메뉴 추가
if (this.items.length === 0 && role === 'CONTENT_MANAGER') {
this.items.push({
title: '콘텐츠 리스트',
route: '/content/list',
items: null
})
}
// 그래도 비어있다면 이전 동작과 동일하게 처리
if (this.items.length === 0) {
this.notifyError("알 수 없는 오류가 발생했습니다. 다시 로그인 해주세요!")
this.logout();
}
// 캐릭터 챗봇 메뉴 추가
this.items.push({
title: '캐릭터 챗봇',
route: null,
items: [
{
title: '배너 등록',
route: '/character/banner',
items: null
},
{
title: '캐릭터 리스트',
route: '/character',
items: null
},
{
title: '큐레이션',
route: '/character/curation',
items: null
},
{
title: '정산',
route: '/character/calculate',
items: null
},
{
title: '원작',
route: '/original-work',
items: null
},
]
})
} else {
this.notifyError("알 수 없는 오류가 발생했습니다. 다시 로그인 해주세요!")
this.logout();
-87
View File
@@ -50,58 +50,6 @@ const routes = [
name: 'CreatorReview',
component: () => import(/* webpackChunkName: "counselor" */ '../views/Creator/CreatorSettlementRatio.vue')
},
// Agent Management
{
path: '/calculate/original-series',
name: 'OriginalSeriesSettlement',
component: () => import(/* webpackChunkName: "calculate" */ '../views/Calculate/OriginalSeriesSettlement.vue')
},
{
path: '/agent/list',
name: 'AgentList',
component: () => import(/* webpackChunkName: "agent" */ '../views/Agent/AgentList.vue')
},
{
path: '/agent/:agentId/settlement/live',
name: 'AgentSettlementLive',
props: true,
component: () => import(/* webpackChunkName: "agent" */ '../views/Agent/AgentLiveSettlement.vue')
},
{
path: '/agent/:agentId/settlement/content',
name: 'AgentSettlementContent',
props: true,
component: () => import(/* webpackChunkName: "agent" */ '../views/Agent/AgentContentSettlement.vue')
},
{
path: '/agent/:agentId/settlement/community',
name: 'AgentSettlementCommunity',
props: true,
component: () => import(/* webpackChunkName: "agent" */ '../views/Agent/AgentCommunitySettlement.vue')
},
{
path: '/agent/:agentId/settlement/content-donation',
name: 'AgentSettlementContentDonation',
props: true,
component: () => import(/* webpackChunkName: "agent" */ '../views/Agent/AgentContentDonationSettlement.vue')
},
{
path: '/agent/:agentId/settlement/channel-donation',
name: 'AgentSettlementChannelDonation',
props: true,
component: () => import(/* webpackChunkName: "agent" */ '../views/Agent/AgentChannelDonationSettlement.vue')
},
{
path: '/agent/settlement-ratio',
name: 'AgentSettlementRatio',
component: () => import(/* webpackChunkName: "agent" */ '../views/Agent/AgentSettlementRatio.vue')
},
{
path: '/agent/:agentId',
name: 'AgentDetail',
props: true,
component: () => import(/* webpackChunkName: "agent" */ '../views/Agent/AgentDetail.vue')
},
{
path: '/live/tags',
name: 'LiveTags',
@@ -182,11 +130,6 @@ const routes = [
name: 'EventView',
component: () => import(/* webpackChunkName: "promotion" */ '../views/Promotion/EventView.vue')
},
{
path: '/promotion/sub-banner',
name: 'SubBannerView',
component: () => import(/* webpackChunkName: "promotion" */ '../views/Promotion/SubBannerView.vue')
},
{
path: '/promotion/push',
name: 'Push',
@@ -267,16 +210,6 @@ const routes = [
name: 'CalculateCommunityByCreator',
component: () => import(/* webpackChunkName: "calculate" */ '../views/Calculate/CalculateCommunityByCreator.vue')
},
{
path: '/calculate/channel-donation',
name: 'CalculateChannelDonation',
component: () => import(/* webpackChunkName: "calculate" */ '../views/Calculate/CalculateChannelDonation.vue')
},
{
path: '/calculate/channel-donation-by-creator',
name: 'CalculateChannelDonationByCreator',
component: () => import(/* webpackChunkName: "calculate" */ '../views/Calculate/CalculateChannelDonationByCreator.vue')
},
{
path: '/notice',
name: 'NoticeView',
@@ -367,26 +300,6 @@ const routes = [
name: 'CharacterCalculate',
component: () => import(/* webpackChunkName: "character" */ '../views/Chat/CharacterCalculateList.vue')
},
{
path: '/gift/list',
name: 'GiftList',
component: () => import(/* webpackChunkName: "gift" */ '../views/Gift/GiftList.vue')
},
{
path: '/gift/category',
name: 'GiftCategory',
component: () => import(/* webpackChunkName: "gift" */ '../views/Gift/GiftCategory.vue')
},
{
path: '/gift/size',
name: 'GiftSize',
component: () => import(/* webpackChunkName: "gift" */ '../views/Gift/GiftSize.vue')
},
{
path: '/gift/mailbox',
name: 'GiftMailbox',
component: () => import(/* webpackChunkName: "gift" */ '../views/Gift/GiftMailbox.vue')
},
{
path: '/original-work',
name: 'OriginalList',
+19 -7
View File
@@ -12,13 +12,17 @@ enhanceAccessToken();
const accountStore = {
namespaced: true,
state: {
userId: '',
nickname: '',
accessToken: '',
role: '',
profileImage: '',
},
getters: {
isAuthenticated(state) {
state.userId = state.userId || localStorage.userId
state.nickname = state.nickname || localStorage.nickname
state.profileImage = state.profileImage || localStorage.profileImage
state.accessToken = state.accessToken || localStorage.accessToken
state.role = state.role || localStorage.role
return state.accessToken !== undefined &&
state.accessToken !== null &&
@@ -27,19 +31,27 @@ const accountStore = {
}
},
mutations: {
LOGIN(state, {token, role}) {
LOGIN(state, {userId, nickname, token, profileImage}) {
state.userId = userId
localStorage.userId = userId
state.nickname = nickname
localStorage.nickname = nickname
state.profileImage = profileImage
localStorage.profileImage = profileImage
state.accessToken = token
localStorage.accessToken = token
state.role = role
localStorage.role = role
Vue.axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
},
LOGOUT(state) {
state.userId = ''
state.nickname = ''
state.profileImage = ''
state.accessToken = ''
state.role = ''
localStorage.clear()
if (location.pathname === '/') {
-71
View File
@@ -1,71 +0,0 @@
const DATE_TIME_PATTERN = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/
export function toDateTimeLocalInput(value) {
if (value === null || value === undefined) return ''
const text = String(value).trim()
if (!text || text === 'null') return ''
return text.replace(' ', 'T').slice(0, 16)
}
export function toServerDateTime(value) {
if (value === null || value === undefined) return null
const text = String(value).trim()
if (!text || text === 'null') return null
return text.replace('T', ' ').slice(0, 16)
}
export function formatScheduleRange(startDate, endDate) {
const start = toServerDateTime(startDate)
const end = toServerDateTime(endDate)
if (!start && !end) return '상시 노출'
if (start && !end) return `${start} ~`
if (!start && end) return `~ ${end}`
return `${start} ~ ${end}`
}
export function createBannerScheduleForm(banner = {}) {
return {
start_date: toDateTimeLocalInput(banner.startDate),
end_date: toDateTimeLocalInput(banner.endDate)
}
}
export function validateBannerSchedule(form = {}) {
const errors = {}
const start = toServerDateTime(form.start_date)
const end = toServerDateTime(form.end_date)
if (start !== null && !DATE_TIME_PATTERN.test(start)) {
errors.start_date = '시작 일시 형식이 올바르지 않습니다. (yyyy-MM-dd HH:mm)'
}
if (end !== null && !DATE_TIME_PATTERN.test(end)) {
errors.end_date = '종료 일시 형식이 올바르지 않습니다. (yyyy-MM-dd HH:mm)'
}
if (!errors.start_date && !errors.end_date && start !== null && end !== null && start > end) {
errors.end_date = '종료 일시는 시작 일시보다 빠를 수 없습니다.'
}
return errors
}
export function applyScheduleToSaveRequest(request, form = {}) {
const start = toServerDateTime(form.start_date)
const end = toServerDateTime(form.end_date)
if (start !== null) request.startDate = start
if (end !== null) request.endDate = end
return request
}
export function applyScheduleToModifyRequest(request, form = {}, banner = {}) {
const start = toServerDateTime(form.start_date)
const end = toServerDateTime(form.end_date)
const originalStart = toServerDateTime(banner.startDate)
const originalEnd = toServerDateTime(banner.endDate)
if (start !== originalStart) request.startDate = start
if (end !== originalEnd) request.endDate = end
return request
}
-24
View File
@@ -1,24 +0,0 @@
export const giftStatuses = [
{ text: '전체', value: '' },
{ text: '접수 완료', value: 'RECEIVED' },
{ text: '발송 확인', value: 'TRACKING_REGISTERED' },
{ text: '사서함 도착', value: 'ARRIVED_AT_MAILBOX' },
{ text: '검수 완료', value: 'INSPECTION_COMPLETED' },
{ text: '전달 완료', value: 'DELIVERED' },
{ text: '전달 불가', value: 'UNDELIVERABLE' },
{ text: '신청 취소', value: 'CANCELED' }
]
export const giftActions = [
{ value: 'ARRIVE_MAILBOX', label: '사서함 도착 처리', method: 'arriveMailbox' },
{ value: 'COMPLETE_INSPECTION', label: '검수 완료 처리', method: 'completeInspection' },
{ value: 'COMPLETE_DELIVERY', label: '전달 완료 처리', method: 'completeDelivery' },
{ value: 'MARK_UNDELIVERABLE', label: '전달 불가 처리', method: 'markUndeliverable' },
{ value: 'CANCEL', label: '신청 취소', method: 'cancelGift' }
]
export function validateUndeliverableReason(reason) {
if (typeof reason !== 'string' || !reason.trim()) return '전달 불가 사유를 입력해 주세요.'
if (reason.length > 255) return '전달 불가 사유는 255자 이내로 입력해 주세요.'
return true
}
-55
View File
@@ -1,55 +0,0 @@
export function createGiftCategoryForm() {
return {
classificationNumber: '',
categoryCode: '',
name: '',
receiptCode: '',
representativeItem: '',
requiresDamageWaiver: false,
isActive: true
}
}
export function buildGiftCategoryRequest(form) {
return {
classificationNumber: form.classificationNumber,
categoryCode: form.categoryCode,
name: form.name,
receiptCode: form.receiptCode,
representativeItem: form.representativeItem,
requiresDamageWaiver: form.requiresDamageWaiver,
isActive: form.isActive
}
}
export function validateGiftCategory(form) {
const errors = {}
const requiredFields = [
['classificationNumber', '분류번호', 3],
['categoryCode', '카테고리 코드', 50],
['name', '카테고리명', 50],
['receiptCode', '접수 코드', 9],
['representativeItem', '대표 품목', 100]
]
for (const [key, label, maxLength] of requiredFields) {
const value = form[key]
if (typeof value !== 'string' || !value.trim()) {
errors[key] = `${label} 항목은 필수입니다.`
} else if (value.length > maxLength) {
errors[key] = `${label} 항목은 ${maxLength}자 이하로 입력해 주세요.`
}
}
if (!errors.classificationNumber && (!/^[0-9]{3}$/.test(form.classificationNumber) || form.classificationNumber.length !== 3)) {
errors.classificationNumber = '분류번호는 숫자 3자리로 입력해 주세요.'
}
if (!errors.receiptCode && /[^A-Z]/.test(form.receiptCode)) {
errors.receiptCode = '접수 코드는 영문 대문자 1~9자로 입력해 주세요.'
}
if (typeof form.requiresDamageWaiver !== 'boolean') {
errors.requiresDamageWaiver = '파손면책 동의 필요 여부를 선택해 주세요.'
}
if (typeof form.isActive !== 'boolean') {
errors.isActive = '활성 여부를 선택해 주세요.'
}
return errors
}
-37
View File
@@ -1,37 +0,0 @@
export const giftSizes = Object.freeze(['SMALL', 'MEDIUM', 'LARGE'])
export function createGiftSizeForm(item = {}) {
return {
sizeCode: item.sizeCode || '',
name: item.name || '',
basePriceCan: item.basePriceCan === undefined ? '' : item.basePriceCan,
salePriceCan: item.salePriceCan === undefined ? '' : item.salePriceCan,
isActive: item.isActive === undefined ? false : item.isActive
}
}
export function buildGiftSizeRequest(form) {
return {
basePriceCan: Number(form.basePriceCan),
salePriceCan: Number(form.salePriceCan),
isActive: form.isActive
}
}
export function validateGiftSize(form) {
const errors = {}
if (!giftSizes.includes(form.sizeCode)) errors.sizeCode = '올바른 선물 사이즈가 아닙니다.'
for (const [key, label] of [['basePriceCan', '기본가'], ['salePriceCan', '판매가']]) {
const value = form[key]
if (value === null || value === undefined || (typeof value === 'string' && !value.trim())) {
errors[key] = `${label}를 입력해 주세요.`
} else if (!['number', 'string'].includes(typeof value) || !Number.isSafeInteger(Number(value)) || Number(value) < 1) {
errors[key] = `${label}는 1 이상의 정수로 입력해 주세요.`
}
}
if (!errors.basePriceCan && !errors.salePriceCan && Number(form.salePriceCan) > Number(form.basePriceCan)) {
errors.salePriceCan = '판매가는 기본가보다 클 수 없습니다.'
}
if (typeof form.isActive !== 'boolean') errors.isActive = '활성 여부를 선택해 주세요.'
return errors
}
-28
View File
@@ -1,28 +0,0 @@
let loading
export function loadPostcode() {
if (window.daum && window.daum.Postcode) return Promise.resolve(window.daum.Postcode)
if (loading) return loading
loading = new Promise((resolve, reject) => {
const script = document.createElement('script')
const finish = error => {
clearTimeout(timer)
script.onload = null
script.onerror = null
if (error) {
script.remove()
loading = null
reject(error)
} else {
resolve(window.daum.Postcode)
}
}
const timer = setTimeout(() => finish(new Error('주소 검색을 불러오지 못했습니다. 다시 시도해주세요.')), 15000)
script.src = 'https://t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js'
script.async = true
script.onload = () => finish(window.daum && window.daum.Postcode ? null : new Error('주소 검색을 불러오지 못했습니다. 다시 시도해주세요.'))
script.onerror = () => finish(new Error('주소 검색을 불러오지 못했습니다. 다시 시도해주세요.'))
document.head.appendChild(script)
})
return loading
}
-312
View File
@@ -1,312 +0,0 @@
const DATE_TIME_PATTERN = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/
const SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/
const DENIED_SCHEMES = ['javascript', 'data', 'file', 'content']
// 변환된 경계 instant 가 UTC 1970-01-01 00:00:01 ~ 2038-01-19 03:14:07 사이여야 하므로
// KST 분 단위 입력의 허용 범위는 아래와 같다.
export const START_DATE_MIN = '1970-01-01 09:01'
export const START_DATE_MAX = '2038-01-19 12:14'
export const END_DATE_MIN = '1970-01-01 09:00'
export const END_DATE_MAX = '2038-01-19 12:13'
// 과거 한국 서머타임(KST)으로 존재하지 않는 현지 시각 구간
const NON_EXISTENT_KST_RANGES = [
{from: '1987-05-10 02:00', to: '1987-05-10 02:59'},
{from: '1988-05-08 02:00', to: '1988-05-08 02:59'}
]
export const SUB_BANNER_PLACEMENTS = [
{value: 'HOME_RECOMMENDATION', text: '홈'},
{value: 'CONTENT_RECOMMENDATION', text: '콘텐츠'}
]
export const SUB_BANNER_LANGS = [
{value: 'KO', text: '한국어'},
{value: 'JA', text: '일본어'},
{value: 'EN', text: '영어'}
]
export const SUB_BANNER_DEFAULT_LANG = 'KO'
export function langLabel(lang) {
const found = SUB_BANNER_LANGS.find((item) => item.value === lang)
return found ? found.text : ''
}
export function isSubBannerLang(lang) {
return SUB_BANNER_LANGS.some((item) => item.value === lang)
}
export function placementLabel(placement) {
const found = SUB_BANNER_PLACEMENTS.find((item) => item.value === placement)
return found ? found.text : ''
}
export function isSubBannerPlacement(placement) {
return SUB_BANNER_PLACEMENTS.some((item) => item.value === placement)
}
export function toDateTimeLocalInput(value) {
if (value === null || value === undefined) return ''
const text = String(value).trim()
if (!text || text === 'null') return ''
return text.replace(' ', 'T').slice(0, 16)
}
export function toServerDateTime(value) {
if (value === null || value === undefined) return null
const text = String(value).trim()
if (!text || text === 'null') return null
return text.replace('T', ' ')
}
export function formatScheduleRange(startDate, endDate) {
const start = toServerDateTime(startDate)
const end = toServerDateTime(endDate)
if (!start && !end) return '상시 노출 (기간 제한 없음)'
if (start && !end) return `${start} ~ (KST)`
if (!start && end) return `~ ${end} (KST)`
return `${start} ~ ${end} (KST)`
}
export function scheduleStatus(banner = {}, now = null) {
const start = toServerDateTime(banner.startDate)
const end = toServerDateTime(banner.endDate)
const current = now === null || now === undefined ? nowKstMinute() : toServerDateTime(now)
if (!start && !end) return '무기간'
if (start && current < start) return '예정'
if (end && current > end) return '만료'
return '노출중'
}
export function nowKstMinute(date = new Date()) {
const kst = new Date(date.getTime() + (9 * 60 + date.getTimezoneOffset()) * 60000)
const pad = (value) => String(value).padStart(2, '0')
return `${kst.getFullYear()}-${pad(kst.getMonth() + 1)}-${pad(kst.getDate())} ${pad(kst.getHours())}:${pad(kst.getMinutes())}`
}
export function normalizeUrl(value) {
if (value === null || value === undefined) return null
const text = String(value).trim()
if (!text) return null
return text
}
function schemeOf(value) {
const matched = SCHEME_PATTERN.exec(value)
return matched ? matched[0].slice(0, -1).toLowerCase() : null
}
export function isValidWebUrl(value) {
const url = normalizeUrl(value)
if (url === null) return false
try {
const parsed = new URL(url)
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false
return !!parsed.host
} catch (e) {
return false
}
}
export function isValidDeepLink(value) {
const url = normalizeUrl(value)
if (url === null) return false
const scheme = schemeOf(url)
if (scheme === null) return false
if (DENIED_SCHEMES.indexOf(scheme) >= 0) return false
try {
new URL(url)
return true
} catch (e) {
return false
}
}
function isRealDateTime(value) {
if (!DATE_TIME_PATTERN.test(value)) return false
const year = Number(value.slice(0, 4))
const month = Number(value.slice(5, 7))
const day = Number(value.slice(8, 10))
const hour = Number(value.slice(11, 13))
const minute = Number(value.slice(14, 16))
if (month < 1 || month > 12) return false
if (hour > 23 || minute > 59) return false
const lastDay = new Date(Date.UTC(year, month, 0)).getUTCDate()
if (day < 1 || day > lastDay) return false
return !NON_EXISTENT_KST_RANGES.some((range) => value >= range.from && value <= range.to)
}
export function validateDateBoundary(value, boundary) {
const text = toServerDateTime(value)
if (text === null) return null
const label = boundary === 'end' ? '종료 일시' : '시작 일시'
if (!isRealDateTime(text)) {
return `${label} 형식이 올바르지 않습니다. 한국 시간(KST) yyyy-MM-dd HH:mm 분 단위로 입력하세요.`
}
const min = boundary === 'end' ? END_DATE_MIN : START_DATE_MIN
const max = boundary === 'end' ? END_DATE_MAX : START_DATE_MAX
if (text < min || text > max) {
return `${label}는 ${min} ~ ${max} (KST) 범위 안이어야 합니다.`
}
return null
}
export function createSubBannerForm(banner = {}) {
return {
id: banner.id === undefined ? null : banner.id,
placement: banner.placement || SUB_BANNER_PLACEMENTS[0].value,
// 저장된 언어가 있으면 그대로 사용하고, 신규 등록일 때만 KO 를 기본값으로 쓴다.
lang: isSubBannerLang(banner.lang) ? banner.lang : SUB_BANNER_DEFAULT_LANG,
image: null,
image_url: banner.imageUrl || null,
web_url: banner.webUrl === null || banner.webUrl === undefined ? '' : String(banner.webUrl),
android_deep_link: banner.androidDeepLink === null || banner.androidDeepLink === undefined
? ''
: String(banner.androidDeepLink),
ios_deep_link: banner.iosDeepLink === null || banner.iosDeepLink === undefined
? ''
: String(banner.iosDeepLink),
start_date: toDateTimeLocalInput(banner.startDate),
end_date: toDateTimeLocalInput(banner.endDate)
}
}
export function normalizeUrls(form = {}) {
return {
webUrl: normalizeUrl(form.web_url),
androidDeepLink: normalizeUrl(form.android_deep_link),
iosDeepLink: normalizeUrl(form.ios_deep_link)
}
}
export function validateSubBannerUrls(form = {}) {
const errors = {}
const urls = normalizeUrls(form)
if (urls.webUrl !== null && !isValidWebUrl(urls.webUrl)) {
errors.web_url = '웹 URL은 host 가 있는 절대 http(s) URL 이어야 합니다.'
}
if (urls.androidDeepLink !== null && !isValidDeepLink(urls.androidDeepLink)) {
errors.android_deep_link = 'Android 딥링크는 유효한 절대 URI 여야 하며 javascript, data, file, content scheme 은 사용할 수 없습니다.'
}
if (urls.iosDeepLink !== null && !isValidDeepLink(urls.iosDeepLink)) {
errors.ios_deep_link = 'iOS 딥링크는 유효한 절대 URI 여야 하며 javascript, data, file, content scheme 은 사용할 수 없습니다.'
}
if (urls.webUrl === null && urls.androidDeepLink === null && urls.iosDeepLink === null) {
errors.web_url = '웹 URL, Android 딥링크, iOS 딥링크 중 최소 한 개는 입력해야 합니다.'
}
return errors
}
export function validateSubBannerSchedule(form = {}, banner = null) {
const errors = {}
const startError = validateDateBoundary(form.start_date, 'start')
const endError = validateDateBoundary(form.end_date, 'end')
if (startError) errors.start_date = startError
if (endError) errors.end_date = endError
if (startError || endError) return errors
const request = banner === null
? buildSubBannerCreateRequest(form)
: buildSubBannerUpdateRequest(form, banner)
const effective = effectiveSchedule(request, banner)
if (effective.startDate !== null && effective.endDate !== null && effective.startDate > effective.endDate) {
errors.end_date = '종료 일시는 시작 일시보다 빠를 수 없습니다.'
}
return errors
}
export function effectiveSchedule(request = {}, banner = null) {
const saved = banner === null ? {} : banner
const startDate = Object.prototype.hasOwnProperty.call(request, 'startDate')
? request.startDate
: toServerDateTime(saved.startDate)
const endDate = Object.prototype.hasOwnProperty.call(request, 'endDate')
? request.endDate
: toServerDateTime(saved.endDate)
return {startDate, endDate}
}
export function validateSubBannerForm(form = {}, banner = null) {
return {...validateSubBannerUrls(form), ...validateSubBannerSchedule(form, banner)}
}
function baseRequest(form) {
const urls = normalizeUrls(form)
return {
placement: form.placement,
webUrl: urls.webUrl,
androidDeepLink: urls.androidDeepLink,
iosDeepLink: urls.iosDeepLink,
// 언어는 생성·수정 모두 현재 선택을 정규 대문자 코드로 항상 보낸다.
lang: isSubBannerLang(form.lang) ? form.lang : SUB_BANNER_DEFAULT_LANG
}
}
export function buildSubBannerCreateRequest(form = {}) {
const request = baseRequest(form)
const startDate = toServerDateTime(form.start_date)
const endDate = toServerDateTime(form.end_date)
if (startDate !== null) request.startDate = startDate
if (endDate !== null) request.endDate = endDate
return request
}
export function buildSubBannerUpdateRequest(form = {}, banner = {}) {
const request = baseRequest(form)
const startDate = toServerDateTime(form.start_date)
const endDate = toServerDateTime(form.end_date)
const savedStartDate = toServerDateTime(banner.startDate)
const savedEndDate = toServerDateTime(banner.endDate)
// 값이 그대로면 생략해 서버의 저장 값을 보존하고, 사용자가 지웠으면 명시적 null 로 해당 경계만 해제한다.
if (startDate !== savedStartDate) request.startDate = startDate
if (endDate !== savedEndDate) request.endDate = endDate
return request
}
export function appendSubBannerRequestPart(formData, request) {
const json = JSON.stringify(request)
// request 파트는 Content-Type: application/json 으로 전송한다.
if (typeof Blob === 'function') {
formData.append('request', new Blob([json], {type: 'application/json'}))
} else {
formData.append('request', json)
}
return formData
}
export function resolveSubBannerTarget(banner = {}, os = 'android') {
const webUrl = normalizeUrl(banner.webUrl)
const deepLink = os === 'ios'
? normalizeUrl(banner.iosDeepLink)
: normalizeUrl(banner.androidDeepLink)
if (deepLink !== null && webUrl !== null) return 'DEEP_LINK_WITH_WEB_FALLBACK'
if (deepLink !== null) return 'DEEP_LINK'
if (webUrl !== null) return 'WEB'
return 'NONE'
}
@@ -1,254 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-btn
icon
@click="$router.back()"
>
<v-icon>mdi-arrow-left</v-icon>
</v-btn>
<v-toolbar-title>{{ displayNickname }} 정산 상세 - 채널 후원</v-toolbar-title>
<v-spacer />
</v-toolbar>
<v-container>
<!-- 필터 영역 -->
<v-row
class="mt-2 mb-2"
align="center"
justify="end"
>
<v-col
cols="12"
md="3"
>
<v-menu
v-model="menuStart"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-bind="attrs"
label="시작일"
readonly
dense
:value="startDateStr"
v-on="on"
/>
</template>
<v-date-picker
v-model="startDateStr"
scrollable
@input="menuStart = false"
/>
</v-menu>
</v-col>
<v-col
cols="12"
md="3"
>
<v-menu
v-model="menuEnd"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-bind="attrs"
label="종료일"
readonly
dense
:value="endDateStr"
v-on="on"
/>
</template>
<v-date-picker
v-model="endDateStr"
scrollable
@input="menuEnd = false"
/>
</v-menu>
</v-col>
<v-col
cols="12"
md="2"
>
<v-btn
color="primary"
:loading="isLoading"
@click="onSearch"
>
조회
</v-btn>
</v-col>
</v-row>
<!-- 테이블 영역 -->
<v-data-table
:headers="headers"
:items="items"
:loading="isLoading"
:items-per-page="pageSize"
class="elevation-1"
disable-pagination
hide-default-footer
>
<!-- 표 최상단 합계 행 -->
<template v-slot:body.prepend>
<tr>
<td class="text-center">
합계
</td>
<td class="text-center">
{{ numberFormat(total.count) }}
</td>
<td class="text-center">
{{ numberFormat(total.totalCan) }}
</td>
<td class="text-center">
{{ currencyKRW(total.krw) }}
</td>
<td class="text-center">
{{ currencyKRW(total.fee) }}
</td>
<td class="text-center">
{{ currencyKRW(total.settlementAmount) }}
</td>
<td class="text-center">
{{ currencyKRW(total.tax) }}
</td>
<td class="text-center">
{{ currencyKRW(total.depositAmount) }}
</td>
<td class="text-center">
{{ currencyKRW(total.agentSettlementAmount) }}
</td>
</tr>
</template>
<template v-slot:item.count="{ item }">
{{ numberFormat(item.count) }}
</template>
<template v-slot:item.totalCan="{ item }">
{{ numberFormat(item.totalCan) }}
</template>
<template v-slot:item.krw="{ item }">
{{ currencyKRW(item.krw) }}
</template>
<template v-slot:item.fee="{ item }">
{{ currencyKRW(item.fee) }}
</template>
<template v-slot:item.settlementAmount="{ item }">
{{ currencyKRW(item.settlementAmount) }}
</template>
<template v-slot:item.tax="{ item }">
{{ currencyKRW(item.tax) }}
</template>
<template v-slot:item.depositAmount="{ item }">
{{ currencyKRW(item.depositAmount) }}
</template>
<template v-slot:item.agentSettlementAmount="{ item }">
{{ currencyKRW(item.agentSettlementAmount) }}
</template>
</v-data-table>
<!-- 페이지네이션 -->
<div class="d-flex justify-center mt-2">
<v-pagination
v-model="page"
:length="totalPages"
:total-visible="7"
@input="onPageChange"
/>
</div>
</v-container>
</div>
</template>
<script>
import { getAgentChannelDonationSettlementByCreator } from '@/api/agent'
export default {
name: 'AgentChannelDonationSettlement',
props: { agentId: { type: [String, Number], required: true } },
data() {
const today = new Date()
const yyyy = today.getFullYear()
const mm = String(today.getMonth() + 1).padStart(2, '0')
const dd = String(today.getDate()).padStart(2, '0')
const firstDay = `${yyyy}-${mm}-01`
const endDay = `${yyyy}-${mm}-${dd}`
return {
startDateStr: firstDay,
endDateStr: endDay,
menuStart: false,
menuEnd: false,
page: 1,
pageSize: 20,
isLoading: false,
totalCount: 0,
totalPages: 1,
total: { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 },
items: [],
headers: [
{ text: '닉네임', value: 'creatorNickname', align: 'center' },
{ text: '건수', value: 'count', align: 'center', width: 100 },
{ text: '총 CAN', value: 'totalCan', align: 'center', width: 120 },
{ text: '원화', value: 'krw', align: 'center', width: 140 },
{ text: '수수료', value: 'fee', align: 'center', width: 120 },
{ text: '정산금액', value: 'settlementAmount', align: 'center', width: 140 },
{ text: '세금', value: 'tax', align: 'center', width: 120 },
{ text: '입금액', value: 'depositAmount', align: 'center', width: 140 },
{ text: '에이전트 정산', value: 'agentSettlementAmount', align: 'center', width: 160 },
]
}
},
computed: {
displayNickname() {
const q = (this.$route && this.$route.query) || {}
return q.nickname || '에이전트'
}
},
mounted() { this.fetchList() },
methods: {
numberFormat(n) { return new Intl.NumberFormat('ko-KR').format(Number(n || 0)) },
currencyKRW(n) { return new Intl.NumberFormat('ko-KR', { style: 'currency', currency: 'KRW', maximumFractionDigits: 0 }).format(Number(n || 0)) },
onSearch() { this.page = 1; this.fetchList() },
onPageChange() { this.fetchList() },
async fetchList() {
this.isLoading = true
try {
const res = await getAgentChannelDonationSettlementByCreator(this.agentId, {
startDateStr: this.startDateStr,
endDateStr: this.endDateStr,
page: this.page,
size: this.pageSize,
})
let payload = res && res.data ? res.data : null
if (payload && payload.data && (!payload.items && !payload.totalCount)) payload = payload.data
const data = payload || { totalCount: 0, total: {}, items: [] }
this.totalCount = Number(data.totalCount || 0)
this.totalPages = Math.max(1, Math.ceil(this.totalCount / this.pageSize))
const defTotal = { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 }
this.total = Object.assign({}, defTotal, data.total || {})
this.items = Array.isArray(data.items) ? data.items : []
} catch (e) {
this.totalCount = 0
this.totalPages = 1
this.total = { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 }
this.items = []
} finally {
this.isLoading = false
}
}
}
}
</script>
<style scoped>
</style>
@@ -1,254 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-btn
icon
@click="$router.back()"
>
<v-icon>mdi-arrow-left</v-icon>
</v-btn>
<v-toolbar-title>{{ displayNickname }} 정산 상세 - 커뮤니티</v-toolbar-title>
<v-spacer />
</v-toolbar>
<v-container>
<!-- 필터 영역 -->
<v-row
class="mt-2 mb-2"
align="center"
justify="end"
>
<v-col
cols="12"
md="3"
>
<v-menu
v-model="menuStart"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-bind="attrs"
label="시작일"
readonly
dense
:value="startDateStr"
v-on="on"
/>
</template>
<v-date-picker
v-model="startDateStr"
scrollable
@input="menuStart = false"
/>
</v-menu>
</v-col>
<v-col
cols="12"
md="3"
>
<v-menu
v-model="menuEnd"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-bind="attrs"
label="종료일"
readonly
dense
:value="endDateStr"
v-on="on"
/>
</template>
<v-date-picker
v-model="endDateStr"
scrollable
@input="menuEnd = false"
/>
</v-menu>
</v-col>
<v-col
cols="12"
md="2"
>
<v-btn
color="primary"
:loading="isLoading"
@click="onSearch"
>
조회
</v-btn>
</v-col>
</v-row>
<!-- 테이블 영역 -->
<v-data-table
:headers="headers"
:items="items"
:loading="isLoading"
:items-per-page="pageSize"
class="elevation-1"
disable-pagination
hide-default-footer
>
<!-- 표 최상단 합계 행 -->
<template v-slot:body.prepend>
<tr>
<td class="text-center">
합계
</td>
<td class="text-center">
{{ numberFormat(total.count) }}
</td>
<td class="text-center">
{{ numberFormat(total.totalCan) }}
</td>
<td class="text-center">
{{ currencyKRW(total.krw) }}
</td>
<td class="text-center">
{{ currencyKRW(total.fee) }}
</td>
<td class="text-center">
{{ currencyKRW(total.settlementAmount) }}
</td>
<td class="text-center">
{{ currencyKRW(total.tax) }}
</td>
<td class="text-center">
{{ currencyKRW(total.depositAmount) }}
</td>
<td class="text-center">
{{ currencyKRW(total.agentSettlementAmount) }}
</td>
</tr>
</template>
<template v-slot:item.count="{ item }">
{{ numberFormat(item.count) }}
</template>
<template v-slot:item.totalCan="{ item }">
{{ numberFormat(item.totalCan) }}
</template>
<template v-slot:item.krw="{ item }">
{{ currencyKRW(item.krw) }}
</template>
<template v-slot:item.fee="{ item }">
{{ currencyKRW(item.fee) }}
</template>
<template v-slot:item.settlementAmount="{ item }">
{{ currencyKRW(item.settlementAmount) }}
</template>
<template v-slot:item.tax="{ item }">
{{ currencyKRW(item.tax) }}
</template>
<template v-slot:item.depositAmount="{ item }">
{{ currencyKRW(item.depositAmount) }}
</template>
<template v-slot:item.agentSettlementAmount="{ item }">
{{ currencyKRW(item.agentSettlementAmount) }}
</template>
</v-data-table>
<!-- 페이지네이션 -->
<div class="d-flex justify-center mt-2">
<v-pagination
v-model="page"
:length="totalPages"
:total-visible="7"
@input="onPageChange"
/>
</div>
</v-container>
</div>
</template>
<script>
import { getAgentCommunitySettlementByCreator } from '@/api/agent'
export default {
name: 'AgentCommunitySettlement',
props: { agentId: { type: [String, Number], required: true } },
data() {
const today = new Date()
const yyyy = today.getFullYear()
const mm = String(today.getMonth() + 1).padStart(2, '0')
const dd = String(today.getDate()).padStart(2, '0')
const firstDay = `${yyyy}-${mm}-01`
const endDay = `${yyyy}-${mm}-${dd}`
return {
startDateStr: firstDay,
endDateStr: endDay,
menuStart: false,
menuEnd: false,
page: 1,
pageSize: 20,
isLoading: false,
totalCount: 0,
totalPages: 1,
total: { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 },
items: [],
headers: [
{ text: '닉네임', value: 'creatorNickname', align: 'center' },
{ text: '건수', value: 'count', align: 'center', width: 100 },
{ text: '총 CAN', value: 'totalCan', align: 'center', width: 120 },
{ text: '원화', value: 'krw', align: 'center', width: 140 },
{ text: '수수료', value: 'fee', align: 'center', width: 120 },
{ text: '정산금액', value: 'settlementAmount', align: 'center', width: 140 },
{ text: '세금', value: 'tax', align: 'center', width: 120 },
{ text: '입금액', value: 'depositAmount', align: 'center', width: 140 },
{ text: '에이전트 정산', value: 'agentSettlementAmount', align: 'center', width: 160 },
]
}
},
computed: {
displayNickname() {
const q = (this.$route && this.$route.query) || {}
return q.nickname || '에이전트'
}
},
mounted() { this.fetchList() },
methods: {
numberFormat(n) { return new Intl.NumberFormat('ko-KR').format(Number(n || 0)) },
currencyKRW(n) { return new Intl.NumberFormat('ko-KR', { style: 'currency', currency: 'KRW', maximumFractionDigits: 0 }).format(Number(n || 0)) },
onSearch() { this.page = 1; this.fetchList() },
onPageChange() { this.fetchList() },
async fetchList() {
this.isLoading = true
try {
const res = await getAgentCommunitySettlementByCreator(this.agentId, {
startDateStr: this.startDateStr,
endDateStr: this.endDateStr,
page: this.page,
size: this.pageSize,
})
let payload = res && res.data ? res.data : null
if (payload && payload.data && (!payload.items && !payload.totalCount)) payload = payload.data
const data = payload || { totalCount: 0, total: {}, items: [] }
this.totalCount = Number(data.totalCount || 0)
this.totalPages = Math.max(1, Math.ceil(this.totalCount / this.pageSize))
const defTotal = { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 }
this.total = Object.assign({}, defTotal, data.total || {})
this.items = Array.isArray(data.items) ? data.items : []
} catch (e) {
this.totalCount = 0
this.totalPages = 1
this.total = { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 }
this.items = []
} finally {
this.isLoading = false
}
}
}
}
</script>
<style scoped>
</style>
@@ -1,254 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-btn
icon
@click="$router.back()"
>
<v-icon>mdi-arrow-left</v-icon>
</v-btn>
<v-toolbar-title>{{ displayNickname }} 정산 상세 - 콘텐츠 후원</v-toolbar-title>
<v-spacer />
</v-toolbar>
<v-container>
<!-- 필터 영역 -->
<v-row
class="mt-2 mb-2"
align="center"
justify="end"
>
<v-col
cols="12"
md="3"
>
<v-menu
v-model="menuStart"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-bind="attrs"
label="시작일"
readonly
dense
:value="startDateStr"
v-on="on"
/>
</template>
<v-date-picker
v-model="startDateStr"
scrollable
@input="menuStart = false"
/>
</v-menu>
</v-col>
<v-col
cols="12"
md="3"
>
<v-menu
v-model="menuEnd"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-bind="attrs"
label="종료일"
readonly
dense
:value="endDateStr"
v-on="on"
/>
</template>
<v-date-picker
v-model="endDateStr"
scrollable
@input="menuEnd = false"
/>
</v-menu>
</v-col>
<v-col
cols="12"
md="2"
>
<v-btn
color="primary"
:loading="isLoading"
@click="onSearch"
>
조회
</v-btn>
</v-col>
</v-row>
<!-- 테이블 영역 -->
<v-data-table
:headers="headers"
:items="items"
:loading="isLoading"
:items-per-page="pageSize"
class="elevation-1"
disable-pagination
hide-default-footer
>
<!-- 표 최상단 합계 행 -->
<template v-slot:body.prepend>
<tr>
<td class="text-center">
합계
</td>
<td class="text-center">
{{ numberFormat(total.count) }}
</td>
<td class="text-center">
{{ numberFormat(total.totalCan) }}
</td>
<td class="text-center">
{{ currencyKRW(total.krw) }}
</td>
<td class="text-center">
{{ currencyKRW(total.fee) }}
</td>
<td class="text-center">
{{ currencyKRW(total.settlementAmount) }}
</td>
<td class="text-center">
{{ currencyKRW(total.tax) }}
</td>
<td class="text-center">
{{ currencyKRW(total.depositAmount) }}
</td>
<td class="text-center">
{{ currencyKRW(total.agentSettlementAmount) }}
</td>
</tr>
</template>
<template v-slot:item.count="{ item }">
{{ numberFormat(item.count) }}
</template>
<template v-slot:item.totalCan="{ item }">
{{ numberFormat(item.totalCan) }}
</template>
<template v-slot:item.krw="{ item }">
{{ currencyKRW(item.krw) }}
</template>
<template v-slot:item.fee="{ item }">
{{ currencyKRW(item.fee) }}
</template>
<template v-slot:item.settlementAmount="{ item }">
{{ currencyKRW(item.settlementAmount) }}
</template>
<template v-slot:item.tax="{ item }">
{{ currencyKRW(item.tax) }}
</template>
<template v-slot:item.depositAmount="{ item }">
{{ currencyKRW(item.depositAmount) }}
</template>
<template v-slot:item.agentSettlementAmount="{ item }">
{{ currencyKRW(item.agentSettlementAmount) }}
</template>
</v-data-table>
<!-- 페이지네이션 -->
<div class="d-flex justify-center mt-2">
<v-pagination
v-model="page"
:length="totalPages"
:total-visible="7"
@input="onPageChange"
/>
</div>
</v-container>
</div>
</template>
<script>
import { getAgentContentDonationSettlementByCreator } from '@/api/agent'
export default {
name: 'AgentContentDonationSettlement',
props: { agentId: { type: [String, Number], required: true } },
data() {
const today = new Date()
const yyyy = today.getFullYear()
const mm = String(today.getMonth() + 1).padStart(2, '0')
const dd = String(today.getDate()).padStart(2, '0')
const firstDay = `${yyyy}-${mm}-01`
const endDay = `${yyyy}-${mm}-${dd}`
return {
startDateStr: firstDay,
endDateStr: endDay,
menuStart: false,
menuEnd: false,
page: 1,
pageSize: 20,
isLoading: false,
totalCount: 0,
totalPages: 1,
total: { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 },
items: [],
headers: [
{ text: '닉네임', value: 'creatorNickname', align: 'center' },
{ text: '건수', value: 'count', align: 'center', width: 100 },
{ text: '총 CAN', value: 'totalCan', align: 'center', width: 120 },
{ text: '원화', value: 'krw', align: 'center', width: 140 },
{ text: '수수료', value: 'fee', align: 'center', width: 120 },
{ text: '정산금액', value: 'settlementAmount', align: 'center', width: 140 },
{ text: '세금', value: 'tax', align: 'center', width: 120 },
{ text: '입금액', value: 'depositAmount', align: 'center', width: 140 },
{ text: '에이전트 정산', value: 'agentSettlementAmount', align: 'center', width: 160 },
]
}
},
computed: {
displayNickname() {
const q = (this.$route && this.$route.query) || {}
return q.nickname || '에이전트'
}
},
mounted() { this.fetchList() },
methods: {
numberFormat(n) { return new Intl.NumberFormat('ko-KR').format(Number(n || 0)) },
currencyKRW(n) { return new Intl.NumberFormat('ko-KR', { style: 'currency', currency: 'KRW', maximumFractionDigits: 0 }).format(Number(n || 0)) },
onSearch() { this.page = 1; this.fetchList() },
onPageChange() { this.fetchList() },
async fetchList() {
this.isLoading = true
try {
const res = await getAgentContentDonationSettlementByCreator(this.agentId, {
startDateStr: this.startDateStr,
endDateStr: this.endDateStr,
page: this.page,
size: this.pageSize,
})
let payload = res && res.data ? res.data : null
if (payload && payload.data && (!payload.items && !payload.totalCount)) payload = payload.data
const data = payload || { totalCount: 0, total: {}, items: [] }
this.totalCount = Number(data.totalCount || 0)
this.totalPages = Math.max(1, Math.ceil(this.totalCount / this.pageSize))
const defTotal = { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 }
this.total = Object.assign({}, defTotal, data.total || {})
this.items = Array.isArray(data.items) ? data.items : []
} catch (e) {
this.totalCount = 0
this.totalPages = 1
this.total = { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 }
this.items = []
} finally {
this.isLoading = false
}
}
}
}
</script>
<style scoped>
</style>
-254
View File
@@ -1,254 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-btn
icon
@click="$router.back()"
>
<v-icon>mdi-arrow-left</v-icon>
</v-btn>
<v-toolbar-title>{{ displayNickname }} 정산 상세 - 콘텐츠</v-toolbar-title>
<v-spacer />
</v-toolbar>
<v-container>
<!-- 필터 영역 -->
<v-row
class="mt-2 mb-2"
align="center"
justify="end"
>
<v-col
cols="12"
md="3"
>
<v-menu
v-model="menuStart"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-bind="attrs"
label="시작일"
readonly
dense
:value="startDateStr"
v-on="on"
/>
</template>
<v-date-picker
v-model="startDateStr"
scrollable
@input="menuStart = false"
/>
</v-menu>
</v-col>
<v-col
cols="12"
md="3"
>
<v-menu
v-model="menuEnd"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-bind="attrs"
label="종료일"
readonly
dense
:value="endDateStr"
v-on="on"
/>
</template>
<v-date-picker
v-model="endDateStr"
scrollable
@input="menuEnd = false"
/>
</v-menu>
</v-col>
<v-col
cols="12"
md="2"
>
<v-btn
color="primary"
:loading="isLoading"
@click="onSearch"
>
조회
</v-btn>
</v-col>
</v-row>
<!-- 테이블 영역 -->
<v-data-table
:headers="headers"
:items="items"
:loading="isLoading"
:items-per-page="pageSize"
class="elevation-1"
disable-pagination
hide-default-footer
>
<!-- 표 최상단 합계 행 -->
<template v-slot:body.prepend>
<tr>
<td class="text-center">
합계
</td>
<td class="text-center">
{{ numberFormat(total.count) }}
</td>
<td class="text-center">
{{ numberFormat(total.totalCan) }}
</td>
<td class="text-center">
{{ currencyKRW(total.krw) }}
</td>
<td class="text-center">
{{ currencyKRW(total.fee) }}
</td>
<td class="text-center">
{{ currencyKRW(total.settlementAmount) }}
</td>
<td class="text-center">
{{ currencyKRW(total.tax) }}
</td>
<td class="text-center">
{{ currencyKRW(total.depositAmount) }}
</td>
<td class="text-center">
{{ currencyKRW(total.agentSettlementAmount) }}
</td>
</tr>
</template>
<template v-slot:item.count="{ item }">
{{ numberFormat(item.count) }}
</template>
<template v-slot:item.totalCan="{ item }">
{{ numberFormat(item.totalCan) }}
</template>
<template v-slot:item.krw="{ item }">
{{ currencyKRW(item.krw) }}
</template>
<template v-slot:item.fee="{ item }">
{{ currencyKRW(item.fee) }}
</template>
<template v-slot:item.settlementAmount="{ item }">
{{ currencyKRW(item.settlementAmount) }}
</template>
<template v-slot:item.tax="{ item }">
{{ currencyKRW(item.tax) }}
</template>
<template v-slot:item.depositAmount="{ item }">
{{ currencyKRW(item.depositAmount) }}
</template>
<template v-slot:item.agentSettlementAmount="{ item }">
{{ currencyKRW(item.agentSettlementAmount) }}
</template>
</v-data-table>
<!-- 페이지네이션 -->
<div class="d-flex justify-center mt-2">
<v-pagination
v-model="page"
:length="totalPages"
:total-visible="7"
@input="onPageChange"
/>
</div>
</v-container>
</div>
</template>
<script>
import { getAgentContentSettlementByCreator } from '@/api/agent'
export default {
name: 'AgentContentSettlement',
props: { agentId: { type: [String, Number], required: true } },
data() {
const today = new Date()
const yyyy = today.getFullYear()
const mm = String(today.getMonth() + 1).padStart(2, '0')
const dd = String(today.getDate()).padStart(2, '0')
const firstDay = `${yyyy}-${mm}-01`
const endDay = `${yyyy}-${mm}-${dd}`
return {
startDateStr: firstDay,
endDateStr: endDay,
menuStart: false,
menuEnd: false,
page: 1,
pageSize: 20,
isLoading: false,
totalCount: 0,
totalPages: 1,
total: { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 },
items: [],
headers: [
{ text: '닉네임', value: 'creatorNickname', align: 'center' },
{ text: '건수', value: 'count', align: 'center', width: 100 },
{ text: '총 CAN', value: 'totalCan', align: 'center', width: 120 },
{ text: '원화', value: 'krw', align: 'center', width: 140 },
{ text: '수수료', value: 'fee', align: 'center', width: 120 },
{ text: '정산금액', value: 'settlementAmount', align: 'center', width: 140 },
{ text: '세금', value: 'tax', align: 'center', width: 120 },
{ text: '입금액', value: 'depositAmount', align: 'center', width: 140 },
{ text: '에이전트 정산', value: 'agentSettlementAmount', align: 'center', width: 160 },
]
}
},
computed: {
displayNickname() {
const q = (this.$route && this.$route.query) || {}
return q.nickname || '에이전트'
}
},
mounted() { this.fetchList() },
methods: {
numberFormat(n) { return new Intl.NumberFormat('ko-KR').format(Number(n || 0)) },
currencyKRW(n) { return new Intl.NumberFormat('ko-KR', { style: 'currency', currency: 'KRW', maximumFractionDigits: 0 }).format(Number(n || 0)) },
onSearch() { this.page = 1; this.fetchList() },
onPageChange() { this.fetchList() },
async fetchList() {
this.isLoading = true
try {
const res = await getAgentContentSettlementByCreator(this.agentId, {
startDateStr: this.startDateStr,
endDateStr: this.endDateStr,
page: this.page,
size: this.pageSize,
})
let payload = res && res.data ? res.data : null
if (payload && payload.data && (!payload.items && !payload.totalCount)) payload = payload.data
const data = payload || { totalCount: 0, total: {}, items: [] }
this.totalCount = Number(data.totalCount || 0)
this.totalPages = Math.max(1, Math.ceil(this.totalCount / this.pageSize))
const defTotal = { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 }
this.total = Object.assign({}, defTotal, data.total || {})
this.items = Array.isArray(data.items) ? data.items : []
} catch (e) {
this.totalCount = 0
this.totalPages = 1
this.total = { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 }
this.items = []
} finally {
this.isLoading = false
}
}
}
}
</script>
<style scoped>
</style>
-515
View File
@@ -1,515 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-btn
icon
@click="$router.back()"
>
<v-icon>mdi-arrow-left</v-icon>
</v-btn>
<v-toolbar-title>{{ (agentNickname || '-') + ' 소속 크리에이터' }}</v-toolbar-title>
<v-spacer />
<v-btn
color="#3bb9f1"
dark
:loading="assignDialog.loading"
@click="openAssignDialog"
>
소속 추가
</v-btn>
</v-toolbar>
<br>
<v-container>
<!-- 소속 크리에이터 목록 -->
<v-row>
<v-col>
<v-simple-table class="elevation-10">
<template>
<thead>
<tr>
<th class="text-center">
닉네임
</th>
<th class="text-center">
소속일
</th>
<th class="text-center">
관리
</th>
</tr>
</thead>
<tbody>
<tr v-if="is_loading">
<td
colspan="3"
class="text-center"
>
불러오는 중...
</td>
</tr>
<tr v-else-if="items.length === 0">
<td
colspan="3"
class="text-center"
>
소속된 크리에이터가 없습니다.
</td>
</tr>
<tr
v-for="row in items"
:key="row.creatorId"
>
<td class="text-center">
{{ row.creatorNickname }}
</td>
<td class="text-center">
{{ formatDateTime(row.assignedAt) }}
</td>
<td class="text-center">
<v-btn
text
small
color="error"
@click="openUnassignDialog(row)"
>
소속 해제
</v-btn>
</td>
</tr>
</tbody>
</template>
</v-simple-table>
</v-col>
</v-row>
<v-row
v-if="total_page > 1"
class="text-center"
>
<v-col>
<v-pagination
v-model="page"
:length="total_page"
circle
@input="fetchList"
/>
</v-col>
</v-row>
</v-container>
<!-- 소속 추가 다이얼로그 -->
<v-dialog
v-model="assignDialog.visible"
max-width="600px"
>
<v-card>
<v-card-title>크리에이터 소속 추가</v-card-title>
<v-card-text>
<v-autocomplete
v-model="assignDialog.selectedCreatorId"
:items="assignDialog.searchItems"
:loading="assignDialog.searchLoading"
:search-input.sync="assignDialog.searchQuery"
hide-no-data
hide-selected
clearable
label="크리에이터 검색"
item-text="creatorNickname"
item-value="creatorId"
@update:search-input="onSearchCreators"
/>
<v-menu
ref="menuAssignedDate"
v-model="assignDialog.menu"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-model="assignDialog.assignedDate"
label="소속 날짜(자정으로 처리)"
readonly
dense
v-bind="attrs"
clearable
v-on="on"
/>
</template>
<v-date-picker
v-model="assignDialog.assignedDate"
locale="ko-kr"
@input="$refs.menuAssignedDate.save(assignDialog.assignedDate)"
/>
</v-menu>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn
text
@click="closeAssignDialog"
>
취소
</v-btn>
<v-btn
color="primary"
:disabled="!canAssign"
:loading="assignDialog.loading"
@click="onAssign"
>
추가
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<!-- 소속 해제 다이얼로그 -->
<v-dialog
v-model="unassignDialog.visible"
max-width="600px"
>
<v-card>
<v-card-title>소속 해제</v-card-title>
<v-card-text>
<div class="mb-3">
크리에이터: <strong>{{ unassignDialog.target && unassignDialog.target.creatorNickname || '-' }}</strong>
</div>
<v-menu
ref="menuUnassignDate"
v-model="unassignDialog.menuDate"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-model="unassignDialog.date"
label="해제 날짜"
readonly
dense
v-bind="attrs"
clearable
v-on="on"
/>
</template>
<v-date-picker
v-model="unassignDialog.date"
locale="ko-kr"
@input="$refs.menuUnassignDate.save(unassignDialog.date)"
/>
</v-menu>
<v-menu
ref="menuUnassignTime"
v-model="unassignDialog.menuTime"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="290px"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-model="unassignDialog.time"
label="해제 시간(시:분)"
readonly
dense
v-bind="attrs"
clearable
v-on="on"
/>
</template>
<v-time-picker
v-if="unassignDialog.menuTime"
v-model="unassignDialog.time"
format="24hr"
full-width
@click:minute="$refs.menuUnassignTime.save(unassignDialog.time)"
/>
</v-menu>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn
text
@click="closeUnassignDialog"
>
취소
</v-btn>
<v-btn
color="error"
:disabled="!canUnassign"
:loading="unassignDialog.loading"
@click="onUnassign"
>
해제
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</div>
</template>
<script>
import {
getAgentAssignedCreatorList,
searchAdminAgentAssignableCreators,
assignAgentCreator,
removeAgentCreator
} from '@/api/agent'
export default {
name: 'AgentDetail',
props: {
agentId: {
type: [String, Number],
required: true
}
},
data() {
return {
agentNickname: this.$route && this.$route.query ? this.$route.query.nickname : '',
is_loading: false,
items: [],
totalCount: 0,
page: 1,
page_size: 20,
assignDialog: {
visible: false,
loading: false,
selectedCreatorId: null,
assignedDate: this.todayStr(),
menu: false,
searchQuery: '',
searchItems: [],
searchLoading: false,
// 디바운스 타이머 보관
searchDebounceTimer: null,
},
unassignDialog: {
visible: false,
loading: false,
target: null,
date: this.todayStr(),
time: this.nowTimeHHmm(),
menuDate: false,
menuTime: false,
},
}
},
computed: {
total_page() {
return Math.max(1, Math.ceil((this.totalCount || 0) / this.page_size))
},
canAssign() {
return !!(this.assignDialog.selectedCreatorId && this.assignDialog.assignedDate)
},
canUnassign() {
return !!(this.unassignDialog.target && this.unassignDialog.date && this.unassignDialog.time)
}
},
created() {
this.fetchList(1)
},
beforeDestroy() {
// 검색 디바운스 타이머 정리
if (this.assignDialog && this.assignDialog.searchDebounceTimer) {
clearTimeout(this.assignDialog.searchDebounceTimer)
this.assignDialog.searchDebounceTimer = null
}
},
methods: {
notifyError(message) {
// vuetify-dialog 플러그인을 통해 오류 노출
if (this.$dialog && this.$dialog.notify && this.$dialog.notify.error) {
this.$dialog.notify.error(message)
}
},
getErrorMessage(e) {
const fallback = '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.'
try {
if (!e) return fallback
// axios 형태의 에러 응답을 우선 사용
const msg = (e.response && e.response.data && (e.response.data.message || e.response.data.error || e.response.data.msg))
|| e.message
return msg || fallback
} catch (_) {
return fallback
}
},
async fetchList(page = this.page) {
if (this.is_loading) return
this.is_loading = true
try {
this.page = page
const res = await getAgentAssignedCreatorList(this.agentId, Math.max(1, this.page), this.page_size)
if (res && res.status === 200 && res.data && res.data.success === true) {
const data = (res.data && res.data.data) || { totalCount: 0, items: [] }
this.totalCount = data.totalCount || 0
this.items = Array.isArray(data.items) ? data.items : []
} else {
const msg = res && res.data && (res.data.message || res.data.error || res.data.msg)
this.notifyError(msg || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
}
} catch (e) {
this.totalCount = 0
this.items = []
this.notifyError(this.getErrorMessage(e))
} finally {
this.is_loading = false
}
},
openAssignDialog() {
this.assignDialog.visible = true
this.assignDialog.selectedCreatorId = null
this.assignDialog.assignedDate = this.todayStr()
this.assignDialog.searchQuery = ''
this.assignDialog.searchItems = []
},
closeAssignDialog() {
this.assignDialog.visible = false
// 다이얼로그 닫힐 때 디바운스 및 로딩 상태 초기화
if (this.assignDialog.searchDebounceTimer) {
clearTimeout(this.assignDialog.searchDebounceTimer)
this.assignDialog.searchDebounceTimer = null
}
this.assignDialog.searchLoading = false
},
onSearchCreators(q) {
const query = (q || '').trim()
this.assignDialog.searchQuery = query
// 기존 타이머가 있으면 취소
if (this.assignDialog.searchDebounceTimer) {
clearTimeout(this.assignDialog.searchDebounceTimer)
this.assignDialog.searchDebounceTimer = null
}
if (!query) {
// 검색어 없으면 결과/로딩 초기화
this.assignDialog.searchItems = []
this.assignDialog.searchLoading = false
return
}
// 디바운스: 300ms 이후 최신 검색어로 요청
this.assignDialog.searchDebounceTimer = setTimeout(async () => {
// 요청 직전 로딩 시작
this.assignDialog.searchLoading = true
const currentQuery = this.assignDialog.searchQuery
try {
const res = await searchAdminAgentAssignableCreators(currentQuery)
// 사용자가 그 사이에 검색어를 바꿨다면 이 응답은 무시
if (this.assignDialog.searchQuery !== currentQuery) return
if (res && res.status === 200 && res.data && res.data.success === true) {
const data = (res.data && res.data.data) || { totalCount: 0, items: [] }
this.assignDialog.searchItems = Array.isArray(data.items) ? data.items : []
} else {
this.assignDialog.searchItems = []
const msg = res && res.data && (res.data.message || res.data.error || res.data.msg)
this.notifyError(msg || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
}
} catch (e) {
// 에러 시에도 최신 검색어와 일치할 때만 처리
if (this.assignDialog.searchQuery === currentQuery) {
this.assignDialog.searchItems = []
this.notifyError(this.getErrorMessage(e))
}
} finally {
// 최신 검색어와 일치할 때만 로딩 해제
if (this.assignDialog.searchQuery === currentQuery) {
this.assignDialog.searchLoading = false
}
}
}, 300)
},
async onAssign() {
if (!this.canAssign) return
this.assignDialog.loading = true
try {
const assignedAt = `${this.assignDialog.assignedDate}T00:00:00`
const res = await assignAgentCreator({
agentId: Number(this.agentId),
creatorId: Number(this.assignDialog.selectedCreatorId),
assignedAt,
})
if (res && res.status === 200 && res.data && res.data.success === true) {
this.closeAssignDialog()
this.fetchList(1)
} else {
const msg = res && res.data && (res.data.message || res.data.error || res.data.msg)
this.notifyError(msg || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
}
} catch (e) {
this.notifyError(this.getErrorMessage(e))
} finally {
this.assignDialog.loading = false
}
},
openUnassignDialog(row) {
this.unassignDialog.visible = true
this.unassignDialog.loading = false
this.unassignDialog.target = row
this.unassignDialog.date = this.todayStr()
this.unassignDialog.time = this.nowTimeHHmm()
},
closeUnassignDialog() {
this.unassignDialog.visible = false
},
async onUnassign() {
if (!this.canUnassign) return
this.unassignDialog.loading = true
try {
const time = this.unassignDialog.time || '00:00'
const unassignedAt = `${this.unassignDialog.date}T${time}:00`
const res = await removeAgentCreator({
creatorId: Number(this.unassignDialog.target.creatorId),
unassignedAt,
})
if (res && res.status === 200 && res.data && res.data.success === true) {
this.closeUnassignDialog()
this.fetchList(this.page)
} else {
const msg = res && res.data && (res.data.message || res.data.error || res.data.msg)
this.notifyError(msg || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
}
} catch (e) {
this.notifyError(this.getErrorMessage(e))
} finally {
this.unassignDialog.loading = false
}
},
formatDateTime(s) {
if (!s) return '-'
try {
// s는 LocalDateTime 문자열(예: 2026-01-01T00:00:00)
const [d, t] = String(s).split('T')
const hhmm = (t || '').slice(0,5)
return `${d} ${hhmm}`
} catch (e) {
return s
}
},
todayStr() {
const d = new Date()
const mm = String(d.getMonth() + 1).padStart(2, '0')
const dd = String(d.getDate()).padStart(2, '0')
return `${d.getFullYear()}-${mm}-${dd}`
},
nowTimeHHmm() {
const d = new Date()
const hh = String(d.getHours()).padStart(2, '0')
const mm = String(d.getMinutes()).padStart(2, '0')
return `${hh}:${mm}`
}
}
}
</script>
-242
View File
@@ -1,242 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-spacer />
<v-toolbar-title>에이전트 리스트</v-toolbar-title>
<v-spacer />
</v-toolbar>
<br>
<v-container>
<v-row>
<v-col
cols="6"
class="text-left"
>
<strong>{{ settlementMonthLabel }}</strong>
</v-col>
<v-col
cols="6"
class="text-right"
>
총 에이전트 수: <strong>{{ totalCount | numberFormat }}</strong>
</v-col>
</v-row>
<v-row>
<v-col>
<v-simple-table class="elevation-10">
<template>
<thead>
<tr>
<th class="text-center">
에이전트 닉네임
</th>
<th class="text-center">
소속 크리에이터 수
</th>
<th class="text-center">
라이브
</th>
<th class="text-center">
콘텐츠
</th>
<th class="text-center">
커뮤니티
</th>
<th class="text-center">
콘텐츠 후원
</th>
<th class="text-center">
채널 후원
</th>
<th class="text-center">
합계
</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in agentList"
:key="item.agentId"
>
<td
class="link"
@click="goAgentDetail(item)"
>
{{ item.agentNickname }}
</td>
<td class="text-center">
{{ item.assignedCreatorCount | numberFormat }}
</td>
<td
class="text-center clickable"
@click="goSettlement(item, 'live')"
>
{{ formatCurrency(item.liveAgentSettlementAmount) }}
</td>
<td
class="text-center clickable"
@click="goSettlement(item, 'content')"
>
{{ formatCurrency(item.contentAgentSettlementAmount) }}
</td>
<td
class="text-center clickable"
@click="goSettlement(item, 'community')"
>
{{ formatCurrency(item.communityAgentSettlementAmount) }}
</td>
<td
class="text-center clickable"
@click="goSettlement(item, 'content-donation')"
>
{{ formatCurrency(item.contentDonationAgentSettlementAmount) }}
</td>
<td
class="text-center clickable"
@click="goSettlement(item, 'channel-donation')"
>
{{ formatCurrency(item.channelDonationAgentSettlementAmount) }}
</td>
<td class="text-center">
{{ formatCurrency(totalAmount(item)) }}
</td>
</tr>
</tbody>
</template>
</v-simple-table>
</v-col>
</v-row>
<!-- 페이지네이션은 서버 지원 시 활성화
<v-row class="text-center">
<v-col>
<v-pagination
v-model="page"
:length="total_page"
circle
@input="fetchList"
/>
</v-col>
</v-row>
-->
</v-container>
</div>
</template>
<script>
import { getAgentList } from '@/api/agent'
export default {
name: 'AgentList',
filters: {
numberFormat(v) {
if (v === null || v === undefined) return '-'
try {
return new Intl.NumberFormat('ko-KR').format(v)
} catch (e) {
return v
}
}
},
data() {
return {
agentList: [],
totalCount: 0,
// 페이지네이션(필요 시)
page: 1,
total_page: 1,
page_size: 20,
is_loading: false,
}
},
computed: {
settlementMonthLabel() {
const now = new Date()
const month = now.getMonth() + 1 // 1~12
return `${month}월 정산 내역`
}
},
created() {
this.fetchList()
},
methods: {
async fetchList() {
if (this.is_loading) return
this.is_loading = true
try {
const res = await getAgentList(/* this.page, this.page_size */)
// 일부 API는 { data: { totalCount, items } } 형태로 한 번 더 래핑됨을 대비
let payload = (res && res.data) ? res.data : null
if (payload && payload.data && (!payload.items && !payload.totalCount)) {
payload = payload.data
}
const data = payload || { totalCount: 0, items: [] }
this.totalCount = data.totalCount || 0
this.agentList = Array.isArray(data.items) ? data.items : []
// 서버가 페이지네이션 정보를 주면 설정하도록 남김
this.total_page = Math.max(1, Math.ceil(this.totalCount / this.page_size))
} catch (e) {
this.totalCount = 0
this.agentList = []
} finally {
this.is_loading = false
}
},
formatCurrency(n) {
const num = Number(n || 0)
return new Intl.NumberFormat('ko-KR', { style: 'currency', currency: 'KRW', maximumFractionDigits: 0 }).format(num)
},
totalAmount(item) {
const {
liveAgentSettlementAmount = 0,
contentAgentSettlementAmount = 0,
communityAgentSettlementAmount = 0,
contentDonationAgentSettlementAmount = 0,
channelDonationAgentSettlementAmount = 0,
} = item || {}
return (
(liveAgentSettlementAmount || 0) +
(contentAgentSettlementAmount || 0) +
(communityAgentSettlementAmount || 0) +
(contentDonationAgentSettlementAmount || 0) +
(channelDonationAgentSettlementAmount || 0)
)
},
goAgentDetail(item) {
this.$router.push({ name: 'AgentDetail', params: { agentId: item.agentId }, query: { nickname: item.agentNickname } })
},
goSettlement(item, type) {
const id = item.agentId
const nameMap = {
'live': 'AgentSettlementLive',
'content': 'AgentSettlementContent',
'community': 'AgentSettlementCommunity',
'content-donation': 'AgentSettlementContentDonation',
'channel-donation': 'AgentSettlementChannelDonation',
}
const name = nameMap[type]
if (!name) return
this.$router.push({ name, params: { agentId: id }, query: { nickname: item.agentNickname } })
}
}
}
</script>
<style scoped>
.link {
color: #3f51b5;
cursor: pointer;
text-decoration: underline;
}
.clickable {
cursor: pointer;
}
/* 테이블 셀 가운데 정렬 */
table th,
table td {
text-align: center !important;
}
</style>
-290
View File
@@ -1,290 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-btn
icon
@click="$router.back()"
>
<v-icon>mdi-arrow-left</v-icon>
</v-btn>
<v-toolbar-title>{{ displayNickname }} 정산 상세 - 라이브</v-toolbar-title>
<v-spacer />
</v-toolbar>
<v-container>
<!-- 필터 영역 -->
<v-row
class="mt-2 mb-2"
align="center"
justify="end"
>
<v-col
cols="12"
md="3"
>
<v-menu
v-model="menuStart"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-bind="attrs"
label="시작일"
readonly
dense
:value="startDateStr"
v-on="on"
/>
</template>
<v-date-picker
v-model="startDateStr"
scrollable
@input="menuStart = false"
/>
</v-menu>
</v-col>
<v-col
cols="12"
md="3"
>
<v-menu
v-model="menuEnd"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-bind="attrs"
label="종료일"
readonly
dense
:value="endDateStr"
v-on="on"
/>
</template>
<v-date-picker
v-model="endDateStr"
scrollable
@input="menuEnd = false"
/>
</v-menu>
</v-col>
<v-col
cols="12"
md="2"
>
<v-btn
color="primary"
:loading="isLoading"
@click="onSearch"
>
조회
</v-btn>
</v-col>
</v-row>
<!-- 테이블 영역 -->
<v-data-table
:headers="headers"
:items="items"
:loading="isLoading"
:items-per-page="pageSize"
class="elevation-1"
disable-pagination
hide-default-footer
>
<!-- 표 최상단 합계 행 -->
<template v-slot:body.prepend>
<tr>
<td class="text-center">
합계
</td>
<td class="text-center">
{{ numberFormat(total.count) }}
</td>
<td class="text-center">
{{ numberFormat(total.totalCan) }}
</td>
<td class="text-center">
{{ currencyKRW(total.krw) }}
</td>
<td class="text-center">
{{ currencyKRW(total.fee) }}
</td>
<td class="text-center">
{{ currencyKRW(total.settlementAmount) }}
</td>
<td class="text-center">
{{ currencyKRW(total.tax) }}
</td>
<td class="text-center">
{{ currencyKRW(total.depositAmount) }}
</td>
<td class="text-center">
{{ currencyKRW(total.agentSettlementAmount) }}
</td>
</tr>
</template>
<template v-slot:item.count="{ item }">
{{ numberFormat(item.count) }}
</template>
<template v-slot:item.totalCan="{ item }">
{{ numberFormat(item.totalCan) }}
</template>
<template v-slot:item.krw="{ item }">
{{ currencyKRW(item.krw) }}
</template>
<template v-slot:item.fee="{ item }">
{{ currencyKRW(item.fee) }}
</template>
<template v-slot:item.settlementAmount="{ item }">
{{ currencyKRW(item.settlementAmount) }}
</template>
<template v-slot:item.tax="{ item }">
{{ currencyKRW(item.tax) }}
</template>
<template v-slot:item.depositAmount="{ item }">
{{ currencyKRW(item.depositAmount) }}
</template>
<template v-slot:item.agentSettlementAmount="{ item }">
{{ currencyKRW(item.agentSettlementAmount) }}
</template>
</v-data-table>
<!-- 페이지네이션 -->
<div class="d-flex justify-center mt-2">
<v-pagination
v-model="page"
:length="totalPages"
:total-visible="7"
@input="onPageChange"
/>
</div>
</v-container>
</div>
</template>
<script>
import { getAgentLiveSettlementByCreator } from '@/api/agent'
export default {
name: 'AgentLiveSettlement',
props: {
agentId: { type: [String, Number], required: true }
},
data() {
const today = new Date()
const yyyy = today.getFullYear()
const mm = String(today.getMonth() + 1).padStart(2, '0')
const dd = String(today.getDate()).padStart(2, '0')
const firstDay = `${yyyy}-${mm}-01`
const endDay = `${yyyy}-${mm}-${dd}`
return {
// 필터
startDateStr: firstDay,
endDateStr: endDay,
menuStart: false,
menuEnd: false,
page: 1,
pageSize: 20,
// 데이터
isLoading: false,
totalCount: 0,
totalPages: 1,
total: {
count: 0,
totalCan: 0,
krw: 0,
fee: 0,
settlementAmount: 0,
tax: 0,
depositAmount: 0,
agentSettlementAmount: 0
},
items: [],
headers: [
{ text: '닉네임', value: 'creatorNickname', align: 'center' },
{ text: '건수', value: 'count', align: 'center', width: 100 },
{ text: '총 CAN', value: 'totalCan', align: 'center', width: 120 },
{ text: '원화', value: 'krw', align: 'center', width: 140 },
{ text: '수수료', value: 'fee', align: 'center', width: 120 },
{ text: '정산금액', value: 'settlementAmount', align: 'center', width: 140 },
{ text: '세금', value: 'tax', align: 'center', width: 120 },
{ text: '입금액', value: 'depositAmount', align: 'center', width: 140 },
{ text: '에이전트 정산', value: 'agentSettlementAmount', align: 'center', width: 160 },
]
}
},
computed: {
displayNickname() {
const q = (this.$route && this.$route.query) || {}
return q.nickname || '에이전트'
}
},
mounted() {
this.fetchList()
},
methods: {
numberFormat(n) {
const v = Number(n || 0)
return new Intl.NumberFormat('ko-KR').format(v)
},
currencyKRW(n) {
const v = Number(n || 0)
return new Intl.NumberFormat('ko-KR', { style: 'currency', currency: 'KRW', maximumFractionDigits: 0 }).format(v)
},
onSearch() {
this.page = 1
this.fetchList()
},
onPageChange() {
this.fetchList()
},
async fetchList() {
this.isLoading = true
try {
const res = await getAgentLiveSettlementByCreator(this.agentId, {
startDateStr: this.startDateStr,
endDateStr: this.endDateStr,
// UI는 1-based, API 유틸이 0-based로 변환함
page: this.page,
size: this.pageSize,
})
// 일부 API가 { data: {...} } 래핑일 수 있으므로 방어적으로 파싱
let payload = res && res.data ? res.data : null
if (payload && payload.data && (!payload.items && !payload.totalCount)) {
payload = payload.data
}
const data = payload || { totalCount: 0, total: {}, items: [] }
this.totalCount = Number(data.totalCount || 0)
this.totalPages = Math.max(1, Math.ceil(this.totalCount / this.pageSize))
const defTotal = {
count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0
}
this.total = Object.assign({}, defTotal, data.total || {})
this.items = Array.isArray(data.items) ? data.items : []
} catch (e) {
this.totalCount = 0
this.totalPages = 1
this.total = { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 }
this.items = []
} finally {
this.isLoading = false
}
}
}
}
</script>
<style scoped>
</style>
-339
View File
@@ -1,339 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-spacer />
<v-toolbar-title>에이전트 정산 비율</v-toolbar-title>
<v-spacer />
<v-btn
color="primary"
dark
@click="onClickCreate"
>
에이전트 비율 추가
</v-btn>
</v-toolbar>
<br>
<v-container>
<v-row>
<v-col
cols="12"
class="text-right"
>
총 에이전트 수: <strong>{{ totalCount | numberFormat }}</strong>
</v-col>
</v-row>
<v-row>
<v-col>
<v-simple-table class="elevation-10">
<template>
<thead>
<tr>
<th class="text-center">
에이전트 닉네임
</th>
<th class="text-center">
정산 비율(%)
</th>
<th class="text-center">
관리
</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in items"
:key="item.memberId"
>
<td class="text-center">
{{ item.nickname }}
</td>
<td class="text-center">
{{ (item.current && item.current.settlementRatio != null) ? item.current.settlementRatio : '-' }}
</td>
<td class="text-center">
<v-btn
small
outlined
color="primary"
@click="onClickEdit(item)"
>
수정
</v-btn>
</td>
</tr>
<tr v-if="!loading && (!items || items.length===0)">
<td
colspan="3"
class="text-center grey--text"
>
데이터가 없습니다.
</td>
</tr>
</tbody>
</template>
</v-simple-table>
</v-col>
</v-row>
</v-container>
<!-- 등록/수정 팝업 -->
<v-dialog
v-model="dialog"
max-width="560px"
persistent
>
<v-card>
<v-card-title class="headline">
{{ isEdit ? '에이전트 비율 수정' : '에이전트 비율 등록' }}
</v-card-title>
<v-card-text>
<v-form
ref="form"
v-model="formValid"
>
<!-- 에이전트 선택/표시 -->
<div v-if="!isEdit">
<v-autocomplete
v-model="selectedAgent"
:items="agentSearchItems"
:loading="agentSearchLoading"
:search-input.sync="agentSearchQuery"
hide-selected
hide-no-data
label="에이전트 닉네임 검색"
item-text="nickname"
item-value="id"
return-object
clearable
:rules="[v=>!!v || '에이전트를 선택하세요.']"
@update:search-input="onSearchAgent"
/>
</div>
<div v-else>
<v-text-field
v-model="form.nickname"
label="에이전트"
disabled
/>
</div>
<v-text-field
v-model.number="form.settlementRatio"
label="정산 비율(%)"
type="number"
min="0"
max="100"
:rules="ratioRules"
required
/>
<v-text-field
v-model="form.effectiveFrom"
label="적용 시작 날짜"
type="date"
:rules="[v=>!!v || '적용 시작 날짜를 선택하세요.']"
required
/>
</v-form>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn
text
:disabled="submitting"
@click="closeDialog"
>
취소
</v-btn>
<v-btn
color="primary"
dark
:loading="submitting"
:disabled="!formValid || submitting"
@click="onSubmit"
>
등록
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</div>
</template>
<script>
import {
getAgentSettlementRatioList,
createAgentSettlementRatio,
updateAgentSettlementRatio,
searchAgentByNickname
} from '@/api/agent'
export default {
name: 'AgentSettlementRatio',
filters: {
numberFormat(v) {
if (v === null || v === undefined) return '-'
try {
return new Intl.NumberFormat('ko-KR').format(v)
} catch (e) {
return v
}
}
},
data() {
return {
loading: false,
items: [],
totalCount: 0,
dialog: false,
isEdit: false,
submitting: false,
formValid: false,
form: {
memberId: null,
nickname: '',
settlementRatio: null,
effectiveFrom: ''
},
ratioRules: [
v => (v !== null && v !== '' && !isNaN(v)) || '숫자를 입력하세요.',
v => (v >= 0 && v <= 100) || '0~100 사이 값이어야 합니다.'
],
// 에이전트 검색
selectedAgent: null,
agentSearchQuery: '',
agentSearchItems: [],
agentSearchLoading: false,
}
},
created() {
this.fetchList()
},
methods: {
async fetchList() {
if (this.loading) return
this.loading = true
try {
const res = await getAgentSettlementRatioList()
let payload = (res && res.data) ? res.data : null
if (payload && payload.data && (!payload.items && !payload.totalCount)) {
payload = payload.data
}
const data = payload || { totalCount: 0, items: [] }
this.totalCount = data.totalCount || 0
this.items = Array.isArray(data.items) ? data.items : []
} catch (e) {
this.totalCount = 0
this.items = []
} finally {
this.loading = false
}
},
onClickCreate() {
this.isEdit = false
this.resetForm()
this.dialog = true
},
onClickEdit(item) {
this.isEdit = true
this.resetForm()
this.form.memberId = item.memberId
this.form.nickname = item.nickname
this.form.settlementRatio = item && item.current ? item.current.settlementRatio : null
this.form.effectiveFrom = this.defaultDateTimeLocal()
this.dialog = true
},
closeDialog() {
if (this.submitting) return
this.dialog = false
},
resetForm() {
this.submitting = false
this.formValid = false
this.form = {
memberId: null,
nickname: '',
settlementRatio: null,
effectiveFrom: this.defaultDateTimeLocal()
}
this.selectedAgent = null
this.agentSearchQuery = ''
this.agentSearchItems = []
if (this.$refs.form && this.$refs.form.resetValidation) this.$refs.form.resetValidation()
},
defaultDateTimeLocal() {
// 날짜만 선택하도록 기본값은 오늘 날짜 (YYYY-MM-DD)
const d = new Date()
const pad = n => n.toString().padStart(2, '0')
const yyyy = d.getFullYear()
const MM = pad(d.getMonth() + 1)
const dd = pad(d.getDate())
return `${yyyy}-${MM}-${dd}`
},
toLocalDateTimeString(v) {
// 입력 타입이 date이므로 "YYYY-MM-DD"를 받아 "YYYY-MM-DDT00:00:00"로 변환
// 과거 호환: datetime-local("YYYY-MM-DDTHH:mm")가 들어오면 초를 붙여 반환
if (!v) return null
if (v.length === 10) return `${v}T00:00:00`
if (v.length === 16) return `${v}:00`
// 이미 초까지 포함된 형태면 그대로 사용
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$/.test(v)) {
return v.length === 16 ? `${v}:00` : v
}
return `${v}T00:00:00`
},
async onSubmit() {
if (this.submitting) return
const ok = await this.$refs.form.validate?.()
if (!ok) return
try {
this.submitting = true
const payload = {
memberId: this.isEdit ? this.form.memberId : (this.selectedAgent && this.selectedAgent.id),
settlementRatio: Number(this.form.settlementRatio),
effectiveFrom: this.toLocalDateTimeString(this.form.effectiveFrom)
}
if (!payload.memberId) {
this.submitting = false
return
}
if (this.isEdit) {
await updateAgentSettlementRatio(payload)
} else {
await createAgentSettlementRatio(payload)
}
this.dialog = false
await this.fetchList()
} catch (e) {
// 실패 시에도 버튼 로딩 해제
} finally {
this.submitting = false
}
},
async onSearchAgent(q) {
if (!q) {
this.agentSearchItems = []
return
}
this.agentSearchLoading = true
try {
const list = await searchAgentByNickname(q)
this.agentSearchItems = Array.isArray(list) ? list : []
} catch (e) {
this.agentSearchItems = []
} finally {
this.agentSearchLoading = false
}
}
}
}
</script>
<style scoped>
.clickable { cursor: pointer; }
.link { color: #1976d2; cursor: pointer; text-decoration: underline; }
</style>
@@ -1,267 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-spacer />
<v-toolbar-title>채널 후원 정산</v-toolbar-title>
<v-spacer />
</v-toolbar>
<br>
<v-container>
<v-row>
<v-col cols="2">
<datetime
v-model="start_date"
class="datepicker"
format="YYYY-MM-DD"
/>
</v-col>
<v-col cols="1">
~
</v-col>
<v-col cols="2">
<datetime
v-model="end_date"
class="datepicker"
format="YYYY-MM-DD"
/>
</v-col>
<v-col cols="1" />
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
dark
depressed
@click="getCalculateChannelDonationByDate"
>
조회
</v-btn>
</v-col>
<v-spacer />
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
dark
depressed
@click="downloadExcel"
>
엑셀 다운로드
</v-btn>
</v-col>
</v-row>
<v-row>
<v-col>
<v-data-table
:headers="headers"
:items="items"
:loading="is_loading"
:items-per-page="-1"
class="elevation-1"
hide-default-footer
>
<template slot="body.prepend">
<tr v-if="total">
<td colspan="2">
합계
</td>
<td class="text-center">
{{ total.count.toLocaleString() }} 건
</td>
<td class="text-center">
{{ total.totalCan.toLocaleString() }} 캔
</td>
<td class="text-center">
{{ total.krw.toLocaleString() }} 원
</td>
<td class="text-center">
{{ total.fee.toLocaleString() }} 원
</td>
<td class="text-center">
{{ total.settlementAmount.toLocaleString() }} 원
</td>
<td class="text-center">
{{ total.withholdingTax.toLocaleString() }} 원
</td>
<td class="text-center">
{{ total.depositAmount.toLocaleString() }} 원
</td>
</tr>
</template>
<template v-slot:item.date="{ item }">
{{ item.date }}
</template>
<template v-slot:item.creator="{ item }">
{{ item.creator }}
</template>
<template v-slot:item.count="{ item }">
{{ item.count.toLocaleString() }} 건
</template>
<template v-slot:item.totalCan="{ item }">
{{ item.totalCan.toLocaleString() }} 캔
</template>
<template v-slot:item.krw="{ item }">
{{ item.krw.toLocaleString() }} 원
</template>
<template v-slot:item.fee="{ item }">
{{ item.fee.toLocaleString() }} 원
</template>
<template v-slot:item.settlementAmount="{ item }">
{{ item.settlementAmount.toLocaleString() }} 원
</template>
<template v-slot:item.withholdingTax="{ item }">
{{ item.withholdingTax.toLocaleString() }} 원
</template>
<template v-slot:item.depositAmount="{ item }">
{{ item.depositAmount.toLocaleString() }} 원
</template>
</v-data-table>
</v-col>
</v-row>
<v-row>
<v-col>
<v-pagination
v-model="page"
:length="total_page"
:total-visible="7"
@input="next"
/>
</v-col>
</v-row>
</v-container>
</div>
</template>
<script>
import * as api from '@/api/calculate'
import datetime from 'vuejs-datetimepicker'
export default {
name: 'CalculateChannelDonation',
components: {
datetime
},
data() {
return {
start_date: '',
end_date: '',
is_loading: false,
items: [],
total: null,
page: 1,
page_size: 20,
total_page: 1,
headers: [
{ text: '날짜', align: 'center', sortable: false, value: 'date' },
{ text: '크리에이터', align: 'center', sortable: false, value: 'creator' },
{ text: '건수', align: 'center', sortable: false, value: 'count' },
{ text: '캔', align: 'center', sortable: false, value: 'totalCan' },
{ text: '원화', align: 'center', sortable: false, value: 'krw' },
{ text: '수수료(6.6%)', align: 'center', sortable: false, value: 'fee' },
{ text: '정산금액', align: 'center', sortable: false, value: 'settlementAmount' },
{ text: '원천세(3.3%)', align: 'center', sortable: false, value: 'withholdingTax' },
{ text: '입금액', align: 'center', sortable: false, value: 'depositAmount' }
]
}
},
async created() {
const date = new Date()
const firstDate = new Date(date.getFullYear(), date.getMonth(), 1)
const lastDate = new Date(date.getFullYear(), date.getMonth() + 1, 0)
this.start_date = this.formatDate(firstDate)
this.end_date = this.formatDate(lastDate)
await this.getCalculateChannelDonationByDate()
},
methods: {
formatDate(date) {
const year = date.getFullYear()
const month = ('0' + (date.getMonth() + 1)).slice(-2)
const day = ('0' + date.getDate()).slice(-2)
return `${year}-${month}-${day}`
},
notifyError(message) {
this.$dialog.notify.error(message)
},
async next() {
await this.getCalculateChannelDonationByDate()
},
async getCalculateChannelDonationByDate() {
this.is_loading = true
try {
const res = await api.getCalculateChannelDonationByDate(
this.start_date.substring(0, 10),
this.end_date.substring(0, 10),
this.page,
this.page_size
)
if (res.status === 200 && res.data.success === true) {
const data = res.data.data
this.items = data.items
this.total = data.total
this.total_page = Math.ceil(data.totalCount / this.page_size) || 1
} else {
this.notifyError(res.data.message || '데이터를 불러오는 중 오류가 발생했습니다.')
}
} catch (e) {
this.notifyError('서버와의 통신 중 오류가 발생했습니다.')
} finally {
this.is_loading = false
}
},
async downloadExcel() {
try {
const res = await api.downloadCalculateChannelDonationByDateExcel(
this.start_date.substring(0, 10),
this.end_date.substring(0, 10)
)
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', '채널후원정산.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch (e) {
this.notifyError('엑셀 다운로드 중 오류가 발생했습니다.')
}
}
}
}
</script>
<style scoped>
.datepicker {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
</style>
@@ -1,262 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-spacer />
<v-toolbar-title>크리에이터별 채널 후원 정산</v-toolbar-title>
<v-spacer />
</v-toolbar>
<br>
<v-container>
<v-row>
<v-col cols="2">
<datetime
v-model="start_date"
class="datepicker"
format="YYYY-MM-DD"
/>
</v-col>
<v-col cols="1">
~
</v-col>
<v-col cols="2">
<datetime
v-model="end_date"
class="datepicker"
format="YYYY-MM-DD"
/>
</v-col>
<v-col cols="1" />
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
dark
depressed
@click="getCalculateChannelDonationByCreator"
>
조회
</v-btn>
</v-col>
<v-spacer />
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
dark
depressed
@click="downloadExcel"
>
엑셀 다운로드
</v-btn>
</v-col>
</v-row>
<v-row>
<v-col>
<v-data-table
:headers="headers"
:items="items"
:loading="is_loading"
:items-per-page="-1"
class="elevation-1"
hide-default-footer
>
<template slot="body.prepend">
<tr v-if="total">
<td>
합계
</td>
<td class="text-center">
{{ total.count.toLocaleString() }} 건
</td>
<td class="text-center">
{{ total.totalCan.toLocaleString() }} 캔
</td>
<td class="text-center">
{{ total.krw.toLocaleString() }} 원
</td>
<td class="text-center">
{{ total.fee.toLocaleString() }} 원
</td>
<td class="text-center">
{{ total.settlementAmount.toLocaleString() }} 원
</td>
<td class="text-center">
{{ total.withholdingTax.toLocaleString() }} 원
</td>
<td class="text-center">
{{ total.depositAmount.toLocaleString() }} 원
</td>
</tr>
</template>
<template v-slot:item.creator="{ item }">
{{ item.creator }}
</template>
<template v-slot:item.count="{ item }">
{{ item.count.toLocaleString() }} 건
</template>
<template v-slot:item.totalCan="{ item }">
{{ item.totalCan.toLocaleString() }} 캔
</template>
<template v-slot:item.krw="{ item }">
{{ item.krw.toLocaleString() }} 원
</template>
<template v-slot:item.fee="{ item }">
{{ item.fee.toLocaleString() }} 원
</template>
<template v-slot:item.settlementAmount="{ item }">
{{ item.settlementAmount.toLocaleString() }} 원
</template>
<template v-slot:item.withholdingTax="{ item }">
{{ item.withholdingTax.toLocaleString() }} 원
</template>
<template v-slot:item.depositAmount="{ item }">
{{ item.depositAmount.toLocaleString() }} 원
</template>
</v-data-table>
</v-col>
</v-row>
<v-row>
<v-col>
<v-pagination
v-model="page"
:length="total_page"
:total-visible="7"
@input="next"
/>
</v-col>
</v-row>
</v-container>
</div>
</template>
<script>
import * as api from '@/api/calculate'
import datetime from 'vuejs-datetimepicker'
export default {
name: 'CalculateChannelDonationByCreator',
components: {
datetime
},
data() {
return {
start_date: '',
end_date: '',
is_loading: false,
items: [],
total: null,
page: 1,
page_size: 20,
total_page: 1,
headers: [
{ text: '크리에이터', align: 'center', sortable: false, value: 'creator' },
{ text: '건수', align: 'center', sortable: false, value: 'count' },
{ text: '캔', align: 'center', sortable: false, value: 'totalCan' },
{ text: '원화', align: 'center', sortable: false, value: 'krw' },
{ text: '수수료(6.6%)', align: 'center', sortable: false, value: 'fee' },
{ text: '정산금액', align: 'center', sortable: false, value: 'settlementAmount' },
{ text: '원천세(3.3%)', align: 'center', sortable: false, value: 'withholdingTax' },
{ text: '입금액', align: 'center', sortable: false, value: 'depositAmount' }
]
}
},
async created() {
const date = new Date()
const firstDate = new Date(date.getFullYear(), date.getMonth(), 1)
const lastDate = new Date(date.getFullYear(), date.getMonth() + 1, 0)
this.start_date = this.formatDate(firstDate)
this.end_date = this.formatDate(lastDate)
await this.getCalculateChannelDonationByCreator()
},
methods: {
formatDate(date) {
const year = date.getFullYear()
const month = ('0' + (date.getMonth() + 1)).slice(-2)
const day = ('0' + date.getDate()).slice(-2)
return `${year}-${month}-${day}`
},
notifyError(message) {
this.$dialog.notify.error(message)
},
async next() {
await this.getCalculateChannelDonationByCreator()
},
async getCalculateChannelDonationByCreator() {
this.is_loading = true
try {
const res = await api.getCalculateChannelDonationByCreator(
this.start_date.substring(0, 10),
this.end_date.substring(0, 10),
this.page,
this.page_size
)
if (res.status === 200 && res.data.success === true) {
const data = res.data.data
this.items = data.items
this.total = data.total
this.total_page = Math.ceil(data.totalCount / this.page_size) || 1
} else {
this.notifyError(res.data.message || '데이터를 불러오는 중 오류가 발생했습니다.')
}
} catch (e) {
this.notifyError('서버와의 통신 중 오류가 발생했습니다.')
} finally {
this.is_loading = false
}
},
async downloadExcel() {
try {
const res = await api.downloadCalculateChannelDonationByCreatorExcel(
this.start_date.substring(0, 10),
this.end_date.substring(0, 10)
)
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', '크리에이터별_채널후원정산.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch (e) {
this.notifyError('엑셀 다운로드 중 오류가 발생했습니다.')
}
}
}
}
</script>
<style scoped>
.datepicker {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
</style>
@@ -47,15 +47,22 @@
<v-spacer />
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
dark
depressed
@click="downloadExcel"
<vue-excel-xlsx
:data="items"
:columns="columns"
:file-name="'정산'"
:file-type="'xlsx'"
:sheet-name="'정산'"
>
엑셀 다운로드
</v-btn>
<v-btn
block
color="#3bb9f1"
dark
depressed
>
엑셀 다운로드
</v-btn>
</vue-excel-xlsx>
</v-col>
</v-row>
@@ -149,6 +156,40 @@ export default {
page_size: 20,
total_page: 0,
items: [],
columns: [
{
label: "이메일",
field: "email",
},
{
label: "크리에이터",
field: "nickname",
},
{
label: "합계(캔)",
field: "totalCan",
},
{
label: "원화",
field: "totalKrw",
},
{
label: "결제수수료(6.6%)",
field: "paymentFee",
},
{
label: "정산금액",
field: "settlementAmount",
},
{
label: "원천세(3.3%)",
field: "tax",
},
{
label: "입금액",
field: "depositAmount",
},
],
headers: [
{
text: '이메일',
@@ -268,21 +309,6 @@ export default {
} finally {
this.is_loading = false
}
},
async downloadExcel() {
try {
const res = await api.downloadCalculateCommunityByCreatorExcel(this.start_date, this.end_date)
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', '크리에이터별_커뮤니티정산.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch (e) {
this.notifyError('엑셀 다운로드 중 오류가 발생했습니다.')
}
}
}
}
+62 -24
View File
@@ -35,7 +35,7 @@
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
color="#9970ff"
dark
depressed
@click="getCalculateCommunityPost"
@@ -47,15 +47,22 @@
<v-spacer />
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
dark
depressed
@click="downloadExcel"
<vue-excel-xlsx
:data="items"
:columns="columns"
:file-name="'커뮤니티-정산'"
:file-type="'xlsx'"
:sheet-name="'커뮤니티-정산'"
>
엑셀 다운로드
</v-btn>
<v-btn
block
color="#9970ff"
dark
depressed
>
엑셀 다운로드
</v-btn>
</vue-excel-xlsx>
</v-col>
</v-row>
<v-row>
@@ -129,6 +136,52 @@ export default {
page_size: 20,
total_page: 0,
items: [],
columns: [
{
label: '날짜',
field: 'date',
},
{
label: '크리에이터',
field: 'nickname',
},
{
label: '내용(앞 10글자)',
field: 'title'
},
{
label: '판매금액(캔)',
field: 'can',
},
{
label: '구매유저수',
field: 'numberOfPurchase',
},
{
label: '합계(캔)',
field: 'totalCan',
},
{
label: '원화',
field: 'totalKrw',
},
{
label: '수수료\n(6.6%)',
field: 'paymentFee',
},
{
label: '정산금액',
field: 'settlementAmount',
},
{
label: '원천세\n(3.3%)',
field: 'tax',
},
{
label: '입금액',
field: 'depositAmount',
}
],
headers: [
{
text: '날짜',
@@ -256,21 +309,6 @@ export default {
this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
this.is_loading = false
}
},
async downloadExcel() {
try {
const res = await api.downloadCalculateCommunityPostExcel(this.start_date, this.end_date)
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', '커뮤니티-정산.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch (e) {
this.notifyError('엑셀 다운로드 중 오류가 발생했습니다.')
}
}
}
}
+72 -44
View File
@@ -35,7 +35,7 @@
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
color="#9970ff"
dark
depressed
@click="getCalculateContent"
@@ -48,15 +48,22 @@
<v-spacer />
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
dark
depressed
@click="downloadExcel"
<vue-excel-xlsx
:data="items"
:columns="columns"
:file-name="'정산'"
:file-type="'xlsx'"
:sheet-name="'정산'"
>
엑셀 다운로드
</v-btn>
<v-btn
block
color="#9970ff"
dark
depressed
>
엑셀 다운로드
</v-btn>
</vue-excel-xlsx>
</v-col>
</v-row>
<v-row>
@@ -119,16 +126,6 @@
</v-data-table>
</v-col>
</v-row>
<v-row class="text-center">
<v-col>
<v-pagination
v-model="page"
:length="total_page"
circle
@input="next"
/>
</v-col>
</v-row>
</v-container>
</div>
</template>
@@ -146,10 +143,61 @@ export default {
is_loading: false,
start_date: null,
end_date: null,
page: 1,
page_size: 20,
total_page: 0,
items: [],
columns: [
{
label: '판매일',
field: 'saleDate',
},
{
label: '크리에이터',
field: 'nickname',
},
{
label: '제목',
field: 'title',
},
{
label: '구분',
field: 'orderType',
},
{
label: '판매금액(캔)',
field: 'orderPrice',
},
{
label: '판매수',
field: 'numberOfPeople',
},
{
label: '합계(캔)',
field: 'totalCan',
},
{
label: '원화',
field: 'totalKrw',
},
{
label: '수수료\n(6.6%)',
field: 'paymentFee',
},
{
label: '정산금액',
field: 'settlementAmount',
},
{
label: '원천세\n(3.3%)',
field: 'tax',
},
{
label: '입금액',
field: 'depositAmount',
},
{
label: '등록일',
field: 'registrationDate',
},
],
headers: [
{
text: '판매일',
@@ -273,10 +321,9 @@ export default {
this.is_loading = true
try {
const res = await api.getCalculateContent(this.start_date, this.end_date, this.page, this.page_size)
const res = await api.getCalculateContent(this.start_date, this.end_date)
if (res.status === 200 && res.data.success === true) {
this.items = res.data.data.items
this.total_page = Math.ceil(res.data.data.totalCount / this.page_size)
this.items = res.data.data
} else {
this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
}
@@ -286,25 +333,6 @@ export default {
this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
this.is_loading = false
}
},
next() {
this.getCalculateContent()
},
async downloadExcel() {
try {
const res = await api.downloadCalculateContentExcel(this.start_date, this.end_date)
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', '콘텐츠정산.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch (e) {
this.notifyError('엑셀 다운로드 중 오류가 발생했습니다.')
}
}
}
}
@@ -47,15 +47,22 @@
<v-spacer />
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
dark
depressed
@click="downloadExcel"
<vue-excel-xlsx
:data="items"
:columns="columns"
:file-name="'정산'"
:file-type="'xlsx'"
:sheet-name="'정산'"
>
엑셀 다운로드
</v-btn>
<v-btn
block
color="#3bb9f1"
dark
depressed
>
엑셀 다운로드
</v-btn>
</vue-excel-xlsx>
</v-col>
</v-row>
@@ -149,6 +156,40 @@ export default {
page_size: 20,
total_page: 0,
items: [],
columns: [
{
label: "이메일",
field: "email",
},
{
label: "크리에이터",
field: "nickname",
},
{
label: "합계(캔)",
field: "totalCan",
},
{
label: "원화",
field: "totalKrw",
},
{
label: "결제수수료(6.6%)",
field: "paymentFee",
},
{
label: "정산금액",
field: "settlementAmount",
},
{
label: "원천세(3.3%)",
field: "tax",
},
{
label: "입금액",
field: "depositAmount",
},
],
headers: [
{
text: '이메일',
@@ -268,21 +309,6 @@ export default {
} finally {
this.is_loading = false
}
},
async downloadExcel() {
try {
const res = await api.downloadCalculateContentByCreatorExcel(this.start_date, this.end_date)
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', '크리에이터별_콘텐츠정산.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch (e) {
this.notifyError('엑셀 다운로드 중 오류가 발생했습니다.')
}
}
}
}
@@ -35,7 +35,7 @@
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
color="#9970ff"
dark
depressed
@click="getCalculateContentDonation"
@@ -48,15 +48,22 @@
<v-spacer />
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
dark
depressed
@click="downloadExcel"
<vue-excel-xlsx
:data="items"
:columns="columns"
:file-name="'정산'"
:file-type="'xlsx'"
:sheet-name="'정산'"
>
엑셀 다운로드
</v-btn>
<v-btn
block
color="#9970ff"
dark
depressed
>
엑셀 다운로드
</v-btn>
</vue-excel-xlsx>
</v-col>
</v-row>
<v-row>
@@ -111,16 +118,6 @@
</v-data-table>
</v-col>
</v-row>
<v-row class="text-center">
<v-col>
<v-pagination
v-model="page"
:length="total_page"
circle
@input="next"
/>
</v-col>
</v-row>
</v-container>
</div>
</template>
@@ -138,10 +135,57 @@ export default {
is_loading: false,
start_date: null,
end_date: null,
page: 1,
page_size: 20,
total_page: 0,
items: [],
columns: [
{
label: '후원날짜',
field: 'donationDate',
},
{
label: '크리에이터',
field: 'nickname',
},
{
label: '콘텐츠 제목',
field: 'title',
},
{
label: '구분',
field: 'paidOrFree',
},
{
label: '후원수',
field: 'numberOfDonation',
},
{
label: '합계(캔)',
field: 'totalCan',
},
{
label: '원화',
field: 'totalKrw',
},
{
label: '수수료\n(6.6%)',
field: 'paymentFee',
},
{
label: '정산금액',
field: 'settlementAmount',
},
{
label: '원천세\n(3.3%)',
field: 'tax',
},
{
label: '입금액',
field: 'depositAmount',
},
{
label: '콘텐츠 등록일',
field: 'registrationDate',
},
],
headers: [
{
text: '후원날짜',
@@ -259,10 +303,9 @@ export default {
this.is_loading = true
try {
const res = await api.getCalculateContentDonation(this.start_date, this.end_date, this.page, this.page_size)
const res = await api.getCalculateContentDonation(this.start_date, this.end_date)
if (res.status === 200 && res.data.success === true) {
this.items = res.data.data.items
this.total_page = Math.ceil(res.data.data.totalCount / this.page_size)
this.items = res.data.data
} else {
this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
}
@@ -272,25 +315,6 @@ export default {
this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
this.is_loading = false
}
},
next() {
this.getCalculateContentDonation()
},
async downloadExcel() {
try {
const res = await api.downloadCalculateContentDonationExcel(this.start_date, this.end_date)
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', '콘텐츠후원정산.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch (e) {
this.notifyError('엑셀 다운로드 중 오류가 발생했습니다.')
}
}
}
}
+82 -76
View File
@@ -35,7 +35,7 @@
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
color="#9970ff"
dark
depressed
@click="getCalculateLive"
@@ -47,15 +47,22 @@
<v-spacer />
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
dark
depressed
@click="downloadExcel"
<vue-excel-xlsx
:data="items"
:columns="columns"
:file-name="'정산'"
:file-type="'xlsx'"
:sheet-name="'정산'"
>
엑셀 다운로드
</v-btn>
<v-btn
block
color="#9970ff"
dark
depressed
>
엑셀 다운로드
</v-btn>
</vue-excel-xlsx>
</v-col>
</v-row>
@@ -69,6 +76,10 @@
class="elevation-1"
hide-default-footer
>
<template v-slot:item.email="{ item }">
{{ item.email }}
</template>
<template v-slot:item.nickname="{ item }">
{{ item.nickname }}
</template>
@@ -112,29 +123,9 @@
<template v-slot:item.depositAmount="{ item }">
{{ item.depositAmount.toLocaleString() }} 원
</template>
<template v-slot:item.actions="{ item }">
<v-btn
small
color="error"
@click="refund(item)"
>
환불
</v-btn>
</template>
</v-data-table>
</v-col>
</v-row>
<v-row class="text-center">
<v-col>
<v-pagination
v-model="page"
:length="total_page"
circle
@input="next"
/>
</v-col>
</v-row>
</v-container>
</div>
</template>
@@ -152,11 +143,68 @@ export default {
is_loading: false,
start_date: null,
end_date: null,
page: 1,
page_size: 20,
total_page: 0,
items: [],
columns: [
{
label: "이메일",
field: "email",
},
{
label: "크리에이터",
field: "nickname",
},
{
label: "날짜",
field: "date",
},
{
label: "제목",
field: "title",
},
{
label: "구분",
field: "canUsageStr",
},
{
label: "입장캔",
field: "entranceFee",
},
{
label: "인원",
field: "numberOfPeople",
},
{
label: "합계(캔)",
field: "totalAmount",
},
{
label: "원화",
field: "totalKrw",
},
{
label: "결제수수료(6.6%)",
field: "paymentFee",
},
{
label: "정산금액",
field: "settlementAmount",
},
{
label: "원천세(3.3%)",
field: "tax",
},
{
label: "입금액",
field: "depositAmount",
},
],
headers: [
{
text: '이메일',
align: 'center',
sortable: false,
value: 'email',
},
{
text: '크리에이터',
align: 'center',
@@ -227,12 +275,6 @@ export default {
align: 'center',
sortable: false,
value: 'depositAmount',
},
{
text: '관리',
align: 'center',
sortable: false,
value: 'actions',
}
],
}
@@ -273,10 +315,9 @@ export default {
this.is_loading = true
try {
const res = await api.getCalculateLive(this.start_date, this.end_date, this.page, this.page_size)
const res = await api.getCalculateLive(this.start_date, this.end_date)
if (res.status === 200 && res.data.success === true) {
this.items = res.data.data.items
this.total_page = Math.ceil(res.data.data.totalCount / this.page_size)
this.items = res.data.data
} else {
this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
}
@@ -286,41 +327,6 @@ export default {
this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
this.is_loading = false
}
},
next() {
this.getCalculateLive()
},
async refund(item) {
if (confirm('정말로 환불하시겠습니까?')) {
try {
const res = await api.refundLive(item.roomId, item.canUsageStr)
if (res.status === 200 && res.data.success === true) {
this.notifySuccess('환불 처리가 완료되었습니다.')
await this.getCalculateLive()
} else {
this.notifyError(res.data.message || '환불 처리 중 오류가 발생했습니다.')
}
} catch (e) {
this.notifyError('환불 처리 중 오류가 발생했습니다.')
}
}
},
async downloadExcel() {
try {
const res = await api.downloadCalculateLiveExcel(this.start_date, this.end_date)
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', '라이브정산.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch (e) {
this.notifyError('엑셀 다운로드 중 오류가 발생했습니다.')
}
}
}
}
+49 -23
View File
@@ -47,15 +47,22 @@
<v-spacer />
<v-col cols="2">
<v-btn
block
color="#3bb9f1"
dark
depressed
@click="downloadExcel"
<vue-excel-xlsx
:data="items"
:columns="columns"
:file-name="'정산'"
:file-type="'xlsx'"
:sheet-name="'정산'"
>
엑셀 다운로드
</v-btn>
<v-btn
block
color="#3bb9f1"
dark
depressed
>
엑셀 다운로드
</v-btn>
</vue-excel-xlsx>
</v-col>
</v-row>
@@ -149,6 +156,40 @@ export default {
page_size: 20,
total_page: 0,
items: [],
columns: [
{
label: "이메일",
field: "email",
},
{
label: "크리에이터",
field: "nickname",
},
{
label: "합계(캔)",
field: "totalCan",
},
{
label: "원화",
field: "totalKrw",
},
{
label: "결제수수료(6.6%)",
field: "paymentFee",
},
{
label: "정산금액",
field: "settlementAmount",
},
{
label: "원천세(3.3%)",
field: "tax",
},
{
label: "입금액",
field: "depositAmount",
},
],
headers: [
{
text: '이메일',
@@ -268,21 +309,6 @@ export default {
} finally {
this.is_loading = false
}
},
async downloadExcel() {
try {
const res = await api.downloadCalculateLiveByCreatorExcel(this.start_date, this.end_date)
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', '크리에이터별_라이브정산.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch (e) {
this.notifyError('엑셀 다운로드 중 오류가 발생했습니다.')
}
}
}
}
@@ -1,340 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-btn
icon
@click="$router.back()"
>
<v-icon>mdi-arrow-left</v-icon>
</v-btn>
<v-toolbar-title>오리지널 시리즈 정산</v-toolbar-title>
<v-spacer />
<v-btn
color="primary"
:loading="excelLoading"
@click="onDownloadExcel"
>
엑셀 다운로드
</v-btn>
</v-toolbar>
<v-container>
<!-- 필터 영역 -->
<v-row
class="mt-2 mb-2"
align="center"
justify="end"
>
<v-col
cols="12"
md="3"
>
<v-autocomplete
v-model="selectedCreatorId"
:items="ownerOptions"
:loading="ownersLoading"
item-text="nickname"
item-value="creatorId"
label="멤버 선택"
dense
clearable
hide-details
/>
</v-col>
<v-col
cols="12"
md="3"
>
<v-menu
v-model="menuStart"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-bind="attrs"
label="시작일"
readonly
dense
:value="startDateStr"
v-on="on"
/>
</template>
<v-date-picker
v-model="startDateStr"
scrollable
@input="menuStart = false"
/>
</v-menu>
</v-col>
<v-col
cols="12"
md="3"
>
<v-menu
v-model="menuEnd"
:close-on-content-click="false"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-bind="attrs"
label="종료일"
readonly
dense
:value="endDateStr"
v-on="on"
/>
</template>
<v-date-picker
v-model="endDateStr"
scrollable
@input="menuEnd = false"
/>
</v-menu>
</v-col>
<v-col
cols="12"
md="2"
>
<v-btn
color="primary"
:loading="isLoading"
@click="onSearch"
>
조회
</v-btn>
</v-col>
</v-row>
<!-- 테이블 영역 -->
<v-data-table
:headers="headers"
:items="items"
:loading="isLoading"
:items-per-page="pageSize"
class="elevation-1"
disable-pagination
hide-default-footer
>
<template v-slot:no-data>
<div class="text-center grey--text pa-6">
데이터가 없습니다.
</div>
</template>
<template v-slot:item.price="{ item }">
<span>{{ numberFormat(item.price) }}</span>
</template>
<template v-slot:item.totalCan="{ item }">
<span>{{ numberFormat(item.totalCan) }}</span>
</template>
<template v-slot:item.totalPoint="{ item }">
<span>{{ numberFormat(item.totalPoint) }}</span>
</template>
</v-data-table>
<v-row
class="mt-4"
justify="center"
>
<v-pagination
v-model="page"
:length="totalPages"
:total-visible="7"
@input="fetchList"
/>
</v-row>
</v-container>
</div>
</template>
<script>
import {
getOwners,
getSettlementDetails,
downloadSettlementExcel,
} from "@/api/original_series_settlement";
export default {
name: "OriginalSeriesSettlement",
data() {
return {
// 필터 상태
ownersLoading: false,
ownerOptions: [],
selectedCreatorId: null,
startDateStr: "",
endDateStr: "",
menuStart: false,
menuEnd: false,
// 목록 상태
isLoading: false,
items: [],
totalCount: 0,
page: 1,
pageSize: 20,
excelLoading: false,
headers: [
{ text: "시리즈 제목", value: "seriesTitle", align: "center" },
{ text: "콘텐츠 제목", value: "contentTitle", align: "center" },
{ text: "가격", value: "price", align: "center" },
{ text: "구분", value: "orderType", align: "center" },
{ text: "판매 수", value: "salesCount", align: "center" },
{ text: "합계(캔)", value: "totalCan", align: "center" },
{ text: "합계(포인트)", value: "totalPoint", align: "center" },
],
};
},
computed: {
totalPages() {
return Math.max(1, Math.ceil(this.totalCount / this.pageSize));
},
},
created() {
this.initDefaultDates();
this.loadOwners();
},
methods: {
numberFormat(v) {
if (v === null || v === undefined) return "-";
try {
return Number(v).toLocaleString();
} catch (e) {
return String(v);
}
},
notifyError(message) {
this.$dialog.notify.error(message);
},
notifySuccess(message) {
this.$dialog.notify.success(message);
},
// 이번 달 1일 ~ 오늘
initDefaultDates() {
const now = new Date();
const y = now.getFullYear();
const m = now.getMonth();
const first = new Date(y, m, 1);
const pad = (n) => (n < 10 ? "0" + n : "" + n);
this.startDateStr = `${first.getFullYear()}-${pad(
first.getMonth() + 1
)}-${pad(first.getDate())}`;
this.endDateStr = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(
now.getDate()
)}`;
},
async loadOwners() {
this.ownersLoading = true;
try {
const res = await getOwners();
if (res.status === 200 && res.data && res.data.success) {
const list = Array.isArray(res.data.data) ? res.data.data : [];
this.ownerOptions = list;
// 가장 조회된 값 순서로 온다고 가정, 첫 번째를 기본 선택
if (list.length > 0) {
this.selectedCreatorId = list[0].creatorId;
}
// 초기 조회 (이번 달 범위, 기본 멤버)
this.page = 1;
await this.fetchList();
} else {
this.notifyError(
res.data && res.data.message
? res.data.message
: "소지 유저 조회 실패"
);
}
} catch (e) {
this.notifyError("소지 유저 조회 중 오류가 발생했습니다.");
} finally {
this.ownersLoading = false;
}
},
async onSearch() {
this.page = 1;
await this.fetchList();
},
async fetchList() {
if (!this.selectedCreatorId) {
this.items = [];
this.totalCount = 0;
return;
}
this.isLoading = true;
try {
const res = await getSettlementDetails({
startDate: this.startDateStr,
endDate: this.endDateStr,
creatorId: this.selectedCreatorId,
page: this.page,
size: this.pageSize,
});
if (res.status === 200 && res.data) {
if (res.data.success) {
const data = res.data.data || { totalCount: 0, items: [] };
this.totalCount = data.totalCount || 0;
this.items = Array.isArray(data.items) ? data.items : [];
} else {
this.notifyError(res.data.message || "정산 내역 조회 실패");
}
} else {
this.notifyError("정산 내역 조회 실패");
}
} catch (e) {
this.notifyError("정산 내역 조회 중 오류가 발생했습니다.");
} finally {
this.isLoading = false;
}
},
async onDownloadExcel() {
this.excelLoading = true;
try {
const res = await downloadSettlementExcel({
startDate: this.startDateStr,
endDate: this.endDateStr,
});
const blob = new Blob([res.data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "오리지널_시리즈_정산.xlsx");
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
window.URL.revokeObjectURL(url);
this.notifySuccess("엑셀 다운로드가 시작되었습니다.");
} catch (e) {
this.notifyError("엑셀 다운로드 중 오류가 발생했습니다.");
} finally {
this.excelLoading = false;
}
},
},
};
</script>
<style scoped>
/* 테이블 헤더/바디 모두 가운데 정렬 */
.v-data-table table thead th,
.v-data-table table tbody td {
text-align: center !important;
}
</style>
+1 -2
View File
@@ -135,8 +135,7 @@ export default {
currency: 'KRW',
currencies: [
{ text: 'KRW (한국 원)', value: 'KRW' },
{ text: 'USD (미국 달러)', value: 'USD' },
{ text: 'JPY (일본 엔)', value: 'JPY' }
{ text: 'USD (미국 달러)', value: 'USD' }
],
headers: [
{
+10 -57
View File
@@ -94,6 +94,10 @@
class="elevation-1"
hide-default-footer
>
<template v-slot:item.accountId="{ item }">
{{ item.accountId }}
</template>
<template v-slot:item.nickname="{ item }">
{{ item.nickname }}
</template>
@@ -109,16 +113,6 @@
<template v-slot:item.datetime="{ item }">
{{ item.datetime }}
</template>
<template v-slot:item.refund="{ item }">
<v-btn
color="error"
small
@click="confirmRefund(item)"
>
환불
</v-btn>
</template>
</v-data-table>
<v-card-actions v-show="!is_loading">
<v-spacer />
@@ -152,9 +146,14 @@ export default {
end_date: null,
items: [],
detail_items: null,
selected_date_item: null,
show_popup_dialog: false,
detail_headers: [
{
text: 'no',
align: 'center',
sortable: false,
value: 'accountId',
},
{
text: '닉네임',
align: 'center',
@@ -185,12 +184,6 @@ export default {
sortable: false,
value: 'datetime',
},
{
text: '환불',
align: 'center',
sortable: false,
value: 'refund',
},
],
headers: [
{
@@ -291,7 +284,6 @@ export default {
async getChargeStatusDetail(value) {
if (value.date !== '합계') {
this.is_loading = true
this.selected_date_item = value
try {
const res = await api.getChargeStatusDetail(value.date, value.pg, value.currency)
@@ -308,45 +300,6 @@ export default {
this.is_loading = false
}
}
},
async confirmRefund(item) {
let canText = `${item.chargeCan}캔`
if (item.rewardCan > 0) {
canText += ` + ${item.rewardCan}캔`
}
const confirm = await this.$dialog.confirm({
title: '환불 확인',
text: `${item.nickname}님의 ${canText}을 환불하시겠습니까?`,
actions: {
false: '취소',
true: '환불'
}
})
if (confirm) {
await this.refundCharge(item.chargeId)
}
},
async refundCharge(chargeId) {
this.is_loading = true
try {
const res = await api.refundCharge(chargeId)
if (res.status === 200 && res.data.success === true) {
this.notifySuccess('환불이 완료되었습니다.')
await this.getChargeStatusDetail(this.selected_date_item)
await this.getChargeStatus()
} else {
this.notifyError(res.data.message || '환불 처리 중 오류가 발생했습니다.')
}
} catch (e) {
this.notifyError('환불 처리 중 오류가 발생했습니다.')
} finally {
this.is_loading = false
}
}
}
}
+6 -28
View File
@@ -184,18 +184,6 @@
</v-alert>
</v-col>
</v-row>
<v-row v-if="!isEdit">
<v-col cols="12">
<v-select
v-model="bannerForm.lang"
:items="languageOptions"
label="언어 선택"
item-text="text"
item-value="value"
outlined
/>
</v-col>
</v-row>
<v-row v-if="selectedCharacter">
<v-col cols="12">
<v-alert
@@ -314,14 +302,8 @@ export default {
image: null,
imageUrl: '',
characterId: null,
bannerId: null,
lang: 'ko'
bannerId: null
},
languageOptions: [
{ text: '한국어', value: 'ko' },
{ text: '일본어', value: 'ja' },
{ text: '영어', value: 'en' }
],
imageRules: [
v => !!v || this.isEdit || '이미지를 선택하세요'
]
@@ -330,7 +312,7 @@ export default {
computed: {
isFormValid() {
return (this.bannerForm.image || (this.isEdit && this.bannerForm.imageUrl)) && this.selectedCharacter && this.bannerForm.lang;
return (this.bannerForm.image || (this.isEdit && this.bannerForm.imageUrl)) && this.selectedCharacter;
}
},
@@ -411,8 +393,7 @@ export default {
image: null,
imageUrl: '',
characterId: null,
bannerId: null,
lang: 'ko'
bannerId: null
};
this.previewImage = null;
this.searchKeyword = '';
@@ -433,8 +414,7 @@ export default {
image: null,
imageUrl: banner.imageUrl,
characterId: banner.characterId,
bannerId: banner.id,
lang: banner.lang || banner.language || null
bannerId: banner.id
};
this.previewImage = null;
this.searchKeyword = '';
@@ -450,8 +430,7 @@ export default {
image: null,
imageUrl: '',
characterId: null,
bannerId: null,
lang: 'ko'
bannerId: null
};
this.previewImage = null;
this.searchKeyword = '';
@@ -522,8 +501,7 @@ export default {
// 배너 추가
const response = await createCharacterBanner({
image: this.bannerForm.image,
characterId: this.selectedCharacter.id,
lang: this.bannerForm.lang
characterId: this.selectedCharacter.id
});
if (response && response.status === 200 && response.data && response.data.success === true) {
this.notifySuccess('배너가 추가되었습니다.');
+2 -4
View File
@@ -353,11 +353,10 @@
<v-col cols="12">
<v-textarea
v-model="character.systemPrompt"
label="시스템 프롬프트 (최대 2000자)"
label="시스템 프롬프트"
outlined
auto-grow
rows="4"
counter="2000"
:class="{ 'required-asterisk': !isEdit }"
:rules="systemPromptRules"
/>
@@ -1183,8 +1182,7 @@ export default {
],
typeOptions: ['Clone', 'Character'],
systemPromptRules: [
v => (this.isEdit ? true : (!!v && v.trim().length > 0) || '시스템 프롬프트를 입력하세요'),
v => (!!v && v.length <= 2000) || '최대 2000자까지 입력 가능합니다'
v => (this.isEdit ? true : (!!v && v.trim().length > 0) || '시스템 프롬프트를 입력하세요')
],
// 인물 관계 옵션 및 검증 규칙
relationshipTypeOptions: ['가족', '친구', '동료', '연인', '기타'],
+5 -91
View File
@@ -36,7 +36,7 @@
>
<v-btn
slot="append"
color="#3bb9f1"
color="#9970ff"
dark
@click="search"
>
@@ -75,9 +75,6 @@
<th class="text-center">
가격
</th>
<th class="text-center">
정산요율
</th>
<th class="text-center">
한정판
</th>
@@ -96,10 +93,7 @@
<th class="text-center">
오픈 예정일
</th>
<th
v-if="isAdmin"
class="text-center"
>
<th class="text-center">
관리
</th>
</tr>
@@ -163,12 +157,6 @@
<td v-else>
무료
</td>
<td>
<!-- settlementRatio가 null 또는 빈값이면 빈칸으로 표시 -->
<span v-if="item.settlementRatio !== null && item.settlementRatio !== undefined && String(item.settlementRatio).trim() !== ''">
{{ item.settlementRatio }}
</span>
</td>
<td
v-if="
item.totalContentCount > 0 &&
@@ -217,7 +205,7 @@
</td>
<td>{{ item.date }}</td>
<td>{{ item.releaseDate }}</td>
<td v-if="isAdmin">
<td>
<v-row>
<v-col>
<v-btn
@@ -367,36 +355,6 @@
</v-col>
</v-row>
</v-card-text>
<v-card-text v-if="selected_audio_content.price > 0">
<v-row align="center">
<v-col cols="4">
정산요율
</v-col>
<v-col cols="8">
<v-text-field
v-model="audio_content.settlement_ratio"
label="정산요율"
placeholder="예: 30"
type="number"
hide-details="auto"
:disabled="audio_content.is_settlement_ratio_deleted"
/>
</v-col>
</v-row>
</v-card-text>
<v-card-text v-if="selected_audio_content.price > 0">
<v-row>
<v-col cols="4">
정산요율 삭제
</v-col>
<v-col cols="8">
<input
v-model="audio_content.is_settlement_ratio_deleted"
type="checkbox"
>
</v-col>
</v-row>
</v-card-text>
<v-card-text>
<v-row>
<v-col cols="4">
@@ -530,14 +488,6 @@ export default {
};
},
computed: {
isAdmin() {
const role = (this.$store && this.$store.state && this.$store.state.accountStore && this.$store.state.accountStore.role)
|| (typeof localStorage !== 'undefined' ? localStorage.role : '');
return role === 'ADMIN';
},
},
async created() {
this.audio_content = {
id: null,
@@ -547,13 +497,8 @@ export default {
is_adult: false,
is_comment_available: false,
is_default_cover_image: false,
is_settlement_ratio_deleted: false,
settlement_ratio: "",
};
// ADMIN 권한일 때만 테마 리스트 조회
if (this.isAdmin) {
await this.getAudioContentThemeList();
}
await this.getAudioContentThemeList();
await this.getAudioContent();
},
@@ -586,11 +531,6 @@ export default {
this.audio_content.is_adult = item.isAdult;
this.audio_content.is_comment_available = item.isCommentAvailable;
this.audio_content.is_default_cover_image = false;
this.audio_content.is_settlement_ratio_deleted = false;
this.audio_content.settlement_ratio =
item.settlementRatio !== null && item.settlementRatio !== undefined
? String(item.settlementRatio)
: "";
this.image_preview = item.coverImageUrl;
this.cover_image_file = null;
@@ -650,8 +590,6 @@ export default {
is_adult: false,
is_comment_available: false,
is_default_cover_image: false,
is_settlement_ratio_deleted: false,
settlement_ratio: "",
};
this.image_preview = null;
this.cover_image_file = null;
@@ -693,12 +631,6 @@ export default {
isDefaultCoverImage: this.audio_content.is_default_cover_image,
};
// 유료 콘텐츠인 경우에만 정산요율 관련 플래그/값 전송 고려
const isPaid = this.selected_audio_content && this.selected_audio_content.price > 0;
if (isPaid) {
request.isSettlementRatioDeleted = this.audio_content.is_settlement_ratio_deleted;
}
if (
this.audio_content.title !== this.selected_audio_content.title &&
this.audio_content.title.trim().length > 0
@@ -725,21 +657,6 @@ export default {
request.isCommentAvailable = this.audio_content.is_comment_available;
}
// settlementRatio 처리 (null/빈문자 케이스 포함)
const originalRatio =
this.selected_audio_content.settlementRatio !== null &&
this.selected_audio_content.settlementRatio !== undefined
? String(this.selected_audio_content.settlementRatio)
: "";
const newRatio =
this.audio_content.settlement_ratio !== null &&
this.audio_content.settlement_ratio !== undefined
? String(this.audio_content.settlement_ratio)
: "";
if (isPaid && !this.audio_content.is_settlement_ratio_deleted && newRatio !== originalRatio) {
request.settlementRatio = newRatio;
}
const formData = new FormData();
formData.append("request", JSON.stringify(request));
@@ -777,10 +694,7 @@ export default {
isActive: false,
};
const formData = new FormData();
formData.append("request", JSON.stringify(request));
const res = await api.modifyAudioContent(formData);
const res = await api.modifyAudioContent(request);
if (res.status === 200 && res.data.success === true) {
this.cancel();
this.notifySuccess("삭제되었습니다.");
+9 -272
View File
@@ -60,9 +60,6 @@
<v-img :src="item.thumbnailImageUrl" />
<v-spacer />
</v-card-title>
<v-card-subtitle class="text-center schedule-text">
{{ scheduleRangeText(item) }}
</v-card-subtitle>
<v-card-actions>
<v-spacer />
<v-btn
@@ -112,23 +109,6 @@
</v-col>
</v-row>
</v-card-text>
<!-- 언어 선택: 등록 시에만 노출 (수정 시 비노출) -->
<v-card-text v-if="!is_modify">
<v-row align="center">
<v-col cols="4">
언어
</v-col>
<v-col cols="8">
<v-select
v-model="banner.lang"
:items="langItems"
item-text="text"
item-value="value"
label="언어 선택"
/>
</v-col>
</v-row>
</v-card-text>
<v-card-text>
<v-row align="center">
<v-col cols="4">
@@ -248,38 +228,6 @@
</v-col>
</v-row>
</v-card-text>
<v-card-text>
<v-row align="center">
<v-col cols="4">
노출 기간 (한국 시간 기준)
</v-col>
<v-col cols="4">
<v-text-field
v-model="banner.start_date"
type="datetime-local"
label="시작 일시 (선택)"
:error-messages="schedule_errors.start_date"
clearable
@click:clear="banner.start_date = ''"
/>
</v-col>
<v-col cols="4">
<v-text-field
v-model="banner.end_date"
type="datetime-local"
label="종료 일시 (선택)"
:error-messages="schedule_errors.end_date"
clearable
@click:clear="banner.end_date = ''"
/>
</v-col>
</v-row>
<v-row>
<v-col class="schedule-text">
비워두면 해당 경계의 예약 제한이 없습니다. 입력한 시간은 한국 시간(KST)으로 저장됩니다.
</v-col>
</v-row>
</v-card-text>
<div class="image-select">
<label for="image">
배너 이미지 등록
@@ -325,47 +273,6 @@
</v-card>
</v-dialog>
<!-- 이미지 크롭 다이얼로그 (CropperJS) -->
<v-dialog
v-model="show_crop_dialog"
max-width="900px"
persistent
>
<v-card class="cropper-card">
<v-card-title>
이미지 크롭 (1:1)
</v-card-title>
<v-card-text class="cropper-card-text">
<div class="cropper-canvas-wrap">
<img
v-if="crop_src"
ref="cropperImage"
:src="crop_src"
alt="crop"
class="cropper-dialog-img"
>
</div>
</v-card-text>
<v-card-actions v-show="!is_loading">
<v-spacer />
<v-btn
color="blue darken-1"
text
@click="handleCropCancel"
>
취소
</v-btn>
<v-btn
color="blue darken-1"
text
@click="handleCropConfirm"
>
확인
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-dialog
v-model="show_delete_confirm_dialog"
max-width="400px"
@@ -401,19 +308,11 @@
<script>
import Draggable from "vuedraggable";
import debounce from "lodash/debounce";
import Cropper from 'cropperjs'
import * as seriesApi from "@/api/audio_content_series"
import * as memberApi from "@/api/member";
import * as eventApi from "@/api/event";
import * as api from "@/api/audio_content"
import {
applyScheduleToModifyRequest,
applyScheduleToSaveRequest,
createBannerScheduleForm,
formatScheduleRange,
validateBannerSchedule
} from "@/utils/audio_content_banner"
export default {
name: "AudioContentMainTopBanner",
@@ -427,14 +326,8 @@ export default {
is_modify: false,
show_write_dialog: false,
show_delete_confirm_dialog: false,
// 이미지 크롭용 상태
show_crop_dialog: false,
cropper: null,
crop_src: null,
selected_file_for_crop: null,
selected_banner: {},
banner: {type: 'CREATOR', tab_id: 1, lang: 'ko', ...createBannerScheduleForm()},
schedule_errors: {},
banner: {type: 'CREATOR', tab_id: 1},
banners: [],
events: [],
creators: [],
@@ -442,12 +335,7 @@ export default {
search_query_creator: '',
search_query_series: '',
tabs: [],
selected_tab_id: 1,
langItems: [
{ text: '한국어', value: 'ko' },
{ text: '일본어', value: 'ja' },
{ text: '영어', value: 'en' }
]
selected_tab_id: 1
}
},
@@ -476,101 +364,14 @@ export default {
},
methods: {
async imageAdd(payload) {
imageAdd(payload) {
const file = payload;
// 파일 해제 시 초기화
if (!file) {
if (this.banner.thumbnail_image_url) {
URL.revokeObjectURL(this.banner.thumbnail_image_url)
}
this.banner.thumbnail_image = null
if (file) {
this.banner.thumbnail_image_url = URL.createObjectURL(file)
URL.revokeObjectURL(file)
} else {
this.banner.thumbnail_image_url = null
return
}
// CropperJS 다이얼로그 오픈 흐름
if (this.crop_src) {
URL.revokeObjectURL(this.crop_src)
}
this.selected_file_for_crop = file
this.crop_src = URL.createObjectURL(file)
this.show_crop_dialog = true
this.$nextTick(() => {
this.initCropper()
})
},
initCropper() {
const imageEl = this.$refs.cropperImage
if (!imageEl) return
// 기존 인스턴스 제거
if (this.cropper) {
this.cropper.destroy()
this.cropper = null
}
this.cropper = new Cropper(imageEl, {
aspectRatio: 1,
viewMode: 1,
autoCropArea: 1,
movable: true,
zoomable: true,
scalable: false,
rotatable: false,
responsive: true,
background: false,
})
},
destroyCropper() {
if (this.cropper) {
this.cropper.destroy()
this.cropper = null
}
},
async handleCropConfirm() {
if (!this.cropper || !this.selected_file_for_crop) return
try {
this.is_loading = true
const mime = this.selected_file_for_crop.type && /^image\//.test(this.selected_file_for_crop.type)
? this.selected_file_for_crop.type
: 'image/png'
const canvas = this.cropper.getCroppedCanvas()
await new Promise((resolve, reject) => {
canvas.toBlob((blob) => {
if (!blob) return reject(new Error('크롭된 이미지를 생성할 수 없습니다.'))
const croppedFile = new File([blob], this.selected_file_for_crop.name || 'image.png', { type: mime })
// 기존 미리보기 URL 해제
if (this.banner.thumbnail_image_url) {
URL.revokeObjectURL(this.banner.thumbnail_image_url)
}
this.banner.thumbnail_image = croppedFile
this.banner.thumbnail_image_url = URL.createObjectURL(croppedFile)
resolve()
}, mime)
})
this.show_crop_dialog = false
} catch (e) {
this.notifyError('이미지 크롭 중 오류가 발생했습니다. 다시 시도해 주세요.')
} finally {
this.is_loading = false
this.cleanupCropDialog()
}
},
handleCropCancel() {
this.show_crop_dialog = false
this.cleanupCropDialog()
},
cleanupCropDialog() {
this.destroyCropper()
if (this.crop_src) {
URL.revokeObjectURL(this.crop_src)
this.crop_src = null
}
this.selected_file_for_crop = null
},
cancel() {
@@ -578,8 +379,7 @@ export default {
this.is_selecting = false
this.show_write_dialog = false
this.show_delete_confirm_dialog = false
this.banner = {type: 'CREATOR', tab_id: 1, lang: 'ko', ...createBannerScheduleForm()}
this.schedule_errors = {}
this.banner = {type: 'CREATOR', tab_id: 1}
this.selected_banner = {}
this.search_query_creator = ''
this.search_query_series = ''
@@ -632,14 +432,6 @@ export default {
this.banner.link = banner.link
this.banner.is_adult = banner.isAdult
this.banner.tab_id = banner.tabId
const schedule = createBannerScheduleForm(banner)
this.banner.start_date = schedule.start_date
this.banner.end_date = schedule.end_date
this.schedule_errors = {}
// 수정 시 언어는 변경 불가하므로 UI를 표시하지 않음. 필요 시 내부 유지만 함 (기본값 또는 서버 값 사용)
if (banner.lang) {
this.banner.lang = banner.lang
}
setTimeout(() => {
this.is_selecting = false; // 선택 상태 해제
@@ -681,26 +473,9 @@ export default {
return false;
}
return this.validateSchedule()
},
validateSchedule() {
const errors = validateBannerSchedule(this.banner)
this.schedule_errors = errors
const messages = Object.keys(errors).map((key) => errors[key])
if (messages.length > 0) {
this.notifyError(messages[0])
return false;
}
return true
},
scheduleRangeText(banner) {
return formatScheduleRange(banner.startDate, banner.endDate)
},
deleteConfirm(banner) {
this.selected_banner = banner
this.show_delete_confirm_dialog = true
@@ -722,8 +497,7 @@ export default {
let request = {
type: this.banner.type,
isAdult: this.banner.is_adult,
lang: this.banner.lang || 'ko'
isAdult: this.banner.is_adult
}
if (this.banner.type === 'CREATOR') {
@@ -740,8 +514,6 @@ export default {
request.tabId = this.banner.tab_id
}
applyScheduleToSaveRequest(request, this.banner)
formData.append("request", JSON.stringify(request))
const res = await api.saveBanner(formData)
@@ -762,7 +534,6 @@ export default {
},
async modify() {
if (!this.validateSchedule()) return;
if (this.is_loading) return;
this.is_loading = true
@@ -818,8 +589,6 @@ export default {
request.tabId = this.banner.tab_id
}
applyScheduleToModifyRequest(request, this.banner, this.selected_banner)
formData.append("request", JSON.stringify(request))
const res = await api.modifyBanner(formData)
@@ -1015,11 +784,6 @@ export default {
border: 0;
}
.schedule-text {
font-size: 12px;
color: #666;
}
.image-preview {
max-width: 100%;
width: 250px;
@@ -1027,30 +791,3 @@ export default {
margin-top: 10px;
}
</style>
<style>
/* CropperJS 기본 스타일 */
@import '~cropperjs/dist/cropper.css';
.cropper-card {
max-height: 80vh; /* 뷰포트 대비 제한하여 하단 버튼이 항상 보이도록 */
display: flex;
flex-direction: column;
}
.cropper-card-text {
flex: 1;
overflow: auto; /* 내부 스크롤로 이미지만 스크롤되게 함 */
}
.cropper-canvas-wrap {
width: 100%;
height: 60vh; /* 이미지 표시 영역 고정 */
}
.cropper-dialog-img {
max-width: 100%;
max-height: 100%;
display: block;
}
</style>
-278
View File
@@ -66,15 +66,9 @@
<th class="text-center">
이용중지/탈퇴일
</th>
<th class="text-center">
일본어 표시 이름
</th>
<th class="text-center">
공유
</th>
<th class="text-center">
관리
</th>
</tr>
</thead>
<tbody>
@@ -119,7 +113,6 @@
</td>
<td>{{ item.signUpDate }}</td>
<td>{{ item.signOutDate }}</td>
<td>{{ japaneseNameOf(item) || '미등록' }}</td>
<td>
<v-btn
:disabled="is_loading"
@@ -128,14 +121,6 @@
공유
</v-btn>
</td>
<td>
<v-btn
dark
@click="showPopupDialog(item)"
>
수정
</v-btn>
</td>
</tr>
</tbody>
</template>
@@ -153,118 +138,6 @@
</v-col>
</v-row>
</v-container>
<v-row>
<v-dialog
v-model="show_popup_dialog"
max-width="1000px"
persistent
>
<v-card>
<v-card-title>계정 상세</v-card-title>
<v-card-text>
<v-row align="center">
<v-col cols="4">
이메일 :
</v-col>
<v-col cols="8">
{{ email }}
</v-col>
</v-row>
</v-card-text>
<v-card-text>
<v-row align="center">
<v-col cols="4">
원본 이름 :
</v-col>
<v-col cols="8">
{{ nickname }}
</v-col>
</v-row>
</v-card-text>
<v-card-text>
<v-row align="center">
<v-col cols="4">
<label for="japanese_display_name">일본어 표시 이름</label>
</v-col>
<v-col cols="8">
<v-text-field
id="japanese_display_name"
v-model="japanese_display_name"
label="일본어 표시 이름"
:hint="japanese_display_name_hint"
persistent-hint
:error-messages="japanese_display_name_error"
:disabled="is_saving"
@compositionstart="is_composing = true"
@compositionend="is_composing = false"
@keyup.enter="submitByEnter"
/>
</v-col>
</v-row>
</v-card-text>
<v-card-text>
<v-row align="center">
<v-col cols="4">
권한
</v-col>
<v-col cols="8">
<v-radio-group
v-model="user_type"
row
:disabled="is_saving"
>
<v-spacer />
<v-radio
value="CREATOR"
label="크리에이터"
/>
<v-radio
value="AGENT"
label="에이전트"
/>
<v-radio
value="USER"
label="일반회원"
/>
<v-radio
value="CONTENT_MANAGER"
label="콘텐츠 관리자"
/>
<v-spacer />
</v-radio-group>
</v-col>
</v-row>
</v-card-text>
<v-card-actions v-show="!is_saving">
<v-spacer />
<v-btn
color="blue darken-1"
text
@click="cancel"
>
취소
</v-btn>
<v-btn
color="blue darken-1"
text
:disabled="is_saving"
@click="modify"
>
수정
</v-btn>
</v-card-actions>
<v-card-actions v-show="is_saving">
<v-spacer />
<v-progress-circular
indeterminate
color="#9970ff"
/>
<v-spacer />
</v-card-actions>
</v-card>
</v-dialog>
</v-row>
</div>
</template>
@@ -278,45 +151,23 @@ export default {
data() {
return {
is_loading: false,
is_saving: false,
is_composing: false,
page: 1,
total_page: 0,
total_creator_count: 0,
search_word: '',
accounts: [],
account: {},
member: null,
email: null,
nickname: null,
user_type: null,
japanese_display_name: '',
japanese_display_name_initial: '',
japanese_display_name_error: '',
show_popup_dialog: false,
utm_source: '',
utm_medium: '',
utm_campaign: '',
}
},
computed: {
japanese_display_name_hint() {
return this.japanese_display_name_initial.length === 0
? '일본어 표시 이름이 등록되지 않았습니다. 비워두면 해제됩니다.'
: '비워두면 일본어 표시 이름이 해제됩니다.'
},
},
async created() {
await this.getAccounts()
},
methods: {
japaneseNameOf(item) {
return (item && item.localizedNames && item.localizedNames.ja) || ''
},
notifyError(message) {
this.$dialog.notify.error(message)
},
@@ -396,135 +247,6 @@ export default {
}
},
showPopupDialog(account) {
this.member = account
if (account.userType === '일반회원') {
this.user_type = 'USER'
} else if (account.userType === '에이전트') {
this.user_type = 'AGENT'
} else if (account.userType === '콘텐츠 관리자') {
this.user_type = 'CONTENT_MANAGER'
} else {
this.user_type = 'CREATOR'
}
this.email = account.email
this.nickname = account.nickname
this.japanese_display_name_initial = this.japaneseNameOf(account)
this.japanese_display_name = this.japanese_display_name_initial
this.japanese_display_name_error = ''
this.is_composing = false
this.show_popup_dialog = true
},
cancel() {
this.member = null
this.email = null
this.nickname = null
this.user_type = null
this.japanese_display_name = ''
this.japanese_display_name_initial = ''
this.japanese_display_name_error = ''
this.is_composing = false
this.show_popup_dialog = false
},
submitByEnter() {
if (this.is_composing || this.is_saving) return
this.modify()
},
async modify() {
if (this.is_saving) return
const value = this.japanese_display_name || ''
if (Array.from(value).length > 255) {
this.japanese_display_name_error = '일본어 표시 이름은 255자 이내로 입력하세요.'
return
}
this.japanese_display_name_error = ''
const target = this.member
const is_name_changed = value !== this.japanese_display_name_initial
const is_user_type_changed = !(
(this.user_type === 'CREATOR' && target.userType === '크리에이터') ||
(this.user_type === 'USER' && target.userType === '일반회원') ||
(this.user_type === 'AGENT' && target.userType === '에이전트') ||
(this.user_type === 'CONTENT_MANAGER' && target.userType === '콘텐츠 관리자')
)
if (!is_name_changed && !is_user_type_changed) {
this.notifyError('변경사항이 없습니다.')
return
}
this.is_saving = true
try {
if (is_name_changed) {
const res = await api.updateCreatorLocalizedNameJa(target.id, value)
if (res.status === 200 && res.data.success === true) {
this.applyJapaneseName(target.id, res.data.data.displayName)
if (this.member && this.member.id === target.id) {
this.japanese_display_name_initial = res.data.data.displayName || ''
}
this.notifySuccess('일본어 표시 이름이 저장되었습니다.')
} else {
if (res.data.errorProperty === 'displayName') {
this.japanese_display_name_error = res.data.message || '일본어 표시 이름을 저장하지 못했습니다.'
}
this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
return
}
}
if (is_user_type_changed) {
const res = await api.updateMember(target.id, this.user_type)
if (res.status === 200 && res.data.success === true) {
this.notifySuccess('수정되었습니다.')
if (this.member && this.member.id === target.id) {
this.cancel()
}
await this.refreshList()
} else {
this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
}
return
}
if (this.member && this.member.id === target.id) {
this.cancel()
}
} catch (e) {
this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
} finally {
this.is_saving = false
}
},
applyJapaneseName(id, displayName) {
const account = this.accounts.find(item => item.id === id)
if (!account) return
const localizedNames = { ...(account.localizedNames || {}) }
if (displayName === null || displayName === undefined || displayName === '') {
delete localizedNames.ja
} else {
localizedNames.ja = displayName
}
this.$set(account, 'localizedNames', localizedNames)
},
async refreshList() {
if (this.search_word.length >= 2) {
await this.searchAccount()
} else {
await this.getAccounts()
}
},
async shareCreatorChannel(item) {
this.is_loading = true
try {
-33
View File
@@ -1,33 +0,0 @@
<template>
<span>
<v-btn
v-for="action in visibleActions"
:key="action.value"
:color="action.value === 'MARK_UNDELIVERABLE' || action.value === 'CANCEL' ? 'error' : 'primary'"
:disabled="disabled"
class="ma-1"
small
outlined
@click.stop="$emit('select', action.value)"
>
{{ action.label }}
</v-btn>
</span>
</template>
<script>
import { giftActions } from '@/utils/gift'
export default {
name: 'GiftActions',
props: {
actions: { type: Array, default: () => [] },
disabled: { type: Boolean, default: false }
},
computed: {
visibleActions() {
return giftActions.filter(action => this.actions.includes(action.value))
}
}
}
</script>
-344
View File
@@ -1,344 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-spacer />
<v-toolbar-title>선물 카테고리</v-toolbar-title>
<v-spacer />
<v-btn
color="primary"
:disabled="is_loading || is_operating"
@click="openCreate"
>
카테고리 등록
</v-btn>
</v-toolbar>
<br>
<v-container fluid>
<v-row>
<v-col>
<div class="mb-2">
총 {{ categories.length }}건
</div>
<v-progress-linear
v-if="is_loading"
indeterminate
/>
<v-simple-table class="elevation-10">
<thead>
<tr>
<th
v-for="header in headers"
:key="header"
class="text-center"
>
{{ header }}
</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in categories"
:key="item.categoryId"
>
<td class="text-center">
{{ item.categoryId }}
</td>
<td class="text-center">
{{ item.classificationNumber }}
</td>
<td class="text-center">
{{ item.categoryCode }}
</td>
<td class="text-center">
{{ item.name }}
</td>
<td class="text-center">
{{ item.receiptCode }}
</td>
<td class="text-center">
{{ item.representativeItem }}
</td>
<td class="text-center">
{{ item.requiresDamageWaiver ? '예' : '아니오' }}
</td>
<td class="text-center">
{{ item.isActive ? '활성' : '비활성' }}
</td>
<td class="text-center">
<v-btn
small
outlined
color="primary"
:disabled="is_loading || is_operating"
@click="openEdit(item)"
>
수정
</v-btn>
<v-btn
small
outlined
color="error"
class="ma-1"
:disabled="!item.isActive || is_loading || is_operating"
@click="requestDeactivation(item)"
>
비활성화
</v-btn>
</td>
</tr>
<tr v-if="!categories.length">
<td
:colspan="headers.length"
class="text-center grey--text"
>
{{ is_loading ? '조회 중입니다.' : list_error ? '목록을 불러오지 못했습니다.' : '등록된 카테고리가 없습니다.' }}
</td>
</tr>
</tbody>
</v-simple-table>
<v-btn
v-if="list_error"
class="mt-3"
:disabled="is_loading || is_operating"
@click="getCategories"
>
다시 조회
</v-btn>
</v-col>
</v-row>
</v-container>
<v-dialog
v-model="show_form_dialog"
max-width="560px"
persistent
>
<v-card>
<v-form @submit.prevent="saveCategory">
<v-card-title class="headline">
{{ isEdit ? '카테고리 수정' : '카테고리 등록' }}
</v-card-title>
<v-card-text>
<v-text-field
v-for="field in fields"
:key="field.key"
v-model="form[field.key]"
:label="field.label"
:placeholder="field.placeholder"
:counter="field.maxLength"
:readonly="isEdit && field.key === 'categoryCode'"
:hint="isEdit && field.key === 'categoryCode' ? '카테고리 코드는 수정할 수 없습니다.' : ''"
:persistent-hint="isEdit && field.key === 'categoryCode'"
:disabled="is_operating"
:error-messages="form_errors[field.key]"
@input="$set(form_errors, field.key, '')"
/>
<v-switch
v-model="form.requiresDamageWaiver"
label="파손면책 동의 필요 여부"
:disabled="is_operating"
:error-messages="form_errors.requiresDamageWaiver"
@change="$set(form_errors, 'requiresDamageWaiver', '')"
/>
<v-switch
v-model="form.isActive"
label="활성 여부"
:disabled="is_operating"
:error-messages="form_errors.isActive"
@change="$set(form_errors, 'isActive', '')"
/>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn
color="blue darken-1"
text
:disabled="is_operating"
@click="closeForm"
>
취소
</v-btn>
<v-btn
type="submit"
color="primary"
:loading="is_operating"
:disabled="is_operating"
>
{{ isEdit ? '수정' : '등록' }}
</v-btn>
</v-card-actions>
</v-form>
</v-card>
</v-dialog>
<v-dialog
v-model="show_confirm_dialog"
max-width="500px"
persistent
>
<v-card>
<v-card-title>카테고리 비활성화 확인</v-card-title>
<v-card-text v-if="pendingCategory">
<p>{{ pendingCategory.name }} 카테고리를 비활성화하시겠습니까?</p>
<p>실제 삭제되지 않고 비활성 상태로 변경됩니다.</p>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn
color="blue darken-1"
text
:disabled="is_operating"
@click="cancelDeactivation"
>
취소
</v-btn>
<v-btn
color="blue darken-1"
text
:loading="is_operating"
:disabled="is_operating"
@click="deactivateCategory"
>
확인
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</div>
</template>
<script>
import * as api from '@/api/gift_category'
import { createGiftCategoryForm, buildGiftCategoryRequest, validateGiftCategory } from '@/utils/gift_category'
export default {
name: 'GiftCategory',
data() {
return {
headers: ['카테고리 ID', '분류번호', '카테고리 코드', '카테고리명', '접수 코드', '대표 품목', '파손면책 동의 필요 여부', '활성 여부', '관리'],
fields: [
{ key: 'classificationNumber', label: '분류번호', placeholder: '예: 100', maxLength: 3 },
{ key: 'categoryCode', label: '카테고리 코드', placeholder: '예: DOLL', maxLength: 50 },
{ key: 'name', label: '카테고리명', placeholder: '예: 인형', maxLength: 50 },
{ key: 'receiptCode', label: '접수 코드', placeholder: '예: A', maxLength: 9 },
{ key: 'representativeItem', label: '대표 품목', placeholder: '예: 피규어', maxLength: 100 }
],
categories: [],
is_loading: false,
list_error: false,
listRequestId: 0,
is_operating: false,
show_form_dialog: false,
categoryId: null,
form: createGiftCategoryForm(),
form_errors: {},
show_confirm_dialog: false,
pendingCategory: null
}
},
computed: {
isEdit() {
return this.categoryId !== null
}
},
async created() {
await this.getCategories()
},
beforeDestroy() {
this.listRequestId++
},
methods: {
notifyError(error) {
const response = error.response && error.response.data
this.$dialog.notify.error((response && response.message) || error.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
},
checkResponse(response) {
if (response.success !== true) throw new Error(response.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
},
async getCategories() {
const requestId = ++this.listRequestId
this.is_loading = true
this.list_error = false
try {
const response = await api.getGiftCategories()
if (requestId !== this.listRequestId) return
this.checkResponse(response)
this.categories = response.data
} catch (error) {
if (requestId !== this.listRequestId) return
this.categories = []
this.list_error = true
this.notifyError(error)
} finally {
if (requestId === this.listRequestId) this.is_loading = false
}
},
openCreate() {
if (this.is_loading || this.is_operating) return
this.categoryId = null
this.form = createGiftCategoryForm()
this.form_errors = {}
this.show_form_dialog = true
},
openEdit(item) {
if (this.is_loading || this.is_operating) return
this.categoryId = item.categoryId
this.form = buildGiftCategoryRequest(item)
this.form_errors = {}
this.show_form_dialog = true
},
closeForm() {
if (this.is_operating) return
this.show_form_dialog = false
},
async saveCategory() {
if (!this.show_form_dialog || this.is_operating) return
this.form_errors = validateGiftCategory(this.form)
if (Object.keys(this.form_errors).length) return
this.is_operating = true
try {
const response = this.isEdit
? await api.updateGiftCategory(this.categoryId, this.form)
: await api.createGiftCategory(this.form)
this.checkResponse(response)
this.$dialog.notify.success(this.isEdit ? '카테고리가 수정되었습니다.' : '카테고리가 등록되었습니다.')
await this.getCategories()
this.show_form_dialog = false
} catch (error) {
this.notifyError(error)
} finally {
this.is_operating = false
}
},
requestDeactivation(item) {
if (!item.isActive || this.is_loading || this.is_operating) return
this.pendingCategory = item
this.show_confirm_dialog = true
},
cancelDeactivation() {
if (this.is_operating) return
this.show_confirm_dialog = false
this.pendingCategory = null
},
async deactivateCategory() {
if (!this.show_confirm_dialog || !this.pendingCategory || !this.pendingCategory.isActive || this.is_operating) return
this.is_operating = true
try {
const response = await api.deactivateGiftCategory(this.pendingCategory.categoryId)
this.checkResponse(response)
const index = this.categories.findIndex(item => item.categoryId === this.pendingCategory.categoryId)
if (index !== -1) this.$set(this.categories, index, response.data)
this.show_confirm_dialog = false
this.pendingCategory = null
this.$dialog.notify.success('카테고리가 비활성화되었습니다.')
} catch (error) {
this.notifyError(error)
} finally {
this.is_operating = false
}
}
}
}
</script>
-574
View File
@@ -1,574 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-spacer />
<v-toolbar-title>선물함 리스트</v-toolbar-title>
<v-spacer />
</v-toolbar>
<br>
<v-container fluid>
<v-form @submit.prevent="search">
<v-row align="center">
<v-col
cols="12"
md="2"
>
<v-select
v-model="filters.status"
:items="giftStatuses"
:disabled="is_loading || is_operating"
label="상태"
/>
</v-col>
<v-col
cols="12"
md="3"
>
<v-text-field
v-model="filters.applicationNo"
:disabled="is_loading || is_operating"
label="신청번호"
clearable
/>
</v-col>
<v-col
cols="12"
md="4"
>
<v-text-field
v-model="filters.nickname"
:disabled="is_loading || is_operating"
label="발송인 또는 수취인 닉네임"
clearable
/>
</v-col>
<v-col
cols="12"
md="3"
>
<v-btn
type="submit"
color="#3bb9f1"
:disabled="is_loading || is_operating"
dark
>
검색
</v-btn>
<v-btn
class="ml-2"
:disabled="is_loading || is_operating"
@click="reset"
>
초기화
</v-btn>
</v-col>
</v-row>
</v-form>
<v-row>
<v-col>
<div class="mb-2">
총 {{ totalCount }}건
</div>
<v-progress-linear
v-if="is_loading"
indeterminate
/>
<v-simple-table class="elevation-10">
<thead>
<tr>
<th
v-for="header in headers"
:key="header"
class="text-center"
>
{{ header }}
</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in gifts"
:key="item.applicationNo"
>
<td class="text-center">
{{ item.applicationNo }}
</td>
<td class="text-center">
{{ item.senderNickname }}
</td>
<td class="text-center">
{{ item.recipientNickname }}
</td>
<td class="text-center">
{{ item.sizeName }} / {{ item.sizeCode }}
</td>
<td class="text-center">
{{ item.categoryName }}
</td>
<td class="text-center">
{{ item.classificationNumber }}
</td>
<td class="text-center">
{{ item.courierCompanyName || '-' }}
</td>
<td class="text-center">
{{ item.trackingNumber || '-' }}
</td>
<td class="text-center">
{{ item.statusName }}
</td>
<td class="text-center">
<v-btn
class="ma-1"
small
:disabled="is_operating || is_loading"
@click="openDetail(item.applicationNo)"
>
상세
</v-btn>
<gift-actions
:actions="item.availableActions"
:disabled="is_operating || is_loading"
@select="requestAction(item, $event)"
/>
</td>
</tr>
<tr v-if="!gifts.length">
<td
:colspan="headers.length"
class="text-center"
>
{{ is_loading ? '조회 중입니다.' : list_error ? '목록을 불러오지 못했습니다. 다시 검색해 주세요.' : '조회된 선물 신청이 없습니다.' }}
</td>
</tr>
</tbody>
</v-simple-table>
</v-col>
</v-row>
<v-row class="text-center">
<v-col>
<v-pagination
:value="page"
:length="total_page"
:disabled="is_loading || is_operating"
:total-visible="10"
circle
@input="changePage"
/>
</v-col>
</v-row>
</v-container>
<v-dialog
v-model="show_detail_dialog"
max-width="1000px"
persistent
scrollable
>
<v-card>
<v-card-title>선물 상세</v-card-title>
<v-progress-linear
v-if="is_detail_loading"
indeterminate
/>
<v-card-text>
<template v-if="detail">
<div class="mb-4">
신청번호: {{ detail.applicationNo }} / 현재 상태: {{ detail.statusName }}
</div>
<v-row>
<v-col
v-for="member in memberSections"
:key="member.key"
cols="12"
md="6"
>
<h3 class="mb-2">
{{ member.title }}
</h3>
<v-simple-table>
<tbody>
<tr
v-for="field in memberFields"
:key="field.key"
>
<th>{{ field.label }}</th>
<td>{{ detail[member.key][field.key] || (member.key === 'recipientInfo' && field.key !== 'nickname' ? '미입력' : '-') }}</td>
</tr>
</tbody>
</v-simple-table>
</v-col>
<v-col
cols="12"
md="6"
>
<h3 class="mb-2">
상품 정보
</h3>
<v-simple-table>
<tbody>
<tr><th>사이즈</th><td>{{ detail.productInfo.sizeName }} / {{ detail.productInfo.sizeCode }}</td></tr>
<tr><th>카테고리</th><td>{{ detail.productInfo.categoryName }}</td></tr>
<tr><th>분류번호</th><td>{{ detail.productInfo.classificationNumber }}</td></tr>
</tbody>
</v-simple-table>
</v-col>
<v-col
cols="12"
md="6"
>
<h3 class="mb-2">
입고 배송 정보
</h3>
<v-simple-table>
<tbody>
<tr><th>택배사</th><td>{{ detail.inboundDeliveryInfo.courierCompanyName || '-' }}</td></tr>
<tr><th>운송장번호</th><td>{{ detail.inboundDeliveryInfo.trackingNumber || '-' }}</td></tr>
</tbody>
</v-simple-table>
</v-col>
</v-row>
<div class="mt-4">
<h3 class="mb-2">
가능한 액션
</h3>
<gift-actions
:actions="detail.availableActions"
:disabled="is_operating || is_detail_loading || is_loading"
@select="requestAction(detail, $event)"
/>
<span v-if="!detail.availableActions.length">현재 가능한 액션이 없습니다.</span>
</div>
</template>
<div v-else-if="!is_detail_loading">
상세 정보를 불러오지 못했습니다.
<v-btn
text
color="primary"
@click="getDetail(detailApplicationNo)"
>
다시 시도
</v-btn>
</div>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn
color="blue darken-1"
text
:disabled="is_operating"
@click="closeDetail"
>
닫기
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-dialog
v-model="show_reason_dialog"
max-width="500px"
persistent
>
<v-card>
<v-card-title>전달 불가 처리</v-card-title>
<v-card-text>
<p>신청번호: {{ pendingAction ? pendingAction.applicationNo : '' }}</p>
<v-form @submit.prevent="confirmReason">
<v-textarea
v-model="reason"
label="전달 불가 사유"
:rules="[validateUndeliverableReason]"
:error-messages="reason_error"
:disabled="is_operating"
counter="255"
maxlength="255"
auto-grow
rows="3"
@input="reason_error = ''"
/>
</v-form>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn
color="blue darken-1"
text
:disabled="is_operating"
@click="cancelAction"
>
취소
</v-btn>
<v-btn
color="blue darken-1"
text
:disabled="is_operating"
@click="confirmReason"
>
확인
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-dialog
v-model="show_confirm_dialog"
max-width="400px"
persistent
>
<v-card>
<v-card-title>상태 변경 확인</v-card-title>
<v-card-text v-if="pendingAction">
<p>신청번호: {{ pendingAction.applicationNo }}</p>
<p v-if="pendingAction.value === 'CANCEL'">
신청번호 {{ pendingAction.applicationNo }}의 선물 신청을 취소하시겠습니까?
</p>
<p v-else>
{{ pendingAction.label }}하시겠습니까?
</p>
<p v-if="pendingAction.value === 'CANCEL'">
사용한 캔 전액이 발신자에게 리워드캔으로 환불됩니다.
</p>
<p
v-if="pendingAction.value === 'MARK_UNDELIVERABLE'"
class="gift-reason"
>
사유: {{ reason.trim() }}
</p>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn
color="blue darken-1"
text
:disabled="is_operating"
@click="cancelConfirmation"
>
취소
</v-btn>
<v-btn
color="blue darken-1"
text
:loading="is_operating"
:disabled="is_operating"
@click="executeAction"
>
확인
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</div>
</template>
<script>
import * as api from '@/api/gift'
import { giftActions, giftStatuses, validateUndeliverableReason } from '@/utils/gift'
import GiftActions from './GiftActions.vue'
export default {
name: 'GiftList',
components: { GiftActions },
data() {
return {
giftStatuses,
headers: ['신청번호', '발송인 닉네임', '수취인 닉네임', '사이즈', '카테고리', '분류번호', '택배사', '운송장번호', '상태', '액션'],
memberSections: [{ key: 'senderInfo', title: '발송인 정보' }, { key: 'recipientInfo', title: '수취인 정보' }],
memberFields: [{ key: 'nickname', label: '닉네임' }, { key: 'name', label: '이름' }, { key: 'phoneNumber', label: '전화번호' }, { key: 'address', label: '주소' }],
filters: { status: '', applicationNo: '', nickname: '' },
appliedFilters: { status: '', applicationNo: '', nickname: '' },
gifts: [],
page: 1,
size: 20,
totalCount: 0,
hasNext: false,
is_loading: false,
list_error: false,
listRequestId: 0,
detail: null,
detailApplicationNo: '',
detailRequestId: 0,
is_detail_loading: false,
show_detail_dialog: false,
is_operating: false,
pendingAction: null,
show_reason_dialog: false,
show_confirm_dialog: false,
reason: '',
reason_error: ''
}
},
computed: {
total_page() {
const count = Math.max(1, Math.ceil(this.totalCount / this.size))
return this.hasNext ? Math.max(count, this.page + 1) : Math.max(1, this.page)
}
},
async created() {
await this.getGifts()
},
beforeDestroy() {
this.listRequestId++
this.detailRequestId++
},
methods: {
validateUndeliverableReason,
notifyError(error) {
const response = error.response && error.response.data
this.$dialog.notify.error((response && response.message) || error.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
},
checkResponse(response) {
if (response.success !== true) throw new Error(response.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
},
async getGifts(page = this.page) {
const requestId = ++this.listRequestId
this.is_loading = true
this.list_error = false
try {
const response = await api.getGifts({ ...this.appliedFilters, page: page - 1, size: this.size })
if (requestId !== this.listRequestId) return
this.checkResponse(response)
this.gifts = response.data.items
this.page = response.data.page + 1
this.size = response.data.size
this.totalCount = response.data.totalCount
this.hasNext = response.data.hasNext
} catch (error) {
if (requestId !== this.listRequestId) return
this.gifts = []
this.totalCount = 0
this.hasNext = false
this.list_error = true
this.notifyError(error)
} finally {
if (requestId === this.listRequestId) this.is_loading = false
}
},
async search() {
if (this.is_loading || this.is_operating) return
this.appliedFilters = {
status: this.filters.status || '',
applicationNo: (this.filters.applicationNo || '').trim(),
nickname: (this.filters.nickname || '').trim()
}
await this.getGifts(1)
},
async reset() {
if (this.is_loading || this.is_operating) return
this.filters = { status: '', applicationNo: '', nickname: '' }
await this.search()
},
async changePage(page) {
if (this.is_loading || this.is_operating) return
await this.getGifts(page)
},
async openDetail(applicationNo) {
if (this.is_operating) return
this.detail = null
this.show_detail_dialog = true
await this.getDetail(applicationNo)
},
async getDetail(applicationNo) {
const requestId = ++this.detailRequestId
this.detailApplicationNo = applicationNo
this.is_detail_loading = true
try {
const response = await api.getGift(applicationNo)
if (requestId !== this.detailRequestId) return
this.checkResponse(response)
this.detail = response.data
} catch (error) {
if (requestId !== this.detailRequestId) return
this.detail = null
this.notifyError(error)
} finally {
if (requestId === this.detailRequestId) this.is_detail_loading = false
}
},
closeDetail() {
if (this.is_operating) return
this.detailRequestId++
this.show_detail_dialog = false
this.is_detail_loading = false
this.detail = null
this.detailApplicationNo = ''
},
requestAction(item, value) {
if (this.is_operating || this.is_loading || this.is_detail_loading || this.pendingAction) return
const action = giftActions.find(action => action.value === value)
if (!action || !item.availableActions.includes(value)) return
this.pendingAction = { ...action, applicationNo: item.applicationNo }
this.reason = ''
this.reason_error = ''
if (value === 'MARK_UNDELIVERABLE') {
this.show_reason_dialog = true
} else {
this.show_confirm_dialog = true
}
},
confirmReason() {
if (this.is_operating || !this.pendingAction || this.pendingAction.value !== 'MARK_UNDELIVERABLE') return
const validation = validateUndeliverableReason(this.reason)
this.reason_error = validation === true ? '' : validation
if (validation === true) this.show_confirm_dialog = true
},
cancelConfirmation() {
if (this.is_operating) return
if (this.pendingAction && this.pendingAction.value === 'MARK_UNDELIVERABLE') {
this.show_confirm_dialog = false
} else {
this.cancelAction()
}
},
cancelAction() {
if (this.is_operating) return
this.show_confirm_dialog = false
this.show_reason_dialog = false
this.pendingAction = null
this.reason = ''
this.reason_error = ''
},
async refreshCurrentState() {
const refreshes = [this.getGifts()]
if (this.show_detail_dialog) refreshes.push(this.getDetail(this.detail ? this.detail.applicationNo : this.detailApplicationNo))
await Promise.all(refreshes)
},
async executeAction() {
if (this.is_operating || !this.pendingAction || !this.show_confirm_dialog) return
const action = this.pendingAction
if (action.value === 'MARK_UNDELIVERABLE' && validateUndeliverableReason(this.reason) !== true) {
this.show_confirm_dialog = false
this.confirmReason()
return
}
this.is_operating = true
try {
const response = action.value === 'MARK_UNDELIVERABLE'
? await api.markUndeliverable(action.applicationNo, this.reason.trim())
: await api[action.method](action.applicationNo)
this.checkResponse(response)
this.show_confirm_dialog = false
this.show_reason_dialog = false
this.pendingAction = null
this.reason = ''
this.$dialog.notify.success(`${action.label}되었습니다.`)
await this.refreshCurrentState()
} catch (error) {
this.notifyError(error)
if (action.value === 'CANCEL') await this.refreshCurrentState()
} finally {
this.is_operating = false
}
}
}
}
</script>
<style scoped>
.gift-reason {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
-256
View File
@@ -1,256 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-spacer />
<v-toolbar-title>받을 주소</v-toolbar-title>
<v-spacer />
</v-toolbar>
<br>
<v-container fluid>
<p>팬이 선물을 발송할 때 확인하는 받을 주소입니다.</p>
<v-progress-linear
v-if="is_loading"
indeterminate
/>
<v-alert
v-if="load_error"
type="error"
text
>
받을 주소를 불러오지 못했습니다.
<v-btn
text
:disabled="is_loading"
@click="getMailbox"
>
다시 조회
</v-btn>
</v-alert>
<p v-else-if="loaded && !mailbox">
등록된 받을 주소가 없습니다. 주소를 입력하고 저장해주세요.
</p>
<v-card>
<v-form @submit.prevent="saveMailbox">
<v-card-text>
<div
v-for="field in fields"
:key="field.key"
:class="{ 'mailbox-postcode-row': field.key === 'zipCode' }"
>
<v-text-field
:key="field.key"
v-model="form[field.key]"
:label="field.label"
:readonly="field.key === 'zipCode' || field.key === 'address'"
:disabled="field.key === 'zipCode' || field.key === 'address' || !loaded || is_loading || is_operating"
:filled="field.key === 'zipCode' || field.key === 'address'"
:error-messages="form_errors[field.key]"
outlined
dense
@input="$set(form_errors, field.key, '')"
/>
<v-btn
v-if="field.key === 'zipCode'"
type="button"
outlined
color="primary"
height="40"
:disabled="!loaded || is_loading || is_operating"
@click="openAddressSearch"
>
주소 검색
</v-btn>
</div>
<p class="text-caption grey--text text--darken-1">
우편번호와 주소는 주소 검색으로 입력해주세요. 상세주소는 직접 입력할 수 있습니다.
</p>
<p v-if="mailbox">
등록된 받을 주소: {{ mailbox.address }}
</p>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn
type="submit"
color="primary"
:loading="is_operating"
:disabled="!loaded || is_loading || is_operating"
>
저장
</v-btn>
</v-card-actions>
</v-form>
</v-card>
</v-container>
<v-dialog
v-model="show_address_search"
max-width="560px"
>
<v-card>
<v-card-title>주소 검색</v-card-title>
<v-card-text>
<v-progress-linear
v-if="is_postcode_loading"
indeterminate
/>
<div
ref="postcodeContainer"
style="width: 100%; height: 500px;"
/>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn
text
@click="show_address_search = false"
>
닫기
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</div>
</template>
<script>
import * as api from '@/api/gift_mailbox'
import { loadPostcode } from '@/utils/postcode'
export default {
name: 'GiftMailbox',
data() {
return {
fields: [
{ key: 'name', label: '받을 사람 이름', required: true },
{ key: 'phoneNumber', label: '연락처', required: true },
{ key: 'zipCode', label: '우편번호', required: true },
{ key: 'address', label: '주소', required: true },
{ key: 'addressDetail', label: '상세주소', required: false }
],
form: { name: '', phoneNumber: '', zipCode: '', address: '', addressDetail: '' },
form_errors: {},
mailbox: null,
loaded: false,
load_error: false,
is_loading: false,
show_address_search: false,
is_postcode_loading: false,
postcodeRequestId: 0,
is_operating: false
}
},
async created() {
await this.getMailbox()
},
beforeDestroy() {
this.postcodeRequestId++
},
methods: {
async openAddressSearch() {
if (!this.loaded || this.is_loading || this.is_operating) return
const requestId = ++this.postcodeRequestId
this.show_address_search = true
this.is_postcode_loading = true
try {
const Postcode = await loadPostcode()
await this.$nextTick()
if (requestId !== this.postcodeRequestId || !this.show_address_search) return
this.$refs.postcodeContainer.innerHTML = ''
new Postcode({
width: '100%',
height: '100%',
oncomplete: data => {
if (requestId !== this.postcodeRequestId || !this.show_address_search || this.is_operating) return
this.form.zipCode = data.zonecode
this.form.address = data.userSelectedType === 'R' ? data.roadAddress : data.jibunAddress
this.form.addressDetail = ''
this.$set(this.form_errors, 'zipCode', '')
this.$set(this.form_errors, 'address', '')
this.show_address_search = false
}
}).embed(this.$refs.postcodeContainer)
} catch (error) {
if (requestId !== this.postcodeRequestId || !this.show_address_search) return
this.show_address_search = false
this.notifyError(error)
} finally {
if (requestId === this.postcodeRequestId) this.is_postcode_loading = false
}
},
notifyError(error) {
const response = error.response && error.response.data
this.$dialog.notify.error((response && response.message) || error.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
},
checkResponse(response) {
if (response.success !== true) throw new Error(response.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
},
async getMailbox() {
if (this.is_loading || this.is_operating) return
this.is_loading = true
this.loaded = false
this.load_error = false
try {
const response = await api.getGiftMailbox()
this.checkResponse(response)
this.mailbox = response.data
const item = response.data || {}
const address = item.address || ''
const parts = address.match(/^\(([^)]+)\)\s*(.*)$/)
const street = parts ? parts[2] : address
const separator = street.indexOf(', ')
this.form = {
name: item.name || '',
phoneNumber: item.phoneNumber || '',
zipCode: parts ? parts[1] : '',
address: separator < 0 ? street : street.slice(0, separator),
addressDetail: separator < 0 ? '' : street.slice(separator + 2)
}
this.form_errors = {}
this.loaded = true
} catch (error) {
this.load_error = true
this.notifyError(error)
} finally {
this.is_loading = false
}
},
async saveMailbox() {
if (!this.loaded || this.is_loading || this.is_operating) return
const request = {}
this.form_errors = {}
this.fields.forEach(field => {
const value = (this.form[field.key] || '').trim()
request[field.key] = field.required ? value : value || null
if (field.required && !value) {
this.$set(this.form_errors, field.key, `${field.label}을(를) 입력해주세요.`)
}
})
if (Object.keys(this.form_errors).length) return
this.is_operating = true
try {
const response = await api.updateGiftMailbox(request)
this.checkResponse(response)
this.mailbox = response.data
this.form.name = response.data.name
this.form.phoneNumber = response.data.phoneNumber
this.$dialog.notify.success('받을 주소가 저장되었습니다.')
} catch (error) {
this.notifyError(error)
} finally {
this.is_operating = false
}
}
}
}
</script>
<style scoped>
.mailbox-postcode-row {
display: grid;
grid-template-columns: minmax(0, 200px) max-content;
gap: 12px;
align-items: start;
}
</style>
-304
View File
@@ -1,304 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-spacer />
<v-toolbar-title>선물 사이즈</v-toolbar-title>
<v-spacer />
<v-btn
v-if="availableSizes.length"
color="primary"
:disabled="!canCreate"
@click="openCreate"
>
사이즈 등록
</v-btn>
</v-toolbar>
<br>
<v-container fluid>
<v-row>
<v-col>
<div class="mb-2">
총 {{ sizes.length }}건
</div>
<v-progress-linear
v-if="is_loading"
indeterminate
/>
<v-simple-table class="elevation-10">
<thead>
<tr>
<th
v-for="header in headers"
:key="header"
class="text-center"
>
{{ header }}
</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in sizes"
:key="item.sizeCode"
>
<td class="text-center">
{{ item.sizeCode }}
</td>
<td class="text-center">
{{ item.name }}
</td>
<td class="text-center">
{{ item.basePriceCan.toLocaleString() }}
</td>
<td class="text-center">
{{ item.salePriceCan.toLocaleString() }}
</td>
<td class="text-center">
{{ item.isActive ? '활성' : '비활성' }}
</td>
<td class="text-center">
<v-btn
small
outlined
color="primary"
:disabled="is_loading || is_operating"
@click="openEdit(item)"
>
수정
</v-btn>
</td>
</tr>
<tr v-if="!sizes.length">
<td
:colspan="headers.length"
class="text-center grey--text"
>
{{ is_loading ? '조회 중입니다.' : list_error ? '목록을 불러오지 못했습니다.' : '등록된 선물 사이즈가 없습니다.' }}
</td>
</tr>
</tbody>
</v-simple-table>
<v-btn
v-if="list_error"
class="mt-3"
:disabled="is_loading || is_operating"
@click="getSizes"
>
다시 조회
</v-btn>
</v-col>
</v-row>
</v-container>
<v-dialog
v-model="show_form_dialog"
max-width="560px"
persistent
>
<v-card>
<v-form @submit.prevent="saveSize">
<v-card-title class="headline">
선물 사이즈 {{ isEdit ? '수정' : '등록' }}
</v-card-title>
<v-card-text>
<v-text-field
v-if="isEdit"
:value="form.sizeCode"
label="사이즈 코드"
readonly
:error-messages="form_errors.sizeCode"
/>
<v-select
v-else
v-model="form.sizeCode"
:items="availableSizes"
label="사이즈 코드"
hint="미등록 사이즈만 등록할 수 있습니다."
persistent-hint
:disabled="is_operating"
:error-messages="form_errors.sizeCode"
@change="$set(form_errors, 'sizeCode', '')"
/>
<v-text-field
v-if="isEdit"
:value="form.name"
label="사이즈명"
readonly
/>
<v-text-field
v-model="form.basePriceCan"
label="기본가"
type="number"
min="1"
step="1"
:disabled="is_operating"
:error-messages="form_errors.basePriceCan"
@input="clearPriceErrors"
/>
<v-text-field
v-model="form.salePriceCan"
label="판매가"
type="number"
min="1"
step="1"
:disabled="is_operating"
:error-messages="form_errors.salePriceCan"
@input="clearPriceErrors"
/>
<v-switch
v-model="form.isActive"
label="활성 여부"
:disabled="is_operating"
:error-messages="form_errors.isActive"
@change="$set(form_errors, 'isActive', '')"
/>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn
color="blue darken-1"
text
:disabled="is_operating"
@click="closeForm"
>
취소
</v-btn>
<v-btn
type="submit"
color="primary"
:loading="is_operating"
:disabled="is_operating || is_loading || (!isEdit && (!list_loaded || list_error))"
>
저장
</v-btn>
</v-card-actions>
</v-form>
</v-card>
</v-dialog>
</div>
</template>
<script>
import * as api from '@/api/gift_size'
import { giftSizes, createGiftSizeForm, buildGiftSizeRequest, validateGiftSize } from '@/utils/gift_size'
export default {
name: 'GiftSize',
data() {
return {
headers: ['사이즈 코드', '사이즈명', '기본가', '판매가', '활성 여부', '관리'],
sizes: [],
is_loading: false,
list_loaded: false,
list_error: false,
listRequestId: 0,
is_operating: false,
show_form_dialog: false,
isEdit: false,
form: createGiftSizeForm(),
form_errors: {}
}
},
computed: {
availableSizes() {
return giftSizes.filter(sizeCode => !this.sizes.some(item => item.sizeCode === sizeCode))
},
canCreate() {
return this.list_loaded && !this.list_error && !this.is_loading && !this.is_operating && this.availableSizes.length > 0
}
},
async created() {
await this.getSizes()
},
beforeDestroy() {
this.listRequestId++
},
methods: {
notifyError(error) {
const response = error.response && error.response.data
this.$dialog.notify.error((response && response.message) || error.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
},
checkResponse(response) {
if (response.success !== true) throw new Error(response.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
},
async getSizes() {
const requestId = ++this.listRequestId
this.is_loading = true
this.list_loaded = false
this.list_error = false
try {
const response = await api.getGiftSizePrices()
if (requestId !== this.listRequestId) return
this.checkResponse(response)
this.sizes = response.data
this.list_loaded = true
} catch (error) {
if (requestId !== this.listRequestId) return
this.sizes = []
this.list_error = true
this.notifyError(error)
} finally {
if (requestId === this.listRequestId) this.is_loading = false
}
},
openCreate() {
if (!this.canCreate) return
this.isEdit = false
this.form = createGiftSizeForm()
this.form_errors = {}
this.show_form_dialog = true
},
openEdit(item) {
if (this.is_loading || this.is_operating) return
this.isEdit = true
this.form = createGiftSizeForm(item)
this.form_errors = {}
this.show_form_dialog = true
},
closeForm() {
if (this.is_operating) return
this.show_form_dialog = false
},
clearPriceErrors() {
this.$set(this.form_errors, 'basePriceCan', '')
this.$set(this.form_errors, 'salePriceCan', '')
},
async saveSize() {
if (!this.show_form_dialog || this.is_operating || this.is_loading) return
if (!this.isEdit && (!this.list_loaded || this.list_error)) return
this.form_errors = validateGiftSize(this.form)
if (!this.isEdit && !this.form_errors.sizeCode && !this.availableSizes.includes(this.form.sizeCode)) {
this.$set(this.form_errors, 'sizeCode', '이미 등록된 사이즈입니다. 수정 버튼을 이용해 주세요.')
}
if (Object.keys(this.form_errors).length) return
const sizeCode = this.form.sizeCode
const request = buildGiftSizeRequest(this.form)
const action = this.isEdit ? '수정' : '등록'
this.is_operating = true
try {
const confirm = await this.$dialog.confirm({
title: `선물 사이즈 ${action} 확인`,
text: `${this.form.name || sizeCode} 사이즈의 가격과 활성 여부를 ${action}하시겠습니까?`,
actions: { false: '취소', true: '저장' }
})
if (!confirm) return
if (!this.isEdit && (!this.list_loaded || this.list_error || !this.availableSizes.includes(sizeCode))) {
this.$set(this.form_errors, 'sizeCode', '등록 가능한 사이즈를 다시 확인해 주세요.')
return
}
const response = await api.updateGiftSizePrice(sizeCode, request)
this.checkResponse(response)
this.$dialog.notify.success(`선물 사이즈가 ${action}되었습니다.`)
await this.getSizes()
this.show_form_dialog = false
} catch (error) {
this.notifyError(error)
} finally {
this.is_operating = false
}
}
}
}
</script>
+1 -30
View File
@@ -153,22 +153,6 @@
</v-col>
</v-row>
</v-card-text>
<v-card-text v-if="selected_recommend_live === null">
<v-row align="center">
<v-col cols="4">
언어
</v-col>
<v-col cols="8">
<v-select
v-model="lang"
:items="languageOptions"
item-text="label"
item-value="value"
label="언어 선택"
/>
</v-col>
</v-row>
</v-card-text>
<v-card-text>
<v-row align="center">
<v-col cols="4">
@@ -250,12 +234,6 @@ export default {
start_date: null,
end_date: null,
is_adult: false,
lang: 'ko',
languageOptions: [
{ label: '한국어', value: 'ko' },
{ label: '일본어', value: 'ja' },
{ label: '영어', value: 'en' },
],
headers: [
{
text: '이미지',
@@ -380,7 +358,6 @@ export default {
formData.append("start_date", this.start_date)
formData.append("end_date", this.end_date)
formData.append("is_adult", this.is_adult)
formData.append("lang", this.lang)
const res = await api.createRecommendCreatorBanner(formData);
if (res.status === 200 && res.data.success === true) {
@@ -406,8 +383,7 @@ export default {
this.image === null ||
this.creator_id === null ||
this.start_date === null ||
this.end_date === null ||
this.lang === null
this.end_date === null
) {
this.notifyError('내용을 입력하세요')
} else {
@@ -422,9 +398,6 @@ export default {
this.creator_id = null
this.start_date = null
this.end_date = null
this.is_adult = false
this.lang = 'ko'
this.selected_recommend_live = null
},
notifyError(message) {
@@ -498,8 +471,6 @@ export default {
}
},
showWriteDialog() {
this.selected_recommend_live = null
this.lang = 'ko'
this.show_write_dialog = true
},
}
+4 -141
View File
@@ -19,7 +19,7 @@
>
<v-btn
slot="append"
color="#3bb9f1"
color="#9970ff"
dark
@click="search"
>
@@ -171,7 +171,7 @@
<v-card-text>
<v-row align="center">
<v-col cols="4">
권한
사용 여부
</v-col>
<v-col cols="8">
<v-radio-group
@@ -183,32 +183,16 @@
value="CREATOR"
label="크리에이터"
/>
<v-radio
value="AGENT"
label="에이전트"
/>
<v-radio
value="USER"
label="일반회원"
/>
<v-radio
value="CONTENT_MANAGER"
label="콘텐츠 관리자"
/>
<v-spacer />
</v-radio-group>
</v-col>
</v-row>
</v-card-text>
<v-card-actions v-show="!is_loading">
<v-btn
color="error"
text
@click="showBlockReasonDialog"
>
차단
</v-btn>
<v-spacer />
<v-btn
color="blue darken-1"
text
@@ -216,6 +200,7 @@
>
비밀번호 재설정
</v-btn>
<v-spacer />
<v-btn
color="blue darken-1"
text
@@ -267,74 +252,6 @@
</v-card>
</v-dialog>
</v-row>
<v-row>
<v-dialog
v-model="show_block_reason_dialog"
max-width="500px"
persistent
>
<v-card>
<v-card-title>차단(탈퇴) 사유 입력</v-card-title>
<v-card-text>
<v-textarea
v-model="block_reason"
label="사유를 입력해주세요"
outlined
hide-details
/>
</v-card-text>
<v-card-actions v-show="!is_loading">
<v-spacer />
<v-btn
color="error"
text
@click="confirmBlock"
>
차단
</v-btn>
<v-btn
color="blue darken-1"
text
@click="cancelBlock"
>
취소
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-row>
<v-row>
<v-dialog
v-model="show_confirm_block_dialog"
max-width="500px"
persistent
>
<v-card>
<v-card-title class="text-h6">
'{{ nickname }}' 계정과 본인인증 정보, 같은 본인인증 정보를 사용하는 모든 계정을 차단합니다.
</v-card-title>
<v-card-actions v-show="!is_loading">
<v-spacer />
<v-btn
color="error"
text
@click="blockMember"
>
차단
</v-btn>
<v-btn
color="blue darken-1"
text
@click="cancelBlock"
>
취소
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-row>
</div>
</template>
@@ -357,9 +274,6 @@ export default {
user_type: null,
show_popup_dialog: false,
show_confirm_reset_password_dialog: false,
show_block_reason_dialog: false,
show_confirm_block_dialog: false,
block_reason: '',
}
},
@@ -453,10 +367,6 @@ export default {
this.user_type = 'USER'
} else if (member.userType === '크리에이터') {
this.user_type = 'CREATOR'
} else if (member.userType === '에이전트') {
this.user_type = 'AGENT'
} else if (member.userType === '콘텐츠 관리자') {
this.user_type = 'CONTENT_MANAGER'
}
this.email = member.email
@@ -472,51 +382,6 @@ export default {
this.user_type = null
this.show_popup_dialog = false
this.show_confirm_reset_password_dialog = false
this.show_block_reason_dialog = false
this.show_confirm_block_dialog = false
this.block_reason = ''
},
showBlockReasonDialog() {
this.show_popup_dialog = false
this.show_block_reason_dialog = true
},
cancelBlock() {
this.show_block_reason_dialog = false
this.show_confirm_block_dialog = false
this.block_reason = ''
this.show_popup_dialog = true
},
confirmBlock() {
if (this.block_reason.length === 0) {
this.notifyError('차단 사유를 입력해주세요.')
return
}
this.show_block_reason_dialog = false
this.show_confirm_block_dialog = true
},
async blockMember() {
this.is_loading = true
try {
const res = await api.blockMember(this.member.id, this.block_reason)
if (res.status === 200 && res.data.success === true) {
this.notifySuccess('차단되었습니다.')
this.cancel()
this.page = 1
await this.getMemberList()
} else {
this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
}
this.is_loading = false
} catch (e) {
this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
this.is_loading = false
}
},
async modify() {
@@ -524,9 +389,7 @@ export default {
if (
(this.user_type === 'CREATOR' && this.member.userType === '크리에이터') ||
(this.user_type === 'USER' && this.member.userType === '일반회원') ||
(this.user_type === 'AGENT' && this.member.userType === '에이전트') ||
(this.user_type === 'CONTENT_MANAGER' && this.member.userType === '콘텐츠 관리자')
(this.user_type === 'USER' && this.member.userType === '일반회원')
) {
this.notifyError("변경사항이 없습니다.")
} else {
+4 -27
View File
@@ -56,22 +56,6 @@
<v-card-title v-show="is_modify">
이벤트 수정
</v-card-title>
<v-card-text v-if="!is_modify">
<v-row align="center">
<v-col cols="4">
언어
</v-col>
<v-col cols="8">
<v-select
v-model="event.lang"
:items="langItems"
item-text="text"
item-value="value"
label="언어 선택"
/>
</v-col>
</v-row>
</v-card-text>
<v-card-text>
<v-text-field
v-model="event.title"
@@ -304,15 +288,10 @@ export default {
is_loading: false,
is_modify: false,
events: [],
event: {isAdult: '', lang: 'ko'},
event: {isAdult: ''},
show_write_dialog: false,
show_delete_confirm_dialog: false,
selected_event: {},
langItems: [
{ text: '한국어', value: 'ko' },
{ text: '일본어', value: 'ja' },
{ text: '영어', value: 'en' }
]
}
},
@@ -378,7 +357,6 @@ export default {
showWriteDialog() {
this.event.isAdult = ''
this.event.lang = this.event.lang || 'ko'
this.show_write_dialog = true
},
@@ -400,7 +378,7 @@ export default {
cancel() {
this.is_modify = false
this.event = {isAdult: '', lang: 'ko'}
this.event = {isAdult: ''}
this.selected_event = {}
this.show_write_dialog = false
},
@@ -442,7 +420,6 @@ export default {
formData.append("isPopup", this.event.isPopup ? this.event.isPopup : false)
formData.append("startDate", this.event.startDate)
formData.append("endDate", this.event.endDate)
formData.append("lang", this.event.lang || 'ko')
if (this.event.detailImage != null) {
formData.append("detail", this.event.detailImage)
@@ -466,7 +443,7 @@ export default {
this.notifySuccess('등록되었습니다.')
this.page = 1
await this.getEvents()
this.event = {isAdult: '', lang: 'ko'}
this.event = {isAdult: ''}
}
} catch (e) {
this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
@@ -529,7 +506,7 @@ export default {
this.notifySuccess('수정되었습니다.')
this.page = 1
await this.getEvents()
this.event = {isAdult: '', lang: 'ko'}
this.event = {isAdult: ''}
this.is_modify = false
} else {
this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
-677
View File
@@ -1,677 +0,0 @@
<template>
<div>
<v-toolbar dark>
<v-spacer />
<v-toolbar-title>가로형 서브 배너</v-toolbar-title>
<v-spacer />
</v-toolbar>
<br>
<v-dialog
v-model="show_write_dialog"
max-width="1000px"
persistent
>
<template v-slot:activator="{ on, attrs }">
<v-container>
<v-row align="center">
<v-col cols="9">
<v-radio-group
v-model="selected_placement"
row
@change="getSubBanners"
>
<v-radio
v-for="placement in placements"
:key="placement.value"
:label="placement.text"
:value="placement.value"
/>
</v-radio-group>
</v-col>
<v-spacer />
<v-col>
<v-btn
block
color="#3BB9F1"
dark
depressed
v-bind="attrs"
v-on="on"
@click="showCreateDialog"
>
배너 등록
</v-btn>
<v-btn
block
class="mt-2"
depressed
:disabled="is_loading"
@click="getSubBanners"
>
목록 새로고침
</v-btn>
</v-col>
</v-row>
<v-row>
<v-col>
<v-simple-table class="elevation-10">
<template>
<thead>
<tr>
<th class="text-center">
번호
</th>
<th class="text-center">
이미지
</th>
<th class="text-center">
언어
</th>
<th class="text-center">
웹 URL
</th>
<th class="text-center">
Android 딥링크
</th>
<th class="text-center">
iOS 딥링크
</th>
<th class="text-center">
노출 기간 (KST)
</th>
<th class="text-center">
상태
</th>
<th class="text-center">
관리
</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in sub_banners"
:key="item.id"
>
<td>{{ item.id }}</td>
<td>
<img
:src="item.imageUrl"
alt=""
class="list-image"
>
</td>
<td>{{ langText(item) }}</td>
<td>{{ item.webUrl || '-' }}</td>
<td>{{ item.androidDeepLink || '-' }}</td>
<td>{{ item.iosDeepLink || '-' }}</td>
<td>{{ scheduleRangeText(item) }}</td>
<td>{{ statusText(item) }}</td>
<td>
<v-btn
text
@click="showModifyDialog(item)"
>
수정
</v-btn>
<v-btn
text
@click="deleteConfirm(item)"
>
삭제
</v-btn>
</td>
</tr>
<tr v-if="sub_banners.length === 0">
<td
colspan="9"
class="text-center"
>
등록된 배너가 없습니다.
</td>
</tr>
</tbody>
</template>
</v-simple-table>
</v-col>
</v-row>
</v-container>
</template>
<v-card>
<v-card-title v-if="is_modify === true">
서브 배너 수정
</v-card-title>
<v-card-title v-else>
서브 배너 등록
</v-card-title>
<v-card-text>
<v-row align="center">
<v-col cols="4">
노출 위치
</v-col>
<v-col cols="8">
<v-radio-group
v-model="sub_banner.placement"
row
>
<v-radio
v-for="placement in placements"
:key="placement.value"
:label="placement.text"
:value="placement.value"
/>
</v-radio-group>
</v-col>
</v-row>
</v-card-text>
<v-card-text>
<v-row align="center">
<v-col cols="4">
<label for="sub-banner-lang">언어</label>
</v-col>
<v-col cols="8">
<v-select
id="sub-banner-lang"
v-model="sub_banner.lang"
:items="langs"
item-text="text"
item-value="value"
label="언어 선택"
:error-messages="form_errors.lang"
/>
</v-col>
</v-row>
<v-row>
<v-col class="guide-text">
영어(EN)는 저장과 목록 조회는 가능하지만 현재 앱 공개 국가 매핑(JP → 일본어, 그 외 → 한국어)에서는 노출되지 않습니다.
배너 소재 언어와 연결된 이벤트 언어는 운영자가 직접 맞춰 주세요.
</v-col>
</v-row>
</v-card-text>
<v-card-text>
<v-row align="center">
<v-col cols="4">
웹 URL
</v-col>
<v-col cols="8">
<v-text-field
v-model="sub_banner.web_url"
label="https://example.com/promo"
:error-messages="form_errors.web_url"
/>
</v-col>
</v-row>
<v-row align="center">
<v-col cols="4">
Android 딥링크
</v-col>
<v-col cols="8">
<v-text-field
v-model="sub_banner.android_deep_link"
label="sampleapp://promo"
:error-messages="form_errors.android_deep_link"
/>
</v-col>
</v-row>
<v-row align="center">
<v-col cols="4">
iOS 딥링크
</v-col>
<v-col cols="8">
<v-text-field
v-model="sub_banner.ios_deep_link"
label="sampleapp://promo"
:error-messages="form_errors.ios_deep_link"
/>
</v-col>
</v-row>
<v-row>
<v-col class="guide-text">
웹 URL, Android 딥링크, iOS 딥링크 중 최소 한 개는 입력해야 합니다. 비워둔 주소는 null 로 저장되어 해제됩니다.
</v-col>
</v-row>
</v-card-text>
<v-card-text>
<v-row align="center">
<v-col cols="4">
노출 기간 (한국 시간 KST 기준)
</v-col>
<v-col cols="4">
<v-text-field
v-model="sub_banner.start_date"
type="datetime-local"
label="시작 일시 (KST, 선택)"
:error-messages="form_errors.start_date"
clearable
@click:clear="sub_banner.start_date = ''"
/>
</v-col>
<v-col cols="4">
<v-text-field
v-model="sub_banner.end_date"
type="datetime-local"
label="종료 일시 (KST, 선택)"
:error-messages="form_errors.end_date"
clearable
@click:clear="sub_banner.end_date = ''"
/>
</v-col>
</v-row>
<v-row>
<v-col class="guide-text">
입력한 시간은 한국 시간(KST) 분 단위로 저장됩니다. 비워두면 해당 경계의 기간 제한이 없습니다.
(시작만 있으면 시작 분의 :00 부터, 종료만 있으면 종료 분의 :59 까지 노출)
</v-col>
</v-row>
</v-card-text>
<div class="image-select">
<label for="image">
배너 이미지 등록
</label>
<v-file-input
id="image"
v-model="sub_banner.image"
accept="image/*"
@change="imageAdd"
/>
</div>
<img
v-if="sub_banner.image_url"
:src="sub_banner.image_url"
alt=""
class="image-preview"
>
<v-card-text
v-if="is_modify === true"
class="guide-text"
>
이미지를 새로 등록하지 않으면 기존 이미지가 그대로 유지됩니다.
</v-card-text>
<v-card-text
v-if="submit_blocked === true"
class="guide-text"
>
응답을 받지 못해 저장 여부를 알 수 없습니다. 중복 저장을 막기 위해 다시 보내지 않습니다. 목록에서 결과를 확인한 뒤 진행해 주세요.
</v-card-text>
<v-card-actions v-show="!is_loading">
<v-spacer />
<v-btn
color="blue darken-1"
text
@click="cancel"
>
취소
</v-btn>
<v-btn
v-if="is_modify === true"
color="blue darken-1"
text
:disabled="is_loading || submit_blocked"
@click="modify"
>
수정
</v-btn>
<v-btn
v-else
color="blue darken-1"
text
:disabled="is_loading || submit_blocked"
@click="submit"
>
등록
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-dialog
v-model="show_delete_confirm_dialog"
max-width="400px"
persistent
>
<v-card>
<v-card-text />
<v-card-text>
삭제하시겠습니까?
</v-card-text>
<v-card-actions v-show="!is_loading">
<v-spacer />
<v-btn
color="blue darken-1"
text
@click="deleteCancel"
>
취소
</v-btn>
<v-btn
color="blue darken-1"
text
:disabled="is_loading"
@click="deleteSubBanner"
>
확인
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</div>
</template>
<script>
import * as api from "@/api/sub_banner"
import {
appendSubBannerRequestPart,
buildSubBannerCreateRequest,
buildSubBannerUpdateRequest,
createSubBannerForm,
formatScheduleRange,
langLabel,
scheduleStatus,
SUB_BANNER_LANGS,
SUB_BANNER_PLACEMENTS,
validateSubBannerForm
} from "@/utils/sub_banner"
export default {
name: "SubBannerView",
data() {
return {
is_loading: false,
is_modify: false,
submit_blocked: false,
show_write_dialog: false,
show_delete_confirm_dialog: false,
placements: SUB_BANNER_PLACEMENTS,
langs: SUB_BANNER_LANGS,
selected_placement: SUB_BANNER_PLACEMENTS[0].value,
sub_banners: [],
selected_sub_banner: {},
sub_banner: createSubBannerForm(),
form_errors: {}
}
},
async created() {
await this.getSubBanners()
},
methods: {
notifyError(message) {
this.$dialog.notify.error(message)
},
notifySuccess(message) {
this.$dialog.notify.success(message)
},
// 400 등 4xx 는 ApiResponse 가 아닌 표준 Spring Boot body 일 수 있어 단정하지 않는다.
clientErrorMessage(error) {
const response = error && error.response
if (!response || response.status < 400 || response.status >= 500) return null
const body = response.data
const message = body && typeof body === 'object' ? (body.message || body.error) : null
return message || '입력값을 서버가 거부했습니다. 값을 확인한 뒤 다시 시도해 주세요.'
},
imageAdd(payload) {
const file = payload
if (!file) {
// 새 이미지를 해제하면 기존 이미지 상태로 되돌린다.
this.sub_banner.image = null
this.sub_banner.image_url = this.selected_sub_banner.imageUrl || null
return
}
this.sub_banner.image = file
this.sub_banner.image_url = URL.createObjectURL(file)
},
showCreateDialog() {
this.is_modify = false
this.selected_sub_banner = {}
this.sub_banner = createSubBannerForm({placement: this.selected_placement})
this.form_errors = {}
this.submit_blocked = false
this.show_write_dialog = true
},
showModifyDialog(subBanner) {
// 별도 상세 조회가 없으므로 목록의 전체 객체로 form 을 채운다.
this.is_modify = true
this.selected_sub_banner = subBanner
this.sub_banner = createSubBannerForm(subBanner)
this.form_errors = {}
this.submit_blocked = false
this.show_write_dialog = true
},
cancel() {
this.is_modify = false
this.show_write_dialog = false
this.show_delete_confirm_dialog = false
this.selected_sub_banner = {}
this.sub_banner = createSubBannerForm({placement: this.selected_placement})
this.form_errors = {}
this.submit_blocked = false
},
scheduleRangeText(subBanner) {
return formatScheduleRange(subBanner.startDate, subBanner.endDate)
},
statusText(subBanner) {
return scheduleStatus(subBanner)
},
langText(subBanner) {
// lang 이 없는 응답을 KO 로 간주하지 않는다.
return langLabel(subBanner.lang) || '-'
},
validate() {
const errors = validateSubBannerForm(
this.sub_banner,
this.is_modify === true ? this.selected_sub_banner : null
)
this.form_errors = errors
const messages = Object.keys(errors).map((key) => errors[key])
if (messages.length > 0) {
this.notifyError(messages[0])
return false
}
if (this.is_modify !== true && !this.sub_banner.image) {
this.notifyError('배너 이미지를 등록하세요.')
return false
}
return true
},
deleteConfirm(subBanner) {
this.selected_sub_banner = subBanner
this.show_delete_confirm_dialog = true
},
deleteCancel() {
this.show_delete_confirm_dialog = false
this.selected_sub_banner = {}
},
async submit() {
if (this.is_loading === true || this.submit_blocked === true) return
if (!this.validate()) return
this.is_loading = true
try {
const formData = new FormData()
formData.append("image", this.sub_banner.image)
appendSubBannerRequestPart(formData, buildSubBannerCreateRequest(this.sub_banner))
const res = await api.saveSubBanner(formData)
if (res.status === 200 && res.data.success === true) {
this.selected_placement = this.sub_banner.placement
this.cancel()
this.notifySuccess('등록되었습니다.')
await this.getSubBanners()
} else {
// 실패 시 입력값과 기존 이미지 상태를 그대로 보존한다.
this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
}
} catch (e) {
const clientError = this.clientErrorMessage(e)
if (clientError !== null) {
// 서버가 확실히 거부했으므로 입력값·선택 파일·날짜를 그대로 두고 재전송도 막지 않는다.
this.notifyError(clientError)
} else {
// 결과가 불명확하므로 자동 재시도 없이 중복 전송을 막고 목록으로 상태를 확인한다.
this.submit_blocked = true
this.notifyError('응답을 받지 못했습니다. 등록 여부를 목록에서 확인해 주세요.')
}
} finally {
this.is_loading = false
}
if (this.submit_blocked === true) {
await this.getSubBanners()
}
},
async modify() {
if (this.is_loading === true || this.submit_blocked === true) return
if (!this.validate()) return
this.is_loading = true
try {
const formData = new FormData()
// 이미지를 새로 선택하지 않으면 image 파트를 생략해 기존 이미지를 유지한다.
if (this.sub_banner.image) {
formData.append("image", this.sub_banner.image)
}
appendSubBannerRequestPart(
formData,
buildSubBannerUpdateRequest(this.sub_banner, this.selected_sub_banner)
)
const res = await api.modifySubBanner(this.sub_banner.id, formData)
if (res.status === 200 && res.data.success === true) {
this.selected_placement = this.sub_banner.placement
this.cancel()
this.notifySuccess('수정되었습니다.')
await this.getSubBanners()
} else {
this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
}
} catch (e) {
const clientError = this.clientErrorMessage(e)
if (clientError !== null) {
this.notifyError(clientError)
} else {
this.submit_blocked = true
this.notifyError('응답을 받지 못했습니다. 수정 여부를 목록에서 확인해 주세요.')
}
} finally {
this.is_loading = false
}
if (this.submit_blocked === true) {
await this.getSubBanners()
}
},
async deleteSubBanner() {
if (this.is_loading === true) return
this.is_loading = true
try {
const res = await api.deleteSubBanner(this.selected_sub_banner.id)
if (res.status === 200 && res.data.success === true) {
this.cancel()
this.notifySuccess('삭제되었습니다.')
await this.getSubBanners()
} else {
this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
}
} catch (e) {
this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
} finally {
this.is_loading = false
}
},
async getSubBanners() {
this.is_loading = true
try {
const res = await api.getSubBanners(this.selected_placement)
if (res.status === 200 && res.data.success === true) {
// 서버가 id 오름차순으로 내려주므로 재정렬하지 않고 전부 표시한다.
this.sub_banners = Array.isArray(res.data.data) ? res.data.data : []
// 응답에 lang 이 없으면 KO 로 간주하지 않고 계약 미충족을 알린다.
if (this.sub_banners.some((item) => !item || item.lang === undefined)) {
this.notifyError('목록 응답에 lang 이 없습니다. 언어 계약이 적용된 서버인지 확인해 주세요.')
}
} else {
// 조회 실패를 빈 목록으로 오인하지 않는다.
this.notifyError(res.data.message || '목록을 불러오지 못했습니다. 다시 시도해 주세요.')
}
} catch (e) {
this.notifyError('목록을 불러오지 못했습니다. 다시 시도해 주세요.')
} finally {
this.is_loading = false
}
}
}
}
</script>
<style scoped>
.image-select label {
display: inline-block;
padding: 10px 20px;
background-color: #232d4a;
color: #fff;
vertical-align: middle;
font-size: 15px;
cursor: pointer;
border-radius: 5px;
}
.v-file-input {
position: absolute;
width: 0;
height: 0;
padding: 0;
overflow: hidden;
border: 0;
}
.guide-text {
font-size: 12px;
color: #666;
}
.list-image {
width: 160px;
object-fit: cover;
}
.image-preview {
max-width: 100%;
width: 320px;
object-fit: cover;
margin-top: 10px;
}
</style>
+6 -35
View File
@@ -66,14 +66,6 @@
/>
<v-card-text class="text-center">
<div>{{ resolveSeriesTitle(banner) }}</div>
<v-chip
v-if="banner.lang"
x-small
label
class="mt-1"
>
{{ banner.lang === 'ko' ? '한국어' : banner.lang === 'ja' ? '일본어' : '영어' }}
</v-chip>
</v-card-text>
<v-card-actions>
<v-spacer />
@@ -154,17 +146,6 @@
/>
</v-col>
</v-row>
<v-row v-if="!isEdit">
<v-col cols="12">
<v-select
v-model="bannerForm.lang"
:items="languages"
label="언어 선택"
outlined
:rules="[v => !!v || '언어를 선택하세요']"
/>
</v-col>
</v-row>
<v-row>
<v-col cols="12">
<v-text-field
@@ -312,17 +293,11 @@ export default {
searchResults: [],
searchPerformed: false,
previewImage: null,
languages: [
{ text: '한국어', value: 'ko' },
{ text: '일본어', value: 'ja' },
{ text: '영어', value: 'en' }
],
bannerForm: {
image: null,
imageUrl: '',
seriesId: null,
bannerId: null,
lang: 'ko'
bannerId: null
},
imageRules: [
v => !!v || this.isEdit || '이미지를 선택하세요'
@@ -331,7 +306,7 @@ export default {
},
computed: {
isFormValid() {
return (this.bannerForm.image || (this.isEdit && this.bannerForm.imageUrl)) && this.selectedSeries && (this.isEdit || this.bannerForm.lang)
return (this.bannerForm.image || (this.isEdit && this.bannerForm.imageUrl)) && this.selectedSeries
}
},
watch: {
@@ -393,7 +368,7 @@ export default {
showAddDialog() {
this.isEdit = false
this.selectedSeries = null
this.bannerForm = { image: null, imageUrl: '', seriesId: null, bannerId: null, lang: 'ko' }
this.bannerForm = { image: null, imageUrl: '', seriesId: null, bannerId: null }
this.previewImage = null
this.searchKeyword = ''
this.searchResults = []
@@ -412,8 +387,7 @@ export default {
image: null,
imageUrl: banner.imageUrl || banner.imagePath,
seriesId: banner.seriesId,
bannerId: banner.id,
lang: banner.lang || 'ko'
bannerId: banner.id
}
this.previewImage = null
this.searchKeyword = ''
@@ -424,7 +398,7 @@ export default {
closeDialog() {
this.showDialog = false
this.selectedSeries = null
this.bannerForm = { image: null, imageUrl: '', seriesId: null, bannerId: null, lang: 'ko' }
this.bannerForm = { image: null, imageUrl: '', seriesId: null, bannerId: null }
this.previewImage = null
this.searchKeyword = ''
this.searchResults = []
@@ -476,16 +450,13 @@ export default {
})
if (response && response.status === 200 && response.data && response.data.success === true) {
this.notifySuccess('배너가 수정되었습니다.')
this.closeDialog()
this.refreshBanners()
} else {
this.notifyError('배너 수정을 실패했습니다.')
}
} else {
const response = await createSeriesBanner({
image: this.bannerForm.image,
seriesId: this.selectedSeries.id,
lang: this.bannerForm.lang
seriesId: this.selectedSeries.id
})
if (response && response.status === 200 && response.data && response.data.success === true) {
this.notifySuccess('배너가 추가되었습니다.')
+3 -133
View File
@@ -56,7 +56,7 @@
{{ item.title }}
</td>
<td>
{{ displayDate(item) }}
{{ item.date }}
</td>
</tr>
</tbody>
@@ -95,33 +95,6 @@
:editor-toolbar="customToolbar"
/>
</v-card-text>
<v-card-text>
<v-checkbox
v-model="use_schedule"
:disabled="is_modify && !can_change_publish_at"
label="예약 공개"
hide-details
/>
<v-text-field
v-show="use_schedule"
v-model="publish_at_input"
:disabled="is_modify && !can_change_publish_at"
label="공개 시각 (KST)"
type="datetime-local"
/>
<v-checkbox
v-show="is_modify && can_change_publish_at && !use_schedule"
v-model="publish_now"
label="지금 공개로 전환"
hide-details
/>
<div
v-show="is_modify && !can_change_publish_at"
class="text-caption grey--text"
>
이미 공개된 공지는 공개 시각을 변경할 수 없습니다.
</div>
</v-card-text>
<v-card-actions v-show="!is_loading">
<v-btn
v-show="is_modify"
@@ -212,11 +185,6 @@ export default {
total_page: 0,
notices: [],
notice: {},
use_schedule: false,
publish_now: false,
publish_at_input: '',
original_publish_at: null,
can_change_publish_at: true,
show_write_dialog: false,
show_delete_confirm_dialog: false,
customToolbar: [
@@ -251,44 +219,6 @@ export default {
await this.getNotices()
},
// "yyyy-MM-dd HH:mm:ss"(KST) -> "yyyy-MM-ddTHH:mm" (시간대 변환 없이 문자열만 변환)
toInputValue(publishAt) {
if (!publishAt) return ''
return publishAt.replace(' ', 'T').substring(0, 16)
},
// "yyyy-MM-ddTHH:mm" -> "yyyy-MM-dd HH:mm:ss"(KST)
toContractValue(input) {
if (!input) return null
const value = input.replace('T', ' ')
if (value.length === 16) return value + ':00'
return value.substring(0, 19)
},
nowKstString() {
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Asia/Seoul',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
}).formatToParts(new Date()).reduce((acc, p) => {
acc[p.type] = p.value
return acc
}, {})
return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}:${parts.second}`
},
displayDate(item) {
const source = (item.isScheduled === true && item.publishAt) ? item.publishAt : item.createdAt
if (!source) return ''
return source.substring(0, 10)
},
async getNotices() {
this.is_loading = true
@@ -315,7 +245,6 @@ export default {
},
showWriteDialog() {
this.resetPublishState()
this.show_write_dialog = true
},
@@ -324,35 +253,12 @@ export default {
this.notice.id = item.id;
this.notice.title = item.title;
this.notice.content = item.content;
this.resetPublishState()
this.original_publish_at = item.publishAt || null
// 예약 공지이면서 공개 시각이 아직 도래하지 않은 경우에만 공개 시각 변경을 시도할 수 있다.
// 공개 경계의 최종 판단은 API 응답을 따른다.
this.can_change_publish_at = item.isScheduled === true &&
!!item.publishAt &&
item.publishAt > this.nowKstString()
if (this.can_change_publish_at) {
this.use_schedule = true
this.publish_at_input = this.toInputValue(item.publishAt)
}
this.show_write_dialog = true
},
resetPublishState() {
this.use_schedule = false
this.publish_now = false
this.publish_at_input = ''
this.original_publish_at = null
this.can_change_publish_at = true
},
cancel() {
this.is_modify = false
this.notice = {}
this.resetPublishState()
this.show_write_dialog = false
},
@@ -367,36 +273,9 @@ export default {
return false;
}
if (this.use_schedule) {
if (this.publish_at_input == null || this.publish_at_input.trim().length === 0) {
this.notifyError("공개 시각을 입력하세요.")
return false;
}
if (this.toContractValue(this.publish_at_input) <= this.nowKstString()) {
this.notifyError("공개 시각은 현재보다 미래여야 합니다.")
return false;
}
}
return true
},
// 수정 요청에 담을 publishAt 산출
// undefined: 생략(기존 예약 상태 보존), null: 지금 공개로 전환, 문자열: 재예약
publishAtForModify() {
if (!this.can_change_publish_at) return undefined
if (this.publish_now && !this.use_schedule) return null
if (this.use_schedule) {
const publishAt = this.toContractValue(this.publish_at_input)
if (publishAt !== this.original_publish_at) return publishAt
}
return undefined
},
async submit() {
if (!this.validate()) return;
if (this.is_loading) return;
@@ -404,15 +283,13 @@ export default {
this.is_loading = true
try {
const publishAt = this.use_schedule ? this.toContractValue(this.publish_at_input) : null
const res = await api.save(this.notice.title, this.notice.content, publishAt)
const res = await api.save(this.notice.title, this.notice.content)
if (res.status === 200 && res.data.success === true) {
this.show_write_dialog = false
this.notifySuccess('등록되었습니다.')
this.page = 1
await this.getNotices()
this.notice = {}
this.resetPublishState()
} else {
this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
}
@@ -430,19 +307,13 @@ export default {
this.is_loading = true
try {
const res = await api.modify(
this.notice.id,
this.notice.title,
this.notice.content,
this.publishAtForModify()
)
const res = await api.modify(this.notice.id, this.notice.title, this.notice.content)
if (res.status === 200 && res.data.success === true) {
this.show_write_dialog = false
this.notifySuccess('수정되었습니다.')
this.page = 1
await this.getNotices()
this.notice = {}
this.resetPublishState()
this.is_modify = false
} else {
this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
@@ -475,7 +346,6 @@ export default {
this.page = 1
await this.getNotices()
this.notice = {}
this.resetPublishState()
this.is_modify = false
} else {
this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
-251
View File
@@ -1,251 +0,0 @@
const assert = require('assert').strict
const fs = require('fs')
const path = require('path')
const Module = require('module')
const { transformSync } = require('@babel/core')
const compiler = require('vue-template-compiler')
const Vue = require('vue')
const root = path.resolve(__dirname, '..')
const originalResolve = Module._resolveFilename
Module._resolveFilename = function(request, parent, ...rest) {
return originalResolve.call(this, request.startsWith('@/') ? path.join(root, 'src', request.slice(2)) : request, parent, ...rest)
}
const originalJs = require.extensions['.js']
function compileScript(source, filename) {
return transformSync(source, {
filename,
babelrc: false,
configFile: false,
plugins: ['@babel/plugin-transform-modules-commonjs']
}).code
}
require.extensions['.js'] = (module, filename) => {
if (!filename.startsWith(path.join(root, 'src') + path.sep)) return originalJs(module, filename)
module._compile(compileScript(fs.readFileSync(filename, 'utf8'), filename), filename)
}
require.extensions['.vue'] = (module, filename) => {
const { script, template } = compiler.parseComponent(fs.readFileSync(filename, 'utf8'))
const compiled = compiler.compile(template.content)
assert.deepEqual(compiled.errors, [], `${filename}: 템플릿 컴파일`)
module._compile(compileScript(script.content, filename), filename)
Object.assign(module.exports.default, compiler.compileToFunctions(template.content))
}
const {
applyScheduleToModifyRequest,
applyScheduleToSaveRequest,
createBannerScheduleForm,
formatScheduleRange,
toDateTimeLocalInput,
toServerDateTime,
validateBannerSchedule
} = require('../src/utils/audio_content_banner')
const Banner = require('../src/views/Content/ContentMainTopBanner.vue').default
const tests = []
const test = (name, run) => tests.push({ name, run })
const envelope = data => ({ success: true, data })
const banner = (overrides = {}) => ({
id: 1, type: 'LINK', link: 'https://sodalive.net', isAdult: false, tabId: 1, lang: 'ko',
thumbnailImageUrl: 'https://cdn/banner.png', startDate: null, endDate: null,
...overrides
})
function nodes(vnode) {
if (!vnode) return []
return [vnode].concat((vnode.children || (vnode.componentOptions && vnode.componentOptions.children) || []).flatMap(nodes))
}
const text = vnode => nodes(vnode).map(node => node.text || '').join('').trim()
function activatorNodes(vm) {
const dialog = nodes(vm._render()).find(node => node.tag === 'v-dialog' && node.data.scopedSlots && node.data.scopedSlots.activator)
return [].concat(dialog.data.scopedSlots.activator({ on: {}, attrs: {} }))
}
const activatorText = vm => activatorNodes(vm).flatMap(nodes).map(node => node.text || '').join(' ')
function page() {
const errors = []
const successes = []
const vm = new Vue({ ...Banner, created: undefined })
vm.$dialog = { notify: { error: message => errors.push(message), success: message => successes.push(message) } }
return { vm, errors, successes }
}
function requestOf(formData) {
return JSON.parse(formData.get('request'))
}
function stubFormData() {
global.FormData = class {
constructor() { this.parts = new Map() }
append(key, value) { this.parts.set(key, value) }
get(key) { return this.parts.has(key) ? this.parts.get(key) : null }
has(key) { return this.parts.has(key) }
}
}
test('예약 기간 변환: KST 문자열과 datetime-local 값을 시간 이동 없이 왕복한다', () => {
assert.equal(toDateTimeLocalInput('2026-10-28 10:30'), '2026-10-28T10:30')
assert.equal(toServerDateTime('2026-10-28T10:30'), '2026-10-28 10:30')
assert.equal(toServerDateTime(toDateTimeLocalInput('2026-10-28 10:30')), '2026-10-28 10:30')
assert.equal(toServerDateTime('2026-10-28T10:30:00'), '2026-10-28 10:30')
for (const empty of [null, undefined, '', ' ', 'null']) {
assert.equal(toDateTimeLocalInput(empty), '')
assert.equal(toServerDateTime(empty), null)
}
})
test('예약 기간 표시: 네 조합과 미설정 배너를 목록에서 확인할 수 있다', () => {
assert.equal(formatScheduleRange(null, null), '상시 노출')
assert.equal(formatScheduleRange('2026-10-28 10:30', null), '2026-10-28 10:30 ~')
assert.equal(formatScheduleRange(null, '2026-10-29 23:59'), '~ 2026-10-29 23:59')
assert.equal(formatScheduleRange('2026-10-28 10:30', '2026-10-29 23:59'), '2026-10-28 10:30 ~ 2026-10-29 23:59')
const { vm } = page()
vm.banners = [
banner({ id: 1 }),
banner({ id: 2, startDate: '2030-01-01 00:00' }),
banner({ id: 3, endDate: '2020-01-01 00:00' }),
banner({ id: 4, startDate: '2026-10-28 10:30', endDate: '2026-10-29 23:59' })
]
const rendered = activatorText(vm)
assert.ok(rendered.includes('상시 노출'))
assert.ok(rendered.includes('2030-01-01 00:00 ~'))
assert.ok(rendered.includes('~ 2020-01-01 00:00'))
assert.ok(rendered.includes('2026-10-28 10:30 ~ 2026-10-29 23:59'))
})
test('예약 기간 검증: 역전 범위는 거부하고 같은 분과 한쪽만 입력은 허용한다', () => {
assert.deepEqual(validateBannerSchedule({ start_date: '', end_date: '' }), {})
assert.deepEqual(validateBannerSchedule({ start_date: '2026-10-28T10:30', end_date: '' }), {})
assert.deepEqual(validateBannerSchedule({ start_date: null, end_date: '2026-10-28T10:30' }), {})
assert.deepEqual(validateBannerSchedule({ start_date: '2026-10-28T10:30', end_date: '2026-10-28T10:30' }), {})
assert.deepEqual(validateBannerSchedule({ start_date: '2020-01-01T00:00', end_date: '2020-01-01T00:01' }), {})
const reversed = validateBannerSchedule({ start_date: '2026-10-28T10:31', end_date: '2026-10-28T10:30' })
assert.deepEqual(Object.keys(reversed), ['end_date'])
assert.equal(typeof reversed.end_date, 'string')
assert.deepEqual(Object.keys(validateBannerSchedule({ start_date: '2026-10-28', end_date: '' })), ['start_date'])
})
test('예약 기간 등록 요청: 입력한 값만 포함하고 비우면 생략한다', () => {
assert.deepEqual(applyScheduleToSaveRequest({ type: 'LINK' }, { start_date: '', end_date: '' }), { type: 'LINK' })
assert.deepEqual(
applyScheduleToSaveRequest({ type: 'LINK' }, { start_date: '2026-10-28T10:30', end_date: '2026-10-29T23:59' }),
{ type: 'LINK', startDate: '2026-10-28 10:30', endDate: '2026-10-29 23:59' }
)
assert.deepEqual(
applyScheduleToSaveRequest({}, { start_date: '2026-10-28T10:30', end_date: null }),
{ startDate: '2026-10-28 10:30' }
)
})
test('예약 기간 수정 요청: 미변경은 생략하고 지운 경계는 null을 전송한다', () => {
const saved = { startDate: '2026-10-28 10:30', endDate: '2026-10-29 23:59' }
assert.deepEqual(applyScheduleToModifyRequest({ id: 1 }, createBannerScheduleForm(saved), saved), { id: 1 })
assert.deepEqual(
applyScheduleToModifyRequest({ id: 1 }, { start_date: '', end_date: '2026-10-29T23:59' }, saved),
{ id: 1, startDate: null }
)
assert.deepEqual(
applyScheduleToModifyRequest({ id: 1 }, { start_date: null, end_date: null }, saved),
{ id: 1, startDate: null, endDate: null }
)
assert.deepEqual(
applyScheduleToModifyRequest({ id: 1 }, { start_date: '2026-10-28T10:30', end_date: '2026-11-01T00:00' }, saved),
{ id: 1, endDate: '2026-11-01 00:00' }
)
assert.deepEqual(applyScheduleToModifyRequest({ id: 1 }, createBannerScheduleForm(banner()), banner()), { id: 1 })
})
test('수정 폼: 조회값으로 초기화되고 다른 배너 입력 상태가 남지 않는다', () => {
const { vm } = page()
vm.showModifyBannerDialog(banner({ startDate: '2026-10-28 10:30', endDate: '2026-10-29 23:59' }))
assert.equal(vm.banner.start_date, '2026-10-28T10:30')
assert.equal(vm.banner.end_date, '2026-10-29T23:59')
const fields = nodes(vm._render()).filter(node => node.tag === 'v-text-field' && node.data.attrs.type === 'datetime-local')
assert.deepEqual(fields.map(field => field.data.attrs.label), ['시작 일시 (선택)', '종료 일시 (선택)'])
assert.ok(text(vm._render()).includes('한국 시간'))
vm.cancel()
assert.deepEqual(createBannerScheduleForm(), { start_date: '', end_date: '' })
assert.equal(vm.banner.start_date, '')
assert.equal(vm.banner.end_date, '')
vm.showModifyBannerDialog(banner({ id: 2 }))
assert.equal(vm.banner.start_date, '')
assert.equal(vm.banner.end_date, '')
})
test('수정 저장: 날짜만 바꾸면 이미지 없이 request JSON만 전송한다', async () => {
stubFormData()
const { vm, successes } = page()
const calls = []
Vue.axios = {
put: async (...args) => { calls.push(args); return { status: 200, data: envelope(null) } },
get: async () => ({ status: 200, data: envelope([]) })
}
vm.showModifyBannerDialog(banner({ startDate: '2026-10-28 10:30', endDate: '2026-10-29 23:59' }))
vm.banner.thumbnail_image = null
vm.banner.start_date = '2026-11-01T09:00'
vm.banner.end_date = ''
await vm.modify()
assert.equal(calls.length, 1)
assert.equal(calls[0][0], '/admin/audio-content/banner')
const formData = calls[0][1]
assert.equal(formData.has('image'), false)
assert.deepEqual(requestOf(formData), { id: 1, startDate: '2026-11-01 09:00', endDate: null })
assert.deepEqual(successes, ['수정되었습니다.'])
})
test('수정 저장: 역전 범위는 저장을 막고 success=false 메시지를 노출한다', async () => {
stubFormData()
const blocked = page()
const calls = []
Vue.axios = { put: async () => { calls.push('PUT'); return { status: 200, data: envelope(null) } } }
blocked.vm.showModifyBannerDialog(banner())
blocked.vm.banner.start_date = '2026-10-29T10:31'
blocked.vm.banner.end_date = '2026-10-29T10:30'
await blocked.vm.modify()
assert.deepEqual(calls, [])
assert.equal(blocked.errors.length, 1)
assert.deepEqual(Object.keys(blocked.vm.schedule_errors), ['end_date'])
const failed = page()
Vue.axios = { put: async () => ({ status: 200, data: { success: false, message: '예약 기간이 올바르지 않습니다.' } }) }
failed.vm.showModifyBannerDialog(banner())
failed.vm.banner.start_date = '2026-10-29T10:30'
await failed.vm.modify()
assert.deepEqual(failed.errors, ['예약 기간이 올바르지 않습니다.'])
assert.deepEqual(failed.successes, [])
})
test('등록 저장: 이미지와 예약 기간을 함께 전송하고 성공 후 목록을 재조회한다', async () => {
stubFormData()
const { vm, successes } = page()
const calls = []
Vue.axios = {
post: async (...args) => { calls.push(args); return { status: 200, data: envelope(null) } },
get: async (...args) => { calls.push(args); return { status: 200, data: envelope([banner()]) } }
}
vm.banner.type = 'LINK'
vm.banner.link = 'https://sodalive.net'
vm.banner.is_adult = false
vm.banner.thumbnail_image = { name: 'banner.png' }
vm.banner.start_date = '2026-10-28T10:30'
vm.banner.end_date = '2026-10-29T23:59'
await vm.submit()
assert.equal(calls[0][0], '/admin/audio-content/banner')
assert.equal(calls[0][1].get('image').name, 'banner.png')
assert.deepEqual(requestOf(calls[0][1]), {
type: 'LINK', isAdult: false, lang: 'ko', link: 'https://sodalive.net',
startDate: '2026-10-28 10:30', endDate: '2026-10-29 23:59'
})
assert.deepEqual(calls[1], ['/admin/audio-content/banner?tabId=1'])
assert.deepEqual(successes, ['등록되었습니다.'])
assert.deepEqual(Array.from(vm.banners), [banner()])
})
;(async () => {
for (const { name, run } of tests) {
try {
await run()
console.log(`PASS ${name}`)
} catch (error) {
process.exitCode = 1
console.error(`FAIL ${name}`, error)
}
}
})()
-226
View File
@@ -1,226 +0,0 @@
const assert = require('assert').strict
const fs = require('fs')
const path = require('path')
const Module = require('module')
const { transformSync } = require('@babel/core')
const compiler = require('vue-template-compiler')
const Vue = require('vue')
const root = path.resolve(__dirname, '..')
const originalResolve = Module._resolveFilename
Module._resolveFilename = function(request, parent, ...rest) {
return originalResolve.call(this, request.startsWith('@/') ? path.join(root, 'src', request.slice(2)) : request, parent, ...rest)
}
const originalJs = require.extensions['.js']
function compileScript(source, filename) {
return transformSync(source, {
filename,
babelrc: false,
configFile: false,
plugins: ['@babel/plugin-transform-modules-commonjs']
}).code
}
require.extensions['.js'] = (module, filename) => {
if (!filename.startsWith(path.join(root, 'src') + path.sep)) return originalJs(module, filename)
module._compile(compileScript(fs.readFileSync(filename, 'utf8'), filename), filename)
}
require.extensions['.vue'] = (module, filename) => {
const { script, template } = compiler.parseComponent(fs.readFileSync(filename, 'utf8'))
const compiled = compiler.compile(template.content)
assert.deepEqual(compiled.errors, [], `${filename}: 템플릿 컴파일`)
module._compile(compileScript(script.content, filename), filename)
Object.assign(module.exports.default, compiler.compileToFunctions(template.content))
}
const api = require('../src/api/member')
const CreatorList = require('../src/views/Creator/CreatorList.vue').default
const tests = []
const test = (name, run) => tests.push({ name, run })
const creator = (overrides = {}) => ({
id: 123, email: 'a@b.c', nickname: '하늘', userType: '크리에이터', container: 'aos', ...overrides
})
function page(accounts = [creator()]) {
const errors = []
const successes = []
const vm = new Vue({ ...CreatorList, created: undefined })
vm.$dialog = { notify: { error: message => errors.push(message), success: message => successes.push(message) } }
vm.accounts = accounts
return { vm, errors, successes }
}
function deferred() {
let resolve
const promise = new Promise(done => { resolve = done })
return { promise, resolve }
}
const ok = displayName => ({ status: 200, data: { success: true, message: null, data: { creatorId: 123, locale: 'ja', originalNickname: '하늘', displayName }, errorProperty: null } })
test('API: JA 표시 이름은 정확한 PUT 경로와 displayName 본문만 전송한다', async () => {
const calls = []
Vue.axios = { put: async (...args) => { calls.push(args); return ok('ソラ') } }
await api.updateCreatorLocalizedNameJa(123, 'ソラ')
await api.updateCreatorLocalizedNameJa(123, '')
assert.deepEqual(calls, [
['/api/v2/admin/creators/123/localized-names/ja', { displayName: 'ソラ' }],
['/api/v2/admin/creators/123/localized-names/ja', { displayName: '' }]
])
assert.equal(typeof api.updateCreatorLocalizedNameJa, 'function')
})
test('초안: JA 없음은 빈 입력, 있음은 등록값으로 초기화하고 원본을 복사하지 않는다', () => {
const { vm } = page()
vm.showPopupDialog(creator({ localizedNames: {} }))
assert.equal(vm.japanese_display_name, '')
assert.equal(vm.nickname, '하늘')
assert.ok(vm.japanese_display_name_hint.includes('등록되지 않았습니다'))
vm.japanese_display_name = '편집중'
vm.japanese_display_name_error = '이전 오류'
vm.showPopupDialog(creator({ id: 7, nickname: 'Sky', localizedNames: { ja: 'ソラ', en: 'Sky' } }))
assert.equal(vm.japanese_display_name, 'ソラ')
assert.equal(vm.japanese_display_name_error, '')
assert.equal(vm.nickname, 'Sky')
})
test('검증: code point 255 허용, 256 및 공백 256 차단, 자동 잘라내기 없음', async () => {
const { vm, errors } = page()
Vue.axios = { put: async () => { throw new Error('호출되면 안 됨') } }
for (const value of ['😀'.repeat(256), ' '.repeat(256)]) {
vm.showPopupDialog(creator({ localizedNames: {} }))
vm.japanese_display_name = value
await vm.modify()
assert.ok(vm.japanese_display_name_error.length > 0)
assert.equal(vm.japanese_display_name, value)
assert.equal(vm.show_popup_dialog, true)
}
assert.deepEqual(errors, [])
const calls = []
Vue.axios = { put: async (...args) => { calls.push(args); return ok('😀'.repeat(255)) } }
vm.showPopupDialog(creator({ localizedNames: {} }))
vm.japanese_display_name = '😀'.repeat(255)
await vm.modify()
assert.equal(calls.length, 1)
assert.equal(vm.japanese_display_name_error, '')
})
test('저장: 공백·이모지를 가공 없이 전송하고 성공 시 JA만 갱신한다', async () => {
const calls = []
Vue.axios = { put: async (...args) => { calls.push(args); return ok(' 手動 Name 😀 ') } }
const account = creator({ localizedNames: { en: 'Sky' } })
const { vm, successes } = page([account])
vm.showPopupDialog(account)
vm.japanese_display_name = ' 手動 Name 😀 '
await vm.modify()
assert.deepEqual(calls[0][1], { displayName: ' 手動 Name 😀 ' })
assert.deepEqual(account.localizedNames, { en: 'Sky', ja: ' 手動 Name 😀 ' })
assert.equal(account.nickname, '하늘')
assert.equal(successes.length, 1)
assert.equal(vm.show_popup_dialog, false)
vm.showPopupDialog(account)
assert.equal(vm.japanese_display_name, ' 手動 Name 😀 ')
})
test('해제: 빈 문자열을 전송하고 null 응답에서 JA 키만 제거한다', async () => {
const calls = []
Vue.axios = { put: async (...args) => { calls.push(args); return ok(null) } }
const account = creator({ localizedNames: { ja: 'ソラ', en: 'Sky' } })
const { vm } = page([account])
vm.showPopupDialog(account)
vm.japanese_display_name = ''
await vm.modify()
assert.deepEqual(calls[0][1], { displayName: '' })
assert.deepEqual(account.localizedNames, { en: 'Sky' })
vm.showPopupDialog(account)
assert.equal(vm.japanese_display_name, '')
assert.ok(vm.japanese_display_name_hint.includes('등록되지 않았습니다'))
})
test('실패: success false에서 서버 메시지·필드 오류와 입력을 유지하고 저장 상태를 바꾸지 않는다', async () => {
Vue.axios = { put: async () => ({ status: 200, data: { success: false, message: '서버 오류 메시지', data: null, errorProperty: 'displayName' } }) }
const account = creator({ localizedNames: { ja: 'ソラ' } })
const { vm, errors, successes } = page([account])
vm.showPopupDialog(account)
vm.japanese_display_name = '新しい'
await vm.modify()
assert.deepEqual(errors, ['서버 오류 메시지'])
assert.deepEqual(successes, [])
assert.equal(vm.japanese_display_name_error, '서버 오류 메시지')
assert.equal(vm.japanese_display_name, '新しい')
assert.equal(vm.show_popup_dialog, true)
assert.deepEqual(account.localizedNames, { ja: 'ソラ' })
Vue.axios = { put: async () => { throw new Error('network') } }
await vm.modify()
assert.equal(vm.japanese_display_name, '新しい')
assert.deepEqual(account.localizedNames, { ja: 'ソラ' })
assert.equal(vm.is_saving, false)
})
test('상호작용: 취소는 무요청, 중복 저장 방지, IME 조합 중 Enter 제출 차단', async () => {
const account = creator({ localizedNames: {} })
const { vm, errors } = page([account])
Vue.axios = { put: async () => { throw new Error('호출되면 안 됨') } }
vm.showPopupDialog(account)
vm.japanese_display_name = 'ソラ'
vm.cancel()
assert.equal(vm.show_popup_dialog, false)
assert.equal(vm.japanese_display_name, '')
assert.deepEqual(errors, [])
const gate = deferred()
let count = 0
Vue.axios = { put: async () => { count += 1; await gate.promise; return ok('ソラ') } }
vm.showPopupDialog(account)
vm.japanese_display_name = 'ソラ'
const first = vm.modify()
await vm.modify()
vm.is_composing = true
vm.submitByEnter()
gate.resolve()
await first
assert.equal(count, 1)
})
test('대상 보호: 응답은 요청한 ID에만 적용하고 다른 항목을 덮어쓰지 않는다', async () => {
const first = creator({ id: 1, localizedNames: {} })
const second = creator({ id: 2, localizedNames: { ja: '他' } })
const { vm } = page([first, second])
const gate = deferred()
Vue.axios = { put: async () => { await gate.promise; return { status: 200, data: { success: true, message: null, data: { creatorId: 1, locale: 'ja', originalNickname: '하늘', displayName: 'ソラ' }, errorProperty: null } } } }
vm.showPopupDialog(first)
vm.japanese_display_name = 'ソラ'
const saving = vm.modify()
vm.showPopupDialog(second)
gate.resolve()
await saving
assert.deepEqual(first.localizedNames, { ja: 'ソラ' })
assert.deepEqual(second.localizedNames, { ja: '他' })
assert.equal(vm.japanese_display_name, '他')
})
test('목록: JA 미등록은 미등록으로 표시하고 수정 버튼을 노출한다', () => {
const { vm } = page([creator({ localizedNames: {} }), creator({ id: 2, localizedNames: { ja: 'ソラ' } })])
assert.equal(vm.japaneseNameOf(vm.accounts[0]), '')
assert.equal(vm.japaneseNameOf(vm.accounts[1]), 'ソラ')
const source = fs.readFileSync(path.join(root, 'src/views/Creator/CreatorList.vue'), 'utf8')
assert.ok(source.includes('showPopupDialog(item)'))
assert.ok(!source.includes('maxlength="255"'))
assert.ok(!source.includes('v-model.trim="japanese_display_name"'))
})
;(async () => {
for (const { name, run } of tests) {
try {
await run()
console.log(`PASS ${name}`)
} catch (error) {
process.exitCode = 1
console.error(`FAIL ${name}`, error)
}
}
})()
-523
View File
@@ -1,523 +0,0 @@
const assert = require('assert').strict
const fs = require('fs')
const path = require('path')
const Module = require('module')
const { transformSync } = require('@babel/core')
const compiler = require('vue-template-compiler')
const Vue = require('vue')
const root = path.resolve(__dirname, '..')
const originalResolve = Module._resolveFilename
Module._resolveFilename = function(request, parent, ...rest) {
return originalResolve.call(this, request.startsWith('@/') ? path.join(root, 'src', request.slice(2)) : request, parent, ...rest)
}
const originalJs = require.extensions['.js']
function compileScript(source, filename) {
return transformSync(source, {
filename,
babelrc: false,
configFile: false,
plugins: ['@babel/plugin-transform-modules-commonjs']
}).code
}
require.extensions['.js'] = (module, filename) => {
if (!filename.startsWith(path.join(root, 'src') + path.sep)) return originalJs(module, filename)
module._compile(compileScript(fs.readFileSync(filename, 'utf8'), filename), filename)
}
require.extensions['.vue'] = (module, filename) => {
const { script, template } = compiler.parseComponent(fs.readFileSync(filename, 'utf8'))
const compiled = compiler.compile(template.content)
assert.deepEqual(compiled.errors, [], `${filename}: 템플릿 컴파일`)
module._compile(compileScript(script.content, filename), filename)
Object.assign(module.exports.default, compiler.compileToFunctions(template.content))
}
const api = require('../src/api/gift')
const { giftActions, giftStatuses, validateUndeliverableReason } = require('../src/utils/gift')
const GiftActions = require('../src/views/Gift/GiftActions.vue').default
const GiftList = require('../src/views/Gift/GiftList.vue').default
const SideMenu = require('../src/components/SideMenu.vue').default
const tests = []
const test = (name, run) => tests.push({ name, run })
const envelope = data => ({ success: true, data })
const list = (overrides = {}) => ({ items: [], page: 0, size: 20, totalCount: 0, hasNext: false, ...overrides })
const detail = (overrides = {}) => ({
applicationNo: 'G-001', status: 'TRACKING_REGISTERED', statusName: '발송 확인',
availableActions: ['ARRIVE_MAILBOX', 'MARK_UNDELIVERABLE'],
senderInfo: { nickname: '발송인', name: '이름', phoneNumber: '010', address: '주소' },
recipientInfo: { nickname: '수취인', name: '', phoneNumber: '', address: '' },
productInfo: { sizeName: '소형', sizeCode: 'SMALL', categoryName: '문구', classificationNumber: 'C1' },
inboundDeliveryInfo: { courierCompanyName: null, trackingNumber: null },
...overrides
})
function page() {
const errors = []
const successes = []
const vm = new Vue({ ...GiftList, created: undefined })
vm.$dialog = { notify: { error: message => errors.push(message), success: message => successes.push(message) } }
return { vm, errors, successes }
}
function deferred() {
let resolve
const promise = new Promise(done => { resolve = done })
return { promise, resolve }
}
function nodes(vnode) {
if (!vnode) return []
return [vnode].concat((vnode.children || (vnode.componentOptions && vnode.componentOptions.children) || []).flatMap(nodes))
}
test('API: 기본 페이지와 조합 필터를 query로 전달하고 envelope를 반환한다', async () => {
const calls = []
const response = envelope(list())
Vue.axios = { get: async (...args) => { calls.push(args); return { data: response } } }
assert.equal(await api.getGifts(), response)
assert.deepEqual(calls[0], ['/api/v2/admin/gifts', { params: { page: 0, size: 20 } }])
await api.getGifts({ status: 'ARRIVED_AT_MAILBOX', applicationNo: 'G-01', nickname: '닉 네임', page: 2, size: 10 })
assert.deepEqual(calls[1][1].params, { status: 'ARRIVED_AT_MAILBOX', applicationNo: 'G-01', nickname: '닉 네임', page: 2, size: 10 })
await api.getGifts({ status: '', applicationNo: '', nickname: '' })
assert.deepEqual(calls[2][1].params, { page: 0, size: 20 })
})
test('API: 상세 및 다섯 가지 POST 경로/본문을 정확하게 전달한다', async () => {
const calls = []
Vue.axios = {
get: async (...args) => { calls.push(['GET', ...args]); return { data: envelope(detail()) } },
post: async (...args) => { calls.push(['POST', ...args]); return { data: envelope({ status: 'ARRIVED_AT_MAILBOX' }) } }
}
await api.getGift('G/001')
await api.arriveMailbox('G/001')
await api.completeInspection('G/001')
await api.completeDelivery('G/001')
await api.markUndeliverable('G/001', '파손')
await api.cancelGift('G/001')
assert.deepEqual(calls, [
['GET', '/api/v2/admin/gifts/G%2F001'],
['POST', '/api/v2/admin/gifts/G%2F001/arrive-mailbox'],
['POST', '/api/v2/admin/gifts/G%2F001/complete-inspection'],
['POST', '/api/v2/admin/gifts/G%2F001/complete-delivery'],
['POST', '/api/v2/admin/gifts/G%2F001/mark-undeliverable', { reason: '파손' }],
['POST', '/api/v2/admin/gifts/G%2F001/cancel']
])
})
test('액션: 서버 availableActions에 있는 버튼만 실제 템플릿에서 노출한다', () => {
assert.deepEqual(giftActions.map(action => [action.value, action.label]), [
['ARRIVE_MAILBOX', '사서함 도착 처리'], ['COMPLETE_INSPECTION', '검수 완료 처리'],
['COMPLETE_DELIVERY', '전달 완료 처리'], ['MARK_UNDELIVERABLE', '전달 불가 처리'], ['CANCEL', '신청 취소']
])
const scenarios = [['CANCEL'], ['ARRIVE_MAILBOX', 'MARK_UNDELIVERABLE'], ['COMPLETE_INSPECTION', 'MARK_UNDELIVERABLE'], ['COMPLETE_DELIVERY', 'MARK_UNDELIVERABLE'], [], [], []]
for (const actions of scenarios.concat([['UNKNOWN'], ['MARK_UNDELIVERABLE']])) {
const vm = new Vue({ ...GiftActions, propsData: { actions } })
const buttons = nodes(vm._render()).filter(node => node.tag === 'v-btn')
assert.deepEqual(buttons.map(button => nodes(button).map(node => node.text || '').join('').trim()), giftActions.filter(action => actions.includes(action.value)).map(action => action.label))
}
})
test('필터: 전체와 일곱 가지 상태를 한국어로 제공한다', () => {
assert.deepEqual(giftStatuses.map(status => [status.value, status.text]), [
['', '전체'], ['RECEIVED', '접수 완료'], ['TRACKING_REGISTERED', '발송 확인'],
['ARRIVED_AT_MAILBOX', '사서함 도착'], ['INSPECTION_COMPLETED', '검수 완료'],
['DELIVERED', '전달 완료'], ['UNDELIVERABLE', '전달 불가'], ['CANCELED', '신청 취소']
])
})
test('액션 버튼: 선택 이벤트와 중복 실행 방지 속성을 연결한다', () => {
const vm = new Vue({ ...GiftActions, propsData: { actions: ['ARRIVE_MAILBOX'], disabled: true } })
const button = nodes(vm._render()).find(node => node.tag === 'v-btn')
assert.equal(button.data.attrs.disabled, true)
let selected
let stopped = false
vm.$on('select', action => { selected = action })
button.data.on.click({ stopPropagation: () => { stopped = true } })
assert.equal(selected, 'ARRIVE_MAILBOX')
assert.equal(stopped, true)
})
test('전달 불가 사유: 빈 값/공백/256자는 거부하고 255자는 허용한다', () => {
for (const value of ['', ' \n\t ', null, undefined, '가'.repeat(256)]) {
assert.notEqual(validateUndeliverableReason(value), true)
}
assert.equal(validateUndeliverableReason('가'.repeat(255)), true)
assert.equal(validateUndeliverableReason(' 파손 '), true)
})
test('목록: 검색은 첫 페이지, 페이지 이동은 적용된 필터와 서버 size를 유지한다', async () => {
const { vm } = page()
const calls = []
Vue.axios = { get: async (url, config) => {
calls.push(config.params)
return { data: envelope(list({ page: config.params.page, size: 10, totalCount: 25, hasNext: config.params.page < 2 })) }
} }
vm.filters = { status: 'RECEIVED', applicationNo: ' G-01 ', nickname: ' 닉네임 ' }
vm.page = 3
await vm.search()
assert.deepEqual(calls[0], { status: 'RECEIVED', applicationNo: 'G-01', nickname: '닉네임', page: 0, size: 20 })
assert.equal(vm.page, 1)
assert.equal(vm.total_page, 3)
vm.filters.nickname = '아직 검색하지 않은 값'
await vm.changePage(2)
assert.deepEqual(calls[1], { status: 'RECEIVED', applicationNo: 'G-01', nickname: '닉네임', page: 1, size: 10 })
await vm.reset()
assert.deepEqual(calls[2], { page: 0, size: 10 })
assert.deepEqual(vm.filters, { status: '', applicationNo: '', nickname: '' })
})
test('페이지네이션: 빈 결과 및 마지막 페이지의 hasNext를 반영한다', () => {
const { vm } = page()
assert.equal(vm.total_page, 1)
vm.totalCount = 100
vm.page = 2
vm.hasNext = false
assert.equal(vm.total_page, 2)
vm.hasNext = true
assert.equal(vm.total_page, 5)
})
test('목록: 열과 빈 값을 표시하고 상세 버튼과 액션 이벤트를 연결한다', async () => {
const { vm } = page()
const item = {
applicationNo: 'G-001', senderNickname: '발송인', recipientNickname: '수취인',
sizeName: '소형', sizeCode: 'S', categoryName: '문구', classificationNumber: 'C1',
courierCompanyName: null, trackingNumber: null, statusName: '발송 확인', availableActions: ['ARRIVE_MAILBOX']
}
vm.gifts = [item]
const rendered = nodes(vm._render())
const cells = rendered.filter(node => node.tag === 'td').map(node => nodes(node).map(child => child.text || '').join('').trim())
assert.deepEqual(cells.slice(0, 9), ['G-001', '발송인', '수취인', '소형 / S', '문구', 'C1', '-', '-', '발송 확인'])
assert.equal(rendered.filter(node => node.tag === 'th').length, 10)
const actions = rendered.find(node => node.componentOptions && node.componentOptions.Ctor.options.name === 'GiftActions')
assert.deepEqual(Array.from(actions.componentOptions.propsData.actions), ['ARRIVE_MAILBOX'])
actions.componentOptions.listeners.select('ARRIVE_MAILBOX')
assert.equal(vm.pendingAction.applicationNo, 'G-001')
vm.cancelAction()
Vue.axios = { get: async url => {
assert.equal(url, '/api/v2/admin/gifts/G-001')
return { data: envelope(detail()) }
} }
const button = rendered.find(node => node.tag === 'v-btn' && nodes(node).some(child => (child.text || '').trim() === '상세'))
await button.data.on.click()
assert.equal(vm.show_detail_dialog, true)
assert.equal(vm.detail.applicationNo, 'G-001')
})
test('상세: 수취인 미입력과 배송정보 null을 표시하고 모든 정보를 제공한다', async () => {
const { vm } = page()
Vue.axios = { get: async () => ({ data: envelope(detail()) }) }
await vm.openDetail('G-001')
const text = nodes(vm._render()).map(node => node.text || '').join(' ')
for (const label of ['발송인 정보', '수취인 정보', '상품 정보', '입고 배송 정보', '미입력', '발송 확인', 'G-001', '소형', '문구', 'C1']) assert.ok(text.includes(label), label)
assert.ok(text.includes('-'))
})
test('액션: 확인 전 POST하지 않고 취소/미허용 액션은 실행하지 않는다', async () => {
const { vm } = page()
let posts = 0
Vue.axios = { post: async () => { posts++; return { data: envelope({}) } } }
vm.requestAction(detail(), 'COMPLETE_DELIVERY')
assert.equal(vm.show_confirm_dialog, false)
vm.requestAction(detail(), 'ARRIVE_MAILBOX')
assert.equal(vm.show_confirm_dialog, true)
assert.equal(posts, 0)
vm.cancelAction()
await vm.executeAction()
assert.equal(posts, 0)
})
test('전달 불가: 사유 검증 후 확인창을 열고 trim된 사유만 전송한다', async () => {
const { vm } = page()
const posts = []
Vue.axios = {
post: async (...args) => { posts.push(args); return { data: envelope({ status: 'UNDELIVERABLE' }) } },
get: async () => ({ data: envelope(list()) })
}
vm.requestAction(detail(), 'MARK_UNDELIVERABLE')
assert.equal(vm.show_reason_dialog, true)
assert.equal(vm.show_confirm_dialog, false)
for (const reason of ['', ' \n ', '가'.repeat(256)]) {
vm.reason = reason
vm.confirmReason()
await vm.executeAction()
assert.equal(vm.show_confirm_dialog, false)
assert.equal(posts.length, 0)
}
vm.reason = ' 파손 '
vm.confirmReason()
assert.equal(vm.show_confirm_dialog, true)
assert.equal(posts.length, 0)
await vm.executeAction()
assert.deepEqual(posts, [['/api/v2/admin/gifts/G-001/mark-undeliverable', { reason: '파손' }]])
})
test('전달 불가: 확인 취소 시 사유를 유지하고 입력 모달 취소 시 초기화한다', () => {
const { vm } = page()
vm.requestAction(detail(), 'MARK_UNDELIVERABLE')
vm.reason = '파손'
vm.confirmReason()
vm.cancelConfirmation()
assert.equal(vm.show_confirm_dialog, false)
assert.equal(vm.show_reason_dialog, true)
assert.equal(vm.reason, '파손')
vm.cancelAction()
assert.equal(vm.show_reason_dialog, false)
assert.equal(vm.pendingAction, null)
assert.equal(vm.reason, '')
})
test('액션: 각 무본문 액션을 확인 후 실행하며 닫힌 상세는 조회하지 않는다', async () => {
const scenarios = [
['ARRIVE_MAILBOX', 'arrive-mailbox'], ['COMPLETE_INSPECTION', 'complete-inspection'], ['COMPLETE_DELIVERY', 'complete-delivery']
]
for (const [action, endpoint] of scenarios) {
const { vm, successes } = page()
const calls = []
Vue.axios = {
post: async (...args) => { calls.push(args); return { data: envelope({}) } },
get: async (url, config) => {
assert.equal(url, '/api/v2/admin/gifts')
assert.equal(config.params.page, 0)
return { data: envelope(list()) }
}
}
vm.requestAction(detail({ availableActions: [action] }), action)
await vm.executeAction()
assert.deepEqual(calls, [[`/api/v2/admin/gifts/G-001/${endpoint}`]])
assert.equal(successes.length, 1)
}
})
test('성공: 중복 실행을 차단하고 목록과 열린 상세를 재조회한다', async () => {
const { vm, successes } = page()
const pending = deferred()
const calls = []
Vue.axios = {
post: async (...args) => { calls.push(['POST', ...args]); await pending.promise; return { data: envelope({ status: 'ARRIVED_AT_MAILBOX' }) } },
get: async (url, config) => {
calls.push(['GET', url, config])
return { data: envelope(config ? list({ page: 2, totalCount: 60 }) : detail({ status: 'ARRIVED_AT_MAILBOX', availableActions: ['COMPLETE_INSPECTION', 'MARK_UNDELIVERABLE'] })) }
}
}
vm.appliedFilters = { status: 'TRACKING_REGISTERED', applicationNo: '', nickname: '발송인' }
vm.page = 3
vm.detail = detail()
vm.show_detail_dialog = true
vm.requestAction(vm.detail, 'ARRIVE_MAILBOX')
const operation = vm.executeAction()
await vm.executeAction()
pending.resolve()
await operation
assert.equal(calls.filter(call => call[0] === 'POST').length, 1)
assert.deepEqual(calls.find(call => call[1] === '/api/v2/admin/gifts')[2].params, { status: 'TRACKING_REGISTERED', nickname: '발송인', page: 2, size: 20 })
assert.ok(calls.some(call => call[1] === '/api/v2/admin/gifts/G-001'))
assert.equal(vm.detail.status, 'ARRIVED_AT_MAILBOX')
assert.equal(successes.length, 1)
assert.equal(vm.is_operating, false)
assert.equal(vm.show_confirm_dialog, false)
})
test('실패: envelope 실패/HTTP 오류에 공통 오류 알림을 표시한다', async () => {
const { vm, errors, successes } = page()
Vue.axios = { get: async () => ({ data: { success: false, message: '조회 실패' } }) }
await vm.getGifts()
assert.ok(errors.includes('조회 실패'))
for (const fail of [async () => ({ data: { success: false, message: '상태 변경 실패' } }), async () => { throw { response: { data: { message: '권한 없음' } } } }]) {
Vue.axios.post = fail
vm.requestAction(detail(), 'ARRIVE_MAILBOX')
await vm.executeAction()
assert.equal(vm.is_operating, false)
vm.cancelAction()
}
assert.deepEqual(errors, ['조회 실패', '상태 변경 실패', '권한 없음'])
assert.equal(successes.length, 0)
})
test('성공 후 재조회 실패: 오래된 액션을 제거하고 성공/조회 실패를 구분한다', async () => {
const { vm, errors, successes } = page()
vm.detail = detail()
vm.show_detail_dialog = true
Vue.axios = {
post: async () => ({ data: envelope({}) }),
get: async () => { throw new Error('조회 실패') }
}
vm.requestAction(vm.detail, 'ARRIVE_MAILBOX')
await vm.executeAction()
assert.equal(successes.length, 1)
assert.equal(errors.length, 2)
assert.equal(vm.detail, null)
assert.equal(vm.gifts.length, 0)
assert.equal(vm.list_error, true)
assert.equal(vm.is_operating, false)
Vue.axios.get = async () => ({ data: envelope(detail({ availableActions: ['COMPLETE_INSPECTION'] })) })
await vm.getDetail(vm.detailApplicationNo)
assert.deepEqual(Array.from(vm.detail.availableActions), ['COMPLETE_INSPECTION'])
})
test('목록: 늦게 도착한 응답이 최신 페이지를 덮어쓰지 않는다', async () => {
const { vm } = page()
const pending = deferred()
Vue.axios = { get: async (url, config) => config.params.page === 0 ? pending.promise : { data: envelope(list({ page: 1, totalCount: 40 })) } }
const old = vm.getGifts(1)
await vm.getGifts(2)
pending.resolve({ data: envelope(list({ page: 0, totalCount: 1 })) })
await old
assert.equal(vm.page, 2)
assert.equal(vm.totalCount, 40)
assert.equal(vm.is_loading, false)
})
test('상세: 뒤늦은 이전 응답이 새로 선택한 선물을 덮어쓰지 않는다', async () => {
const { vm } = page()
const pending = deferred()
Vue.axios = { get: async url => url.endsWith('/OLD') ? pending.promise : { data: envelope(detail({ applicationNo: 'NEW' })) } }
const old = vm.openDetail('OLD')
await vm.openDetail('NEW')
pending.resolve({ data: envelope(detail({ applicationNo: 'OLD' })) })
await old
assert.equal(vm.detail.applicationNo, 'NEW')
})
test('상세: 조회 중 닫은 모달에 늦은 응답을 반영하지 않는다', async () => {
const { vm } = page()
const pending = deferred()
Vue.axios = { get: async () => pending.promise }
const request = vm.openDetail('G-001')
vm.closeDetail()
pending.resolve({ data: envelope(detail()) })
await request
assert.equal(vm.show_detail_dialog, false)
assert.equal(vm.detail, null)
assert.equal(vm.is_detail_loading, false)
})
test('메뉴: ADMIN에 선물함 리스트를 추가하고 기존 서버 메뉴와 중복되지 않는다', async () => {
for (const role of ['ADMIN', 'CONTENT_MANAGER']) {
for (const existing of [false, true]) {
const menus = [{ title: '콘텐츠 리스트', route: '/content/list' }]
if (existing) menus.push({ title: '선물함 관리', items: [{ title: '선물함 리스트', route: '/gift/list' }] })
Vue.axios = { get: async () => ({ status: 200, data: envelope(menus) }) }
const vm = new Vue({ ...SideMenu, created: undefined })
vm.$store = { state: { accountStore: { role } } }
await vm.getMenus()
const gifts = vm.items.filter(item => item.title === '선물함 관리')
assert.equal(gifts.length, role === 'ADMIN' || existing ? 1 : 0)
if (gifts.length) assert.equal(gifts[0].items.filter(item => item.route === '/gift/list').length, 1)
}
}
})
test('취소: 서버 availableActions에 CANCEL이 있을 때만 목록과 상세에 노출하고 기존 dispatch로 실행한다', () => {
const { vm } = page()
vm.gifts = [{
applicationNo: 'G-001', senderNickname: '발송인', recipientNickname: '수취인',
sizeName: '소형', sizeCode: 'S', categoryName: '문구', classificationNumber: 'C1',
courierCompanyName: null, trackingNumber: null, status: 'RECEIVED', statusName: '접수 완료', availableActions: ['CANCEL']
}]
vm.detail = detail({ status: 'RECEIVED', statusName: '접수 완료', availableActions: ['CANCEL'] })
vm.show_detail_dialog = true
const components = nodes(vm._render()).filter(node => node.componentOptions && node.componentOptions.Ctor.options.name === 'GiftActions')
assert.equal(components.length, 2)
for (const component of components) {
const actions = Array.from(component.componentOptions.propsData.actions)
assert.deepEqual(actions, ['CANCEL'])
const buttons = nodes(new Vue({ ...GiftActions, propsData: { actions } })._render()).filter(node => node.tag === 'v-btn')
assert.deepEqual(buttons.map(button => nodes(button).map(node => node.text || '').join('').trim()), ['신청 취소'])
}
components[0].componentOptions.listeners.select('CANCEL')
assert.deepEqual({ ...vm.pendingAction }, { value: 'CANCEL', label: '신청 취소', method: 'cancelGift', applicationNo: 'G-001' })
vm.cancelAction()
for (const actions of [[], ['ARRIVE_MAILBOX'], ['COMPLETE_INSPECTION'], ['COMPLETE_DELIVERY', 'MARK_UNDELIVERABLE']]) {
const buttons = nodes(new Vue({ ...GiftActions, propsData: { actions } })._render()).filter(node => node.tag === 'v-btn')
assert.equal(buttons.map(button => nodes(button).map(node => node.text || '').join('').trim()).includes('신청 취소'), false)
}
vm.requestAction({ applicationNo: 'G-002', status: 'RECEIVED', availableActions: [] }, 'CANCEL')
assert.equal(vm.pendingAction, null)
assert.equal(vm.show_confirm_dialog, false)
})
test('취소 확인창: 신청번호와 전액 리워드캔 환불 안내를 표시하고 닫으면 요청하지 않는다', async () => {
const { vm } = page()
let posts = 0
Vue.axios = { post: async () => { posts++; return { data: envelope({}) } }, get: async () => ({ data: envelope(list()) }) }
vm.requestAction(detail({ status: 'RECEIVED', statusName: '접수 완료', availableActions: ['CANCEL'] }), 'CANCEL')
assert.equal(vm.show_confirm_dialog, true)
assert.equal(vm.show_reason_dialog, false)
const text = nodes(vm._render()).map(node => node.text || '').join(' ')
for (const part of ['G-001', '취소하시겠습니까?', '사용한 캔 전액이 발신자에게 리워드캔으로 환불됩니다.']) assert.ok(text.includes(part), part)
vm.cancelConfirmation()
assert.equal(vm.show_confirm_dialog, false)
assert.equal(vm.pendingAction, null)
await vm.executeAction()
assert.equal(posts, 0)
})
test('취소: 확정 시 본문 없이 한 번만 요청하고 필터/페이지를 유지한 채 목록과 상세를 갱신한다', async () => {
const { vm, successes, errors } = page()
const pending = deferred()
const calls = []
Vue.axios = {
post: async (...args) => {
calls.push(['POST', ...args])
await pending.promise
return { data: envelope({ applicationNo: 'G-001', status: 'CANCELED', statusName: '신청 취소', occurredAt: '2026-09-30T12:00:00Z' }) }
},
get: async (url, config) => {
calls.push(['GET', url, config])
return { data: envelope(config ? list({ page: 2, totalCount: 60 }) : detail({ status: 'CANCELED', statusName: '신청 취소', availableActions: [] })) }
}
}
vm.appliedFilters = { status: 'RECEIVED', applicationNo: '', nickname: '발송인' }
vm.page = 3
vm.detail = detail({ status: 'RECEIVED', statusName: '접수 완료', availableActions: ['CANCEL'] })
vm.show_detail_dialog = true
vm.requestAction(vm.detail, 'CANCEL')
const operation = vm.executeAction()
await vm.executeAction()
pending.resolve()
await operation
assert.deepEqual(calls.filter(call => call[0] === 'POST'), [['POST', '/api/v2/admin/gifts/G-001/cancel']])
assert.deepEqual(calls.find(call => call[1] === '/api/v2/admin/gifts')[2].params, { status: 'RECEIVED', nickname: '발송인', page: 2, size: 20 })
assert.ok(calls.some(call => call[1] === '/api/v2/admin/gifts/G-001'))
assert.equal(vm.page, 3)
assert.equal(vm.detail.status, 'CANCELED')
assert.equal(vm.detail.statusName, '신청 취소')
assert.deepEqual(Array.from(vm.detail.availableActions), [])
assert.deepEqual(successes, ['신청 취소되었습니다.'])
assert.deepEqual(errors, [])
assert.equal(vm.is_operating, false)
assert.equal(vm.show_confirm_dialog, false)
})
test('취소 실패: 가짜 취소 없이 공통 오류를 표시하고 서버 현재 상태를 재조회한다', async () => {
for (const fail of [async () => ({ data: { success: false, message: '이미 변경된 상태입니다.' } }), async () => { throw { response: { data: { message: '통신 실패' } } } }]) {
const { vm, errors, successes } = page()
const calls = []
Vue.axios = {
post: fail,
get: async (url, config) => {
calls.push(url)
return { data: envelope(config ? list() : detail({ status: 'DELIVERED', statusName: '전달 완료', availableActions: [] })) }
}
}
vm.detail = detail({ status: 'RECEIVED', statusName: '접수 완료', availableActions: ['CANCEL'] })
vm.show_detail_dialog = true
vm.requestAction(vm.detail, 'CANCEL')
await vm.executeAction()
assert.equal(errors.length, 1)
assert.equal(successes.length, 0)
assert.deepEqual(calls.slice().sort(), ['/api/v2/admin/gifts', '/api/v2/admin/gifts/G-001'])
assert.equal(vm.detail.status, 'DELIVERED')
assert.equal(vm.is_operating, false)
}
})
;(async () => {
for (const { name, run } of tests) {
try {
await run()
console.log(`PASS ${name}`)
} catch (error) {
process.exitCode = 1
console.error(`FAIL ${name}`, error)
}
}
})()
-399
View File
@@ -1,399 +0,0 @@
const assert = require('assert').strict
const fs = require('fs')
const path = require('path')
const Module = require('module')
const { transformSync } = require('@babel/core')
const compiler = require('vue-template-compiler')
const Vue = require('vue')
const root = path.resolve(__dirname, '..')
const originalResolve = Module._resolveFilename
Module._resolveFilename = function(request, parent, ...rest) {
return originalResolve.call(this, request.startsWith('@/') ? path.join(root, 'src', request.slice(2)) : request, parent, ...rest)
}
const originalJs = require.extensions['.js']
function compileScript(source, filename) {
return transformSync(source, {
filename,
babelrc: false,
configFile: false,
plugins: ['@babel/plugin-transform-modules-commonjs']
}).code
}
require.extensions['.js'] = (module, filename) => {
if (!filename.startsWith(path.join(root, 'src') + path.sep)) return originalJs(module, filename)
module._compile(compileScript(fs.readFileSync(filename, 'utf8'), filename), filename)
}
require.extensions['.vue'] = (module, filename) => {
const { script, template } = compiler.parseComponent(fs.readFileSync(filename, 'utf8'))
const compiled = compiler.compile(template.content)
assert.deepEqual(compiled.errors, [], `${filename}: 템플릿 컴파일`)
module._compile(compileScript(script.content, filename), filename)
Object.assign(module.exports.default, compiler.compileToFunctions(template.content))
}
const api = require('../src/api/gift_category')
const { createGiftCategoryForm, buildGiftCategoryRequest, validateGiftCategory } = require('../src/utils/gift_category')
const GiftCategory = require('../src/views/Gift/GiftCategory.vue').default
const SideMenu = require('../src/components/SideMenu.vue').default
const tests = []
const test = (name, run) => tests.push({ name, run })
const envelope = data => ({ success: true, data })
const category = (overrides = {}) => ({
categoryId: 1, classificationNumber: '100', categoryCode: 'DOLL', name: '인형',
receiptCode: 'A', representativeItem: '피규어', requiresDamageWaiver: false, isActive: true,
...overrides
})
const request = (overrides = {}) => ({
classificationNumber: '100', categoryCode: 'DOLL', name: '인형', receiptCode: 'A',
representativeItem: '피규어', requiresDamageWaiver: false, isActive: true,
...overrides
})
function page() {
const errors = []
const successes = []
const vm = new Vue({ ...GiftCategory, created: undefined })
vm.$dialog = { notify: { error: message => errors.push(message), success: message => successes.push(message) } }
return { vm, errors, successes }
}
function deferred() {
let resolve
const promise = new Promise(done => { resolve = done })
return { promise, resolve }
}
function nodes(vnode) {
if (!vnode) return []
return [vnode].concat((vnode.children || (vnode.componentOptions && vnode.componentOptions.children) || []).flatMap(nodes))
}
const text = vnode => nodes(vnode).map(node => node.text || '').join('').trim()
const button = (vm, label) => nodes(vm._render()).find(node => node.tag === 'v-btn' && text(node) === label)
test('카테고리 API: GET/POST/PUT/DELETE 경로, 본문 및 공통 envelope를 사용한다', async () => {
const calls = []
const response = envelope(category())
Vue.axios = Object.fromEntries(['get', 'post', 'put', 'delete'].map(method => [method, async (...args) => {
calls.push([method, ...args])
return { data: response }
}]))
assert.equal(await api.getGiftCategories(), response)
assert.equal(await api.createGiftCategory(category({ extra: '제외' })), response)
assert.equal(await api.updateGiftCategory(1, category({ extra: '제외' })), response)
assert.equal(await api.deactivateGiftCategory(1), response)
assert.deepEqual(calls, [
['get', '/api/v2/admin/gift-categories'],
['post', '/api/v2/admin/gift-categories', request()],
['put', '/api/v2/admin/gift-categories/1', request()],
['delete', '/api/v2/admin/gift-categories/1']
])
})
test('카테고리 validation: 필수/형식/길이/boolean 오류를 검사한다', () => {
const invalid = {
classificationNumber: ['', ' ', null, undefined, 100, '10', '1000', 'A10', '123', '100\n', ' 10'],
categoryCode: ['', ' \t ', null, undefined, 1, 'A'.repeat(51)],
name: ['', ' \n ', null, undefined, 1, '가'.repeat(51)],
receiptCode: ['', ' ', null, undefined, 1, 'a', 'Aa', 'A1', '가', 'A B', 'A\n', 'A'.repeat(10)],
representativeItem: ['', ' ', null, undefined, 1, '가'.repeat(101)],
requiresDamageWaiver: [null, undefined, '', 'false', 0, 1],
isActive: [null, undefined, '', 'true', 0, 1]
}
for (const [key, values] of Object.entries(invalid)) {
for (const value of values) {
const errors = validateGiftCategory(request({ [key]: value }))
assert.deepEqual(Object.keys(errors), [key], `${key}: ${String(value)}`)
assert.equal(typeof errors[key], 'string')
}
}
})
test('카테고리 validation: 최대 길이/앞자리 0/false를 보존하며 ID는 본문에서 제외한다', () => {
for (const requiresDamageWaiver of [true, false]) {
for (const isActive of [true, false]) {
const form = request({
classificationNumber: '001', categoryCode: 'A'.repeat(50), name: '가'.repeat(50),
receiptCode: 'ABCDEFGHI', representativeItem: '가'.repeat(100), requiresDamageWaiver, isActive
})
assert.deepEqual(validateGiftCategory(form), {})
assert.deepEqual(buildGiftCategoryRequest({ categoryId: 7, extra: '제외', ...form }), form)
}
}
const first = createGiftCategoryForm()
first.name = '변경'
assert.equal(createGiftCategoryForm().name, '')
})
test('카테고리 목록: 최초 GET의 response.data 배열과 필수 9개 컬럼을 표시한다', async () => {
const { vm } = page()
const calls = []
Vue.axios = { get: async (...args) => { calls.push(args); return { data: envelope([category()]) } } }
await GiftCategory.created.call(vm)
assert.deepEqual(calls, [['/api/v2/admin/gift-categories']])
assert.deepEqual(Array.from(vm.categories), [category()])
const rendered = nodes(vm._render())
assert.deepEqual(rendered.filter(node => node.tag === 'th').map(text), [
'카테고리 ID', '분류번호', '카테고리 코드', '카테고리명', '접수 코드', '대표 품목', '파손면책 동의 필요 여부', '활성 여부', '관리'
])
assert.deepEqual(rendered.filter(node => node.tag === 'td').slice(0, 8).map(text), ['1', '100', 'DOLL', '인형', 'A', '피규어', '아니오', '활성'])
button(vm, '수정').data.on.click()
assert.equal(vm.isEdit, true)
vm.closeForm()
button(vm, '카테고리 등록').data.on.click()
assert.equal(vm.isEdit, false)
assert.equal(vm.show_form_dialog, true)
})
test('카테고리 목록: 빈 목록, 로딩 및 오류 재조회 상태를 표시한다', async () => {
const { vm, errors } = page()
assert.ok(text(vm._render()).includes('등록된 카테고리가 없습니다.'))
const pending = deferred()
Vue.axios = { get: async () => pending.promise }
const load = vm.getCategories()
assert.equal(vm.is_loading, true)
assert.ok(text(vm._render()).includes('조회 중입니다.'))
assert.equal(button(vm, '카테고리 등록').data.attrs.disabled, true)
pending.resolve({ data: { success: false, message: '조회 실패' } })
await load
assert.deepEqual(errors, ['조회 실패'])
assert.equal(vm.is_loading, false)
assert.equal(vm.list_error, true)
Vue.axios.get = async () => ({ data: envelope([]) })
await button(vm, '다시 조회').data.on.click()
assert.equal(vm.list_error, false)
})
test('카테고리 폼: 수정 코드는 읽기 전용이며 취소는 목록을 변경하지 않고 등록은 초기화한다', () => {
const { vm } = page()
const item = category()
vm.openEdit(item)
assert.equal(vm.categoryId, 1)
assert.deepEqual(vm.form, request())
const fields = nodes(vm._render()).filter(node => node.tag === 'v-text-field')
assert.equal(fields.length, 5)
for (const field of fields) assert.equal(field.data.attrs.readonly, field.data.attrs.label === '카테고리 코드')
assert.equal(nodes(vm._render()).filter(node => node.tag === 'v-switch').length, 2)
vm.form.name = '변경'
vm.form.isActive = false
vm.closeForm()
assert.equal(item.name, '인형')
assert.equal(item.isActive, true)
vm.form_errors = { name: '오류' }
vm.openCreate()
assert.equal(vm.categoryId, null)
assert.deepEqual(vm.form, createGiftCategoryForm())
assert.deepEqual(vm.form_errors, {})
assert.equal(nodes(vm._render()).find(node => node.tag === 'v-text-field' && node.data.attrs.label === '카테고리 코드').data.attrs.readonly, false)
})
test('카테고리 폼: validation 실패 시 등록/수정 API 없이 필드 오류를 표시한다', async () => {
for (const edit of [false, true]) {
const { vm, successes } = page()
const calls = []
Vue.axios = { post: async () => { calls.push('POST') }, put: async () => { calls.push('PUT') } }
if (edit) vm.openEdit(category())
else vm.openCreate()
vm.form = request({ classificationNumber: '10', categoryCode: '', name: '', receiptCode: 'a', representativeItem: '', requiresDamageWaiver: null, isActive: null })
const form = nodes(vm._render()).find(node => node.tag === 'v-form')
await form.data.on.submit({ preventDefault() {} })
assert.deepEqual(calls, [])
assert.deepEqual(successes, [])
assert.equal(Object.keys(vm.form_errors).length, 7)
for (const field of nodes(vm._render()).filter(node => ['v-text-field', 'v-switch'].includes(node.tag))) {
assert.ok(field.data.attrs['error-messages'])
}
assert.equal(vm.show_form_dialog, true)
assert.equal(vm.is_operating, false)
}
})
test('카테고리 저장: POST/PUT 성공 후 재조회하고 모달을 닫으며 중복 제출을 차단한다', async () => {
for (const edit of [false, true]) {
const { vm, successes } = page()
const pending = deferred()
const calls = []
const payload = request({ classificationNumber: '001', requiresDamageWaiver: true, isActive: false })
const saved = category(payload)
Vue.axios = {
[edit ? 'put' : 'post']: async (...args) => { calls.push([edit ? 'PUT' : 'POST', ...args]); return { data: envelope(saved) } },
get: async (...args) => { calls.push(['GET', ...args]); return pending.promise }
}
if (edit) vm.openEdit(category())
else vm.openCreate()
vm.form = { ...payload, categoryId: 99, extra: '제외' }
const operation = vm.saveCategory()
await vm.saveCategory()
await Vue.nextTick()
assert.equal(vm.is_operating, true)
assert.equal(vm.show_form_dialog, true)
vm.closeForm()
vm.openEdit(category({ categoryId: 2 }))
vm.openCreate()
assert.equal(vm.categoryId, edit ? 1 : null)
assert.equal(vm.show_form_dialog, true)
pending.resolve({ data: envelope([saved]) })
await operation
assert.deepEqual(calls, [
[edit ? 'PUT' : 'POST', `/api/v2/admin/gift-categories${edit ? '/1' : ''}`, payload],
['GET', '/api/v2/admin/gift-categories']
])
assert.deepEqual(Array.from(vm.categories), [saved])
assert.equal(vm.show_form_dialog, false)
assert.equal(vm.is_operating, false)
assert.deepEqual(successes, [edit ? '카테고리가 수정되었습니다.' : '카테고리가 등록되었습니다.'])
await vm.saveCategory()
assert.equal(calls.length, 2)
}
})
test('카테고리 저장 실패: 공통 오류 알림과 입력/모달을 유지한다', async () => {
for (const edit of [false, true]) {
for (const fail of [
async () => ({ data: { success: false, message: '저장 실패' } }),
async () => { throw { response: { data: { message: '저장 실패' } } } },
async () => { throw new Error('저장 실패') }
]) {
const { vm, errors, successes } = page()
let loads = 0
Vue.axios = { post: fail, put: fail, get: async () => { loads++ } }
if (edit) vm.openEdit(category())
else vm.openCreate()
vm.form = request()
await vm.saveCategory()
assert.deepEqual(errors, ['저장 실패'])
assert.deepEqual(successes, [])
assert.deepEqual(vm.form, request())
assert.equal(vm.show_form_dialog, true)
assert.equal(vm.is_operating, false)
assert.equal(loads, 0)
}
}
})
test('카테고리 저장 후 조회 실패: 저장 성공과 조회 오류를 구분하며 중복 등록을 방지한다', async () => {
const { vm, errors, successes } = page()
Vue.axios = {
post: async () => ({ data: envelope(category()) }),
get: async () => { throw new Error('조회 실패') }
}
vm.openCreate()
vm.form = request()
await vm.saveCategory()
assert.deepEqual(successes, ['카테고리가 등록되었습니다.'])
assert.deepEqual(errors, ['조회 실패'])
assert.equal(vm.show_form_dialog, false)
assert.equal(vm.list_error, true)
assert.equal(vm.is_operating, false)
})
test('카테고리 비활성화: 확인 전/취소 후/이미 비활성이면 DELETE하지 않는다', async () => {
const { vm } = page()
let calls = 0
Vue.axios = { delete: async () => { calls++ } }
vm.categories = [category()]
button(vm, '비활성화').data.on.click()
assert.equal(vm.show_confirm_dialog, true)
assert.ok(text(vm._render()).includes('인형 카테고리를 비활성화하시겠습니까?'))
assert.equal(calls, 0)
vm.cancelDeactivation()
await vm.deactivateCategory()
assert.equal(calls, 0)
assert.equal(vm.pendingCategory, null)
vm.categories = [category({ isActive: false, requiresDamageWaiver: true })]
assert.equal(button(vm, '비활성화').data.attrs.disabled, true)
assert.ok(text(vm._render()).includes('비활성'))
assert.ok(text(vm._render()).includes('예'))
vm.requestDeactivation(vm.categories[0])
await vm.deactivateCategory()
assert.equal(calls, 0)
assert.equal(vm.show_confirm_dialog, false)
})
test('카테고리 비활성화 성공: 응답의 isActive=false를 반영하고 row는 유지한다', async () => {
const { vm, successes } = page()
const pending = deferred()
const calls = []
Vue.axios = { delete: async (...args) => { calls.push(args); return pending.promise } }
vm.categories = [category(), category({ categoryId: 2 })]
vm.requestDeactivation(vm.categories[0])
const operation = button(vm, '확인').data.on.click()
await vm.deactivateCategory()
vm.cancelDeactivation()
assert.equal(vm.show_confirm_dialog, true)
assert.equal(vm.is_operating, true)
assert.equal(button(vm, '비활성화').data.attrs.disabled, true)
pending.resolve({ data: envelope(category({ isActive: false })) })
await operation
assert.deepEqual(calls, [['/api/v2/admin/gift-categories/1']])
assert.deepEqual(Array.from(vm.categories), [category({ isActive: false }), category({ categoryId: 2 })])
assert.equal(button(vm, '비활성화').data.attrs.disabled, true)
assert.equal(vm.show_confirm_dialog, false)
assert.equal(vm.pendingCategory, null)
assert.equal(vm.is_operating, false)
assert.deepEqual(successes, ['카테고리가 비활성화되었습니다.'])
})
test('카테고리 비활성화 실패: 기존 활성 상태를 유지하고 공통 오류를 표시한다', async () => {
for (const fail of [
async () => ({ data: { success: false, message: '비활성화 실패' } }),
async () => { throw { response: { data: { message: '비활성화 실패' } } } }
]) {
const { vm, errors, successes } = page()
Vue.axios = { delete: fail }
vm.categories = [category()]
vm.requestDeactivation(vm.categories[0])
await vm.deactivateCategory()
assert.equal(vm.categories[0].isActive, true)
assert.equal(vm.show_confirm_dialog, true)
assert.equal(vm.is_operating, false)
assert.deepEqual(errors, ['비활성화 실패'])
assert.deepEqual(successes, [])
}
})
test('카테고리 목록: 늦게 도착한 이전 응답은 최신 목록을 덮어쓰지 않는다', async () => {
const { vm } = page()
const pending = deferred()
Vue.axios = { get: async () => pending.promise }
const old = vm.getCategories()
Vue.axios.get = async () => ({ data: envelope([category({ categoryId: 2 })]) })
await vm.getCategories()
pending.resolve({ data: envelope([category()]) })
await old
assert.deepEqual(Array.from(vm.categories), [category({ categoryId: 2 })])
assert.equal(vm.is_loading, false)
})
test('카테고리 메뉴: ADMIN 보완 메뉴와 서버 메뉴를 중복 없이 유지한다', async () => {
for (const role of ['ADMIN', 'CONTENT_MANAGER']) {
for (const existing of ['none', 'null', 'list', 'category', 'object']) {
const menus = []
if (existing !== 'none') {
const items = existing === 'null' ? null : existing === 'list'
? [{ title: '선물함 리스트', route: '/gift/list' }]
: existing === 'object' ? { title: '선물 카테고리', route: '/gift/category' }
: [{ title: '선물 카테고리', route: '/gift/category' }]
menus.push({ title: '선물함 관리', items })
}
Vue.axios = { get: async () => ({ status: 200, data: envelope(menus) }) }
const vm = new Vue({ ...SideMenu, created: undefined })
vm.$store = { state: { accountStore: { role } } }
await vm.getMenus()
const gifts = vm.items.filter(item => item.title === '선물함 관리')
assert.equal(gifts.length, role === 'ADMIN' || existing !== 'none' ? 1 : 0)
const children = gifts.length && gifts[0].items ? [].concat(gifts[0].items) : []
assert.equal(children.filter(item => item.route === '/gift/category').length, role === 'ADMIN' || ['category', 'object'].includes(existing) ? 1 : 0)
if (role === 'ADMIN') assert.equal(children.filter(item => item.route === '/gift/list').length, 1)
}
}
})
;(async () => {
for (const { name, run } of tests) {
try {
await run()
console.log(`PASS ${name}`)
} catch (error) {
process.exitCode = 1
console.error(`FAIL ${name}`, error)
}
}
})()
-294
View File
@@ -1,294 +0,0 @@
const assert = require('assert').strict
const fs = require('fs')
const path = require('path')
const Module = require('module')
const { transformSync } = require('@babel/core')
const compiler = require('vue-template-compiler')
const Vue = require('vue')
const root = path.resolve(__dirname, '..')
const originalResolve = Module._resolveFilename
Module._resolveFilename = function(request, parent, ...rest) {
return originalResolve.call(this, request.startsWith('@/') ? path.join(root, 'src', request.slice(2)) : request, parent, ...rest)
}
const originalJs = require.extensions['.js']
function compileScript(source, filename) {
return transformSync(source, {
filename, babelrc: false, configFile: false,
plugins: ['@babel/plugin-transform-modules-commonjs']
}).code
}
require.extensions['.js'] = (module, filename) => {
if (!filename.startsWith(path.join(root, 'src') + path.sep)) return originalJs(module, filename)
module._compile(compileScript(fs.readFileSync(filename, 'utf8'), filename), filename)
}
require.extensions['.vue'] = (module, filename) => {
const { script, template } = compiler.parseComponent(fs.readFileSync(filename, 'utf8'))
assert.deepEqual(compiler.compile(template.content).errors, [])
module._compile(compileScript(script.content, filename), filename)
Object.assign(module.exports.default, compiler.compileToFunctions(template.content))
}
const GiftMailbox = require('../src/views/Gift/GiftMailbox.vue').default
const SideMenu = require('../src/components/SideMenu.vue').default
const tests = []
const test = (name, run) => tests.push({ name, run })
const envelope = data => ({ data: { success: true, data } })
const saved = { name: '운영팀', phoneNumber: '010-1234-5678', address: '(01234) 서울시 도로 1, 2층, 운영실' }
const form = () => ({ name: ' 운영팀 ', phoneNumber: ' 010-1234-5678 ', zipCode: '01234', address: '서울시 도로 1', addressDetail: '2층, 운영실' })
function page() {
const vm = new Vue({ ...GiftMailbox, created: undefined })
const errors = []
const successes = []
vm.$dialog = { notify: { error: message => errors.push(message), success: message => successes.push(message) } }
return { vm, errors, successes }
}
function nodes(vnode) {
return vnode ? [vnode].concat((vnode.children || []).flatMap(nodes)) : []
}
const text = vm => nodes(vm._render()).map(node => node.text || '').join('')
test('초기 GET과 null 빈 폼, 안내 및 필드 표시', async () => {
const { vm } = page()
const calls = []
Vue.axios = { get: async (...args) => { calls.push(args); return envelope(null) } }
await GiftMailbox.created.call(vm)
assert.deepEqual(calls, [['/api/v2/admin/gift-mailbox']])
assert.ok(Object.values(vm.form).every(value => value === ''))
assert.ok(text(vm).includes('등록된 받을 주소가 없습니다.'))
assert.equal(nodes(vm._render()).filter(node => node.tag === 'v-text-field').length, 5)
})
test('등록된 주소 조회 및 상세주소 없는 주소 편집', async () => {
const { vm } = page()
Vue.axios = { get: async () => envelope(saved) }
await vm.getMailbox()
assert.deepEqual(vm.form, { ...form(), name: saved.name, phoneNumber: saved.phoneNumber })
Vue.axios.get = async () => envelope({ ...saved, address: '(01234) 서울시 도로 1' })
await vm.getMailbox()
assert.equal(vm.form.address, '서울시 도로 1')
assert.equal(vm.form.addressDetail, '')
})
test('필수값 공백 시 필드 오류 표시 및 PUT 차단', async () => {
const { vm } = page()
vm.loaded = true
let calls = 0
Vue.axios = { put: async () => { calls++ } }
for (const key of ['name', 'phoneNumber', 'zipCode', 'address']) {
for (const value of ['', ' \t\n ', null]) {
vm.form = { ...form(), [key]: value }
await vm.saveMailbox()
assert.deepEqual(Object.keys(vm.form_errors), [key])
const field = nodes(vm._render()).find(node => node.tag === 'v-text-field' && node.key === key)
assert.ok(field.data.attrs['error-messages'])
}
}
assert.equal(calls, 0)
})
test('생성·수정 PUT 본문, 선택값 null, 성공 알림 및 서버 응답 반영', async () => {
for (const detail of ['2층, 운영실', ' ']) {
const { vm, successes } = page()
vm.loaded = true
vm.form = { ...form(), addressDetail: detail, extra: '제외' }
const calls = []
const result = { ...saved, name: '서버 이름', phoneNumber: '서버 연락처' }
Vue.axios = { put: async (...args) => { calls.push(args); return envelope(result) } }
await vm.saveMailbox()
await vm.saveMailbox()
assert.equal(calls.length, 2)
assert.deepEqual(calls[0], ['/api/v2/admin/gift-mailbox', {
...form(), name: saved.name, phoneNumber: saved.phoneNumber, addressDetail: detail.trim() || null
}])
assert.equal(vm.form.name, result.name)
assert.equal(vm.form.phoneNumber, result.phoneNumber)
assert.equal(vm.form.address, form().address)
assert.equal(vm.form.addressDetail, detail)
assert.equal(successes.length, 2)
assert.ok(text(vm).includes(saved.address))
}
})
test('조회·저장 실패 알림, 입력 유지, 조회 재시도', async () => {
for (const fail of [
async () => ({ data: { success: false, message: '실패' } }),
async () => { throw { response: { data: { message: '실패' } } } }
]) {
const { vm, errors, successes } = page()
let puts = 0
Vue.axios = { get: fail, put: async () => { puts++; return fail() } }
await vm.getMailbox()
await vm.saveMailbox()
assert.equal(puts, 0)
assert.equal(vm.load_error, true)
assert.ok(text(vm).includes('다시 조회'))
Vue.axios.get = async () => envelope(null)
await vm.getMailbox()
vm.form = form()
await vm.saveMailbox()
assert.deepEqual(vm.form, form())
assert.deepEqual(errors, ['실패', '실패'])
assert.deepEqual(successes, [])
assert.equal(vm.is_operating, false)
}
})
test('조회 중 저장 및 중복 저장 차단', async () => {
const { vm } = page()
let resolve
let puts = 0
Vue.axios = {
get: () => new Promise(done => { resolve = done }),
put: () => { puts++; return new Promise(done => { resolve = done }) }
}
const load = vm.getMailbox()
await vm.saveMailbox()
assert.equal(puts, 0)
resolve(envelope(null))
await load
vm.form = form()
const save = vm.saveMailbox()
await vm.saveMailbox()
assert.equal(puts, 1)
resolve(envelope(saved))
await save
})
test('주소 검색 선택: 읽기 전용 필드, 도로명·지번 선택 및 PUT 반영', async () => {
const postcode = require('../src/utils/postcode')
const original = postcode.loadPostcode
try {
for (const type of ['R', 'J']) {
const { vm } = page()
vm.loaded = true
vm.form = form()
vm.form_errors = { zipCode: '필수', address: '필수' }
vm.$refs.postcodeContainer = { innerHTML: '이전 검색' }
let options
postcode.loadPostcode = async () => function(config) {
options = config
this.embed = container => assert.equal(container, vm.$refs.postcodeContainer)
}
const fields = nodes(vm._render()).filter(node => node.tag === 'v-text-field')
for (const field of fields) {
assert.equal(field.data.attrs.readonly, ['zipCode', 'address'].includes(field.key))
assert.equal(field.data.attrs.disabled, ['zipCode', 'address'].includes(field.key))
}
const postcodeRow = nodes(vm._render()).find(node => node.data && node.data.class && node.data.class['mailbox-postcode-row'])
assert.ok(postcodeRow, '우편번호와 검색 버튼을 같은 행에 배치한다')
assert.ok(nodes(postcodeRow).some(node => node.key === 'zipCode'))
assert.ok(nodes(postcodeRow).some(node => node.tag === 'v-btn' && nodes(node).map(child => child.text || '').join('').trim() === '주소 검색'))
await vm.openAddressSearch()
assert.equal(vm.show_address_search, true)
options.oncomplete({ zonecode: '04524', userSelectedType: type, roadAddress: '서울 중구 세종대로 110', jibunAddress: '서울 중구 태평로1가 31' })
assert.equal(vm.form.zipCode, '04524')
assert.equal(vm.form.address, type === 'R' ? '서울 중구 세종대로 110' : '서울 중구 태평로1가 31')
assert.equal(vm.form.addressDetail, '')
assert.equal(vm.form_errors.zipCode, '')
assert.equal(vm.form_errors.address, '')
assert.equal(vm.show_address_search, false)
vm.form.addressDetail = '3층'
let request
Vue.axios = { put: async (url, body) => { request = body; return envelope(saved) } }
await vm.saveMailbox()
assert.equal(request.zipCode, '04524')
assert.equal(request.address, vm.form.address)
assert.equal(request.addressDetail, '3층')
}
} finally {
postcode.loadPostcode = original
}
})
test('주소 검색 취소·화면 종료·오류 시 기존 입력 보존 및 재시도', async () => {
const postcode = require('../src/utils/postcode')
const original = postcode.loadPostcode
try {
const { vm, errors } = page()
vm.loaded = true
vm.form = form()
let resolve
let embeds = 0
postcode.loadPostcode = () => new Promise(done => { resolve = done })
const pending = vm.openAddressSearch()
vm.show_address_search = false
resolve(function() { this.embed = () => { embeds++ } })
await pending
assert.equal(embeds, 0)
assert.deepEqual(vm.form, form())
postcode.loadPostcode = async () => { throw new Error('검색 로딩 실패') }
await vm.openAddressSearch()
assert.deepEqual(errors, ['검색 로딩 실패'])
assert.equal(vm.is_postcode_loading, false)
assert.equal(vm.show_address_search, false)
assert.deepEqual(vm.form, form())
postcode.loadPostcode = () => new Promise(done => { resolve = done })
const retry = vm.openAddressSearch()
GiftMailbox.beforeDestroy.call(vm)
resolve(function() { this.embed = () => { embeds++ } })
await retry
assert.equal(embeds, 0)
} finally {
postcode.loadPostcode = original
}
})
test('주소 검색 스크립트 단일 로드, 실패 후 재시도 및 기존 SDK 재사용', async () => {
const { loadPostcode } = require('../src/utils/postcode')
const scripts = []
const previousWindow = global.window
const previousDocument = global.document
global.window = {}
global.document = {
createElement: () => ({ remove() { this.removed = true } }),
head: { appendChild: script => scripts.push(script) }
}
try {
const first = loadPostcode()
assert.equal(loadPostcode(), first)
assert.equal(scripts.length, 1)
assert.equal(scripts[0].src, 'https://t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js')
scripts[0].onerror()
await assert.rejects(first, /주소 검색/)
assert.equal(scripts[0].removed, true)
const retry = loadPostcode()
assert.equal(scripts.length, 2)
global.window.daum = { Postcode: function() {} }
scripts[1].onload()
assert.equal(await retry, global.window.daum.Postcode)
assert.equal(await loadPostcode(), global.window.daum.Postcode)
assert.equal(scripts.length, 2)
} finally {
if (previousWindow === undefined) delete global.window
else global.window = previousWindow
if (previousDocument === undefined) delete global.document
else global.document = previousDocument
}
})
test('관리자 선물함 메뉴 연결 및 중복 방지, 라우트 등록', async () => {
for (const items of [[], [{ title: '선물함 관리', items: null }], [{ title: '선물함 관리', items: [{ title: '받을 주소', route: '/gift/mailbox' }] }]]) {
Vue.axios = { get: async () => ({ status: 200, ...envelope(items) }) }
const vm = new Vue({ ...SideMenu, created: undefined })
vm.$store = { state: { accountStore: { role: 'ADMIN' } } }
await vm.getMenus()
const children = vm.items.find(item => item.title === '선물함 관리').items
assert.equal(children.filter(item => item.route === '/gift/mailbox').length, 1)
assert.equal(children.find(item => item.route === '/gift/mailbox').title, '받을 주소')
}
const router = fs.readFileSync(path.join(root, 'src/router/index.js'), 'utf8')
assert.match(router, /path: '\/gift\/mailbox',\s*name: 'GiftMailbox',\s*component: \(\) => import\([^\n]*'\.\.\/views\/Gift\/GiftMailbox.vue'\)/)
})
;(async () => {
for (const { name, run } of tests) {
try {
await run()
console.log(`PASS ${name}`)
} catch (error) {
process.exitCode = 1
console.error(`FAIL ${name}`, error)
}
}
})()
-602
View File
@@ -1,602 +0,0 @@
const assert = require('assert').strict
const fs = require('fs')
const path = require('path')
const Module = require('module')
const { transformSync } = require('@babel/core')
const compiler = require('vue-template-compiler')
const Vue = require('vue')
const root = path.resolve(__dirname, '..')
const originalResolve = Module._resolveFilename
Module._resolveFilename = function(request, parent, ...rest) {
return originalResolve.call(this, request.startsWith('@/') ? path.join(root, 'src', request.slice(2)) : request, parent, ...rest)
}
const originalJs = require.extensions['.js']
function compileScript(source, filename) {
return transformSync(source, {
filename,
babelrc: false,
configFile: false,
plugins: ['@babel/plugin-transform-modules-commonjs']
}).code
}
require.extensions['.js'] = (module, filename) => {
if (!filename.startsWith(path.join(root, 'src') + path.sep)) return originalJs(module, filename)
module._compile(compileScript(fs.readFileSync(filename, 'utf8'), filename), filename)
}
require.extensions['.vue'] = (module, filename) => {
const { script, template } = compiler.parseComponent(fs.readFileSync(filename, 'utf8'))
const compiled = compiler.compile(template.content)
assert.deepEqual(compiled.errors, [], `${filename}: 템플릿 컴파일`)
module._compile(compileScript(script.content, filename), filename)
Object.assign(module.exports.default, compiler.compileToFunctions(template.content))
}
const api = require('../src/api/gift_size')
const { giftSizes, createGiftSizeForm, buildGiftSizeRequest, validateGiftSize } = require('../src/utils/gift_size')
const GiftSize = require('../src/views/Gift/GiftSize.vue').default
const SideMenu = require('../src/components/SideMenu.vue').default
const tests = []
const test = (name, run) => tests.push({ name, run })
const envelope = data => ({ success: true, data })
const size = (overrides = {}) => ({ sizeCode: 'SMALL', name: '소형', basePriceCan: 12000, salePriceCan: 10000, isActive: true, ...overrides })
const request = (overrides = {}) => ({ basePriceCan: 12000, salePriceCan: 10000, isActive: true, ...overrides })
function page() {
const errors = []
const successes = []
const confirmations = []
const vm = new Vue({ ...GiftSize, created: undefined })
vm.$dialog = {
notify: { error: message => errors.push(message), success: message => successes.push(message) },
confirm: async options => { confirmations.push(options); return true }
}
return { vm, errors, successes, confirmations }
}
function deferred() {
let resolve
const promise = new Promise(done => { resolve = done })
return { promise, resolve }
}
function nodes(vnode) {
if (!vnode) return []
return [vnode].concat((vnode.children || (vnode.componentOptions && vnode.componentOptions.children) || []).flatMap(nodes))
}
const text = vnode => nodes(vnode).map(node => node.text || '').join('').trim()
const button = (vm, label) => nodes(vm._render()).find(node => node.tag === 'v-btn' && text(node) === label)
test('사이즈 API: 유니크한 GiftSize 3종의 GET/PUT 경로와 본문 및 envelope가 일치한다', async () => {
assert.deepEqual(giftSizes, ['SMALL', 'MEDIUM', 'LARGE'])
assert.equal(new Set(giftSizes).size, 3)
assert.deepEqual(Object.keys(api).sort(), ['getGiftSizePrices', 'updateGiftSizePrice'])
const calls = []
const response = envelope(size())
Vue.axios = Object.fromEntries(['get', 'put'].map(method => [method, async (...args) => {
calls.push([method, ...args])
return { data: response }
}]))
assert.equal(await api.getGiftSizePrices(), response)
for (const sizeCode of giftSizes) {
assert.equal(await api.updateGiftSizePrice(sizeCode, size({ basePriceCan: '12000', salePriceCan: '10000', isActive: false, extra: '제외' })), response)
}
assert.deepEqual(calls, [
['get', '/api/v2/admin/gift-size-prices'],
...giftSizes.map(code => ['put', `/api/v2/admin/gift-size-prices/${code}`, request({ isActive: false })])
])
for (const code of ['S', 'M', 'L', 'small', '', 'XLARGE', null, undefined]) {
await assert.rejects(api.updateGiftSizePrice(code, size()))
}
assert.equal(calls.length, 4)
})
test('사이즈 validation: 필수·1 이상 정수·안전한 숫자·boolean·enum을 검사한다', () => {
const invalidPrices = ['', ' ', null, undefined, 0, '0', -1, '-1', 1.1, '1.1', 'abc', NaN, Infinity, 'Infinity', true, false, [], {}, Number.MAX_SAFE_INTEGER + 1]
for (const field of ['basePriceCan', 'salePriceCan']) {
for (const value of invalidPrices) {
const errors = validateGiftSize(size({ [field]: value }))
assert.deepEqual(Object.keys(errors), [field], `${field}: ${String(value)}`)
assert.ok(errors[field])
}
}
for (const code of ['S', 'M', 'L', 'small', '', null, undefined, 'XLARGE']) {
assert.deepEqual(Object.keys(validateGiftSize(size({ sizeCode: code }))), ['sizeCode'])
}
for (const value of [null, undefined, 'true', 'false', 0, 1]) {
assert.deepEqual(Object.keys(validateGiftSize(size({ isActive: value }))), ['isActive'])
}
})
test('사이즈 validation: 최소값·동일 가격·숫자 문자열·false를 허용하고 초과 판매가는 거부한다', () => {
for (const sizeCode of giftSizes) {
for (const price of [1, '1', Number.MAX_SAFE_INTEGER]) {
const item = size({ sizeCode, basePriceCan: price, salePriceCan: price, isActive: false })
assert.deepEqual(validateGiftSize(item), {})
assert.deepEqual(buildGiftSizeRequest({ ...item, extra: '제외' }), { basePriceCan: Number(price), salePriceCan: Number(price), isActive: false })
}
}
assert.deepEqual(Object.keys(validateGiftSize(size({ basePriceCan: '9', salePriceCan: '10' }))), ['salePriceCan'])
const form = createGiftSizeForm(size())
assert.deepEqual(form, size())
form.basePriceCan = 1
assert.equal(createGiftSizeForm(size()).basePriceCan, 12000)
})
test('사이즈 목록: 최초 GET, 6개 컬럼, 숫자 포맷과 수정 전용 버튼을 표시한다', async () => {
const { vm } = page()
const rows = giftSizes.map(sizeCode => size({ sizeCode, isActive: sizeCode !== 'LARGE' }))
const expected = rows.map(item => ({ ...item }))
const calls = []
Vue.axios = { get: async (...args) => { calls.push(args); return { data: envelope(rows) } } }
await GiftSize.created.call(vm)
assert.deepEqual(calls, [['/api/v2/admin/gift-size-prices']])
assert.deepEqual(Array.from(vm.sizes), expected)
const rendered = nodes(vm._render())
assert.equal(text(rendered.find(node => node.tag === 'v-toolbar-title')), '선물 사이즈')
assert.deepEqual(rendered.filter(node => node.tag === 'th').map(text), ['사이즈 코드', '사이즈명', '기본가', '판매가', '활성 여부', '관리'])
assert.deepEqual(rendered.filter(node => node.tag === 'td').slice(0, 6).map(text), ['SMALL', '소형', (12000).toLocaleString(), (10000).toLocaleString(), '활성', '수정'])
assert.ok(text(vm._render()).includes('비활성'))
assert.deepEqual(rendered.filter(node => node.tag === 'v-btn').map(text), ['수정', '수정', '수정', '취소', '저장'])
button(vm, '수정').data.on.click()
assert.deepEqual(vm.form, rows[0])
assert.equal(vm.show_form_dialog, true)
})
test('사이즈 목록: 빈 목록·로딩·실패·재조회 및 늦은 응답을 처리한다', async () => {
const { vm, errors } = page()
assert.ok(text(vm._render()).includes('등록된 선물 사이즈가 없습니다.'))
const pending = deferred()
Vue.axios = { get: async () => pending.promise }
const old = vm.getSizes()
assert.equal(vm.is_loading, true)
assert.ok(text(vm._render()).includes('조회 중입니다.'))
vm.openEdit(size())
assert.equal(vm.show_form_dialog, false)
Vue.axios.get = async () => ({ data: { success: false, message: '조회 실패' } })
await vm.getSizes()
assert.deepEqual(errors, ['조회 실패'])
assert.equal(vm.list_error, true)
Vue.axios.get = async () => ({ data: envelope([size()]) })
await button(vm, '다시 조회').data.on.click()
pending.resolve({ data: envelope([]) })
await old
assert.deepEqual(Array.from(vm.sizes), [size()])
assert.equal(vm.list_error, false)
assert.equal(vm.is_loading, false)
})
test('사이즈 최초 등록: 빈 목록에서 고정 3종만 선택하며 가격과 활성 여부를 입력한다', async () => {
const { vm } = page()
Vue.axios = { get: async () => ({ data: envelope([]) }) }
await GiftSize.created.call(vm)
const create = button(vm, '사이즈 등록')
assert.ok(create, '빈 목록에서도 최초 등록 버튼이 있어야 한다')
assert.equal(create.data.attrs.disabled, false)
create.data.on.click()
assert.equal(vm.show_form_dialog, true)
assert.deepEqual(vm.form, createGiftSizeForm())
const rendered = nodes(vm._render())
assert.ok(text(vm._render()).includes('선물 사이즈 등록'))
const select = rendered.find(node => node.tag === 'v-select')
assert.ok(select)
assert.equal(select.data.attrs.label, '사이즈 코드')
assert.deepEqual(Array.from(select.data.attrs.items), ['SMALL', 'MEDIUM', 'LARGE'])
select.data.model.callback('MEDIUM')
assert.equal(vm.form.sizeCode, 'MEDIUM')
const prices = rendered.filter(node => node.tag === 'v-text-field')
assert.deepEqual(prices.map(node => node.data.attrs.label), ['기본가', '판매가'])
assert.ok(prices.every(node => node.data.attrs.type === 'number'))
assert.equal(rendered.filter(node => node.tag === 'v-switch').length, 1)
assert.equal(button(vm, '삭제'), undefined)
})
test('사이즈 최초 등록: 비활성을 포함한 등록 코드는 제외하고 3종 모두 등록되면 추가할 수 없다', async () => {
const { vm } = page()
Vue.axios = { get: async () => ({ data: envelope([size({ isActive: false }), size({ sizeCode: 'LARGE' })]) }) }
await vm.getSizes()
button(vm, '사이즈 등록').data.on.click()
const select = nodes(vm._render()).find(node => node.tag === 'v-select')
assert.deepEqual(Array.from(select.data.attrs.items), ['MEDIUM'])
vm.closeForm()
Vue.axios.get = async () => ({ data: envelope(giftSizes.map(sizeCode => size({ sizeCode, isActive: false }))) })
await vm.getSizes()
assert.equal(button(vm, '사이즈 등록'), undefined)
vm.openCreate()
assert.equal(vm.show_form_dialog, false)
assert.equal(nodes(vm._render()).filter(node => node.tag === 'v-btn' && text(node) === '수정').length, 3)
})
test('사이즈 최초 등록: 최초 조회 전·조회 중·조회 실패에는 등록을 차단하고 재조회 후 허용한다', async () => {
const { vm } = page()
assert.equal(button(vm, '사이즈 등록').data.attrs.disabled, true)
vm.openCreate()
assert.equal(vm.show_form_dialog, false)
const pending = deferred()
Vue.axios = { get: async () => pending.promise }
const load = vm.getSizes()
assert.equal(button(vm, '사이즈 등록').data.attrs.disabled, true)
vm.openCreate()
assert.equal(vm.show_form_dialog, false)
pending.resolve({ data: { success: false, message: '조회 실패' } })
await load
assert.equal(button(vm, '사이즈 등록').data.attrs.disabled, true)
vm.openCreate()
assert.equal(vm.show_form_dialog, false)
Vue.axios.get = async () => ({ data: envelope([]) })
await button(vm, '다시 조회').data.on.click()
assert.equal(button(vm, '사이즈 등록').data.attrs.disabled, false)
vm.openCreate()
assert.equal(vm.show_form_dialog, true)
})
test('사이즈 최초 등록: 미선택·잘못된 코드·기등록 코드·잘못된 가격은 필드 오류로 표시하고 PUT하지 않는다', async () => {
for (const overrides of [
{ sizeCode: '' }, { sizeCode: 'XLARGE' }, { sizeCode: 'SMALL' },
{ basePriceCan: '' }, { salePriceCan: '' }, { basePriceCan: 0 }, { salePriceCan: 1.5 }, { salePriceCan: 12001 }
]) {
const { vm, confirmations } = page()
let calls = 0
Vue.axios = {
get: async () => ({ data: envelope([size()]) }),
put: async () => { calls++ }
}
await vm.getSizes()
vm.openCreate()
Object.assign(vm.form, size({ sizeCode: 'MEDIUM', ...overrides }))
await vm.saveSize()
assert.equal(calls, 0)
assert.equal(confirmations.length, 0)
const labels = { sizeCode: '사이즈 코드', basePriceCan: '기본가', salePriceCan: '판매가' }
const label = labels[Object.keys(overrides)[0]]
const field = nodes(vm._render()).find(node => ['v-text-field', 'v-select'].includes(node.tag) && node.data.attrs.label === label)
assert.ok(field.data.attrs['error-messages'])
if (overrides.salePriceCan === 12001) assert.equal(field.data.attrs['error-messages'], '판매가는 기본가보다 클 수 없습니다.')
assert.equal(vm.show_form_dialog, true)
}
})
test('사이즈 최초 등록: 취소·수정 후 다시 열면 등록 폼과 오류를 초기화한다', async () => {
const { vm } = page()
Vue.axios = { get: async () => ({ data: envelope([size()]) }) }
await vm.getSizes()
vm.openCreate()
Object.assign(vm.form, size({ sizeCode: 'MEDIUM' }))
vm.form_errors = { sizeCode: '오류', salePriceCan: '오류' }
vm.closeForm()
vm.openCreate()
assert.deepEqual(vm.form, createGiftSizeForm())
assert.deepEqual(vm.form_errors, {})
vm.closeForm()
vm.openEdit(vm.sizes[0])
assert.equal(nodes(vm._render()).find(node => node.tag === 'v-select'), undefined)
assert.ok(text(vm._render()).includes('선물 사이즈 수정'))
vm.closeForm()
vm.openCreate()
assert.deepEqual(vm.form, createGiftSizeForm())
assert.ok(text(vm._render()).includes('선물 사이즈 등록'))
assert.deepEqual(Array.from(vm.sizes), [size()])
})
test('사이즈 최초 등록: 고정 3종을 기존 PUT으로 등록하고 정확한 본문·확인창·토스트·재조회를 제공한다', async () => {
const { vm, successes, confirmations } = page()
const rows = []
const calls = []
Vue.axios = { get: async () => ({ data: envelope([]) }) }
await vm.getSizes()
for (const [index, sizeCode] of giftSizes.entries()) {
const pending = deferred()
const saved = size({ sizeCode, name: `서버 이름 ${index}`, basePriceCan: 13000, salePriceCan: 11000, isActive: index !== 1 })
Vue.axios = {
put: async (...args) => { calls.push(['PUT', ...args]); rows.push(saved); return { data: envelope(saved) } },
get: async (...args) => { calls.push(['GET', ...args]); return pending.promise }
}
button(vm, '사이즈 등록').data.on.click()
Object.assign(vm.form, { sizeCode, basePriceCan: '13000', salePriceCan: '11000', isActive: saved.isActive, extra: '제외' })
const save = vm.saveSize()
await Vue.nextTick()
assert.equal(vm.show_form_dialog, true)
assert.equal(vm.is_operating, true)
assert.equal(button(vm, '사이즈 등록').data.attrs.disabled, true)
await vm.saveSize()
pending.resolve({ data: envelope([...rows]) })
await save
assert.deepEqual(calls.slice(index * 2), [
['PUT', `/api/v2/admin/gift-size-prices/${sizeCode}`, request({ basePriceCan: 13000, salePriceCan: 11000, isActive: saved.isActive })],
['GET', '/api/v2/admin/gift-size-prices']
])
assert.equal(confirmations[index].title, '선물 사이즈 등록 확인')
assert.ok(confirmations[index].text.includes(sizeCode))
assert.deepEqual(confirmations[index].actions, { false: '취소', true: '저장' })
assert.equal(successes[index], '선물 사이즈가 등록되었습니다.')
assert.deepEqual(Array.from(vm.sizes), rows)
assert.ok(text(vm._render()).includes(saved.name))
assert.equal(vm.show_form_dialog, false)
assert.equal(vm.is_operating, false)
}
assert.equal(button(vm, '사이즈 등록'), undefined)
assert.equal(calls.length, 6)
})
test('사이즈 최초 등록: 확인 취소·중복 제출을 차단하며 저장 중에는 코드와 입력값을 바꿀 수 없다', async () => {
const { vm } = page()
const pending = deferred()
let calls = 0
let confirms = 0
Vue.axios = { get: async () => ({ data: envelope([]) }), put: async () => { calls++ } }
await vm.getSizes()
vm.openCreate()
Object.assign(vm.form, size())
vm.$dialog.confirm = async () => { confirms++; return pending.promise }
const save = vm.saveSize()
await vm.saveSize()
vm.openCreate()
vm.openEdit(size({ sizeCode: 'LARGE' }))
vm.closeForm()
assert.deepEqual(vm.form, size())
assert.equal(vm.show_form_dialog, true)
assert.equal(confirms, 1)
assert.equal(calls, 0)
const rendered = nodes(vm._render())
for (const field of rendered.filter(node => ['v-select', 'v-text-field', 'v-switch'].includes(node.tag))) {
assert.equal(field.data.attrs.disabled, true)
}
assert.equal(button(vm, '저장').data.attrs.disabled, true)
assert.equal(button(vm, '취소').data.attrs.disabled, true)
pending.resolve(false)
await save
assert.equal(calls, 0)
assert.equal(vm.is_operating, false)
assert.equal(vm.show_form_dialog, true)
})
test('사이즈 최초 등록: 폼을 연 뒤나 확인 중 목록이 변경되면 기존 데이터 덮어쓰기를 차단한다', async () => {
for (const timing of ['before', 'confirm']) {
for (const state of ['registered', 'loading', 'failure']) {
const { vm } = page()
const confirmation = deferred()
const pending = deferred()
let calls = 0
Vue.axios = { get: async () => ({ data: envelope([]) }), put: async () => { calls++ } }
await vm.getSizes()
vm.openCreate()
Object.assign(vm.form, size())
vm.$dialog.confirm = async () => confirmation.promise
const save = timing === 'confirm' ? vm.saveSize() : null
Vue.axios.get = state === 'loading'
? async () => pending.promise
: async () => ({ data: state === 'failure' ? { success: false, message: '조회 실패' } : envelope([size()]) })
const load = vm.getSizes()
if (state !== 'loading') await load
confirmation.resolve(true)
if (timing === 'confirm') await save
else await vm.saveSize()
assert.equal(calls, 0)
assert.equal(vm.show_form_dialog, true)
assert.equal(vm.is_operating, false)
if (timing === 'confirm' || state === 'registered') assert.ok(vm.form_errors.sizeCode)
if (state === 'loading') {
pending.resolve({ data: envelope([]) })
await load
}
}
}
})
test('사이즈 최초 등록 실패: 서버 오류 시 입력을 유지하고 재조회 실패 시 중복 등록 진입을 차단한다', async () => {
for (const fail of [
async () => ({ data: { success: false, message: '등록 실패' } }),
async () => { throw { response: { data: { message: '등록 실패' } } } }
]) {
const { vm, errors, successes } = page()
let loads = 0
Vue.axios = { get: async () => { loads++; return { data: envelope([]) } }, put: fail }
await vm.getSizes()
vm.openCreate()
Object.assign(vm.form, size())
await vm.saveSize()
assert.deepEqual(errors, ['등록 실패'])
assert.deepEqual(successes, [])
assert.deepEqual(vm.form, size())
assert.equal(vm.show_form_dialog, true)
assert.equal(vm.is_operating, false)
assert.equal(loads, 1)
}
const { vm, errors, successes } = page()
Vue.axios = { get: async () => ({ data: envelope([]) }), put: async () => ({ data: envelope(size()) }) }
await vm.getSizes()
vm.openCreate()
Object.assign(vm.form, size())
Vue.axios.get = async () => { throw new Error('조회 실패') }
await vm.saveSize()
assert.deepEqual(successes, ['선물 사이즈가 등록되었습니다.'])
assert.deepEqual(errors, ['조회 실패'])
assert.equal(vm.show_form_dialog, false)
assert.equal(button(vm, '사이즈 등록').data.attrs.disabled, true)
vm.openCreate()
assert.equal(vm.show_form_dialog, false)
Vue.axios.get = async () => ({ data: envelope([size()]) })
await button(vm, '다시 조회').data.on.click()
vm.openCreate()
const select = nodes(vm._render()).find(node => node.tag === 'v-select')
assert.deepEqual(Array.from(select.data.attrs.items), ['MEDIUM', 'LARGE'])
})
test('사이즈 폼: 코드와 이름은 읽기 전용, 가격은 number, 취소는 row를 변경하지 않는다', () => {
const { vm } = page()
const item = size()
vm.openEdit(item)
const fields = nodes(vm._render()).filter(node => node.tag === 'v-text-field')
assert.equal(fields.length, 4)
for (const field of fields) {
const attrs = field.data.attrs
if (['사이즈 코드', '사이즈명'].includes(attrs.label)) assert.ok(attrs.readonly !== undefined && attrs.readonly !== false)
else {
assert.equal(attrs.type, 'number')
assert.equal(Number(attrs.min), 1)
assert.equal(Number(attrs.step), 1)
}
}
assert.equal(nodes(vm._render()).filter(node => node.tag === 'v-switch').length, 1)
vm.form.basePriceCan = 123
vm.form.isActive = false
vm.closeForm()
assert.deepEqual(item, size())
vm.form_errors = { salePriceCan: '오류' }
vm.openEdit(size({ sizeCode: 'MEDIUM', basePriceCan: 20000 }))
assert.equal(vm.form.sizeCode, 'MEDIUM')
assert.equal(vm.form.basePriceCan, 20000)
assert.deepEqual(vm.form_errors, {})
})
test('사이즈 폼: 잘못된 가격이면 API/확인창 없이 해당 필드 오류를 표시한다', async () => {
for (const overrides of [{ salePriceCan: 12001 }, { basePriceCan: '' }, { salePriceCan: '' }, { basePriceCan: 0 }, { salePriceCan: 1.5 }]) {
const { vm, confirmations } = page()
let calls = 0
Vue.axios = { put: async () => { calls++ } }
vm.openEdit(size(overrides))
const form = nodes(vm._render()).find(node => node.tag === 'v-form')
await form.data.on.submit({ preventDefault() {} })
assert.equal(calls, 0)
assert.equal(confirmations.length, 0)
const label = Object.keys(overrides)[0] === 'basePriceCan' ? '기본가' : '판매가'
const field = nodes(vm._render()).find(node => node.tag === 'v-text-field' && node.data.attrs.label === label)
assert.ok(field.data.attrs['error-messages'])
if (overrides.salePriceCan === 12001) assert.equal(field.data.attrs['error-messages'], '판매가는 기본가보다 클 수 없습니다.')
assert.equal(vm.show_form_dialog, true)
assert.equal(vm.is_operating, false)
}
})
test('사이즈 저장: 확인 전/취소 후에는 PUT하지 않고 중복 제출과 폼 변경을 차단한다', async () => {
const { vm } = page()
let calls = 0
const pending = deferred()
let confirms = 0
vm.$dialog.confirm = async () => { confirms++; return pending.promise }
Vue.axios = { put: async () => { calls++ } }
vm.openEdit(size())
const save = vm.saveSize()
await vm.saveSize()
vm.closeForm()
vm.openEdit(size({ sizeCode: 'LARGE' }))
assert.equal(confirms, 1)
assert.equal(calls, 0)
assert.equal(vm.form.sizeCode, 'SMALL')
assert.equal(vm.show_form_dialog, true)
assert.equal(button(vm, '저장').data.attrs.disabled, true)
assert.equal(button(vm, '취소').data.attrs.disabled, true)
pending.resolve(false)
await save
assert.equal(calls, 0)
assert.equal(vm.is_operating, false)
assert.equal(vm.show_form_dialog, true)
})
test('사이즈 저장: PUT의 정확한 본문, 성공 토스트, 목록 refresh 후 모달 닫기를 보장한다', async () => {
for (const sizeCode of giftSizes) {
const { vm, successes, confirmations } = page()
const pending = deferred()
const calls = []
const saved = size({ sizeCode, basePriceCan: 13000, salePriceCan: 11000, isActive: false })
Vue.axios = {
put: async (...args) => { calls.push(['PUT', ...args]); return { data: envelope(saved) } },
get: async (...args) => { calls.push(['GET', ...args]); return pending.promise }
}
vm.openEdit(size({ sizeCode }))
vm.form.basePriceCan = '13000'
vm.form.salePriceCan = '11000'
vm.form.isActive = false
vm.form.extra = '제외'
const save = vm.saveSize()
await Vue.nextTick()
assert.equal(vm.show_form_dialog, true)
assert.equal(vm.is_operating, true)
await vm.saveSize()
pending.resolve({ data: envelope([saved]) })
await save
assert.deepEqual(calls, [
['PUT', `/api/v2/admin/gift-size-prices/${sizeCode}`, request({ basePriceCan: 13000, salePriceCan: 11000, isActive: false })],
['GET', '/api/v2/admin/gift-size-prices']
])
assert.equal(confirmations.length, 1)
assert.deepEqual(confirmations[0].actions, { false: '취소', true: '저장' })
assert.deepEqual(successes, ['선물 사이즈가 수정되었습니다.'])
assert.deepEqual(Array.from(vm.sizes), [saved])
assert.equal(vm.show_form_dialog, false)
assert.equal(vm.is_operating, false)
await vm.saveSize()
assert.equal(calls.length, 2)
}
})
test('사이즈 저장 실패: envelope/HTTP 오류를 알리고 입력값과 모달을 유지한다', async () => {
for (const fail of [
async () => ({ data: { success: false, message: '저장 실패' } }),
async () => { throw { response: { data: { message: '저장 실패' } } } },
async () => { throw new Error('저장 실패') }
]) {
const { vm, errors, successes } = page()
let loads = 0
Vue.axios = { put: fail, get: async () => { loads++ } }
vm.openEdit(size())
await vm.saveSize()
assert.deepEqual(errors, ['저장 실패'])
assert.deepEqual(successes, [])
assert.deepEqual(vm.form, size())
assert.equal(vm.show_form_dialog, true)
assert.equal(vm.is_operating, false)
assert.equal(loads, 0)
}
})
test('사이즈 저장 후 조회 실패: 저장 성공과 조회 실패를 구분하고 재시도를 제공한다', async () => {
const { vm, errors, successes } = page()
Vue.axios = {
put: async () => ({ data: envelope(size()) }),
get: async () => { throw new Error('조회 실패') }
}
vm.openEdit(size())
await vm.saveSize()
assert.deepEqual(successes, ['선물 사이즈가 수정되었습니다.'])
assert.deepEqual(errors, ['조회 실패'])
assert.equal(vm.show_form_dialog, false)
assert.equal(vm.list_error, true)
assert.equal(vm.is_operating, false)
assert.ok(button(vm, '다시 조회'))
})
test('사이즈 메뉴/라우트: ADMIN만 보완하고 기존 서버 항목을 중복 없이 유지한다', async () => {
for (const role of ['ADMIN', 'CONTENT_MANAGER']) {
for (const existing of ['none', 'null', 'list', 'size', 'object']) {
const menus = []
if (existing !== 'none') {
const item = { title: existing === 'list' ? '선물함 리스트' : '선물 사이즈', route: existing === 'list' ? '/gift/list' : '/gift/size' }
menus.push({ title: '선물함 관리', items: existing === 'null' ? null : existing === 'object' ? item : [item] })
}
Vue.axios = { get: async () => ({ status: 200, data: envelope(menus) }) }
const vm = new Vue({ ...SideMenu, created: undefined })
vm.$store = { state: { accountStore: { role } } }
await vm.getMenus()
const gifts = vm.items.filter(item => item.title === '선물함 관리')
const children = gifts.length && gifts[0].items ? [].concat(gifts[0].items) : []
assert.equal(children.filter(item => item.route === '/gift/size').length, role === 'ADMIN' || ['size', 'object'].includes(existing) ? 1 : 0)
if (role === 'ADMIN') {
assert.equal(gifts.length, 1)
assert.equal(children.filter(item => item.route === '/gift/list').length, 1)
assert.equal(children.filter(item => item.route === '/gift/category').length, 1)
}
}
}
const router = fs.readFileSync(path.join(root, 'src/router/index.js'), 'utf8')
assert.match(router, /path: '\/gift\/size',\s*name: 'GiftSize',\s*component: \(\) => import\([^\n]*'\.\.\/views\/Gift\/GiftSize.vue'\)/)
})
;(async () => {
for (const { name, run } of tests) {
try {
await run()
console.log(`PASS ${name}`)
} catch (error) {
process.exitCode = 1
console.error(`FAIL ${name}`, error)
}
}
})()
-708
View File
@@ -1,708 +0,0 @@
const assert = require('assert').strict
const fs = require('fs')
const path = require('path')
const Module = require('module')
const { transformSync } = require('@babel/core')
const compiler = require('vue-template-compiler')
const Vue = require('vue')
const root = path.resolve(__dirname, '..')
const originalResolve = Module._resolveFilename
Module._resolveFilename = function(request, parent, ...rest) {
return originalResolve.call(this, request.startsWith('@/') ? path.join(root, 'src', request.slice(2)) : request, parent, ...rest)
}
const originalJs = require.extensions['.js']
function compileScript(source, filename) {
return transformSync(source, {
filename,
babelrc: false,
configFile: false,
plugins: ['@babel/plugin-transform-modules-commonjs']
}).code
}
require.extensions['.js'] = (module, filename) => {
if (!filename.startsWith(path.join(root, 'src') + path.sep)) return originalJs(module, filename)
module._compile(compileScript(fs.readFileSync(filename, 'utf8'), filename), filename)
}
require.extensions['.vue'] = (module, filename) => {
const { script, template } = compiler.parseComponent(fs.readFileSync(filename, 'utf8'))
const compiled = compiler.compile(template.content)
assert.deepEqual(compiled.errors, [], `${filename}: 템플릿 컴파일`)
module._compile(compileScript(script.content, filename), filename)
Object.assign(module.exports.default, compiler.compileToFunctions(template.content))
}
const utils = require('../src/utils/sub_banner')
const {
buildSubBannerCreateRequest,
buildSubBannerUpdateRequest,
createSubBannerForm,
formatScheduleRange,
langLabel,
normalizeUrls,
placementLabel,
resolveSubBannerTarget,
scheduleStatus,
toDateTimeLocalInput,
toServerDateTime,
validateSubBannerForm,
validateSubBannerUrls
} = utils
const SubBanner = require('../src/views/Promotion/SubBannerView.vue').default
const tests = []
const test = (name, run) => tests.push({ name, run })
const envelope = (data, success = true, message = null) => ({ success, message, data, errorProperty: null })
const subBanner = (overrides = {}) => ({
id: 1,
placement: 'HOME_RECOMMENDATION',
lang: 'KO',
imageUrl: 'https://cdn.example.test/promo.jpg',
webUrl: 'https://example.test/promo',
androidDeepLink: null,
iosDeepLink: null,
startDate: null,
endDate: null,
...overrides
})
const form = (overrides = {}) => ({ ...createSubBannerForm(), ...overrides })
function nodes(vnode) {
if (!vnode) return []
return [vnode].concat((vnode.children || (vnode.componentOptions && vnode.componentOptions.children) || []).flatMap(nodes))
}
const text = vnode => nodes(vnode).map(node => node.text || '').join(' ')
function activatorNodes(vm) {
const dialog = nodes(vm._render()).find(node => node.tag === 'v-dialog' && node.data.scopedSlots && node.data.scopedSlots.activator)
return [].concat(dialog.data.scopedSlots.activator({ on: {}, attrs: {} }))
}
const activatorText = vm => activatorNodes(vm).flatMap(nodes).map(node => node.text || '').join(' ')
function page() {
const errors = []
const successes = []
const vm = new Vue({ ...SubBanner, created: undefined })
vm.$dialog = { notify: { error: message => errors.push(message), success: message => successes.push(message) } }
return { vm, errors, successes }
}
function stubFormData() {
global.Blob = class {
constructor(parts, options) { this.parts = parts; this.type = options && options.type }
toString() { return this.parts.join('') }
}
global.FormData = class {
constructor() { this.store = new Map() }
append(key, value) { this.store.set(key, value) }
get(key) { return this.store.has(key) ? this.store.get(key) : null }
has(key) { return this.store.has(key) }
}
global.URL.createObjectURL = () => 'blob:preview'
}
function requestPart(formData) {
return formData.get('request')
}
function requestOf(formData) {
return JSON.parse(String(requestPart(formData)))
}
const URL_COMBINATIONS = [
{ web: false, android: false, ios: false, valid: false, androidTarget: 'NONE', iosTarget: 'NONE' },
{ web: true, android: false, ios: false, valid: true, androidTarget: 'WEB', iosTarget: 'WEB' },
{ web: false, android: true, ios: false, valid: true, androidTarget: 'DEEP_LINK', iosTarget: 'NONE' },
{ web: false, android: false, ios: true, valid: true, androidTarget: 'NONE', iosTarget: 'DEEP_LINK' },
{ web: true, android: true, ios: false, valid: true, androidTarget: 'DEEP_LINK_WITH_WEB_FALLBACK', iosTarget: 'WEB' },
{ web: true, android: false, ios: true, valid: true, androidTarget: 'WEB', iosTarget: 'DEEP_LINK_WITH_WEB_FALLBACK' },
{ web: false, android: true, ios: true, valid: true, androidTarget: 'DEEP_LINK', iosTarget: 'DEEP_LINK' },
{ web: true, android: true, ios: true, valid: true, androidTarget: 'DEEP_LINK_WITH_WEB_FALLBACK', iosTarget: 'DEEP_LINK_WITH_WEB_FALLBACK' }
]
test('placement: 두 값만 사용하고 레이블은 홈/콘텐츠로 표시한다', () => {
assert.deepEqual(utils.SUB_BANNER_PLACEMENTS.map(item => item.value), ['HOME_RECOMMENDATION', 'CONTENT_RECOMMENDATION'])
assert.equal(placementLabel('HOME_RECOMMENDATION'), '홈')
assert.equal(placementLabel('CONTENT_RECOMMENDATION'), '콘텐츠')
assert.equal(utils.isSubBannerPlacement('ETC'), false)
const { vm } = page()
const labels = nodes(vm._render()).filter(node => node.tag === 'v-radio').map(node => node.data.attrs.label)
assert.ok(labels.includes('홈') && labels.includes('콘텐츠'))
})
test('주소 조합 여덟 가지: 최소 한 개 요구와 Android/iOS 대상 판단', () => {
for (const combination of URL_COMBINATIONS) {
const current = form({
web_url: combination.web ? 'https://example.test/promo' : '',
android_deep_link: combination.android ? 'sampleapp://promo' : '',
ios_deep_link: combination.ios ? 'sampleapp://promo' : ''
})
const errors = validateSubBannerUrls(current)
assert.equal(Object.keys(errors).length === 0, combination.valid, JSON.stringify(combination))
const urls = normalizeUrls(current)
assert.equal(resolveSubBannerTarget(urls, 'android'), combination.androidTarget, JSON.stringify(combination))
assert.equal(resolveSubBannerTarget(urls, 'ios'), combination.iosTarget, JSON.stringify(combination))
}
})
test('주소 정규화: 공백 trim 후 blank 는 null, nonblank 는 원형을 보존한다', () => {
const raw = 'https://example.test/promo?q=%ED%95%9C%EA%B8%80&a=b+c#frag'
assert.deepEqual(
normalizeUrls(form({ web_url: ` ${raw} `, android_deep_link: ' ', ios_deep_link: '' })),
{ webUrl: raw, androidDeepLink: null, iosDeepLink: null }
)
const request = buildSubBannerCreateRequest(form({ web_url: ` ${raw} `, placement: 'HOME_RECOMMENDATION' }))
assert.equal(request.webUrl, raw)
assert.equal(request.androidDeepLink, null)
assert.equal(request.iosDeepLink, null)
})
test('주소 검증: 절대 http(s) 웹 URL 과 거부 scheme 딥링크를 가린다', () => {
for (const valid of ['https://example.test/promo', 'http://example.test']) {
assert.deepEqual(validateSubBannerUrls(form({ web_url: valid })), {})
}
for (const invalid of ['example.test/promo', '/promo', 'ftp://example.test', 'https://']) {
assert.deepEqual(Object.keys(validateSubBannerUrls(form({ web_url: invalid }))), ['web_url'], invalid)
}
for (const denied of ['javascript:alert(1)', 'JavaScript:alert(1)', 'DATA:text/html,1', 'file:///etc/passwd', 'content://media/1']) {
assert.deepEqual(
Object.keys(validateSubBannerUrls(form({ android_deep_link: denied }))),
['android_deep_link'],
denied
)
assert.deepEqual(Object.keys(validateSubBannerUrls(form({ ios_deep_link: denied }))), ['ios_deep_link'], denied)
}
assert.deepEqual(validateSubBannerUrls(form({ ios_deep_link: 'sampleapp://promo/1?a=b' })), {})
assert.deepEqual(Object.keys(validateSubBannerUrls(form({ ios_deep_link: 'promo' }))), ['ios_deep_link'])
})
test('주소 수정: 전부 비우면 오류, 한 필드만 비우면 해당 값만 null 로 보낸다', () => {
const saved = subBanner({ androidDeepLink: 'sampleapp://promo', iosDeepLink: 'sampleapp://ios' })
const cleared = createSubBannerForm(saved)
cleared.web_url = ''
cleared.android_deep_link = ''
cleared.ios_deep_link = ''
assert.deepEqual(Object.keys(validateSubBannerForm(cleared, saved)), ['web_url'])
const one = createSubBannerForm(saved)
one.ios_deep_link = ' '
assert.deepEqual(validateSubBannerForm(one, saved), {})
assert.deepEqual(buildSubBannerUpdateRequest(one, saved), {
placement: 'HOME_RECOMMENDATION',
webUrl: 'https://example.test/promo',
androidDeepLink: 'sampleapp://promo',
iosDeepLink: null,
lang: 'KO'
})
})
test('기간 변환: KST 분 문자열을 시간대 변환 없이 왕복한다', () => {
assert.equal(toDateTimeLocalInput('2026-11-01 09:30'), '2026-11-01T09:30')
assert.equal(toServerDateTime('2026-11-01T09:30'), '2026-11-01 09:30')
assert.equal(toServerDateTime(toDateTimeLocalInput('2026-11-01 09:30')), '2026-11-01 09:30')
for (const empty of [null, undefined, '', ' ', 'null']) {
assert.equal(toDateTimeLocalInput(empty), '')
assert.equal(toServerDateTime(empty), null)
}
})
test('기간 표시/상태: 무기간, 시작만, 종료만, 양끝과 미래/현재/만료', () => {
assert.equal(formatScheduleRange(null, null), '상시 노출 (기간 제한 없음)')
assert.equal(formatScheduleRange('2026-11-01 09:30', null), '2026-11-01 09:30 ~ (KST)')
assert.equal(formatScheduleRange(null, '2026-11-30 23:59'), '~ 2026-11-30 23:59 (KST)')
assert.equal(formatScheduleRange('2026-11-01 09:30', '2026-11-30 23:59'), '2026-11-01 09:30 ~ 2026-11-30 23:59 (KST)')
const now = '2026-11-10 00:00'
assert.equal(scheduleStatus(subBanner(), now), '무기간')
assert.equal(scheduleStatus(subBanner({ startDate: '2026-12-01 00:00' }), now), '예정')
assert.equal(scheduleStatus(subBanner({ endDate: '2026-11-09 23:59' }), now), '만료')
assert.equal(scheduleStatus(subBanner({ startDate: '2026-11-01 00:00', endDate: '2026-11-30 23:59' }), now), '노출중')
})
test('기간 검증: 두 날짜 null, 한쪽만, 같은 분, 경계값, 과거 날짜를 허용한다', () => {
const valid = [
{ start_date: '', end_date: '' },
{ start_date: '2026-11-01T09:30', end_date: '' },
{ start_date: '', end_date: '2026-11-30T23:59' },
{ start_date: '2026-11-01T09:30', end_date: '2026-11-01T09:30' },
{ start_date: '2026-11-01T00:00', end_date: '2026-11-01T23:59' },
{ start_date: '1970-01-01T09:01', end_date: '1970-01-01T09:01' },
{ start_date: '2038-01-19T12:14', end_date: '' },
{ start_date: '', end_date: '2038-01-19T12:13' },
{ start_date: '1970-01-01T09:01', end_date: '2038-01-19T12:13' },
{ start_date: '2020-01-01T00:00', end_date: '2021-01-01T00:00' }
]
for (const current of valid) {
assert.deepEqual(validateSubBannerForm(form({ ...current, web_url: 'https://example.test/promo' })), {}, JSON.stringify(current))
}
assert.deepEqual(validateSubBannerForm(form({ end_date: '2038-01-19T12:13', web_url: 'https://example.test/promo' })), {})
})
test('기간 검증: 잘못된 형식/범위/역전은 거부하고 값을 보정하지 않는다', () => {
const invalidStart = [
'2026-11-01T09:30:00', '2026-11-01T09:30:30Z', '2026-11-01T09:30+09:00', '2026-11-01',
'2026-13-01T09:30', '2026-02-30T09:30', '1988-05-08T02:30', '1970-01-01T09:00', '2038-01-19T12:15'
]
for (const start_date of invalidStart) {
const errors = validateSubBannerForm(form({ start_date, web_url: 'https://example.test/promo' }))
assert.deepEqual(Object.keys(errors), ['start_date'], start_date)
}
for (const end_date of ['2038-01-19T12:14', '1969-12-31T23:59', '2026-11-01T09:30:00']) {
const errors = validateSubBannerForm(form({ end_date, web_url: 'https://example.test/promo' }))
assert.deepEqual(Object.keys(errors), ['end_date'], end_date)
}
const reversed = validateSubBannerForm(form({
web_url: 'https://example.test/promo',
start_date: '2026-11-01T09:31',
end_date: '2026-11-01T09:30'
}))
assert.deepEqual(Object.keys(reversed), ['end_date'])
assert.deepEqual(
buildSubBannerCreateRequest(form({ start_date: '2026-11-01T09:31', end_date: '2026-11-01T09:30' })).startDate,
'2026-11-01 09:31'
)
})
test('등록 요청: 네 기본 필드는 항상 보내고 날짜 미입력은 생략한다', () => {
const base = form({
placement: 'CONTENT_RECOMMENDATION',
web_url: 'https://example.test/promo',
android_deep_link: 'sampleapp://promo'
})
assert.deepEqual(buildSubBannerCreateRequest(base), {
placement: 'CONTENT_RECOMMENDATION',
webUrl: 'https://example.test/promo',
androidDeepLink: 'sampleapp://promo',
iosDeepLink: null,
lang: 'KO'
})
assert.deepEqual(buildSubBannerCreateRequest({ ...base, start_date: '2026-11-01T09:30' }).startDate, '2026-11-01 09:30')
assert.deepEqual(buildSubBannerCreateRequest({ ...base, end_date: '2026-11-30T23:59' }).endDate, '2026-11-30 23:59')
})
test('수정 요청: 미변경 경계는 생략해 보존하고 지운 경계만 null 로 해제한다', () => {
const saved = subBanner({
androidDeepLink: 'sampleapp://promo',
startDate: '2026-11-01 09:30',
endDate: '2026-11-30 23:59'
})
const base = {
placement: 'HOME_RECOMMENDATION',
webUrl: 'https://example.test/promo',
androidDeepLink: 'sampleapp://promo',
iosDeepLink: null,
lang: 'KO'
}
// loaded date 재전송: 값이 같으면 생략해 저장 값을 보존한다.
assert.deepEqual(buildSubBannerUpdateRequest(createSubBannerForm(saved), saved), base)
const clearedEnd = createSubBannerForm(saved)
clearedEnd.end_date = ''
assert.deepEqual(buildSubBannerUpdateRequest(clearedEnd, saved), { ...base, endDate: null })
const clearedBoth = createSubBannerForm(saved)
clearedBoth.start_date = ''
clearedBoth.end_date = ''
assert.deepEqual(buildSubBannerUpdateRequest(clearedBoth, saved), { ...base, startDate: null, endDate: null })
const changed = createSubBannerForm(saved)
changed.start_date = '2026-12-01T00:00'
assert.deepEqual(buildSubBannerUpdateRequest(changed, saved), { ...base, startDate: '2026-12-01 00:00' })
})
test('수정 검증: 저장된 값과 새 값의 조합으로 범위를 판단한다', () => {
const saved = subBanner({ startDate: '2026-11-01 09:30', endDate: '2026-11-30 23:59' })
const lateStart = createSubBannerForm(saved)
lateStart.start_date = '2026-12-01T00:00'
assert.deepEqual(Object.keys(validateSubBannerForm(lateStart, saved)), ['end_date'])
const clearedEnd = createSubBannerForm(saved)
clearedEnd.start_date = '2026-12-01T00:00'
clearedEnd.end_date = ''
assert.deepEqual(validateSubBannerForm(clearedEnd, saved), {})
const savedStartOnly = subBanner({ startDate: '2026-11-01 09:30' })
const earlyEnd = createSubBannerForm(savedStartOnly)
earlyEnd.end_date = '2026-10-01T00:00'
assert.deepEqual(Object.keys(validateSubBannerForm(earlyEnd, savedStartOnly)), ['end_date'])
})
test('목록: placement 별로 조회하고 서버 순서대로 모두 표시한다', async () => {
const { vm, errors } = page()
const calls = []
Vue.axios = {
get: async (...args) => {
calls.push(args)
return {
status: 200,
data: envelope([
subBanner({ id: 7, startDate: '2030-01-01 00:00' }),
subBanner({ id: 3, endDate: '2020-01-01 00:00' }),
subBanner({ id: 11, startDate: '2026-11-01 09:30', endDate: '2026-11-30 23:59' }),
subBanner({ id: 5 })
])
}
}
}
await vm.getSubBanners()
assert.deepEqual(calls[0], ['/admin/sub-banners', { params: { placement: 'HOME_RECOMMENDATION' } }])
assert.deepEqual(vm.sub_banners.map(item => item.id), [7, 3, 11, 5])
const rendered = activatorText(vm)
assert.ok(rendered.includes('2030-01-01 00:00 ~ (KST)'))
assert.ok(rendered.includes('~ 2020-01-01 00:00 (KST)'))
assert.ok(rendered.includes('상시 노출 (기간 제한 없음)'))
assert.ok(rendered.includes('KST'))
vm.selected_placement = 'CONTENT_RECOMMENDATION'
await vm.getSubBanners()
assert.deepEqual(calls[1], ['/admin/sub-banners', { params: { placement: 'CONTENT_RECOMMENDATION' } }])
assert.deepEqual(errors, [])
})
test('목록 실패: success=false 와 예외를 빈 목록 성공으로 오인하지 않는다', async () => {
const { vm, errors } = page()
vm.sub_banners = [subBanner()]
Vue.axios = { get: async () => ({ status: 200, data: envelope(null, false, '권한이 없습니다.') }) }
await vm.getSubBanners()
assert.deepEqual(errors, ['권한이 없습니다.'])
assert.deepEqual(vm.sub_banners.map(item => item.id), [1])
Vue.axios = { get: async () => { throw new Error('401') } }
await vm.getSubBanners()
assert.equal(errors.length, 2)
assert.deepEqual(vm.sub_banners.map(item => item.id), [1])
})
test('등록: image 와 application/json request 파트를 보내고 목록을 갱신한다', async () => {
stubFormData()
const { vm, successes } = page()
const calls = []
Vue.axios = {
post: async (...args) => { calls.push(args); return { status: 200, data: envelope(subBanner()) } },
get: async () => ({ status: 200, data: envelope([subBanner()]) })
}
vm.showCreateDialog()
vm.sub_banner.placement = 'CONTENT_RECOMMENDATION'
vm.sub_banner.web_url = ' https://example.test/promo '
vm.sub_banner.start_date = '2026-11-01T09:30'
vm.imageAdd({ name: 'promo.jpg', type: 'image/jpeg' })
await vm.submit()
assert.equal(calls.length, 1)
assert.equal(calls[0][0], '/admin/sub-banners')
assert.equal(calls[0][1].get('image').name, 'promo.jpg')
assert.equal(calls[0][1].get('request').type, 'application/json')
assert.deepEqual(requestOf(calls[0][1]), {
placement: 'CONTENT_RECOMMENDATION',
webUrl: 'https://example.test/promo',
androidDeepLink: null,
iosDeepLink: null,
lang: 'KO',
startDate: '2026-11-01 09:30'
})
assert.deepEqual(successes, ['등록되었습니다.'])
assert.equal(vm.selected_placement, 'CONTENT_RECOMMENDATION')
assert.deepEqual(vm.sub_banners.map(item => item.id), [1])
})
test('등록 검증: 이미지와 최소 한 주소가 없으면 전송하지 않는다', async () => {
stubFormData()
const { vm, errors } = page()
const calls = []
Vue.axios = { post: async () => { calls.push('POST'); return { status: 200, data: envelope(subBanner()) } } }
vm.showCreateDialog()
await vm.submit()
assert.deepEqual(calls, [])
assert.equal(errors.length, 1)
vm.sub_banner.web_url = 'https://example.test/promo'
await vm.submit()
assert.deepEqual(calls, [])
assert.deepEqual(errors[1], '배너 이미지를 등록하세요.')
})
test('수정: 목록 객체로 폼을 채우고 일정만 바꾸면 image 를 생략한다', async () => {
stubFormData()
const { vm, successes } = page()
const calls = []
Vue.axios = {
put: async (...args) => { calls.push(args); return { status: 200, data: envelope(subBanner()) } },
get: async () => ({ status: 200, data: envelope([subBanner()]) })
}
const saved = subBanner({
id: 123,
androidDeepLink: 'sampleapp://promo',
startDate: '2026-11-01 09:30',
endDate: '2026-11-30 23:59'
})
vm.showModifyDialog(saved)
assert.equal(vm.sub_banner.web_url, 'https://example.test/promo')
assert.equal(vm.sub_banner.android_deep_link, 'sampleapp://promo')
assert.equal(vm.sub_banner.ios_deep_link, '')
assert.equal(vm.sub_banner.start_date, '2026-11-01T09:30')
assert.equal(vm.sub_banner.end_date, '2026-11-30T23:59')
assert.equal(vm.sub_banner.image_url, 'https://cdn.example.test/promo.jpg')
vm.sub_banner.end_date = '2026-12-31T23:59'
await vm.modify()
assert.equal(calls[0][0], '/admin/sub-banners/123')
assert.equal(calls[0][1].has('image'), false)
assert.deepEqual(requestOf(calls[0][1]), {
placement: 'HOME_RECOMMENDATION',
webUrl: 'https://example.test/promo',
androidDeepLink: 'sampleapp://promo',
iosDeepLink: null,
lang: 'KO',
endDate: '2026-12-31 23:59'
})
assert.deepEqual(successes, ['수정되었습니다.'])
})
test('수정 실패: 입력값과 기존 이미지 상태를 보존하고 실패를 알린다', async () => {
stubFormData()
const { vm, errors, successes } = page()
Vue.axios = { put: async () => ({ status: 200, data: envelope(null, false, '저장에 실패했습니다.') }) }
vm.showModifyDialog(subBanner({ id: 9 }))
vm.sub_banner.web_url = 'https://example.test/changed'
await vm.modify()
assert.deepEqual(errors, ['저장에 실패했습니다.'])
assert.deepEqual(successes, [])
assert.equal(vm.show_write_dialog, true)
assert.equal(vm.sub_banner.web_url, 'https://example.test/changed')
assert.equal(vm.sub_banner.image_url, 'https://cdn.example.test/promo.jpg')
})
test('삭제: 확인 후 호출하고 성공하면 목록에서 사라진다', async () => {
const { vm, successes, errors } = page()
const calls = []
let remaining = [subBanner({ id: 1 }), subBanner({ id: 2 })]
Vue.axios = {
delete: async (...args) => {
calls.push(args)
remaining = remaining.filter(item => item.id !== 2)
return { status: 200, data: envelope(null) }
},
get: async () => ({ status: 200, data: envelope(remaining) })
}
vm.sub_banners = remaining
vm.deleteConfirm(subBanner({ id: 2 }))
assert.equal(vm.show_delete_confirm_dialog, true)
vm.deleteCancel()
assert.equal(vm.show_delete_confirm_dialog, false)
assert.deepEqual(calls, [])
vm.deleteConfirm(subBanner({ id: 2 }))
await vm.deleteSubBanner()
assert.deepEqual(calls, [['/admin/sub-banners/2']])
assert.deepEqual(vm.sub_banners.map(item => item.id), [1])
assert.deepEqual(successes, ['삭제되었습니다.'])
assert.deepEqual(errors, [])
})
test('삭제 실패: 404 이후 응답은 success=false 로 알리고 목록을 유지한다', async () => {
const { vm, errors } = page()
Vue.axios = { delete: async () => ({ status: 200, data: envelope(null, false, '존재하지 않는 배너입니다.') }) }
vm.sub_banners = [subBanner({ id: 1 })]
vm.deleteConfirm(subBanner({ id: 1 }))
await vm.deleteSubBanner()
assert.deepEqual(errors, ['존재하지 않는 배너입니다.'])
assert.deepEqual(vm.sub_banners.map(item => item.id), [1])
})
test('중복 제출 방지: 진행 중 재호출과 timeout 이후 재전송을 막는다', async () => {
stubFormData()
const { vm, errors } = page()
let posts = 0
let resolvePost = null
Vue.axios = {
post: async () => {
posts += 1
await new Promise(resolve => { resolvePost = resolve })
return { status: 200, data: envelope(subBanner()) }
},
get: async () => ({ status: 200, data: envelope([subBanner()]) })
}
vm.showCreateDialog()
vm.sub_banner.web_url = 'https://example.test/promo'
vm.imageAdd({ name: 'promo.jpg', type: 'image/jpeg' })
const first = vm.submit()
await Promise.resolve()
await vm.submit()
assert.equal(posts, 1)
resolvePost()
await first
// timeout 등으로 결과가 불명확하면 자동 재시도 없이 전송을 차단한다.
const timeoutPage = page()
let timeoutPosts = 0
Vue.axios = {
post: async () => { timeoutPosts += 1; throw new Error('timeout of 0ms exceeded') },
get: async () => ({ status: 200, data: envelope([subBanner()]) })
}
timeoutPage.vm.showCreateDialog()
timeoutPage.vm.sub_banner.web_url = 'https://example.test/promo'
timeoutPage.vm.imageAdd({ name: 'promo.jpg', type: 'image/jpeg' })
await timeoutPage.vm.submit()
await timeoutPage.vm.submit()
assert.equal(timeoutPosts, 1)
assert.equal(timeoutPage.vm.submit_blocked, true)
assert.deepEqual(timeoutPage.vm.sub_banners.map(item => item.id), [1])
assert.equal(timeoutPage.errors.length, 1)
})
test('언어: 신규 기본값은 KO 이고 선택한 코드가 정규 대문자로 직렬화된다', () => {
assert.equal(createSubBannerForm().lang, 'KO')
assert.equal(langLabel('KO'), '한국어')
assert.equal(langLabel('JA'), '일본어')
assert.equal(langLabel('EN'), '영어')
assert.equal(langLabel('ko'), '')
for (const lang of ['KO', 'JA', 'EN']) {
const created = buildSubBannerCreateRequest(form({ lang, web_url: 'https://example.test/promo' }))
assert.deepEqual(created, {
placement: 'HOME_RECOMMENDATION',
webUrl: 'https://example.test/promo',
androidDeepLink: null,
iosDeepLink: null,
lang
})
const saved = subBanner({ lang })
const updated = buildSubBannerUpdateRequest(createSubBannerForm(saved), saved)
assert.deepEqual(Object.keys(updated), ['placement', 'webUrl', 'androidDeepLink', 'iosDeepLink', 'lang'])
assert.equal(updated.lang, lang)
}
})
test('언어: 수정 폼은 저장된 JA/EN 으로 미리 선택되고 다른 값만 바꿔도 보존된다', async () => {
stubFormData()
const { vm } = page()
const calls = []
Vue.axios = {
put: async (...args) => { calls.push(args); return { status: 200, data: envelope(subBanner({ lang: 'JA' })) } },
get: async () => ({ status: 200, data: envelope([subBanner({ lang: 'JA' })]) })
}
const saved = subBanner({ id: 55, lang: 'JA', startDate: '2026-11-01 09:30', endDate: '2026-11-30 23:59' })
vm.showModifyDialog(saved)
assert.equal(vm.sub_banner.lang, 'JA')
// 이미지와 종료 일시만 바꿔도 저장된 언어가 그대로 전송된다.
vm.imageAdd({ name: 'new.jpg', type: 'image/jpeg' })
vm.sub_banner.end_date = '2026-12-31T23:59'
await vm.modify()
assert.equal(calls[0][0], '/admin/sub-banners/55')
assert.equal(calls[0][1].get('image').name, 'new.jpg')
assert.deepEqual(requestOf(calls[0][1]), {
placement: 'HOME_RECOMMENDATION',
webUrl: 'https://example.test/promo',
androidDeepLink: null,
iosDeepLink: null,
lang: 'JA',
endDate: '2026-12-31 23:59'
})
const en = subBanner({ id: 56, lang: 'EN' })
vm.showModifyDialog(en)
assert.equal(vm.sub_banner.lang, 'EN')
// 언어만 바꿔도 나머지 값은 그대로다.
vm.sub_banner.lang = 'KO'
await vm.modify()
assert.deepEqual(requestOf(calls[1][1]), {
placement: 'HOME_RECOMMENDATION',
webUrl: 'https://example.test/promo',
androidDeepLink: null,
iosDeepLink: null,
lang: 'KO'
})
assert.equal(calls[1][1].has('image'), false)
})
test('언어 오류: 400 Boot body 와 success=false 모두 입력·이미지·날짜를 보존한다', async () => {
stubFormData()
const bootError = {
response: {
status: 400,
data: { timestamp: '2026-11-01T00:00:00.000+00:00', status: 400, error: 'Bad Request', message: '지원하지 않는 언어입니다.', path: '/admin/sub-banners' }
}
}
const { vm, errors, successes } = page()
Vue.axios = {
post: async () => { throw bootError },
get: async () => ({ status: 200, data: envelope([subBanner()]) })
}
vm.showCreateDialog()
vm.sub_banner.lang = 'EN'
vm.sub_banner.web_url = 'https://example.test/promo'
vm.sub_banner.start_date = '2026-11-01T09:30'
vm.imageAdd({ name: 'promo.jpg', type: 'image/jpeg' })
await vm.submit()
assert.deepEqual(errors, ['지원하지 않는 언어입니다.'])
assert.deepEqual(successes, [])
// 400 은 서버가 확실히 거부한 것이므로 재전송을 막지 않고 상태를 보존한다.
assert.equal(vm.submit_blocked, false)
assert.equal(vm.show_write_dialog, true)
assert.equal(vm.sub_banner.lang, 'EN')
assert.equal(vm.sub_banner.web_url, 'https://example.test/promo')
assert.equal(vm.sub_banner.start_date, '2026-11-01T09:30')
assert.equal(vm.sub_banner.image.name, 'promo.jpg')
const failed = page()
Vue.axios = { put: async () => ({ status: 200, data: envelope(null, false, '언어 값이 올바르지 않습니다.') }) }
failed.vm.showModifyDialog(subBanner({ id: 9, lang: 'JA', startDate: '2026-11-01 09:30' }))
failed.vm.sub_banner.lang = 'EN'
await failed.vm.modify()
assert.deepEqual(failed.errors, ['언어 값이 올바르지 않습니다.'])
assert.equal(failed.vm.sub_banner.lang, 'EN')
assert.equal(failed.vm.sub_banner.start_date, '2026-11-01T09:30')
assert.equal(failed.vm.sub_banner.image_url, 'https://cdn.example.test/promo.jpg')
})
test('목록: 언어를 표시하고 lang 이 없는 응답은 KO 로 간주하지 않는다', async () => {
const { vm, errors } = page()
Vue.axios = {
get: async () => ({
status: 200,
data: envelope([subBanner({ id: 1, lang: 'KO' }), subBanner({ id: 2, lang: 'JA' }), subBanner({ id: 3, lang: 'EN' })])
})
}
await vm.getSubBanners()
const rendered = activatorText(vm)
assert.ok(rendered.includes('한국어'))
assert.ok(rendered.includes('일본어'))
assert.ok(rendered.includes('영어'))
assert.deepEqual(errors, [])
const missing = subBanner({ id: 4 })
delete missing.lang
Vue.axios = { get: async () => ({ status: 200, data: envelope([missing]) }) }
await vm.getSubBanners()
assert.equal(errors.length, 1)
assert.equal(vm.langText(missing), '-')
})
;(async () => {
for (const { name, run } of tests) {
try {
await run()
console.log(`PASS ${name}`)
} catch (error) {
process.exitCode = 1
console.error(`FAIL ${name}`, error)
}
}
})()