import {z} from 'zod' export type ScheduledCadenceType = 'monthly' | 'weekly' | 'daily'; export type ScheduleTriggerRequest = {type: 'schedule', cadence: ScheduledCadenceType, start_after?: string | undefined, day_of_month?: number | undefined, day_of_week?: ('monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday') | undefined}; export type CashDepositedTriggerRequest = {type: 'cash_deposited'}; export type TriggerRequest = ScheduleTriggerRequest | CashDepositedTriggerRequest; export type ActionType = 'order.create_and_confirm' | 'invest_with_allocations'; export type WorkflowOrderType = 'batch'; export type Side = 'buy' | 'sell'; export type OrderDataRequest = {type: WorkflowOrderType, side: Side, instrument: string, securities_account?: string | undefined, amount: unknown, fee: unknown, currency: string}; export type InvestmentAllocation = {isin: string, allocation_pct: unknown}; export type InvestWithAllocationsDataRequest = {securities_account?: string | undefined, allocations: Array}; export type ActionDataRequest = {type: ActionType, order?: OrderDataRequest | undefined, invest_with_allocations?: InvestWithAllocationsDataRequest | undefined}; export type CreateCustomerWorkflowRequest = {trigger: TriggerRequest, action: ActionDataRequest}; export type CreateApiAccountsAccountIdWorkflowsArgs = {account_id: string, unified_orders?: boolean | undefined, 'LMG-Data-Privacy-Access-Principal': string, 'LMG-Data-Privacy-Access-Justification': string, body: CreateCustomerWorkflowRequest}; export type CreateApiAccountsAccountIdWorkflowsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const scheduledCadenceType = z.enum(["monthly", "weekly", "daily"]); export const scheduleTriggerResponse = z.object({type: z.literal("schedule"), cadence: scheduledCadenceType, start_after: z.string().optional(), next_run_date: z.string().optional(), day_of_month: z.number().int().gte(1).lte(31).optional(), day_of_week: z.enum(["monday", "tuesday", "wednesday", "thursday", "friday"]).optional()}); export const cashDepositedTriggerResponse = z.object({type: z.literal("cash_deposited")}); export const triggerResponse = z.discriminatedUnion("type", [scheduleTriggerResponse, cashDepositedTriggerResponse]); export const actionType = z.enum(["order.create_and_confirm", "invest_with_allocations"]); export const workflowOrderType = z.literal("batch"); export const side = z.enum(["buy", "sell"]); export const orderDataResponse = z.object({type: workflowOrderType, side: side, instrument: z.string(), securities_account: z.string().optional(), amount: z.string(), fee: z.string(), currency: z.string().min(3).max(3)}); export const investmentAllocation = z.object({isin: z.string(), allocation_pct: z.string()}); export const investWithAllocationsDataResponse = z.object({securities_account: z.string(), allocations: z.array(investmentAllocation)}); export const actionDataResponse = z.object({type: actionType, order: orderDataResponse.optional(), invest_with_allocations: investWithAllocationsDataResponse.optional()}); export const brokerAppsApiEndpointsCustomerWorkflowsRegulatoryDisclosureResponse = z.object({kid: z.string().optional(), estimated_price: z.string(), estimated_quantity: z.string(), estimated_amount: z.string(), service_costs_total: z.string(), service_costs_total_pct: z.string(), entry_costs: z.string(), entry_costs_pct: z.string(), third_party_grants: z.string(), third_party_grants_pct: z.string(), acquisition_costs: z.string(), acquisition_costs_pct: z.string(), custody_costs: z.string(), custody_costs_pct: z.string(), product_costs: z.string(), product_costs_pct: z.string(), running_costs: z.string(), running_costs_pct: z.string(), exit_costs: z.string(), exit_costs_pct: z.string(), impact_first_year: z.string(), impact_first_year_pct: z.string(), impact_subsequent_year: z.string(), impact_subsequent_year_pct: z.string(), impact_final_year: z.string(), impact_final_year_pct: z.string(), recurring_impact_year_1: z.string(), recurring_impact_year_1_pct: z.string(), recurring_impact_year_2: z.string(), recurring_impact_year_2_pct: z.string(), recurring_impact_year_3: z.string(), recurring_impact_year_3_pct: z.string(), recurring_impact_year_4: z.string(), recurring_impact_year_4_pct: z.string(), recurring_impact_year_5: z.string(), recurring_impact_year_5_pct: z.string(), recurring_impact_total: z.string(), recurring_impact_total_pct: z.string()}); export const sCAResponse = z.object({required: z.boolean(), challenge: z.string()}); export const appropriatenessConsentResponse = z.object({required: z.boolean()}); export const customerWorkflowStatus = z.enum(["canceled", "confirmed", "created"]); export const statusChangeCustomerWorkflowStatus = z.object({status: customerWorkflowStatus, timestamp: z.string()}); export const customerWorkflowResponse = z.object({id: z.string(), trigger: triggerResponse, action: actionDataResponse, regulatory_disclosures: brokerAppsApiEndpointsCustomerWorkflowsRegulatoryDisclosureResponse.optional(), sca: sCAResponse.optional(), appropriateness_consent: appropriatenessConsentResponse.optional(), history: z.array(statusChangeCustomerWorkflowStatus)}); 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 }; /** * Create Workflow * * POST /accounts/{account_id}/workflows */ export const createApiAccountsAccountIdWorkflows = async (args: CreateApiAccountsAccountIdWorkflowsArgs, options?: CreateApiAccountsAccountIdWorkflowsOptions) => { const {baseUrl = "https://sandbox.api.lemon.markets/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.unified_orders != null) query.append("unified_orders", String(args.unified_orders)) if (args['LMG-Data-Privacy-Access-Principal'] != null) headers.set("LMG-Data-Privacy-Access-Principal", String(args['LMG-Data-Privacy-Access-Principal'])) if (args['LMG-Data-Privacy-Access-Justification'] != null) headers.set("LMG-Data-Privacy-Access-Justification", String(args['LMG-Data-Privacy-Access-Justification'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/accounts/${encodeURIComponent(String(args.account_id))}/workflows${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(customerWorkflowResponse, await res.json()) };