BlueGit

timfa questward

Files

questward / server / src / shop / service.js

service.js

service.js 23.3 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 { chebyshev } from "../combat/service.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 && chebyshev(
119 playerPos.tileX,
120 playerPos.tileY,
121 entity.position.tileX,
122 entity.position.tileY
123 ) <= 1;
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, lastSaleOpts(itemId)),
399 available: lot.quantity,
400 source: "bought",
401 instance: lot.instance ? structuredClone(lot.instance) : null
402 });
403 }
404 return stock;
405}
406
407function shopOpenEvent (world, sessionId, characterId, npcEntityId, shop, displayName, now)
408{
409 const npcHandle = world.ecs.handleOf(npcEntityId);
410 return {
411 type: "shop-open",
412 sessionId,
413 characterId,
414 npcEntityId,
415 displayName,
416 sex: npcHandle != null ? npcSex(world, npcHandle) : "male",
417 buysItems: !!shop.buysItems,
418 stock: shopStockView(world, shop, now)
419 };
420}
421
422function requireShopAccess (world, sessionId, characterId, npcEntityId)
423{
424 const entityId = world.characterEntities.get(characterId);
425 if (entityId == null)
426 { throw userError("Character is not in the world."); }
427 const handle = world.ecs.handleOf(entityId);
428 const identity = world.ecs.get(handle, Component.networkIdentity);
429 if (!identity || identity.sessionId !== sessionId)
430 { throw userError("Character is not in the world."); }
431 if (world.ecs.has(handle, Component.dead))
432 { throw userError("You are dead."); }
433
434 const npcHandle = world.ecs.handleOf(npcEntityId);
435 if (npcHandle == null)
436 { throw userError("Target is not here."); }
437 const shop = world.ecs.get(npcHandle, Component.shop);
438 const sex = npcSex(world, npcHandle);
439 if (!shop || (!(shop.catalog?.length) && !shop.buysItems))
440 {
441 const who = sex === "female" ? "She" : "He";
442 throw userError(`${who} is not selling anything.`);
443 }
444
445 const playerPos = world.ecs.get(handle, Component.position);
446 const npcPos = world.ecs.get(npcHandle, Component.position);
447 if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1)
448 { throw userError(`You need to stand next to ${objectPronoun(sex)}.`); }
449
450 return { handle, npcHandle, shop, entityId };
451}
452
453export function openShop (world, sessionId, characterId, npcEntityId, now = Date.now())
454{
455 const { shop, npcHandle } = requireShopAccess(world, sessionId, characterId, npcEntityId);
456 ensureShopRestocked(shop, now);
457 addShopBrowser(world, shop, npcHandle, characterId);
458 const displayName = shopDisplayName(shop, npcHandle, world);
459 return {
460 events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)]
461 };
462}
463
464export function closeShop (world, sessionId, characterId, npcEntityId)
465{
466 const entityId = world.characterEntities.get(characterId);
467 if (entityId == null)
468 { return { events: [] }; }
469 const handle = world.ecs.handleOf(entityId);
470 const identity = world.ecs.get(handle, Component.networkIdentity);
471 if (!identity || identity.sessionId !== sessionId)
472 { return { events: [] }; }
473 const npcHandle = world.ecs.handleOf(npcEntityId | 0);
474 if (npcHandle == null)
475 { return { events: [] }; }
476 const shop = world.ecs.get(npcHandle, Component.shop);
477 removeShopBrowser(shop, characterId);
478 return { events: [] };
479}
480
481function parseListing (listingId, itemId, source)
482{
483 if (typeof listingId === "string")
484 {
485 if (listingId.startsWith("bought:"))
486 {
487 const stockKey = listingId.slice("bought:".length);
488 return {
489 source: "bought",
490 itemId: itemIdFromStockKey(stockKey),
491 stockKey
492 };
493 }
494 if (listingId.startsWith("stock:"))
495 {
496 return {
497 source: "stock",
498 itemId: listingId.slice("stock:".length) | 0,
499 stockKey: null
500 };
501 }
502 }
503 if (source === "bought")
504 {
505 const id = itemId | 0;
506 return { source: "bought", itemId: id, stockKey: String(id) };
507 }
508 return { source: "stock", itemId: itemId | 0, stockKey: null };
509}
510
511export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now(), listingId = null, source = null)
512{
513 const { handle, npcHandle, shop } = requireShopAccess(world, sessionId, characterId, npcEntityId);
514 ensureShopRestocked(shop, now);
515 const listing = parseListing(listingId, itemId, source);
516 const buyItemId = listing.itemId;
517 if (listing.source === "stock")
518 {
519 if (!catalogLine(shop, buyItemId))
520 { throw userError("That item cannot be sold here."); }
521 }
522 else if (boughtAvailable(shop, listing.stockKey) <= 0)
523 { throw userError("Not enough stock."); }
524
525 const qty = Math.max(1, quantity | 0 || 1);
526 const def = itemDefinition(buyItemId);
527 if (!def)
528 { throw userError("Unknown item."); }
529
530 const available = listing.source === "bought"
531 ? boughtAvailable(shop, listing.stockKey)
532 : catalogAvailable(shop, buyItemId);
533 if (available < qty)
534 { throw userError("Not enough stock."); }
535
536 const unitPrice = listing.source === "bought"
537 ? shopBoughtResalePrice(buyItemId, {
538 lastSale: lastSaleFor(world, buyItemId),
539 now,
540 lerpDurationMs: lerpDuration(world),
541 settings: world.settings ?? null
542 })
543 : shopUnitPrice(buyItemId, {
544 lastSale: lastSaleFor(world, buyItemId),
545 now,
546 lerpDurationMs: lerpDuration(world),
547 hiddenDiscount: shop.hiddenDiscount ?? 1,
548 settings: world.settings ?? null
549 });
550 const total = unitPrice * qty;
551 const inventory = world.ecs.get(handle, Component.inventory);
552 if (!inventory)
553 { throw userError("No inventory."); }
554 if (countCoinsInSlots(inventory.slots) < total)
555 { throw userError("You cannot afford that."); }
556
557 const paid = takeCoinsFromSlots(inventory.slots, total);
558 if (!paid.ok)
559 { throw userError("You cannot afford that."); }
560
561 const displayName = shopDisplayName(shop, npcHandle, world);
562 let stack;
563 if (listing.source === "bought")
564 {
565 const lot = boughtLot(shop, listing.stockKey);
566 if (!lot || lot.quantity < qty)
567 { throw userError("Not enough stock."); }
568 const split = splitOrigins(lot.origins, qty);
569 stack = attachOrigins({
570 itemId: buyItemId,
571 quantity: qty,
572 instance: lot.instance ? structuredClone(lot.instance) : null,
573 origins: split.taken
574 });
575 }
576 else
577 {
578 const shopOriginEntry = { kind: ItemOriginKind.shop, displayName };
579 const defaultInstance = def?.defaultInstance
580 ? structuredClone(def.defaultInstance)
581 : null;
582 stack = attachOrigins({
583 itemId: buyItemId,
584 quantity: qty,
585 instance: defaultInstance,
586 origins: [{ origin: shopOriginEntry, quantity: qty }]
587 });
588 }
589 const added = insertStack(paid.slots, stack, def);
590 inventory.slots = added.slots;
591 if (added.remainder > 0)
592 {
593 const overflowOrigins = splitOrigins(normalizeOrigins(stack), qty - added.remainder).remain;
594 const overflow = attachOrigins({
595 itemId: buyItemId,
596 quantity: added.remainder,
597 instance: stack.instance ? structuredClone(stack.instance) : null,
598 origins: overflowOrigins
599 });
600 const vault = ensureVault(world.ecs, handle);
601 const vaulted = insertStackGrowable(vault.slots, overflow, def);
602 if (!vaulted.ok || vaulted.remainder > 0)
603 { throw userError("Your bank cannot hold that purchase."); }
604 vault.slots = vaulted.slots;
605 }
606
607 if (listing.source === "bought")
608 {
609 if (!takeBoughtLot(shop, listing.stockKey, qty))
610 { throw userError("Not enough stock."); }
611 }
612 else
613 {
614 const line = catalogLine(shop, buyItemId);
615 if (line && (line.quantity | 0) > 0)
616 { shop.remaining[buyItemId] = catalogAvailable(shop, buyItemId) - qty; }
617 }
618
619 return {
620 events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)],
621 private: bagView(world.ecs, handle)
622 };
623}
624
625/**
626 * Player sells to NPC (requires buysItems).
627 * Buys any transferable bag goods except blank cheques.
628 * Filled cheques sell as their reserved goods with a 5% admin fee.
629 * Limited catalog lines refill first; remainder goes into boughtStock
630 * (cleared at midnight). Infinite catalog lines absorb goods without resale stock.
631 * Letters pay out but are destroyed — never restocked or put in boughtStock.
632 */
633export function sellToShop (world, sessionId, characterId, npcEntityId, slotIndex, quantity = 1, now = Date.now())
634{
635 const { handle, npcHandle, shop } = requireShopAccess(world, sessionId, characterId, npcEntityId);
636 ensureShopRestocked(shop, now);
637 if (!shop.buysItems)
638 { throw userError("They are not buying anything."); }
639
640 const inventory = world.ecs.get(handle, Component.inventory);
641 if (!inventory)
642 { throw userError("No inventory."); }
643 const slot = inventory.slots[slotIndex | 0];
644 if (!slot)
645 { throw userError("That slot is empty."); }
646 if (!canPlayerSellToNpc(slot))
647 { throw userError("They will not buy that."); }
648
649 const isCheque = (slot.itemId | 0) === ItemId.filledCheque;
650 const isLetter = isLetterStack(slot);
651 const quote = resolveShopSellQuote(slot, {
652 lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)),
653 now,
654 lerpDurationMs: lerpDuration(world),
655 settings: world.settings ?? null,
656 quantity: isCheque ? 1 : (quantity | 0 || 1)
657 });
658 if (!quote)
659 { throw userError("They will not buy that."); }
660
661 const goodsItemId = quote.goodsItemId;
662 const qty = quote.goodsQuantity;
663 const line = catalogLine(shop, goodsItemId);
664 let refill = 0;
665 let leftover = qty;
666 if (isLetter)
667 {
668 // Destroyed on sale — never enter shop stock.
669 refill = 0;
670 leftover = 0;
671 }
672 else if (line)
673 {
674 if ((line.quantity | 0) <= 0)
675 {
676 refill = qty;
677 leftover = 0;
678 }
679 else
680 {
681 const space = Math.max(0, (line.quantity | 0) - catalogAvailable(shop, goodsItemId));
682 refill = Math.min(qty, space);
683 leftover = qty - refill;
684 }
685 }
686
687 const total = quote.payout;
688 let reservedStack = null;
689 let chequeTaken = null;
690 let taken = null;
691
692 if (isCheque)
693 {
694 const instance = slot.instance;
695 const issuerId = instance.issuerCharacterId;
696 chequeTaken = takeFromSlot(inventory.slots, slotIndex | 0, 1);
697 if (!chequeTaken.ok)
698 { throw userError("Could not take that item."); }
699 inventory.slots = chequeTaken.slots;
700
701 if (Number(issuerId) === Number(characterId))
702 {
703 const vault = world.ecs.get(handle, Component.vault);
704 if (!vault)
705 {
706 inventory.slots[slotIndex | 0] = chequeTaken.taken;
707 throw userError("That cheque cannot be sold.");
708 }
709 if (!Array.isArray(vault.reserved))
710 { vault.reserved = []; }
711 const index = findReservedChequeIndex(vault.reserved, instance);
712 if (index < 0)
713 {
714 inventory.slots[slotIndex | 0] = chequeTaken.taken;
715 throw userError("That cheque cannot be sold.");
716 }
717 reservedStack = cloneStack(vault.reserved[index]);
718 vault.reserved = vault.reserved.filter((_, i) => i !== index);
719 }
720 else
721 {
722 const release = world.releaseChequeReservation?.(issuerId, instance.chequeId, instance);
723 if (!release?.ok)
724 {
725 inventory.slots[slotIndex | 0] = chequeTaken.taken;
726 throw userError(release?.error ?? "That cheque cannot be sold.");
727 }
728 reservedStack = release.stack;
729 }
730 }
731 else
732 {
733 taken = takeFromSlot(inventory.slots, slotIndex | 0, qty);
734 if (!taken.ok)
735 { throw userError("Could not take that item."); }
736 }
737
738 const slotsAfterTake = isCheque ? inventory.slots : taken.slots;
739 const paid = addCoinsToSlots(slotsAfterTake, total);
740 if (!paid.ok)
741 {
742 if (isCheque)
743 {
744 inventory.slots[slotIndex | 0] = chequeTaken.taken;
745 if (Number(slot.instance.issuerCharacterId) === Number(characterId))
746 {
747 const vault = world.ecs.get(handle, Component.vault);
748 if (vault && reservedStack)
749 { vault.reserved = [...(vault.reserved ?? []), reservedStack]; }
750 }
751 else if (reservedStack)
752 { world.restoreChequeReservation?.(slot.instance.issuerCharacterId, reservedStack); }
753 }
754 else
755 {
756 const def = itemDefinition(goodsItemId);
757 inventory.slots = insertStack(taken.slots, taken.taken, def).slots;
758 }
759 throw userError("Not enough bag space for coins.");
760 }
761 inventory.slots = paid.slots;
762
763 if (line && (line.quantity | 0) > 0 && refill > 0)
764 { shop.remaining[goodsItemId] = catalogAvailable(shop, goodsItemId) + refill; }
765 if (leftover > 0)
766 {
767 const soldStack = isCheque ? reservedStack : taken.taken;
768 const soldOrigins = normalizeOrigins(soldStack);
769 // Catalog refill absorbs first; leftover keeps remaining origins for resale.
770 const { remain: resaleOrigins } = splitOrigins(soldOrigins, refill);
771 addBoughtLot(
772 shop,
773 goodsItemId,
774 leftover,
775 resaleOrigins,
776 soldStack?.instance ?? null
777 );
778 }
779
780 const displayName = shopDisplayName(shop, npcHandle, world);
781 return {
782 events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)],
783 private: bagView(world.ecs, handle)
784 };
785}
786
787export function handleShopCommand (world, sessionId, command, now)
788{
789 switch (command.type)
790 {
791 case "buy-from-shop":
792 return buyFromShop(
793 world,
794 sessionId,
795 command.characterId,
796 command.npcEntityId | 0,
797 command.itemId | 0,
798 command.quantity | 0 || 1,
799 now,
800 command.listingId ?? null,
801 command.source ?? null
802 );
803 case "sell-to-shop":
804 return sellToShop(
805 world,
806 sessionId,
807 command.characterId,
808 command.npcEntityId | 0,
809 command.slotIndex | 0,
810 command.quantity | 0 || 1,
811 now
812 );
813 case "close-shop":
814 return closeShop(world, sessionId, command.characterId, command.npcEntityId | 0);
815 default:
816 return null;
817 }
818}
819
820export function shopHasInterface (shop)
821{
822 if (!shop)
823 { return false; }
824 if (shop.buysItems)
825 { return true; }
826 if ((shop.catalog?.length ?? 0) > 0)
827 { return true; }
828 if (Object.keys(shop.boughtStock ?? {}).length > 0)
829 { return true; }
830 // Legacy shops spawned before catalog migration.
831 if ((shop.stock?.length ?? 0) > 0)
832 { return true; }
833 return false;
834}