@curless/hotel-storefront 0.76.0 → 0.76.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -92,12 +92,46 @@ export const MAX_PLACE = 200;
92
92
  */
93
93
  export const QUOTE_PARALLEL = 4;
94
94
  export const QUOTE_DEADLINE_MS = 15_000;
95
+ /**
96
+ * ⚠️ A LIST WITH NIGHTS IS PRICED FOR THEM, A PAGE AT A TIME (0.76.1, 总线程 11-18 - robin had
97
+ * asked why Huazhu's list said "1 night, taxes in" and Otaless's "From US$226 / night"; the
98
+ * backend's `/hotels` keeps its `minPrice` whatever the dates, questions #98): each hotel on the
99
+ * page is priced the way its own page is - `/rooms` for those nights and that party, and for more
100
+ * than one room-night one 7 `/rooms/quote` of its cheapest room - into `forStay`, as Huazhu's list
101
+ * is. At most `LIST_PRICED_MAX` hotels (the page is cut to that), `LIST_PRICE_PARALLEL` at a time -
102
+ * so no more than that many requests are out at once - each within its group's own time limit
103
+ * (`timeoutMs`, Accor's 20 s), all within `LIST_PRICE_DEADLINE_MS` (or the longest of those).
104
+ * A hotel not priced by then keeps its from-price, marked `stayUnpriced`.
105
+ */
106
+ export const LIST_PRICED_MAX = 12;
107
+ export const LIST_PRICE_PARALLEL = 3;
108
+ export const LIST_PRICE_DEADLINE_MS = 20_000;
109
+ /**
110
+ * How long a hotel's price for given nights, party and rooms is kept for the next list - the
111
+ * client keeps each read a minute too (`CACHE_MS`); this keeps the answer made of them. A price
112
+ * not had (`stayUnpriced`) is not kept.
113
+ */
114
+ export const LIST_PRICE_KEPT_MS = 3 * 60_000;
115
+ /** The most of those kept - the oldest go first. */
116
+ const LIST_PRICES_MAX = 2_000;
117
+ /** A read's time limit where the deployment gives none (client.ts's own). */
118
+ const READ_TIMEOUT_MS = 10_000;
95
119
  /** How many room names are remembered, to name a room its group did not price in time. */
96
120
  const KEPT_ROOM_NAMES = 5_000;
97
- /** Who a read is for, as the limits count it (limits.ts): the conversation, and its network by its /64. */
98
- const callerOf = (who) => who
121
+ /**
122
+ * Who a read is for, as the limits count it (limits.ts): the conversation, and its network by its /64.
123
+ *
124
+ * ⚠️ A DATED LIST'S PRICES HAVE A CONVERSATION BUCKET OF THEIR OWN (`lane` 'list', 0.76.1 - 总线程
125
+ * 11-18): a cold list of two nights is about six searches and up to 24 prices, past the 20 a
126
+ * conversation starts with. Counted in the conversation's own bucket, the last of them queued a
127
+ * second each - the list some ten seconds slower, a slow group's hotels past their time, and the
128
+ * guest's next tap on a hotel queued behind them. In their own bucket, at the same rate, they
129
+ * are still held to it per conversation - and the network's and everyone's limits count them as
130
+ * any read.
131
+ */
132
+ const callerOf = (who, lane) => who
99
133
  ? {
100
- conversation: who.sessionId,
134
+ conversation: lane ? `${who.sessionId} ${lane}` : who.sessionId,
101
135
  ...(who.ip ? { address: addressKey(who.ip) } : {}),
102
136
  }
103
137
  : undefined;
@@ -155,6 +189,19 @@ const num = (v) => {
155
189
  return typeof n === 'number' && Number.isFinite(n) ? n : undefined;
156
190
  };
157
191
  const text = (v) => typeof v === 'string' && v.trim() ? v.trim() : undefined;
192
+ /**
193
+ * A price's US-dollar figure as the backend settles it, in cents - for a price order across
194
+ * currencies only (0.68.0, robin 11-12), never shown. ⚠️ NOT A FIGURE THAT WAS NEVER CONVERTED
195
+ * (0.68.1, 酒店对接 / 总线程: the same Atour hotel came back as USD 226 on /hotels and CNY 226 on
196
+ * its rooms - questions #45 / #67): a price in another currency whose "US dollars" are the same
197
+ * number is the price itself mislabelled, not a conversion - none.
198
+ */
199
+ const usdOfPrice = (p, currency) => {
200
+ const usd = text(p?.settlementCurrency)?.toUpperCase() === 'USD' ? num(p?.settlementAmount) : undefined;
201
+ const own = num(p?.originalAmount);
202
+ const converted = currency === 'USD' || own === undefined || usd !== own;
203
+ return usd !== undefined && usd > 0 && converted ? toMinor(usd, 'USD') : undefined;
204
+ };
158
205
  const regionNames = (() => {
159
206
  try {
160
207
  return new Intl.DisplayNames(['en'], { type: 'region' });
@@ -416,6 +463,8 @@ export const createOtalessHotels = (opts) => {
416
463
  : {}),
417
464
  };
418
465
  };
466
+ /** Each room's US-dollar figure as it was read, for a dated list's price order (`usdOfPrice`). */
467
+ const roomUsd = new WeakMap();
419
468
  const toRoom = (r, stay, hotelId) => {
420
469
  const id = text(r.unifiedRoomId);
421
470
  const name = text(r.name);
@@ -431,7 +480,7 @@ export const createOtalessHotels = (opts) => {
431
480
  const nightly = money(toMinor(amount, currency), currency);
432
481
  const picture = imageOf(r.imageUrl, imageHosts, opts.picturesAt);
433
482
  const bookingUrl = bookingLinkOf(r.bookingUrl);
434
- return {
483
+ const room = {
435
484
  id,
436
485
  name,
437
486
  ...(picture ? { imageUrl: picture } : {}),
@@ -458,6 +507,10 @@ export const createOtalessHotels = (opts) => {
458
507
  roomsLeft: UNCOUNTED_ROOMS,
459
508
  uncounted: true,
460
509
  };
510
+ const usd = usdOfPrice(r.price, currency);
511
+ if (usd !== undefined)
512
+ roomUsd.set(room, usd * n);
513
+ return room;
461
514
  };
462
515
  /**
463
516
  * The hotels seen that a name fits: the ones whose name holds it - or, for a
@@ -589,8 +642,8 @@ export const createOtalessHotels = (opts) => {
589
642
  return ask();
590
643
  }
591
644
  };
592
- const roomsFor = async (h, stay, who) => {
593
- const caller = callerOf(who);
645
+ const roomsFor = async (h, stay, who, lane) => {
646
+ const caller = callerOf(who, lane);
594
647
  const wire = await asMember(authOf(h, who), (token, again) => client.rooms({
595
648
  unifiedHotelId: h.id,
596
649
  checkIn: stay.checkIn,
@@ -622,9 +675,9 @@ export const createOtalessHotels = (opts) => {
622
675
  * The trip's price and a booking's check ask it the same way, so the
623
676
  * booking's ask is answered from the client's cache (a minute).
624
677
  */
625
- const quoteWire = (h, roomId, stay, rooms, who) => asMember(authOf(h, who), async (token, again) => {
678
+ const quoteWire = (h, roomId, stay, rooms, who, lane) => asMember(authOf(h, who), async (token, again) => {
626
679
  const body = quoteBody(h, roomId, stay, rooms);
627
- const data = await client.quote(body, callerOf(who), token, again);
680
+ const data = await client.quote(body, callerOf(who, lane), token, again);
628
681
  // The price the guest is shown, with whose sign-in it was asked under (`recentQuote`) -
629
682
  // timed from when the backend gave it: the client's minute of kept answers hands the same
630
683
  // answer back, and a repeat of it is no newer price.
@@ -668,6 +721,284 @@ export const createOtalessHotels = (opts) => {
668
721
  };
669
722
  /** A room line its group gave no price for - the same sentence whether it sent none, refused, or sent it too late (C11). */
670
723
  const noPriceWhy = (h, room, late = false) => `${groupOf(h.supplier ?? '').name} ${late ? 'gave no price in time' : 'sent no price'} for ${room ?? 'the room asked for'} at ${h.name} for those nights, so it is not priced in the trip.`;
724
+ /**
725
+ * 7's answer for `wanted` of `room` on given nights, held to the room's own rate a night: the
726
+ * stay's total - or why it is none. The trip's line, a dated list's hotel and a hotel's page
727
+ * hold it alike (0.76.1).
728
+ */
729
+ const quotedTotal = (h, room, stay, wanted, q) => {
730
+ // Its own currency - or, with none, its settlement's (`priceTaken`, questions #45).
731
+ const p = priceTaken(q);
732
+ const currency = text(p.currency)?.toUpperCase();
733
+ const amount = num(p.amount);
734
+ if (p.settled && currency && amount !== undefined && amount > 0)
735
+ pricedInSettlement(h.id);
736
+ // ⚠️ AN ANSWER WITH NO PRICE IS NOT "DID NOT ANSWER": the dev backend
737
+ // quotes every room USD 0 (11-05, questions #46), and asking again
738
+ // gets the same - so it is said as the group's answer, with no "try
739
+ // again", and the room's own nightly rate is never made its total.
740
+ if (!currency || amount === undefined || amount <= 0)
741
+ return { none: 'no-price' };
742
+ const total = money(toMinor(amount, currency), currency);
743
+ // ⚠️ A TOTAL THAT DOES NOT COVER THE NIGHTS ASKED IS NOT THE STAY'S (总线程 11-12
744
+ // live test; questions #70): the dev backend priced Atour's Deluxe King CNY 132 for
745
+ // one night and CNY 132 for two - its nightly rate, whatever the nights - and the
746
+ // trip said ¥132 for a stay the room's page put at ¥264. The document's quote is
747
+ // the stay's total (「共2晚总价」); one below the room's own rate for every room-night
748
+ // asked is taken as no total: said as no price, never as the stay's - and never made
749
+ // up from the nightly rate either (#46). ⚠️ EVERY ROOM-NIGHT, NOT ALL BUT ONE (总线程's
750
+ // live test of 0.69.3, HIGH): held only against one room-night fewer, a quote of one
751
+ // night with its taxes in passed - lyf Funan, two nights at S$135.89, put in the trip
752
+ // at S$150.99. A cent a room-night is let go for rounding; nothing more.
753
+ // ⚠️ KNOWN TO HOLD BACK A FAIR STAY TOO (总线程's re-review of 0.69.4, P3): the rate
754
+ // held against every night is /rooms' one rate a night - if that is the first night's
755
+ // or a peak one, a stay whose later nights cost less is left out. None seen yet; what
756
+ // /rooms' rate is, is questions #70's to say (docs/otaless-hotels.md §15.26).
757
+ const units = room.nights * wanted;
758
+ // ⚠️ …AND ONE THAT CANNOT BE HELD AGAINST THE ROOM'S RATE IS NOT TAKEN AS IT EITHER
759
+ // (总线程's re-review of ea5c5547, P3 1): a quote in another currency than the room's
760
+ // rate - the mislabelled currencies of questions #45 / #67 - is just where a one
761
+ // night's price would pass unseen and a stay be booked at it. For more than one
762
+ // room-night it is no total, said so on the log. ⚠️ A "STAY THREE, PAY TWO" OFFER
763
+ // IS HELD BACK TOO: accepted (总线程, the same review).
764
+ const otherCurrency = room.nightly.currency !== currency;
765
+ const short = total.minor + units < room.nightly.minor * units;
766
+ const asked = `quote for ${room.id} at ${h.id}, ${stay.checkIn} to ${stay.checkOut}, ${wanted} room(s): ${currency} ${amount}`;
767
+ // ⚠️ DEV TESTING ONLY, OFF BEFORE REAL MONEY (`skipPriceChecks`, 0.71.1 - robin
768
+ // 11-13 through 总线程: 「全季先放开能订,价格不管」): the group's quote is the
769
+ // stay's total as it came, said on the log beside the room's own rate. Nothing
770
+ // is added to what the guest sees - the figure is the group's.
771
+ const unchecked = units > 1 && (otherCurrency || short) && skipPrices.has(h.supplier ?? '');
772
+ if (unchecked) {
773
+ log(`[otaless] ${asked} - the room's own rate is ${room.nightly.currency} ${room.nightly.minor / minorFactor(room.nightly.currency)} a night, for ${room.nights} night(s) x ${wanted} room(s) - taken as the stay's total all the same (skipPriceChecks; questions #70${otherCurrency ? ', #45' : ''})`);
774
+ }
775
+ else if (units > 1 && (otherCurrency || short)) {
776
+ log(otherCurrency
777
+ ? `[otaless] ${asked} - in another currency than the room's own rate (${room.nightly.currency}), so whether it covers every night cannot be told - not taken as the stay's total (questions #70, #45)`
778
+ : `[otaless] ${asked} - below ${room.nights} night(s) x ${wanted} room(s) at the room's own ${currency} ${room.nightly.minor / minorFactor(currency)} a night - not taken as the stay's total (questions #70)`);
779
+ return { none: 'no-total', otherCurrency, currency };
780
+ }
781
+ const usd = usdOfPrice(q, currency);
782
+ return { total, unchecked, ...(usd !== undefined ? { usd } : {}) };
783
+ };
784
+ /** The cheapest of a hotel's rooms that sleep the party, by the group's own rate a night. */
785
+ const cheapestRoom = (rooms) => rooms.reduce((best, r) => !best ||
786
+ (r.nightly.currency === best.nightly.currency && r.nightly.minor < best.nightly.minor)
787
+ ? r
788
+ : best, undefined);
789
+ /**
790
+ * ⚠️ THE HOTEL'S PAGE HAS THE STAY'S PRICE WHERE THE GROUP GIVES ONE (0.76.1, the review of
791
+ * 11-18, H1 - it had "CN¥1,380 a night" and no total): for more than one night, its cheapest
792
+ * room's 7 for those nights, one room - the same ask as a dated list's for one room, so a hotel
793
+ * opened from the list is answered from the client's minute of kept reads. Held as
794
+ * `quotedTotal` holds it; the other rooms stay a night's price each (`stayTotalUnquoted`).
795
+ * Not had - no answer, a limit of ours, no total - the page is as it was.
796
+ */
797
+ const withStayQuoted = async (h, rooms, stay, who) => {
798
+ if (nightsOf(stay.checkIn, stay.checkOut) <= 1)
799
+ return rooms;
800
+ const room = cheapestRoom(rooms);
801
+ if (!room)
802
+ return rooms;
803
+ try {
804
+ const checked = quotedTotal(h, room, stay, 1, await quoteWire(h, room.id, stay, 1, who));
805
+ if (checked.none)
806
+ return rooms;
807
+ const { stayTotalUnquoted: _unquoted, ...rest } = room;
808
+ const quoted = { ...rest, stayTotal: checked.total };
809
+ return rooms.map((r) => (r === room ? quoted : r));
810
+ }
811
+ catch (err) {
812
+ if (err instanceof OtalessError)
813
+ return rooms;
814
+ throw err;
815
+ }
816
+ };
817
+ /**
818
+ * One hotel priced for a dated list the way its own page is (0.76.1): `/rooms` for the nights
819
+ * and the party, its cheapest room that sleeps them, and - for more than one room-night - that
820
+ * room's 7 for `rooms` of it, held to its own rate (`quotedTotal`). One room for one night is
821
+ * `/rooms`' own figure: a night's price, taxes in, is that stay's.
822
+ */
823
+ const priceForStay = async (h, stay, rooms, who) => {
824
+ let read;
825
+ try {
826
+ read = await roomsFor(h, stay, who, 'list');
827
+ }
828
+ catch (err) {
829
+ if (err instanceof OtalessBusy)
830
+ return { kind: 'unpriced', reason: 'held' };
831
+ if (err instanceof OtalessError)
832
+ return { kind: 'unpriced', reason: 'not-answered' };
833
+ throw err;
834
+ }
835
+ // ⚠️ NO ROOM FOR THOSE NIGHTS IS SAID AS THAT, NOT AS A FROM-PRICE (0.76.1, 总线程 11-18) -
836
+ // in the words and code the hotel's own page says it with (`getHotel`).
837
+ if (read.length === 0)
838
+ return {
839
+ kind: 'none',
840
+ why: `${h.name} has no room for ${stay.checkIn} to ${stay.checkOut} here.`,
841
+ code: 'unavailable',
842
+ };
843
+ const fitting = read.filter((r) => r.sleeps >= stay.guests);
844
+ if (fitting.length === 0) {
845
+ const p = partyNeedsOf(stay.guests, Math.max(...read.map((r) => r.sleeps)));
846
+ return { kind: 'none', why: p.why, code: p.code, args: p.args };
847
+ }
848
+ const room = cheapestRoom(fitting);
849
+ if (!room)
850
+ return { kind: 'unpriced', reason: 'not-answered' };
851
+ const units = room.nights * rooms;
852
+ let total = room.nightly;
853
+ let usd = roomUsd.get(room);
854
+ if (units > 1) {
855
+ let q;
856
+ try {
857
+ q = await quoteWire(h, room.id, stay, rooms, who, 'list');
858
+ }
859
+ catch (err) {
860
+ if (err instanceof OtalessBusy)
861
+ return { kind: 'unpriced', reason: 'held' };
862
+ if (err instanceof OtalessError)
863
+ return { kind: 'unpriced', reason: 'not-answered' };
864
+ throw err;
865
+ }
866
+ const checked = quotedTotal(h, room, stay, rooms, q);
867
+ // ⚠️ A QUOTE WITH NO PRICE, OR ONE THAT DOES NOT COVER THE NIGHTS, IS NO TOTAL (questions
868
+ // #46, #70): the hotel keeps its from-price on the list, said as that - never nights times
869
+ // a night of ours.
870
+ if (checked.none)
871
+ return { kind: 'unpriced', reason: 'no-total' };
872
+ total = checked.total;
873
+ usd = checked.usd;
874
+ }
875
+ return {
876
+ kind: 'priced',
877
+ forStay: {
878
+ total,
879
+ nightly: room.nightly,
880
+ room: room.name,
881
+ rooms,
882
+ nights: room.nights,
883
+ roomsLeft: room.roomsLeft,
884
+ // ⚠️ NOT KNOWN, SO NOT SAID (`Room.terms`): the group's cancellation sentence is not
885
+ // read for "free" - and `refundable` is left out, never "non-refundable" for it.
886
+ freeCancellation: false,
887
+ ...(room.breakfast ? { meal: { plan: 'breakfast' } } : {}),
888
+ },
889
+ ...(usd !== undefined ? { usd } : {}),
890
+ };
891
+ };
892
+ /** Each dated list's hotel prices, kept `LIST_PRICE_KEPT_MS` by hotel, nights, party, rooms and membership. */
893
+ const listPrices = new Map();
894
+ const listPriceKey = (h, stay, rooms, who) => {
895
+ // ⚠️ A MEMBER'S PRICE IS THEIRS (0.59.0): priced with a linked membership's token, it is
896
+ // kept under that token's hash, never handed to anyone else.
897
+ const token = authOf(h, who)?.token;
898
+ const whose = token ? createHash('sha256').update(token).digest('base64url').slice(0, 22) : '';
899
+ return `${h.id}|${stay.checkIn}|${stay.checkOut}|${stay.guests}|${rooms}|${whose}`;
900
+ };
901
+ /** A hotel's own time limit for one read - its group's where it has one (`groupTimeoutMs`). */
902
+ const timeoutOf = (h) => {
903
+ const base = opts.timeoutMs ?? READ_TIMEOUT_MS;
904
+ const own = h.supplier ? opts.groupTimeoutMs?.[h.supplier] : undefined;
905
+ return typeof own === 'number' && Number.isFinite(own) ? Math.max(base, own) : base;
906
+ };
907
+ /**
908
+ * The hotels of a dated list's page priced for their nights (0.76.1) - at most
909
+ * `LIST_PRICED_MAX`, `LIST_PRICE_PARALLEL` at a time, each within its group's time limit and
910
+ * all within the list's; what was priced, or found to have no room, kept for the next list.
911
+ * One line on the log for each list: how many, how they came out, how long.
912
+ */
913
+ const priceList = async (hs, stay, rooms, who) => {
914
+ const t0 = performance.now();
915
+ const keptMs = opts.listPriceKeptMs ?? LIST_PRICE_KEPT_MS;
916
+ const out = new Map();
917
+ // Nothing on the page, nothing priced - and no line.
918
+ if (hs.length === 0)
919
+ return out;
920
+ const todo = [];
921
+ let kept = 0;
922
+ for (const h of hs.slice(0, LIST_PRICED_MAX)) {
923
+ const hit = listPrices.get(listPriceKey(h, stay, rooms, who));
924
+ if (hit && clock() - hit.at < keptMs) {
925
+ out.set(h.id, hit.price);
926
+ kept += 1;
927
+ }
928
+ else
929
+ todo.push(h);
930
+ }
931
+ const keep = (k, price) => {
932
+ // A price not had is not kept - except no total for the nights, which asking again gives too.
933
+ if (price.kind === 'unpriced' && price.reason !== 'no-total')
934
+ return;
935
+ listPrices.delete(k);
936
+ listPrices.set(k, { at: clock(), price });
937
+ while (listPrices.size > LIST_PRICES_MAX) {
938
+ const first = listPrices.keys().next().value;
939
+ if (first === undefined)
940
+ break;
941
+ listPrices.delete(first);
942
+ }
943
+ };
944
+ let closed = false;
945
+ await within(todo.map((h) => async () => {
946
+ const k = listPriceKey(h, stay, rooms, who);
947
+ let timer;
948
+ const late = new Promise((ok) => {
949
+ timer = setTimeout(() => ok({ kind: 'unpriced', reason: 'late' }), timeoutOf(h));
950
+ timer.unref?.();
951
+ });
952
+ const asked = priceForStay(h, stay, rooms, who).then((price) => {
953
+ // Priced after its time all the same: kept for the next list.
954
+ keep(k, price);
955
+ return price;
956
+ }, (err) => {
957
+ console.error(`[otaless] pricing ${h.id} for a dated list failed:`, err);
958
+ return { kind: 'unpriced', reason: 'not-answered' };
959
+ });
960
+ const price = await Promise.race([asked, late]);
961
+ clearTimeout(timer);
962
+ if (!closed)
963
+ out.set(h.id, price);
964
+ // ⚠️ ITS PLACE IS HELD UNTIL ITS OWN REQUEST IS BACK (0.76.1): a hotel past its time is
965
+ // said as not priced at once, but the next one is not sent while its read is still out -
966
+ // so no more than `LIST_PRICE_PARALLEL` requests are ever out for one list.
967
+ await asked;
968
+ }), opts.listPriceParallel ?? LIST_PRICE_PARALLEL, Math.max(opts.listPriceDeadlineMs ?? LIST_PRICE_DEADLINE_MS, ...todo.map(timeoutOf)));
969
+ closed = true;
970
+ for (const h of todo)
971
+ if (!out.has(h.id))
972
+ out.set(h.id, { kind: 'unpriced', reason: 'late' });
973
+ const all = [...out.values()];
974
+ const n = (f) => all.filter(f).length;
975
+ const why = (r) => n((p) => p.kind === 'unpriced' && p.reason === r);
976
+ // ⚠️ COUNTS AND TIME ONLY - never the hotels, the place or the nights asked for.
977
+ log(`[otaless] dated list priced: ${out.size} hotel(s) - ${n((p) => p.kind === 'priced')} priced, ${n((p) => p.kind === 'none')} with no room, ${n((p) => p.kind === 'unpriced')} not priced (${why('not-answered')} not answered, ${why('late')} past their time, ${why('held')} held back, ${why('no-total')} no total for the nights); ${kept} kept from an earlier list; ${Math.round(performance.now() - t0)} ms`);
978
+ return out;
979
+ };
980
+ /** A hotel on a dated list with what it came to - see `StayPrice`. */
981
+ const withStayPrice = (h, p) => {
982
+ if (!p)
983
+ return h;
984
+ if (p.kind === 'none')
985
+ return {
986
+ ...h,
987
+ noRoomsForStay: p.why,
988
+ noRoomsForStayCode: p.code,
989
+ ...(p.args ? { noRoomsForStayArgs: p.args } : {}),
990
+ };
991
+ if (p.kind === 'unpriced')
992
+ return { ...h, stayUnpriced: true };
993
+ const currency = p.forStay.total.currency;
994
+ // ⚠️ ONE HOTEL, ONE CURRENCY WITHIN AN ANSWER (as `getHotel`, questions #45): a from-price in
995
+ // another currency than its rooms are priced in is not carried beside the stay's price.
996
+ if (h.fromNightly && h.fromNightly.currency !== currency) {
997
+ const { fromNightly: _from, fromNightlyTaxes: _taxes, ...rest } = h;
998
+ return { ...rest, currency, forStay: p.forStay };
999
+ }
1000
+ return { ...h, currency: h.currency || currency, forStay: p.forStay };
1001
+ };
671
1002
  const suppliers = () => [...(opts.groups ?? []).map((g) => g.code), ...[...seen].filter((c) => !named.has(c))].map((code) => {
672
1003
  const g = named.get(code);
673
1004
  return {
@@ -865,18 +1196,11 @@ export const createOtalessHotels = (opts) => {
865
1196
  const h = !read.countryCode && COUNTRY_FIRST.has(code) && country
866
1197
  ? { ...read, countryCode: country }
867
1198
  : read;
868
- const usd = text(w.minPrice?.settlementCurrency)?.toUpperCase() === 'USD'
869
- ? num(w.minPrice?.settlementAmount)
870
- : undefined;
871
- // ⚠️ NOT A FIGURE THAT WAS NEVER CONVERTED (0.68.1, 酒店对接 / 总线程: the same
872
- // Atour hotel came back as USD 226 on /hotels and CNY 226 on its rooms - questions
873
- // #45 / #67). A price in another currency whose "US dollars" are the same number is
874
- // the price itself mislabelled, not a conversion: it is not ordered by - the hotel
875
- // goes last, as one with no US-dollar figure.
876
- const own = num(w.minPrice?.originalAmount);
877
- const converted = h.currency === 'USD' || own === undefined || usd !== own;
878
- if (usd !== undefined && usd > 0 && converted)
879
- usdOf.set(h.id, toMinor(usd, 'USD'));
1199
+ // A mislabelled figure is not ordered by - the hotel goes last, as one with no
1200
+ // US-dollar figure (`usdOfPrice`).
1201
+ const usd = usdOfPrice(w.minPrice, h.currency);
1202
+ if (usd !== undefined)
1203
+ usdOf.set(h.id, usd);
880
1204
  return [h];
881
1205
  }));
882
1206
  }
@@ -958,16 +1282,55 @@ export const createOtalessHotels = (opts) => {
958
1282
  ignored.roomTerms = true;
959
1283
  unapplied.push('Whether a room can be cancelled free or includes breakfast is only known room by room here, on each hotel for the nights asked about - this list is not narrowed by it.');
960
1284
  }
961
- const currencies = [...new Set(placed.map((h) => h.currency).filter(Boolean))];
1285
+ // ⚠️ A LIST WITH NIGHTS IS PRICED FOR THEM (0.76.1, 总线程 11-18 - see `LIST_PRICED_MAX`): the
1286
+ // page's hotels each priced as their own page prices them, into `forStay`; no room for the
1287
+ // nights said as that; one not priced in time keeps its from-price, marked `stayUnpriced`.
1288
+ // ⚠️ A PRICE ORDER AND A CEILING GO BY THOSE PRICES where every match fits on one priced page
1289
+ // (`priceEvery`) - all of them are priced first. Past that only the page is priced, and the
1290
+ // order and the ceiling went by the from-prices, as without nights - said, not hidden.
1291
+ const stay = q.stay && !f.hourly ? q.stay : undefined;
1292
+ const roomsAsked = Math.max(1, Math.floor(Number(q.rooms) > 0 ? Number(q.rooms) : 1));
1293
+ const priceKnob = q.maxNightly !== undefined || q.sort === 'price-low' || q.sort === 'price-high';
1294
+ const priceEvery = !!stay && priceKnob && passed.length <= LIST_PRICED_MAX;
1295
+ const prices = priceEvery && stay
1296
+ ? await priceList(passed, stay, roomsAsked, who)
1297
+ : new Map();
1298
+ if (priceEvery)
1299
+ passed = passed.map((h) => withStayPrice(h, prices.get(h.id)));
1300
+ /** The currency a hotel is shown in here: its stay's, where it was priced. */
1301
+ const pricedNow = new Map(passed.map((h) => [h.id, h]));
1302
+ const currencyOf = (h) => {
1303
+ const shown = pricedNow.get(h.id) ?? h;
1304
+ return shown.forStay?.total.currency ?? shown.currency;
1305
+ };
1306
+ let currencies = [...new Set(placed.map(currencyOf).filter(Boolean))];
962
1307
  const oneCurrency = currencies.length <= 1;
963
1308
  let overBudget;
1309
+ let nearest = [];
964
1310
  const beforeCeiling = passed.length;
965
1311
  if (q.maxNightly !== undefined) {
966
1312
  if (oneCurrency) {
967
1313
  const cap = currencies[0] ? toMinor(q.maxNightly, currencies[0]) : undefined;
968
- const under = passed.filter((h) => !h.fromNightly || cap === undefined || h.fromNightly.minor <= cap);
969
- overBudget = passed.length - under.length;
970
- passed = under;
1314
+ // A night of the stay where it was priced - else the from-price, as without nights. A
1315
+ // hotel with no room for the nights is no match under a ceiling, and not over it either.
1316
+ const isUnder = (h) => cap === undefined
1317
+ ? true
1318
+ : h.forStay
1319
+ ? h.forStay.nightly.minor <= cap
1320
+ : h.noRoomsForStay
1321
+ ? false
1322
+ : !h.fromNightly || h.fromNightly.minor <= cap;
1323
+ const over = passed.filter((h) => !isUnder(h) && !h.noRoomsForStay);
1324
+ overBudget = over.length;
1325
+ passed = passed.filter(isUnder);
1326
+ // ⚠️ THE MISSES ARE THE ANSWER WHERE THE CEILING EMPTIED THE LIST (as Huazhu's, 0.76.1):
1327
+ // the cheapest three over it - "nothing under X; the cheapest is Y" - never "no room".
1328
+ // A stay's price before a from-price: "the cheapest is" is said of a price for the nights.
1329
+ const nightOf = (h) => h.forStay?.nightly.minor ?? h.fromNightly?.minor ?? 0;
1330
+ if (passed.length === 0 && over.length)
1331
+ nearest = [...over]
1332
+ .sort((a, b) => (a.forStay ? 0 : 1) - (b.forStay ? 0 : 1) || nightOf(a) - nightOf(b))
1333
+ .slice(0, 3);
971
1334
  }
972
1335
  else {
973
1336
  ignored.ceiling = true;
@@ -979,18 +1342,31 @@ export const createOtalessHotels = (opts) => {
979
1342
  // dollars is put in price order by that - a hotel with none goes last, either way.
980
1343
  // The prices shown stay each hotel's own; the answer says what the order is by
981
1344
  // (`priceOrderIn`). In one currency, by the prices themselves, as before.
982
- const inUsd = !oneCurrency && placed.some((h) => usdOf.has(h.id));
1345
+ // ⚠️ PRICED FOR THE NIGHTS, BY THE STAY (0.76.1): the priced hotels first, by the stay's
1346
+ // price (its US dollars across currencies - the quote's own figure); then the ones not
1347
+ // priced, by their from-prices; then the ones with no room for the nights.
1348
+ const usdNow = (h) => {
1349
+ if (h.noRoomsForStay)
1350
+ return undefined;
1351
+ if (!h.forStay)
1352
+ return usdOf.get(h.id);
1353
+ const p = prices.get(h.id);
1354
+ return p?.kind === 'priced' ? p.usd : undefined;
1355
+ };
1356
+ const inUsd = !oneCurrency && (placed.some((h) => usdOf.has(h.id)) || passed.some((h) => !!usdNow(h)));
983
1357
  if (q.sort === 'price-low' || q.sort === 'price-high') {
984
1358
  const dir = q.sort === 'price-low' ? 1 : -1;
1359
+ const tier = (h) => (h.forStay ? 0 : h.noRoomsForStay ? 2 : 1);
1360
+ const own = (h) => h.forStay ? h.forStay.total.minor : h.noRoomsForStay ? undefined : h.fromNightly?.minor;
1361
+ const byKey = (key) => (a, b) => tier(a) - tier(b) ||
1362
+ (key(a) === undefined ? 1 : 0) - (key(b) === undefined ? 1 : 0) ||
1363
+ dir * ((key(a) ?? 0) - (key(b) ?? 0));
985
1364
  if (oneCurrency) {
986
- passed = [...passed].sort((a, b) => (a.fromNightly ? 0 : 1) - (b.fromNightly ? 0 : 1) ||
987
- dir * ((a.fromNightly?.minor ?? 0) - (b.fromNightly?.minor ?? 0)));
1365
+ passed = [...passed].sort(byKey(own));
988
1366
  }
989
1367
  else if (inUsd) {
990
- const usd = (h) => usdOf.get(h.id);
991
- passed = [...passed].sort((a, b) => (usd(a) === undefined ? 1 : 0) - (usd(b) === undefined ? 1 : 0) ||
992
- dir * ((usd(a) ?? 0) - (usd(b) ?? 0)));
993
- const without = passed.filter((h) => !usdOf.has(h.id)).length;
1368
+ passed = [...passed].sort(byKey(usdNow));
1369
+ const without = passed.filter((h) => !h.noRoomsForStay && usdNow(h) === undefined).length;
994
1370
  if (without)
995
1371
  unapplied.push(`${without} of these ${without === 1 ? 'has' : 'have'} no US-dollar figure from the hotel groups, so ${without === 1 ? 'it is' : 'they are'} at the end, not in price order.`);
996
1372
  }
@@ -999,6 +1375,14 @@ export const createOtalessHotels = (opts) => {
999
1375
  unapplied.push(`These hotels charge in ${currencies.join(', ')}; nothing here converts one into another, so they are not put in price order.`);
1000
1376
  }
1001
1377
  }
1378
+ const byFrom = [
1379
+ (q.sort === 'price-low' || q.sort === 'price-high') && (oneCurrency || inUsd)
1380
+ ? 'the price order'
1381
+ : '',
1382
+ q.maxNightly !== undefined && oneCurrency ? 'the price ceiling' : '',
1383
+ ].filter(Boolean);
1384
+ if (stay && !priceEvery && byFrom.length)
1385
+ unapplied.push(`${beforeCeiling} hotels matched - more than are priced for those nights at once (${LIST_PRICED_MAX}), so ${byFrom.join(' and ')} went by each hotel's from-price a night; the prices shown are for those nights. A city, a group or a filter narrows it.`);
1002
1386
  if (q.sort === 'rating') {
1003
1387
  ignored.sort = true;
1004
1388
  unapplied.push('No ratings are published here, so the list is not in rating order.');
@@ -1048,14 +1432,24 @@ export const createOtalessHotels = (opts) => {
1048
1432
  return [...m.entries()].sort((a, b) => b[1] - a[1]);
1049
1433
  };
1050
1434
  const offset = Math.max(0, Math.floor(q.offset ?? 0));
1051
- const limit = Math.max(1, Math.min(MAX_PAGE, Math.floor(q.limit ?? DEFAULT_PAGE)));
1435
+ // With nights, a page is no longer than what is priced at once (0.76.1).
1436
+ const limit = Math.max(1, Math.min(stay ? LIST_PRICED_MAX : MAX_PAGE, Math.floor(q.limit ?? DEFAULT_PAGE)));
1437
+ let page = passed.slice(offset, offset + limit);
1438
+ if (stay && !priceEvery) {
1439
+ const got = await priceList(page, stay, roomsAsked, who);
1440
+ page = page.map((h) => withStayPrice(h, got.get(h.id)));
1441
+ for (const h of page)
1442
+ pricedNow.set(h.id, h);
1443
+ currencies = [...new Set(placed.map(currencyOf).filter(Boolean))];
1444
+ }
1052
1445
  const codeOf = new Map(pool.map((h) => [h.country ?? '', h.countryCode]));
1053
1446
  return {
1054
- hotels: passed.slice(offset, offset + limit),
1447
+ hotels: page,
1055
1448
  total: passed.length,
1056
1449
  currencies,
1057
1450
  ...(inUsd ? { priceOrderIn: 'USD' } : {}),
1058
1451
  ...(overBudget ? { overBudget } : {}),
1452
+ ...(nearest.length ? { nearest } : {}),
1059
1453
  ...(placed.length !== passed.length ? { beforeFilters: placed.length } : {}),
1060
1454
  ...(q.maxNightly !== undefined && oneCurrency ? { beforeCeiling } : {}),
1061
1455
  ...(extras.length ? { elsewhere: extras.length } : {}),
@@ -1166,7 +1560,7 @@ export const createOtalessHotels = (opts) => {
1166
1560
  const p = partyNeedsOf(stay.guests, largest);
1167
1561
  return withNotes({ hotel, stay, noRooms: p.why, noRoomsCode: p.code, noRoomsArgs: p.args });
1168
1562
  }
1169
- return withNotes({ hotel, stay, rooms: fitting });
1563
+ return withNotes({ hotel, stay, rooms: await withStayQuoted(h, fitting, stay, who) });
1170
1564
  },
1171
1565
  // No rate calendar: the backend has none (§8.2), and one rooms request per
1172
1566
  // date would be seven of them for one hotel opened.
@@ -1239,17 +1633,8 @@ export const createOtalessHotels = (opts) => {
1239
1633
  };
1240
1634
  }
1241
1635
  const q = await quoteWire(h, room.id, line.stay, wanted, who);
1242
- // Its own currency - or, with none, its settlement's (`priceTaken`, questions #45).
1243
- const p = priceTaken(q);
1244
- const currency = text(p.currency)?.toUpperCase();
1245
- const amount = num(p.amount);
1246
- if (p.settled && currency && amount !== undefined && amount > 0)
1247
- pricedInSettlement(h.id);
1248
- // ⚠️ AN ANSWER WITH NO PRICE IS NOT "DID NOT ANSWER": the dev backend
1249
- // quotes every room USD 0 (11-05, questions #46), and asking again
1250
- // gets the same - so it is said as the group's answer, with no "try
1251
- // again", and the room's own nightly rate is never made its total.
1252
- if (!currency || amount === undefined || amount <= 0)
1636
+ const checked = quotedTotal(h, room, line.stay, wanted, q);
1637
+ if (checked.none === 'no-price')
1253
1638
  return {
1254
1639
  dropped: {
1255
1640
  title: h.name,
@@ -1258,43 +1643,8 @@ export const createOtalessHotels = (opts) => {
1258
1643
  line: leftOut(h, line, 'no-price', room.name),
1259
1644
  },
1260
1645
  };
1261
- const total = money(toMinor(amount, currency), currency);
1262
- // ⚠️ A TOTAL THAT DOES NOT COVER THE NIGHTS ASKED IS NOT THE STAY'S (总线程 11-12
1263
- // live test; questions #70): the dev backend priced Atour's Deluxe King CNY 132 for
1264
- // one night and CNY 132 for two - its nightly rate, whatever the nights - and the
1265
- // trip said ¥132 for a stay the room's page put at ¥264. The document's quote is
1266
- // the stay's total (「共2晚总价」); one below the room's own rate for every room-night
1267
- // asked is taken as no total: said as no price, never as the stay's - and never made
1268
- // up from the nightly rate either (#46). ⚠️ EVERY ROOM-NIGHT, NOT ALL BUT ONE (总线程's
1269
- // live test of 0.69.3, HIGH): held only against one room-night fewer, a quote of one
1270
- // night with its taxes in passed - lyf Funan, two nights at S$135.89, put in the trip
1271
- // at S$150.99. A cent a room-night is let go for rounding; nothing more.
1272
- // ⚠️ KNOWN TO HOLD BACK A FAIR STAY TOO (总线程's re-review of 0.69.4, P3): the rate
1273
- // held against every night is /rooms' one rate a night - if that is the first night's
1274
- // or a peak one, a stay whose later nights cost less is left out. None seen yet; what
1275
- // /rooms' rate is, is questions #70's to say (docs/otaless-hotels.md §15.26).
1276
- const units = room.nights * wanted;
1277
- // ⚠️ …AND ONE THAT CANNOT BE HELD AGAINST THE ROOM'S RATE IS NOT TAKEN AS IT EITHER
1278
- // (总线程's re-review of ea5c5547, P3 1): a quote in another currency than the room's
1279
- // rate - the mislabelled currencies of questions #45 / #67 - is just where a one
1280
- // night's price would pass unseen and a stay be booked at it. For more than one
1281
- // room-night it is no total, said so on the log. ⚠️ A "STAY THREE, PAY TWO" OFFER
1282
- // IS HELD BACK TOO: accepted (总线程, the same review).
1283
- const otherCurrency = room.nightly.currency !== currency;
1284
- const short = total.minor + units < room.nightly.minor * units;
1285
- const asked = `quote for ${room.id} at ${h.id}, ${line.stay.checkIn} to ${line.stay.checkOut}, ${wanted} room(s): ${currency} ${amount}`;
1286
- // ⚠️ DEV TESTING ONLY, OFF BEFORE REAL MONEY (`skipPriceChecks`, 0.71.1 - robin
1287
- // 11-13 through 总线程: 「全季先放开能订,价格不管」): the group's quote is the
1288
- // stay's total as it came, said on the log beside the room's own rate. Nothing
1289
- // is added to what the guest sees - the figure is the group's.
1290
- const unchecked = units > 1 && (otherCurrency || short) && skipPrices.has(h.supplier ?? '');
1291
- if (unchecked) {
1292
- log(`[otaless] ${asked} - the room's own rate is ${room.nightly.currency} ${room.nightly.minor / minorFactor(room.nightly.currency)} a night, for ${room.nights} night(s) x ${wanted} room(s) - taken as the stay's total all the same (skipPriceChecks; questions #70${otherCurrency ? ', #45' : ''})`);
1293
- }
1294
- else if (units > 1 && (otherCurrency || short)) {
1295
- log(otherCurrency
1296
- ? `[otaless] ${asked} - in another currency than the room's own rate (${room.nightly.currency}), so whether it covers every night cannot be told - not taken as the stay's total (questions #70, #45)`
1297
- : `[otaless] ${asked} - below ${room.nights} night(s) x ${wanted} room(s) at the room's own ${currency} ${room.nightly.minor / minorFactor(currency)} a night - not taken as the stay's total (questions #70)`);
1646
+ if (checked.none === 'no-total') {
1647
+ const { otherCurrency, currency } = checked;
1298
1648
  // The nights and rooms as they were asked (总线程, the same test: a stay of three
1299
1649
  // was said as "a stay of two").
1300
1650
  const nightsSaid = `${room.nights} ${room.nights === 1 ? 'night' : 'nights'}`;
@@ -1306,7 +1656,7 @@ export const createOtalessHotels = (opts) => {
1306
1656
  // Atour's dev backend quotes a stay of two nights or more at one night's rate -
1307
1657
  // questions #70 - and the model was told only that asking again gives the same). What
1308
1658
  // is said: it cannot be booked here for these nights, and what the guest can do - one
1309
- // room-night always passes this check (`units > 1` above).
1659
+ // room-night always passes this check (`quotedTotal`).
1310
1660
  const fewer = room.nights > 1 && wanted > 1
1311
1661
  ? 'book one room for one night'
1312
1662
  : room.nights > 1
@@ -1339,8 +1689,10 @@ export const createOtalessHotels = (opts) => {
1339
1689
  quantity: wanted,
1340
1690
  // Taken unchecked: a night is the group's total shared out, as the booking
1341
1691
  // will say it (booking.ts `toBooking`) - one currency, one figure throughout.
1342
- unit: unchecked ? money(Math.round(total.minor / units), currency) : room.nightly,
1343
- total,
1692
+ unit: checked.unchecked
1693
+ ? money(Math.round(checked.total.minor / (room.nights * wanted)), checked.total.currency)
1694
+ : room.nightly,
1695
+ total: checked.total,
1344
1696
  terms: room.terms ?? '',
1345
1697
  day: line.stay.checkIn,
1346
1698
  },