import {z} from 'zod' export type ApiKpiMetricDateRange = 'LastThirtyVsPrevious' | 'TodayVsYesterday' | 'YesterdayVsPrevious' | 'ThisWeekVsLast' | 'LastWeekVsPrevious' | 'ThisMonthVsLast' | 'LastMonthVsPrevious' | 'ThisYearVsLast' | 'LastYearVsPrevious' | 'AllTime' | 'NotAvailableInThisVersion'; export type GetApiV2EcommerceSummariesArgs = {dateRange?: ApiKpiMetricDateRange | undefined}; export type GetApiV2EcommerceSummariesOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const kpiMetricType = z.enum(["TotalRevenue", "AverageOrderValue", "CustomerLifetimeValue", "TotalOrders", "AverageItemsPerOrder", "AverageDaysToSecondOrder", "Customers", "SinglePurchaseCustomers", "RepeatCustomers", "TotalDelay", "TotalRepeatOrders", "TotalItems"]); export const kpiMetricValue = z.object({initialTotalValue: z.number().optional(), comparisonTotalValue: z.number().optional()}); export const ecommercePredefinedDateRanges = z.enum(["LastThirtyVsPrevious", "TodayVsYesterday", "YesterdayVsPrevious", "ThisWeekVsLast", "LastWeekVsPrevious", "ThisMonthVsLast", "LastMonthVsPrevious", "ThisYearVsLast", "LastYearVsPrevious", "AllTime", "Custom"]); export const kpiMetricSummary = z.object({metricType: kpiMetricType.optional(), metricValues: kpiMetricValue.nullable().optional(), dateRange: ecommercePredefinedDateRanges.optional()}); export const reportSummaryOfKpiMetricSummary = z.object({records: z.array(kpiMetricSummary).nullable().optional(), dateRange: ecommercePredefinedDateRanges.nullable().optional(), asOfDate: z.string().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 }; /** * Returns the Retail KPI summaries for the specified date range. * * GET /v2/ecommerce/summaries */ export const getApiV2EcommerceSummaries = async (args: GetApiV2EcommerceSummariesArgs, options?: GetApiV2EcommerceSummariesOptions) => { const {baseUrl = "https://api.dotdigital.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.dateRange != null) query.append("dateRange", String(args.dateRange)) const url = `${baseUrl.replace(/\/+$/, '')}/v2/ecommerce/summaries${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(reportSummaryOfKpiMetricSummary, await res.json()) };