import { Component } from "../ecs/components.js"; import { bagView, findReservedChequeIndex } from "../items/bags.js"; import { ItemId, itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js"; import { ItemOriginKind, attachOrigins, mergeOriginLists, normalizeOrigins, splitOrigins, shopOrigin } from "../../../shared/items/origin.js"; import { isLetterStack } from "../../../shared/items/letters.js"; import { addCoinsToSlots, cloneStack, countCoinsInSlots, dyeStackIdentity, insertStack, insertStackGrowable, potionStackIdentity, takeCoinsFromSlots, takeFromSlot } from "../../../shared/items/inventory.js"; import { canPlayerSellToNpc, resolveShopSellQuote, shopUnitPrice, shopBoughtResalePrice, shopRestockDayKey } from "../../../shared/shop/pricing.js"; import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js"; import { chebyshev } from "../combat/service.js"; import { objectPronoun } from "../../../shared/speech/pronouns.js"; function userError (message) { const error = new Error(message); error.userFacing = true; return error; } function npcSex (world, npcHandle) { const appearance = world.ecs.get(npcHandle, Component.appearance); return appearance?.sex === "female" ? "female" : "male"; } /** Runtime map of characterId → true; plain object so entity transfer can clone it. */ function ensureBrowsers (shop) { if (!shop.browsers || typeof shop.browsers !== "object" || Array.isArray(shop.browsers)) { shop.browsers = Object.create(null); } return shop.browsers; } export function shopHasActiveBrowsers (shop) { const browsers = shop?.browsers; if (!browsers || typeof browsers !== "object") { return false; } return Object.keys(browsers).length > 0; } function stopNpcMovement (world, npcHandle) { const path = world.ecs.get(npcHandle, Component.path); if (path) { path.tiles = []; } } function addShopBrowser (world, shop, npcHandle, characterId) { ensureBrowsers(shop)[characterId] = true; stopNpcMovement(world, npcHandle); } function removeShopBrowser (shop, characterId) { if (!shop?.browsers) { return; } delete shop.browsers[characterId]; } export function releaseShopBrowsersForCharacter (world, characterId) { if (characterId == null) { return; } for (const entity of world.ecs.query(Component.shop)) { removeShopBrowser(entity.shop, characterId); } } /** * Drop browsers who left / walked away, pin paths while anyone browses, * and emit shop-closed so clients dismiss the UI. */ export function pruneShopBrowsers (world) { const events = []; for (const entity of world.ecs.query(Component.shop, Component.position)) { const shop = entity.shop; const browsers = ensureBrowsers(shop); const ids = Object.keys(browsers).map((id) => Number(id)); if (!ids.length) { continue; } stopNpcMovement(world, entity.handle); for (const characterId of ids) { const playerEntityId = world.characterEntities.get(characterId); if (playerEntityId == null) { removeShopBrowser(shop, characterId); continue; } const playerHandle = world.ecs.handleOf(playerEntityId); const playerPos = world.ecs.get(playerHandle, Component.position); const stillNear = playerPos && chebyshev( playerPos.tileX, playerPos.tileY, entity.position.tileX, entity.position.tileY ) <= 1; if (stillNear) { continue; } removeShopBrowser(shop, characterId); const identity = world.ecs.get(playerHandle, Component.networkIdentity); if (identity?.sessionId != null) { events.push({ type: "shop-closed", sessionId: identity.sessionId, characterId, npcEntityId: entity.entityId }); } } } return events; } function lastSaleFor (world, itemId) { return world.itemLastSales?.get(itemId) ?? null; } function lerpDuration (world) { return world.settings?.shopPriceLerpDurationMs ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs; } function shopDisplayName (shop, npcHandle, world) { const appearance = world.ecs.get(npcHandle, Component.appearance); return shop.displayName || [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ") || "Shopkeeper"; } function ensureVault (ecs, handle) { let vault = ecs.get(handle, Component.vault); if (!vault) { vault = ecs.add(handle, Component.vault, { slots: [], reserved: [] }); } if (!Array.isArray(vault.slots)) { vault.slots = []; } if (!Array.isArray(vault.reserved)) { vault.reserved = []; } return vault; } /** Refresh catalog remaining and clear bought-from-players stock at local midnight. */ export function ensureShopRestocked (shop, now = Date.now()) { if (!shop) { return; } if (!Array.isArray(shop.catalog)) { shop.catalog = []; } if (Array.isArray(shop.stock) && !shop.catalog.length) { shop.catalog = shop.stock .map((id) => ({ itemId: id | 0, quantity: 0 })) .filter((line) => line.itemId > 0); } if (!shop.remaining || typeof shop.remaining !== "object") { shop.remaining = Object.create(null); } if (!shop.boughtStock || typeof shop.boughtStock !== "object") { shop.boughtStock = Object.create(null); } const day = shopRestockDayKey(now); if (shop.restockDay === day) { return; } shop.restockDay = day; shop.boughtStock = Object.create(null); shop.remaining = Object.create(null); for (const line of shop.catalog) { const itemId = line.itemId | 0; const quantity = Math.max(0, line.quantity | 0 || 0); if (itemId > 0 && quantity > 0) { shop.remaining[itemId] = quantity; } } } function catalogLine (shop, itemId) { return (shop.catalog ?? []).find((line) => (line.itemId | 0) === (itemId | 0)) ?? null; } function catalogAvailable (shop, itemId) { const line = catalogLine(shop, itemId); if (!line) { return 0; } if ((line.quantity | 0) <= 0) { return Number.POSITIVE_INFINITY; } return Math.max(0, shop.remaining?.[itemId] | 0 || 0); } /** * Bought-stock map key. Plain items use `${itemId}`; dyes/potions/flowers keep * colour / recipe identity so resale lots do not merge across variants. */ export function boughtStockKey (itemId, instance = null) { const id = itemId | 0; const def = itemDefinition(id); if (def?.dye) { const identity = dyeStackIdentity(instance); return identity ? `${id}#dye:${identity}` : String(id); } if (def?.potion) { const identity = potionStackIdentity(instance); return identity ? `${id}#potion:${identity}` : String(id); } if (def?.flower && instance?.colorId) { return `${id}#flower:${instance.colorId}`; } return String(id); } function itemIdFromStockKey (stockKey) { if (stockKey == null) { return 0; } const text = String(stockKey); const hash = text.indexOf("#"); return (hash >= 0 ? text.slice(0, hash) : text) | 0; } /** Normalize legacy qty-only boughtStock entries into `{ itemId, quantity, origins, instance }`. */ function boughtLot (shop, stockKey) { const key = stockKey == null ? null : String(stockKey); if (!key) { return null; } let raw = shop.boughtStock?.[key]; if (raw == null && /^\d+$/.test(key)) { raw = shop.boughtStock?.[Number(key)]; } if (raw == null) { return null; } const itemId = (typeof raw === "object" && raw.itemId != null) ? (raw.itemId | 0) : itemIdFromStockKey(key); if (typeof raw === "number") { const quantity = Math.max(0, raw | 0); if (quantity <= 0) { return null; } return { stockKey: key, itemId, quantity, origins: [{ origin: shopOrigin("a shop"), quantity }], instance: null }; } const quantity = Math.max(0, raw.quantity | 0 || 0); if (quantity <= 0) { return null; } const origins = normalizeOrigins({ quantity, origins: raw.origins }); const originQty = origins.reduce((sum, entry) => sum + entry.quantity, 0); if (originQty < quantity) { origins.push({ origin: shopOrigin("a shop"), quantity: quantity - originQty }); } return { stockKey: key, itemId, quantity, origins, instance: raw.instance ? structuredClone(raw.instance) : null }; } function boughtAvailable (shop, stockKey) { return boughtLot(shop, stockKey)?.quantity ?? 0; } function addBoughtLot (shop, itemId, quantity, origins, instance = null) { const qty = Math.max(0, quantity | 0 || 0); if (qty <= 0) { return; } const key = boughtStockKey(itemId, instance); const existing = boughtLot(shop, key); const nextOrigins = mergeOriginLists( existing?.origins ?? [], normalizeOrigins({ quantity: qty, origins }) ); const keptInstance = existing?.instance ?? (instance ? structuredClone(instance) : null); shop.boughtStock[key] = { itemId: itemId | 0, quantity: (existing?.quantity ?? 0) + qty, origins: nextOrigins, instance: keptInstance }; } /** Pull FIFO origins from bought stock; returns null if insufficient. */ function takeBoughtLot (shop, stockKey, quantity) { const qty = Math.max(0, quantity | 0 || 0); const lot = boughtLot(shop, stockKey); if (!lot || lot.quantity < qty) { return null; } const split = splitOrigins(lot.origins, qty); const remainQty = lot.quantity - qty; const key = lot.stockKey; if (remainQty <= 0) { delete shop.boughtStock[key]; } else { shop.boughtStock[key] = { itemId: lot.itemId, quantity: remainQty, origins: split.remain, instance: lot.instance ? structuredClone(lot.instance) : null }; } return { quantity: qty, origins: split.taken, instance: lot.instance ? structuredClone(lot.instance) : null, itemId: lot.itemId }; } function shopStockView (world, shop, now) { ensureShopRestocked(shop, now); const lastSaleOpts = (itemId) => ({ lastSale: lastSaleFor(world, itemId), now, lerpDurationMs: lerpDuration(world), settings: world.settings ?? null }); const stock = []; for (const line of shop.catalog ?? []) { const itemId = line.itemId | 0; const def = itemDefinition(itemId); if (!def) { continue; } const available = catalogAvailable(shop, itemId); if (available === 0) { continue; } stock.push({ listingId: `stock:${itemId}`, itemId, displayName: def.displayName, unitPrice: shopUnitPrice(itemId, { ...lastSaleOpts(itemId), hiddenDiscount: shop.hiddenDiscount ?? 1 }), available: Number.isFinite(available) ? available : null, source: "stock", instance: null }); } for (const key of Object.keys(shop.boughtStock ?? {})) { const lot = boughtLot(shop, key); if (!lot || lot.quantity <= 0) { continue; } const itemId = lot.itemId; const def = itemDefinition(itemId); if (!def) { continue; } const stack = { itemId, quantity: lot.quantity, instance: lot.instance }; stock.push({ listingId: `bought:${lot.stockKey}`, itemId, displayName: itemDisplayName(stack, def), unitPrice: shopBoughtResalePrice(itemId, lastSaleOpts(itemId)), available: lot.quantity, source: "bought", instance: lot.instance ? structuredClone(lot.instance) : null }); } return stock; } function shopOpenEvent (world, sessionId, characterId, npcEntityId, shop, displayName, now) { const npcHandle = world.ecs.handleOf(npcEntityId); return { type: "shop-open", sessionId, characterId, npcEntityId, displayName, sex: npcHandle != null ? npcSex(world, npcHandle) : "male", buysItems: !!shop.buysItems, stock: shopStockView(world, shop, now) }; } function requireShopAccess (world, sessionId, characterId, npcEntityId) { const entityId = world.characterEntities.get(characterId); if (entityId == null) { throw userError("Character is not in the world."); } const handle = world.ecs.handleOf(entityId); const identity = world.ecs.get(handle, Component.networkIdentity); if (!identity || identity.sessionId !== sessionId) { throw userError("Character is not in the world."); } if (world.ecs.has(handle, Component.dead)) { throw userError("You are dead."); } const npcHandle = world.ecs.handleOf(npcEntityId); if (npcHandle == null) { throw userError("Target is not here."); } const shop = world.ecs.get(npcHandle, Component.shop); const sex = npcSex(world, npcHandle); if (!shop || (!(shop.catalog?.length) && !shop.buysItems)) { const who = sex === "female" ? "She" : "He"; throw userError(`${who} is not selling anything.`); } const playerPos = world.ecs.get(handle, Component.position); const npcPos = world.ecs.get(npcHandle, Component.position); if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1) { throw userError(`You need to stand next to ${objectPronoun(sex)}.`); } return { handle, npcHandle, shop, entityId }; } export function openShop (world, sessionId, characterId, npcEntityId, now = Date.now()) { const { shop, npcHandle } = requireShopAccess(world, sessionId, characterId, npcEntityId); ensureShopRestocked(shop, now); addShopBrowser(world, shop, npcHandle, characterId); const displayName = shopDisplayName(shop, npcHandle, world); return { events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)] }; } export function closeShop (world, sessionId, characterId, npcEntityId) { const entityId = world.characterEntities.get(characterId); if (entityId == null) { return { events: [] }; } const handle = world.ecs.handleOf(entityId); const identity = world.ecs.get(handle, Component.networkIdentity); if (!identity || identity.sessionId !== sessionId) { return { events: [] }; } const npcHandle = world.ecs.handleOf(npcEntityId | 0); if (npcHandle == null) { return { events: [] }; } const shop = world.ecs.get(npcHandle, Component.shop); removeShopBrowser(shop, characterId); return { events: [] }; } function parseListing (listingId, itemId, source) { if (typeof listingId === "string") { if (listingId.startsWith("bought:")) { const stockKey = listingId.slice("bought:".length); return { source: "bought", itemId: itemIdFromStockKey(stockKey), stockKey }; } if (listingId.startsWith("stock:")) { return { source: "stock", itemId: listingId.slice("stock:".length) | 0, stockKey: null }; } } if (source === "bought") { const id = itemId | 0; return { source: "bought", itemId: id, stockKey: String(id) }; } return { source: "stock", itemId: itemId | 0, stockKey: null }; } export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now(), listingId = null, source = null) { const { handle, npcHandle, shop } = requireShopAccess(world, sessionId, characterId, npcEntityId); ensureShopRestocked(shop, now); const listing = parseListing(listingId, itemId, source); const buyItemId = listing.itemId; if (listing.source === "stock") { if (!catalogLine(shop, buyItemId)) { throw userError("That item cannot be sold here."); } } else if (boughtAvailable(shop, listing.stockKey) <= 0) { throw userError("Not enough stock."); } const qty = Math.max(1, quantity | 0 || 1); const def = itemDefinition(buyItemId); if (!def) { throw userError("Unknown item."); } const available = listing.source === "bought" ? boughtAvailable(shop, listing.stockKey) : catalogAvailable(shop, buyItemId); if (available < qty) { throw userError("Not enough stock."); } const unitPrice = listing.source === "bought" ? shopBoughtResalePrice(buyItemId, { lastSale: lastSaleFor(world, buyItemId), now, lerpDurationMs: lerpDuration(world), settings: world.settings ?? null }) : shopUnitPrice(buyItemId, { lastSale: lastSaleFor(world, buyItemId), now, lerpDurationMs: lerpDuration(world), hiddenDiscount: shop.hiddenDiscount ?? 1, settings: world.settings ?? null }); const total = unitPrice * qty; const inventory = world.ecs.get(handle, Component.inventory); if (!inventory) { throw userError("No inventory."); } if (countCoinsInSlots(inventory.slots) < total) { throw userError("You cannot afford that."); } const paid = takeCoinsFromSlots(inventory.slots, total); if (!paid.ok) { throw userError("You cannot afford that."); } const displayName = shopDisplayName(shop, npcHandle, world); let stack; if (listing.source === "bought") { const lot = boughtLot(shop, listing.stockKey); if (!lot || lot.quantity < qty) { throw userError("Not enough stock."); } const split = splitOrigins(lot.origins, qty); stack = attachOrigins({ itemId: buyItemId, quantity: qty, instance: lot.instance ? structuredClone(lot.instance) : null, origins: split.taken }); } else { const shopOriginEntry = { kind: ItemOriginKind.shop, displayName }; const defaultInstance = def?.defaultInstance ? structuredClone(def.defaultInstance) : null; stack = attachOrigins({ itemId: buyItemId, quantity: qty, instance: defaultInstance, origins: [{ origin: shopOriginEntry, quantity: qty }] }); } const added = insertStack(paid.slots, stack, def); inventory.slots = added.slots; if (added.remainder > 0) { const overflowOrigins = splitOrigins(normalizeOrigins(stack), qty - added.remainder).remain; const overflow = attachOrigins({ itemId: buyItemId, quantity: added.remainder, instance: stack.instance ? structuredClone(stack.instance) : null, origins: overflowOrigins }); const vault = ensureVault(world.ecs, handle); const vaulted = insertStackGrowable(vault.slots, overflow, def); if (!vaulted.ok || vaulted.remainder > 0) { throw userError("Your bank cannot hold that purchase."); } vault.slots = vaulted.slots; } if (listing.source === "bought") { if (!takeBoughtLot(shop, listing.stockKey, qty)) { throw userError("Not enough stock."); } } else { const line = catalogLine(shop, buyItemId); if (line && (line.quantity | 0) > 0) { shop.remaining[buyItemId] = catalogAvailable(shop, buyItemId) - qty; } } return { events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)], private: bagView(world.ecs, handle) }; } /** * Player sells to NPC (requires buysItems). * Buys any transferable bag goods except blank cheques. * Filled cheques sell as their reserved goods with a 5% admin fee. * Limited catalog lines refill first; remainder goes into boughtStock * (cleared at midnight). Infinite catalog lines absorb goods without resale stock. * Letters pay out but are destroyed — never restocked or put in boughtStock. */ export function sellToShop (world, sessionId, characterId, npcEntityId, slotIndex, quantity = 1, now = Date.now()) { const { handle, npcHandle, shop } = requireShopAccess(world, sessionId, characterId, npcEntityId); ensureShopRestocked(shop, now); if (!shop.buysItems) { throw userError("They are not buying anything."); } const inventory = world.ecs.get(handle, Component.inventory); if (!inventory) { throw userError("No inventory."); } const slot = inventory.slots[slotIndex | 0]; if (!slot) { throw userError("That slot is empty."); } if (!canPlayerSellToNpc(slot)) { throw userError("They will not buy that."); } const isCheque = (slot.itemId | 0) === ItemId.filledCheque; const isLetter = isLetterStack(slot); const quote = resolveShopSellQuote(slot, { lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)), now, lerpDurationMs: lerpDuration(world), settings: world.settings ?? null, quantity: isCheque ? 1 : (quantity | 0 || 1) }); if (!quote) { throw userError("They will not buy that."); } const goodsItemId = quote.goodsItemId; const qty = quote.goodsQuantity; const line = catalogLine(shop, goodsItemId); let refill = 0; let leftover = qty; if (isLetter) { // Destroyed on sale — never enter shop stock. refill = 0; leftover = 0; } else if (line) { if ((line.quantity | 0) <= 0) { refill = qty; leftover = 0; } else { const space = Math.max(0, (line.quantity | 0) - catalogAvailable(shop, goodsItemId)); refill = Math.min(qty, space); leftover = qty - refill; } } const total = quote.payout; let reservedStack = null; let chequeTaken = null; let taken = null; if (isCheque) { const instance = slot.instance; const issuerId = instance.issuerCharacterId; chequeTaken = takeFromSlot(inventory.slots, slotIndex | 0, 1); if (!chequeTaken.ok) { throw userError("Could not take that item."); } inventory.slots = chequeTaken.slots; if (Number(issuerId) === Number(characterId)) { const vault = world.ecs.get(handle, Component.vault); if (!vault) { inventory.slots[slotIndex | 0] = chequeTaken.taken; throw userError("That cheque cannot be sold."); } if (!Array.isArray(vault.reserved)) { vault.reserved = []; } const index = findReservedChequeIndex(vault.reserved, instance); if (index < 0) { inventory.slots[slotIndex | 0] = chequeTaken.taken; throw userError("That cheque cannot be sold."); } reservedStack = cloneStack(vault.reserved[index]); vault.reserved = vault.reserved.filter((_, i) => i !== index); } else { const release = world.releaseChequeReservation?.(issuerId, instance.chequeId, instance); if (!release?.ok) { inventory.slots[slotIndex | 0] = chequeTaken.taken; throw userError(release?.error ?? "That cheque cannot be sold."); } reservedStack = release.stack; } } else { taken = takeFromSlot(inventory.slots, slotIndex | 0, qty); if (!taken.ok) { throw userError("Could not take that item."); } } const slotsAfterTake = isCheque ? inventory.slots : taken.slots; const paid = addCoinsToSlots(slotsAfterTake, total); if (!paid.ok) { if (isCheque) { inventory.slots[slotIndex | 0] = chequeTaken.taken; if (Number(slot.instance.issuerCharacterId) === Number(characterId)) { const vault = world.ecs.get(handle, Component.vault); if (vault && reservedStack) { vault.reserved = [...(vault.reserved ?? []), reservedStack]; } } else if (reservedStack) { world.restoreChequeReservation?.(slot.instance.issuerCharacterId, reservedStack); } } else { const def = itemDefinition(goodsItemId); inventory.slots = insertStack(taken.slots, taken.taken, def).slots; } throw userError("Not enough bag space for coins."); } inventory.slots = paid.slots; if (line && (line.quantity | 0) > 0 && refill > 0) { shop.remaining[goodsItemId] = catalogAvailable(shop, goodsItemId) + refill; } if (leftover > 0) { const soldStack = isCheque ? reservedStack : taken.taken; const soldOrigins = normalizeOrigins(soldStack); // Catalog refill absorbs first; leftover keeps remaining origins for resale. const { remain: resaleOrigins } = splitOrigins(soldOrigins, refill); addBoughtLot( shop, goodsItemId, leftover, resaleOrigins, soldStack?.instance ?? null ); } const displayName = shopDisplayName(shop, npcHandle, world); return { events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)], private: bagView(world.ecs, handle) }; } export function handleShopCommand (world, sessionId, command, now) { switch (command.type) { case "buy-from-shop": return buyFromShop( world, sessionId, command.characterId, command.npcEntityId | 0, command.itemId | 0, command.quantity | 0 || 1, now, command.listingId ?? null, command.source ?? null ); case "sell-to-shop": return sellToShop( world, sessionId, command.characterId, command.npcEntityId | 0, command.slotIndex | 0, command.quantity | 0 || 1, now ); case "close-shop": return closeShop(world, sessionId, command.characterId, command.npcEntityId | 0); default: return null; } } export function shopHasInterface (shop) { if (!shop) { return false; } if (shop.buysItems) { return true; } if ((shop.catalog?.length ?? 0) > 0) { return true; } if (Object.keys(shop.boughtStock ?? {}).length > 0) { return true; } // Legacy shops spawned before catalog migration. if ((shop.stock?.length ?? 0) > 0) { return true; } return false; }