Files
sodalive-vuejs-admin/src/utils/sub_banner.js
T
Yu Sung 1ba1311373 feat(sub-banner): 서브 배너 생성·수정 폼에 언어 선택 추가
- 생성·수정 폼에 KO/JA/EN 언어 select 추가 (신규 기본값 KO, 수정은 저장된 lang 유지)
- multipart request JSON 파트에 정규 대문자 lang 을 항상 포함해 전송
- 목록에 언어 열 추가, lang 누락 응답은 KO 로 간주하지 않고 계약 미충족 안내
- EN 은 현재 앱 공개 국가 매핑에서 미노출됨을 폼에 안내
- 400 등 4xx 거부 시 입력값·선택 파일·날짜를 보존하고 재전송을 막지 않도록 처리
- 언어 관련 focused test 추가
2026-11-03 02:17:03 +09:00

313 lines
11 KiB
JavaScript

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'
}