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