Compare commits
101
Commits
test
..
94ecf2b2ec
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
94ecf2b2ec | ||
|
|
17ff1b817d | ||
|
|
6769d8d485 | ||
|
|
860b3c7bab | ||
|
|
7d694a4c36 | ||
|
|
cae9e9a430 | ||
|
|
f90f8f6250 | ||
|
|
abb15cb2c7 | ||
|
|
b26837f258 | ||
|
|
f42602886e | ||
|
|
b8373829f0 | ||
|
|
2769c3c9f0 | ||
|
|
648d4d3a97 | ||
|
|
4baf253b7e | ||
|
|
e0c63df2a6 | ||
|
|
892923becc | ||
|
|
d3ea703204 | ||
|
|
70298b8f8f | ||
|
|
9fa9f3e699 | ||
|
|
d82531583c | ||
|
|
6240a285c2 | ||
|
|
f577ab575e | ||
|
|
0c3e3fc3fd | ||
|
|
6886c372aa | ||
|
|
8dd3dcb770 | ||
|
|
1a435b6074 | ||
|
|
492859dae3 | ||
|
|
18b59b5598 | ||
|
|
5fcdd7f06d | ||
|
|
1e149f7e41 | ||
|
|
aca3767a24 | ||
|
|
d51655f15e | ||
|
|
47dd32939f | ||
|
|
2e1891ab08 | ||
|
|
99d70cc8f7 | ||
|
|
9f1675e82d | ||
|
|
c2838be2ed | ||
|
|
b5c2941c0d | ||
|
|
d5c01d8d23 | ||
|
|
7118b0649a | ||
|
|
8f5346581e | ||
|
|
e43f2e30be | ||
|
|
397fd267e0 | ||
|
|
fe4b88350b | ||
|
|
537474e162 | ||
|
|
b5abdf3cf5 | ||
|
|
a2e457b5e8 | ||
|
|
05ddd417cd | ||
|
|
e70426af68 | ||
|
|
81b33e1322 | ||
|
|
588fcfbe90 | ||
|
|
ff2c126382 | ||
|
|
702daca29f | ||
|
|
8e9008a3c1 | ||
|
|
5c0c00aad4 | ||
|
|
e0949c6d73 | ||
|
|
0449bac8d5 | ||
|
|
d412c15c9d | ||
|
|
ed16a6ddad | ||
|
|
f06e2d41e0 | ||
|
|
7505269db3 | ||
|
|
15eeb6943d | ||
|
|
7e7ed46cea | ||
|
|
fd01786649 | ||
|
|
c48c1c2f09 | ||
|
|
9bcf3a3cdb | ||
|
|
4c5b987d98 | ||
|
|
f168403048 | ||
|
|
82ee1584e7 | ||
|
|
65cb918389 | ||
|
|
784baf9a2f | ||
|
|
7a85ac41cc | ||
|
|
9d4c9437cf | ||
|
|
68845aeae1 | ||
|
|
bbdca29337 | ||
|
|
c14c041daa | ||
|
|
a515a144eb | ||
|
|
54a6773905 | ||
|
|
d97087b4e9 | ||
|
|
ddb2449053 | ||
|
|
8aca07cdf7 | ||
|
|
0ba845d95a | ||
|
|
64b1fd5395 | ||
|
|
639bea70fa | ||
|
|
6a89ba059b | ||
|
|
ff83041585 | ||
|
|
e660be0bf4 | ||
|
|
62cdd57069 | ||
|
|
f8346ed5ef | ||
|
|
9656b9a9d1 | ||
|
|
97a58266bb | ||
|
|
8fc0cfa345 | ||
|
|
22f9c2287d | ||
|
|
9284f7d5c3 | ||
|
|
e6f27a4529 | ||
|
|
6a33d1c024 | ||
|
|
3b83789c15 | ||
|
|
55f0ab9af3 | ||
|
|
9b168a6112 | ||
|
|
c47937933e | ||
|
|
4744fe7d9a |
@@ -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
|
||||
|
||||
Generated
+22609
-7174
File diff suppressed because it is too large
Load Diff
+11
-23
@@ -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": [
|
||||
|
||||
@@ -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 }
|
||||
@@ -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 }
|
||||
@@ -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 }
|
||||
@@ -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 }
|
||||
@@ -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")
|
||||
}
|
||||
@@ -97,7 +90,6 @@ export {
|
||||
getCreatorList,
|
||||
searchCreator,
|
||||
updateMember,
|
||||
updateCreatorLocalizedNameJa,
|
||||
getCreatorAllList,
|
||||
resetPassword,
|
||||
blockMember,
|
||||
|
||||
+7
-18
@@ -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
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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}
|
||||
@@ -104,37 +104,6 @@ export default {
|
||||
|
||||
// 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) : [])
|
||||
}
|
||||
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 === '시리즈 관리')
|
||||
@@ -155,28 +124,6 @@ export default {
|
||||
// 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]
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
// 캐릭터 챗봇 메뉴 추가
|
||||
this.items.push({
|
||||
title: '캐릭터 챗봇',
|
||||
|
||||
@@ -182,11 +182,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',
|
||||
@@ -367,26 +362,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',
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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'
|
||||
}
|
||||
@@ -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
|
||||
@@ -248,38 +245,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">
|
||||
배너 이미지 등록
|
||||
@@ -407,13 +372,6 @@ 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",
|
||||
@@ -433,8 +391,7 @@ export default {
|
||||
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, lang: 'ko'},
|
||||
banners: [],
|
||||
events: [],
|
||||
creators: [],
|
||||
@@ -578,8 +535,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, lang: 'ko'}
|
||||
this.selected_banner = {}
|
||||
this.search_query_creator = ''
|
||||
this.search_query_series = ''
|
||||
@@ -632,10 +588,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
|
||||
@@ -681,26 +633,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
|
||||
@@ -740,8 +675,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 +695,6 @@ export default {
|
||||
},
|
||||
|
||||
async modify() {
|
||||
if (!this.validateSchedule()) return;
|
||||
if (this.is_loading) return;
|
||||
|
||||
this.is_loading = true
|
||||
@@ -818,8 +750,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 +945,6 @@ export default {
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.schedule-text {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.image-preview {
|
||||
max-width: 100%;
|
||||
width: 250px;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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,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>
|
||||
@@ -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 || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
})()
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
})()
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
})()
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
})()
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
})()
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
})()
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
})()
|
||||
Reference in New Issue
Block a user