freshyo/packages/db_helper_sqlite/src/superadmin-apis/global-stores.ts
2026-10-10 15:00:50 +05:30

80 lines
2.4 KiB
TypeScript

import { db } from '../db/db_index'
import { storeInfo, productInfo } from '../db/schema'
import { and, eq, sql } from 'drizzle-orm'
import type { Store, CreateStoreInput, UpdateStoreInput } from '@packages/shared'
const toStore = (s: any): Store => ({
id: s.id,
name: s.name,
description: s.description,
imageUrl: s.imageUrl,
isGlobal: s.isGlobal,
createdAt: s.createdAt,
})
/** True when the store exists and is global. */
export async function isGlobalStore(storeId: number): Promise<boolean> {
const s = await db.query.storeInfo.findFirst({
where: eq(storeInfo.id, storeId),
columns: { isGlobal: true },
})
return !!s?.isGlobal
}
export async function listGlobalStores(): Promise<Store[]> {
const rows = await db.query.storeInfo.findMany({
where: eq(storeInfo.isGlobal, true),
orderBy: storeInfo.name,
})
return rows.map(toStore)
}
export async function getGlobalStore(id: number): Promise<Store | null> {
const s = await db.query.storeInfo.findFirst({
where: and(eq(storeInfo.id, id), eq(storeInfo.isGlobal, true)),
})
return s ? toStore(s) : null
}
export async function createGlobalStore(input: CreateStoreInput): Promise<Store> {
const [s] = await db
.insert(storeInfo)
.values({
regionId: null,
isGlobal: true,
name: input.name,
description: input.description ?? null,
imageUrl: input.imageUrl ?? null,
})
.returning()
return toStore(s)
}
export async function updateGlobalStore(id: number, input: UpdateStoreInput): Promise<Store> {
const [s] = await db
.update(storeInfo)
.set({ ...input })
.where(and(eq(storeInfo.id, id), eq(storeInfo.isGlobal, true)))
.returning()
if (!s) throw new Error('Global store not found')
return toStore(s)
}
export async function deleteGlobalStore(id: number): Promise<{ message: string }> {
const existing = await db.query.storeInfo.findFirst({
where: and(eq(storeInfo.id, id), eq(storeInfo.isGlobal, true)),
columns: { id: true },
})
if (!existing) throw new Error('Global store not found')
const [{ count }] = await db
.select({ count: sql<number>`count(*)` })
.from(productInfo)
.where(eq(productInfo.storeId, id))
if (Number(count) > 0) {
throw new Error('Cannot delete a global store that still has products. Remove them first.')
}
await db.delete(storeInfo).where(eq(storeInfo.id, id))
return { message: 'Global store deleted successfully' }
}