@final-commerce/common 2.12.0-staging.1 → 2.12.0-staging.3

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.mts CHANGED
@@ -1783,6 +1783,16 @@ declare const shortestMinutesOf: ({ count, unit }: BookingDuration) => number;
1783
1783
  declare const longestMinutesOf: ({ count, unit }: BookingDuration) => number;
1784
1784
  declare const durationText: ({ count, unit }: BookingDuration) => string;
1785
1785
 
1786
+ interface BookingRentalEnd {
1787
+ periods: number;
1788
+ endAt: string;
1789
+ lastDayKey: string;
1790
+ coveredSlots: {
1791
+ startAt: string;
1792
+ dayKey: string;
1793
+ }[];
1794
+ }
1795
+
1786
1796
  declare const DEFAULT_HOLD_MINUTES = 10;
1787
1797
  interface PlanWindowInput {
1788
1798
  rule: BookingRulesInput;
@@ -1810,6 +1820,14 @@ declare function windowForPeriods({ rule, timeZone, startAt, periods, now }: Win
1810
1820
  startAt: Date;
1811
1821
  endAt: Date;
1812
1822
  };
1823
+ interface RentalEndsInput {
1824
+ rule: BookingRulesInput;
1825
+ timeZone: string;
1826
+ startAt: Date;
1827
+ now: Date;
1828
+ untilDay: string;
1829
+ }
1830
+ declare function rentalEnds(input: RentalEndsInput): BookingRentalEnd[];
1813
1831
  interface PlanCourseInput {
1814
1832
  rule: BookingRulesInput;
1815
1833
  timeZone: string;
@@ -1863,6 +1881,7 @@ interface BookingOccupancy {
1863
1881
  qty: number;
1864
1882
  startAt: Date;
1865
1883
  bufferEndAt: Date;
1884
+ outletId?: string;
1866
1885
  }
1867
1886
  interface BookingResourceInput {
1868
1887
  id: string;
@@ -1900,6 +1919,7 @@ interface AvailabilityInput {
1900
1919
  rule: BookingRulesInput;
1901
1920
  resources: BookingResourceInput[];
1902
1921
  occupied: BookingOccupancy[];
1922
+ outletId?: string;
1903
1923
  from: Date;
1904
1924
  to: Date;
1905
1925
  now: Date;
@@ -1910,12 +1930,13 @@ declare function occupancyIn(occupied: BookingOccupancy[], productId: string, st
1910
1930
  taken: number;
1911
1931
  foreignProductId?: string;
1912
1932
  };
1933
+ declare function occupiedAtOutlet<T extends BookingOccupancy>(occupied: T[], rule: Pick<BookingRulesInput, 'ratePeriod'>, outletId?: string): T[];
1913
1934
  declare function shopDayKey(instant: Date, timeZone: string): string;
1914
1935
  declare function shopDayRange(fromDayKey: string, count: number, timeZone: string): {
1915
1936
  from: Date;
1916
1937
  to: Date;
1917
1938
  };
1918
- declare function buildAvailability({ productId, bookingRulesId, rule, resources, occupied, from, to, now, timeZone, }: AvailabilityInput): {
1939
+ declare function buildAvailability({ productId, bookingRulesId, rule, resources, occupied: everyOutlet, outletId, from, to, now, timeZone, }: AvailabilityInput): {
1919
1940
  course: ({
1920
1941
  sessions: number;
1921
1942
  alreadyStarted: boolean;
@@ -2158,4 +2179,4 @@ declare const EXPENSE_DEFAULT_CATEGORIES: readonly [{
2158
2179
  }];
2159
2180
  type ExpenseDefaultCategoryKey = (typeof EXPENSE_DEFAULT_CATEGORIES)[number]['key'];
2160
2181
 
2161
- export { ADYEN_JOB_TITLE_ASSOCIATION_TYPES, ADYEN_LEGAL_ENTITY_STATE_PROVINCE_COUNTRIES, ADYEN_NO_TAX_NUMBER_ABSENT_COUNTRIES, ADYEN_ROLLOUT_COUNTRY_CODES, ADYEN_STORE_STATE_PROVINCE_COUNTRIES, ADYEN_TAX_NUMBER_FORMATS, ADYEN_TAX_NUMBER_MIN_LENGTH, AFFIRM_COUNTRY_CODES, AFFIRM_PRICE_PLANS, type AddressLike, type AdyenBnplSettings, type AdyenBnplSkippedStore, type AdyenBnplUpdateResult, type AffirmPricePlan, type Amount, type AssignUserChange, AttributeType, type AvailabilityInput, type AvailabilitySlot, type AvailableTransition, BNPL_METHOD_STATUS, BNPL_SKIP_REASON, type BnplMethodStatus, type BnplSkipReason, type BookingDateRanges, type BookingDuration, type BookingDurationField, type BookingDurationProblem, type BookingDurationProblemKind, BookingDurationUnit, type BookingMethod, type BookingOccupancy, BookingRatePeriod, type BookingResourceInput, BookingResourceKind, BookingResourceStatus, type BookingRuleDurations, type BookingRuleInNewShape, type BookingRuleNewFields, type BookingRuleParts, BookingRulesError, type BookingRulesInput, BookingSessionSale, type BookingTimeSlots, BookingType, type BusyWindow, CANADA_PROVINCES, CONDITION_OPERATORS, COUNTRY_CURRENCIES, CURRENCY_CONFIG, type CartDiscountBucket, type CartFeeBucket, type CashDrawer, type CashRoundingTuple, type CategoryModifierRow, type CategoryRow, CompanyType, type CompositeAvailabilityRows, type CompositeMakeable, type CompositeMakeableRow, type CompositePriceItem, type CompositePricePart, type CompositeReservationOrder, type CompositeShelf, type CompositeStockPart, type Condition, type ConditionGroup, type ConditionOperator, type ConfigUpdatedPayload, type ConfigValidationError, type ConfigValidationResult, type ConfigValidationWarning, type CountryOption, type CrossAxisRequires, type CrossAxisRule, type CrossAxisTrigger, CurrencyCode, type CurrencyConfig, type CurrencyRate, CustomTableAvailability, CustomerPlatform, DEFAULT_CONFIG, DEFAULT_CROSS_AXIS_RULES, DEFAULT_DISPLAY_STATE_MAP, DEFAULT_HOLD_MINUTES, DEFAULT_RESOLVED_CONFIG, DEFAULT_UNIT_ID, type DeleteStateConfigFragmentParams, type DeleteStateConfigFragmentResponse, type DiscountsBreakdown, type DiscountsTuple, type DisplayStateResult, type DisplayStateRule, DualWriteStrategy, EUFixedRates, EUROPE, EVERYWHERE_KEY, EXPENSE_DEFAULT_CATEGORIES, EXPENSE_NAME_MAX_LENGTH, EXPENSE_PAYMENT_METHOD_PRESETS, type EndOfSessionReport, type ExpenseDefaultCategoryKey, ExtensionCategory, FINANCIAL_INVARIANTS, FULFILLMENT_STATES, type FailedCondition, type FeesBreakdown, FeesCustomBillingStatus, type FeesTuple, type FinancialInvariant, type FragmentParam, type FragmentValidationResult, type FulfillmentState, type FulfillmentStateDefinition, type FulfillmentTransitionPath, type GetAvailableTransitionsParams, type GetAvailableTransitionsResponse, type GetOrderDisplayStateParams, type GetOrderDisplayStateResponse, type GetOrderStateConfigParams, type GetOrderStateConfigResponse, type GetStateConfigFragmentParams, type GetStateConfigFragmentResponse, type GridSlot, HttpMethod, InventoryBaseActionEnum, type InventoryBaseActionType, InventorySpecificActionType, InvoiceStatus, LegacyWriteStrategy, LibraryItemType, type LineStockMove, MAX_PRECISION, type Measurable, type MeasurementBase, type MeasurementUnit, type MeasurementUnitFamily, MenuProject, type ModifierChoiceRow, type ModifierRow, type ModifiersBreakdown, type ModifiersTuple, NAFixedRates, NORTH_AMERICA, NonRevenueItemType, type NormalizedAddress, ORDER_STATE_ACTIONS, ORDER_STATE_EVENTS, ORDER_STATE_TOPIC, type OrderContext, type OrderLikeForAssignedUsers, type OrderLikeForContext, type OrderLikeForInCart, type OrderLikeForLegacyInference, type OrderLineItem, type OrderMutationData, type OrderPaymentMethod, OrderPlatform, type OrderRefund, type OrderReservationForContext, type OrderStateEventPayload, type OrderStateWritable, type OrderStatusDefinition, type OrderStatusValidationError, type OrderWriteStrategy, OtherFixedRates, OwnerType, PATH_MODES, PAYMENT_CHANNELS, PAYMENT_STATES, POS_VALID_INITIAL_STATES, type PathMode, type PaymentChannel, PaymentMethod, PaymentProcessor, type PaymentState, type PaymentStateDefinition, type PaymentTransitionPath, type PlanCourseInput, type PlanWindowInput, Platform, type PoolDrawing, PreviewImageMode, PricingLevel, PricingPlanEnum, PricingRegionEnum, ProcessorType, type ProductDiscountBucket, type ProductFeeBucket, ProductSalesChartStep, ProductSalesReportCompare, ProductStatus, ProductType, type Province, PublicationAvailability, type PublicationConfig, PublicationStatus, REGION_MAPPING, REPORT_NEGATE_PATHS, ReceiptSendChannel, ReceiptType, type RefundsBreakdown, ReservationStatus, ResidualPaymentMethod, ResidualStatus, type ResolveInputs, type ResolveShippingInput, type ResolveTemplateResult, type ResourceAvailability, ResourceAvailabilityState, type ResourceInWindow, type ResourcePresenceRow, SHIPPING_COUNTRIES, STATE_SCHEMA, STRIPE_SUPPORTED_COUNTRIES, SYSTEM_FAMILIES, SYSTEM_FAMILY_IDS, SYSTEM_UNITS, SYSTEM_UNIT_IDS, SalesLineAction, SalesLineSourceArray, type SalesSummary, type SaveStateConfigFragmentParams, type SaveStateConfigFragmentResponse, type SettlementBreakdown, type SettlementBuckets, type SettlementCardSection, type SettlementCashSection, type SettlementCustomEntry, ShippingChannel, ShippingNoOptionReason, type ShippingOptionRule, ShippingOptionType, type ShippingPlace, type ShippingPriceTier, type ShippingQuoteOption, ShippingRateType, type ShippingResolution, type ShippingTuple, ShippingZoneError, ShippingZoneKind, type ShippingZoneProblem, type ShippingZoneRule, type SplitPayment, type SplitPaymentPayment, type StaffSales, type StaffSalesEntry, type StateConfig, type StateConfigFragment, type StateDefinition, type StatePair, type StateSchema, type StateTransitionBlockedPayload, type StateTransitionCompletedPayload, StationStatus, type StockLine, type StockLineComponent, type StockReservationLink, type StoredStateConfig, StripeCurrencyCode, StripeStatus, type TaxBreakdown, type TaxBreakdownRateEntry, type TaxBreakdownSection, type TaxBreakdownSubtotal, type TaxesTuple, TimePeriod, type TipEntry, type TipsBreakdown, type TipsTuple, TopMetericsSort, type TransitionBlockedBy, type TransitionConditionSet, type TransitionOrderStateParams, type TransitionOrderStateResponse, type TransitionPath, type TransitionRequest, type TransitionResult, UNLIMITED_PLACES, UserTypes, type WeeklyHours, type WindowForPeriodsInput, addAmounts, addressPlaceKeys, adyenLegalEntityRequiresStateOrProvince, adyenRequiresJobTitle, adyenStoreRequiresStateOrProvince, adyenSupportsTaxNumberAbsent, adyenTaxNumberFormat, allowedDurationUnits, amountToString, ancestorChain, applyAssignment, assertUnitSane, availableIn, baseFor, baseFulfillmentDefinitions, baseOf, basePaymentDefinitions, bookingMethodOf, bookingRuleParts, buildAvailability, buildGrid, buildOrderContext, buildPosPresetConfig, buildResolvedConfig, calculatePercentage, calendarDate, canTransition, capacityOf, cheapestCompositeItem, cheapestCompositePrice, checkPartySize, checkQtyPerBooking, compositeItemCost, compositeItemUnavailable, compositeMakeable, compositeModifierMismatches, compositeReservationMismatches, compositeVariantInStock, conditionSummary, convertFixedFeeToLocalCurrency, courseSessions, courseStarted, courseStartedInZone, createAmount, crossAxisRuleApplies, currentAssignees, deriveDisplayState, deriveFamilyCode, deriveUnitId, displayRuleMatchesPair, divideAmount, durationProblems, durationText, evaluateCondition, evaluateConditionSet, extendPrice, extendPriceFor, fewestFreeOver, formatCurrency, formatInUnit, formatMinorUnitsToString, formatQuantity, fromBase, fromMinorUnits, generateMongoID, getAvailableTransitions, getCashAmountDue, getCountriesByRegion, getCurrencyConfig, getCurrentISODate, getFinancialInvariantViolations, getGoodsPortion, getLineSubtotal, getMinorUnitMultiplier, getMinorUnits, getPaymentLegTotal, getPricingRegionFromCountry, getSettlementTotal, getTotalCollected, hasInCartFlag, hasSellableChoice, holdExpiresAt, inferStatesFromLegacyStatus, isAdyenRolloutCountry, isAffirmCountry, isAffirmPricePlan, isChoiceAvailableAtOutlet, isConditionOperator, isFulfillmentState, isInCart, isPaymentState, isSupportedCurrency, isSystemFamilyCode, isValidQuantity, isWhole, lineStockMoves, listCountries, listProvinces, listShippingCountries, longestMinutesOf, mapToLegacyStatus, maxAdvanceMinutesOf, maxPrecisionFor, mergeFragment, modifiersSellable, multiplyAmount, normalizeAddress, normalizeCityKey, normalizeCountry, normalizeMongoIdString, normalizePostCode, normalizeProvince, occupancyIn, oldMaxAdvanceOf, orderAssignments, parseAmountToMinorUnits, parseCurrencyCode, parseStripeCurrencyCode, pickFreeResource, placeKey, planCourse, planWindow, poolDemand, poolOf, poolShortfall, poolStockAt, postCodeMatchesProvince, presentAt, priceForTotal, provincesForPostCode, removeFragment, resolveFamily, resolveModifiersForProduct, resolveShipping, resolveTemplate, resolveUnit, roundToPrecision, ruleDurationsOf, ruleInNewShape, sameFamily, sessionCells, setOrderState, shipsToCountry, shopDayKey, shopDayRange, shortestMinutesOf, signReportForDisplay, slotsForWindow, soldAsCourse, stringifyMinorUnits, subtractAmounts, toBase, toMinorUnits, validateConfig, validateFragmentCompatibility, validateOrderStatuses, validateShippingZone, violatesFinancialInvariant, windowEndsAt, windowEndsAtInZone, windowForPeriods, withinPresence };
2182
+ export { ADYEN_JOB_TITLE_ASSOCIATION_TYPES, ADYEN_LEGAL_ENTITY_STATE_PROVINCE_COUNTRIES, ADYEN_NO_TAX_NUMBER_ABSENT_COUNTRIES, ADYEN_ROLLOUT_COUNTRY_CODES, ADYEN_STORE_STATE_PROVINCE_COUNTRIES, ADYEN_TAX_NUMBER_FORMATS, ADYEN_TAX_NUMBER_MIN_LENGTH, AFFIRM_COUNTRY_CODES, AFFIRM_PRICE_PLANS, type AddressLike, type AdyenBnplSettings, type AdyenBnplSkippedStore, type AdyenBnplUpdateResult, type AffirmPricePlan, type Amount, type AssignUserChange, AttributeType, type AvailabilityInput, type AvailabilitySlot, type AvailableTransition, BNPL_METHOD_STATUS, BNPL_SKIP_REASON, type BnplMethodStatus, type BnplSkipReason, type BookingDateRanges, type BookingDuration, type BookingDurationField, type BookingDurationProblem, type BookingDurationProblemKind, BookingDurationUnit, type BookingMethod, type BookingOccupancy, BookingRatePeriod, type BookingResourceInput, BookingResourceKind, BookingResourceStatus, type BookingRuleDurations, type BookingRuleInNewShape, type BookingRuleNewFields, type BookingRuleParts, BookingRulesError, type BookingRulesInput, BookingSessionSale, type BookingTimeSlots, BookingType, type BusyWindow, CANADA_PROVINCES, CONDITION_OPERATORS, COUNTRY_CURRENCIES, CURRENCY_CONFIG, type CartDiscountBucket, type CartFeeBucket, type CashDrawer, type CashRoundingTuple, type CategoryModifierRow, type CategoryRow, CompanyType, type CompositeAvailabilityRows, type CompositeMakeable, type CompositeMakeableRow, type CompositePriceItem, type CompositePricePart, type CompositeReservationOrder, type CompositeShelf, type CompositeStockPart, type Condition, type ConditionGroup, type ConditionOperator, type ConfigUpdatedPayload, type ConfigValidationError, type ConfigValidationResult, type ConfigValidationWarning, type CountryOption, type CrossAxisRequires, type CrossAxisRule, type CrossAxisTrigger, CurrencyCode, type CurrencyConfig, type CurrencyRate, CustomTableAvailability, CustomerPlatform, DEFAULT_CONFIG, DEFAULT_CROSS_AXIS_RULES, DEFAULT_DISPLAY_STATE_MAP, DEFAULT_HOLD_MINUTES, DEFAULT_RESOLVED_CONFIG, DEFAULT_UNIT_ID, type DeleteStateConfigFragmentParams, type DeleteStateConfigFragmentResponse, type DiscountsBreakdown, type DiscountsTuple, type DisplayStateResult, type DisplayStateRule, DualWriteStrategy, EUFixedRates, EUROPE, EVERYWHERE_KEY, EXPENSE_DEFAULT_CATEGORIES, EXPENSE_NAME_MAX_LENGTH, EXPENSE_PAYMENT_METHOD_PRESETS, type EndOfSessionReport, type ExpenseDefaultCategoryKey, ExtensionCategory, FINANCIAL_INVARIANTS, FULFILLMENT_STATES, type FailedCondition, type FeesBreakdown, FeesCustomBillingStatus, type FeesTuple, type FinancialInvariant, type FragmentParam, type FragmentValidationResult, type FulfillmentState, type FulfillmentStateDefinition, type FulfillmentTransitionPath, type GetAvailableTransitionsParams, type GetAvailableTransitionsResponse, type GetOrderDisplayStateParams, type GetOrderDisplayStateResponse, type GetOrderStateConfigParams, type GetOrderStateConfigResponse, type GetStateConfigFragmentParams, type GetStateConfigFragmentResponse, type GridSlot, HttpMethod, InventoryBaseActionEnum, type InventoryBaseActionType, InventorySpecificActionType, InvoiceStatus, LegacyWriteStrategy, LibraryItemType, type LineStockMove, MAX_PRECISION, type Measurable, type MeasurementBase, type MeasurementUnit, type MeasurementUnitFamily, MenuProject, type ModifierChoiceRow, type ModifierRow, type ModifiersBreakdown, type ModifiersTuple, NAFixedRates, NORTH_AMERICA, NonRevenueItemType, type NormalizedAddress, ORDER_STATE_ACTIONS, ORDER_STATE_EVENTS, ORDER_STATE_TOPIC, type OrderContext, type OrderLikeForAssignedUsers, type OrderLikeForContext, type OrderLikeForInCart, type OrderLikeForLegacyInference, type OrderLineItem, type OrderMutationData, type OrderPaymentMethod, OrderPlatform, type OrderRefund, type OrderReservationForContext, type OrderStateEventPayload, type OrderStateWritable, type OrderStatusDefinition, type OrderStatusValidationError, type OrderWriteStrategy, OtherFixedRates, OwnerType, PATH_MODES, PAYMENT_CHANNELS, PAYMENT_STATES, POS_VALID_INITIAL_STATES, type PathMode, type PaymentChannel, PaymentMethod, PaymentProcessor, type PaymentState, type PaymentStateDefinition, type PaymentTransitionPath, type PlanCourseInput, type PlanWindowInput, Platform, type PoolDrawing, PreviewImageMode, PricingLevel, PricingPlanEnum, PricingRegionEnum, ProcessorType, type ProductDiscountBucket, type ProductFeeBucket, ProductSalesChartStep, ProductSalesReportCompare, ProductStatus, ProductType, type Province, PublicationAvailability, type PublicationConfig, PublicationStatus, REGION_MAPPING, REPORT_NEGATE_PATHS, ReceiptSendChannel, ReceiptType, type RefundsBreakdown, type RentalEndsInput, ReservationStatus, ResidualPaymentMethod, ResidualStatus, type ResolveInputs, type ResolveShippingInput, type ResolveTemplateResult, type ResourceAvailability, ResourceAvailabilityState, type ResourceInWindow, type ResourcePresenceRow, SHIPPING_COUNTRIES, STATE_SCHEMA, STRIPE_SUPPORTED_COUNTRIES, SYSTEM_FAMILIES, SYSTEM_FAMILY_IDS, SYSTEM_UNITS, SYSTEM_UNIT_IDS, SalesLineAction, SalesLineSourceArray, type SalesSummary, type SaveStateConfigFragmentParams, type SaveStateConfigFragmentResponse, type SettlementBreakdown, type SettlementBuckets, type SettlementCardSection, type SettlementCashSection, type SettlementCustomEntry, ShippingChannel, ShippingNoOptionReason, type ShippingOptionRule, ShippingOptionType, type ShippingPlace, type ShippingPriceTier, type ShippingQuoteOption, ShippingRateType, type ShippingResolution, type ShippingTuple, ShippingZoneError, ShippingZoneKind, type ShippingZoneProblem, type ShippingZoneRule, type SplitPayment, type SplitPaymentPayment, type StaffSales, type StaffSalesEntry, type StateConfig, type StateConfigFragment, type StateDefinition, type StatePair, type StateSchema, type StateTransitionBlockedPayload, type StateTransitionCompletedPayload, StationStatus, type StockLine, type StockLineComponent, type StockReservationLink, type StoredStateConfig, StripeCurrencyCode, StripeStatus, type TaxBreakdown, type TaxBreakdownRateEntry, type TaxBreakdownSection, type TaxBreakdownSubtotal, type TaxesTuple, TimePeriod, type TipEntry, type TipsBreakdown, type TipsTuple, TopMetericsSort, type TransitionBlockedBy, type TransitionConditionSet, type TransitionOrderStateParams, type TransitionOrderStateResponse, type TransitionPath, type TransitionRequest, type TransitionResult, UNLIMITED_PLACES, UserTypes, type WeeklyHours, type WindowForPeriodsInput, addAmounts, addressPlaceKeys, adyenLegalEntityRequiresStateOrProvince, adyenRequiresJobTitle, adyenStoreRequiresStateOrProvince, adyenSupportsTaxNumberAbsent, adyenTaxNumberFormat, allowedDurationUnits, amountToString, ancestorChain, applyAssignment, assertUnitSane, availableIn, baseFor, baseFulfillmentDefinitions, baseOf, basePaymentDefinitions, bookingMethodOf, bookingRuleParts, buildAvailability, buildGrid, buildOrderContext, buildPosPresetConfig, buildResolvedConfig, calculatePercentage, calendarDate, canTransition, capacityOf, cheapestCompositeItem, cheapestCompositePrice, checkPartySize, checkQtyPerBooking, compositeItemCost, compositeItemUnavailable, compositeMakeable, compositeModifierMismatches, compositeReservationMismatches, compositeVariantInStock, conditionSummary, convertFixedFeeToLocalCurrency, courseSessions, courseStarted, courseStartedInZone, createAmount, crossAxisRuleApplies, currentAssignees, deriveDisplayState, deriveFamilyCode, deriveUnitId, displayRuleMatchesPair, divideAmount, durationProblems, durationText, evaluateCondition, evaluateConditionSet, extendPrice, extendPriceFor, fewestFreeOver, formatCurrency, formatInUnit, formatMinorUnitsToString, formatQuantity, fromBase, fromMinorUnits, generateMongoID, getAvailableTransitions, getCashAmountDue, getCountriesByRegion, getCurrencyConfig, getCurrentISODate, getFinancialInvariantViolations, getGoodsPortion, getLineSubtotal, getMinorUnitMultiplier, getMinorUnits, getPaymentLegTotal, getPricingRegionFromCountry, getSettlementTotal, getTotalCollected, hasInCartFlag, hasSellableChoice, holdExpiresAt, inferStatesFromLegacyStatus, isAdyenRolloutCountry, isAffirmCountry, isAffirmPricePlan, isChoiceAvailableAtOutlet, isConditionOperator, isFulfillmentState, isInCart, isPaymentState, isSupportedCurrency, isSystemFamilyCode, isValidQuantity, isWhole, lineStockMoves, listCountries, listProvinces, listShippingCountries, longestMinutesOf, mapToLegacyStatus, maxAdvanceMinutesOf, maxPrecisionFor, mergeFragment, modifiersSellable, multiplyAmount, normalizeAddress, normalizeCityKey, normalizeCountry, normalizeMongoIdString, normalizePostCode, normalizeProvince, occupancyIn, occupiedAtOutlet, oldMaxAdvanceOf, orderAssignments, parseAmountToMinorUnits, parseCurrencyCode, parseStripeCurrencyCode, pickFreeResource, placeKey, planCourse, planWindow, poolDemand, poolOf, poolShortfall, poolStockAt, postCodeMatchesProvince, presentAt, priceForTotal, provincesForPostCode, removeFragment, rentalEnds, resolveFamily, resolveModifiersForProduct, resolveShipping, resolveTemplate, resolveUnit, roundToPrecision, ruleDurationsOf, ruleInNewShape, sameFamily, sessionCells, setOrderState, shipsToCountry, shopDayKey, shopDayRange, shortestMinutesOf, signReportForDisplay, slotsForWindow, soldAsCourse, stringifyMinorUnits, subtractAmounts, toBase, toMinorUnits, validateConfig, validateFragmentCompatibility, validateOrderStatuses, validateShippingZone, violatesFinancialInvariant, windowEndsAt, windowEndsAtInZone, windowForPeriods, withinPresence };
package/dist/index.d.ts CHANGED
@@ -1783,6 +1783,16 @@ declare const shortestMinutesOf: ({ count, unit }: BookingDuration) => number;
1783
1783
  declare const longestMinutesOf: ({ count, unit }: BookingDuration) => number;
1784
1784
  declare const durationText: ({ count, unit }: BookingDuration) => string;
1785
1785
 
1786
+ interface BookingRentalEnd {
1787
+ periods: number;
1788
+ endAt: string;
1789
+ lastDayKey: string;
1790
+ coveredSlots: {
1791
+ startAt: string;
1792
+ dayKey: string;
1793
+ }[];
1794
+ }
1795
+
1786
1796
  declare const DEFAULT_HOLD_MINUTES = 10;
1787
1797
  interface PlanWindowInput {
1788
1798
  rule: BookingRulesInput;
@@ -1810,6 +1820,14 @@ declare function windowForPeriods({ rule, timeZone, startAt, periods, now }: Win
1810
1820
  startAt: Date;
1811
1821
  endAt: Date;
1812
1822
  };
1823
+ interface RentalEndsInput {
1824
+ rule: BookingRulesInput;
1825
+ timeZone: string;
1826
+ startAt: Date;
1827
+ now: Date;
1828
+ untilDay: string;
1829
+ }
1830
+ declare function rentalEnds(input: RentalEndsInput): BookingRentalEnd[];
1813
1831
  interface PlanCourseInput {
1814
1832
  rule: BookingRulesInput;
1815
1833
  timeZone: string;
@@ -1863,6 +1881,7 @@ interface BookingOccupancy {
1863
1881
  qty: number;
1864
1882
  startAt: Date;
1865
1883
  bufferEndAt: Date;
1884
+ outletId?: string;
1866
1885
  }
1867
1886
  interface BookingResourceInput {
1868
1887
  id: string;
@@ -1900,6 +1919,7 @@ interface AvailabilityInput {
1900
1919
  rule: BookingRulesInput;
1901
1920
  resources: BookingResourceInput[];
1902
1921
  occupied: BookingOccupancy[];
1922
+ outletId?: string;
1903
1923
  from: Date;
1904
1924
  to: Date;
1905
1925
  now: Date;
@@ -1910,12 +1930,13 @@ declare function occupancyIn(occupied: BookingOccupancy[], productId: string, st
1910
1930
  taken: number;
1911
1931
  foreignProductId?: string;
1912
1932
  };
1933
+ declare function occupiedAtOutlet<T extends BookingOccupancy>(occupied: T[], rule: Pick<BookingRulesInput, 'ratePeriod'>, outletId?: string): T[];
1913
1934
  declare function shopDayKey(instant: Date, timeZone: string): string;
1914
1935
  declare function shopDayRange(fromDayKey: string, count: number, timeZone: string): {
1915
1936
  from: Date;
1916
1937
  to: Date;
1917
1938
  };
1918
- declare function buildAvailability({ productId, bookingRulesId, rule, resources, occupied, from, to, now, timeZone, }: AvailabilityInput): {
1939
+ declare function buildAvailability({ productId, bookingRulesId, rule, resources, occupied: everyOutlet, outletId, from, to, now, timeZone, }: AvailabilityInput): {
1919
1940
  course: ({
1920
1941
  sessions: number;
1921
1942
  alreadyStarted: boolean;
@@ -2158,4 +2179,4 @@ declare const EXPENSE_DEFAULT_CATEGORIES: readonly [{
2158
2179
  }];
2159
2180
  type ExpenseDefaultCategoryKey = (typeof EXPENSE_DEFAULT_CATEGORIES)[number]['key'];
2160
2181
 
2161
- export { ADYEN_JOB_TITLE_ASSOCIATION_TYPES, ADYEN_LEGAL_ENTITY_STATE_PROVINCE_COUNTRIES, ADYEN_NO_TAX_NUMBER_ABSENT_COUNTRIES, ADYEN_ROLLOUT_COUNTRY_CODES, ADYEN_STORE_STATE_PROVINCE_COUNTRIES, ADYEN_TAX_NUMBER_FORMATS, ADYEN_TAX_NUMBER_MIN_LENGTH, AFFIRM_COUNTRY_CODES, AFFIRM_PRICE_PLANS, type AddressLike, type AdyenBnplSettings, type AdyenBnplSkippedStore, type AdyenBnplUpdateResult, type AffirmPricePlan, type Amount, type AssignUserChange, AttributeType, type AvailabilityInput, type AvailabilitySlot, type AvailableTransition, BNPL_METHOD_STATUS, BNPL_SKIP_REASON, type BnplMethodStatus, type BnplSkipReason, type BookingDateRanges, type BookingDuration, type BookingDurationField, type BookingDurationProblem, type BookingDurationProblemKind, BookingDurationUnit, type BookingMethod, type BookingOccupancy, BookingRatePeriod, type BookingResourceInput, BookingResourceKind, BookingResourceStatus, type BookingRuleDurations, type BookingRuleInNewShape, type BookingRuleNewFields, type BookingRuleParts, BookingRulesError, type BookingRulesInput, BookingSessionSale, type BookingTimeSlots, BookingType, type BusyWindow, CANADA_PROVINCES, CONDITION_OPERATORS, COUNTRY_CURRENCIES, CURRENCY_CONFIG, type CartDiscountBucket, type CartFeeBucket, type CashDrawer, type CashRoundingTuple, type CategoryModifierRow, type CategoryRow, CompanyType, type CompositeAvailabilityRows, type CompositeMakeable, type CompositeMakeableRow, type CompositePriceItem, type CompositePricePart, type CompositeReservationOrder, type CompositeShelf, type CompositeStockPart, type Condition, type ConditionGroup, type ConditionOperator, type ConfigUpdatedPayload, type ConfigValidationError, type ConfigValidationResult, type ConfigValidationWarning, type CountryOption, type CrossAxisRequires, type CrossAxisRule, type CrossAxisTrigger, CurrencyCode, type CurrencyConfig, type CurrencyRate, CustomTableAvailability, CustomerPlatform, DEFAULT_CONFIG, DEFAULT_CROSS_AXIS_RULES, DEFAULT_DISPLAY_STATE_MAP, DEFAULT_HOLD_MINUTES, DEFAULT_RESOLVED_CONFIG, DEFAULT_UNIT_ID, type DeleteStateConfigFragmentParams, type DeleteStateConfigFragmentResponse, type DiscountsBreakdown, type DiscountsTuple, type DisplayStateResult, type DisplayStateRule, DualWriteStrategy, EUFixedRates, EUROPE, EVERYWHERE_KEY, EXPENSE_DEFAULT_CATEGORIES, EXPENSE_NAME_MAX_LENGTH, EXPENSE_PAYMENT_METHOD_PRESETS, type EndOfSessionReport, type ExpenseDefaultCategoryKey, ExtensionCategory, FINANCIAL_INVARIANTS, FULFILLMENT_STATES, type FailedCondition, type FeesBreakdown, FeesCustomBillingStatus, type FeesTuple, type FinancialInvariant, type FragmentParam, type FragmentValidationResult, type FulfillmentState, type FulfillmentStateDefinition, type FulfillmentTransitionPath, type GetAvailableTransitionsParams, type GetAvailableTransitionsResponse, type GetOrderDisplayStateParams, type GetOrderDisplayStateResponse, type GetOrderStateConfigParams, type GetOrderStateConfigResponse, type GetStateConfigFragmentParams, type GetStateConfigFragmentResponse, type GridSlot, HttpMethod, InventoryBaseActionEnum, type InventoryBaseActionType, InventorySpecificActionType, InvoiceStatus, LegacyWriteStrategy, LibraryItemType, type LineStockMove, MAX_PRECISION, type Measurable, type MeasurementBase, type MeasurementUnit, type MeasurementUnitFamily, MenuProject, type ModifierChoiceRow, type ModifierRow, type ModifiersBreakdown, type ModifiersTuple, NAFixedRates, NORTH_AMERICA, NonRevenueItemType, type NormalizedAddress, ORDER_STATE_ACTIONS, ORDER_STATE_EVENTS, ORDER_STATE_TOPIC, type OrderContext, type OrderLikeForAssignedUsers, type OrderLikeForContext, type OrderLikeForInCart, type OrderLikeForLegacyInference, type OrderLineItem, type OrderMutationData, type OrderPaymentMethod, OrderPlatform, type OrderRefund, type OrderReservationForContext, type OrderStateEventPayload, type OrderStateWritable, type OrderStatusDefinition, type OrderStatusValidationError, type OrderWriteStrategy, OtherFixedRates, OwnerType, PATH_MODES, PAYMENT_CHANNELS, PAYMENT_STATES, POS_VALID_INITIAL_STATES, type PathMode, type PaymentChannel, PaymentMethod, PaymentProcessor, type PaymentState, type PaymentStateDefinition, type PaymentTransitionPath, type PlanCourseInput, type PlanWindowInput, Platform, type PoolDrawing, PreviewImageMode, PricingLevel, PricingPlanEnum, PricingRegionEnum, ProcessorType, type ProductDiscountBucket, type ProductFeeBucket, ProductSalesChartStep, ProductSalesReportCompare, ProductStatus, ProductType, type Province, PublicationAvailability, type PublicationConfig, PublicationStatus, REGION_MAPPING, REPORT_NEGATE_PATHS, ReceiptSendChannel, ReceiptType, type RefundsBreakdown, ReservationStatus, ResidualPaymentMethod, ResidualStatus, type ResolveInputs, type ResolveShippingInput, type ResolveTemplateResult, type ResourceAvailability, ResourceAvailabilityState, type ResourceInWindow, type ResourcePresenceRow, SHIPPING_COUNTRIES, STATE_SCHEMA, STRIPE_SUPPORTED_COUNTRIES, SYSTEM_FAMILIES, SYSTEM_FAMILY_IDS, SYSTEM_UNITS, SYSTEM_UNIT_IDS, SalesLineAction, SalesLineSourceArray, type SalesSummary, type SaveStateConfigFragmentParams, type SaveStateConfigFragmentResponse, type SettlementBreakdown, type SettlementBuckets, type SettlementCardSection, type SettlementCashSection, type SettlementCustomEntry, ShippingChannel, ShippingNoOptionReason, type ShippingOptionRule, ShippingOptionType, type ShippingPlace, type ShippingPriceTier, type ShippingQuoteOption, ShippingRateType, type ShippingResolution, type ShippingTuple, ShippingZoneError, ShippingZoneKind, type ShippingZoneProblem, type ShippingZoneRule, type SplitPayment, type SplitPaymentPayment, type StaffSales, type StaffSalesEntry, type StateConfig, type StateConfigFragment, type StateDefinition, type StatePair, type StateSchema, type StateTransitionBlockedPayload, type StateTransitionCompletedPayload, StationStatus, type StockLine, type StockLineComponent, type StockReservationLink, type StoredStateConfig, StripeCurrencyCode, StripeStatus, type TaxBreakdown, type TaxBreakdownRateEntry, type TaxBreakdownSection, type TaxBreakdownSubtotal, type TaxesTuple, TimePeriod, type TipEntry, type TipsBreakdown, type TipsTuple, TopMetericsSort, type TransitionBlockedBy, type TransitionConditionSet, type TransitionOrderStateParams, type TransitionOrderStateResponse, type TransitionPath, type TransitionRequest, type TransitionResult, UNLIMITED_PLACES, UserTypes, type WeeklyHours, type WindowForPeriodsInput, addAmounts, addressPlaceKeys, adyenLegalEntityRequiresStateOrProvince, adyenRequiresJobTitle, adyenStoreRequiresStateOrProvince, adyenSupportsTaxNumberAbsent, adyenTaxNumberFormat, allowedDurationUnits, amountToString, ancestorChain, applyAssignment, assertUnitSane, availableIn, baseFor, baseFulfillmentDefinitions, baseOf, basePaymentDefinitions, bookingMethodOf, bookingRuleParts, buildAvailability, buildGrid, buildOrderContext, buildPosPresetConfig, buildResolvedConfig, calculatePercentage, calendarDate, canTransition, capacityOf, cheapestCompositeItem, cheapestCompositePrice, checkPartySize, checkQtyPerBooking, compositeItemCost, compositeItemUnavailable, compositeMakeable, compositeModifierMismatches, compositeReservationMismatches, compositeVariantInStock, conditionSummary, convertFixedFeeToLocalCurrency, courseSessions, courseStarted, courseStartedInZone, createAmount, crossAxisRuleApplies, currentAssignees, deriveDisplayState, deriveFamilyCode, deriveUnitId, displayRuleMatchesPair, divideAmount, durationProblems, durationText, evaluateCondition, evaluateConditionSet, extendPrice, extendPriceFor, fewestFreeOver, formatCurrency, formatInUnit, formatMinorUnitsToString, formatQuantity, fromBase, fromMinorUnits, generateMongoID, getAvailableTransitions, getCashAmountDue, getCountriesByRegion, getCurrencyConfig, getCurrentISODate, getFinancialInvariantViolations, getGoodsPortion, getLineSubtotal, getMinorUnitMultiplier, getMinorUnits, getPaymentLegTotal, getPricingRegionFromCountry, getSettlementTotal, getTotalCollected, hasInCartFlag, hasSellableChoice, holdExpiresAt, inferStatesFromLegacyStatus, isAdyenRolloutCountry, isAffirmCountry, isAffirmPricePlan, isChoiceAvailableAtOutlet, isConditionOperator, isFulfillmentState, isInCart, isPaymentState, isSupportedCurrency, isSystemFamilyCode, isValidQuantity, isWhole, lineStockMoves, listCountries, listProvinces, listShippingCountries, longestMinutesOf, mapToLegacyStatus, maxAdvanceMinutesOf, maxPrecisionFor, mergeFragment, modifiersSellable, multiplyAmount, normalizeAddress, normalizeCityKey, normalizeCountry, normalizeMongoIdString, normalizePostCode, normalizeProvince, occupancyIn, oldMaxAdvanceOf, orderAssignments, parseAmountToMinorUnits, parseCurrencyCode, parseStripeCurrencyCode, pickFreeResource, placeKey, planCourse, planWindow, poolDemand, poolOf, poolShortfall, poolStockAt, postCodeMatchesProvince, presentAt, priceForTotal, provincesForPostCode, removeFragment, resolveFamily, resolveModifiersForProduct, resolveShipping, resolveTemplate, resolveUnit, roundToPrecision, ruleDurationsOf, ruleInNewShape, sameFamily, sessionCells, setOrderState, shipsToCountry, shopDayKey, shopDayRange, shortestMinutesOf, signReportForDisplay, slotsForWindow, soldAsCourse, stringifyMinorUnits, subtractAmounts, toBase, toMinorUnits, validateConfig, validateFragmentCompatibility, validateOrderStatuses, validateShippingZone, violatesFinancialInvariant, windowEndsAt, windowEndsAtInZone, windowForPeriods, withinPresence };
2182
+ export { ADYEN_JOB_TITLE_ASSOCIATION_TYPES, ADYEN_LEGAL_ENTITY_STATE_PROVINCE_COUNTRIES, ADYEN_NO_TAX_NUMBER_ABSENT_COUNTRIES, ADYEN_ROLLOUT_COUNTRY_CODES, ADYEN_STORE_STATE_PROVINCE_COUNTRIES, ADYEN_TAX_NUMBER_FORMATS, ADYEN_TAX_NUMBER_MIN_LENGTH, AFFIRM_COUNTRY_CODES, AFFIRM_PRICE_PLANS, type AddressLike, type AdyenBnplSettings, type AdyenBnplSkippedStore, type AdyenBnplUpdateResult, type AffirmPricePlan, type Amount, type AssignUserChange, AttributeType, type AvailabilityInput, type AvailabilitySlot, type AvailableTransition, BNPL_METHOD_STATUS, BNPL_SKIP_REASON, type BnplMethodStatus, type BnplSkipReason, type BookingDateRanges, type BookingDuration, type BookingDurationField, type BookingDurationProblem, type BookingDurationProblemKind, BookingDurationUnit, type BookingMethod, type BookingOccupancy, BookingRatePeriod, type BookingResourceInput, BookingResourceKind, BookingResourceStatus, type BookingRuleDurations, type BookingRuleInNewShape, type BookingRuleNewFields, type BookingRuleParts, BookingRulesError, type BookingRulesInput, BookingSessionSale, type BookingTimeSlots, BookingType, type BusyWindow, CANADA_PROVINCES, CONDITION_OPERATORS, COUNTRY_CURRENCIES, CURRENCY_CONFIG, type CartDiscountBucket, type CartFeeBucket, type CashDrawer, type CashRoundingTuple, type CategoryModifierRow, type CategoryRow, CompanyType, type CompositeAvailabilityRows, type CompositeMakeable, type CompositeMakeableRow, type CompositePriceItem, type CompositePricePart, type CompositeReservationOrder, type CompositeShelf, type CompositeStockPart, type Condition, type ConditionGroup, type ConditionOperator, type ConfigUpdatedPayload, type ConfigValidationError, type ConfigValidationResult, type ConfigValidationWarning, type CountryOption, type CrossAxisRequires, type CrossAxisRule, type CrossAxisTrigger, CurrencyCode, type CurrencyConfig, type CurrencyRate, CustomTableAvailability, CustomerPlatform, DEFAULT_CONFIG, DEFAULT_CROSS_AXIS_RULES, DEFAULT_DISPLAY_STATE_MAP, DEFAULT_HOLD_MINUTES, DEFAULT_RESOLVED_CONFIG, DEFAULT_UNIT_ID, type DeleteStateConfigFragmentParams, type DeleteStateConfigFragmentResponse, type DiscountsBreakdown, type DiscountsTuple, type DisplayStateResult, type DisplayStateRule, DualWriteStrategy, EUFixedRates, EUROPE, EVERYWHERE_KEY, EXPENSE_DEFAULT_CATEGORIES, EXPENSE_NAME_MAX_LENGTH, EXPENSE_PAYMENT_METHOD_PRESETS, type EndOfSessionReport, type ExpenseDefaultCategoryKey, ExtensionCategory, FINANCIAL_INVARIANTS, FULFILLMENT_STATES, type FailedCondition, type FeesBreakdown, FeesCustomBillingStatus, type FeesTuple, type FinancialInvariant, type FragmentParam, type FragmentValidationResult, type FulfillmentState, type FulfillmentStateDefinition, type FulfillmentTransitionPath, type GetAvailableTransitionsParams, type GetAvailableTransitionsResponse, type GetOrderDisplayStateParams, type GetOrderDisplayStateResponse, type GetOrderStateConfigParams, type GetOrderStateConfigResponse, type GetStateConfigFragmentParams, type GetStateConfigFragmentResponse, type GridSlot, HttpMethod, InventoryBaseActionEnum, type InventoryBaseActionType, InventorySpecificActionType, InvoiceStatus, LegacyWriteStrategy, LibraryItemType, type LineStockMove, MAX_PRECISION, type Measurable, type MeasurementBase, type MeasurementUnit, type MeasurementUnitFamily, MenuProject, type ModifierChoiceRow, type ModifierRow, type ModifiersBreakdown, type ModifiersTuple, NAFixedRates, NORTH_AMERICA, NonRevenueItemType, type NormalizedAddress, ORDER_STATE_ACTIONS, ORDER_STATE_EVENTS, ORDER_STATE_TOPIC, type OrderContext, type OrderLikeForAssignedUsers, type OrderLikeForContext, type OrderLikeForInCart, type OrderLikeForLegacyInference, type OrderLineItem, type OrderMutationData, type OrderPaymentMethod, OrderPlatform, type OrderRefund, type OrderReservationForContext, type OrderStateEventPayload, type OrderStateWritable, type OrderStatusDefinition, type OrderStatusValidationError, type OrderWriteStrategy, OtherFixedRates, OwnerType, PATH_MODES, PAYMENT_CHANNELS, PAYMENT_STATES, POS_VALID_INITIAL_STATES, type PathMode, type PaymentChannel, PaymentMethod, PaymentProcessor, type PaymentState, type PaymentStateDefinition, type PaymentTransitionPath, type PlanCourseInput, type PlanWindowInput, Platform, type PoolDrawing, PreviewImageMode, PricingLevel, PricingPlanEnum, PricingRegionEnum, ProcessorType, type ProductDiscountBucket, type ProductFeeBucket, ProductSalesChartStep, ProductSalesReportCompare, ProductStatus, ProductType, type Province, PublicationAvailability, type PublicationConfig, PublicationStatus, REGION_MAPPING, REPORT_NEGATE_PATHS, ReceiptSendChannel, ReceiptType, type RefundsBreakdown, type RentalEndsInput, ReservationStatus, ResidualPaymentMethod, ResidualStatus, type ResolveInputs, type ResolveShippingInput, type ResolveTemplateResult, type ResourceAvailability, ResourceAvailabilityState, type ResourceInWindow, type ResourcePresenceRow, SHIPPING_COUNTRIES, STATE_SCHEMA, STRIPE_SUPPORTED_COUNTRIES, SYSTEM_FAMILIES, SYSTEM_FAMILY_IDS, SYSTEM_UNITS, SYSTEM_UNIT_IDS, SalesLineAction, SalesLineSourceArray, type SalesSummary, type SaveStateConfigFragmentParams, type SaveStateConfigFragmentResponse, type SettlementBreakdown, type SettlementBuckets, type SettlementCardSection, type SettlementCashSection, type SettlementCustomEntry, ShippingChannel, ShippingNoOptionReason, type ShippingOptionRule, ShippingOptionType, type ShippingPlace, type ShippingPriceTier, type ShippingQuoteOption, ShippingRateType, type ShippingResolution, type ShippingTuple, ShippingZoneError, ShippingZoneKind, type ShippingZoneProblem, type ShippingZoneRule, type SplitPayment, type SplitPaymentPayment, type StaffSales, type StaffSalesEntry, type StateConfig, type StateConfigFragment, type StateDefinition, type StatePair, type StateSchema, type StateTransitionBlockedPayload, type StateTransitionCompletedPayload, StationStatus, type StockLine, type StockLineComponent, type StockReservationLink, type StoredStateConfig, StripeCurrencyCode, StripeStatus, type TaxBreakdown, type TaxBreakdownRateEntry, type TaxBreakdownSection, type TaxBreakdownSubtotal, type TaxesTuple, TimePeriod, type TipEntry, type TipsBreakdown, type TipsTuple, TopMetericsSort, type TransitionBlockedBy, type TransitionConditionSet, type TransitionOrderStateParams, type TransitionOrderStateResponse, type TransitionPath, type TransitionRequest, type TransitionResult, UNLIMITED_PLACES, UserTypes, type WeeklyHours, type WindowForPeriodsInput, addAmounts, addressPlaceKeys, adyenLegalEntityRequiresStateOrProvince, adyenRequiresJobTitle, adyenStoreRequiresStateOrProvince, adyenSupportsTaxNumberAbsent, adyenTaxNumberFormat, allowedDurationUnits, amountToString, ancestorChain, applyAssignment, assertUnitSane, availableIn, baseFor, baseFulfillmentDefinitions, baseOf, basePaymentDefinitions, bookingMethodOf, bookingRuleParts, buildAvailability, buildGrid, buildOrderContext, buildPosPresetConfig, buildResolvedConfig, calculatePercentage, calendarDate, canTransition, capacityOf, cheapestCompositeItem, cheapestCompositePrice, checkPartySize, checkQtyPerBooking, compositeItemCost, compositeItemUnavailable, compositeMakeable, compositeModifierMismatches, compositeReservationMismatches, compositeVariantInStock, conditionSummary, convertFixedFeeToLocalCurrency, courseSessions, courseStarted, courseStartedInZone, createAmount, crossAxisRuleApplies, currentAssignees, deriveDisplayState, deriveFamilyCode, deriveUnitId, displayRuleMatchesPair, divideAmount, durationProblems, durationText, evaluateCondition, evaluateConditionSet, extendPrice, extendPriceFor, fewestFreeOver, formatCurrency, formatInUnit, formatMinorUnitsToString, formatQuantity, fromBase, fromMinorUnits, generateMongoID, getAvailableTransitions, getCashAmountDue, getCountriesByRegion, getCurrencyConfig, getCurrentISODate, getFinancialInvariantViolations, getGoodsPortion, getLineSubtotal, getMinorUnitMultiplier, getMinorUnits, getPaymentLegTotal, getPricingRegionFromCountry, getSettlementTotal, getTotalCollected, hasInCartFlag, hasSellableChoice, holdExpiresAt, inferStatesFromLegacyStatus, isAdyenRolloutCountry, isAffirmCountry, isAffirmPricePlan, isChoiceAvailableAtOutlet, isConditionOperator, isFulfillmentState, isInCart, isPaymentState, isSupportedCurrency, isSystemFamilyCode, isValidQuantity, isWhole, lineStockMoves, listCountries, listProvinces, listShippingCountries, longestMinutesOf, mapToLegacyStatus, maxAdvanceMinutesOf, maxPrecisionFor, mergeFragment, modifiersSellable, multiplyAmount, normalizeAddress, normalizeCityKey, normalizeCountry, normalizeMongoIdString, normalizePostCode, normalizeProvince, occupancyIn, occupiedAtOutlet, oldMaxAdvanceOf, orderAssignments, parseAmountToMinorUnits, parseCurrencyCode, parseStripeCurrencyCode, pickFreeResource, placeKey, planCourse, planWindow, poolDemand, poolOf, poolShortfall, poolStockAt, postCodeMatchesProvince, presentAt, priceForTotal, provincesForPostCode, removeFragment, rentalEnds, resolveFamily, resolveModifiersForProduct, resolveShipping, resolveTemplate, resolveUnit, roundToPrecision, ruleDurationsOf, ruleInNewShape, sameFamily, sessionCells, setOrderState, shipsToCountry, shopDayKey, shopDayRange, shortestMinutesOf, signReportForDisplay, slotsForWindow, soldAsCourse, stringifyMinorUnits, subtractAmounts, toBase, toMinorUnits, validateConfig, validateFragmentCompatibility, validateOrderStatuses, validateShippingZone, violatesFinancialInvariant, windowEndsAt, windowEndsAtInZone, windowForPeriods, withinPresence };
package/dist/index.js CHANGED
@@ -241,6 +241,7 @@ __export(index_exports, {
241
241
  normalizePostCode: () => normalizePostCode,
242
242
  normalizeProvince: () => normalizeProvince,
243
243
  occupancyIn: () => occupancyIn,
244
+ occupiedAtOutlet: () => occupiedAtOutlet,
244
245
  oldMaxAdvanceOf: () => oldMaxAdvanceOf,
245
246
  orderAssignments: () => orderAssignments,
246
247
  parseAmountToMinorUnits: () => parseAmountToMinorUnits,
@@ -259,6 +260,7 @@ __export(index_exports, {
259
260
  priceForTotal: () => priceForTotal,
260
261
  provincesForPostCode: () => provincesForPostCode,
261
262
  removeFragment: () => removeFragment,
263
+ rentalEnds: () => rentalEnds,
262
264
  resolveFamily: () => resolveFamily,
263
265
  resolveModifiersForProduct: () => resolveModifiersForProduct,
264
266
  resolveShipping: () => resolveShipping,
@@ -3759,6 +3761,11 @@ function occupancyIn(occupied, productId, startAt, bufferEndAt, shared) {
3759
3761
  foreignProductId: foreign?.productId
3760
3762
  };
3761
3763
  }
3764
+ var inEveryOutletPool = (entry) => !entry.outletId;
3765
+ function occupiedAtOutlet(occupied, rule, outletId) {
3766
+ if (bookingMethodOf(rule) !== "sessions" || !outletId) return occupied;
3767
+ return occupied.filter((entry) => inEveryOutletPool(entry) || entry.outletId === outletId);
3768
+ }
3762
3769
  var stateFor = (hasShift, offerable, free) => {
3763
3770
  if (offerable === 0) {
3764
3771
  return hasShift() ? "fullyBooked" /* FULLY_BOOKED */ : "noHoursInRange" /* NO_HOURS_IN_RANGE */;
@@ -3790,12 +3797,14 @@ function buildAvailability({
3790
3797
  bookingRulesId,
3791
3798
  rule,
3792
3799
  resources,
3793
- occupied,
3800
+ occupied: everyOutlet,
3801
+ outletId,
3794
3802
  from,
3795
3803
  to,
3796
3804
  now,
3797
3805
  timeZone
3798
3806
  }) {
3807
+ const occupied = occupiedAtOutlet(everyOutlet, rule, outletId);
3799
3808
  const shared = rule.slot.sharedAcrossProducts ?? false;
3800
3809
  const bookableUntil = windowEndsAtInZone(rule, now, timeZone ?? null);
3801
3810
  const parts = bookingRuleParts(rule);
@@ -4123,6 +4132,70 @@ function windowForPeriods({ rule, timeZone, startAt, periods, now }) {
4123
4132
  slotsForWindow(grid, startAt, endAt);
4124
4133
  return { startAt, endAt };
4125
4134
  }
4135
+ function rentalEnds(input) {
4136
+ const { rule, timeZone, startAt, now, untilDay } = input;
4137
+ const parts = bookingRuleParts(rule);
4138
+ if (parts.method !== "date-ranges") throw new BookingRulesError("Only date-range rules book a stay");
4139
+ const horizon = shopDayRange(untilDay, 1, timeZone).to;
4140
+ if (horizon <= startAt) throw new BookingRulesError(`untilDay ${untilDay} is before the stay starts`);
4141
+ const gridUntil = (end) => buildGrid(rule, timeZone, startAt, new Date(Math.min(end, startAt.getTime() + 366 * 1440 * 6e4)), now);
4142
+ let walk = walkRentalEnds(gridUntil(horizon.getTime() + 1440 * 6e4), input, parts, horizon);
4143
+ if (!walk.ends.length && walk.refusal && walk.ranOut)
4144
+ walk = walkRentalEnds(gridUntil(Infinity), input, parts, horizon);
4145
+ if (walk.ends.length) return walk.ends;
4146
+ throw walk.refusal ?? new BookingRulesError(
4147
+ `No stay from ${startAt.toISOString()} fits these rules: the bookable days run out before the shortest allowed stay`
4148
+ );
4149
+ }
4150
+ function walkRentalEnds(grid, { rule, timeZone, startAt, untilDay }, parts, horizon) {
4151
+ const startIndex = grid.findIndex((cell) => cell.startAt.getTime() === startAt.getTime());
4152
+ if (startIndex < 0) {
4153
+ throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
4154
+ }
4155
+ slotsForWindow(grid, startAt, grid[startIndex].endAt);
4156
+ const ends = [];
4157
+ let refusal;
4158
+ for (const cell of grid.slice(startIndex)) {
4159
+ if (cell.endAt > horizon && (ends.length || !refusal)) {
4160
+ refusal ??= new BookingRulesError(`No stay from ${startAt.toISOString()} ends on or before ${untilDay}`);
4161
+ return { ends, refusal, ranOut: false };
4162
+ }
4163
+ const slots = refusalOr(() => slotsForWindow(grid, startAt, cell.endAt));
4164
+ if (slots instanceof BookingRulesError) return { ends, refusal, ranOut: false };
4165
+ const periods = refusalOr(
4166
+ () => parts.wholePeriods ? wholePeriodsIn(rule.ratePeriod, timeZone, startAt, cell.endAt, slots.length) : slots.length
4167
+ );
4168
+ if (periods instanceof BookingRulesError) continue;
4169
+ const stay = refusalOr(() => checkStay(parts, timeZone, startAt, periods));
4170
+ if (stay instanceof BookingRulesError) {
4171
+ if (ends.length) return { ends, refusal, ranOut: false };
4172
+ refusal = stay;
4173
+ continue;
4174
+ }
4175
+ ends.push(rentalEndOf(slots, periods, timeZone));
4176
+ }
4177
+ return { ends, refusal, ranOut: true };
4178
+ }
4179
+ function rentalEndOf(slots, periods, timeZone) {
4180
+ const endAt = slots[slots.length - 1].endAt;
4181
+ return {
4182
+ periods,
4183
+ endAt: endAt.toISOString(),
4184
+ lastDayKey: shopDayKey(new Date(endAt.getTime() - 1), timeZone),
4185
+ coveredSlots: slots.map((slot) => ({
4186
+ startAt: slot.startAt.toISOString(),
4187
+ dayKey: shopDayKey(slot.startAt, timeZone)
4188
+ }))
4189
+ };
4190
+ }
4191
+ function refusalOr(run) {
4192
+ try {
4193
+ return run();
4194
+ } catch (error) {
4195
+ if (error instanceof BookingRulesError) return error;
4196
+ throw error;
4197
+ }
4198
+ }
4126
4199
  function sameDayMonthsLater(startAt, months, timeZone) {
4127
4200
  const { year, month, day } = zonedParts(startAt, timeZone);
4128
4201
  return instantFromLocal(...sameDayMonthsLaterDate(year, month, day, months), 0, timeZone);
@@ -5323,6 +5396,7 @@ var EXPENSE_DEFAULT_CATEGORIES = [
5323
5396
  normalizePostCode,
5324
5397
  normalizeProvince,
5325
5398
  occupancyIn,
5399
+ occupiedAtOutlet,
5326
5400
  oldMaxAdvanceOf,
5327
5401
  orderAssignments,
5328
5402
  parseAmountToMinorUnits,
@@ -5341,6 +5415,7 @@ var EXPENSE_DEFAULT_CATEGORIES = [
5341
5415
  priceForTotal,
5342
5416
  provincesForPostCode,
5343
5417
  removeFragment,
5418
+ rentalEnds,
5344
5419
  resolveFamily,
5345
5420
  resolveModifiersForProduct,
5346
5421
  resolveShipping,