@curless/hotel-storefront 0.77.4 → 0.77.6

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.
@@ -232,6 +232,12 @@ const localIsoAt = (instant, tz) => {
232
232
  .map((x) => [x.type, x.value]));
233
233
  return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}`;
234
234
  };
235
+ /**
236
+ * How long a rate booked without its payment (`demoBooking`) must still be free to cancel, at the
237
+ * moment it is priced and again at the moment it is booked: an hour, so a guest who books it has
238
+ * the time to cancel it for nothing (0.77.5).
239
+ */
240
+ export const UNPAID_FREE_FOR_MS = 60 * 60_000;
235
241
  /**
236
242
  * How a rate paid in advance is priced to be SHOWN where none is sold: as the
237
243
  * test environment sells it with prepaid open (`OPN`), so the list is the same
@@ -525,8 +531,22 @@ const DETAIL_FRESH_MS = 60_000;
525
531
  const DETAIL_RETRY_MS = 2 * 60_000;
526
532
  /** The background watch tries a booking again this soon after a read of it failed (never later than its usual interval). */
527
533
  const WATCH_RETRY_MS = 30 * 60_000;
528
- /** How long prices and rooms left are kept for showing (a booking never uses them). */
529
- export const ARI_TTL_MS = 10 * 60_000;
534
+ /**
535
+ * ⚠️ HUAZHU'S OWN PULL RATE FOR ARI (`/ari/daily/offers`, `/ari/daily/inventory`), per hotel, by
536
+ * how far the dates are from today (robin 2026-11-19, from Huazhu's docs 「全量同步 —— 由分销商
537
+ * 定时调用华住 API 服务」): 0-7 days - at most once an hour; 8-30 days - once per 2 hours; 31-60
538
+ * days - once per 6 hours; 61-90 days - once per 24 hours. More often is answered 2001 「流控限制」.
539
+ * A read of prices and rooms left is kept exactly that long - for showing AND for booking (Huazhu's
540
+ * own prebook is the last check of price and rooms).
541
+ */
542
+ export const ARI_TTL_BUCKETS = [
543
+ { upToDays: 7, ttlMs: 60 * 60_000 },
544
+ { upToDays: 30, ttlMs: 2 * 3_600_000 },
545
+ { upToDays: 60, ttlMs: 6 * 3_600_000 },
546
+ { upToDays: Number.POSITIVE_INFINITY, ttlMs: 24 * 3_600_000 },
547
+ ];
548
+ /** How long a read of ARI is kept, for dates `days` after today on the hotel's own date (the strictest: the nearest night). */
549
+ export const ariTtlForDays = (days) => (ARI_TTL_BUCKETS.find((b) => days <= b.upToDays) ?? ARI_TTL_BUCKETS[0])?.ttlMs ?? 3_600_000;
530
550
  /** How long what a hotel sells (room types x rates, sell days) is kept. */
531
551
  export const PRODUCTS_TTL_MS = 6 * 3_600_000;
532
552
  /** A read of prices up to this old is shown when Huazhu will not answer (2001 / unreachable). */
@@ -554,6 +574,13 @@ export const createHuazhuHotels = (opts) => {
554
574
  /** Unpaid this long, the page is closed and the booking lapses - inside the card page's own ~31 minutes. */
555
575
  const payWithin = opts.prepaid?.payWithinMs ?? 30 * 60_000;
556
576
  const prepaidType = checkout ? 'OPN' : undefined;
577
+ // ⚠️ BOOKED WITHOUT PAYMENT ONLY WHERE NO PAYMENT IS TAKEN AT ALL, AGAINST THE LIVE HUAZHU
578
+ // (0.77.5): beside a payment page, or in a simulation or a test system, it means nothing.
579
+ if (opts.demoBooking && (checkout || opts.sandbox || opts.testEnvironment))
580
+ throw new Error('demoBooking is for the live Huazhu with no payment taken - not beside prepaid, the simulated Huazhu or its test system');
581
+ const unpaidAt = opts.demoBooking
582
+ ? { hotels: new Set(opts.demoBooking.hotels), maxOpen: opts.demoBooking.maxOpen }
583
+ : undefined;
557
584
  /**
558
585
  * One rate for one stay: sold here, or refused - and, refused only for being
559
586
  * paid in advance where no payment is taken, asked again as `SHOWN_AS`.
@@ -580,12 +607,14 @@ export const createHuazhuHotels = (opts) => {
580
607
  const listed = (p) => p.res.ok ? p : p.shown ? { ...p, res: p.shown } : undefined;
581
608
  const now = opts.now ?? (() => Date.now());
582
609
  const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
583
- // ⚠️ SHOWING IS CACHED LONG, BOOKING IS NEVER (0.77.3, robin 11-19: Huazhu's
584
- // production answered 2001 流控 after four calls). What a hotel sells (rooms
585
- // x rates, days ahead) changes rarely: six hours. Prices and rooms left, for
586
- // showing - tiles, the page, a comparison - ten minutes. A booking, and the
587
- // review that feeds it, asks fresh (`fresh: true`) and never takes this.
588
- const ariTtl = opts.ariTtlMs ?? ARI_TTL_MS;
610
+ // ⚠️ SHOWING AND BOOKING SHARE ONE CACHE, KEPT AS LONG AS HUAZHU ALLOWS ASKING (0.77.3, robin
611
+ // 11-19: Huazhu's production answered 2001 流控 after four calls). What a hotel sells (rooms x
612
+ // rates, days ahead) changes rarely: six hours. Prices and rooms left: by how far the stay is
613
+ // from today - see `ARI_TTL_BUCKETS`; `data.api.ariTtlMs`, when set, replaces that. A booking,
614
+ // and the review that feeds it, take the same cache (it used to ask fresh, and a booking right
615
+ // after a view was refused 流控): Huazhu's prebook checks price and rooms last, and a "moved"
616
+ // from it is the guest's `price-changed` and drops the entry (`dropAri`).
617
+ const ariTtlOf = (checkIn) => opts.ariTtlMs ?? ariTtlForDays(Math.max(0, nightsBetween(today(), checkIn)));
589
618
  const productsTtl = opts.productsTtlMs ?? PRODUCTS_TTL_MS;
590
619
  const allowTags = new Set(opts.allowTags ?? []);
591
620
  const view = {
@@ -785,17 +814,16 @@ export const createHuazhuHotels = (opts) => {
785
814
  /**
786
815
  * A hotel Huazhu answered "too many requests" (2009) for, let be until then -
787
816
  * a minute, doubling to ten while it goes on (2026-10-16 audit, P1-11: asked
788
- * again at once, every guest's ask). Prices last read are used meanwhile; a
789
- * booking's own fresh ask is not held back.
817
+ * again at once, every guest's ask). Prices last read are used meanwhile,
818
+ * booking included.
790
819
  */
791
820
  const ariBackoff = new Map();
792
821
  /**
793
822
  * ⚠️ HUAZHU'S OWN FLOW CONTROL (0.77.3): 2001 with 「流控限制」 - production
794
823
  * answered it after four calls 3.5 s apart, and a list tile said no price
795
824
  * while the page a moment later had them. When it is answered, no price call
796
- * for SHOWING goes out for `ARI_PAUSE_MS` (deployment-wide); what was read
797
- * last is shown instead, if it is under an hour old. A booking's fresh ask is
798
- * never held back, and never served from the old.
825
+ * goes out for `ARI_PAUSE_MS` (deployment-wide); what was read
826
+ * last is used instead, if it is under an hour past the time it was kept for.
799
827
  */
800
828
  let ariPausedUntil = 0;
801
829
  const isFlowControl = (err) => err instanceof HuazhuRefusal &&
@@ -812,9 +840,10 @@ export const createHuazhuHotels = (opts) => {
812
840
  console.error(`[huazhu] Huazhu answered 2001 流控限制: price calls for showing paused ${ARI_PAUSE_MS / 1000}s`);
813
841
  };
814
842
  /** The last read of `key`, when it is under an hour old - or nothing. */
815
- const staleOf = (cache, key, err) => {
843
+ const staleOf = (cache, key, err, ttl) => {
816
844
  const hit = cache.get(key);
817
- if (!hit || now() - hit.at >= ARI_STALE_MS)
845
+ // Up to an hour past the time it was kept for: a read kept 6 hours would otherwise never be stale.
846
+ if (!hit || now() - hit.at >= ttl + ARI_STALE_MS)
818
847
  return undefined;
819
848
  const why = isFlowControl(err)
820
849
  ? '2001 流控'
@@ -826,19 +855,19 @@ export const createHuazhuHotels = (opts) => {
826
855
  };
827
856
  const pausedError = (path) => new HuazhuUnreachable(path, 'not sent - paused after Huazhu answered 2001 流控限制');
828
857
  /** Every product's prices, rules and rooms left, one element per date from `start` to `end`. */
829
- const ariFor = async (hotelId, start, end, fresh = false) => {
858
+ const ariFor = async (hotelId, start, end) => {
830
859
  const key = `${hotelId}|${start}|${end}`;
831
860
  const hit = ariCache.get(key);
832
- if (!fresh && hit && now() - hit.at < ariTtl)
861
+ if (hit && now() - hit.at < ariTtlOf(start))
833
862
  return hit.value;
834
863
  const held = ariBackoff.get(hotelId);
835
- if (!fresh && held && now() < held.until) {
864
+ if (held && now() < held.until) {
836
865
  if (hit)
837
866
  return hit.value;
838
867
  throw new HuazhuRefusal(CODES.rateLimited, 'Too many requests', '', '/ari/daily/offers');
839
868
  }
840
- if (!fresh && now() < ariPausedUntil) {
841
- const old = staleOf(ariCache, key, new HuazhuRefusal(CODES.systemError, '', '流控限制', ''));
869
+ if (now() < ariPausedUntil) {
870
+ const old = staleOf(ariCache, key, new HuazhuRefusal(CODES.systemError, '', '流控限制', ''), ariTtlOf(start));
842
871
  if (old)
843
872
  return old;
844
873
  throw pausedError('/ari/daily/offers');
@@ -871,8 +900,7 @@ export const createHuazhuHotels = (opts) => {
871
900
  }
872
901
  if (isFlowControl(err))
873
902
  pauseAri();
874
- // A booking's fresh ask never takes an old read.
875
- const old = !fresh && staleable(err) ? staleOf(ariCache, key, err) : undefined;
903
+ const old = staleable(err) ? staleOf(ariCache, key, err, ariTtlOf(start)) : undefined;
876
904
  if (old)
877
905
  return old;
878
906
  throw err;
@@ -901,8 +929,29 @@ export const createHuazhuHotels = (opts) => {
901
929
  ariCache.delete(ariCache.keys().next().value);
902
930
  return out;
903
931
  };
932
+ /**
933
+ * Until when a rate is free to cancel, where that is at least `UNPAID_FREE_FOR_MS` from now -
934
+ * else undefined. What lets a rate paid in advance be booked without its payment (0.77.5).
935
+ */
936
+ const freeLongEnough = (s, checkIn) => {
937
+ const policy = parseCancelPolicy(s.cancelCode);
938
+ const until = policy ? freeUntilOf(policy, checkIn, opts.tz, now()) : undefined;
939
+ return until !== undefined && until >= now() + UNPAID_FREE_FOR_MS ? until : undefined;
940
+ };
941
+ /**
942
+ * A rate refused only for being paid in advance, at a hotel `demoBooking` names, made bookable
943
+ * without its payment - the rate as sold paid in advance (`shown`), while it is free to cancel
944
+ * for long enough. Nights only; anything else is left as it was.
945
+ */
946
+ const unpaidOf = (hotelId, checkIn, priced) => unpaidAt?.hotels.has(hotelId) &&
947
+ !priced.res.ok &&
948
+ priced.res.kind === 'prepaid' &&
949
+ priced.shown &&
950
+ freeLongEnough(priced.shown, checkIn) !== undefined
951
+ ? { res: priced.shown, unpaid: true }
952
+ : priced;
904
953
  /** Every sellable-or-not product of one hotel for one stay. */
905
- const priceStay = async (h, stay, rooms, fresh = false) => {
954
+ const priceStay = async (h, stay, rooms) => {
906
955
  const { value: all, sellDays } = await productsWithDays(h.hotelId);
907
956
  // Nights only: rooms by the hour are priced for today apart - `priceHourly`.
908
957
  const products = all.filter((p) => p.checkinType === 'DAY');
@@ -926,7 +975,7 @@ export const createHuazhuHotels = (opts) => {
926
975
  }))
927
976
  .filter((x) => !(x.roomType && x.roomType.status === 0));
928
977
  }
929
- const ari = await ariFor(h.hotelId, stay.checkIn, stay.checkOut, fresh);
978
+ const ari = await ariFor(h.hotelId, stay.checkIn, stay.checkOut);
930
979
  const context = {
931
980
  checkIn: stay.checkIn,
932
981
  checkOut: stay.checkOut,
@@ -943,11 +992,12 @@ export const createHuazhuHotels = (opts) => {
943
992
  .map((product) => {
944
993
  const roomType = (h.hotelRoomTypeList ?? []).find((r) => r.roomTypeCode === product.roomTypeCode);
945
994
  const w = ari.get(roomIdOf(product));
946
- const { res, shown } = w
947
- ? priceOne(product, w, roomType, context)
995
+ const { res, shown, unpaid } = w
996
+ ? unpaidOf(h.hotelId, stay.checkIn, priceOne(product, w, roomType, context))
948
997
  : {
949
998
  res: { ok: false, kind: 'no-price', why: 'no price for those nights' },
950
999
  shown: undefined,
1000
+ unpaid: undefined,
951
1001
  };
952
1002
  const ifOpen = w && !res.ok && res.kind === 'sold-out'
953
1003
  ? openOne(product, w, roomType, context)
@@ -958,6 +1008,7 @@ export const createHuazhuHotels = (opts) => {
958
1008
  res,
959
1009
  ...(shown ? { shown } : {}),
960
1010
  ...(ifOpen ? { ifOpen } : {}),
1011
+ ...(unpaid ? { unpaid } : {}),
961
1012
  };
962
1013
  })
963
1014
  .filter((x) => !(x.roomType && x.roomType.status === 0));
@@ -968,13 +1019,15 @@ export const createHuazhuHotels = (opts) => {
968
1019
  * these for today only ("时租房 … 只能查 startDate 为当天的 ARI"), asked apart
969
1020
  * from the nights with `checkinType: HOUR`.
970
1021
  */
971
- const hourlyAriFor = async (hotelId, date, fresh = false) => {
1022
+ const hourlyAriFor = async (hotelId, date) => {
972
1023
  const key = `${hotelId}|${date}`;
973
1024
  const hit = hourlyAriCache.get(key);
974
- if (!fresh && hit && now() - hit.at < ariTtl)
1025
+ // Rooms by the hour are today's: the nearest bucket.
1026
+ const hourlyTtl = opts.ariTtlMs ?? ariTtlForDays(0);
1027
+ if (hit && now() - hit.at < hourlyTtl)
975
1028
  return hit.value;
976
- if (!fresh && now() < ariPausedUntil) {
977
- const old = staleOf(hourlyAriCache, key, new HuazhuRefusal(CODES.systemError, '', '流控限制', ''));
1029
+ if (now() < ariPausedUntil) {
1030
+ const old = staleOf(hourlyAriCache, key, new HuazhuRefusal(CODES.systemError, '', '流控限制', ''), hourlyTtl);
978
1031
  if (old)
979
1032
  return old;
980
1033
  throw pausedError('/ari/daily/offers');
@@ -995,7 +1048,7 @@ export const createHuazhuHotels = (opts) => {
995
1048
  ]).catch((err) => {
996
1049
  if (isFlowControl(err))
997
1050
  pauseAri();
998
- const old = !fresh && staleable(err) ? staleOf(hourlyAriCache, key, err) : undefined;
1051
+ const old = staleable(err) ? staleOf(hourlyAriCache, key, err, hourlyTtl) : undefined;
999
1052
  if (old)
1000
1053
  return old;
1001
1054
  throw err;
@@ -1021,7 +1074,7 @@ export const createHuazhuHotels = (opts) => {
1021
1074
  * Singapore it is still yesterday nowhere that matters, and a start that has
1022
1075
  * already gone by on the hotel's clock is not offered.
1023
1076
  */
1024
- const priceHourly = async (h, guests, rooms, fresh = false) => {
1077
+ const priceHourly = async (h, guests, rooms) => {
1025
1078
  const products = (await productsOf(h.hotelId)).filter((p) => p.checkinType === 'HOUR');
1026
1079
  if (products.length === 0)
1027
1080
  return [];
@@ -1041,7 +1094,7 @@ export const createHuazhuHotels = (opts) => {
1041
1094
  const live = todays.filter((p) => bookableNow(p.bookWindow, date, clock));
1042
1095
  if (live.length === 0)
1043
1096
  return todays.map(gone).filter((x) => !(x.roomType && x.roomType.status === 0));
1044
- const ari = await hourlyAriFor(h.hotelId, date, fresh);
1097
+ const ari = await hourlyAriFor(h.hotelId, date);
1045
1098
  // One day, priced once: `sell` reads it as a single night from today.
1046
1099
  const context = {
1047
1100
  checkIn: date,
@@ -1184,12 +1237,12 @@ export const createHuazhuHotels = (opts) => {
1184
1237
  ...(roomPhoto(h, p.product.roomTypeCode)
1185
1238
  ? { imageUrl: roomPhoto(h, p.product.roomTypeCode) }
1186
1239
  : {}),
1187
- // A whole yuan, as a hotel quotes a nightly rate - not ¥343.50 (2026-10-05
1188
- // audit, P3). The stay total stays exact. A room by the hour is the
1189
- // price of its hours, and no nights.
1190
- nightly: hourly
1191
- ? money(total, cur)
1192
- : money(Math.round(pre / n / minorFactor(cur)) * minorFactor(cur), cur),
1240
+ // A whole yuan where the night is one, as a hotel quotes a nightly rate. ⚠️ NEVER ROUNDED
1241
+ // TO ONE WHEN IT IS NOT (0.77.6, robin 11-19: 「房价 ¥221.00,总价另含 ¥13.26」 beside a
1242
+ // total of ¥234.22 - 221.00 + 13.26 is not 234.22): the night is the before-tax figure to
1243
+ // the cent, so the rate, the taxes and the total add up on the card (2026-10-05's whole
1244
+ // yuan made them not). A room by the hour is the price of its hours, and no nights.
1245
+ nightly: hourly ? money(total, cur) : money(Math.round(pre / n), cur),
1193
1246
  stayTotal: money(total, cur),
1194
1247
  taxesAndFees: money(total - pre, cur),
1195
1248
  nights: hourly ? 0 : n,
@@ -1222,7 +1275,10 @@ export const createHuazhuHotels = (opts) => {
1222
1275
  // rate is one `priceOne` SHOWED: listed and marked as it is sold, and
1223
1276
  // not booked here (robin, 2026-10-30).
1224
1277
  payment: s.prepaid ? 'prepaid' : 'at-hotel',
1225
- ...(s.prepaid && !prepaidType ? { notSoldHere: 'prepaid' } : {}),
1278
+ // …but one booked without its payment (`demoBooking`, 0.77.5) IS booked here: still
1279
+ // paid in advance, never "not sold here".
1280
+ ...(s.prepaid && !prepaidType && !p.unpaid ? { notSoldHere: 'prepaid' } : {}),
1281
+ ...(p.unpaid ? { paymentNotConnected: true } : {}),
1226
1282
  ...(hourly ? { hourly } : {}),
1227
1283
  ...(maxChildren > 0 && maxChildren < 99 ? { maxChildren } : {}),
1228
1284
  };
@@ -1394,8 +1450,19 @@ export const createHuazhuHotels = (opts) => {
1394
1450
  return { why: 'Not on sale for those nights.', code: 'closed' };
1395
1451
  return { why: 'No room here can be booked for those nights.', code: 'unavailable' };
1396
1452
  };
1453
+ /**
1454
+ * Forgets what was read of a stay's prices and rooms, after Huazhu's prebook or booking said
1455
+ * the price moved or no room is left: the next view re-reads. That one read is allowed to
1456
+ * break the pull rate (`ARI_TTL_BUCKETS`) - a guest was just told a price that is not true.
1457
+ */
1458
+ const dropAri = (hotelId, stay, hourly) => {
1459
+ if (hourly)
1460
+ hourlyAriCache.delete(`${hotelId}|${stay.checkIn}`);
1461
+ else
1462
+ ariCache.delete(`${hotelId}|${stay.checkIn}|${stay.checkOut}`);
1463
+ };
1397
1464
  // --------------------------------------------------------------- quote ----
1398
- const quoteLines = async (trip, fresh = false) => {
1465
+ const quoteLines = async (trip) => {
1399
1466
  const lines = [];
1400
1467
  const dropped = [];
1401
1468
  const sold = new Map();
@@ -1434,8 +1501,8 @@ export const createHuazhuHotels = (opts) => {
1434
1501
  let priced;
1435
1502
  try {
1436
1503
  priced = hourly
1437
- ? await priceHourly(h, line.stay.guests, wanted, fresh)
1438
- : await priceStay(h, line.stay, wanted, fresh);
1504
+ ? await priceHourly(h, line.stay.guests, wanted)
1505
+ : await priceStay(h, line.stay, wanted);
1439
1506
  }
1440
1507
  catch (err) {
1441
1508
  dropped.push({
@@ -1457,7 +1524,11 @@ export const createHuazhuHotels = (opts) => {
1457
1524
  dropped.push({
1458
1525
  title: `${hotelName} - ${roomTypeOf(p.product)}`,
1459
1526
  why: p.shown
1460
- ? 'This rate is paid in advance, and a stay paid in advance cannot be booked here yet - only rates paid at the hotel can.'
1527
+ ? unpaidAt?.hotels.has(h.hotelId) && !hourly
1528
+ ? // Where some rates paid in advance are booked without payment (0.77.5): only
1529
+ // while they are free to cancel for at least another hour.
1530
+ 'This rate is paid in advance, and here one is booked only while it is free to cancel for at least another hour - this one is not.'
1531
+ : 'This rate is paid in advance, and a stay paid in advance cannot be booked here yet - only rates paid at the hotel can.'
1461
1532
  : `${p.res.why}.`,
1462
1533
  });
1463
1534
  continue;
@@ -1538,6 +1609,7 @@ export const createHuazhuHotels = (opts) => {
1538
1609
  nights: room.nights,
1539
1610
  ...(hourly ? { hourly } : {}),
1540
1611
  ...(room.payment === 'prepaid' ? { payment: 'prepaid' } : {}),
1612
+ ...(room.paymentNotConnected ? { paymentNotConnected: true } : {}),
1541
1613
  quantity: wanted,
1542
1614
  unit: room.nightly,
1543
1615
  total: money(preTax, room.stayTotal.currency),
@@ -1573,8 +1645,8 @@ export const createHuazhuHotels = (opts) => {
1573
1645
  };
1574
1646
  };
1575
1647
  const quote = async (trip) => {
1576
- // Fresh: this is the review a booking follows - never a ten-minute-old price.
1577
- const { sold, ...q } = await quoteLines(trip, true);
1648
+ // The cache, like showing: Huazhu's prebook is the last check of the price.
1649
+ const { sold, ...q } = await quoteLines(trip);
1578
1650
  void sold;
1579
1651
  return q;
1580
1652
  };
@@ -1666,6 +1738,9 @@ export const createHuazhuHotels = (opts) => {
1666
1738
  ...(b.cancellationFee ? { cancellationFee: b.cancellationFee } : {}),
1667
1739
  ...(b.requests ? { requests: b.requests } : {}),
1668
1740
  ...(b.prepaid ? { payment: paymentOf(b) } : {}),
1741
+ ...(b.paymentNotConnected ? { paymentNotConnected: true } : {}),
1742
+ // Huazhu's own order number, beside our code (0.77.6): only `resId`, never the short `resCode`.
1743
+ ...(b.resId && b.resId !== b.confirmationCode ? { orderNumber: b.resId } : {}),
1669
1744
  });
1670
1745
  /**
1671
1746
  * The codes a guest may have been given for a booking: ours, and the
@@ -1959,6 +2034,17 @@ export const createHuazhuHotels = (opts) => {
1959
2034
  return false;
1960
2035
  }
1961
2036
  };
2037
+ /**
2038
+ * The bookings without payment (`demoBooking`, 0.77.5) that stand - booked or being booked,
2039
+ * not cancelled, the stay not over: what `maxOpen` counts, from the bookings written down here.
2040
+ */
2041
+ const openUnpaid = () => store.all().filter((b) => !!b.paymentNotConnected && isLive(b));
2042
+ /** A booking without payment's free-cancellation deadline, for the log (no guest's details in it). */
2043
+ const freeUntilSaid = (b) => {
2044
+ const policy = policyOf(b.cancelCode);
2045
+ const until = policy ? freeUntilOf(policy, b.stay.checkIn, b.tz, now()) : undefined;
2046
+ return until !== undefined ? new Date(until).toISOString() : '-';
2047
+ };
1962
2048
  /** The booking itself, one request at a time per conversation and email - see `single`. */
1963
2049
  const book = async (lines, shown, tripKey, email, guest, contact, who, requests) => {
1964
2050
  // ⚠️ THE SAME TRIP ASKED FOR AGAIN IS ANSWERED WITH THE FIRST. A second
@@ -2872,8 +2958,10 @@ export const createHuazhuHotels = (opts) => {
2872
2958
  }
2873
2959
  };
2874
2960
  const bookHeld = async (lines, shown, tripKey, email, guest, contact, who, requests, slot) => {
2875
- // Priced afresh, not from the cache: this is the price that will be sent.
2876
- const priced = await quoteLines({ lines }, true);
2961
+ // Priced from the cache (kept as long as Huazhu allows asking), not asked again: Huazhu's
2962
+ // prebook below is the check of the price that will be sent, and its "moved" is the
2963
+ // guest's price-changed (`failStay`), dropping the cache entry.
2964
+ const priced = await quoteLines({ lines });
2877
2965
  // ⚠️ AT THE PRICE AND TERMS THE GUEST SAW, OR NOT AT ALL - see `ShownQuote`.
2878
2966
  // The whole trip's question, asked before any stay is booked: the guest
2879
2967
  // has not agreed to a price they were not shown, and the trip is shown to
@@ -2928,11 +3016,15 @@ export const createHuazhuHotels = (opts) => {
2928
3016
  const qline = priced.lines[soldAt.indexOf(i)];
2929
3017
  plans.push({ i, line, sold, qline });
2930
3018
  }
3019
+ // A stay whose money is taken here before Huazhu is asked. ⚠️ NOT ONE BOOKED WITHOUT ITS
3020
+ // PAYMENT (`demoBooking`, 0.77.5): paid in advance, but nothing is taken - it is booked
3021
+ // as a stay paid at the hotel is, below, and never opens a payment page.
3022
+ const paysHere = (p) => p.sold.res.prepaid && !p.sold.unpaid;
2931
3023
  // ⚠️ A STAY PAID IN ADVANCE IS BOOKED ON ITS OWN (v1): its money is taken
2932
3024
  // before Huazhu is asked, and a trip half paid and half not - or two paid
2933
3025
  // stays, one refused - has no whole refund to give (总线程, 2026-10-12).
2934
3026
  // The whole trip's rule: nothing is booked.
2935
- if (lines.length > 1 && plans.some((p) => p.sold.res.prepaid))
3027
+ if (lines.length > 1 && plans.some(paysHere))
2936
3028
  throw new Error('Nothing was booked: a stay paid in advance is booked on its own here. Take the other stays out of the trip, book this one, then book the rest.');
2937
3029
  // ⚠️ THE OTHER CEILING (2026-10-21 re-audit, T2-14): a request to pay in
2938
3030
  // advance costs one prebook at Huazhu and one payment page at Stripe
@@ -2941,7 +3033,7 @@ export const createHuazhuHotels = (opts) => {
2941
3033
  // flood of them stops more of them and not the bookings that are real. It
2942
3034
  // is checked before Huazhu is asked anything; this request's own place is
2943
3035
  // already in `slot`.
2944
- if (plans.some((p) => p.sold.res.prepaid)) {
3036
+ if (plans.some(paysHere)) {
2945
3037
  slot.unpaid = true;
2946
3038
  const unpaid = store.all().filter((b) => now() - Date.parse(b.createdAt) < DAY_MS && unpaidAsk(b)).length +
2947
3039
  slotsWhere((x) => !!x.unpaid);
@@ -2954,6 +3046,20 @@ export const createHuazhuHotels = (opts) => {
2954
3046
  throw new Error(`Nothing was booked: booking a stay paid in advance here is paused for now - the limit on payment requests left unpaid in a day has been reached. Try again later, pay at the hotel where the rate allows it, or book with ${opts.brand} directly.`);
2955
3047
  }
2956
3048
  }
3049
+ // ⚠️ AT MOST `maxOpen` BOOKINGS WITHOUT PAYMENT STAND AT ONCE (`demoBooking`, 0.77.5): counted
3050
+ // from the bookings written down here and the ones being made now (`slots`), and checked
3051
+ // before Huazhu is asked anything - past it, nothing is sent. Its places are taken in the
3052
+ // same breath as the check, as the other limits' are (`slots`).
3053
+ const noPayment = plans.filter((p) => p.sold.unpaid);
3054
+ if (noPayment.length && unpaidAt) {
3055
+ const open = openUnpaid().length + [...slots].reduce((a, x) => a + (x.noPayment ?? 0), 0);
3056
+ if (open + noPayment.length > unpaidAt.maxOpen) {
3057
+ const where = [...new Set(noPayment.map((p) => p.line.hotelId))].join(',');
3058
+ console.log(`[huazhu demo] refused ${where}: ${open} of ${unpaidAt.maxOpen} open - nothing sent to Huazhu`);
3059
+ throw Object.assign(new Error(`Nothing was booked, and nothing was sent to ${opts.brand}: at most ${unpaidAt.maxOpen} bookings of rates paid in advance can stand here at once without payment, and ${open} already do. Cancel one that is not needed (the bookings list has them), then ask again.`), { code: 'open-orders', max: unpaidAt.maxOpen });
3060
+ }
3061
+ slot.noPayment = noPayment.length;
3062
+ }
2957
3063
  // Prebook is Huazhu's own check of price, rooms and rules - for each stay
2958
3064
  // before any is booked, so a stay it turns down is said with the others'
2959
3065
  // outcome, not after them.
@@ -2985,6 +3091,8 @@ export const createHuazhuHotels = (opts) => {
2985
3091
  const rooms = plan.qline.quantity ?? 1;
2986
3092
  if (err instanceof HuazhuRefusal) {
2987
3093
  const { code, args } = refusalCode(err, rooms);
3094
+ if (code === 'price-changed' || code === 'sold-out')
3095
+ dropAri(plan.line.hotelId, plan.line.stay, !!plan.line.hourly);
2988
3096
  failStay(plan.line, refusalWords(err, title, s.currency), code, args, named);
2989
3097
  }
2990
3098
  else
@@ -3002,7 +3110,7 @@ export const createHuazhuHotels = (opts) => {
3002
3110
  // ⚠️ PAID FIRST, BOOKED AFTER. A stay paid in advance is not asked of
3003
3111
  // Huazhu until the guest has paid on Stripe's checkout page - then
3004
3112
  // `settlePrepaid` books it, and gives the money back whole if it cannot.
3005
- const prepaidPlan = plans.find((p) => p.sold.res.prepaid);
3113
+ const prepaidPlan = plans.find(paysHere);
3006
3114
  if (prepaidPlan) {
3007
3115
  const plan = prepaidPlan;
3008
3116
  const s = plan.sold.res;
@@ -3146,6 +3254,9 @@ export const createHuazhuHotels = (opts) => {
3146
3254
  tz: opts.tz,
3147
3255
  roomTypeCode: plan.sold.product.roomTypeCode,
3148
3256
  rateCode: plan.sold.product.rateCode,
3257
+ // Booked without its payment (`demoBooking`, 0.77.5): kept on the booking, so it is
3258
+ // said so - and counted against `maxOpen` - whatever the setting is later.
3259
+ ...(plan.sold.unpaid ? { paymentNotConnected: true } : {}),
3149
3260
  // ⚠️ SET BEFORE THE CALL: a process that dies mid-call leaves a
3150
3261
  // record the reconciler follows up on restart.
3151
3262
  pendingSince: now(),
@@ -3170,6 +3281,9 @@ export const createHuazhuHotels = (opts) => {
3170
3281
  }
3171
3282
  made.push(row);
3172
3283
  slot.n -= 1;
3284
+ // Written down: from here it counts against `maxOpen` as a booking, not as a place held.
3285
+ if (plan.sold.unpaid && slot.noPayment)
3286
+ slot.noPayment -= 1;
3173
3287
  const reservation = {
3174
3288
  roomTypeCode: plan.sold.product.roomTypeCode,
3175
3289
  rateCode: plan.sold.product.rateCode,
@@ -3261,6 +3375,8 @@ export const createHuazhuHotels = (opts) => {
3261
3375
  store.update(id, { pendingSince: undefined, status: 'failed' });
3262
3376
  made.pop();
3263
3377
  const { code, args } = refusalCode(refusal, rooms);
3378
+ if (code === 'price-changed' || code === 'sold-out')
3379
+ dropAri(plan.line.hotelId, plan.line.stay, !!plan.line.hourly);
3264
3380
  failStay(plan.line, refusalWords(refusal, title, cur), code, args, named);
3265
3381
  continue;
3266
3382
  }
@@ -3279,6 +3395,13 @@ export const createHuazhuHotels = (opts) => {
3279
3395
  finally {
3280
3396
  store.close(tripRef, failed.length ? { failed } : {});
3281
3397
  }
3398
+ // One line a booking made without its payment (0.77.5) - Huazhu's order, ours, and until
3399
+ // when it is free to cancel. No guest's name, email or phone.
3400
+ for (const b of made) {
3401
+ const row = store.get(b.id) ?? b;
3402
+ if (row.paymentNotConnected)
3403
+ console.log(`[huazhu demo] booked ${row.hotelId} resId=${row.resId ?? '-'} code=${row.confirmationCode} status=${row.status} freeUntil=${freeUntilSaid(row)}`);
3404
+ }
3282
3405
  return { booked: made.map((b) => publicBooking(store.get(b.id) ?? b)), failed };
3283
3406
  };
3284
3407
  /**
@@ -3424,6 +3547,7 @@ export const createHuazhuHotels = (opts) => {
3424
3547
  // the guest was shown - the card page is closed too, and the stay
3425
3548
  // lapses (paid on it meanwhile, it goes on as that payment).
3426
3549
  if (said === 'price-changed' || said === 'sold-out') {
3550
+ dropAri(row.hotelId, row.stay, !!row.hourly);
3427
3551
  if (p.sessionId) {
3428
3552
  // ⚠️ THE STAY LAPSES ONLY ONCE THE CARD PAGE IS SEEN CLOSED
3429
3553
  // (2026-10-21 re-audit, T2-1): this branch swallowed a close that
@@ -3652,6 +3776,25 @@ export const createHuazhuHotels = (opts) => {
3652
3776
  ...(opts.hourly ? { hourly: true } : {}),
3653
3777
  ...(checkout ? { prepaid: true } : {}),
3654
3778
  ...(checkout && unionpay ? { unionpay: true } : {}),
3779
+ // Where rates paid in advance are booked without payment (0.77.6), by name: what the model
3780
+ // reads must name the hotel. A hotel not in the catalog yet is named by its id.
3781
+ ...(unpaidAt
3782
+ ? {
3783
+ unpaidBooking: {
3784
+ hotels: [...unpaidAt.hotels].map((id) => {
3785
+ const raw = catalog.all().find((h) => String(h.hotelId) === id);
3786
+ return {
3787
+ id,
3788
+ name: raw
3789
+ ? raw.hotelNameEn
3790
+ ? `${raw.hotelName} (${raw.hotelNameEn})`
3791
+ : raw.hotelName
3792
+ : `hotel ${id}`,
3793
+ };
3794
+ }),
3795
+ },
3796
+ }
3797
+ : {}),
3655
3798
  },
3656
3799
  /**
3657
3800
  * One pass over the bookings paid in advance - every 10 seconds while the
@@ -3725,6 +3868,24 @@ export const createHuazhuHotels = (opts) => {
3725
3868
  ...(ceiling ? { ceilingHitAt: new Date(ceilingHitAt).toISOString() } : {}),
3726
3869
  ...(store.writeFailing ? { writeFailing: store.writeFailing } : {}),
3727
3870
  ...(client.misconfigured ? { misconfigured: client.misconfigured } : {}),
3871
+ // Booking without payment (0.77.5): where it is on, how many stand, and the first
3872
+ // free-cancellation deadline among them - a stay paid in advance kept past it is owed.
3873
+ ...(unpaidAt
3874
+ ? (() => {
3875
+ const deadlines = openUnpaid().map(freeUntilSaid);
3876
+ const next = deadlines.filter((x) => x !== '-').sort()[0];
3877
+ return {
3878
+ demoBooking: {
3879
+ hotels: [...unpaidAt.hotels],
3880
+ maxOpen: unpaidAt.maxOpen,
3881
+ open: deadlines.length,
3882
+ ...(next ? { nextFreeUntil: next } : {}),
3883
+ // Standing past their free cancellation: nobody paid, and Huazhu may bill them.
3884
+ pastFreeCancellation: deadlines.filter((x) => x === '-').length,
3885
+ },
3886
+ };
3887
+ })()
3888
+ : {}),
3728
3889
  };
3729
3890
  },
3730
3891
  /** A person dealt with a booking that needed one - see `BookingStore.resolve`. */
@@ -4020,6 +4181,7 @@ export const createHuazhuHotels = (opts) => {
4020
4181
  ...(b.room.meal ? { meal: b.room.meal } : {}),
4021
4182
  ...(b.room.payment ? { payment: b.room.payment } : {}),
4022
4183
  ...(b.room.notSoldHere ? { notSoldHere: b.room.notSoldHere } : {}),
4184
+ ...(b.room.paymentNotConnected ? { paymentNotConnected: true } : {}),
4023
4185
  },
4024
4186
  };
4025
4187
  };
@@ -4472,11 +4634,14 @@ export const createHuazhuHotels = (opts) => {
4472
4634
  refund: zero,
4473
4635
  rule: forbidden
4474
4636
  ? `This rate cannot be cancelled now. ${rule}`
4475
- : opts.sandbox
4476
- ? `${rule} This booking was not sent to Huazhu: the fee is worked out as a real booking's would be, and nothing is charged to anyone.`
4477
- : opts.testEnvironment
4478
- ? `${rule} This booking holds no room for anyone: the fee is worked out as a real booking's would be, and nothing is charged to anyone.`
4479
- : `${rule} Nothing was paid here - the booking is paid at the hotel - so any fee is charged under the hotel's terms, and Huazhu works out the exact amount when it cancels.`,
4637
+ : b.paymentNotConnected
4638
+ ? // Booked without its payment (0.77.5): never "paid at the hotel".
4639
+ `${rule} Nothing was paid for this booking - payment is not connected here yet - so there is nothing to refund${fee === 0 ? ', and cancelling now costs nothing' : '; Huazhu works out the exact fee when it cancels'}.`
4640
+ : opts.sandbox
4641
+ ? `${rule} This booking was not sent to Huazhu: the fee is worked out as a real booking's would be, and nothing is charged to anyone.`
4642
+ : opts.testEnvironment
4643
+ ? `${rule} This booking holds no room for anyone: the fee is worked out as a real booking's would be, and nothing is charged to anyone.`
4644
+ : `${rule} Nothing was paid here - the booking is paid at the hotel - so any fee is charged under the hotel's terms, and Huazhu works out the exact amount when it cancels.`,
4480
4645
  ...(freeUntil ? { freeUntil: new Date(freeUntil).toISOString() } : {}),
4481
4646
  cancellable: !forbidden,
4482
4647
  ...facts,
@@ -4620,6 +4785,9 @@ export const createHuazhuHotels = (opts) => {
4620
4785
  throw err;
4621
4786
  }
4622
4787
  const after = store.get(b.id);
4788
+ // One line a booking without its payment cancelled (0.77.5) - with what Huazhu said it costs.
4789
+ if (after?.paymentNotConnected && after.status === 'cancelled')
4790
+ console.log(`[huazhu demo] cancelled ${after.hotelId} resId=${after.resId ?? '-'} code=${after.confirmationCode} fee=${after.cancellationFee ? formatMoney(after.cancellationFee) : '-'}`);
4623
4791
  const refund = after?.prepaid?.refund;
4624
4792
  if (refund && !refund.requestId)
4625
4793
  await refundOf(b.id, refund.reason);