@vectoriox/iox-ui 5.101.0 → 5.103.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,7 @@ import { FrameSequence } from '@vectoriox/iox-ui/media-core';
2
2
  import { DesignChoices, AnimateId, ColorScheme, DesignTokenLike, StylePreset } from '@vectoriox/iox-ui/design-core';
3
3
  import { SeoRawDoc } from '@vectoriox/iox-ui/seo-core';
4
4
  import { ContentFieldLike } from '@vectoriox/iox-ui/composite-core';
5
+ import { CheckoutGateRefusal } from '@vectoriox/iox-ui/commerce-core';
5
6
  import { ParallaxDepth } from '@vectoriox/iox-ui/scene-core';
6
7
 
7
8
  declare const SPEC_SITE_PLAN_SHAPE: {
@@ -7758,7 +7759,10 @@ declare enum BuildNoticeCode {
7758
7759
  ShopHasProducts = "shop-has-products",
7759
7760
  /** Commerce G1: the studio had never set its currency and VAT — the build stored the ones its language implies
7760
7761
  * (Hebrew: ILS and 18%), said here so the owner checks them in Settings ▸ General before setting prices. */
7761
- ShopMoneyInferred = "shop-money-inferred"
7762
+ ShopMoneyInferred = "shop-money-inferred",
7763
+ /** Commerce G2: the facts the owner gave (email, phone, address) became the shop's contact details where it had none
7764
+ * — said, so the owner adds what only they know (the legal name, the business number) in Shop ▸ Settings. */
7765
+ ShopBusinessFromFacts = "shop-business-from-facts"
7762
7766
  }
7763
7767
  interface BuildNotice {
7764
7768
  code: string;
@@ -8578,6 +8582,13 @@ declare enum SiteFindingCode {
8578
8582
  /** Commerce G1 (shop-aware §3i): a sample product the build added still has no price — a price is a fact a buyer is
8579
8583
  * held to, so the owner sets it (or removes the sample) before the store goes live. */
8580
8584
  SamplePrice = "sample-price",
8585
+ /** Commerce G2: a sample product the build added has no stock count yet — how many the owner has is theirs to say;
8586
+ * unanswered, the sample is sold out to every visitor (the build never invents stock). */
8587
+ SampleStock = "sample-stock",
8588
+ /** Commerce G2 (R-H8): a site that sells, while the checkout gate (commerce-core `checkoutGate`, C-D19) still refuses
8589
+ * one of its facts — a way to get paid, delivery, the business's identity, the owner's own legal pages. Each is the
8590
+ * owner's to answer, never written for them; the finding carries the gate's code in `fact`. */
8591
+ StoreFact = "store-fact",
8581
8592
  StockPhoto = "stock-photo",
8582
8593
  /** M7: a picture made with AI for the site still stands where one of the studio's own could. */
8583
8594
  MadePicture = "made-picture",
@@ -8605,6 +8616,8 @@ interface SiteFinding {
8605
8616
  nodeId?: string;
8606
8617
  /** The global slot (`header` / `footer`) when it is in a global. */
8607
8618
  owner?: string;
8619
+ /** `store-fact`: the checkout gate's code (commerce-core `CheckoutGateCode`) — which fact, so a screen can open where it is answered. */
8620
+ fact?: string;
8608
8621
  }
8609
8622
  interface SiteCheck {
8610
8623
  id: SiteCheckId;
@@ -8653,6 +8666,19 @@ interface SiteAuditSnapshot {
8653
8666
  id: string;
8654
8667
  label?: string;
8655
8668
  }>;
8669
+ /** Commerce G2: sample products (`isSample`) whose stock count was never set. */
8670
+ unstockedSamples?: ReadonlyArray<{
8671
+ id: string;
8672
+ label?: string;
8673
+ }>;
8674
+ /**
8675
+ * Commerce G2: what the checkout gate refuses for this studio (commerce-core `checkoutGate(…).refusals`) and the
8676
+ * studio's language its words are said in. Read only when the site sells (`siteSells`).
8677
+ */
8678
+ store?: {
8679
+ refusals: ReadonlyArray<Pick<CheckoutGateRefusal, 'code' | 'label'>>;
8680
+ lang?: string | null;
8681
+ } | null;
8656
8682
  /** Stock photos a build placed that are still on the page. */
8657
8683
  stock?: ReadonlyArray<{
8658
8684
  nodeId: string;
@@ -8676,6 +8702,8 @@ interface SiteAuditOptions {
8676
8702
  /** Audit as if only this page were being published (its own page checks + every site-wide one). */
8677
8703
  pageId?: string;
8678
8704
  }
8705
+ /** Commerce G2: the site sells — a page or a global holds a part that puts a product in the bag or opens the checkout. */
8706
+ declare function siteSells(snapshot: Pick<SiteAuditSnapshot, 'pages' | 'globals'>): boolean;
8679
8707
  /** A route pattern (`/work/:slug`) matches a concrete path (`/work/blue-bowl`). */
8680
8708
  declare function routeMatches(pattern: string, path: string): boolean;
8681
8709
  /** Run the eight checks. `pageId` narrows the page checks to the page being published; site-wide ones always run. */
@@ -10074,5 +10102,5 @@ declare function applyLayoutEdits(page: LayoutPage, edits: ReadonlyArray<LayoutE
10074
10102
  /** The strict format a repair is asked in: `{ edits: [{ op, path, value }] }`, every key required. */
10075
10103
  declare function layoutRepairJsonSchema(): JsonSchema;
10076
10104
 
10077
- export { ACCOUNT_ENTRY_ID, ACTION_START_SCALE, ACTIVE_BUILD_STATUSES, AI_REFUSAL_NEXT, AI_REFUSAL_STATUS, AI_STEPS, AI_STEP_LABELS, AI_STEP_NEEDS, AI_STEP_PART_TOKENS, AI_STEP_TYPICAL_TOKENS, ART_DIRECTION_PARTS, AiCallStatus, AiCapability, AiFeature, AiGenerationStage, AiKeyMode, AiLimit, AiNextKind, AiProviderId, AiRefusalCode, AiStep, BAR_ITEMS_MAX, BAR_ITEMS_MIN, BASELINE_ROLES, BUILD_STEPS, BaselineRole, BindScope, BuildNoticeCode, BuildStep, CONTENT_ROLE_MEANINGS, CREDITS_PER_USD, CardBindTarget, CheckSeverity, ComposeError, ComposeIssueCode, ContentFieldControl, ContentFieldType, ContentRole, ContentTypeAction, CreatedKind, DANGLING_LINK_CODES, DEFAULT_PHONE_MENU_BREAKPOINT, DEFAULT_SITE_LOCALE, ENTRANCE_EASING, ENTRANCE_ORIGIN_LOOK, ENTRANCE_TRIGGER, EntrancePart, EntranceSide, FACT_KEYS, FIELD_TYPE_OF_CONTROL, FILL_ASPECT, FILM_PATTERN, FINAL_GENERATION_STAGES, FINDING_SEVERITY, FilmUnplaced, GRAMMAR_TOO_LARGE_MESSAGE, GlobalSlot, HEBREW_PREFIXES, JSON_SCHEMA_BANNED_KEYWORDS, JsonSchemaShapeError, KeptReason, LAYOUT_ACCENT_TEXT, LAYOUT_BEAT_DELAY, LAYOUT_CHECK_VIEWPORT, LAYOUT_COLOUR_TOKEN, LAYOUT_COLUMN_GAP, LAYOUT_DEPTH_ON_PHONE, LAYOUT_DRIFT, LAYOUT_EASING, LAYOUT_ENTRANCE_MAX_MS, LAYOUT_FONT_SIZE, LAYOUT_GUTTER, LAYOUT_HIDDEN_OPACITY, LAYOUT_KINETIC_KINDS, LAYOUT_LINE_HEIGHT, LAYOUT_OPERATED, LAYOUT_PACE, LAYOUT_PHONE_BREAKPOINT, LAYOUT_PHONE_PADDING, LAYOUT_PHOTO_ASPECT, LAYOUT_READY_MADE_TOKEN, LAYOUT_RISE, LAYOUT_SCREEN_PX, LAYOUT_TEXT_KINDS, LAYOUT_TOOLTIP_TRAIT, LAYOUT_VIEWPORTS, LAYOUT_WIRE_AUTOPLAY_MS, LayoutAlign, LayoutBleed, LayoutButtonVariant, LayoutColour, LayoutColourMode, LayoutDepth, LayoutDial, LayoutEase, LayoutEditOp, LayoutEnter, LayoutGalleryEffect, LayoutGapCode, LayoutIssueCode, LayoutLayerKind, LayoutMendKind, LayoutNavKind, LayoutPace, LayoutPhotoShape, LayoutPhotoSource, LayoutRole, LayoutSectionKind, LayoutSequenceToken, LayoutSide, LayoutSignatureId, LayoutSize, LayoutSourceChoice, LayoutTrackProp, LayoutTransition, LayoutViewport, MAX_SITE_PICTURES, NAV_PART_LABELS, NAV_SHAPE_COPY, NEUTRAL_STYLE_PROPS, NODE_BASELINES, NO_TOKENS, NavPagesSource, NavRole, NavShape, NavShapeError, PAGE_ARCHETYPES, PHOTO_ANALYSIS_WIDTH, PHOTO_CALM_DETAIL, PHOTO_GRID, PHOTO_LIGHT_LUMINANCE, PICTURE_ASPECTS, PICTURE_NEVER, PICTURE_REAL_PLACE_FAMILIES, PICTURE_REROLL_EVERY, PICTURE_REVIEW_FORMAT, PICTURE_REVIEW_SHAPE, PICTURE_TEXT_CONTRAST, PICTURE_WORLDS, PICTURE_WORLD_IDS, PLAN_EDITS_ANSWER_SHAPES, PLAN_EDITS_PART_SCHEMA_NAMES, PLAN_EDIT_OP_PART, PLAN_EDIT_SHAPE, PLAN_EDIT_WIRE_KEYS, PLAN_PARTS, PLAN_PART_KEYS, PLAN_WIRE_DERIVED, PLAN_WIRE_PART_SCHEMA_NAMES, PLAN_WIRE_SHAPE, PRICING_PATTERN, PROOF_FINGERPRINTS, PUBLISH_BLOCKING_PLACEHOLDERS, PageDataKind, PathIssueCollector, PatternDirective, PatternGlobalPosition, PatternOpens, PatternPlaceholder, PatternRecipe, PhoneMenuBreakpoint, PhotoTone, PictureRefusal, PictureWorld, PlaceholderKind, PlanChangeAction, PlanChangeKind, PlanDataSourceMode, PlanDataSourceType, PlanEditIssueCode, PlanEditOp, PlanEditsOutcome, PlanPart, PlanWireEntry, PlanWireShapeError, PlanWordIssueCode, PreflightRefusalCode, PriceBindTarget, PublishRefusalCode, RENDER_CHECK, REQUIRED_CONTENT_ROLES, RelativeOp, SAMPLE_IMAGE_REF, SCENE_LEVEL, SCENE_OTHER_PAGES, SCRIM_BACKGROUND, SCRIM_COVER, SCRIM_LEVELS, SHOP_CART_BUTTON_ID, SHOP_CART_DRAWER_ID, SHOP_FIELDS, SHOP_LATEST_LIMIT, SHOP_LIST_LIMIT, SHOP_NEED, SHOP_ONLY_CONTENT_ROLES, SHOP_PRODUCTS_MAX, SHOP_ROLES, SHOP_SLUG_FIELD, SHOWCASE_FILM, SHOWCASE_SHOP, SIGN_IN_DIALOG_ID, SITE_CHECKS, SITE_FACT_LABELS, SITE_HEADER_PATTERN, SITE_LIBRARY, SITE_LOCALES, SITE_NEED_IDS, SITE_PATTERNS, SITE_PLAN_VERSION, SITE_TEMPLATES, SPEC_SITE_ARCHETYPES, SPEC_SITE_COPY_LENGTHS, SPEC_SITE_DENSITY_COPY, SPEC_SITE_FACTS, SPEC_SITE_LAYOUT, SPEC_SITE_LIBRARY, SPEC_SITE_LOCALES, SPEC_SITE_NEED_IDS, SPEC_SITE_PATTERNS, SPEC_SITE_PICTURE_NEVER, SPEC_SITE_PICTURE_WORLDS, SPEC_SITE_PLAN_SHAPE, SPEC_SITE_REQUIRED_ROLES, SPEC_SITE_ROLES, SPEC_SITE_TEMPLATES, STOCK_FAMILIES, STOCK_FAMILY_INTENTS, STOCK_INTENT_ORDER, STOCK_INTENT_SUBJECTS, STOCK_ITEM_ASPECT, STOCK_MIN_KEPT, STOCK_PROVIDER_TERMS, STOCK_SEED_MARGIN, STOCK_SUBJECT_WORDS, STRICT_SCHEMA_BUDGET, STRICT_SCHEMA_LIMITS, STUDIO_TEMPLATE, ScrimLevel, SectionFallbackLastResort, SectionSwapAction, SectionSwapRule, ShopResource, ShopSourceRole, SiteBuildKind, SiteBuildStatus, SiteCheckId, SiteFindingCode, SiteLocale, SitePlanError, SitePlanIssueCode, SitePlanSourceKind, SiteTemplateError, SiteTemplateId, StepState, StockIntent, StockOrientation, StockProviderId, StockReviewFlag, StockReviewVerdict, StockSlotKind, StockSubject, WORDS_AREA_DEFAULT_SHARE, WordsEdge, addBarItem, addStockCredits, aiRefusalNext, aiStepParts, applyLayoutEdits, applyOwnPhotoGalleries, applyPictureScrims, applyPlanEdits, applyStockItemPhotos, applyStockPhotos, archetypeIssues, areaLuminance, artDirectionFor, artDirectionIssues, artDirectionPreamble, aspectRatioOf, assertStyleSlots, assertValidSitePlan, auditLayoutMotion, auditSite, barIconForRoute, blocksPublish, brandHueWord, buildKeys, buildStepFacts, buildStepsOf, builtHomePageId, calmParts, calmUnder, checkLayout, chooseScrim, composeContextOf, composeLayout, composeNavHeader, composePresetForm, composeSection, composeSite, contentTypeOfSource, contentTypePreviewFields, contentTypeToWire, copyLengthOf, costUsd, coverCrop, createSerializedNode, creditsOfUsd, dataSourceToWire, derivedBeats, derivedDataSources, derivedShopSources, describeInventoryForPrompt, describePlanData, describeShapeKey, driftAt, driftOverlap, emptyAreaPhrase, entranceAction, entranceInteraction, estimatePictures, estimateStepCredits, expandLayoutWire, expandPlanWire, expandWireContentType, expandWireDataSource, expandWireEdit, expandWireField, expandWirePage, expandWireSection, expandWireShop, failedBuildStep, fallBackBySection, fieldToWire, filmOfPlan, filmPlacement, findNavRoot, fingerprintOf, frameWords, isActiveBuild, isLayoutRule, isNonEmptyString, isPictureWorld, isPlainObject, isRtlLocale, isShopResource, jsonAnyOf, jsonBoolean, jsonClosedObject, jsonInteger, jsonListOf, jsonOneOf, jsonSchemaKeywords, jsonSchemaObjects, jsonShapedObject, jsonText, judgeLayoutRender, layerShownSpans, layoutBandScheme, layoutBoxPx, layoutColumnsVw, layoutDesignOf, layoutDialOf, layoutDriftPhoto, layoutElementStyle, layoutGalleryLists, layoutGallerySources, layoutGlideDepth, layoutHeldStill, layoutLookChanges, layoutLookOf, layoutMotionOf, layoutNodeClass, layoutOpeningDisplayMend, layoutOpeningDisplays, layoutPathSteps, layoutPhotoIds, layoutPresetColours, layoutPresetOf, layoutRepairJsonSchema, layoutRoomPx, layoutRuleEdge, layoutShapeHasPurpose, layoutStillLine, layoutTextFits, layoutTextWidthEm, layoutToWire, layoutVoidScreens, layoutVoids, layoutWireJsonSchema, luminanceOf, measureLayout, mendLayout, modelCanDo, moveBarItem, navPages, navShapeBreakpoint, navShapeOf, nextSourceOf, nodeBindPaths, orientationOfRatio, ownPhotoFit, pageToWire, parseLayoutPhotoId, parsePatternPath, parseSampleImageRef, pathAt, patternById, patternHasForm, patternLinkSlots, patternListGap, patternManifest, patternNeedsBinding, patternNodes, patternOptionalParts, patternRoleNeeds, patternScopes, patternSlotBudgets, patternSlots, patternTakesBinding, phoneGapBefore, phoneMenuPages, phoneWordsColour, photoInventory, photoShapeOf, pictureAspect, pictureItemsOf, picturePrompt, pictureRefusalOf, pictureRerolls, pictureReviewIssues, pictureReviewJsonSchema, pictureReviewPasses, pictureSlotKey, pictureTargets, pictureTryFits, pixelsUnder, placeFilm, planEditOps, planEditToWire, planEditWireGaps, planEditWireKeys, planEditWireOps, planEditWireShape, planEditsFromWire, planEditsJsonSchema, planEditsToWire, planEntrances, planFromTemplate, planHasShopSource, planLayoutPhotos, planNavShape, planOwnPhotos, planPartOfPath, planPartToWire, planPictures, planSells, planStockPhotos, planToWire, planWireGaps, planWirePartJsonSchema, planWirePartShape, planWordIssues, pricesIn, publishRefusal, publishVerdict, readyMadeColumn, recipeListBinds, recomposeAsks, releasedLayoutDefaults, removeBarItem, requiredAcknowledgements, requiredShapeKeys, roleField, routeMatches, routeParams, samenessIssues, sampleImageRef, scoreStockPhoto, screenFontSize, screenWordColumns, screenWordMisfit, screenWordOverflowPx, sectionEntrances, sectionPatternIds, sectionToWire, sectionsNamed, sequenceShare, sequenceTokenOf, setStyleProps, shapeKeys, shopCategoriesOf, shopContentType, shopSourceAliases, showcaseGlobals, showcasePages, showcasePlans, showcaseScenes, showcaseStorePages, shownTogether, signatureOf, siteNavPages, slotBudget, splitSide, stockCopyKey, stockCreditLine, stockCreditLines, stockCreditNode, stockCreditNodeId, stockFits, stockGroupOf, stockItemSlots, stockKept, stockPhotoRatio, stockPhotoSubject, stockPhotoUsable, stockPhotoWords, stockSlots, stockWord, stockWords, strictSchemaComplexity, strictSchemaRefusal, toneOf, typicalStepTokens, validatePlanEdits, validateSitePlan, variantNamesOf, walkSerialized, wireContentTypeJsonSchema, wireDataSourceJsonSchema, wireFieldJsonSchema, wirePageJsonSchema, wireSectionJsonSchema, wireShopProductJsonSchema, withDerivedSources, wordPattern, wordsOverPhotos, wordsOverPicture, writtenTexts };
10105
+ export { ACCOUNT_ENTRY_ID, ACTION_START_SCALE, ACTIVE_BUILD_STATUSES, AI_REFUSAL_NEXT, AI_REFUSAL_STATUS, AI_STEPS, AI_STEP_LABELS, AI_STEP_NEEDS, AI_STEP_PART_TOKENS, AI_STEP_TYPICAL_TOKENS, ART_DIRECTION_PARTS, AiCallStatus, AiCapability, AiFeature, AiGenerationStage, AiKeyMode, AiLimit, AiNextKind, AiProviderId, AiRefusalCode, AiStep, BAR_ITEMS_MAX, BAR_ITEMS_MIN, BASELINE_ROLES, BUILD_STEPS, BaselineRole, BindScope, BuildNoticeCode, BuildStep, CONTENT_ROLE_MEANINGS, CREDITS_PER_USD, CardBindTarget, CheckSeverity, ComposeError, ComposeIssueCode, ContentFieldControl, ContentFieldType, ContentRole, ContentTypeAction, CreatedKind, DANGLING_LINK_CODES, DEFAULT_PHONE_MENU_BREAKPOINT, DEFAULT_SITE_LOCALE, ENTRANCE_EASING, ENTRANCE_ORIGIN_LOOK, ENTRANCE_TRIGGER, EntrancePart, EntranceSide, FACT_KEYS, FIELD_TYPE_OF_CONTROL, FILL_ASPECT, FILM_PATTERN, FINAL_GENERATION_STAGES, FINDING_SEVERITY, FilmUnplaced, GRAMMAR_TOO_LARGE_MESSAGE, GlobalSlot, HEBREW_PREFIXES, JSON_SCHEMA_BANNED_KEYWORDS, JsonSchemaShapeError, KeptReason, LAYOUT_ACCENT_TEXT, LAYOUT_BEAT_DELAY, LAYOUT_CHECK_VIEWPORT, LAYOUT_COLOUR_TOKEN, LAYOUT_COLUMN_GAP, LAYOUT_DEPTH_ON_PHONE, LAYOUT_DRIFT, LAYOUT_EASING, LAYOUT_ENTRANCE_MAX_MS, LAYOUT_FONT_SIZE, LAYOUT_GUTTER, LAYOUT_HIDDEN_OPACITY, LAYOUT_KINETIC_KINDS, LAYOUT_LINE_HEIGHT, LAYOUT_OPERATED, LAYOUT_PACE, LAYOUT_PHONE_BREAKPOINT, LAYOUT_PHONE_PADDING, LAYOUT_PHOTO_ASPECT, LAYOUT_READY_MADE_TOKEN, LAYOUT_RISE, LAYOUT_SCREEN_PX, LAYOUT_TEXT_KINDS, LAYOUT_TOOLTIP_TRAIT, LAYOUT_VIEWPORTS, LAYOUT_WIRE_AUTOPLAY_MS, LayoutAlign, LayoutBleed, LayoutButtonVariant, LayoutColour, LayoutColourMode, LayoutDepth, LayoutDial, LayoutEase, LayoutEditOp, LayoutEnter, LayoutGalleryEffect, LayoutGapCode, LayoutIssueCode, LayoutLayerKind, LayoutMendKind, LayoutNavKind, LayoutPace, LayoutPhotoShape, LayoutPhotoSource, LayoutRole, LayoutSectionKind, LayoutSequenceToken, LayoutSide, LayoutSignatureId, LayoutSize, LayoutSourceChoice, LayoutTrackProp, LayoutTransition, LayoutViewport, MAX_SITE_PICTURES, NAV_PART_LABELS, NAV_SHAPE_COPY, NEUTRAL_STYLE_PROPS, NODE_BASELINES, NO_TOKENS, NavPagesSource, NavRole, NavShape, NavShapeError, PAGE_ARCHETYPES, PHOTO_ANALYSIS_WIDTH, PHOTO_CALM_DETAIL, PHOTO_GRID, PHOTO_LIGHT_LUMINANCE, PICTURE_ASPECTS, PICTURE_NEVER, PICTURE_REAL_PLACE_FAMILIES, PICTURE_REROLL_EVERY, PICTURE_REVIEW_FORMAT, PICTURE_REVIEW_SHAPE, PICTURE_TEXT_CONTRAST, PICTURE_WORLDS, PICTURE_WORLD_IDS, PLAN_EDITS_ANSWER_SHAPES, PLAN_EDITS_PART_SCHEMA_NAMES, PLAN_EDIT_OP_PART, PLAN_EDIT_SHAPE, PLAN_EDIT_WIRE_KEYS, PLAN_PARTS, PLAN_PART_KEYS, PLAN_WIRE_DERIVED, PLAN_WIRE_PART_SCHEMA_NAMES, PLAN_WIRE_SHAPE, PRICING_PATTERN, PROOF_FINGERPRINTS, PUBLISH_BLOCKING_PLACEHOLDERS, PageDataKind, PathIssueCollector, PatternDirective, PatternGlobalPosition, PatternOpens, PatternPlaceholder, PatternRecipe, PhoneMenuBreakpoint, PhotoTone, PictureRefusal, PictureWorld, PlaceholderKind, PlanChangeAction, PlanChangeKind, PlanDataSourceMode, PlanDataSourceType, PlanEditIssueCode, PlanEditOp, PlanEditsOutcome, PlanPart, PlanWireEntry, PlanWireShapeError, PlanWordIssueCode, PreflightRefusalCode, PriceBindTarget, PublishRefusalCode, RENDER_CHECK, REQUIRED_CONTENT_ROLES, RelativeOp, SAMPLE_IMAGE_REF, SCENE_LEVEL, SCENE_OTHER_PAGES, SCRIM_BACKGROUND, SCRIM_COVER, SCRIM_LEVELS, SHOP_CART_BUTTON_ID, SHOP_CART_DRAWER_ID, SHOP_FIELDS, SHOP_LATEST_LIMIT, SHOP_LIST_LIMIT, SHOP_NEED, SHOP_ONLY_CONTENT_ROLES, SHOP_PRODUCTS_MAX, SHOP_ROLES, SHOP_SLUG_FIELD, SHOWCASE_FILM, SHOWCASE_SHOP, SIGN_IN_DIALOG_ID, SITE_CHECKS, SITE_FACT_LABELS, SITE_HEADER_PATTERN, SITE_LIBRARY, SITE_LOCALES, SITE_NEED_IDS, SITE_PATTERNS, SITE_PLAN_VERSION, SITE_TEMPLATES, SPEC_SITE_ARCHETYPES, SPEC_SITE_COPY_LENGTHS, SPEC_SITE_DENSITY_COPY, SPEC_SITE_FACTS, SPEC_SITE_LAYOUT, SPEC_SITE_LIBRARY, SPEC_SITE_LOCALES, SPEC_SITE_NEED_IDS, SPEC_SITE_PATTERNS, SPEC_SITE_PICTURE_NEVER, SPEC_SITE_PICTURE_WORLDS, SPEC_SITE_PLAN_SHAPE, SPEC_SITE_REQUIRED_ROLES, SPEC_SITE_ROLES, SPEC_SITE_TEMPLATES, STOCK_FAMILIES, STOCK_FAMILY_INTENTS, STOCK_INTENT_ORDER, STOCK_INTENT_SUBJECTS, STOCK_ITEM_ASPECT, STOCK_MIN_KEPT, STOCK_PROVIDER_TERMS, STOCK_SEED_MARGIN, STOCK_SUBJECT_WORDS, STRICT_SCHEMA_BUDGET, STRICT_SCHEMA_LIMITS, STUDIO_TEMPLATE, ScrimLevel, SectionFallbackLastResort, SectionSwapAction, SectionSwapRule, ShopResource, ShopSourceRole, SiteBuildKind, SiteBuildStatus, SiteCheckId, SiteFindingCode, SiteLocale, SitePlanError, SitePlanIssueCode, SitePlanSourceKind, SiteTemplateError, SiteTemplateId, StepState, StockIntent, StockOrientation, StockProviderId, StockReviewFlag, StockReviewVerdict, StockSlotKind, StockSubject, WORDS_AREA_DEFAULT_SHARE, WordsEdge, addBarItem, addStockCredits, aiRefusalNext, aiStepParts, applyLayoutEdits, applyOwnPhotoGalleries, applyPictureScrims, applyPlanEdits, applyStockItemPhotos, applyStockPhotos, archetypeIssues, areaLuminance, artDirectionFor, artDirectionIssues, artDirectionPreamble, aspectRatioOf, assertStyleSlots, assertValidSitePlan, auditLayoutMotion, auditSite, barIconForRoute, blocksPublish, brandHueWord, buildKeys, buildStepFacts, buildStepsOf, builtHomePageId, calmParts, calmUnder, checkLayout, chooseScrim, composeContextOf, composeLayout, composeNavHeader, composePresetForm, composeSection, composeSite, contentTypeOfSource, contentTypePreviewFields, contentTypeToWire, copyLengthOf, costUsd, coverCrop, createSerializedNode, creditsOfUsd, dataSourceToWire, derivedBeats, derivedDataSources, derivedShopSources, describeInventoryForPrompt, describePlanData, describeShapeKey, driftAt, driftOverlap, emptyAreaPhrase, entranceAction, entranceInteraction, estimatePictures, estimateStepCredits, expandLayoutWire, expandPlanWire, expandWireContentType, expandWireDataSource, expandWireEdit, expandWireField, expandWirePage, expandWireSection, expandWireShop, failedBuildStep, fallBackBySection, fieldToWire, filmOfPlan, filmPlacement, findNavRoot, fingerprintOf, frameWords, isActiveBuild, isLayoutRule, isNonEmptyString, isPictureWorld, isPlainObject, isRtlLocale, isShopResource, jsonAnyOf, jsonBoolean, jsonClosedObject, jsonInteger, jsonListOf, jsonOneOf, jsonSchemaKeywords, jsonSchemaObjects, jsonShapedObject, jsonText, judgeLayoutRender, layerShownSpans, layoutBandScheme, layoutBoxPx, layoutColumnsVw, layoutDesignOf, layoutDialOf, layoutDriftPhoto, layoutElementStyle, layoutGalleryLists, layoutGallerySources, layoutGlideDepth, layoutHeldStill, layoutLookChanges, layoutLookOf, layoutMotionOf, layoutNodeClass, layoutOpeningDisplayMend, layoutOpeningDisplays, layoutPathSteps, layoutPhotoIds, layoutPresetColours, layoutPresetOf, layoutRepairJsonSchema, layoutRoomPx, layoutRuleEdge, layoutShapeHasPurpose, layoutStillLine, layoutTextFits, layoutTextWidthEm, layoutToWire, layoutVoidScreens, layoutVoids, layoutWireJsonSchema, luminanceOf, measureLayout, mendLayout, modelCanDo, moveBarItem, navPages, navShapeBreakpoint, navShapeOf, nextSourceOf, nodeBindPaths, orientationOfRatio, ownPhotoFit, pageToWire, parseLayoutPhotoId, parsePatternPath, parseSampleImageRef, pathAt, patternById, patternHasForm, patternLinkSlots, patternListGap, patternManifest, patternNeedsBinding, patternNodes, patternOptionalParts, patternRoleNeeds, patternScopes, patternSlotBudgets, patternSlots, patternTakesBinding, phoneGapBefore, phoneMenuPages, phoneWordsColour, photoInventory, photoShapeOf, pictureAspect, pictureItemsOf, picturePrompt, pictureRefusalOf, pictureRerolls, pictureReviewIssues, pictureReviewJsonSchema, pictureReviewPasses, pictureSlotKey, pictureTargets, pictureTryFits, pixelsUnder, placeFilm, planEditOps, planEditToWire, planEditWireGaps, planEditWireKeys, planEditWireOps, planEditWireShape, planEditsFromWire, planEditsJsonSchema, planEditsToWire, planEntrances, planFromTemplate, planHasShopSource, planLayoutPhotos, planNavShape, planOwnPhotos, planPartOfPath, planPartToWire, planPictures, planSells, planStockPhotos, planToWire, planWireGaps, planWirePartJsonSchema, planWirePartShape, planWordIssues, pricesIn, publishRefusal, publishVerdict, readyMadeColumn, recipeListBinds, recomposeAsks, releasedLayoutDefaults, removeBarItem, requiredAcknowledgements, requiredShapeKeys, roleField, routeMatches, routeParams, samenessIssues, sampleImageRef, scoreStockPhoto, screenFontSize, screenWordColumns, screenWordMisfit, screenWordOverflowPx, sectionEntrances, sectionPatternIds, sectionToWire, sectionsNamed, sequenceShare, sequenceTokenOf, setStyleProps, shapeKeys, shopCategoriesOf, shopContentType, shopSourceAliases, showcaseGlobals, showcasePages, showcasePlans, showcaseScenes, showcaseStorePages, shownTogether, signatureOf, siteNavPages, siteSells, slotBudget, splitSide, stockCopyKey, stockCreditLine, stockCreditLines, stockCreditNode, stockCreditNodeId, stockFits, stockGroupOf, stockItemSlots, stockKept, stockPhotoRatio, stockPhotoSubject, stockPhotoUsable, stockPhotoWords, stockSlots, stockWord, stockWords, strictSchemaComplexity, strictSchemaRefusal, toneOf, typicalStepTokens, validatePlanEdits, validateSitePlan, variantNamesOf, walkSerialized, wireContentTypeJsonSchema, wireDataSourceJsonSchema, wireFieldJsonSchema, wirePageJsonSchema, wireSectionJsonSchema, wireShopProductJsonSchema, withDerivedSources, wordPattern, wordsOverPhotos, wordsOverPicture, writtenTexts };
10078
10106
  export type { AddBarItemResult, AiBuyCredits, AiEntitlementsView, AiMeter, AiModelEntry, AiRefusal, AiTokenCounts, AiTokenPrice, AreaLuminance, ArtDirection, AuditPage, AuditPlaceholder, BarItemsEditResult, BuildNotice, BuildStepError, BuildStepFacts, BuildStepRecord, CalmReading, CheckLayoutContext, CmsDataSourcePlan, ComposeContext, ComposeIssue, ComposeLayoutOptions, ComposedDataSource, ComposedItem, ComposedLayout, ComposedNavHeader, ComposedPage, ComposedPlaceholder, ComposedProduct, ComposedRoute, ComposedSection, ComposedShop, ComposedSite, ContentFieldPlan, ContentRoles, ContentSeedPlan, ContentTypePlan, CreateNodeOptions, CreatedRecord, DataSourcePlan, DriftBox, DriftLayer, DriftMeeting, DynamicKeysAsList, EntranceAction, EntranceActionOptions, EntranceInteraction, EntranceMark, EntranceSpec, EntranceStamp, FactKey, FilmPlacement, FilmTarget, FingerprintedPage, FrameRegion, JsonSchema, LayoutBandMove, LayoutColours, LayoutEdit, LayoutFingerprint, LayoutForm, LayoutGallery, LayoutGalleryList, LayoutGap, LayoutGivenAway, LayoutIssue, LayoutLayer, LayoutLook, LayoutMend, LayoutPage, LayoutPhotoAddress, LayoutReadyMade, LayoutRect, LayoutSection, LayoutSite, LayoutTrack, LayoutVoid, LayoutWire, LayoutWireLayer, LayoutWireSection, LayoutWireSlot, LayoutWireTrack, MeasuredLayer, MeasuredLayout, NavHeaderInput, NavHeaderOptions, NavPage, NavShapeOptions, NavShapeResult, NodeBaseline, OwnPhoto, OwnPhotoPlacement, PageArchetype, PageArchetypeId, PageArchetypeSlot, PageData, PageDataLine, PagePlan, PageSectionPlan, PageSeoPlan, PathIssue, PatternManifestEntry, PatternManifestOptions, PatternNode, PatternPath, PatternRoleNeed, PatternTrack, PhotoInventory, PhotoWordsArea, PicturePlan, PicturePlanOptions, PicturePromptContext, PictureReview, PictureSlot, PictureTryBudget, PictureWorldSpec, PicturesEstimate, PixelReading, PlacedFilm, PlainObject, PlanChange, PlanDirection, PlanEdit, PlanEditIssue, PlanEditResult, PlanEditsAnswer, PlanEntrancesInput, PlanFilm, PlanWireContext, PlanWireParts, PlanWordContext, PlanWordIssue, PreflightRefusal, PublishRefusal, RecipeListBinds, RelativeDataSourcePlan, ScrimChoice, SectionEntrances, SectionFallback, SectionInput, SectionJudge, SectionOptions, SectionSwap, SerializedBinding, SerializedNode, SerializedResponsive, ShapeEntry, ShapeIssueCodes, ShopDataSourcePlan, ShopOptionPlan, ShopPlan, ShopProductPlan, ShowcaseInput, SiteAudit, SiteAuditOptions, SiteAuditSnapshot, SiteBuildRun, SiteBusiness, SiteCheck, SiteFinding, SiteNeedId, SitePageRef, SitePattern, SitePlan, SitePlanContext, SitePlanIssue, SitePlanSource, SitePlanValidation, SiteTemplate, StockCredit, StockItemSlot, StockLink, StockNeed, StockPhoto, StockPhotoTraits, StockPlacement, StockPlanOptions, StockProviderTerms, StockReview, StockSlot, StockTarget, StrictSchemaComplexity, StrictSchemaRefusal, TemplatePlanInput, UndoKept, UndoPreview, UndoRecord, WireOptions, WordsArea, WrittenText };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vectoriox/iox-ui",
3
- "version": "5.101.0",
3
+ "version": "5.103.0",
4
4
  "peerDependencies": {
5
5
  "@angular/common": ">=20.0.0",
6
6
  "@angular/core": ">=20.0.0",
@@ -1,6 +1,7 @@
1
1
  import { CatalogEntry, catalogKey } from './catalog';
2
2
  import { Cart, CART_ISSUE_LABELS, cartOf, CartIssue, PricedCart, PricedLine, priceCart, StudioCommerce } from './cart';
3
3
  import { CurrencyCode } from './currency';
4
+ import { AppliedCoupon } from './coupons';
4
5
  import { CommerceLabel, labelIn } from './labels';
5
6
  import { MAX_LINE_QUANTITY } from './limits';
6
7
  import { Money } from './money';
@@ -35,6 +36,9 @@ export interface CartView {
35
36
  count: number;
36
37
  empty: boolean;
37
38
  subtotal: Money | null;
39
+ /** The coupon's discount (E4) — zero, or null on a cart never priced. */
40
+ discount: Money | null;
41
+ coupon: AppliedCoupon | null;
38
42
  total: Money | null;
39
43
  vat: Money | null;
40
44
  vatPercent: number;
@@ -101,7 +105,7 @@ export function checkoutHref(orgLabel?: string | null): string {
101
105
 
102
106
  /** A cart with nothing in it. */
103
107
  export function emptyCartView(currency: CurrencyCode | null = null): CartView {
104
- return { currency, lines: [], count: 0, empty: true, subtotal: null, total: null, vat: null, vatPercent: 0, issues: [], freeShippingRemaining: null };
108
+ return { currency, lines: [], count: 0, empty: true, subtotal: null, discount: null, coupon: null, total: null, vat: null, vatPercent: 0, issues: [], freeShippingRemaining: null };
105
109
  }
106
110
 
107
111
  /** The view of a priced cart. `lineIdOf` names each line the way the host's routes do (default `cartLineId`);
@@ -121,6 +125,8 @@ export function cartViewOf(priced: PricedCart, options: {
121
125
  count,
122
126
  empty: lines.length === 0,
123
127
  subtotal: priced.subtotal,
128
+ discount: priced.discount,
129
+ coupon: priced.coupon ?? null,
124
130
  total: priced.total,
125
131
  vat: priced.vat,
126
132
  vatPercent: priced.vatPercent,
@@ -1,4 +1,5 @@
1
1
  import { CatalogEntry, catalogKey, sellableQuantity } from './catalog';
2
+ import { AppliedCoupon, Coupon, couponDiscount, CouponRefusal, normalizeCouponCode } from './coupons';
2
3
  import { CurrencyCode, currencyExponent } from './currency';
3
4
  import { CommerceLabel } from './labels';
4
5
  import { MAX_CART_AMOUNT, MAX_CART_LINES, MAX_LINE_QUANTITY } from './limits';
@@ -26,6 +27,10 @@ export interface StudioCommerce {
26
27
 
27
28
  export interface PricingChoice {
28
29
  shippingMethodId?: string | null;
30
+ /** The buyer's coupon (E4) — the caller looked it up; `priceCart` decides what it gives. */
31
+ coupon?: Coupon | null;
32
+ /** Epoch ms the coupon's dates are judged at (no clock is read here). */
33
+ now?: number | null;
29
34
  }
30
35
 
31
36
  export enum CartIssueCode {
@@ -51,6 +56,8 @@ export enum CartIssueCode {
51
56
  ShippingUnavailable = 'shipping-unavailable',
52
57
  /** The studio's VAT is not a usable rate: the VAT line reads 0. */
53
58
  VatInvalid = 'vat-invalid',
59
+ /** The coupon gives this cart nothing now (expired, used up, under its minimum…): no discount; `couponRefusal` says why. */
60
+ CouponNotApplied = 'coupon-not-applied',
54
61
  }
55
62
 
56
63
  export const CART_ISSUE_LABELS: Readonly<Record<CartIssueCode, CommerceLabel>> = Object.freeze({
@@ -69,6 +76,7 @@ export const CART_ISSUE_LABELS: Readonly<Record<CartIssueCode, CommerceLabel>> =
69
76
  [CartIssueCode.AmountTooLarge]: { en: 'The order is too large; an item was removed.', he: 'ההזמנה גדולה מדי; פריט הוסר.' },
70
77
  [CartIssueCode.ShippingUnavailable]: { en: 'That delivery method is not available for this order. Choose another.', he: 'שיטת המשלוח הזו אינה זמינה להזמנה. בחרו אחרת.' },
71
78
  [CartIssueCode.VatInvalid]: { en: 'The shop\'s VAT rate is not set correctly.', he: 'שיעור המע"מ של החנות אינו מוגדר כראוי.' },
79
+ [CartIssueCode.CouponNotApplied]: { en: 'Your coupon no longer applies to this order and was removed.', he: 'הקופון כבר לא חל על ההזמנה הזו והוסר.' },
72
80
  });
73
81
 
74
82
  export interface CartIssue {
@@ -80,6 +88,9 @@ export interface CartIssue {
80
88
  /** What the priced line holds now (clamped / capped). */
81
89
  quantity?: number;
82
90
  shippingMethodId?: string;
91
+ /** CouponNotApplied: the code and why. */
92
+ coupon?: string;
93
+ couponRefusal?: CouponRefusal;
83
94
  }
84
95
 
85
96
  export interface PricedLine {
@@ -100,8 +111,10 @@ export interface PricedCart {
100
111
  currency: CurrencyCode;
101
112
  lines: PricedLine[];
102
113
  subtotal: Money;
103
- /** Zero until coupons (E4); `total` already subtracts it. */
114
+ /** The coupon's discount on the goods (E4); `total` already subtracts it. */
104
115
  discount: Money;
116
+ /** The coupon that gave `discount`, or null. */
117
+ coupon: AppliedCoupon | null;
105
118
  shipping: Money;
106
119
  shippingMethod: ShippingQuote | null;
107
120
  requiresShipping: boolean;
@@ -196,6 +209,18 @@ function lineTotalWithin(unitPrice: Money, quantity: number, subtotal: Money): M
196
209
  }
197
210
  }
198
211
 
212
+ /** The coupon's discount on the goods — none, and an issue said, when the coupon gives this cart nothing now. */
213
+ function discountOf(choice: PricingChoice | null | undefined, subtotal: Money, issues: CartIssue[]): { discount: Money; coupon: AppliedCoupon | null } {
214
+ const none = { discount: money(0, subtotal.currency), coupon: null };
215
+ if (!choice?.coupon) return none;
216
+ const check = couponDiscount(choice.coupon, subtotal, choice.now);
217
+ if (check.ok === false) {
218
+ issues.push({ code: CartIssueCode.CouponNotApplied, coupon: normalizeCouponCode(choice.coupon.code), couponRefusal: check.refusal });
219
+ return none;
220
+ }
221
+ return { discount: check.discount, coupon: check.applied };
222
+ }
223
+
199
224
  /**
200
225
  * THE pricing function (C-D7, trap T1): the engine shows its result, iox-cms recomputes it at checkout and at
201
226
  * payment. Prices come from the catalog only — a cart line carries no number but a quantity. Every money value
@@ -253,7 +278,7 @@ export function priceCart(cart: Cart, catalog: readonly CatalogEntry[], studio:
253
278
  });
254
279
  }
255
280
 
256
- const discount = money(0, currency);
281
+ const { discount, coupon } = discountOf(choice, subtotal, issues);
257
282
  const goods = subtractMoney(subtotal, discount);
258
283
  const requiresShipping = lines.some(line => line.requiresShipping);
259
284
  const chosenId = choice && isText(choice.shippingMethodId) ? choice.shippingMethodId : null;
@@ -270,6 +295,7 @@ export function priceCart(cart: Cart, catalog: readonly CatalogEntry[], studio:
270
295
  lines,
271
296
  subtotal,
272
297
  discount,
298
+ coupon,
273
299
  shipping,
274
300
  shippingMethod,
275
301
  requiresShipping,
@@ -0,0 +1,186 @@
1
+ import { CurrencyCode } from './currency';
2
+ import { CommerceLabel, labelIn } from './labels';
3
+ import { isMoney, money, Money, percentOf } from './money';
4
+
5
+ /**
6
+ * Coupons v1 (commerce plan §3h, E4): a code, a percent or a fixed amount off the GOODS (never the delivery), an
7
+ * optional minimum order, start and end, a uses limit; one per order. `priceCart` is the only place a coupon becomes
8
+ * a discount — iox-cms recomputes it at checkout and when the order is placed (trap T1). Pure: the caller passes `now`.
9
+ */
10
+ export enum CouponKind {
11
+ Percent = 'percent',
12
+ Fixed = 'fixed',
13
+ }
14
+
15
+ export interface Coupon {
16
+ code: string;
17
+ kind: CouponKind;
18
+ /** 1–100, at most two decimals — a Percent coupon's. */
19
+ percent?: number | null;
20
+ /** A Fixed coupon's amount, in the studio currency. */
21
+ amount?: Money | null;
22
+ /** The goods (after nothing else) must come to at least this. */
23
+ minimumOrder?: Money | null;
24
+ /** ISO dates; a missing one is open-ended. */
25
+ startsAt?: string | null;
26
+ expiresAt?: string | null;
27
+ /** Orders it may be used on; null = no limit. */
28
+ maxUses?: number | null;
29
+ /** Orders placed with it so far. */
30
+ uses?: number;
31
+ enabled: boolean;
32
+ }
33
+
34
+ /** What a priced cart says about the coupon it applied (the summary's "Discount · CODE"). */
35
+ export interface AppliedCoupon {
36
+ code: string;
37
+ kind: CouponKind;
38
+ percent: number | null;
39
+ amount: Money | null;
40
+ }
41
+
42
+ export const COUPON_CODE_MIN = 3;
43
+ export const COUPON_CODE_MAX = 32;
44
+ const COUPON_CODE = new RegExp(`^[A-Z0-9][A-Z0-9_-]{${COUPON_CODE_MIN - 1},${COUPON_CODE_MAX - 1}}$`);
45
+ const PERCENT_MAX = 100;
46
+ const PERCENT_DECIMALS = 2;
47
+
48
+ /** A code as it is stored and compared: trimmed, upper-case. A buyer may type `back10` for `BACK10`. */
49
+ export function normalizeCouponCode(value: unknown): string {
50
+ return typeof value === 'string' ? value.trim().toUpperCase() : '';
51
+ }
52
+
53
+ export function isCouponCode(value: unknown): boolean {
54
+ return COUPON_CODE.test(normalizeCouponCode(value));
55
+ }
56
+
57
+ /** What the owner must fix before a coupon may be saved. */
58
+ export enum CouponProblem {
59
+ CodeInvalid = 'code-invalid',
60
+ KindInvalid = 'kind-invalid',
61
+ PercentInvalid = 'percent-invalid',
62
+ AmountInvalid = 'amount-invalid',
63
+ MinimumInvalid = 'minimum-invalid',
64
+ DatesInvalid = 'dates-invalid',
65
+ MaxUsesInvalid = 'max-uses-invalid',
66
+ }
67
+
68
+ const dateOf = (value: unknown): number | null => {
69
+ if (value === null || value === undefined || value === '') return null;
70
+ const at = new Date(value as string).getTime();
71
+ return Number.isFinite(at) ? at : NaN;
72
+ };
73
+
74
+ const percentValid = (value: unknown): boolean => {
75
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > PERCENT_MAX) return false;
76
+ const [, frac = ''] = String(value).split('.');
77
+ return frac.length <= PERCENT_DECIMALS;
78
+ };
79
+
80
+ const positiveMoneyIn = (value: unknown, currency: CurrencyCode): boolean =>
81
+ isMoney(value) && value.currency === currency && value.amount > 0;
82
+
83
+ /** Every reason this coupon cannot be saved for a studio selling in `currency` — empty when it can. */
84
+ export function couponProblems(coupon: Partial<Coupon> | null | undefined, currency: CurrencyCode): CouponProblem[] {
85
+ const c = coupon ?? {};
86
+ const problems: CouponProblem[] = [];
87
+ if (!isCouponCode(c.code)) problems.push(CouponProblem.CodeInvalid);
88
+ if (c.kind === CouponKind.Percent) {
89
+ if (!percentValid(c.percent)) problems.push(CouponProblem.PercentInvalid);
90
+ } else if (c.kind === CouponKind.Fixed) {
91
+ if (!positiveMoneyIn(c.amount, currency)) problems.push(CouponProblem.AmountInvalid);
92
+ } else {
93
+ problems.push(CouponProblem.KindInvalid);
94
+ }
95
+ if (c.minimumOrder !== null && c.minimumOrder !== undefined && !(isMoney(c.minimumOrder) && c.minimumOrder.currency === currency && c.minimumOrder.amount >= 0)) {
96
+ problems.push(CouponProblem.MinimumInvalid);
97
+ }
98
+ const starts = dateOf(c.startsAt);
99
+ const ends = dateOf(c.expiresAt);
100
+ if (Number.isNaN(starts) || Number.isNaN(ends) || (starts !== null && ends !== null && ends <= starts)) problems.push(CouponProblem.DatesInvalid);
101
+ if (c.maxUses !== null && c.maxUses !== undefined && !(Number.isSafeInteger(c.maxUses) && c.maxUses >= 1)) problems.push(CouponProblem.MaxUsesInvalid);
102
+ return problems;
103
+ }
104
+
105
+ /** Why a coupon gives no discount to this cart — each said to the buyer on the coupon field. */
106
+ export enum CouponRefusal {
107
+ Unknown = 'coupon-unknown',
108
+ Disabled = 'coupon-disabled',
109
+ NotStarted = 'coupon-not-started',
110
+ Expired = 'coupon-expired',
111
+ UsedUp = 'coupon-used-up',
112
+ MinimumNotMet = 'coupon-minimum-not-met',
113
+ /** Another currency, or a coupon the owner would not be allowed to save now. */
114
+ NotUsable = 'coupon-not-usable',
115
+ }
116
+
117
+ /** `{amount}` is the minimum order, filled by `couponRefusalWords`. */
118
+ export const COUPON_REFUSAL_LABELS: Readonly<Record<CouponRefusal, CommerceLabel>> = Object.freeze({
119
+ [CouponRefusal.Unknown]: { en: 'This code does not exist. Check it and try again.', he: 'הקוד הזה לא קיים. בדקו אותו ונסו שוב.' },
120
+ [CouponRefusal.Disabled]: { en: 'This code is not active.', he: 'הקוד הזה אינו פעיל.' },
121
+ [CouponRefusal.NotStarted]: { en: 'This code cannot be used yet.', he: 'עדיין אי אפשר להשתמש בקוד הזה.' },
122
+ [CouponRefusal.Expired]: { en: 'This code has expired.', he: 'תוקף הקוד הזה פג.' },
123
+ [CouponRefusal.UsedUp]: { en: 'This code has been used up.', he: 'הקוד הזה נוצל עד תומו.' },
124
+ [CouponRefusal.MinimumNotMet]: { en: 'This code is for orders of {amount} or more.', he: 'הקוד הזה תקף להזמנות של {amount} ומעלה.' },
125
+ [CouponRefusal.NotUsable]: { en: 'This code cannot be used on this order.', he: 'אי אפשר להשתמש בקוד הזה בהזמנה הזו.' },
126
+ });
127
+
128
+ export function couponRefusalWords(refusal: CouponRefusal, lang: string | null | undefined, fill: { amount?: string } = {}): string {
129
+ return labelIn(COUPON_REFUSAL_LABELS[refusal], lang).replace('{amount}', fill.amount ?? '');
130
+ }
131
+
132
+ const COUPON_OFFER_LABELS: Readonly<Record<CouponKind, CommerceLabel>> = Object.freeze({
133
+ [CouponKind.Percent]: { en: '{percent}% off', he: '{percent}% הנחה' },
134
+ [CouponKind.Fixed]: { en: '{amount} off', he: '{amount} הנחה' },
135
+ });
136
+
137
+ /** What a coupon gives, in words ("10% off", "₪50.00 off") — the reminder's offer and the admin's coupon list. */
138
+ export function couponOfferWords(coupon: Pick<Coupon, 'kind' | 'percent' | 'amount'>, lang: string | null | undefined, formatMoney: (value: Money) => string): string {
139
+ const label = COUPON_OFFER_LABELS[coupon.kind];
140
+ if (!label) return '';
141
+ return labelIn(label, lang).replace('{percent}', String(coupon.percent ?? '')).replace('{amount}', coupon.amount ? formatMoney(coupon.amount) : '');
142
+ }
143
+
144
+ export type CouponCheck =
145
+ | { ok: true; discount: Money; applied: AppliedCoupon }
146
+ | { ok: false; refusal: CouponRefusal };
147
+
148
+ interface CouponRule {
149
+ readonly refusal: CouponRefusal;
150
+ readonly refuses: (coupon: Coupon, goods: Money, now: number) => boolean;
151
+ }
152
+
153
+ /** Checked in order; the first that refuses is the one said. */
154
+ const COUPON_RULES: readonly CouponRule[] = Object.freeze([
155
+ { refusal: CouponRefusal.Disabled, refuses: (c: Coupon) => c.enabled !== true },
156
+ { refusal: CouponRefusal.NotUsable, refuses: (c: Coupon, goods: Money) => couponProblems(c, goods.currency).length > 0 },
157
+ { refusal: CouponRefusal.NotStarted, refuses: (c: Coupon, _g: Money, now: number) => dateOf(c.startsAt) !== null && now < (dateOf(c.startsAt) as number) },
158
+ { refusal: CouponRefusal.Expired, refuses: (c: Coupon, _g: Money, now: number) => dateOf(c.expiresAt) !== null && now >= (dateOf(c.expiresAt) as number) },
159
+ { refusal: CouponRefusal.UsedUp, refuses: (c: Coupon) => typeof c.maxUses === 'number' && (c.uses ?? 0) >= c.maxUses },
160
+ { refusal: CouponRefusal.MinimumNotMet, refuses: (c: Coupon, goods: Money) => !!c.minimumOrder && goods.amount < c.minimumOrder.amount },
161
+ ]);
162
+
163
+ /**
164
+ * The discount `coupon` gives goods worth `goods` at `now`: a percent of them (rounded once, half to even) or the
165
+ * fixed amount, never more than the goods themselves. No clock is read: a missing `now` refuses a dated coupon.
166
+ */
167
+ export function couponDiscount(coupon: Coupon | null | undefined, goods: Money, now: number | null | undefined): CouponCheck {
168
+ if (!coupon) return { ok: false, refusal: CouponRefusal.Unknown };
169
+ const at = typeof now === 'number' && Number.isFinite(now) ? now : NaN;
170
+ const dated = dateOf(coupon.startsAt) !== null || dateOf(coupon.expiresAt) !== null;
171
+ if (dated && Number.isNaN(at)) return { ok: false, refusal: CouponRefusal.NotUsable };
172
+ const refused = COUPON_RULES.find(rule => rule.refuses(coupon, goods, at));
173
+ if (refused) return { ok: false, refusal: refused.refusal };
174
+ const raw = coupon.kind === CouponKind.Percent ? percentOf(goods, coupon.percent as number) : (coupon.amount as Money);
175
+ const discount = money(Math.min(raw.amount, goods.amount), goods.currency);
176
+ return {
177
+ ok: true,
178
+ discount,
179
+ applied: {
180
+ code: normalizeCouponCode(coupon.code),
181
+ kind: coupon.kind,
182
+ percent: coupon.kind === CouponKind.Percent ? (coupon.percent as number) : null,
183
+ amount: coupon.kind === CouponKind.Fixed ? money((coupon.amount as Money).amount, goods.currency) : null,
184
+ },
185
+ };
186
+ }
@@ -51,6 +51,8 @@ export interface OrderSnapshot {
51
51
  readonly lines: readonly OrderSnapshotLine[];
52
52
  readonly subtotal: Money;
53
53
  readonly discount: Money;
54
+ /** The coupon code the discount came from (E4), or null. */
55
+ readonly coupon: { readonly code: string } | null;
54
56
  readonly shipping: Money;
55
57
  readonly delivery: { readonly methodId: string; readonly kind: ShippingMethodKind; readonly name: string } | null;
56
58
  readonly total: Money;
@@ -130,6 +132,7 @@ export function orderSnapshot(pricedCart: PricedCart, payment: PaymentMethodConf
130
132
  })),
131
133
  subtotal: copyMoney(pricedCart.subtotal),
132
134
  discount: copyMoney(pricedCart.discount),
135
+ coupon: pricedCart.coupon ? { code: pricedCart.coupon.code } : null,
133
136
  shipping: copyMoney(pricedCart.shipping),
134
137
  delivery: delivery ? { methodId: delivery.methodId, kind: delivery.kind, name: delivery.name } : null,
135
138
  total: copyMoney(pricedCart.total),
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * Money is integer minor units in one ISO-4217 currency, so the engine, the builder and iox-cms compute the same
5
5
  * totals (trap T6: never a float). E0 shipped Money; E1a adds the cart and its ONE pricing function, shipping v1,
6
- * manual payment methods, the order state machine, the checkout steps and gate, and the order snapshot. No clock is
6
+ * manual payment methods, the order state machine, the checkout steps and gate, and the order snapshot; E4 adds
7
+ * coupons (one per order, priced by `priceCart`) and the journey: reminders, the consent gate, the funnel. No clock is
7
8
  * read anywhere — a caller passes `now`.
8
9
  * ⚠️ Not re-exported from the main entry. Consumers wire the usual trio — ng-package raw-ts assets,
9
10
  * jest moduleNameMapper, tsconfig paths — or `nest start` dies with ERR_REQUIRE_ESM.
@@ -16,6 +17,7 @@ export * from './limits';
16
17
  export * from './vat';
17
18
  export * from './catalog';
18
19
  export * from './shipping';
20
+ export * from './coupons';
19
21
  export * from './cart';
20
22
  export * from './payments';
21
23
  export * from './orders';
@@ -26,4 +28,5 @@ export * from './quantity';
26
28
  export * from './cart-transport';
27
29
  export * from './shop-display';
28
30
  export * from './site-checkout';
31
+ export * from './recovery';
29
32
  export { looksLikeEmail, looksLikePhone } from './text';