import { adminSettings } from "$admin-settings/admin-state.svelte"; import { QUERY_KEYS, QUERY_KEYS_ADMIN } from "$lib/config/constants"; import { getOrganizations, getSettings, rawRequest, clearProductMeta, } from "$lib/utils/api"; import type { MagicDescriptionsBulkWpJsonResponse, MagicDescriptionsStatusCheckWpJsonResponse, MagicDescriptionsPreflightWpJsonResponse, MagicDescriptionsPendingReviewsWpJsonResponse, MagicDescriptionProductStatus, } from "$lib/utils/types"; import { createQuery, createMutation } from "@tanstack/svelte-query"; import { toast } from "svelte-sonner"; export function useGetOrganizations() { return createQuery(() => ({ queryKey: [QUERY_KEYS_ADMIN.ORGANIZATIONS], queryFn: async () => await getOrganizations(), enabled: adminSettings.oidc.is_connected || adminSettings.features.oidc, })); } export function useGetSettings() { return createQuery(() => ({ queryKey: [QUERY_KEYS_ADMIN.SETTINGS], queryFn: async () => await getSettings(), })); } /** * Get all products with pending reviews */ export function usePendingMagicDescriptionReviews( enabled = true, poll = false, refetchInterval = 30000, ) { return createQuery(() => ({ queryKey: [QUERY_KEYS.MAGIC_DESCRIPTIONS_PENDING_REVIEWS], queryFn: async () => { return await rawRequest( "productbird/v1/magic-descriptions/pending-reviews", ); }, enabled, staleTime: 0, refetchInterval: poll ? refetchInterval : false, })); } export function useMagicDescriptionProductStatus( productId: number, initialData: MagicDescriptionProductStatus, enabled = true, ) { return createQuery(() => ({ queryKey: [QUERY_KEYS.MAGIC_DESCRIPTIONS_PRODUCT_STATUS, productId], queryFn: async () => { if (initialData) return initialData; return await rawRequest( `productbird/v1/magic-descriptions/product-status/${productId}`, ); }, refetchInterval: (query) => { // Poll every 10 seconds if status is queued or running const status = query.state.data?.status; return status === "queued" || status === "running" ? 10000 : false; }, initialData, staleTime: Number.POSITIVE_INFINITY, gcTime: Number.POSITIVE_INFINITY, enabled, })); } /** * Poll for completed descriptions */ export function usePollMagicDescriptionStatus({ productIds, enabled, shouldPoll = () => false, staleTime = 0, anyQueryKeys = () => [], }: { productIds: number[]; enabled: boolean | (() => boolean); shouldPoll: boolean | (() => boolean); staleTime: number; anyQueryKeys: string[] | (() => string[]); }) { return createQuery(() => ({ queryKey: [ QUERY_KEYS.MAGIC_DESCRIPTIONS_STATUS, productIds, ...(typeof anyQueryKeys === "function" ? anyQueryKeys() : anyQueryKeys), ], queryFn: async () => { if (!productIds.length) return { completed_items: [], remaining_count: 0 }; // Ensure product IDs are properly formatted const formattedIds = productIds.map((id) => String(id)); return await rawRequest( `productbird/v1/magic-descriptions/status?product_ids=${formattedIds.join(",")}`, ); }, refetchInterval: ( typeof shouldPoll === "function" ? shouldPoll() : shouldPoll ) ? 5000 : false, // Poll every 5 seconds when enabled enabled: typeof enabled === "function" ? enabled() : enabled, staleTime, })); } /** * Pre-flight status for selected products before generation starts */ export function usePreflightMagicDescriptions( productIds: number[], enabled = true, ) { return createQuery(() => ({ queryKey: [QUERY_KEYS.MAGIC_DESCRIPTIONS_PREFLIGHT, productIds], queryFn: async () => { if (!productIds.length) return { items: [] }; const formatted = productIds.map((id) => String(id)); return await rawRequest( `productbird/v1/magic-descriptions/preflight?product_ids=${formatted.join(",")}`, ); }, enabled, staleTime: 0, })); } // ################### // #### MUTATIONS #### // ################### /** * Generate magic descriptions in bulk */ export function useGenerateMagicDescriptionsBulk() { return createMutation(() => ({ mutationFn: async ({ productIds, mode, }: { productIds: number[]; mode: "auto-apply" | "review" }) => { return await rawRequest( "productbird/v1/magic-descriptions/bulk", { method: "POST", body: { productIds, mode }, }, ); }, onSuccess: () => { window.__productbird_query_client.invalidateQueries({ queryKey: [QUERY_KEYS.MAGIC_DESCRIPTIONS_STATUS], }); window.__productbird_query_client.invalidateQueries({ queryKey: [QUERY_KEYS.MAGIC_DESCRIPTIONS_PRODUCT_STATUS], }); }, })); } /** * Regenerate a specific product description */ export function useRegenerateProductDescription() { return createMutation(() => ({ mutationFn: async ({ productId, customPrompt, }: { productId: number; customPrompt?: string }) => { return await rawRequest("productbird/v1/regenerate", { method: "PUT", body: { productId, customPrompt }, }); }, })); } /** * Apply a generated description to a product */ export function useApplyProductDescription() { return createMutation(() => ({ mutationFn: async ({ productId, description, }: { productId: number; description: string }) => { return await rawRequest<{ product_id: number }>( "productbird/v1/magic-descriptions/apply", { method: "POST", body: { productId, description }, }, ); }, onSuccess: ({ product_id }) => { window.__productbird_query_client.invalidateQueries({ queryKey: [QUERY_KEYS.MAGIC_DESCRIPTIONS_PRODUCT_STATUS, product_id], }); }, })); } /** * Decline a generated description for a product */ export function useDeclineProductDescription() { return createMutation(() => ({ mutationFn: async ({ productId }: { productId: number }) => { return await rawRequest("productbird/v1/magic-descriptions/decline", { method: "POST", body: { productId }, }); }, })); } /** * Undo decline for a generated description */ export function useUndoDeclineProductDescription() { return createMutation(() => ({ mutationFn: async ({ productId }: { productId: number }) => { return await rawRequest( "productbird/v1/magic-descriptions/undo-decline", { method: "POST", body: { productId }, }, ); }, })); } /** * Clear all Productbird post meta */ export function useClearProductMeta() { return createMutation(() => ({ mutationFn: async () => { return await clearProductMeta(); }, onSuccess: (data) => { toast.success(`${data.cleared} meta fields cleared`); }, })); } /** * Clear all products with queued status */ export function useClearQueuedProducts() { return createMutation(() => ({ mutationFn: async () => { const response = await rawRequest<{ success: boolean; cleared: number; product_count: number; message: string; }>("productbird/v1/clear-queued-products", { method: "POST", }); return response; }, onSuccess: (data) => { toast.success(data.message); }, })); }