var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/solution/ScanOrder/utils.ts
var utils_exports = {};
__export(utils_exports, {
  aggregateItemRuleLimit: () => aggregateItemRuleLimit,
  attachItemRuleLimitsToTopLevelProducts: () => attachItemRuleLimitsToTopLevelProducts,
  buildItemRuleBusinessData: () => buildItemRuleBusinessData,
  buildProductKey: () => buildProductKey,
  buildProductLineFingerprint: () => buildProductLineFingerprint,
  buildQuantityLimitIndex: () => buildQuantityLimitIndex,
  collectLinkProductIdsFromReservationRules: () => collectLinkProductIdsFromReservationRules,
  computeResourceIsFull: () => computeResourceIsFull,
  createEmptySummary: () => createEmptySummary,
  extractStrategyModelIdsFromTableConfig: () => extractStrategyModelIdsFromTableConfig,
  getProductIdentityIndex: () => getProductIdentityIndex,
  getSafeProductNum: () => getSafeProductNum,
  getTopLevelProductId: () => getTopLevelProductId,
  getTopLevelVariantId: () => getTopLevelVariantId,
  hasCustomCapacityProduct: () => hasCustomCapacityProduct,
  isIdentityMatch: () => isIdentityMatch,
  isSkuOnlyDeleteIdentity: () => isSkuOnlyDeleteIdentity,
  normalizeEnabledItemRuleIds: () => normalizeEnabledItemRuleIds,
  normalizeItemRuleStrategies: () => normalizeItemRuleStrategies,
  normalizeOrderProduct: () => normalizeOrderProduct,
  pickFirstCustomCapacityDimensionId: () => pickFirstCustomCapacityDimensionId,
  pickFirstCustomCapacityPaxBounds: () => pickFirstCustomCapacityPaxBounds,
  pickFirstDurationMinutesFromProducts: () => pickFirstDurationMinutesFromProducts,
  resolveSkuMatchedQuantityLimits: () => resolveSkuMatchedQuantityLimits,
  toBoolean: () => toBoolean,
  toNonNegativeInt: () => toNonNegativeInt,
  toNonNegativeNumber: () => toNonNegativeNumber,
  toPositiveString: () => toPositiveString,
  toPriceString: () => toPriceString
});
module.exports = __toCommonJS(utils_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_decimal = __toESM(require("decimal.js"));
var import_utils = require("../../modules/Order/utils");
var import_manualProductDiscount = require("../../modules/Order/utils/manualProductDiscount");
function createEmptySummary() {
  return {
    product_quantity: 0,
    product_original_amount: "0.00",
    product_amount: "0.00",
    product_expect_amount: "0.00",
    product_tax_fee: "0.00",
    shipping_fee: "0.00",
    shipping_tax_fee: "0.00",
    tax_fee: "0.00",
    surcharge_fee: "0.00",
    discount_amount: "0.00",
    deposit_amount: "0.00",
    expect_amount: "0.00",
    total_amount: "0.00",
    total_refund_amount: "0.00",
    customer_paid_amount: "0.00",
    order_paid_amount: "0.00",
    amount_gap: "0.00",
    rounding_amount: "0.00",
    pay_service_charge_amount: "0.00"
  };
}
function getSafeProductNum(num) {
  if (!num || Number.isNaN(num))
    return 1;
  if (num < 1)
    return 1;
  return Math.floor(num);
}
function toBoolean(value) {
  if (typeof value === "boolean")
    return value;
  if (typeof value === "number")
    return value !== 0;
  if (typeof value === "string") {
    const normalized = value.trim().toLowerCase();
    return ["1", "true", "yes", "y", "on"].includes(normalized);
  }
  return false;
}
function toPositiveString(value) {
  if (value === null || value === void 0 || value === "")
    return void 0;
  const normalized = String(value).trim();
  if (!normalized || normalized === "0" || normalized.toLowerCase() === "null") {
    return void 0;
  }
  return normalized;
}
function normalizeEnabledItemRuleIds(rawIds) {
  if (!Array.isArray(rawIds))
    return [];
  const uniqueIds = /* @__PURE__ */ new Set();
  for (const item of rawIds) {
    const strategyId = Number(item);
    if (Number.isFinite(strategyId) && strategyId > 0) {
      uniqueIds.add(strategyId);
    }
  }
  return Array.from(uniqueIds);
}
function extractStrategyModelIdsFromTableConfig(tableConfig) {
  const rawIds = Array.isArray(tableConfig == null ? void 0 : tableConfig.strategy_model_ids) ? tableConfig.strategy_model_ids : [];
  return rawIds.map((id) => Number(id)).filter((id) => Number.isFinite(id) && id > 0);
}
function normalizeItemRuleStrategies(configs) {
  if (!Array.isArray(configs))
    return [];
  return configs.filter(
    (config) => {
      var _a;
      return Boolean(
        config && typeof config === "object" && ((_a = config == null ? void 0 : config.metadata) == null ? void 0 : _a.type) === "item_rule"
      );
    }
  );
}
function toNonNegativeNumber(value) {
  if (typeof value === "number") {
    return Number.isFinite(value) && value >= 0 ? value : 0;
  }
  if (typeof value === "string") {
    const parsed = Number(value);
    return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;
  }
  return 0;
}
function toNonNegativeInt(value) {
  return Math.floor(toNonNegativeNumber(value));
}
function toPriceString(value, fallback = "0.00") {
  const parsedValue = Number(value);
  if (Number.isNaN(parsedValue))
    return fallback;
  return parsedValue.toFixed(2);
}
function buildProductKey(productId, productVariantId) {
  return `${productId}_${productVariantId}`;
}
function getTopLevelProductId(product) {
  const rawProductId = product.product_id ?? product.id;
  const productId = Number(rawProductId);
  if (!Number.isFinite(productId) || productId <= 0)
    return null;
  return productId;
}
function getTopLevelVariantId(product) {
  const rawVariantId = product.product_variant_id ?? product.variant_id;
  if (rawVariantId === void 0 || rawVariantId === null || rawVariantId === "") {
    return null;
  }
  const variantId = Number(rawVariantId);
  if (!Number.isFinite(variantId) || variantId <= 0)
    return null;
  return variantId;
}
function buildQuantityLimitIndex(limits) {
  const exactLimitMap = /* @__PURE__ */ new Map();
  const productLimitMap = /* @__PURE__ */ new Map();
  for (const limit of limits) {
    const targets = limit.targets || [];
    if (targets.length !== 1)
      continue;
    const target = targets[0];
    const productId = Number(target.product_id);
    if (!Number.isFinite(productId) || productId <= 0)
      continue;
    const variantId = Number(target.product_variant_id);
    const hasVariant = Number.isFinite(variantId) && variantId > 0;
    if (hasVariant) {
      const exactKey = buildProductKey(productId, variantId);
      const existed = exactLimitMap.get(exactKey) || [];
      exactLimitMap.set(exactKey, [...existed, limit]);
    } else {
      const existed = productLimitMap.get(productId) || [];
      productLimitMap.set(productId, [...existed, limit]);
    }
  }
  return {
    exactLimitMap,
    productLimitMap
  };
}
function resolveSkuMatchedQuantityLimits(params) {
  const { productId, variantId, limitIndex } = params;
  const exactMatched = variantId && variantId > 0 ? limitIndex.exactLimitMap.get(buildProductKey(productId, variantId)) || [] : [];
  const productMatched = limitIndex.productLimitMap.get(productId) || [];
  return [...exactMatched, ...productMatched];
}
function aggregateItemRuleLimit(matchedLimits) {
  if (!matchedLimits.length)
    return null;
  let min;
  let max;
  let remainingMax;
  let exact;
  let mustInclude = false;
  let maxSourceLimit;
  let remainingMaxSourceLimit;
  let exactSourceLimit;
  let minSourceLimit;
  let firstMessagedLimit;
  for (const limit of matchedLimits) {
    if (typeof limit.requiredMin === "number" && Number.isFinite(limit.requiredMin)) {
      if (min === void 0 || limit.requiredMin > min) {
        min = limit.requiredMin;
        minSourceLimit = limit;
      }
    }
    if (typeof limit.requiredMax === "number" && Number.isFinite(limit.requiredMax)) {
      if (max === void 0 || limit.requiredMax < max) {
        max = limit.requiredMax;
        maxSourceLimit = limit;
      }
    }
    if (typeof limit.remainingMax === "number" && Number.isFinite(limit.remainingMax)) {
      if (remainingMax === void 0 || limit.remainingMax < remainingMax) {
        remainingMax = limit.remainingMax;
        remainingMaxSourceLimit = limit;
      }
    }
    if (typeof limit.requiredExact === "number" && Number.isFinite(limit.requiredExact)) {
      exact = limit.requiredExact;
      exactSourceLimit = limit;
    }
    mustInclude = mustInclude || Boolean(limit.mustInclude);
    if (!firstMessagedLimit && limit.validationMessage) {
      firstMessagedLimit = limit;
    }
  }
  if (typeof exact === "number" && Number.isFinite(exact)) {
    min = exact;
    max = exact;
  }
  const maxMessageSource = maxSourceLimit || remainingMaxSourceLimit || exactSourceLimit || firstMessagedLimit;
  const minMessageSource = minSourceLimit || exactSourceLimit || firstMessagedLimit;
  const maxValidationMessage = maxMessageSource == null ? void 0 : maxMessageSource.validationMessage;
  const rawMaxValidationMessage = maxMessageSource == null ? void 0 : maxMessageSource.rawValidationMessage;
  const minValidationMessage = minMessageSource == null ? void 0 : minMessageSource.validationMessage;
  const rawMinValidationMessage = minMessageSource == null ? void 0 : minMessageSource.rawValidationMessage;
  const validationMessage = maxValidationMessage ?? minValidationMessage;
  const rawValidationMessage = rawMaxValidationMessage ?? rawMinValidationMessage;
  return {
    min,
    max,
    remainingMax,
    exact,
    mustInclude,
    validationMessage,
    rawValidationMessage,
    maxValidationMessage,
    rawMaxValidationMessage,
    minValidationMessage,
    rawMinValidationMessage
  };
}
function buildItemRuleBusinessData(params) {
  const { tempOrder, runtimeConfig, itemRuleConfigs } = params;
  const rawPax = runtimeConfig.pax || {};
  const adultPax = toNonNegativeInt(rawPax.adult);
  const childPax = toNonNegativeInt(rawPax.child);
  const totalPax = toNonNegativeInt(rawPax.total) || adultPax + childPax || 1;
  const cartItems = tempOrder.products.reduce((result, product) => {
    if (typeof product.product_id !== "number")
      return result;
    result.push({
      product_id: product.product_id,
      quantity: toNonNegativeInt(product.num),
      ...typeof product.product_variant_id === "number" ? { product_variant_id: product.product_variant_id } : {}
    });
    return result;
  }, []);
  const historicalItems = Array.isArray(runtimeConfig.historicalItems) ? runtimeConfig.historicalItems.reduce((result, item) => {
    if (typeof (item == null ? void 0 : item.product_id) !== "number")
      return result;
    result.push({
      product_id: item.product_id,
      quantity: toNonNegativeInt(item.quantity),
      ...typeof item.product_variant_id === "number" ? { product_variant_id: item.product_variant_id } : {}
    });
    return result;
  }, []) : [];
  return {
    pax: {
      total: totalPax,
      adult: adultPax,
      child: childPax
    },
    cartItems,
    historicalItems,
    serviceType: runtimeConfig.serviceType || "dine-in",
    submissionIndex: typeof runtimeConfig.submissionIndex === "number" ? toNonNegativeInt(runtimeConfig.submissionIndex) : tempOrder.order_id ? 1 : 0,
    custom: runtimeConfig.custom || {},
    strategyConfigs: itemRuleConfigs
  };
}
function attachItemRuleLimitsToTopLevelProducts(productList, limits) {
  if (!Array.isArray(productList))
    return productList;
  const limitIndex = buildQuantityLimitIndex(limits || []);
  for (const item of productList) {
    if (!item || typeof item !== "object")
      continue;
    const productItem = item;
    const productId = getTopLevelProductId(productItem);
    if (productId === null)
      continue;
    const variantId = getTopLevelVariantId(productItem);
    const matchedLimits = limits.length ? resolveSkuMatchedQuantityLimits({
      productId,
      variantId,
      limitIndex
    }) : [];
    const aggregatedLimit = aggregateItemRuleLimit(matchedLimits);
    if (aggregatedLimit) {
      productItem.item_rule_limit = aggregatedLimit;
    } else if ("item_rule_limit" in productItem) {
      delete productItem.item_rule_limit;
    }
  }
  return productList;
}
function buildProductLineFingerprint(productOptionItem, productBundle) {
  const optArr = Array.isArray(productOptionItem) ? productOptionItem : [];
  const normalizedOpts = optArr.map((item) => ({
    option_group_item_id: Number(item == null ? void 0 : item.option_group_item_id) || 0,
    option_group_id: Number(item == null ? void 0 : item.option_group_id) || 0,
    num: typeof (item == null ? void 0 : item.num) === "number" && !Number.isNaN(item.num) ? Math.max(1, Math.floor(item.num)) : 1,
    price: String((item == null ? void 0 : item.price) ?? "")
  })).sort((p, q) => {
    if (p.option_group_item_id !== q.option_group_item_id) {
      return p.option_group_item_id - q.option_group_item_id;
    }
    if (p.option_group_id !== q.option_group_id)
      return p.option_group_id - q.option_group_id;
    if (p.num !== q.num)
      return p.num - q.num;
    return p.price.localeCompare(q.price);
  });
  const bundleArr = Array.isArray(productBundle) ? productBundle : [];
  const normalizedBundles = bundleArr.map((item) => ({
    bundle_id: Number((item == null ? void 0 : item.bundle_id) ?? (item == null ? void 0 : item.id) ?? 0) || 0,
    product_id: Number(item == null ? void 0 : item.product_id) || 0,
    num: typeof (item == null ? void 0 : item.num) === "number" && !Number.isNaN(item.num) ? Math.max(1, Math.floor(item.num)) : 1
  })).sort((p, q) => {
    if (p.bundle_id !== q.bundle_id)
      return p.bundle_id - q.bundle_id;
    if (p.product_id !== q.product_id)
      return p.product_id - q.product_id;
    return p.num - q.num;
  });
  return JSON.stringify([normalizedOpts, normalizedBundles]);
}
function isSkuOnlyDeleteIdentity(x) {
  if (x.unique_identification_number || x.identity_key)
    return false;
  return !("product_option_item" in x) && !("product_bundle" in x);
}
function fingerprintForIdentityWithOptionKeys(x) {
  const row = x;
  const opts = "product_option_item" in row ? Array.isArray(row.product_option_item) ? row.product_option_item : [] : [];
  const buds = "product_bundle" in row ? Array.isArray(row.product_bundle) ? row.product_bundle : [] : [];
  return buildProductLineFingerprint(opts, buds);
}
function isIdentityMatch(a, b) {
  var _a, _b;
  if (a.product_id !== b.product_id || a.product_variant_id !== b.product_variant_id)
    return false;
  const aUid = ((_a = a.metadata) == null ? void 0 : _a.unique_identification_number) ?? a.unique_identification_number ?? a.identity_key;
  const bUid = ((_b = b.metadata) == null ? void 0 : _b.unique_identification_number) ?? b.unique_identification_number ?? b.identity_key;
  const aHasKey = typeof aUid === "string" && aUid.length > 0;
  const bHasKey = typeof bUid === "string" && bUid.length > 0;
  if (aHasKey && bHasKey)
    return aUid === bUid;
  if (isSkuOnlyDeleteIdentity(a) || isSkuOnlyDeleteIdentity(b))
    return true;
  return fingerprintForIdentityWithOptionKeys(a) === fingerprintForIdentityWithOptionKeys(b);
}
function getProductIdentityIndex(products, identity) {
  return products.findIndex((item) => isIdentityMatch(item, identity));
}
function normalizeOrderProduct(product) {
  var _a, _b, _c, _d, _e, _f;
  const metadata = { ...product.metadata || {} };
  const resolvedIdentityKey = ((_a = product.metadata) == null ? void 0 : _a.unique_identification_number) ? String(product.metadata.unique_identification_number) : product.unique_identification_number && String(product.unique_identification_number).length > 0 ? String(product.unique_identification_number) : product.identity_key && String(product.identity_key).length > 0 ? String(product.identity_key) : (0, import_utils.createUuidV4)();
  metadata.unique_identification_number = resolvedIdentityKey;
  const priceOverride = metadata.price_override;
  const originOtherBundle = (_d = (_c = (_b = metadata.origin) == null ? void 0 : _b._extend) == null ? void 0 : _c.other) == null ? void 0 : _d.bundle;
  let bundleInput = product.product_bundle || [];
  if (priceOverride !== void 0 && priceOverride !== null && priceOverride !== "" && Array.isArray(originOtherBundle) && originOtherBundle.length > 0) {
    const priceById = /* @__PURE__ */ new Map();
    originOtherBundle.forEach((item) => {
      if ((item == null ? void 0 : item.id) == null)
        return;
      const unit = item.price ?? item.bundle_selling_price;
      if (unit === void 0 || unit === null)
        return;
      priceById.set(String(item.id), String(unit));
    });
    const base = Array.isArray(bundleInput) && bundleInput.length > 0 ? bundleInput : originOtherBundle;
    bundleInput = base.map((item) => {
      const unit = priceById.get(String(item == null ? void 0 : item.id));
      if (unit === void 0)
        return item;
      return {
        ...item,
        price: unit,
        bundle_selling_price: unit
      };
    });
  }
  const normalizedBundle = bundleInput.map((item) => ({
    ...item,
    bundle_id: item.bundle_id ?? item.id,
    bundle_product_id: item.bundle_product_id ?? item._bundle_product_id,
    bundle_group_id: item.bundle_group_id ?? item.group_id,
    bundle_selling_price: item.bundle_selling_price ?? item.price ?? "0.00",
    price: item.price ?? item.custom_price ?? item.bundle_selling_price ?? "0.00",
    price_type: item.price_type ?? item.custom_price_type ?? "",
    price_type_ext: item.price_type_ext ?? item.custom_price_type_ext ?? ""
  }));
  const normalizedOptions = product.product_option_item || [];
  const optionSum = (0, import_utils.sumOptionUnitPrice)(normalizedOptions);
  const isV2 = metadata.price_schema_version === 2 || metadata.price_schema_version === "2";
  const variantId = Number(product.product_variant_id || 0);
  const variantList = variantId ? (_e = metadata == null ? void 0 : metadata.origin) == null ? void 0 : _e.variant : null;
  const variantPrice = Array.isArray(variantList) ? (_f = variantList.find((v) => Number(v == null ? void 0 : v.id) === variantId)) == null ? void 0 : _f.price : void 0;
  const resolvedSource = (() => {
    var _a2, _b2;
    if (metadata.source_product_price !== void 0) {
      return String(metadata.source_product_price);
    }
    if (variantPrice !== void 0 && variantPrice !== null) {
      return String(variantPrice);
    }
    const originPrice = (_a2 = product._origin) == null ? void 0 : _a2.price;
    if (originPrice !== void 0 && originPrice !== null) {
      return String(originPrice);
    }
    const originBasePrice = (_b2 = product._origin) == null ? void 0 : _b2.base_price;
    if (originBasePrice !== void 0 && originBasePrice !== null) {
      return String(originBasePrice);
    }
    if (!isV2 && metadata.main_product_original_price !== void 0) {
      return String(metadata.main_product_original_price);
    }
    return product.original_price ?? product.selling_price ?? "0.00";
  })();
  const mainOriginalDec = new import_decimal.default(Number(resolvedSource) || 0).plus(optionSum);
  const mainOriginalStr = mainOriginalDec.toDecimalPlaces(2).toFixed(2);
  let mainSellingDec;
  if (isV2 && metadata.main_product_selling_price != null) {
    mainSellingDec = new import_decimal.default(Number(metadata.main_product_selling_price) || 0);
  } else if (metadata.main_product_selling_price != null && metadata.main_product_original_price != null) {
    const legacyOriginal = new import_decimal.default(Number(metadata.main_product_original_price) || 0);
    const legacySelling = new import_decimal.default(Number(metadata.main_product_selling_price) || 0);
    const legacyDiscount = legacyOriginal.minus(legacySelling);
    mainSellingDec = mainOriginalDec.minus(legacyDiscount);
  } else if (product.original_price != null && product.selling_price != null && new import_decimal.default(Number(product.original_price) || 0).greaterThan(
    new import_decimal.default(Number(product.selling_price) || 0)
  )) {
    const topOriginal = new import_decimal.default(Number(product.original_price) || 0);
    const topSelling = new import_decimal.default(Number(product.selling_price) || 0);
    const legacyDiscount = topOriginal.minus(topSelling);
    mainSellingDec = mainOriginalDec.minus(legacyDiscount);
  } else {
    mainSellingDec = mainOriginalDec;
  }
  const mainSellingStr = mainSellingDec.toDecimalPlaces(2).toFixed(2);
  metadata.source_product_price = resolvedSource;
  metadata.main_product_original_price = mainOriginalStr;
  metadata.main_product_selling_price = mainSellingStr;
  metadata.price_schema_version = 2;
  const composedSellingPrice = (0, import_utils.composeLinePrice)({
    mainPrice: mainSellingStr,
    bundle: normalizedBundle
  });
  const composedOriginalPrice = (0, import_utils.composeLinePrice)({
    mainPrice: mainOriginalStr,
    bundle: normalizedBundle,
    useOriginalBundle: true
  });
  const finalOriginalPrice = (0, import_utils.resolveManualOverrideLineOriginalPrice)(
    { num: product.num, metadata, lineOriginalPrice: product.original_price },
    composedOriginalPrice
  );
  const discountList = (0, import_manualProductDiscount.ensureManualProductDiscountList)({
    discountList: product.discount_list,
    metadata,
    originalPrice: finalOriginalPrice,
    sellingPrice: composedSellingPrice,
    quantity: getSafeProductNum(product.num)
  });
  return {
    order_detail_id: product.order_detail_id || null,
    product_id: product.product_id,
    num: getSafeProductNum(product.num),
    product_variant_id: product.product_variant_id,
    product_option_item: normalizedOptions,
    selling_price: composedSellingPrice,
    original_price: finalOriginalPrice,
    tax_fee: product.tax_fee || "0.00",
    is_charge_tax: product.is_charge_tax ?? 0,
    discount_list: discountList,
    product_bundle: normalizedBundle,
    metadata,
    note: product.note != null ? String(product.note) : ""
  };
}
function collectLinkProductIdsFromReservationRules(rules) {
  if (!Array.isArray(rules))
    return [];
  const ids = [];
  for (const entry of rules) {
    if (!entry || typeof entry !== "object")
      continue;
    const rec = entry;
    if (rec.type !== "link")
      continue;
    if (!Array.isArray(rec.value))
      continue;
    for (const v of rec.value) {
      const n = Number(v);
      if (Number.isFinite(n) && n > 0)
        ids.push(Math.floor(n));
    }
  }
  return [...new Set(ids)];
}
function pickFirstDurationMinutesFromProducts(products) {
  var _a;
  for (const product of products) {
    const value = (_a = product == null ? void 0 : product.duration) == null ? void 0 : _a.value;
    const n = Number(value);
    if (Number.isFinite(n) && n > 0)
      return Math.floor(n);
  }
  return void 0;
}
function hasCustomCapacityProduct(products) {
  return products.some((p) => {
    var _a;
    return ((_a = p == null ? void 0 : p.capacity) == null ? void 0 : _a.type) === "custom";
  });
}
function computeResourceIsFull(params) {
  const { resourceSelectType, lastOrderId, capacityList, capacity } = params;
  if (resourceSelectType === "single")
    return Boolean(lastOrderId);
  if (resourceSelectType !== "multiple")
    return false;
  const totalCapacity = Number(capacity);
  if (!Number.isFinite(totalCapacity) || totalCapacity <= 0)
    return false;
  const now = (0, import_dayjs.default)();
  let occupied = 0;
  for (const slot of capacityList || []) {
    const start = (0, import_dayjs.default)(slot == null ? void 0 : slot.start_at);
    const end = (0, import_dayjs.default)(slot == null ? void 0 : slot.end_at);
    if (!start.isValid() || !end.isValid())
      continue;
    if ((now.isAfter(start) || now.isSame(start)) && (now.isBefore(end) || now.isSame(end))) {
      const pax = Number(slot == null ? void 0 : slot.pax);
      if (Number.isFinite(pax) && pax > 0)
        occupied += pax;
    }
  }
  return occupied >= totalCapacity;
}
function pickFirstCustomCapacityPaxBounds(products) {
  for (const p of products) {
    const cap = p == null ? void 0 : p.capacity;
    if (!cap || cap.type !== "custom")
      continue;
    if (!Array.isArray(cap.custom) || cap.custom.length === 0)
      continue;
    const row = cap.custom[0];
    if (!row || typeof row !== "object")
      continue;
    const raw = row;
    const out = {};
    if (raw.min !== null && raw.min !== void 0 && raw.min !== "") {
      const min = Number(raw.min);
      if (Number.isFinite(min))
        out.min = min;
    }
    if (raw.max !== null && raw.max !== void 0 && raw.max !== "") {
      const max = Number(raw.max);
      if (Number.isFinite(max))
        out.max = max;
    }
    if (out.min !== void 0 || out.max !== void 0)
      return out;
  }
  return void 0;
}
function pickFirstCustomCapacityDimensionId(products) {
  for (const p of products) {
    const cap = p == null ? void 0 : p.capacity;
    if (!cap || cap.type !== "custom")
      continue;
    if (!Array.isArray(cap.custom) || cap.custom.length === 0)
      continue;
    const row = cap.custom[0];
    if (!row || typeof row !== "object")
      continue;
    const id = row.id;
    if (id === null || id === void 0 || id === "")
      continue;
    if (typeof id === "number" && Number.isFinite(id))
      return id;
    if (typeof id === "string") {
      const trimmed = id.trim();
      if (!trimmed)
        continue;
      return trimmed;
    }
  }
  return void 0;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  aggregateItemRuleLimit,
  attachItemRuleLimitsToTopLevelProducts,
  buildItemRuleBusinessData,
  buildProductKey,
  buildProductLineFingerprint,
  buildQuantityLimitIndex,
  collectLinkProductIdsFromReservationRules,
  computeResourceIsFull,
  createEmptySummary,
  extractStrategyModelIdsFromTableConfig,
  getProductIdentityIndex,
  getSafeProductNum,
  getTopLevelProductId,
  getTopLevelVariantId,
  hasCustomCapacityProduct,
  isIdentityMatch,
  isSkuOnlyDeleteIdentity,
  normalizeEnabledItemRuleIds,
  normalizeItemRuleStrategies,
  normalizeOrderProduct,
  pickFirstCustomCapacityDimensionId,
  pickFirstCustomCapacityPaxBounds,
  pickFirstDurationMinutesFromProducts,
  resolveSkuMatchedQuantityLimits,
  toBoolean,
  toNonNegativeInt,
  toNonNegativeNumber,
  toPositiveString,
  toPriceString
});
