import {z} from 'zod' export type GetApiStocksArgs = {cif: string, date: string, warehouseName?: string | undefined, productName?: string | undefined, productCode?: string | undefined}; export type GetApiStocksOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const stockResponse = z.object({errorText: z.string().optional(), list: z.array(z.object({warehouse: z.object({warehouseName: z.string().optional(), warehouseType: z.enum(["en gros", "en detail"]).optional()}).optional(), products: z.array(z.object({productName: z.string().optional(), productCode: z.string().optional(), measuringUnit: z.string().optional(), quantity: z.number().optional()})).optional()})).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Listare stocuri * * GET /stocks */ export const getApiStocks = async (args: GetApiStocksArgs, options?: GetApiStocksOptions) => { const {baseUrl = "https://ws.smartbill.ro/SBORO/api", fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.cif != null) query.append("cif", String(args.cif)) if (args.date != null) query.append("date", String(args.date)) if (args.warehouseName != null) query.append("warehouseName", String(args.warehouseName)) if (args.productName != null) query.append("productName", String(args.productName)) if (args.productCode != null) query.append("productCode", String(args.productCode)) if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/stocks${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(stockResponse, await res.json()) };