dstpabuaran.com/resources/js/lib/product-draft.ts

74 lines
1.7 KiB
TypeScript

const DRAFT_PREFIX = 'product-draft';
export type ProductDraftData = {
productName: string;
status: string;
description: string;
categoryIds: number[];
useSamePrice: boolean;
sharedPrices: Array<{ type: string; price: number }>;
variants: Array<{
id?: number | null;
name: string;
stock: number;
reject_stock: number;
retail_stock: number;
photo: string | null;
prices: Array<{ type: string; price: number }>;
}>;
};
function getKey(
type: 'create' | 'edit',
userId?: number,
productId?: number,
): string {
if (type === 'edit' && productId) {
return `${DRAFT_PREFIX}-edit-${userId ?? 'anon'}-${productId}`;
}
return `${DRAFT_PREFIX}-create-${userId ?? 'anon'}`;
}
export function saveProductDraft(
type: 'create' | 'edit',
data: ProductDraftData,
userId?: number,
productId?: number,
): boolean {
try {
const key = getKey(type, userId, productId);
localStorage.setItem(key, JSON.stringify(data));
return true;
} catch {
return false;
}
}
export function loadProductDraft(
type: 'create' | 'edit',
userId?: number,
productId?: number,
): ProductDraftData | null {
try {
const key = getKey(type, userId, productId);
const raw = localStorage.getItem(key);
if (!raw) return null;
return JSON.parse(raw) as ProductDraftData;
} catch {
return null;
}
}
export function clearProductDraft(
type: 'create' | 'edit',
userId?: number,
productId?: number,
): void {
try {
const key = getKey(type, userId, productId);
localStorage.removeItem(key);
} catch {
// ignore
}
}