BlueGit

timfa questward

Files

questward / server / src / shop / service.js

service.js

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