@fire-spark/core 0.43.0 → 0.46.1
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.
- package/dist/index.d.ts +36 -2
- package/dist/index.js +126 -10
- package/package.json +3 -3
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Money, PaymentAdapter, PaymentCollectAt, PaymentContext, PaymentResult, PaymentReversal, PaymentStorage, PaymentUI, RedeemLike, RedeemSource, isDeliveryFee, isRealPaymentMethod, orderRedeems } from "@fire-spark/payments";
|
|
2
|
-
import { AndConditions, ApplyFeesInput, ApplyFeesOrderScope, CheckoutMode, CheckoutResolved, CmsBlock, Condition, Customer, CustomerIdentifyInput, CustomerRegisterInput, CustomerUpdateInput, DeviceSecretStorage, DeviceSecretsConfigureOptions, DeviceSecretsConfigureOptions as DeviceSecretsConfigureOptions$1, DeviceSecretsPayload, DeviceSecretsPayload as DeviceSecretsPayload$1, Fee, Fulfillment, FulfillmentEligibilityInput, FulfillmentEligibilityInput as FulfillmentEligibilityInput$1, FulfillmentListInput, GroupDisplayType, KioskDeviceConfig, KioskDeviceConfigInput, KioskDeviceOverrides, KioskHealthBatchInput, KioskHealthBatchResult, KioskHeartbeatInput, KioskHeartbeatResult, KioskPickupNameRules, KioskRealtimeToken, LocalServerConfig, LocalServerConfig as LocalServerConfig$1, LocalServerHealthResult, LocalServerHealthResult as LocalServerHealthResult$1, MasivoTotpCode, MasivoTotpCreateInput, MasivoTotpVerification, MasivoTotpVerifyInput, MatchResult, MatchableRule, Menu, Menu as Menu$1, MenuLookup, MenuLookup as MenuLookup$1, MerchantPayment, ModifierControlType, ModifierGroup, OrConditions, Order as Order$1, Order as Order$2, OrderAdvanceFulfillmentInput, OrderCancelInput, OrderCancelInput as OrderCancelInput$1, OrderCancelType, OrderCancelType as OrderCancelType$1, OrderDeviceListInput, OrderDeviceListResult, OrderFulfillment, OrderFulfillmentWorkflow, OrderFulfillmentWorkflowEdge, OrderFulfillmentWorkflowNode, OrderInsertInput, OrderLine, OrderListInput, OrderRateInput, OrderRating, OrderRecord, OrderRecordPaymentInput, OrderRedeem, OrderRedemptionStep, OrderReorderInput, OrderRouteKind, OrderRouteKind as OrderRouteKind$1, OrderRouteStatus, OrderRoutes, OrderRoutes as OrderRoutes$1, OrderSetCustomerInput, OrderTotals, OrderUpdateInput, OrderValidateInput, OrderValidateOutput, PaymentCollectAt as PaymentCollectAt$1, PaymentEligibilityInput, PaymentEligibilityInput as PaymentEligibilityInput$1, PaymentIntentPutInput, PaymentMethod, PaymentProvider, PaymentTender, PaymentTenderInput, PlaceOrderResult, PosCatalog, PosFloorInput, PosFloorOccupancy, PosFloorPlan, PosFloorRealtimeToken, PosHealthBatchInput, PosHealthBatchResult, PosHeartbeatInput, PosHeartbeatResult, PosKioskOrder, PosKioskSettleInput, PosKioskSettleResult, PosOrderInput, PosOrderResult, PosTableAttachOrderInput, PosTableCloseInput, PosTableJoinInput, PosTableSeatInput, PosTableSeatReservationInput, PosTableSplitInput, PricingModifier, Product, Product as Product$1, Recommendation, RecurringDateCronFormatter, RecurringDateCronResult, RecurringDateCronSummary, RecurringDateCronValues, RouteEligibility, RouteEligibility as RouteEligibility$1, RouteEligibilityDetail, RouteEligibilityFlags, RouteEligibilityReason, RouteFailureKind, RouteFailureKind as RouteFailureKind$1, RouteHealthEvent, RouteHealthEvent as RouteHealthEvent$1, RouteHealthListener, RouteHealthListener as RouteHealthListener$1, RulesEngineOrder, RulesEngineOrderLine, RulesEngineParams, RulesEngineRuntime, Schedule, SdkLogContext, SdkLogErrorInfo, SdkLogLevel, SdkLogOptions, Store, StoreGetInput, StoreListInput, StoreNearbyInput, StorefrontAvailability, StorefrontMenu, StorefrontMenuScope, StorefrontMenuStreamOptions, StorefrontPaymentsListInput, StorefrontPreferences, SwitchCustomerArg, SwitchCustomerArg as SwitchCustomerArg$1, SwitchCustomerIdToken, SwitchCustomerOptions, SwitchCustomerOptions as SwitchCustomerOptions$1, SwitchCustomerResult, SwitchCustomerResult as SwitchCustomerResult$1, TenderRefundInput, TenderReplaceInput, TenderVoidInput, Variant, VariantGroup, WordFilterCheckInput, WordFilterCheckResult } from "@fire-spark/types";
|
|
2
|
+
import { AndConditions, ApplyFeesInput, ApplyFeesOrderScope, CheckoutMode, CheckoutResolved, CmsBlock, Condition, Customer, CustomerIdentifyInput, CustomerRegisterInput, CustomerUpdateInput, DeviceSecretStorage, DeviceSecretsConfigureOptions, DeviceSecretsConfigureOptions as DeviceSecretsConfigureOptions$1, DeviceSecretsPayload, DeviceSecretsPayload as DeviceSecretsPayload$1, Fee, Fulfillment, FulfillmentEligibilityInput, FulfillmentEligibilityInput as FulfillmentEligibilityInput$1, FulfillmentListInput, GroupDisplayType, KioskDeviceConfig, KioskDeviceConfigInput, KioskDeviceOverrides, KioskHealthBatchInput, KioskHealthBatchResult, KioskHeartbeatInput, KioskHeartbeatResult, KioskPickupNameRules, KioskRealtimeToken, LocalServerConfig, LocalServerConfig as LocalServerConfig$1, LocalServerHealthResult, LocalServerHealthResult as LocalServerHealthResult$1, MasivoTotpCode, MasivoTotpCreateInput, MasivoTotpVerification, MasivoTotpVerifyInput, MatchResult, MatchableRule, Menu, Menu as Menu$1, MenuLookup, MenuLookup as MenuLookup$1, MerchantPayment, ModifierControlType, ModifierGroup, OrConditions, Order as Order$1, Order as Order$2, OrderAdvanceFulfillmentInput, OrderCancelInput, OrderCancelInput as OrderCancelInput$1, OrderCancelType, OrderCancelType as OrderCancelType$1, OrderDeviceListInput, OrderDeviceListResult, OrderFulfillment, OrderFulfillmentWorkflow, OrderFulfillmentWorkflowEdge, OrderFulfillmentWorkflowNode, OrderInsertInput, OrderLine, OrderListInput, OrderRateInput, OrderRating, OrderRecord, OrderRecordPaymentInput, OrderRedeem, OrderRedemptionStep, OrderReorderInput, OrderRouteKind, OrderRouteKind as OrderRouteKind$1, OrderRouteStatus, OrderRoutes, OrderRoutes as OrderRoutes$1, OrderSetCustomerInput, OrderTotals, OrderUpdateInput, OrderValidateInput, OrderValidateOutput, PaymentCollectAt as PaymentCollectAt$1, PaymentEligibilityInput, PaymentEligibilityInput as PaymentEligibilityInput$1, PaymentIntentPutInput, PaymentMethod, PaymentProvider, PaymentTender, PaymentTenderInput, PlaceOrderResult, PosCatalog, PosFloorInput, PosFloorOccupancy, PosFloorPlan, PosFloorRealtimeToken, PosHealthBatchInput, PosHealthBatchResult, PosHeartbeatInput, PosHeartbeatResult, PosKioskOrder, PosKioskSettleInput, PosKioskSettleResult, PosOrderInput, PosOrderResult, PosTableAttachOrderInput, PosTableCloseInput, PosTableJoinInput, PosTableSeatInput, PosTableSeatReservationInput, PosTableSplitInput, PricingModifier, Product, Product as Product$1, ProductRewardSavings, Recommendation, RecurringDateCronFormatter, RecurringDateCronResult, RecurringDateCronSummary, RecurringDateCronValues, RouteEligibility, RouteEligibility as RouteEligibility$1, RouteEligibilityDetail, RouteEligibilityFlags, RouteEligibilityReason, RouteFailureKind, RouteFailureKind as RouteFailureKind$1, RouteHealthEvent, RouteHealthEvent as RouteHealthEvent$1, RouteHealthListener, RouteHealthListener as RouteHealthListener$1, RulesEngineOrder, RulesEngineOrderLine, RulesEngineParams, RulesEngineRuntime, Schedule, SdkLogContext, SdkLogErrorInfo, SdkLogLevel, SdkLogOptions, Store, StoreGetInput, StoreListInput, StoreNearbyInput, StorefrontAvailability, StorefrontMenu, StorefrontMenuScope, StorefrontMenuStreamOptions, StorefrontPaymentsListInput, StorefrontPreferences, SwitchCustomerArg, SwitchCustomerArg as SwitchCustomerArg$1, SwitchCustomerIdToken, SwitchCustomerOptions, SwitchCustomerOptions as SwitchCustomerOptions$1, SwitchCustomerResult, SwitchCustomerResult as SwitchCustomerResult$1, TenderRefundInput, TenderReplaceInput, TenderVoidInput, Variant, VariantGroup, WordFilterCheckInput, WordFilterCheckResult } from "@fire-spark/types";
|
|
3
3
|
import { Big } from "big.js";
|
|
4
4
|
//#region src/productCustomization/catalog.utils.d.ts
|
|
5
5
|
/** Image for a product inside one modifier group, else the product image. */
|
|
@@ -671,6 +671,12 @@ type ApplyRedeemInput = {
|
|
|
671
671
|
provider?: PaymentProvider;
|
|
672
672
|
/** ISO datetime with offset; validation fails once it has passed. */
|
|
673
673
|
expires_at?: string;
|
|
674
|
+
/**
|
|
675
|
+
* Optional informational unit full price of a Masivo `PRODUCT` reward.
|
|
676
|
+
* Stored in `line.metadata.reward_savings` to display savings; never
|
|
677
|
+
* alters line prices, charged discounts, taxes, or order totals.
|
|
678
|
+
*/
|
|
679
|
+
full_price?: number;
|
|
674
680
|
};
|
|
675
681
|
type RemoveRedeemInput = {
|
|
676
682
|
reward_id: string;
|
|
@@ -1353,6 +1359,34 @@ declare const redemptionSteps: (order: StepOrder) => OrderRedemptionStep[];
|
|
|
1353
1359
|
/** Sum root line group totals into order totals (Big.js). */
|
|
1354
1360
|
declare const recomputeTotals: (lines: OrderLine[], currency?: string) => OrderTotals;
|
|
1355
1361
|
//#endregion
|
|
1362
|
+
//#region src/order/rewardSavings.d.ts
|
|
1363
|
+
declare const REWARD_SAVINGS_METADATA_KEY: "reward_savings";
|
|
1364
|
+
interface ComputeProductRewardSavingsInput {
|
|
1365
|
+
fullPrice: number;
|
|
1366
|
+
quantity: number;
|
|
1367
|
+
lineValue: number;
|
|
1368
|
+
}
|
|
1369
|
+
/**
|
|
1370
|
+
* Cart value of a root line for Masivo product-reward savings comparison.
|
|
1371
|
+
* Matches `masivoContacts.payload` (`group_subtotal`, else `group_total`).
|
|
1372
|
+
*/
|
|
1373
|
+
declare const lineCartValue: (line: Pick<OrderLine, "group_subtotal" | "group_total">) => number;
|
|
1374
|
+
/**
|
|
1375
|
+
* Informational Masivo product-reward savings:
|
|
1376
|
+
* `full_price_total = full_price * quantity`
|
|
1377
|
+
* `savings = max(0, full_price * quantity - lineValue)`
|
|
1378
|
+
* Exact Big.js arithmetic, never rounded.
|
|
1379
|
+
*/
|
|
1380
|
+
declare const computeProductRewardSavings: (input: ComputeProductRewardSavingsInput) => ProductRewardSavings;
|
|
1381
|
+
/** Reads informational `reward_savings` from `line.metadata`, or null. */
|
|
1382
|
+
declare const getLineRewardSavings: (line: Pick<OrderLine, "metadata"> | null | undefined) => ProductRewardSavings | null;
|
|
1383
|
+
/** Attaches or removes `metadata.reward_savings` without mutating totals. */
|
|
1384
|
+
declare const withLineRewardSavings: (line: OrderLine, savings: ProductRewardSavings | null) => OrderLine;
|
|
1385
|
+
/** Recomputes `full_price_total` and `savings` after a line quantity change. */
|
|
1386
|
+
declare const rescaleLineRewardSavings: (line: OrderLine) => OrderLine;
|
|
1387
|
+
/** Applies a `line.uid -> ProductRewardSavings` map to matching lines. */
|
|
1388
|
+
declare const applyRewardSavingsToLines: (lines: OrderLine[], byLineUid: Readonly<Record<string, ProductRewardSavings>> | undefined) => OrderLine[];
|
|
1389
|
+
//#endregion
|
|
1356
1390
|
//#region src/order/lines.d.ts
|
|
1357
1391
|
declare const addLines: (lines: OrderLine[], incoming: OrderLine | OrderLine[]) => OrderLine[];
|
|
1358
1392
|
declare const removeLine: (lines: OrderLine[], lineUid: string) => OrderLine[];
|
|
@@ -4311,4 +4345,4 @@ declare const hpkeSeal: (input: HpkeSealInput) => Promise<{
|
|
|
4311
4345
|
/** Opens a sealed message; throws when anything was altered. */
|
|
4312
4346
|
declare const hpkeOpen: (input: HpkeOpenInput) => Promise<Uint8Array<ArrayBuffer>>;
|
|
4313
4347
|
//#endregion
|
|
4314
|
-
export { type AdvanceAndEnterConfig, type AdvanceAndEnterResult, type ApplyRedeemInput, type AuthConfigureOptions, type BuildRouteHttpInput, type BuildScheduleSlotsConfig, CALLBACK_MISSING_LOCAL_URL, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, type CallbackMissingLocalUrlDetails, type CanonicalInput, type CanonicalizationError, type CanonicalizationErrorCode, type CardBrand, type CardBrandSpec, type CardCvcError, type CardExpiry, type CardExpiryError, type CardNumberError, type CardPreviewSlot, type CardholderNameError, type CmsBlockScope, type CmsVisibilityBlock, type CmsVisibilityContext, type CmsVisibilityRules, type CreateOrderOptions, type CreateSessionOptions, type CustomizationPath, type CustomizationSession, DEFAULT_LOCALE, DEFAULT_MAX_INCOMPLETE_MINUTES, DEFAULT_MAX_SNAPSHOT_AGE_MS, DEFAULT_RECOMMENDATION_TYPES, DEFAULT_ROUTE_COOLDOWN_MS, DEFAULT_WEBHOOK_TIMEOUT_S, DelegatedSessionExpiredError, type DeunaCallbackUrls, type DeunaOrderStatus, type DeviceSecretStorage, type DeviceSecretsConfigureOptions, type DeviceSecretsPayload, type DeviceSecretsStore, type DispatchWebhooksConfig, type EngineCallbackRun, type EngineCallbackRunError, type EngineExecutionContext, type EngineFlagReviewInput, type EngineFulfillmentPatch, type EngineOrder, type EngineOrderChangedEvent, type EngineOrderFulfillment, type EngineOrderStatus, type EngineOrderStatusPatch, type EngineScope, type EngineStepLog, type EngineStepLogEntry, type EngineStepsLogs, type EngineWebhookEnvelope, type EngineWebhookFailureEvent, type EngineWebhookNodeRun, type EngineWebhookTarget, type EnterAndPauseResult, type EnterRunResult, type ExchangeOptions, FULFILLMENT_WORKFLOW_TERMINAL_STATUSES, type FailedCharge, type FinalizePlaceOrderConfig, type FiresparkOrigin, type FlatMenuCategory, type FulfillmentEligibilityInput, type FulfillmentExecutionPort, type FulfillmentPorts, type FulfillmentRunStatus, type FulfillmentStepName, type FulfillmentStoragePort, type FulfillmentTerminalOrderStatus, type GenOrderIdOptions, type GetCmsBlockOptions, type GroupDisplayType, HPKE_ALG, type HpkeAead, type HpkeEnvelope, type HpkeOpenInput, type HpkePrivateJwk, type HpkePublicJwk, type HpkeSealInput, ID_HASH_FORMATS, type IdBuilder, type IdHashFormat, type InvokeCallbackAttemptConfig, type InvokeCallbackAttemptResult, type ListMenusStreamOptions, type ListPaymentsOptions, type LocalDeviceCredentials, type LocalRouteProbeResult, type LocalServerConfig, type LocalServerHealthResult, LosslessNumber, type LosslessNumberLike, MAX_MAX_INCOMPLETE_MINUTES, MAX_SUPPORTED_WORKFLOW_SCHEMA_VERSION, MIN_MAX_INCOMPLETE_MINUTES, MODE_HINT_HEADER, type MarkRouteDownInput, type Menu, type MenuCategoryNode, type MenuLookup, type MilestoneSteps, type MilestoneTrackItem, type ModifierControlType, type ModifierCtx, type ModifierGroupCtx, type NestedMenuCategory, OFFLINE_NO_LOCAL_URL, ORIGIN_HEADER, Order, OrderAuthPinnedError, type OrderCancelInput, type OrderCancelOptions, type OrderCancelResult, type OrderCancelType, type OrderCustomerSource, type OrderDeviceCredential, type OrderDraft, type OrderIssue, type OrderIssueCode, type OrderLineDiff, type OrderLineIssue, type OrderLineIssueCode, OrderNotOpenError, OrderPaymentRequiredError, type OrderRouteKind, type OrderRouteStatus, OrderRouteUnavailableError, type OrderRoutes, type OrderScope, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, type OrderValidationResult, type OriginListener, type OriginState, type PauseForAdvanceConfig, type PayIntentOptions, type PayIntentResult, type PayOptions, type PaymentCardBrand, type PaymentEligibilityInput, type PaymentProgressEvent, type PaymentProgressListener, type PaymentRunOptions, type PaymentSessionOptions, type PendingWebhooks, PickupNameIssue, type PinnedFetchFactory, type PinnedFetchOptions, type PosOrderHttpOptions, type PricingModifier, type ProbeLocalRouteHealthOptions, type ProcessStateNodeCallbackJob, type ProcessStateNodeConfig, type ProcessStateNodeResult, type Product, type ProductCtx, type QuantitiesByPath, RESERVED_FULFILLMENT_STATUSES, type RecommendationType, RecurringDateCron, type RedeemPaymentRow, type RemoveRedeemInput, type ReorderOrderOptions, type ResetOptions, type ResolveRouteEligibilityInput, type ResolvedPaymentEligibility, type ResumeFromAdvanceConfig, type ReversalOutcome, type ReverseAllOptions, type RouteEligibility, type RouteEligibilityDetail, type RouteEligibilityFlags, type RouteEligibilityReason, type RouteFailureClassification, type RouteFailureKind, type RouteHealthEvent, type RouteHealthListener, type RouteHealthSnapshot, type RouteTenderCandidate, RulesEngine, type RunNodeCallbacksResult, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, SCHEDULED_STATUS, SDK_PAYMENT_ELIGIBILITY_CEILINGS, STATE_ALGO, STATE_HASH_PREFIX, type ScheduleSlot, type ScheduleSlotCart, type ScheduleSlotCartLine, type ScheduleWindow, type ScheduledSuccessorConfig, type SdkPaymentEligibility, type SelectionStatus, type SelectionsByPath, type SerializedError, type ServiceHttpOptions, type SimpleTenderPayment, type Snapshot, type StateGoldenRootVector, type StateGoldenVector, type StateGoldenVectors, type StateManifest, type StateManifestSection, type StateRootInput, type StateScope, type StateVectorFailure, type StepOutcome, type StorefrontAccessToken, type StorefrontErrorDetails, StorefrontHttpError, type SwitchCustomerArg, type SwitchCustomerIdToken, type SwitchCustomerOptions, type SwitchCustomerResult, TLS_FINGERPRINT_RESPONSE_HEADER, TLS_PIN_HEADER, type TestLocalServerHealthOptions, TlsFingerprintMismatchError, TokenExchangeError, type TrackWorkflow, type ValidateOptions, type ValidateOrderAgainstMenuInput, type Variant, type VariantGroup, type VariantGroupCtx, type VariantOptionCtx, type VariantSelection, type VerifyWebhookSignatureInput, type VisitedState, WORKFLOW_SCHEMA_VERSION, WORKFLOW_TIMEOUT, WorkflowSchemaVersionError, type WorkflowTimeoutDetails, addLines, advanceAndEnter, appendEngineStepLog, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, assertSupportedWorkflowSchemaVersion, auth, autoEnterSuccessTerminal, base64UrlDecode, base64UrlEncode, beginEngineStepLog, buildCustomerSnapshot, buildEngineCallbackError, buildEngineCallbackRun, buildRouteHttpOptions, buildRulesEngineFromOrder, buildScheduleSlots, buildWorkflowTimeoutDetails, callbackIdsFromNode, canEnterJoin, canPauseNow, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, certFingerprintsMatch, certMatchesAnyPin, classifyRouteFailure, clearDeviceSecrets, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, completeEngineStepLog, computeOrderExpiresAt, computeStartingPrice, configureDeviceSecrets, configureLocalTlsPinning, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createDeviceSecretsStore, createNodePinnedFetch, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultIsPaymentCaptured, defaultOutgoingEdge, defaultWebhookEventsForStatus, defaultWebhookRetryDelayMs, detectCardBrand, dispatchOrderWebhooks, dispatchPendingWebhooks, engineHmacSha256Hex, engineOrderStatusForFailedRun, engineWebhookDeliveryId, engineWebhookRunsForEnteredNodes, engineWebhookStatusKey, engineWebhookTransitionStates, enterAndPause, enterWorkflowNode, executeAdvance, executeScheduledWake, executeStart, failActiveEngineStepLog, finalizePlaceOrder, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findShippingFeeLine, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatLocalServerUrl, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLocalTlsPinning, getLogContext, getOrigin, getRouteHealth, getScheduleWindow, getSecret, hasInFlightPayment, hasLocalTlsPinning, hasSmartRouting, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, injectingMetadataFromCallback, invokeCallbackAttempt, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeliveryFee, isDeviceCharged, isDeviceNotLinked, isExpiredFulfillment, isExpiryComplete, isGenId, isInterruptTerminalStatus, isKioskUnauthorized, isLocalOrderUnknown, isMilestoneStepDone, isNodeRuntime, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderRouteUnavailableError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isReservedFulfillmentStatus, isRouteCircuitOpen, isScheduleSlot, isScheduledAtError, isShippingFeeLine, isStateHash, isStorefrontNotFound, isSupportedWorkflowSchemaVersion, isTerminalFulfillmentStatus, isTerminalMappedStatus, isTlsFingerprintMismatchError, isVariantBase, linePayableTotal, listMenusStream, listSecretKeys, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, markRouteDown, markRouteHealthy, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCertFingerprint, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizeMaxIncompleteMinutes, normalizePickupName, normalizeStateScope, onOriginChange, onRouteHealth, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, pauseForAdvance, paymentMatchesClientConditions, pendingWebhooksOf, pickAdvanceTarget, pickLocalizedText, pickMultiLanguageText, placeCartLines, probeLocalRouteHealth, processStateNode, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, resolveAdvanceEdge, resolveAdvanceEdges, resolveCallbackFailTerminal, resolveCheckout, resolveFailureTerminalEdge, resolveLocalPins, resolveLocalRouteUrl, resolveModifierImageUrl, resolveOrderRouteEligibility, resolvePaymentEligibility, resolveSchedulePrepMinutes, resolveSdkPaymentEligibilityCeiling, resolveSuccessTerminalEdges, resolveWebhookTargetUrl, resumeFromAdvance, reversePayment, reversedWhenCaptured, roundFeeAmount, runIsTerminal, runNodeCallbacks, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, scheduledSuccessorStatus, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, settleEnter, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, syncDeviceSecrets, testLocalServerHealth, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyLocalRoutePin, verifyWebhookSignature, visitedStates, warnNoEdge, workflowSchemaVersionOf };
|
|
4348
|
+
export { type AdvanceAndEnterConfig, type AdvanceAndEnterResult, type ApplyRedeemInput, type AuthConfigureOptions, type BuildRouteHttpInput, type BuildScheduleSlotsConfig, CALLBACK_MISSING_LOCAL_URL, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, type CallbackMissingLocalUrlDetails, type CanonicalInput, type CanonicalizationError, type CanonicalizationErrorCode, type CardBrand, type CardBrandSpec, type CardCvcError, type CardExpiry, type CardExpiryError, type CardNumberError, type CardPreviewSlot, type CardholderNameError, type CmsBlockScope, type CmsVisibilityBlock, type CmsVisibilityContext, type CmsVisibilityRules, type ComputeProductRewardSavingsInput, type CreateOrderOptions, type CreateSessionOptions, type CustomizationPath, type CustomizationSession, DEFAULT_LOCALE, DEFAULT_MAX_INCOMPLETE_MINUTES, DEFAULT_MAX_SNAPSHOT_AGE_MS, DEFAULT_RECOMMENDATION_TYPES, DEFAULT_ROUTE_COOLDOWN_MS, DEFAULT_WEBHOOK_TIMEOUT_S, DelegatedSessionExpiredError, type DeunaCallbackUrls, type DeunaOrderStatus, type DeviceSecretStorage, type DeviceSecretsConfigureOptions, type DeviceSecretsPayload, type DeviceSecretsStore, type DispatchWebhooksConfig, type EngineCallbackRun, type EngineCallbackRunError, type EngineExecutionContext, type EngineFlagReviewInput, type EngineFulfillmentPatch, type EngineOrder, type EngineOrderChangedEvent, type EngineOrderFulfillment, type EngineOrderStatus, type EngineOrderStatusPatch, type EngineScope, type EngineStepLog, type EngineStepLogEntry, type EngineStepsLogs, type EngineWebhookEnvelope, type EngineWebhookFailureEvent, type EngineWebhookNodeRun, type EngineWebhookTarget, type EnterAndPauseResult, type EnterRunResult, type ExchangeOptions, FULFILLMENT_WORKFLOW_TERMINAL_STATUSES, type FailedCharge, type FinalizePlaceOrderConfig, type FiresparkOrigin, type FlatMenuCategory, type FulfillmentEligibilityInput, type FulfillmentExecutionPort, type FulfillmentPorts, type FulfillmentRunStatus, type FulfillmentStepName, type FulfillmentStoragePort, type FulfillmentTerminalOrderStatus, type GenOrderIdOptions, type GetCmsBlockOptions, type GroupDisplayType, HPKE_ALG, type HpkeAead, type HpkeEnvelope, type HpkeOpenInput, type HpkePrivateJwk, type HpkePublicJwk, type HpkeSealInput, ID_HASH_FORMATS, type IdBuilder, type IdHashFormat, type InvokeCallbackAttemptConfig, type InvokeCallbackAttemptResult, type ListMenusStreamOptions, type ListPaymentsOptions, type LocalDeviceCredentials, type LocalRouteProbeResult, type LocalServerConfig, type LocalServerHealthResult, LosslessNumber, type LosslessNumberLike, MAX_MAX_INCOMPLETE_MINUTES, MAX_SUPPORTED_WORKFLOW_SCHEMA_VERSION, MIN_MAX_INCOMPLETE_MINUTES, MODE_HINT_HEADER, type MarkRouteDownInput, type Menu, type MenuCategoryNode, type MenuLookup, type MilestoneSteps, type MilestoneTrackItem, type ModifierControlType, type ModifierCtx, type ModifierGroupCtx, type NestedMenuCategory, OFFLINE_NO_LOCAL_URL, ORIGIN_HEADER, Order, OrderAuthPinnedError, type OrderCancelInput, type OrderCancelOptions, type OrderCancelResult, type OrderCancelType, type OrderCustomerSource, type OrderDeviceCredential, type OrderDraft, type OrderIssue, type OrderIssueCode, type OrderLineDiff, type OrderLineIssue, type OrderLineIssueCode, OrderNotOpenError, OrderPaymentRequiredError, type OrderRouteKind, type OrderRouteStatus, OrderRouteUnavailableError, type OrderRoutes, type OrderScope, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, type OrderValidationResult, type OriginListener, type OriginState, type PauseForAdvanceConfig, type PayIntentOptions, type PayIntentResult, type PayOptions, type PaymentCardBrand, type PaymentEligibilityInput, type PaymentProgressEvent, type PaymentProgressListener, type PaymentRunOptions, type PaymentSessionOptions, type PendingWebhooks, PickupNameIssue, type PinnedFetchFactory, type PinnedFetchOptions, type PosOrderHttpOptions, type PricingModifier, type ProbeLocalRouteHealthOptions, type ProcessStateNodeCallbackJob, type ProcessStateNodeConfig, type ProcessStateNodeResult, type Product, type ProductCtx, type QuantitiesByPath, RESERVED_FULFILLMENT_STATUSES, REWARD_SAVINGS_METADATA_KEY, type RecommendationType, RecurringDateCron, type RedeemPaymentRow, type RemoveRedeemInput, type ReorderOrderOptions, type ResetOptions, type ResolveRouteEligibilityInput, type ResolvedPaymentEligibility, type ResumeFromAdvanceConfig, type ReversalOutcome, type ReverseAllOptions, type RouteEligibility, type RouteEligibilityDetail, type RouteEligibilityFlags, type RouteEligibilityReason, type RouteFailureClassification, type RouteFailureKind, type RouteHealthEvent, type RouteHealthListener, type RouteHealthSnapshot, type RouteTenderCandidate, RulesEngine, type RunNodeCallbacksResult, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, SCHEDULED_STATUS, SDK_PAYMENT_ELIGIBILITY_CEILINGS, STATE_ALGO, STATE_HASH_PREFIX, type ScheduleSlot, type ScheduleSlotCart, type ScheduleSlotCartLine, type ScheduleWindow, type ScheduledSuccessorConfig, type SdkPaymentEligibility, type SelectionStatus, type SelectionsByPath, type SerializedError, type ServiceHttpOptions, type SimpleTenderPayment, type Snapshot, type StateGoldenRootVector, type StateGoldenVector, type StateGoldenVectors, type StateManifest, type StateManifestSection, type StateRootInput, type StateScope, type StateVectorFailure, type StepOutcome, type StorefrontAccessToken, type StorefrontErrorDetails, StorefrontHttpError, type SwitchCustomerArg, type SwitchCustomerIdToken, type SwitchCustomerOptions, type SwitchCustomerResult, TLS_FINGERPRINT_RESPONSE_HEADER, TLS_PIN_HEADER, type TestLocalServerHealthOptions, TlsFingerprintMismatchError, TokenExchangeError, type TrackWorkflow, type ValidateOptions, type ValidateOrderAgainstMenuInput, type Variant, type VariantGroup, type VariantGroupCtx, type VariantOptionCtx, type VariantSelection, type VerifyWebhookSignatureInput, type VisitedState, WORKFLOW_SCHEMA_VERSION, WORKFLOW_TIMEOUT, WorkflowSchemaVersionError, type WorkflowTimeoutDetails, addLines, advanceAndEnter, appendEngineStepLog, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, applyRewardSavingsToLines, assertSupportedWorkflowSchemaVersion, auth, autoEnterSuccessTerminal, base64UrlDecode, base64UrlEncode, beginEngineStepLog, buildCustomerSnapshot, buildEngineCallbackError, buildEngineCallbackRun, buildRouteHttpOptions, buildRulesEngineFromOrder, buildScheduleSlots, buildWorkflowTimeoutDetails, callbackIdsFromNode, canEnterJoin, canPauseNow, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, certFingerprintsMatch, certMatchesAnyPin, classifyRouteFailure, clearDeviceSecrets, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, completeEngineStepLog, computeOrderExpiresAt, computeProductRewardSavings, computeStartingPrice, configureDeviceSecrets, configureLocalTlsPinning, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createDeviceSecretsStore, createNodePinnedFetch, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultIsPaymentCaptured, defaultOutgoingEdge, defaultWebhookEventsForStatus, defaultWebhookRetryDelayMs, detectCardBrand, dispatchOrderWebhooks, dispatchPendingWebhooks, engineHmacSha256Hex, engineOrderStatusForFailedRun, engineWebhookDeliveryId, engineWebhookRunsForEnteredNodes, engineWebhookStatusKey, engineWebhookTransitionStates, enterAndPause, enterWorkflowNode, executeAdvance, executeScheduledWake, executeStart, failActiveEngineStepLog, finalizePlaceOrder, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findShippingFeeLine, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatLocalServerUrl, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLineRewardSavings, getLocalTlsPinning, getLogContext, getOrigin, getRouteHealth, getScheduleWindow, getSecret, hasInFlightPayment, hasLocalTlsPinning, hasSmartRouting, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, injectingMetadataFromCallback, invokeCallbackAttempt, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeliveryFee, isDeviceCharged, isDeviceNotLinked, isExpiredFulfillment, isExpiryComplete, isGenId, isInterruptTerminalStatus, isKioskUnauthorized, isLocalOrderUnknown, isMilestoneStepDone, isNodeRuntime, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderRouteUnavailableError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isReservedFulfillmentStatus, isRouteCircuitOpen, isScheduleSlot, isScheduledAtError, isShippingFeeLine, isStateHash, isStorefrontNotFound, isSupportedWorkflowSchemaVersion, isTerminalFulfillmentStatus, isTerminalMappedStatus, isTlsFingerprintMismatchError, isVariantBase, lineCartValue, linePayableTotal, listMenusStream, listSecretKeys, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, markRouteDown, markRouteHealthy, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCertFingerprint, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizeMaxIncompleteMinutes, normalizePickupName, normalizeStateScope, onOriginChange, onRouteHealth, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, pauseForAdvance, paymentMatchesClientConditions, pendingWebhooksOf, pickAdvanceTarget, pickLocalizedText, pickMultiLanguageText, placeCartLines, probeLocalRouteHealth, processStateNode, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, rescaleLineRewardSavings, resolveAdvanceEdge, resolveAdvanceEdges, resolveCallbackFailTerminal, resolveCheckout, resolveFailureTerminalEdge, resolveLocalPins, resolveLocalRouteUrl, resolveModifierImageUrl, resolveOrderRouteEligibility, resolvePaymentEligibility, resolveSchedulePrepMinutes, resolveSdkPaymentEligibilityCeiling, resolveSuccessTerminalEdges, resolveWebhookTargetUrl, resumeFromAdvance, reversePayment, reversedWhenCaptured, roundFeeAmount, runIsTerminal, runNodeCallbacks, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, scheduledSuccessorStatus, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, settleEnter, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, syncDeviceSecrets, testLocalServerHealth, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyLocalRoutePin, verifyWebhookSignature, visitedStates, warnNoEdge, withLineRewardSavings, workflowSchemaVersionOf };
|
package/dist/index.js
CHANGED
|
@@ -4592,6 +4592,7 @@ const SDK_PAYMENT_ELIGIBILITY_CEILINGS = {
|
|
|
4592
4592
|
"cardvault:CARD": CLOUD_ONLY,
|
|
4593
4593
|
"kushki:CARD": CLOUD_ONLY,
|
|
4594
4594
|
"kushki:WALLET": CLOUD_ONLY,
|
|
4595
|
+
"kushki:BANK_TRANSFER": CLOUD_ONLY,
|
|
4595
4596
|
"yape:BANK_TRANSFER": CLOUD_ONLY
|
|
4596
4597
|
};
|
|
4597
4598
|
const ceilingKey = (providerId, method) => {
|
|
@@ -8094,6 +8095,108 @@ const computeLineFingerprint = (root, lines) => {
|
|
|
8094
8095
|
return `${root.id}[${childKeys(root.uid)}]`;
|
|
8095
8096
|
};
|
|
8096
8097
|
//#endregion
|
|
8098
|
+
//#region src/order/rewardSavings.ts
|
|
8099
|
+
const REWARD_SAVINGS_METADATA_KEY = "reward_savings";
|
|
8100
|
+
const isNonNegativeFinite = (value) => {
|
|
8101
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
8102
|
+
};
|
|
8103
|
+
const isRecord = (value) => {
|
|
8104
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
8105
|
+
};
|
|
8106
|
+
/**
|
|
8107
|
+
* Cart value of a root line for Masivo product-reward savings comparison.
|
|
8108
|
+
* Matches `masivoContacts.payload` (`group_subtotal`, else `group_total`).
|
|
8109
|
+
*/
|
|
8110
|
+
const lineCartValue = (line) => {
|
|
8111
|
+
if (Number.isFinite(line.group_subtotal)) return line.group_subtotal;
|
|
8112
|
+
return line.group_total;
|
|
8113
|
+
};
|
|
8114
|
+
/**
|
|
8115
|
+
* Informational Masivo product-reward savings:
|
|
8116
|
+
* `full_price_total = full_price * quantity`
|
|
8117
|
+
* `savings = max(0, full_price * quantity - lineValue)`
|
|
8118
|
+
* Exact Big.js arithmetic, never rounded.
|
|
8119
|
+
*/
|
|
8120
|
+
const computeProductRewardSavings = (input) => {
|
|
8121
|
+
const { fullPrice, quantity, lineValue } = input;
|
|
8122
|
+
const fullBig = new Big(String(fullPrice));
|
|
8123
|
+
const fullTotalBig = fullBig.times(String(quantity));
|
|
8124
|
+
const diff = fullTotalBig.minus(String(lineValue));
|
|
8125
|
+
const savingsBig = diff.gt(0) ? diff : new Big(0);
|
|
8126
|
+
return {
|
|
8127
|
+
full_price: fullBig.toNumber(),
|
|
8128
|
+
full_price_total: fullTotalBig.toNumber(),
|
|
8129
|
+
savings: savingsBig.toNumber()
|
|
8130
|
+
};
|
|
8131
|
+
};
|
|
8132
|
+
/** Reads informational `reward_savings` from `line.metadata`, or null. */
|
|
8133
|
+
const getLineRewardSavings = (line) => {
|
|
8134
|
+
const meta = line?.metadata;
|
|
8135
|
+
if (!isRecord(meta)) return null;
|
|
8136
|
+
const raw = meta[REWARD_SAVINGS_METADATA_KEY];
|
|
8137
|
+
if (!isRecord(raw)) return null;
|
|
8138
|
+
const { full_price, full_price_total, savings } = raw;
|
|
8139
|
+
if (!isNonNegativeFinite(full_price)) return null;
|
|
8140
|
+
if (!isNonNegativeFinite(full_price_total)) return null;
|
|
8141
|
+
if (!isNonNegativeFinite(savings)) return null;
|
|
8142
|
+
return {
|
|
8143
|
+
full_price,
|
|
8144
|
+
full_price_total,
|
|
8145
|
+
savings
|
|
8146
|
+
};
|
|
8147
|
+
};
|
|
8148
|
+
/** Attaches or removes `metadata.reward_savings` without mutating totals. */
|
|
8149
|
+
const withLineRewardSavings = (line, savings) => {
|
|
8150
|
+
const prev = isRecord(line.metadata) ? line.metadata : {};
|
|
8151
|
+
if (!savings) {
|
|
8152
|
+
if (!("reward_savings" in prev)) return line;
|
|
8153
|
+
const { [REWARD_SAVINGS_METADATA_KEY]: _drop, ...rest } = prev;
|
|
8154
|
+
return {
|
|
8155
|
+
...line,
|
|
8156
|
+
metadata: rest
|
|
8157
|
+
};
|
|
8158
|
+
}
|
|
8159
|
+
const metadata = {
|
|
8160
|
+
...prev,
|
|
8161
|
+
[REWARD_SAVINGS_METADATA_KEY]: savings
|
|
8162
|
+
};
|
|
8163
|
+
return {
|
|
8164
|
+
...line,
|
|
8165
|
+
metadata
|
|
8166
|
+
};
|
|
8167
|
+
};
|
|
8168
|
+
/** Recomputes `full_price_total` and `savings` after a line quantity change. */
|
|
8169
|
+
const rescaleLineRewardSavings = (line) => {
|
|
8170
|
+
const current = getLineRewardSavings(line);
|
|
8171
|
+
if (!current) return line;
|
|
8172
|
+
const fullPrice = current.full_price;
|
|
8173
|
+
const quantity = line.quantity;
|
|
8174
|
+
const lineValue = lineCartValue(line);
|
|
8175
|
+
const next = computeProductRewardSavings({
|
|
8176
|
+
fullPrice,
|
|
8177
|
+
quantity,
|
|
8178
|
+
lineValue
|
|
8179
|
+
});
|
|
8180
|
+
return withLineRewardSavings(line, next);
|
|
8181
|
+
};
|
|
8182
|
+
/** Applies a `line.uid -> ProductRewardSavings` map to matching lines. */
|
|
8183
|
+
const applyRewardSavingsToLines = (lines, byLineUid) => {
|
|
8184
|
+
if (!byLineUid || Object.keys(byLineUid).length === 0) return lines;
|
|
8185
|
+
let changed = false;
|
|
8186
|
+
const next = lines.map((line) => {
|
|
8187
|
+
const savings = byLineUid[line.uid];
|
|
8188
|
+
if (!savings) return line;
|
|
8189
|
+
const existing = getLineRewardSavings(line);
|
|
8190
|
+
const sameFull = existing?.full_price === savings.full_price;
|
|
8191
|
+
const sameTotal = existing?.full_price_total === savings.full_price_total;
|
|
8192
|
+
const sameSavings = existing?.savings === savings.savings;
|
|
8193
|
+
if (sameFull && sameTotal && sameSavings) return line;
|
|
8194
|
+
changed = true;
|
|
8195
|
+
return withLineRewardSavings(line, savings);
|
|
8196
|
+
});
|
|
8197
|
+
return changed ? next : lines;
|
|
8198
|
+
};
|
|
8199
|
+
//#endregion
|
|
8097
8200
|
//#region src/order/lines.ts
|
|
8098
8201
|
const removeSubtree = (lines, rootUid) => {
|
|
8099
8202
|
const drop = /* @__PURE__ */ new Set([rootUid]);
|
|
@@ -8133,11 +8236,11 @@ const scaleLineQuantity = (line, nextQty) => {
|
|
|
8133
8236
|
group_tax_total: gTax,
|
|
8134
8237
|
group_total: gTot
|
|
8135
8238
|
};
|
|
8136
|
-
return {
|
|
8239
|
+
return rescaleLineRewardSavings({
|
|
8137
8240
|
...b1,
|
|
8138
8241
|
...b2,
|
|
8139
8242
|
...b3
|
|
8140
|
-
};
|
|
8243
|
+
});
|
|
8141
8244
|
};
|
|
8142
8245
|
const collectDescendantUids = (lines, rootUid) => {
|
|
8143
8246
|
const uids = /* @__PURE__ */ new Set([rootUid]);
|
|
@@ -10529,7 +10632,7 @@ var Order = class Order {
|
|
|
10529
10632
|
*/
|
|
10530
10633
|
applyRedeem(input) {
|
|
10531
10634
|
if (this.deleted) return;
|
|
10532
|
-
const { line_uid, provider, ...rest } = input;
|
|
10635
|
+
const { line_uid, provider, full_price, ...rest } = input;
|
|
10533
10636
|
const redeem = buildRedeem(rest);
|
|
10534
10637
|
if (redeem.type === "PRODUCT" && line_uid === void 0) throw new Error("Product reward requires a root product line");
|
|
10535
10638
|
if (provider) this.redemptionProviders.set(redeem.payment_id, provider);
|
|
@@ -10544,12 +10647,21 @@ var Order = class Order {
|
|
|
10544
10647
|
throw new Error(msg);
|
|
10545
10648
|
}
|
|
10546
10649
|
if (redeem.type === "PRODUCT" && line.type !== "PRODUCT") throw new Error("Product reward requires a root product line");
|
|
10650
|
+
const hasFullPrice = redeem.type === "PRODUCT" && typeof full_price === "number" && Number.isFinite(full_price) && full_price >= 0;
|
|
10547
10651
|
const lines = this.draft.lines.map((item) => {
|
|
10548
10652
|
if (item.uid !== line_uid) return item;
|
|
10549
|
-
|
|
10653
|
+
const updated = {
|
|
10550
10654
|
...item,
|
|
10551
10655
|
redeem: [...item.redeem ?? [], redeem]
|
|
10552
10656
|
};
|
|
10657
|
+
if (!hasFullPrice) return updated;
|
|
10658
|
+
const fullPrice = full_price;
|
|
10659
|
+
const quantity = updated.quantity;
|
|
10660
|
+
return withLineRewardSavings(updated, computeProductRewardSavings({
|
|
10661
|
+
fullPrice,
|
|
10662
|
+
quantity,
|
|
10663
|
+
lineValue: lineCartValue(updated)
|
|
10664
|
+
}));
|
|
10553
10665
|
});
|
|
10554
10666
|
this.commitLines({ lines });
|
|
10555
10667
|
}
|
|
@@ -10573,15 +10685,17 @@ var Order = class Order {
|
|
|
10573
10685
|
}
|
|
10574
10686
|
const lines = this.draft.lines.map((item) => {
|
|
10575
10687
|
if (item.uid !== line_uid) return item;
|
|
10576
|
-
const
|
|
10688
|
+
const nextRedeem = subtractRedeem(...[
|
|
10577
10689
|
item.redeem ?? [],
|
|
10578
10690
|
reward_id,
|
|
10579
10691
|
quantity
|
|
10580
|
-
];
|
|
10581
|
-
|
|
10692
|
+
]);
|
|
10693
|
+
const updated = {
|
|
10582
10694
|
...item,
|
|
10583
|
-
redeem:
|
|
10695
|
+
redeem: nextRedeem
|
|
10584
10696
|
};
|
|
10697
|
+
if (nextRedeem.some((r) => r.type === "PRODUCT")) return updated;
|
|
10698
|
+
return withLineRewardSavings(updated, null);
|
|
10585
10699
|
});
|
|
10586
10700
|
this.commitLines({ lines });
|
|
10587
10701
|
}
|
|
@@ -10832,7 +10946,9 @@ var Order = class Order {
|
|
|
10832
10946
|
...b4,
|
|
10833
10947
|
...b5
|
|
10834
10948
|
};
|
|
10835
|
-
await services.orders.validate(body, this.activeHttp());
|
|
10949
|
+
const res = await services.orders.validate(body, this.activeHttp());
|
|
10950
|
+
const nextLines = applyRewardSavingsToLines(this.draft.lines, res.reward_savings);
|
|
10951
|
+
if (nextLines !== this.draft.lines) this.commitLines({ lines: nextLines });
|
|
10836
10952
|
}
|
|
10837
10953
|
/**
|
|
10838
10954
|
* Tenders of the next intent: one REDEMPTION per `payment_id` that
|
|
@@ -17976,4 +18092,4 @@ const hpkeOpen = async (input) => {
|
|
|
17976
18092
|
return new Uint8Array(opened);
|
|
17977
18093
|
};
|
|
17978
18094
|
//#endregion
|
|
17979
|
-
export { CALLBACK_MISSING_LOCAL_URL, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, DEFAULT_LOCALE, DEFAULT_MAX_INCOMPLETE_MINUTES, DEFAULT_MAX_SNAPSHOT_AGE_MS, DEFAULT_RECOMMENDATION_TYPES, DEFAULT_ROUTE_COOLDOWN_MS, DEFAULT_WEBHOOK_TIMEOUT_S, DelegatedSessionExpiredError, FULFILLMENT_WORKFLOW_TERMINAL_STATUSES, HPKE_ALG, ID_HASH_FORMATS, LosslessNumber, MAX_MAX_INCOMPLETE_MINUTES, MAX_SUPPORTED_WORKFLOW_SCHEMA_VERSION, MIN_MAX_INCOMPLETE_MINUTES, MODE_HINT_HEADER, OFFLINE_NO_LOCAL_URL, ORIGIN_HEADER, Order, OrderAuthPinnedError, OrderNotOpenError, OrderPaymentRequiredError, OrderRouteUnavailableError, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, RESERVED_FULFILLMENT_STATUSES, RecurringDateCron, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, SCHEDULED_STATUS, SDK_PAYMENT_ELIGIBILITY_CEILINGS, STATE_ALGO, STATE_HASH_PREFIX, StorefrontHttpError, TLS_FINGERPRINT_RESPONSE_HEADER, TLS_PIN_HEADER, TlsFingerprintMismatchError, TokenExchangeError, WORKFLOW_SCHEMA_VERSION, WORKFLOW_TIMEOUT, WorkflowSchemaVersionError, addLines, advanceAndEnter, appendEngineStepLog, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, assertSupportedWorkflowSchemaVersion, auth, autoEnterSuccessTerminal, base64UrlDecode, base64UrlEncode, beginEngineStepLog, buildCustomerSnapshot, buildEngineCallbackError, buildEngineCallbackRun, buildRouteHttpOptions, buildRulesEngineFromOrder, buildScheduleSlots, buildWorkflowTimeoutDetails, callbackIdsFromNode, canEnterJoin, canPauseNow, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, certFingerprintsMatch, certMatchesAnyPin, classifyRouteFailure, clearDeviceSecrets, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, completeEngineStepLog, computeOrderExpiresAt, computeStartingPrice, configureDeviceSecrets, configureLocalTlsPinning, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createDeviceSecretsStore, createNodePinnedFetch, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultIsPaymentCaptured, defaultOutgoingEdge, defaultWebhookEventsForStatus, defaultWebhookRetryDelayMs, detectCardBrand, dispatchOrderWebhooks, dispatchPendingWebhooks, engineHmacSha256Hex, engineOrderStatusForFailedRun, engineWebhookDeliveryId, engineWebhookRunsForEnteredNodes, engineWebhookStatusKey, engineWebhookTransitionStates, enterAndPause, enterWorkflowNode, executeAdvance, executeScheduledWake, executeStart, failActiveEngineStepLog, finalizePlaceOrder, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findShippingFeeLine, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatLocalServerUrl, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLocalTlsPinning, getLogContext, getOrigin, getRouteHealth, getScheduleWindow, getSecret, hasInFlightPayment, hasLocalTlsPinning, hasSmartRouting, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, injectingMetadataFromCallback, invokeCallbackAttempt, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeliveryFee, isDeviceCharged, isDeviceNotLinked, isExpiredFulfillment, isExpiryComplete, isGenId, isInterruptTerminalStatus, isKioskUnauthorized, isLocalOrderUnknown, isMilestoneStepDone, isNodeRuntime, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderRouteUnavailableError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isReservedFulfillmentStatus, isRouteCircuitOpen, isScheduleSlot, isScheduledAtError, isShippingFeeLine, isStateHash, isStorefrontNotFound, isSupportedWorkflowSchemaVersion, isTerminalFulfillmentStatus, isTerminalMappedStatus, isTlsFingerprintMismatchError, isVariantBase, linePayableTotal, listMenusStream, listSecretKeys, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, markRouteDown, markRouteHealthy, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCertFingerprint, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizeMaxIncompleteMinutes, normalizePickupName, normalizeStateScope, onOriginChange, onRouteHealth, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, pauseForAdvance, paymentMatchesClientConditions, pendingWebhooksOf, pickAdvanceTarget, pickLocalizedText, pickMultiLanguageText, placeCartLines, probeLocalRouteHealth, processStateNode, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, resolveAdvanceEdge, resolveAdvanceEdges, resolveCallbackFailTerminal, resolveCheckout, resolveFailureTerminalEdge, resolveLocalPins, resolveLocalRouteUrl, resolveModifierImageUrl, resolveOrderRouteEligibility, resolvePaymentEligibility, resolveSchedulePrepMinutes, resolveSdkPaymentEligibilityCeiling, resolveSuccessTerminalEdges, resolveWebhookTargetUrl, resumeFromAdvance, reversePayment, reversedWhenCaptured, roundFeeAmount, runIsTerminal, runNodeCallbacks, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, scheduledSuccessorStatus, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, settleEnter, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, syncDeviceSecrets, testLocalServerHealth, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyLocalRoutePin, verifyWebhookSignature, visitedStates, warnNoEdge, workflowSchemaVersionOf };
|
|
18095
|
+
export { CALLBACK_MISSING_LOCAL_URL, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, DEFAULT_LOCALE, DEFAULT_MAX_INCOMPLETE_MINUTES, DEFAULT_MAX_SNAPSHOT_AGE_MS, DEFAULT_RECOMMENDATION_TYPES, DEFAULT_ROUTE_COOLDOWN_MS, DEFAULT_WEBHOOK_TIMEOUT_S, DelegatedSessionExpiredError, FULFILLMENT_WORKFLOW_TERMINAL_STATUSES, HPKE_ALG, ID_HASH_FORMATS, LosslessNumber, MAX_MAX_INCOMPLETE_MINUTES, MAX_SUPPORTED_WORKFLOW_SCHEMA_VERSION, MIN_MAX_INCOMPLETE_MINUTES, MODE_HINT_HEADER, OFFLINE_NO_LOCAL_URL, ORIGIN_HEADER, Order, OrderAuthPinnedError, OrderNotOpenError, OrderPaymentRequiredError, OrderRouteUnavailableError, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, RESERVED_FULFILLMENT_STATUSES, REWARD_SAVINGS_METADATA_KEY, RecurringDateCron, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, SCHEDULED_STATUS, SDK_PAYMENT_ELIGIBILITY_CEILINGS, STATE_ALGO, STATE_HASH_PREFIX, StorefrontHttpError, TLS_FINGERPRINT_RESPONSE_HEADER, TLS_PIN_HEADER, TlsFingerprintMismatchError, TokenExchangeError, WORKFLOW_SCHEMA_VERSION, WORKFLOW_TIMEOUT, WorkflowSchemaVersionError, addLines, advanceAndEnter, appendEngineStepLog, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, applyRewardSavingsToLines, assertSupportedWorkflowSchemaVersion, auth, autoEnterSuccessTerminal, base64UrlDecode, base64UrlEncode, beginEngineStepLog, buildCustomerSnapshot, buildEngineCallbackError, buildEngineCallbackRun, buildRouteHttpOptions, buildRulesEngineFromOrder, buildScheduleSlots, buildWorkflowTimeoutDetails, callbackIdsFromNode, canEnterJoin, canPauseNow, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, certFingerprintsMatch, certMatchesAnyPin, classifyRouteFailure, clearDeviceSecrets, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, completeEngineStepLog, computeOrderExpiresAt, computeProductRewardSavings, computeStartingPrice, configureDeviceSecrets, configureLocalTlsPinning, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createDeviceSecretsStore, createNodePinnedFetch, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultIsPaymentCaptured, defaultOutgoingEdge, defaultWebhookEventsForStatus, defaultWebhookRetryDelayMs, detectCardBrand, dispatchOrderWebhooks, dispatchPendingWebhooks, engineHmacSha256Hex, engineOrderStatusForFailedRun, engineWebhookDeliveryId, engineWebhookRunsForEnteredNodes, engineWebhookStatusKey, engineWebhookTransitionStates, enterAndPause, enterWorkflowNode, executeAdvance, executeScheduledWake, executeStart, failActiveEngineStepLog, finalizePlaceOrder, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findShippingFeeLine, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatLocalServerUrl, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLineRewardSavings, getLocalTlsPinning, getLogContext, getOrigin, getRouteHealth, getScheduleWindow, getSecret, hasInFlightPayment, hasLocalTlsPinning, hasSmartRouting, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, injectingMetadataFromCallback, invokeCallbackAttempt, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeliveryFee, isDeviceCharged, isDeviceNotLinked, isExpiredFulfillment, isExpiryComplete, isGenId, isInterruptTerminalStatus, isKioskUnauthorized, isLocalOrderUnknown, isMilestoneStepDone, isNodeRuntime, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderRouteUnavailableError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isReservedFulfillmentStatus, isRouteCircuitOpen, isScheduleSlot, isScheduledAtError, isShippingFeeLine, isStateHash, isStorefrontNotFound, isSupportedWorkflowSchemaVersion, isTerminalFulfillmentStatus, isTerminalMappedStatus, isTlsFingerprintMismatchError, isVariantBase, lineCartValue, linePayableTotal, listMenusStream, listSecretKeys, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, markRouteDown, markRouteHealthy, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCertFingerprint, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizeMaxIncompleteMinutes, normalizePickupName, normalizeStateScope, onOriginChange, onRouteHealth, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, pauseForAdvance, paymentMatchesClientConditions, pendingWebhooksOf, pickAdvanceTarget, pickLocalizedText, pickMultiLanguageText, placeCartLines, probeLocalRouteHealth, processStateNode, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, rescaleLineRewardSavings, resolveAdvanceEdge, resolveAdvanceEdges, resolveCallbackFailTerminal, resolveCheckout, resolveFailureTerminalEdge, resolveLocalPins, resolveLocalRouteUrl, resolveModifierImageUrl, resolveOrderRouteEligibility, resolvePaymentEligibility, resolveSchedulePrepMinutes, resolveSdkPaymentEligibilityCeiling, resolveSuccessTerminalEdges, resolveWebhookTargetUrl, resumeFromAdvance, reversePayment, reversedWhenCaptured, roundFeeAmount, runIsTerminal, runNodeCallbacks, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, scheduledSuccessorStatus, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, settleEnter, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, syncDeviceSecrets, testLocalServerHealth, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyLocalRoutePin, verifyWebhookSignature, visitedStates, warnNoEdge, withLineRewardSavings, workflowSchemaVersionOf };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fire-spark/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.46.1",
|
|
4
4
|
"description": "Fire Spark headless SDK",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -20,8 +20,8 @@
|
|
|
20
20
|
"big.js": "6.2.1",
|
|
21
21
|
"dayjs": "1.11.9",
|
|
22
22
|
"@types/big.js": "6.2.2",
|
|
23
|
-
"@fire-spark/payments": "^0.
|
|
24
|
-
"@fire-spark/types": "^0.
|
|
23
|
+
"@fire-spark/payments": "^0.46.1",
|
|
24
|
+
"@fire-spark/types": "^0.46.1"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"tsdown": "^0.22.14",
|