BlueGit

timfa questward

Files

questward / server / src / shop / service.js

service.js

service.js 20.4 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { bagView, findReservedChequeIndex } from "../items/bags.js";
3import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
4import {
5 ItemOriginKind,
6 attachOrigins,
7 mergeOriginLists,
8 normalizeOrigins,
9 splitOrigins
10} from "../../../shared/items/origin.js";
11import {
12 addCoinsToSlots,
13 cloneStack,
14 countCoinsInSlots,
15 insertStack,
16 insertStackGrowable,
17 takeCoinsFromSlots,
18 takeFromSlot
19} from "../../../shared/items/inventory.js";
20import {
21 canSellInNpcShop,
22 canPlayerSellToNpc,
23 resolveShopSellQuote,
24 shopUnitPrice,
25 shopBoughtResalePrice,
26 shopRestockDayKey
27} from "../../../shared/shop/pricing.js";
28import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
29import { chebyshev } from "../combat/service.js";
30import { objectPronoun } from "../../../shared/speech/pronouns.js";
31
32function userError (message)
33{
34 const error = new Error(message);
35 error.userFacing = true;
36 return error;
37}
38
39function npcSex (world, npcHandle)
40{
41 const appearance = world.ecs.get(npcHandle, Component.appearance);
42 return appearance?.sex === "female" ? "female" : "male";
43}
44
45/** Runtime map of characterId → true; plain object so entity transfer can clone it. */
46function ensureBrowsers (shop)
47{
48 if (!shop.browsers || typeof shop.browsers !== "object" || Array.isArray(shop.browsers))
49 { shop.browsers = Object.create(null); }
50 return shop.browsers;
51}
52
53export function shopHasActiveBrowsers (shop)
54{
55 const browsers = shop?.browsers;
56 if (!browsers || typeof browsers !== "object")
57 { return false; }
58 return Object.keys(browsers).length > 0;
59}
60
61function stopNpcMovement (world, npcHandle)
62{
63 const path = world.ecs.get(npcHandle, Component.path);
64 if (path)
65 { path.tiles = []; }
66}
67
68function addShopBrowser (world, shop, npcHandle, characterId)
69{
70 ensureBrowsers(shop)[characterId] = true;
71 stopNpcMovement(world, npcHandle);
72}
73
74function removeShopBrowser (shop, characterId)
75{
76 if (!shop?.browsers)
77 { return; }
78 delete shop.browsers[characterId];
79}
80
81export function releaseShopBrowsersForCharacter (world, characterId)
82{
83 if (characterId == null)
84 { return; }
85 for (const entity of world.ecs.query(Component.shop))
86 { removeShopBrowser(entity.shop, characterId); }
87}
88
89/**
90 * Drop browsers who left / walked away, pin paths while anyone browses,
91 * and emit shop-closed so clients dismiss the UI.
92 */
93export function pruneShopBrowsers (world)
94{
95 const events = [];
96 for (const entity of world.ecs.query(Component.shop, Component.position))
97 {
98 const shop = entity.shop;
99 const browsers = ensureBrowsers(shop);
100 const ids = Object.keys(browsers).map((id) => Number(id));
101 if (!ids.length)
102 { continue; }
103 stopNpcMovement(world, entity.handle);
104 for (const characterId of ids)
105 {
106 const playerEntityId = world.characterEntities.get(characterId);
107 if (playerEntityId == null)
108 {
109 removeShopBrowser(shop, characterId);
110 continue;
111 }
112 const playerHandle = world.ecs.handleOf(playerEntityId);
113 const playerPos = world.ecs.get(playerHandle, Component.position);
114 const stillNear = playerPos
115 && chebyshev(
116 playerPos.tileX,
117 playerPos.tileY,
118 entity.position.tileX,
119 entity.position.tileY
120 ) <= 1;
121 if (stillNear)
122 { continue; }
123 removeShopBrowser(shop, characterId);
124 const identity = world.ecs.get(playerHandle, Component.networkIdentity);
125 if (identity?.sessionId != null)
126 {
127 events.push({
128 type: "shop-closed",
129 sessionId: identity.sessionId,
130 characterId,
131 npcEntityId: entity.entityId
132 });
133 }
134 }
135 }
136 return events;
137}
138
139function lastSaleFor (world, itemId)
140{
141 return world.itemLastSales?.get(itemId) ?? null;
142}
143
144function lerpDuration (world)
145{
146 return world.settings?.shopPriceLerpDurationMs
147 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
148}
149
150function shopDisplayName (shop, npcHandle, world)
151{
152 const appearance = world.ecs.get(npcHandle, Component.appearance);
153 return shop.displayName
154 || [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ")
155 || "Shopkeeper";
156}
157
158function ensureVault (ecs, handle)
159{
160 let vault = ecs.get(handle, Component.vault);
161 if (!vault)
162 { vault = ecs.add(handle, Component.vault, { slots: [], reserved: [] }); }
163 if (!Array.isArray(vault.slots))
164 { vault.slots = []; }
165 if (!Array.isArray(vault.reserved))
166 { vault.reserved = []; }
167 return vault;
168}
169
170/** Refresh catalog remaining and clear bought-from-players stock at local midnight. */
171export function ensureShopRestocked (shop, now = Date.now())
172{
173 if (!shop)
174 { return; }
175 if (!Array.isArray(shop.catalog))
176 { shop.catalog = []; }
177 if (Array.isArray(shop.stock) && !shop.catalog.length)
178 {
179 shop.catalog = shop.stock
180 .map((id) => ({ itemId: id | 0, quantity: 0 }))
181 .filter((line) => line.itemId > 0);
182 }
183 if (!shop.remaining || typeof shop.remaining !== "object")
184 { shop.remaining = Object.create(null); }
185 if (!shop.boughtStock || typeof shop.boughtStock !== "object")
186 { shop.boughtStock = Object.create(null); }
187 const day = shopRestockDayKey(now);
188 if (shop.restockDay === day)
189 { return; }
190 shop.restockDay = day;
191 shop.boughtStock = Object.create(null);
192 shop.remaining = Object.create(null);
193 for (const line of shop.catalog)
194 {
195 const itemId = line.itemId | 0;
196 const quantity = Math.max(0, line.quantity | 0 || 0);
197 if (itemId > 0 && quantity > 0)
198 { shop.remaining[itemId] = quantity; }
199 }
200}
201
202function catalogLine (shop, itemId)
203{
204 return (shop.catalog ?? []).find((line) => (line.itemId | 0) === (itemId | 0)) ?? null;
205}
206
207function catalogAvailable (shop, itemId)
208{
209 const line = catalogLine(shop, itemId);
210 if (!line)
211 { return 0; }
212 if ((line.quantity | 0) <= 0)
213 { return Number.POSITIVE_INFINITY; }
214 return Math.max(0, shop.remaining?.[itemId] | 0 || 0);
215}
216
217/** Normalize legacy qty-only boughtStock entries into `{ quantity, origins }`. */
218function boughtLot (shop, itemId)
219{
220 const raw = shop.boughtStock?.[itemId];
221 if (raw == null)
222 { return null; }
223 if (typeof raw === "number")
224 {
225 const quantity = Math.max(0, raw | 0);
226 if (quantity <= 0)
227 { return null; }
228 return {
229 quantity,
230 origins: [{ origin: null, quantity }]
231 };
232 }
233 const quantity = Math.max(0, raw.quantity | 0 || 0);
234 if (quantity <= 0)
235 { return null; }
236 const origins = normalizeOrigins({ quantity, origins: raw.origins });
237 const originQty = origins.reduce((sum, entry) => sum + entry.quantity, 0);
238 if (originQty < quantity)
239 {
240 origins.push({ origin: null, quantity: quantity - originQty });
241 }
242 return { quantity, origins };
243}
244
245function boughtAvailable (shop, itemId)
246{
247 return boughtLot(shop, itemId)?.quantity ?? 0;
248}
249
250function addBoughtLot (shop, itemId, quantity, origins)
251{
252 const qty = Math.max(0, quantity | 0 || 0);
253 if (qty <= 0)
254 { return; }
255 const existing = boughtLot(shop, itemId);
256 const nextOrigins = mergeOriginLists(
257 existing?.origins ?? [],
258 normalizeOrigins({ quantity: qty, origins })
259 );
260 shop.boughtStock[itemId] = {
261 quantity: (existing?.quantity ?? 0) + qty,
262 origins: nextOrigins
263 };
264}
265
266/** Pull FIFO origins from bought stock; returns null if insufficient. */
267function takeBoughtLot (shop, itemId, quantity)
268{
269 const qty = Math.max(0, quantity | 0 || 0);
270 const lot = boughtLot(shop, itemId);
271 if (!lot || lot.quantity < qty)
272 { return null; }
273 const split = splitOrigins(lot.origins, qty);
274 const remainQty = lot.quantity - qty;
275 if (remainQty <= 0)
276 { delete shop.boughtStock[itemId]; }
277 else
278 {
279 shop.boughtStock[itemId] = {
280 quantity: remainQty,
281 origins: split.remain
282 };
283 }
284 return { quantity: qty, origins: split.taken };
285}
286
287function shopStockView (world, shop, now)
288{
289 ensureShopRestocked(shop, now);
290 const lastSaleOpts = (itemId) => ({
291 lastSale: lastSaleFor(world, itemId),
292 now,
293 lerpDurationMs: lerpDuration(world),
294 settings: world.settings ?? null
295 });
296 const stock = [];
297 for (const line of shop.catalog ?? [])
298 {
299 const itemId = line.itemId | 0;
300 if (!canSellInNpcShop(itemId))
301 { continue; }
302 const def = itemDefinition(itemId);
303 if (!def)
304 { continue; }
305 const available = catalogAvailable(shop, itemId);
306 if (available === 0)
307 { continue; }
308 stock.push({
309 listingId: `stock:${itemId}`,
310 itemId,
311 displayName: def.displayName,
312 unitPrice: shopUnitPrice(itemId, {
313 ...lastSaleOpts(itemId),
314 hiddenDiscount: shop.hiddenDiscount ?? 1
315 }),
316 available: Number.isFinite(available) ? available : null,
317 source: "stock"
318 });
319 }
320 for (const key of Object.keys(shop.boughtStock ?? {}))
321 {
322 const itemId = key | 0;
323 const available = boughtAvailable(shop, itemId);
324 if (available <= 0 || !canSellInNpcShop(itemId))
325 { continue; }
326 const def = itemDefinition(itemId);
327 if (!def)
328 { continue; }
329 stock.push({
330 listingId: `bought:${itemId}`,
331 itemId,
332 displayName: def.displayName,
333 unitPrice: shopBoughtResalePrice(itemId, lastSaleOpts(itemId)),
334 available,
335 source: "bought"
336 });
337 }
338 return stock;
339}
340
341function shopOpenEvent (world, sessionId, characterId, npcEntityId, shop, displayName, now)
342{
343 const npcHandle = world.ecs.handleOf(npcEntityId);
344 return {
345 type: "shop-open",
346 sessionId,
347 characterId,
348 npcEntityId,
349 displayName,
350 sex: npcHandle != null ? npcSex(world, npcHandle) : "male",
351 buysItems: !!shop.buysItems,
352 stock: shopStockView(world, shop, now)
353 };
354}
355
356function requireShopAccess (world, sessionId, characterId, npcEntityId)
357{
358 const entityId = world.characterEntities.get(characterId);
359 if (entityId == null)
360 { throw userError("Character is not in the world."); }
361 const handle = world.ecs.handleOf(entityId);
362 const identity = world.ecs.get(handle, Component.networkIdentity);
363 if (!identity || identity.sessionId !== sessionId)
364 { throw userError("Character is not in the world."); }
365 if (world.ecs.has(handle, Component.dead))
366 { throw userError("You are dead."); }
367
368 const npcHandle = world.ecs.handleOf(npcEntityId);
369 if (npcHandle == null)
370 { throw userError("Target is not here."); }
371 const shop = world.ecs.get(npcHandle, Component.shop);
372 const sex = npcSex(world, npcHandle);
373 if (!shop || (!(shop.catalog?.length) && !shop.buysItems))
374 {
375 const who = sex === "female" ? "She" : "He";
376 throw userError(`${who} is not selling anything.`);
377 }
378
379 const playerPos = world.ecs.get(handle, Component.position);
380 const npcPos = world.ecs.get(npcHandle, Component.position);
381 if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1)
382 { throw userError(`You need to stand next to ${objectPronoun(sex)}.`); }
383
384 return { handle, npcHandle, shop, entityId };
385}
386
387export function openShop (world, sessionId, characterId, npcEntityId, now = Date.now())
388{
389 const { shop, npcHandle } = requireShopAccess(world, sessionId, characterId, npcEntityId);
390 ensureShopRestocked(shop, now);
391 addShopBrowser(world, shop, npcHandle, characterId);
392 const displayName = shopDisplayName(shop, npcHandle, world);
393 return {
394 events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)]
395 };
396}
397
398export function closeShop (world, sessionId, characterId, npcEntityId)
399{
400 const entityId = world.characterEntities.get(characterId);
401 if (entityId == null)
402 { return { events: [] }; }
403 const handle = world.ecs.handleOf(entityId);
404 const identity = world.ecs.get(handle, Component.networkIdentity);
405 if (!identity || identity.sessionId !== sessionId)
406 { return { events: [] }; }
407 const npcHandle = world.ecs.handleOf(npcEntityId | 0);
408 if (npcHandle == null)
409 { return { events: [] }; }
410 const shop = world.ecs.get(npcHandle, Component.shop);
411 removeShopBrowser(shop, characterId);
412 return { events: [] };
413}
414
415function parseListing (listingId, itemId, source)
416{
417 if (typeof listingId === "string" && listingId.includes(":"))
418 {
419 const [kind, id] = listingId.split(":");
420 return { source: kind === "bought" ? "bought" : "stock", itemId: id | 0 };
421 }
422 if (source === "bought")
423 { return { source: "bought", itemId: itemId | 0 }; }
424 return { source: "stock", itemId: itemId | 0 };
425}
426
427export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now(), listingId = null, source = null)
428{
429 const { handle, npcHandle, shop } = requireShopAccess(world, sessionId, characterId, npcEntityId);
430 ensureShopRestocked(shop, now);
431 const listing = parseListing(listingId, itemId, source);
432 const buyItemId = listing.itemId;
433 if (!canSellInNpcShop(buyItemId))
434 { throw userError("That item cannot be sold here."); }
435
436 const qty = Math.max(1, quantity | 0 || 1);
437 const def = itemDefinition(buyItemId);
438 if (!def)
439 { throw userError("Unknown item."); }
440
441 const available = listing.source === "bought"
442 ? boughtAvailable(shop, buyItemId)
443 : catalogAvailable(shop, buyItemId);
444 if (available < qty)
445 { throw userError("Not enough stock."); }
446
447 const unitPrice = listing.source === "bought"
448 ? shopBoughtResalePrice(buyItemId, {
449 lastSale: lastSaleFor(world, buyItemId),
450 now,
451 lerpDurationMs: lerpDuration(world),
452 settings: world.settings ?? null
453 })
454 : shopUnitPrice(buyItemId, {
455 lastSale: lastSaleFor(world, buyItemId),
456 now,
457 lerpDurationMs: lerpDuration(world),
458 hiddenDiscount: shop.hiddenDiscount ?? 1,
459 settings: world.settings ?? null
460 });
461 const total = unitPrice * qty;
462 const inventory = world.ecs.get(handle, Component.inventory);
463 if (!inventory)
464 { throw userError("No inventory."); }
465 if (countCoinsInSlots(inventory.slots) < total)
466 { throw userError("You cannot afford that."); }
467
468 const paid = takeCoinsFromSlots(inventory.slots, total);
469 if (!paid.ok)
470 { throw userError("You cannot afford that."); }
471
472 const displayName = shopDisplayName(shop, npcHandle, world);
473 let stack;
474 if (listing.source === "bought")
475 {
476 const lot = boughtLot(shop, buyItemId);
477 if (!lot || lot.quantity < qty)
478 { throw userError("Not enough stock."); }
479 const split = splitOrigins(lot.origins, qty);
480 stack = attachOrigins({
481 itemId: buyItemId,
482 quantity: qty,
483 origins: split.taken
484 });
485 }
486 else
487 {
488 const shopOrigin = { kind: ItemOriginKind.shop, displayName };
489 stack = attachOrigins({
490 itemId: buyItemId,
491 quantity: qty,
492 origins: [{ origin: shopOrigin, quantity: qty }]
493 });
494 }
495 const added = insertStack(paid.slots, stack, def);
496 inventory.slots = added.slots;
497 if (added.remainder > 0)
498 {
499 const overflowOrigins = splitOrigins(normalizeOrigins(stack), qty - added.remainder).remain;
500 const overflow = attachOrigins({
501 itemId: buyItemId,
502 quantity: added.remainder,
503 origins: overflowOrigins
504 });
505 const vault = ensureVault(world.ecs, handle);
506 const vaulted = insertStackGrowable(vault.slots, overflow, def);
507 if (!vaulted.ok || vaulted.remainder > 0)
508 { throw userError("Your bank cannot hold that purchase."); }
509 vault.slots = vaulted.slots;
510 }
511
512 if (listing.source === "bought")
513 {
514 if (!takeBoughtLot(shop, buyItemId, qty))
515 { throw userError("Not enough stock."); }
516 }
517 else
518 {
519 const line = catalogLine(shop, buyItemId);
520 if (line && (line.quantity | 0) > 0)
521 { shop.remaining[buyItemId] = catalogAvailable(shop, buyItemId) - qty; }
522 }
523
524 return {
525 events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)],
526 private: bagView(world.ecs, handle)
527 };
528}
529
530/**
531 * Player sells to NPC (requires buysItems).
532 * Buys any transferable bag goods except blank cheques.
533 * Filled cheques sell as their reserved goods with a 5% admin fee.
534 * Limited catalog lines refill first; remainder goes into boughtStock
535 * (cleared at midnight). Infinite catalog lines absorb goods without resale stock.
536 */
537export function sellToShop (world, sessionId, characterId, npcEntityId, slotIndex, quantity = 1, now = Date.now())
538{
539 const { handle, npcHandle, shop } = requireShopAccess(world, sessionId, characterId, npcEntityId);
540 ensureShopRestocked(shop, now);
541 if (!shop.buysItems)
542 { throw userError("They are not buying anything."); }
543
544 const inventory = world.ecs.get(handle, Component.inventory);
545 if (!inventory)
546 { throw userError("No inventory."); }
547 const slot = inventory.slots[slotIndex | 0];
548 if (!slot)
549 { throw userError("That slot is empty."); }
550 if (!canPlayerSellToNpc(slot))
551 { throw userError("They will not buy that."); }
552
553 const isCheque = (slot.itemId | 0) === ItemId.filledCheque;
554 const quote = resolveShopSellQuote(slot, {
555 lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)),
556 now,
557 lerpDurationMs: lerpDuration(world),
558 settings: world.settings ?? null,
559 quantity: isCheque ? 1 : (quantity | 0 || 1)
560 });
561 if (!quote)
562 { throw userError("They will not buy that."); }
563
564 const goodsItemId = quote.goodsItemId;
565 const qty = quote.goodsQuantity;
566 const line = catalogLine(shop, goodsItemId);
567 let refill = 0;
568 let leftover = qty;
569 if (line)
570 {
571 if ((line.quantity | 0) <= 0)
572 {
573 refill = qty;
574 leftover = 0;
575 }
576 else
577 {
578 const space = Math.max(0, (line.quantity | 0) - catalogAvailable(shop, goodsItemId));
579 refill = Math.min(qty, space);
580 leftover = qty - refill;
581 }
582 }
583
584 const total = quote.payout;
585 let reservedStack = null;
586 let chequeTaken = null;
587 let taken = null;
588
589 if (isCheque)
590 {
591 const instance = slot.instance;
592 const issuerId = instance.issuerCharacterId;
593 chequeTaken = takeFromSlot(inventory.slots, slotIndex | 0, 1);
594 if (!chequeTaken.ok)
595 { throw userError("Could not take that item."); }
596 inventory.slots = chequeTaken.slots;
597
598 if (Number(issuerId) === Number(characterId))
599 {
600 const vault = world.ecs.get(handle, Component.vault);
601 if (!vault)
602 {
603 inventory.slots[slotIndex | 0] = chequeTaken.taken;
604 throw userError("That cheque cannot be sold.");
605 }
606 if (!Array.isArray(vault.reserved))
607 { vault.reserved = []; }
608 const index = findReservedChequeIndex(vault.reserved, instance);
609 if (index < 0)
610 {
611 inventory.slots[slotIndex | 0] = chequeTaken.taken;
612 throw userError("That cheque cannot be sold.");
613 }
614 reservedStack = cloneStack(vault.reserved[index]);
615 vault.reserved = vault.reserved.filter((_, i) => i !== index);
616 }
617 else
618 {
619 const release = world.releaseChequeReservation?.(issuerId, instance.chequeId, instance);
620 if (!release?.ok)
621 {
622 inventory.slots[slotIndex | 0] = chequeTaken.taken;
623 throw userError(release?.error ?? "That cheque cannot be sold.");
624 }
625 reservedStack = release.stack;
626 }
627 }
628 else
629 {
630 taken = takeFromSlot(inventory.slots, slotIndex | 0, qty);
631 if (!taken.ok)
632 { throw userError("Could not take that item."); }
633 }
634
635 const slotsAfterTake = isCheque ? inventory.slots : taken.slots;
636 const paid = addCoinsToSlots(slotsAfterTake, total);
637 if (!paid.ok)
638 {
639 if (isCheque)
640 {
641 inventory.slots[slotIndex | 0] = chequeTaken.taken;
642 if (Number(slot.instance.issuerCharacterId) === Number(characterId))
643 {
644 const vault = world.ecs.get(handle, Component.vault);
645 if (vault && reservedStack)
646 { vault.reserved = [...(vault.reserved ?? []), reservedStack]; }
647 }
648 else if (reservedStack)
649 { world.restoreChequeReservation?.(slot.instance.issuerCharacterId, reservedStack); }
650 }
651 else
652 {
653 const def = itemDefinition(goodsItemId);
654 inventory.slots = insertStack(taken.slots, taken.taken, def).slots;
655 }
656 throw userError("Not enough bag space for coins.");
657 }
658 inventory.slots = paid.slots;
659
660 if (line && (line.quantity | 0) > 0 && refill > 0)
661 { shop.remaining[goodsItemId] = catalogAvailable(shop, goodsItemId) + refill; }
662 if (leftover > 0)
663 {
664 const soldStack = isCheque ? reservedStack : taken.taken;
665 const soldOrigins = normalizeOrigins(soldStack);
666 // Catalog refill absorbs first; leftover keeps remaining origins for resale.
667 const { remain: resaleOrigins } = splitOrigins(soldOrigins, refill);
668 addBoughtLot(shop, goodsItemId, leftover, resaleOrigins);
669 }
670
671 const displayName = shopDisplayName(shop, npcHandle, world);
672 return {
673 events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)],
674 private: bagView(world.ecs, handle)
675 };
676}
677
678export function handleShopCommand (world, sessionId, command, now)
679{
680 switch (command.type)
681 {
682 case "buy-from-shop":
683 return buyFromShop(
684 world,
685 sessionId,
686 command.characterId,
687 command.npcEntityId | 0,
688 command.itemId | 0,
689 command.quantity | 0 || 1,
690 now,
691 command.listingId ?? null,
692 command.source ?? null
693 );
694 case "sell-to-shop":
695 return sellToShop(
696 world,
697 sessionId,
698 command.characterId,
699 command.npcEntityId | 0,
700 command.slotIndex | 0,
701 command.quantity | 0 || 1,
702 now
703 );
704 case "close-shop":
705 return closeShop(world, sessionId, command.characterId, command.npcEntityId | 0);
706 default:
707 return null;
708 }
709}
710
711export function shopHasInterface (shop)
712{
713 if (!shop)
714 { return false; }
715 if (shop.buysItems)
716 { return true; }
717 if ((shop.catalog?.length ?? 0) > 0)
718 { return true; }
719 if (Object.keys(shop.boughtStock ?? {}).length > 0)
720 { return true; }
721 // Legacy shops spawned before catalog migration.
722 if ((shop.stock?.length ?? 0) > 0)
723 { return true; }
724 return false;
725}