BlueGit

timfa questward

Files

questward / server / src / shop / service.js

service.js

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