Files
boursecu_admin/src/api/appBanners.ts
T

189 lines
5.9 KiB
TypeScript
Raw Normal View History

2026-07-18 09:55:51 +02:00
import useAxios from '@core/utils/useAxios'
import type { Const } from '@/model/const'
import type { IBenefits } from '@/model/banner'
import {
APP_BANNERS_CONST_KEY,
LEGACY_SLIDER_BANNERS_CONST_KEY,
LEGACY_THEME_BANNERS_CONST_KEY,
emptyAppBanners,
parseAppBanners,
serializeAppBanners,
type AppBannersValue,
} from '@/model/appBanners'
function pickConstRow(res: Const | Const[] | null | undefined): Const | null {
if (!res) return null
if (Array.isArray(res)) {
const rows = res.filter(isMeaningfulConstRow)
if (!rows.length) return null
return rows.reduce((best, row) => {
const a = Number(best.id ?? best.const_id ?? 0)
const b = Number(row.id ?? row.const_id ?? 0)
return b > a ? row : best
})
}
return isMeaningfulConstRow(res) ? res : null
}
/** API برای کلید ناموجود گاهی `{}` یا null برمی‌گرداند — نباید مهاجرت را قطع کند */
function isMeaningfulConstRow(row: Const | null | undefined): row is Const {
if (!row || typeof row !== 'object') return false
const hasId = row.id != null || row.const_id != null
const raw = row.value
const hasValue =
typeof raw === 'string'
? raw.trim() !== ''
: raw != null && !(typeof raw === 'object' && !Array.isArray(raw) && Object.keys(raw as object).length === 0)
return hasId || hasValue
2026-07-18 09:55:51 +02:00
}
function parseLegacySlider(value: string | null | undefined): IBenefits[] {
if (!value) return []
try {
const parsed = JSON.parse(value)
return Array.isArray(parsed) ? (parsed as IBenefits[]) : []
} catch {
return []
}
}
export type AppBannersConstState = {
/** فقط وقتی رکورد واقعاً با key=app_banners است؛ وگرنه null تا create شود */
id: number | null
data: AppBannersValue
}
async function loadLegacySliderInto(merged: AppBannersValue): Promise<void> {
try {
const sliderRes = await useAxios.get<Const | Const[]>(
`/api/const/key/${LEGACY_SLIDER_BANNERS_CONST_KEY}`
)
const sliderRow = pickConstRow(sliderRes)
if (!sliderRow) return
const slides = parseLegacySlider(sliderRow.value)
if (slides.length) merged.slider = slides
} catch {
// ignore
}
}
2026-07-18 09:55:51 +02:00
/**
* یک API واحد برای همهٔ بنرها.
* اگر `app_banners` نبود یا اسلایدر خالی بود، از کلیدهای قدیمی migrate می‌کند (فقط خواندن).
2026-07-18 09:55:51 +02:00
*/
export async function loadAppBannersConst(): Promise<AppBannersConstState> {
let appRow: Const | null = null
2026-07-18 09:55:51 +02:00
try {
const res = await useAxios.get<Const | Const[]>(`/api/const/key/${APP_BANNERS_CONST_KEY}`)
appRow = pickConstRow(res)
2026-07-18 09:55:51 +02:00
} catch {
// ادامه با مهاجرت از کلیدهای قدیمی
}
if (appRow) {
const data = parseAppBanners(appRow.value)
// رکورد جدید خالی: اسلایدر را از header_banner پر کن
if (!data.slider.length) {
await loadLegacySliderInto(data)
}
return {
id: appRow.id ?? appRow.const_id ?? null,
data,
}
}
2026-07-18 09:55:51 +02:00
const merged = emptyAppBanners()
try {
const themeRes = await useAxios.get<Const | Const[]>(
`/api/const/key/${LEGACY_THEME_BANNERS_CONST_KEY}`
)
const themeRow = pickConstRow(themeRes)
if (themeRow) {
const themes = parseAppBanners(themeRow.value)
Object.assign(merged, {
homeAsset: themes.homeAsset,
piggyCreate: themes.piggyCreate,
productsHero: themes.productsHero?.length ? themes.productsHero : merged.productsHero,
2026-07-18 09:55:51 +02:00
referral: themes.referral,
share: themes.share,
invite: themes.invite,
slider: themes.slider?.length ? themes.slider : merged.slider,
})
}
} catch {
// ignore
}
await loadLegacySliderInto(merged)
2026-07-18 09:55:51 +02:00
// id=null → اولین ذخیره، رکورد جدید با key=app_banners می‌سازد
return { id: null, data: merged }
}
async function syncLegacySliderConst(slides: IBenefits[]): Promise<void> {
const value = JSON.stringify(slides ?? [])
const payload = {
key: LEGACY_SLIDER_BANNERS_CONST_KEY,
value,
title_fa: 'بنرهای اسلایدر',
is_active: true,
description: 'اسلایدر بالای صفحه اصلی اپ مشتری (سازگاری با اپ)',
}
try {
const existingRes = await useAxios.get<Const | Const[]>(
`/api/const/key/${LEGACY_SLIDER_BANNERS_CONST_KEY}`
)
const existing = pickConstRow(existingRes)
const existingId = existing?.id ?? existing?.const_id ?? null
if (existingId) {
await useAxios.put<Const>(`/admin/const/${existingId}`, { id: existingId, ...payload })
return
}
} catch {
// create below
}
await useAxios.post<Const>(`/admin/const`, { id: 0, ...payload })
}
2026-07-18 09:55:51 +02:00
export async function saveAppBannersConst(
id: number | null,
data: AppBannersValue
): Promise<number | null> {
const value = serializeAppBanners(data)
const payload = {
key: APP_BANNERS_CONST_KEY,
value,
title_fa: 'بنرهای اپ',
is_active: true,
description: 'همهٔ بنرهای اپ: اسلایدر صفحه اصلی + تصاویر تم لایت/دارک',
}
let nextId = id
try {
const existingRes = await useAxios.get<Const | Const[]>(`/api/const/key/${APP_BANNERS_CONST_KEY}`)
const existing = pickConstRow(existingRes)
nextId = existing?.id ?? existing?.const_id ?? id
} catch {
// create below
}
if (nextId) {
await useAxios.put<Const>(`/admin/const/${nextId}`, { id: nextId, ...payload })
} else {
const created = await useAxios.post<Const>(`/admin/const`, { id: 0, ...payload })
nextId = created?.id ?? created?.const_id ?? null
2026-07-18 09:55:51 +02:00
}
// اپ مشتری هنوز header_banner می‌خواند — اسلایدر را همگام نگه دار
try {
await syncLegacySliderConst(data.slider ?? [])
} catch (error) {
console.error('همگام‌سازی header_banner ناموفق بود:', error)
}
return nextId
2026-07-18 09:55:51 +02:00
}