UNPKG

@retaila/shared-types

Version:

Tipos compartidos para el proyecto Retail

1,777 lines (1,729 loc) 123 kB
interface BaseEntity { id: string; createdAt: Date; updatedAt: Date; deletedAt?: Date; } interface BaseEntityWithAccount extends BaseEntity { accountId: string; } interface BaseEntityWithUser extends BaseEntity { userId: string; } interface BaseEntityWithAccountAndUser extends BaseEntityWithAccount { userId: string; } interface Address { country: string; department: string; locality: string; street: string; number: string; mapPosition: MapPosition; } interface MapPosition { lat: number; lng: number; } declare const SUPPORTED_COUNTRIES: readonly ["UY", "AR"]; type SupportedCountryCode = (typeof SUPPORTED_COUNTRIES)[number]; declare function isSupportedCountry(code: string): code is SupportedCountryCode; interface CountryDefaultBranchAddress { country: string; department: string; locality: string; street: string; number: string; mapPosition: { lat: number; lng: number; }; } interface CountryDefaultTax { name: string; rate: number; rateType: string; } interface CountryDefaultConfig { /** Display name for the country (e.g. for select options). */ name: string; timezone: string; currency: string; phoneCountryCode: string; locale: string; defaultBranchAddress: CountryDefaultBranchAddress; defaultTaxes: CountryDefaultTax[]; } /** Default configurations for enabled countries. Only countries with defaults are listed. */ declare const COUNTRY_DEFAULTS: Record<string, CountryDefaultConfig>; declare function getCountryDefaults(code: string): CountryDefaultConfig | null; /** * Entidad Media * Se utiliza para almacenar y gestionar archivos y recursos multimedia. */ interface Media { id: string; accountId: string; filename: string; url: string; thumbnailUrl: string; mimeType: string; extension: string; size: number; type: MediaType; altText: string; createdAt: Date; updatedAt: Date; deletedAt?: Date | null; } declare enum MediaType { IMAGE = "IMAGE", VIDEO = "VIDEO", FAVICON = "FAVICON", DOCUMENT = "DOCUMENT", AUDIO = "AUDIO", ARCHIVE = "ARCHIVE", OTHER = "OTHER" } interface Phone { countryCode: string; national: string; international: string; type: 'mobile' | 'landline'; validated: boolean; } declare enum Currency { ARS = "ARS",// Peso argentino BRL = "BRL",// Real brasileño CLP = "CLP",// Peso chileno COP = "COP",// Peso colombiano EUR = "EUR",// Euro MXN = "MXN",// Peso mexicano PEN = "PEN",// Sol peruano PYG = "PYG",// Guaraní paraguayo USD = "USD",// Dólar estadounidense UYU = "UYU" } declare function getCurrencySymbol(currencyCode: Currency): string; /** * Analiza un patrón de formato de precio y extrae la configuración necesaria * @param pattern - Patrón de ejemplo como '1,000.12', '1.000,12', '1000.12', '1000' * @returns Configuración de formato de precio para Intl.NumberFormat * * Patrones soportados: * - '1.000,12' → es-ES (punto para miles, coma para decimales) * - '1,000.12' → en-US (coma para miles, punto para decimales) * - '1000,12' → sin separador de miles, coma para decimales * - '1000.12' → sin separador de miles, punto para decimales * - '1.000' → punto para miles, sin decimales * - '1,000' → coma para miles, sin decimales * - '1000' → sin separadores, sin decimales */ declare function parsePriceFormatPattern(pattern: string): { locale: string; useGrouping: boolean; minimumFractionDigits: number; maximumFractionDigits: number; }; type Webhook = { body: Record<string, unknown>; headers: Record<string, string>; }; declare enum DayOfWeek { MONDAY = "MONDAY", TUESDAY = "TUESDAY", WEDNESDAY = "WEDNESDAY", THURSDAY = "THURSDAY", FRIDAY = "FRIDAY", SATURDAY = "SATURDAY", SUNDAY = "SUNDAY" } /** * Entidad AccountDomain * Representa un dominio personalizado asociado a una cuenta. * Permite dominios completos y subdominios, con control de estado y verificación. */ interface AccountDomain { id: string; accountId: string; domain: string; /** Dominio completo (ej: example.com) */ subdomain?: string; /** Subdominio opcional (ej: shop, blog) */ isPrimary: boolean; /** Indica si este es el dominio principal de la cuenta */ preferWww: boolean; /** Preferencia de dominio: true = www.example.com, false = example.com */ status: AccountDomainStatus; /** Estado del dominio: PENDING, ACTIVE, INACTIVE */ verifiedAt?: Date; /** Fecha de verificación del dominio */ createdAt: Date; updatedAt: Date; deletedAt?: Date | null; } declare enum AccountDomainStatus { PENDING = "PENDING", ACTIVE = "ACTIVE", INACTIVE = "INACTIVE" } /** Balance for a calendar month (1-31). */ interface SellerPeriodBalance { year: number; month: number; balance: number; } interface Seller { id: string; name: string; commissionPercent: number; createdAt: Date; updatedAt: Date; deletedAt?: Date; /** Balance by calendar month (1-31). Present when requested from API. */ balanceByPeriod?: SellerPeriodBalance[]; } interface ChargeSellerAllocation { id: string; accountServiceBillingChargeId: string; sellerId: string; amount: number; commissionPercentUsed: number; createdAt: Date; } /** Billing data for Retaila service invoices (tenant / legal entity). Stored as JSON on `account.billingProfile`. */ interface AccountBillingProfile { legalName?: string | null; /** Tax id (e.g. RUT in UY/PY). */ taxId?: string | null; address?: string | null; billingContactEmail?: string | null; /** * Whether VAT (IVA) is charged/invoiced on top of service amounts. * Service plan amounts in the system are always stored net (sin IVA); this flag is for documents and UI. */ invoiceVat?: boolean | null; /** VAT rate when `invoiceVat` is true (e.g. 22 for Uruguay). Percent 0–100. */ vatPercent?: number | null; } interface Account { id: string; name: string; slug: string; logoId?: string; currency: string; email: string; timezone: string; status: AccountStatus; country: string; themeConfig?: ThemeConfig; privateKey?: string; demo: boolean; createdAt: Date; updatedAt: Date; deletedAt?: Date; sellerId?: string; seller?: Seller; accountDomains?: AccountDomain[]; billingProfile?: AccountBillingProfile | null; /** Set when the backoffice onboarding wizard was finished successfully. */ onboardingWizardCompletedAt?: Date | null; /** Set when the merchant chose to skip the onboarding wizard. */ onboardingWizardSkippedAt?: Date | null; /** True until the wizard is completed or skipped (backoffice gate). */ needsOnboardingWizard?: boolean; } declare enum AccountStatus { ACTIVE = "ACTIVE", INACTIVE = "INACTIVE", PENDING = "PENDING", SUSPENDED = "SUSPENDED" } interface ThemeConfig { backgroundColor: string; textColor: string; primaryColor: string; secondaryColor: string; } /** Job lifecycle persisted in `account_onboarding_job`. */ type AccountOnboardingJobStatus = 'queued' | 'running' | 'completed' | 'failed'; /** Row shape for `account_onboarding_job` (phases/result/requestBody are JSON in MySQL). */ interface AccountOnboardingJob { id: string; accountId: string; status: AccountOnboardingJobStatus; phases: unknown[]; percent: number; result: unknown | null; error?: string | null; requestBody: Record<string, unknown>; createdAt: Date; updatedAt: Date; } declare enum AiCreditType { IMAGE = "IMAGE", TEXT = "TEXT" } declare enum AiCreditSource { FREE = "FREE", PAID = "PAID" } declare enum AiCreditTransactionReason { GENERATION = "generation", MONTHLY_REFILL = "monthly_refill", PURCHASE = "purchase", MANUAL_ADJUSTMENT = "manual_adjustment" } interface AccountAiCredits { accountId: string; monthlyFreeImageCredits: number; paidImageCredits: number; monthlyFreeTextCredits: number; paidTextCredits: number; lastMonthlyRefill: Date | null; updatedAt: Date; } interface AccountAiCreditTransaction { id: string; accountId: string; type: AiCreditType; amount: number; source: AiCreditSource; reason: AiCreditTransactionReason; createdAt: Date; } interface AiCreditsBalance { imageCredits: number; textCredits: number; } interface AccountIntegrationConfigDTO { accountId: string; integrationId: string; settingsProduction?: Record<string, any>; settingsDevelopment?: Record<string, any>; environment: AccountIntegrationEnvironment; status?: AccountIntegrationStatus; } /** * Entidad Integration * Define las integraciones de terceros disponibles en la plataforma (ej. pasarelas de pago, transportistas). * Almacena información sobre el proveedor, categoría y esquema de parámetros requeridos. */ declare enum IntegrationCategory { PAYMENT_GATEWAY = "PAYMENT_GATEWAY", SHIPPING_CARRIER = "SHIPPING_CARRIER", MARKETPLACE = "MARKETPLACE", EMAIL_MARKETING = "EMAIL_MARKETING", ANALYTICS = "ANALYTICS", ACCOUNTING = "ACCOUNTING", SOCIAL_MEDIA = "SOCIAL_MEDIA", OTHER = "OTHER" } declare enum IntegrationStatus { ACTIVE = "ACTIVE", INACTIVE = "INACTIVE", BETA = "BETA", DEPRECATED = "DEPRECATED" } interface Integration { id: string; category: IntegrationCategory; providerKey: string; name: string; slug: string; description?: string; setupInstructions?: string; logoUrl?: string; requiredParamsSchema?: any; supportedPaymentMethods?: string[]; paymentCanRecapture?: boolean; paymentCanRefund?: boolean; status: IntegrationStatus; createdAt: Date; updatedAt: Date; deletedAt?: Date | null; order: number; /** ISO country codes where this integration is available. Null or empty = all countries. */ countries?: string[] | null; accountIntegration: AccountIntegration | null; } declare function getIntegrationCategoryName(category: IntegrationCategory): string; /** * Entidad AccountIntegration * Contiene información de la integración y sus credenciales. */ declare enum AccountIntegrationStatus { ACTIVE = "ACTIVE", INACTIVE = "INACTIVE", BETA = "BETA", DEPRECATED = "DEPRECATED" } declare enum AccountIntegrationConnectionStatus { CONNECTED = "CONNECTED", DISCONNECTED = "DISCONNECTED", ERROR = "ERROR", WARNING = "WARNING" } declare enum AccountIntegrationEnvironment { PRODUCTION = "PRODUCTION", DEVELOPMENT = "DEVELOPMENT" } interface AccountIntegration { id: string; accountId: string; integrationId: string; settingsProduction: Object | null; settingsDevelopment: Object | null; environment: AccountIntegrationEnvironment; productionStatus: AccountIntegrationConnectionStatus; developmentStatus: AccountIntegrationConnectionStatus; status: AccountIntegrationStatus; demo: boolean; createdAt: Date; updatedAt: Date; deletedAt?: Date | null; integration: Integration; settings: Record<string, any>; } /** * GeoZone types * Define zonas geográficas reutilizables que pueden ser referenciadas por otras entidades. */ interface GeoZone { id: string; name: string; description?: string; accountId?: string | null; area: MapPosition[]; createdAt: Date; updatedAt: Date; deletedAt?: Date | null; } declare enum GeoZoneStatus { ACTIVE = "ACTIVE", INACTIVE = "INACTIVE" } /** * Delivery types to distinguish between shipping and pickup options */ declare enum DeliveryType { SHIPPING = "SHIPPING", PICKUP = "PICKUP" } /** * Entidad AccountDeliveryOption * Representa una opción de envío de una cuenta. */ interface AccountDeliveryOption { id: string; accountId: string; accountBranchId: string; name: string; accountIntegrationId?: string; isScheduled: boolean; priceLogic: AccountDeliveryOptionPriceLogic; status: AccountDeliveryOptionStatus; deliveryType: DeliveryType; demo: boolean; hideAccountBranchAddress: boolean; /** When true, estimated delivery times are calculated by AI and shown to customers at checkout */ showEstimatedDeliveryTime: boolean; createdAt: Date; updatedAt: Date; deletedAt?: Date | null; data?: Record<string, unknown>; deliveryZones: AccountDeliveryOptionZone[]; integration?: AccountIntegration | null; price?: number | null; accountBranch?: AccountBranch | null; /** Computed by api-public when listing delivery options; ISO date strings */ estimatedDelivery?: { start: string; end: string; }; } declare enum AccountDeliveryOptionPriceLogic { FIXED = "FIXED", BY_ZONE = "BY_ZONE", PROVIDER = "PROVIDER", /** @deprecated Use BY_ZONE instead */ CALCULATED = "CALCULATED" } declare enum AccountDeliveryOptionStatus { ACTIVE = "ACTIVE", INACTIVE = "INACTIVE" } interface AccountDeliveryOptionCalculatedCost { basePrice: number; distanceKm: number; finalPrice: number; priceLogic: AccountDeliveryOptionPriceLogic; currency: string; } interface AccountDeliveryOptionZone { id: string; accountId: string; accountDeliveryOptionId: string; geoZoneId: string; price?: number | null; status: AccountDeliveryOptionZoneStatus; demo: boolean; createdAt: Date; updatedAt: Date; deletedAt?: Date | null; geoZone?: GeoZone; } declare enum AccountDeliveryOptionZoneStatus { ACTIVE = "ACTIVE", INACTIVE = "INACTIVE" } interface DeliveryZoneInput { geoZoneId?: string; geoZone?: GeoZoneInput; price?: number | null; } interface GeoZoneInput { name: string; area: MapPosition[]; description?: string; } interface CreateAccountDeliveryOptionDTO { accountId: string; accountBranchId: string; name: string; accountIntegrationId?: string | null; isScheduled?: boolean; priceLogic?: AccountDeliveryOptionPriceLogic; price?: number; status?: AccountDeliveryOptionStatus; deliveryType: DeliveryType; deliveryZones?: DeliveryZoneInput[]; data?: Record<string, unknown>; showEstimatedDeliveryTime?: boolean; } interface UpdateAccountDeliveryOptionDTO { accountBranchId: string; name?: string; accountIntegrationId?: string | null; isScheduled?: boolean; priceLogic?: AccountDeliveryOptionPriceLogic; status?: AccountDeliveryOptionStatus; deliveryType?: DeliveryType; deliveryZones?: DeliveryZoneInput[]; data?: Record<string, unknown>; showEstimatedDeliveryTime?: boolean; } /** Rule types for estimated delivery calculation */ declare enum DeliveryOptionRuleType { PROCESSING_DAYS = "PROCESSING_DAYS", SAME_DAY_CUTOFF = "SAME_DAY_CUTOFF", DELIVERY_DAYS = "DELIVERY_DAYS", PICKUP_READY_HOURS = "PICKUP_READY_HOURS", FIXED_OFFSET_DAYS = "FIXED_OFFSET_DAYS", /** ISO weekday numbers (1=Mon..7=Sun) that count as operating days */ BUSINESS_DAYS = "BUSINESS_DAYS", /** Delivery time-of-day window inferred by AI from historical orders */ DELIVERY_HOURS = "DELIVERY_HOURS", /** Extra days added to the pessimistic end when volume is high */ BUFFER_SAFETY_MARGIN = "BUFFER_SAFETY_MARGIN" } interface AccountDeliveryOptionRule { id: string; accountId: string; accountDeliveryOptionId: string; ruleType: DeliveryOptionRuleType; params?: Record<string, unknown>; priority: number; createdAt: Date; updatedAt: Date; deletedAt?: Date | null; } interface CreateDeliveryOptionRuleDTO { ruleType: DeliveryOptionRuleType; params?: Record<string, unknown>; priority?: number; } interface UpdateDeliveryOptionRuleDTO { ruleType?: DeliveryOptionRuleType; params?: Record<string, unknown>; priority?: number; } /** Params per rule type for estimation */ interface ProcessingDaysParams { minDays: number; maxDays?: number; } interface SameDayCutoffParams { cutoffTime: string; } interface DeliveryDaysParams { minDays: number; maxDays: number; } interface PickupReadyHoursParams { hours?: number; minHours?: number; maxHours?: number; } interface FixedOffsetDaysParams { minDays: number; maxDays?: number; } interface BusinessDaysParams { /** ISO weekday numbers: 1=Monday … 7=Sunday */ days: number[]; } interface DeliveryHoursParams { /** Start of delivery window "HH:mm" */ start: string; /** End of delivery window "HH:mm" */ end: string; } interface BufferSafetyMarginParams { /** Extra days added to the pessimistic (end) delivery date */ extraDays: number; } /** Unified delivery config shape used by the backoffice form */ interface UnifiedDeliveryConfig { businessDays: number[]; cutoffEnabled: boolean; cutoffTime: string; processingMinDays: number; processingMaxDays: number; deliveryMinDays: number; deliveryMaxDays: number; pickupHours: number; } /** * Entidad AccountBranch * Representa una sucursal de una cuenta. */ interface AccountBranch { id: string; accountId: string; name: string; address?: Address; addressInstructions?: string; isAddressPublic?: boolean; phone?: Phone | null; email?: string | null; demo: boolean; status: AccountBranchStatus; isOpen?: boolean; createdAt: Date; updatedAt: Date; deletedAt?: Date | null; schedule: AccountBranchSchedule[]; deliveryOptions: AccountDeliveryOption[]; } declare enum AccountBranchStatus { ACTIVE = "ACTIVE", INACTIVE = "INACTIVE" } interface AccountBranchSchedule { id: string; accountBranchId: string; day: AccountBranchScheduleDay; start: number; end: number; status: AccountBranchScheduleStatus; demo: boolean; createdAt: Date; updatedAt: Date; deletedAt?: Date | null; } declare enum AccountBranchScheduleStatus { ACTIVE = "ACTIVE", INACTIVE = "INACTIVE" } declare enum AccountBranchScheduleDay { MONDAY = "MONDAY", TUESDAY = "TUESDAY", WEDNESDAY = "WEDNESDAY", THURSDAY = "THURSDAY", FRIDAY = "FRIDAY", SATURDAY = "SATURDAY", SUNDAY = "SUNDAY" } declare enum AccountEmailDomainStatus { PENDING = "PENDING", DNS_PENDING = "DNS_PENDING", ACTIVE = "ACTIVE", INACTIVE = "INACTIVE" } interface AccountEmailDomain { id: string; accountId: string; accountDomainId: string; domain: string; status: AccountEmailDomainStatus; activatedAt: Date | null; createdAt: Date; updatedAt: Date; deletedAt: Date | null; } interface AccountMailbox { id: string; accountId: string; accountEmailDomainId: string; localPart: string; email: string; displayName: string; mayReceive: boolean; maySend: boolean; /** Storage limit in megabytes. Default 500. */ storageLimitMb: number; createdAt: Date; updatedAt: Date; deletedAt: Date | null; } interface StatusInfo { text: string; class: string; actionText?: string; } interface AccountExchangeRate extends BaseEntityWithAccount { id: string; accountId: string; baseCurrency: Currency; targetCurrency: Currency; configurationType: AccountExchangeRateType; manualRate?: number; adjustmentPercentage?: number; roundingConfig?: RoundingConfig; isActive: boolean; lastManualUpdate?: Date; metadata?: AccountExchangeRateMetadata; createdAt: Date; updatedAt: Date; deletedAt?: Date; } declare enum AccountExchangeRateType { AUTOMATIC = "AUTOMATIC", AUTOMATIC_WITH_ADJUSTMENT = "AUTOMATIC_WITH_ADJUSTMENT", MANUAL = "MANUAL" } interface RoundingConfig { method: RoundingMethod; decimalPlaces: number; roundingRule?: RoundingRule; } declare enum RoundingMethod { ROUND = "ROUND", CEIL = "CEIL", FLOOR = "FLOOR", BANKERS = "BANKERS" } declare enum RoundingRule { ROUND_TO_5_CENTS = "ROUND_TO_5_CENTS", ROUND_TO_10_CENTS = "ROUND_TO_10_CENTS", NONE = "NONE" } interface AccountExchangeRateMetadata { description?: string; notes?: string; [key: string]: any; } interface CreateAccountExchangeRateDto { baseCurrency: Currency; targetCurrency: Currency; configurationType: AccountExchangeRateType; manualRate?: number; adjustmentPercentage?: number; roundingConfig?: RoundingConfig; metadata?: AccountExchangeRateMetadata; } interface UpdateAccountExchangeRateDto { configurationType?: AccountExchangeRateType; manualRate?: number; adjustmentPercentage?: number; roundingConfig?: RoundingConfig; isActive?: boolean; metadata?: AccountExchangeRateMetadata; } interface AccountExchangeRateQueryDto { baseCurrency?: Currency; targetCurrency?: Currency; configurationType?: AccountExchangeRateType; isActive?: boolean; limit?: number; offset?: number; } interface AccountExchangeRateResponse { item: AccountExchangeRate; } interface UpdateAccountExchangeRateAllDto { globalConfig?: any; rates: Array<{ id?: string; targetCurrency: Currency; configurationType: AccountExchangeRateType; manualRate?: number; adjustmentPercentage?: number; roundingConfig?: RoundingConfig; }>; } interface AccountExchangeRateListResponse { storeCurrency: Currency; paymentCurrencies: Currency[]; rates: AccountExchangeRateWithEffectiveRate[]; } interface AccountExchangeRateWithEffectiveRate extends AccountExchangeRate { effectiveRate: number; baseGlobalRate: number; source: string; effectiveDate: Date; } interface AccountCurrencyConfig { accountId: string; primaryCurrency: Currency; exchangeRates: AccountExchangeRate[]; effectiveRates: EffectiveExchangeRate[]; } interface EffectiveExchangeRate { baseCurrency: Currency; targetCurrency: Currency; effectiveRate: number; baseGlobalRate: number; configurationType: AccountExchangeRateType; effectiveDate: Date; source: string; } declare enum AccountPaymentMethodStatus { ACTIVE = "ACTIVE",// Active INACTIVE = "INACTIVE" } interface AccountPaymentMethod { id: string; accountId: string; accountIntegrationId?: string; name: string; description?: string; customerInstructions?: string; order: number; availableForWeb?: boolean; status: AccountPaymentMethodStatus; demo: boolean; createdAt: Date; updatedAt: Date; deletedAt?: Date; accountIntegration?: AccountIntegration; account?: Account; statusInfo?: StatusInfo; typeName?: string; /** Currency the gateway will charge in (API-resolved; do not infer from provider in UI). */ chargeCurrency?: Currency; /** Present when account store currency differs from chargeCurrency and a rate exists. */ exchangeRate?: EffectiveExchangeRate; } declare function getAccountPaymentMethodStatusInfo(status: AccountPaymentMethodStatus): StatusInfo; /** * Currency in which the payment gateway will settle the charge for checkout. * Centralizes provider-specific rules; consumers (e.g. storefront) should use * {@link AccountPaymentMethod.chargeCurrency} from the API instead of branching on providerKey. */ declare function resolveChargeCurrency(params: { providerKey?: string | null; settingsCurrency?: string | null; /** Store / account currency; used when settings omit currency or for MANUAL_PAYMENT. */ accountCurrency?: string | null; }): Currency | undefined; /** * Entidad Customer * Cliente de la tienda */ interface Customer { id: string; accountId: string; firstName?: string; lastName?: string; email: string; phone?: Phone; newsletter: boolean; status: CustomerStatus; createdAt: Date; updatedAt: Date; deletedAt?: Date | null; } declare enum CustomerStatus { ACTIVE = "ACTIVE", INACTIVE = "INACTIVE", BLACKLISTED = "BLACKLISTED",// e.g., for fraudulent activity PENDING = "PENDING" } /** * Register or update a customer */ interface CustomerUpsertDto { id?: string; accountId: string; firstName?: string; lastName?: string; email: string; newsletter?: boolean; phone?: Phone; } /** * Size guides: reusable measurement tables and optional "how to measure" content. * Used by admin API, storefront payload (ProductSizeGuidePayload), and DB alignment. */ declare enum SizeGuideStatus { DRAFT = "DRAFT", PUBLIC = "PUBLIC" } declare enum SizeGuideUnitBase { CM = "cm", IN = "in" } declare enum SizeGuideUnitDisplayPolicy { AUTO = "AUTO", FIXED = "FIXED" } interface SizeGuideTableColumn { id: string; label: string; order: number; } interface SizeGuideTableRow { id: string; /** Maps column id -> cell display value (may include ranges or *literal* markers). */ cells: Record<string, string>; order: number; } interface SizeGuideTableJson { columns: SizeGuideTableColumn[]; rows: SizeGuideTableRow[]; } interface SizeGuide { id: string; accountId: string; name: string; status: SizeGuideStatus; tableJson: SizeGuideTableJson; infoTitle?: string | null; infoBody?: string | null; infoMediaId?: string | null; unitBase: SizeGuideUnitBase; unitDisplayPolicy?: SizeGuideUnitDisplayPolicy | null; createdAt: Date; updatedAt: Date; deletedAt?: Date | null; } /** Row in size_guide_category (category-scoped rule with priority). */ interface SizeGuideCategoryRule { sizeGuideId: string; categoryId: string; priority: number; } /** Assignment returned by admin API (without repeating sizeGuideId on each row). */ interface SizeGuideCategoryAssignment { categoryId: string; priority: number; } type SizeGuideDetail = SizeGuide & { categoryRules?: SizeGuideCategoryAssignment[]; }; interface CreateSizeGuideDTO { accountId: string; name: string; status?: SizeGuideStatus; tableJson: SizeGuideTableJson; infoTitle?: string | null; infoBody?: string | null; infoMediaId?: string | null; unitBase?: SizeGuideUnitBase; unitDisplayPolicy?: SizeGuideUnitDisplayPolicy | null; } interface UpdateSizeGuideDTO { name?: string; status?: SizeGuideStatus; tableJson?: SizeGuideTableJson; infoTitle?: string | null; infoBody?: string | null; infoMediaId?: string | null; unitBase?: SizeGuideUnitBase; unitDisplayPolicy?: SizeGuideUnitDisplayPolicy | null; } interface SizeGuideCategoryRuleInput { categoryId: string; priority: number; } /** Resolved size guide on product detail (api-public / storefront). */ interface ProductSizeGuidePayload { id: string; name: string; table: SizeGuideTableJson; unitBase: SizeGuideUnitBase; unitDisplayPolicy?: SizeGuideUnitDisplayPolicy | null; infoTitle?: string | null; infoBody?: string | null; infoImageUrl?: string | null; } /** * Entidad StandardCategory * Define las categorías estándar de productos. * Estas categorías estan pensadas para unificar o agrupar productos de diferentes cuentas. */ interface StandardCategory { id: string; parentId?: string; name: string; slug: string; description?: string; imageId?: string | null; order: number; status: StandardCategoryStatus; metadata?: { icon?: string; displayInMenu?: boolean; seoTitle?: string; seoDescription?: string; attributes?: string[]; }; createdAt: Date; updatedAt: Date; deletedAt?: Date | null; children: StandardCategory[]; parent: StandardCategory | null; } declare enum StandardCategoryStatus { ACTIVE = "ACTIVE", INACTIVE = "INACTIVE" } /** * Entidad ProductCategory * Define las categorías de productos. * Soporta una estructura jerárquica (categorías y subcategorías) mediante el campo parentId. * Cada categoría debe estar asociada a una categoría estándar del sistema. */ interface ProductCategory { id: string; accountId: string; parentId?: string; standardCategoryId: string | null; name: string; slug: string; description?: string; imageId?: string | null; order: number; isFeatured: boolean; status: ProductCategoryStatus; createdAt: Date; updatedAt: Date; deletedAt?: Date | null; children: ProductCategory[]; parent: ProductCategory | null; standardCategory: StandardCategory; } declare enum ProductCategoryStatus { ACTIVE = "ACTIVE", INACTIVE = "INACTIVE" } /** * Entidad Product * Representa un producto vendible en la tienda. Es la entidad base que puede tener múltiples variantes. */ interface Product { id: string; accountId: string; code: string; brandId?: string | null; supplierId?: string | null; /** When set, storefront uses this size guide instead of category rules. */ sizeGuideId?: string | null; productType: ProductType; sku?: string | null; barcode?: string | null; name: string; slug: string; description?: string | null; isFeatured: boolean; allowBackorder: boolean; weight?: number | null; weightUnit?: string | null; height?: number | null; width?: number | null; depth?: number | null; dimensionUnit?: string | null; shippingLeadTime?: string | null; status: ProductStatus; statusInfo?: StatusInfo; createdAt: Date; updatedAt: Date; deletedAt?: Date | null; media?: Media[]; variants?: ProductVariant[]; categories?: ProductCategory[]; /** Present on storefront product detail after server-side resolution. */ sizeGuide?: ProductSizeGuidePayload | null; } declare enum ProductStatus { ACTIVE = "ACTIVE",// Available for sale INACTIVE = "INACTIVE",// Not visible/purchasable ARCHIVED = "ARCHIVED",// Not visible, kept for records DRAFT = "DRAFT" } declare enum ProductType { SIMPLE = "SIMPLE",// Product without variants (may have a default hidden variant) VARIABLE = "VARIABLE",// Product with distinct variants (color, size, etc.) BUNDLE = "BUNDLE",// A package of other products/variants GIFT_CARD = "GIFT_CARD" } interface ProductVariant { id: string; accountId: string; productId: string; sku?: string | null; barcode?: string | null; currency: string; price: number; compareAtPrice?: number; allowBackorder?: boolean; stock: number; status: ProductVariantStatus; weight?: number | null; weightUnit?: string | null; height?: number | null; width?: number | null; depth?: number | null; dimensionUnit?: string | null; shippingLeadTime?: string | null; order: number; createdAt: Date; updatedAt: Date; deletedAt?: Date; } declare enum ProductVariantStatus { ACTIVE = "ACTIVE", OUT_OF_STOCK = "OUT_OF_STOCK", COMING_SOON = "COMING_SOON" } declare function getProductStatusInfo(status: ProductStatus): StatusInfo; type FulfillmentItem = { id: string; fulfillmentId: string; quantity: number; }; type CreateFulfillmentItemDto = { quantity: number; orderItemId: string; }; /** * FulfillmentLabel Entity * Represents shipping labels and tracking information returned by fulfillment providers */ interface FulfillmentLabel { id: string; fulfillmentId: string; trackingNumber: string; trackingUrl?: string; labelUrl?: string; accountId: string; createdAt: Date; updatedAt: Date; deletedAt?: Date; } interface FulfillmentLabelCreateData { fulfillmentId: string; trackingNumber: string; trackingUrl?: string; labelUrl?: string; } interface FulfillmentLabelUpdateData { trackingNumber?: string; trackingUrl?: string; labelUrl?: string; } declare enum PaymentStatus { PENDING = "PENDING",// Pendiente PREAUTHORIZED = "PREAUTHORIZED", APPROVED = "APPROVED",// Pago aprobado online PAID = "PAID",// Pago realizado por redes fisicas REJECTED = "REJECTED",// Pago rechazado REFUND_IN_PROCESS = "REFUND_IN_PROCESS",// En proceso de reembolso con la plataforma de pagos PARTIAL_REFUND = "PARTIAL_REFUND",// Pago parcialmente reembolsado REFUNDED = "REFUNDED",// Pago reembolsado ERROR = "ERROR" } declare enum PaymentMethodType { BANK_TRANSFER = "BANK_TRANSFER", CREDIT_CARD = "CREDIT_CARD", DEBIT_CARD = "DEBIT_CARD", MERCADOPAGO = "MERCADOPAGO", MERCADOPAGO_MARKETPLACE = "MERCADOPAGO_MARKETPLACE", PHYSICAL = "PHYSICAL", INTERNATIONAL = "INTERNATIONAL", PAYPAL = "PAYPAL", AKUA = "AKUA", CASH = "CASH", OTHER = "OTHER" } interface PaymentConversion { fromCurrency: Currency; toCurrency: Currency; rate: number; originalAmount: number; finalAmount: number; } interface Payment { id: string; accountId: string; orderId: string; invoiceId?: string; accountPaymentMethodId?: string; accountIntegrationId?: string; referenceCode?: string; paymentMethodType?: PaymentMethodType; currency: Currency; amount: number; amountReceived: number; amountRefunded: number; paidAt?: string | Date; refundedAt?: string | Date; status: PaymentStatus; statusInfo?: StatusInfo; cardBrand?: string; cardBrandInfo?: PaymentCardBrand; cardLast4?: string; data?: Record<string, any>; conversion?: PaymentConversion; metadata?: Record<string, any>; internalComment?: string; demo: boolean; createdAt: string | Date; updatedAt: string | Date; deletedAt?: string | Date; accountPaymentMethod?: Partial<AccountPaymentMethod> | null; order?: Order; allowedActions?: { canCopyLink: boolean; canMarkAsPaid: boolean; canRecapture: boolean; canRefund: boolean; }; } type PaymentProviderKey = 'MERCADOPAGO' | 'MERCADOPAGO_MARKETPLACE' | 'PLEXO' | 'MANUAL_PAYMENT' | 'PAYPAL' | 'AKUA'; interface PaymentProviderContext { data: Record<string, unknown>; } interface PaymentProviderInitInput { data: Record<string, any>; } interface PaymentProviderInitOutput { data: Record<string, any>; status: PaymentStatus; } interface PaymentProviderCaptureInput { data: Record<string, any>; } interface PaymentProviderCaptureOutput { data: Record<string, any>; } interface PaymentProviderRefundInput { amount: number; data: Record<string, any>; } interface PaymentProviderRefundOutput { data: Record<string, any>; } interface PaymentProviderWebhookResult { paymentId: string | null; status: PaymentStatus; data: Record<string, unknown>; paymentDetails: { referenceCode?: string; method?: string; last4?: string; }; } interface WebhookPayload { provider: string; accountId: string; payload: { query: Record<string, unknown>; body: Record<string, unknown>; headers: Record<string, unknown>; }; } declare enum PaymentCardBrandKey { mp_account_money = "mp_account_money", master = "master", debmaster = "debmaster", visa = "visa", debvisa = "debvisa", diners = "diners", oca = "oca", lider = "lider", amex = "amex", redpagos = "redpagos", abitab = "abitab" } interface PaymentCardBrand { key: string; name: string; image: string; icon: string; } declare function getPaymentCardBrand(key: PaymentCardBrandKey): PaymentCardBrand; interface PaymentProviderAdapter { readonly key: PaymentProviderKey; initPayment(input: PaymentProviderInitInput): Promise<PaymentProviderInitOutput>; capture(input: PaymentProviderCaptureInput): Promise<PaymentProviderCaptureOutput>; refund(input: PaymentProviderRefundInput): Promise<PaymentProviderRefundOutput>; processWebhook(input: WebhookPayload['payload']): Promise<PaymentProviderWebhookResult>; } declare function getPaymentStatusInfo(status: PaymentStatus): StatusInfo; /** Item en el JSON integration.supportedPaymentMethods (íconos de medios). */ interface SupportedPaymentMethodIconRow { id: string; name?: string; thumbnail?: string; icon?: string; [key: string]: unknown; } /** Parsea supportedPaymentMethods desde fila integration (simple-json / array / string JSON). */ declare function parseIntegrationSupportedPaymentMethodsArray(raw: unknown): SupportedPaymentMethodIconRow[]; /** * Lista única de medios de pago en el orden canónico: * 1) Integraciones PAYMENT_GATEWAY ordenadas por integration.order ASC, providerKey ASC * 2) Dentro de cada una, el orden del array integration.supportedPaymentMethods * 3) Deduplicación por id conservando la primera aparición */ declare function flattenSupportedPaymentMethodsFromAccountIntegrations(accountIntegrations: Array<{ integration?: { category?: string; order?: number; providerKey?: string; supportedPaymentMethods?: unknown; } | null; }>): SupportedPaymentMethodIconRow[]; declare enum FulfillmentStatus { PENDING = "pending", SHIPPED = "shipped", DELIVERED = "delivered", CANCELLED = "cancelled" } type FulfillmentTrackingEvent = { providerStatus: string; providerStatusLabel?: string; retailaStatus: FulfillmentStatus; at: string; raw?: Record<string, unknown>; }; type Fulfillment = { id: string; code: string; accountId: string; orderId: string; accountBranchId: string; deliveryOptionId: string; items: FulfillmentItem[]; labels: FulfillmentLabel[]; status: FulfillmentStatus; data: Record<string, unknown> | null; trackingEvents?: FulfillmentTrackingEvent[]; shippedAt: Date | null; deliveredAt: Date | null; cancelledAt: Date | null; createdAt: Date; updatedAt: Date; deletedAt?: Date; }; type FulfillmentDeliveryOption = { id: string; name: string; deliveryType?: 'SHIPPING' | 'PICKUP'; pickupLocations?: PickupLocation[]; [key: string]: unknown; }; interface PickupLocation { id: string; name: string; address: Address; hours?: string; phone?: string; additionalInfo?: Record<string, unknown>; } type FulfillmentRecollectionMode = 'RECOLLECTION' | 'DROP_OFF'; type FulfillmentRecollectionSchedule = { dayOfWeek: number; startHour: number; endHour: number; intervalMinutes?: number; }; type FulfillmentRecollectionCapabilities = { supportsRecollection: boolean; supportsDropOff: boolean; allowsScheduling: boolean; recollectionSchedule?: FulfillmentRecollectionSchedule[]; leadTimeHours: number; maxAdvanceDays: number; dropOffLocationsUrl?: string; }; type FulfillmentRecollectionConfig = { mode: FulfillmentRecollectionMode; scheduledDateTime?: Date; recollectionAddress?: Address; contactInfo?: { name: string; phone: string; email?: string; }; specialInstructions?: string; }; type FulfillmentProviderCreateInput = { data: Record<string, unknown>; items: FulfillmentItem[]; order: Order; fulfillment: Fulfillment; recollectionConfig?: FulfillmentRecollectionConfig; /** ISO 3166-1 alpha-2 country code (e.g. 'UY', 'AR') for provider defaults (e.g. phone fallback). */ accountCountryCode?: string; }; type FulfillmentProviderCreateOutput = { data?: Record<string, unknown>; labels: { trackingNumber: string; trackingUrl?: string; label?: { url?: string; base64?: string; format?: 'pdf' | 'png' | 'zpl'; }; }[]; }; type FulfillmentProviderProcessWebhookInput = WebhookPayload & { fulfillmentService: any; }; type FulfillmentProviderProcessWebhookOutput = { fulfillmentId: string; fulfillmentStatus: FulfillmentStatus; data: Record<string, any>; trackingEvent?: FulfillmentTrackingEvent; }; type FulfillmentProviderKey = 'MANUAL_FULFILLMENT' | 'DAC' | 'PEDIDOSYA'; type FulfillmentProviderContext = { data: Record<string, any>; }; interface FulfillmentProviderAdapter { readonly key: FulfillmentProviderKey; listDeliveryOptions(): Promise<FulfillmentDeliveryOption[]>; canCalculate(data: Record<string, unknown>): Promise<boolean>; calculatePrice(data: Record<string, unknown>): Promise<number>; getRecollectionCapabilities(): Promise<FulfillmentRecollectionCapabilities>; createFulfillment(input: FulfillmentProviderCreateInput): Promise<FulfillmentProviderCreateOutput>; processWebhook(input: FulfillmentProviderProcessWebhookInput): Promise<FulfillmentProviderProcessWebhookOutput | null>; /** Optional: cancel the fulfillment with the provider (e.g. cancel shipping label). */ cancelFulfillment?(fulfillment: Fulfillment): Promise<void>; } /** * OrderDeliveryMethod Entity * Represents a snapshot of the selected delivery option for an order */ interface OrderDeliveryMethod { id: string; orderId: string; deliveryOptionId: string; name: string; description?: string; amount: number; data?: Record<string, any>; accountId: string; createdAt: Date; updatedAt: Date; deletedAt?: Date; deliveryOption?: AccountDeliveryOption; } interface OrderDeliveryMethodCreateData { orderId: string; deliveryOptionId: string; name: string; description?: string; amount: number; data?: Record<string, any>; } interface OrderDeliveryMethodUpdateData { name?: string; description?: string; amount?: number; data?: Record<string, any>; } /** * Entidad Order * Define la orden de compra de un cliente en el sitio web. */ interface Order { id: string; accountId: string; customerId: string; cartId?: string; code: string; deliveryType: OrderDeliveryType; deliveryFirstName?: string; deliveryLastName?: string; deliveryAddress?: any; deliveryPhone?: any; pickupBranchId?: string; accountPaymentMethodId?: string; paymentMethodIntegrationId?: string; billingInformation?: any; currency: Currency; currencySymbol?: string; subtotalPrice: number; totalDiscounts: number; totalShippingPrice: number; totalTax: number; taxDetails?: any; totalPrice: number; totalRefunded: number; status: OrderStatus; statusInfo?: StatusInfo; paymentStatus: OrderPaymentStatus; paymentStatusInfo?: StatusInfo; fulfillmentStatus: FulfillmentStatus; statusHistory?: StatusChangeHistory[]; customerNote?: string; internalNote?: string; source: OrderSource; sourceAccountDomainId?: string; demo: boolean; createdAt: Date; updatedAt: Date; cancelledAt?: Date; cancelReason?: string; deletedAt?: Date; /** Estimated delivery window start (from delivery option rules) */ estimatedDeliveryStart?: Date; /** Estimated delivery window end (from delivery option rules) */ estimatedDeliveryEnd?: Date; items?: OrderItem[]; /** Applied promotions snapshot at order creation (checkout promos with name/code/amount). */ promotions?: OrderAppliedPromotion[]; customer?: Customer | null; paymentMethodIntegration?: AccountIntegration | null; accountDomain?: AccountDomain; deliveryMethod?: OrderDeliveryMethod | null; account?: Account; accountPaymentMethod?: Partial<AccountPaymentMethod> | null; payments?: Payment[]; statusFlow?: StatusFlow[]; statusChangeAllowed?: OrderStatus[]; hasShipment?: boolean; } interface OrderItem { id: string; accountId: string; orderId: string; productId: string; productVariantId: string; sku?: string; productName: string; variantName?: string; currency: Currency; currencySymbol?: string; unitPrice: number; totalDiscount: number; totalPrice: number; quantity: number; quantityFulfilled: number; quantityRefunded: number; quantityReturned: number; totalTax: number; taxName?: string; createdAt: Date; updatedAt: Date; productSnapshot?: OrderItemSnapshot; product?: Product; } declare enum OrderStatus { PENDING = "PENDING",// Order placed, awaiting payment confirmation CONFIRMED = "CONFIRMED",// Payment received, order confirmed PROCESSING = "PROCESSING",// Order being prepared PROCESSED = "PROCESSED",// Order ready to be shipped ON_HOLD = "ON_HOLD",// Order temporarily paused COMPLETED = "COMPLETED",// Order finished (e.g., after return period) CANCELLED = "CANCELLED",// Order cancelled before fulfillment FAILED = "FAILED" } declare enum OrderPaymentStatus { PENDING = "PENDING", PARTIAL = "PARTIAL", PAID = "PAID", OVERPAID = "OVERPAID", REFUNDED = "REFUNDED", PARTIALLY_REFUNDED = "PARTIALLY_REFUNDED" } declare enum OrderSource { WEB = "WEB", POS = "POS", API = "API" } declare enum OrderDeliveryType { SHIPPING = "SHIPPING", PICKUP = "PICKUP" } /** * Pseudo-estado amigable para la vista/filtro de órdenes en backoffice. * Cada valor se deriva de combinaciones de status, paymentStatus, fulfillmentStatus y deliveryType. */ declare enum DisplayOrderStatus { PENDIENTES_DE_PAGO = "PENDIENTES_DE_PAGO", EN_PROCESO = "EN_PROCESO", LISTAS_PARA_ENVIAR = "LISTAS_PARA_ENVIAR", LISTAS_PARA_RETIRAR = "LISTAS_PARA_RETIRAR", ENVIADAS = "ENVIADAS", ENTREGADAS = "ENTREGADAS", EN_ESPERA = "EN_ESPERA", CON_PROBLEMAS = "CON_PROBLEMAS", CANCELADAS = "CANCELADAS", REEMBOLSADAS = "REEMBOLSADAS" } interface StatusChangeHistory { type: 'order' | 'fulfillment' | 'payment'; status: OrderStatus | FulfillmentStatus | PaymentStatus; timestamp: Date; reason?: string; userId?: string; metadata?: Record<string, any>; } interface OrderItemSnapshot { sku?: string; productName: string; variantName?: string; media?: Media[]; } /** Promotion applied to an order (snapshot at checkout time). */ interface OrderAppliedPromotion { code: string; amount: number; name?: string; description?: string; isAutomatic?: boolean; } type StatusByType = { order: OrderStatus; fulfillment: FulfillmentStatus; payment: PaymentStatus; }; type StatusFlow<T extends keyof StatusByType = keyof StatusByType> = { type: T; status: StatusByType[T]; text?: string; doneAt: Date | null; }; type NextStatusAction<T extends keyof StatusByType = keyof StatusByType> = { type: T; status: StatusByType[T]; text: string; fulfillmentId?: string; }; interface OrderCreateFromCartDto { cartId: string; paymentMethodIntegrationId?: string; customerNote?: string; } interface AdminOrderStatusChangeDto { status: OrderStatus; } declare function getOrderStatusInfo(status: OrderStatus): StatusInfo; declare function getOrderPaymentStatusInfo(status: OrderPaymentStatus): StatusInfo; declare function getDisplayOrderStatusInfo(displayStatus: DisplayOrderStatus): StatusInfo; /** Order-like minimal shape for computing display status */ type OrderForDisplayStatus = Pick<Order, 'status' | 'paymentStatus' | 'deliveryType'> & { fulfillmentStatus?: FulfillmentStatus | null; }; /** * Derives the display (pseudo) status for an order from real status, paymentStatus, fulfillmentStatus and deliveryType. * Evaluation order matters: Canceladas and Reembolsadas are mutually exclusive (Canceladas wins). */ declare function getDisplayOrderStatus(order: OrderForDisplayStatus): DisplayOrderStatus; /** * Add an item to the cart */ interface CartItemAddDto { cartId: string; productId: string; variantId?: string; quantity: number; attributes?: { [key: string]: string | number; }; userEmail?: string; userId?: string; } /** * Update an item in the cart */ interface CartItemUpdateDto { cartId: string; itemId: string; quantity: number; } /** * Remove an item from the cart */ interface CartItemRemoveDto { cartId: string; itemId: string; } interface CartUpdateDto { cartId: string; source: OrderSource; accountDomainId?: string; customer: { email: string; }; delivery: { type: 'SHIPPING' | 'PICKUP'; pickupBranchId?: string; firstname: string; lastname: string; phone: { countryCode: string; national: string; international: string; type: string; validated: boolean; }; address: { country: string; department: string; locality: string; street: string; complement?: string; notes?: string; postalCode: string; mapPosition: { lat: number; lng: number; }; }; }; billing: { name: string; address: string; city: string; department: string; }; accountPaymentMethodId?: string; customerNote?: string | null; } /** * Confirm a cart */ interface CartConfirmDto { cartId: string; } /** * Validation information for a cart item */ interface CartItemValidation { hasIssues: boolean; issues: string[]; errorCode?: CartItemErrorCode; currentPrice?: number; availableStock?: number; isProductActive?: boolean; } /** * Error codes for cart items */ declare enum CartItemErrorCode { PRICE_INCREASED = "PRICE_INCREASED",// Precio aumentó PRICE_DECREASED = "PRICE_DECREASED",// Precio disminuyó PRODUCT_INACTIVE = "PRODUCT_INACTIVE",// Producto ya no está disponible STOCK_INSUFFICIENT = "STOCK_INSUFFICIENT",// Stock