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