| 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 { |
| 13 | addCoinsToSlots, |
| 14 | cloneStack, |
| 15 | countCoinsInSlots, |
| 16 | insertStack, |
| 17 | insertStackGrowable, |
| 18 | takeCoinsFromSlots, |
| 19 | takeFromSlot |
| 20 | } from "../../../shared/items/inventory.js"; |
| 21 | import { |
| 22 | canSellInNpcShop, |
| 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 | if (!canSellInNpcShop(itemId)) |
| 302 | { continue; } |
| 303 | const def = itemDefinition(itemId); |
| 304 | if (!def) |
| 305 | { continue; } |
| 306 | const available = catalogAvailable(shop, itemId); |
| 307 | if (available === 0) |
| 308 | { continue; } |
| 309 | stock.push({ |
| 310 | listingId: `stock:${itemId}`, |
| 311 | itemId, |
| 312 | displayName: def.displayName, |
| 313 | unitPrice: shopUnitPrice(itemId, { |
| 314 | ...lastSaleOpts(itemId), |
| 315 | hiddenDiscount: shop.hiddenDiscount ?? 1 |
| 316 | }), |
| 317 | available: Number.isFinite(available) ? available : null, |
| 318 | source: "stock" |
| 319 | }); |
| 320 | } |
| 321 | for (const key of Object.keys(shop.boughtStock ?? {})) |
| 322 | { |
| 323 | const itemId = key | 0; |
| 324 | const available = boughtAvailable(shop, itemId); |
| 325 | if (available <= 0 || !canSellInNpcShop(itemId)) |
| 326 | { continue; } |
| 327 | const def = itemDefinition(itemId); |
| 328 | if (!def) |
| 329 | { continue; } |
| 330 | stock.push({ |
| 331 | listingId: `bought:${itemId}`, |
| 332 | itemId, |
| 333 | displayName: def.displayName, |
| 334 | unitPrice: shopBoughtResalePrice(itemId, lastSaleOpts(itemId)), |
| 335 | available, |
| 336 | source: "bought" |
| 337 | }); |
| 338 | } |
| 339 | return stock; |
| 340 | } |
| 341 | |
| 342 | function shopOpenEvent (world, sessionId, characterId, npcEntityId, shop, displayName, now) |
| 343 | { |
| 344 | const npcHandle = world.ecs.handleOf(npcEntityId); |
| 345 | return { |
| 346 | type: "shop-open", |
| 347 | sessionId, |
| 348 | characterId, |
| 349 | npcEntityId, |
| 350 | displayName, |
| 351 | sex: npcHandle != null ? npcSex(world, npcHandle) : "male", |
| 352 | buysItems: !!shop.buysItems, |
| 353 | stock: shopStockView(world, shop, now) |
| 354 | }; |
| 355 | } |
| 356 | |
| 357 | function requireShopAccess (world, sessionId, characterId, npcEntityId) |
| 358 | { |
| 359 | const entityId = world.characterEntities.get(characterId); |
| 360 | if (entityId == null) |
| 361 | { throw userError("Character is not in the world."); } |
| 362 | const handle = world.ecs.handleOf(entityId); |
| 363 | const identity = world.ecs.get(handle, Component.networkIdentity); |
| 364 | if (!identity || identity.sessionId !== sessionId) |
| 365 | { throw userError("Character is not in the world."); } |
| 366 | if (world.ecs.has(handle, Component.dead)) |
| 367 | { throw userError("You are dead."); } |
| 368 | |
| 369 | const npcHandle = world.ecs.handleOf(npcEntityId); |
| 370 | if (npcHandle == null) |
| 371 | { throw userError("Target is not here."); } |
| 372 | const shop = world.ecs.get(npcHandle, Component.shop); |
| 373 | const sex = npcSex(world, npcHandle); |
| 374 | if (!shop || (!(shop.catalog?.length) && !shop.buysItems)) |
| 375 | { |
| 376 | const who = sex === "female" ? "She" : "He"; |
| 377 | throw userError(`${who} is not selling anything.`); |
| 378 | } |
| 379 | |
| 380 | const playerPos = world.ecs.get(handle, Component.position); |
| 381 | const npcPos = world.ecs.get(npcHandle, Component.position); |
| 382 | if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1) |
| 383 | { throw userError(`You need to stand next to ${objectPronoun(sex)}.`); } |
| 384 | |
| 385 | return { handle, npcHandle, shop, entityId }; |
| 386 | } |
| 387 | |
| 388 | export function openShop (world, sessionId, characterId, npcEntityId, now = Date.now()) |
| 389 | { |
| 390 | const { shop, npcHandle } = requireShopAccess(world, sessionId, characterId, npcEntityId); |
| 391 | ensureShopRestocked(shop, now); |
| 392 | addShopBrowser(world, shop, npcHandle, characterId); |
| 393 | const displayName = shopDisplayName(shop, npcHandle, world); |
| 394 | return { |
| 395 | events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)] |
| 396 | }; |
| 397 | } |
| 398 | |
| 399 | export function closeShop (world, sessionId, characterId, npcEntityId) |
| 400 | { |
| 401 | const entityId = world.characterEntities.get(characterId); |
| 402 | if (entityId == null) |
| 403 | { return { events: [] }; } |
| 404 | const handle = world.ecs.handleOf(entityId); |
| 405 | const identity = world.ecs.get(handle, Component.networkIdentity); |
| 406 | if (!identity || identity.sessionId !== sessionId) |
| 407 | { return { events: [] }; } |
| 408 | const npcHandle = world.ecs.handleOf(npcEntityId | 0); |
| 409 | if (npcHandle == null) |
| 410 | { return { events: [] }; } |
| 411 | const shop = world.ecs.get(npcHandle, Component.shop); |
| 412 | removeShopBrowser(shop, characterId); |
| 413 | return { events: [] }; |
| 414 | } |
| 415 | |
| 416 | function parseListing (listingId, itemId, source) |
| 417 | { |
| 418 | if (typeof listingId === "string" && listingId.includes(":")) |
| 419 | { |
| 420 | const [kind, id] = listingId.split(":"); |
| 421 | return { source: kind === "bought" ? "bought" : "stock", itemId: id | 0 }; |
| 422 | } |
| 423 | if (source === "bought") |
| 424 | { return { source: "bought", itemId: itemId | 0 }; } |
| 425 | return { source: "stock", itemId: itemId | 0 }; |
| 426 | } |
| 427 | |
| 428 | export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now(), listingId = null, source = null) |
| 429 | { |
| 430 | const { handle, npcHandle, shop } = requireShopAccess(world, sessionId, characterId, npcEntityId); |
| 431 | ensureShopRestocked(shop, now); |
| 432 | const listing = parseListing(listingId, itemId, source); |
| 433 | const buyItemId = listing.itemId; |
| 434 | if (!canSellInNpcShop(buyItemId)) |
| 435 | { throw userError("That item cannot be sold here."); } |
| 436 | |
| 437 | const qty = Math.max(1, quantity | 0 || 1); |
| 438 | const def = itemDefinition(buyItemId); |
| 439 | if (!def) |
| 440 | { throw userError("Unknown item."); } |
| 441 | |
| 442 | const available = listing.source === "bought" |
| 443 | ? boughtAvailable(shop, buyItemId) |
| 444 | : catalogAvailable(shop, buyItemId); |
| 445 | if (available < qty) |
| 446 | { throw userError("Not enough stock."); } |
| 447 | |
| 448 | const unitPrice = listing.source === "bought" |
| 449 | ? shopBoughtResalePrice(buyItemId, { |
| 450 | lastSale: lastSaleFor(world, buyItemId), |
| 451 | now, |
| 452 | lerpDurationMs: lerpDuration(world), |
| 453 | settings: world.settings ?? null |
| 454 | }) |
| 455 | : shopUnitPrice(buyItemId, { |
| 456 | lastSale: lastSaleFor(world, buyItemId), |
| 457 | now, |
| 458 | lerpDurationMs: lerpDuration(world), |
| 459 | hiddenDiscount: shop.hiddenDiscount ?? 1, |
| 460 | settings: world.settings ?? null |
| 461 | }); |
| 462 | const total = unitPrice * qty; |
| 463 | const inventory = world.ecs.get(handle, Component.inventory); |
| 464 | if (!inventory) |
| 465 | { throw userError("No inventory."); } |
| 466 | if (countCoinsInSlots(inventory.slots) < total) |
| 467 | { throw userError("You cannot afford that."); } |
| 468 | |
| 469 | const paid = takeCoinsFromSlots(inventory.slots, total); |
| 470 | if (!paid.ok) |
| 471 | { throw userError("You cannot afford that."); } |
| 472 | |
| 473 | const displayName = shopDisplayName(shop, npcHandle, world); |
| 474 | let stack; |
| 475 | if (listing.source === "bought") |
| 476 | { |
| 477 | const lot = boughtLot(shop, buyItemId); |
| 478 | if (!lot || lot.quantity < qty) |
| 479 | { throw userError("Not enough stock."); } |
| 480 | const split = splitOrigins(lot.origins, qty); |
| 481 | stack = attachOrigins({ |
| 482 | itemId: buyItemId, |
| 483 | quantity: qty, |
| 484 | origins: split.taken |
| 485 | }); |
| 486 | } |
| 487 | else |
| 488 | { |
| 489 | const shopOriginEntry = { kind: ItemOriginKind.shop, displayName }; |
| 490 | stack = attachOrigins({ |
| 491 | itemId: buyItemId, |
| 492 | quantity: qty, |
| 493 | origins: [{ origin: shopOriginEntry, quantity: qty }] |
| 494 | }); |
| 495 | } |
| 496 | const added = insertStack(paid.slots, stack, def); |
| 497 | inventory.slots = added.slots; |
| 498 | if (added.remainder > 0) |
| 499 | { |
| 500 | const overflowOrigins = splitOrigins(normalizeOrigins(stack), qty - added.remainder).remain; |
| 501 | const overflow = attachOrigins({ |
| 502 | itemId: buyItemId, |
| 503 | quantity: added.remainder, |
| 504 | origins: overflowOrigins |
| 505 | }); |
| 506 | const vault = ensureVault(world.ecs, handle); |
| 507 | const vaulted = insertStackGrowable(vault.slots, overflow, def); |
| 508 | if (!vaulted.ok || vaulted.remainder > 0) |
| 509 | { throw userError("Your bank cannot hold that purchase."); } |
| 510 | vault.slots = vaulted.slots; |
| 511 | } |
| 512 | |
| 513 | if (listing.source === "bought") |
| 514 | { |
| 515 | if (!takeBoughtLot(shop, buyItemId, qty)) |
| 516 | { throw userError("Not enough stock."); } |
| 517 | } |
| 518 | else |
| 519 | { |
| 520 | const line = catalogLine(shop, buyItemId); |
| 521 | if (line && (line.quantity | 0) > 0) |
| 522 | { shop.remaining[buyItemId] = catalogAvailable(shop, buyItemId) - qty; } |
| 523 | } |
| 524 | |
| 525 | return { |
| 526 | events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)], |
| 527 | private: bagView(world.ecs, handle) |
| 528 | }; |
| 529 | } |
| 530 | |
| 531 | /** |
| 532 | * Player sells to NPC (requires buysItems). |
| 533 | * Buys any transferable bag goods except blank cheques. |
| 534 | * Filled cheques sell as their reserved goods with a 5% admin fee. |
| 535 | * Limited catalog lines refill first; remainder goes into boughtStock |
| 536 | * (cleared at midnight). Infinite catalog lines absorb goods without resale stock. |
| 537 | */ |
| 538 | export function sellToShop (world, sessionId, characterId, npcEntityId, slotIndex, quantity = 1, now = Date.now()) |
| 539 | { |
| 540 | const { handle, npcHandle, shop } = requireShopAccess(world, sessionId, characterId, npcEntityId); |
| 541 | ensureShopRestocked(shop, now); |
| 542 | if (!shop.buysItems) |
| 543 | { throw userError("They are not buying anything."); } |
| 544 | |
| 545 | const inventory = world.ecs.get(handle, Component.inventory); |
| 546 | if (!inventory) |
| 547 | { throw userError("No inventory."); } |
| 548 | const slot = inventory.slots[slotIndex | 0]; |
| 549 | if (!slot) |
| 550 | { throw userError("That slot is empty."); } |
| 551 | if (!canPlayerSellToNpc(slot)) |
| 552 | { throw userError("They will not buy that."); } |
| 553 | |
| 554 | const isCheque = (slot.itemId | 0) === ItemId.filledCheque; |
| 555 | const quote = resolveShopSellQuote(slot, { |
| 556 | lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)), |
| 557 | now, |
| 558 | lerpDurationMs: lerpDuration(world), |
| 559 | settings: world.settings ?? null, |
| 560 | quantity: isCheque ? 1 : (quantity | 0 || 1) |
| 561 | }); |
| 562 | if (!quote) |
| 563 | { throw userError("They will not buy that."); } |
| 564 | |
| 565 | const goodsItemId = quote.goodsItemId; |
| 566 | const qty = quote.goodsQuantity; |
| 567 | const line = catalogLine(shop, goodsItemId); |
| 568 | let refill = 0; |
| 569 | let leftover = qty; |
| 570 | if (line) |
| 571 | { |
| 572 | if ((line.quantity | 0) <= 0) |
| 573 | { |
| 574 | refill = qty; |
| 575 | leftover = 0; |
| 576 | } |
| 577 | else |
| 578 | { |
| 579 | const space = Math.max(0, (line.quantity | 0) - catalogAvailable(shop, goodsItemId)); |
| 580 | refill = Math.min(qty, space); |
| 581 | leftover = qty - refill; |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | const total = quote.payout; |
| 586 | let reservedStack = null; |
| 587 | let chequeTaken = null; |
| 588 | let taken = null; |
| 589 | |
| 590 | if (isCheque) |
| 591 | { |
| 592 | const instance = slot.instance; |
| 593 | const issuerId = instance.issuerCharacterId; |
| 594 | chequeTaken = takeFromSlot(inventory.slots, slotIndex | 0, 1); |
| 595 | if (!chequeTaken.ok) |
| 596 | { throw userError("Could not take that item."); } |
| 597 | inventory.slots = chequeTaken.slots; |
| 598 | |
| 599 | if (Number(issuerId) === Number(characterId)) |
| 600 | { |
| 601 | const vault = world.ecs.get(handle, Component.vault); |
| 602 | if (!vault) |
| 603 | { |
| 604 | inventory.slots[slotIndex | 0] = chequeTaken.taken; |
| 605 | throw userError("That cheque cannot be sold."); |
| 606 | } |
| 607 | if (!Array.isArray(vault.reserved)) |
| 608 | { vault.reserved = []; } |
| 609 | const index = findReservedChequeIndex(vault.reserved, instance); |
| 610 | if (index < 0) |
| 611 | { |
| 612 | inventory.slots[slotIndex | 0] = chequeTaken.taken; |
| 613 | throw userError("That cheque cannot be sold."); |
| 614 | } |
| 615 | reservedStack = cloneStack(vault.reserved[index]); |
| 616 | vault.reserved = vault.reserved.filter((_, i) => i !== index); |
| 617 | } |
| 618 | else |
| 619 | { |
| 620 | const release = world.releaseChequeReservation?.(issuerId, instance.chequeId, instance); |
| 621 | if (!release?.ok) |
| 622 | { |
| 623 | inventory.slots[slotIndex | 0] = chequeTaken.taken; |
| 624 | throw userError(release?.error ?? "That cheque cannot be sold."); |
| 625 | } |
| 626 | reservedStack = release.stack; |
| 627 | } |
| 628 | } |
| 629 | else |
| 630 | { |
| 631 | taken = takeFromSlot(inventory.slots, slotIndex | 0, qty); |
| 632 | if (!taken.ok) |
| 633 | { throw userError("Could not take that item."); } |
| 634 | } |
| 635 | |
| 636 | const slotsAfterTake = isCheque ? inventory.slots : taken.slots; |
| 637 | const paid = addCoinsToSlots(slotsAfterTake, total); |
| 638 | if (!paid.ok) |
| 639 | { |
| 640 | if (isCheque) |
| 641 | { |
| 642 | inventory.slots[slotIndex | 0] = chequeTaken.taken; |
| 643 | if (Number(slot.instance.issuerCharacterId) === Number(characterId)) |
| 644 | { |
| 645 | const vault = world.ecs.get(handle, Component.vault); |
| 646 | if (vault && reservedStack) |
| 647 | { vault.reserved = [...(vault.reserved ?? []), reservedStack]; } |
| 648 | } |
| 649 | else if (reservedStack) |
| 650 | { world.restoreChequeReservation?.(slot.instance.issuerCharacterId, reservedStack); } |
| 651 | } |
| 652 | else |
| 653 | { |
| 654 | const def = itemDefinition(goodsItemId); |
| 655 | inventory.slots = insertStack(taken.slots, taken.taken, def).slots; |
| 656 | } |
| 657 | throw userError("Not enough bag space for coins."); |
| 658 | } |
| 659 | inventory.slots = paid.slots; |
| 660 | |
| 661 | if (line && (line.quantity | 0) > 0 && refill > 0) |
| 662 | { shop.remaining[goodsItemId] = catalogAvailable(shop, goodsItemId) + refill; } |
| 663 | if (leftover > 0) |
| 664 | { |
| 665 | const soldStack = isCheque ? reservedStack : taken.taken; |
| 666 | const soldOrigins = normalizeOrigins(soldStack); |
| 667 | // Catalog refill absorbs first; leftover keeps remaining origins for resale. |
| 668 | const { remain: resaleOrigins } = splitOrigins(soldOrigins, refill); |
| 669 | addBoughtLot(shop, goodsItemId, leftover, resaleOrigins); |
| 670 | } |
| 671 | |
| 672 | const displayName = shopDisplayName(shop, npcHandle, world); |
| 673 | return { |
| 674 | events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)], |
| 675 | private: bagView(world.ecs, handle) |
| 676 | }; |
| 677 | } |
| 678 | |
| 679 | export function handleShopCommand (world, sessionId, command, now) |
| 680 | { |
| 681 | switch (command.type) |
| 682 | { |
| 683 | case "buy-from-shop": |
| 684 | return buyFromShop( |
| 685 | world, |
| 686 | sessionId, |
| 687 | command.characterId, |
| 688 | command.npcEntityId | 0, |
| 689 | command.itemId | 0, |
| 690 | command.quantity | 0 || 1, |
| 691 | now, |
| 692 | command.listingId ?? null, |
| 693 | command.source ?? null |
| 694 | ); |
| 695 | case "sell-to-shop": |
| 696 | return sellToShop( |
| 697 | world, |
| 698 | sessionId, |
| 699 | command.characterId, |
| 700 | command.npcEntityId | 0, |
| 701 | command.slotIndex | 0, |
| 702 | command.quantity | 0 || 1, |
| 703 | now |
| 704 | ); |
| 705 | case "close-shop": |
| 706 | return closeShop(world, sessionId, command.characterId, command.npcEntityId | 0); |
| 707 | default: |
| 708 | return null; |
| 709 | } |
| 710 | } |
| 711 | |
| 712 | export function shopHasInterface (shop) |
| 713 | { |
| 714 | if (!shop) |
| 715 | { return false; } |
| 716 | if (shop.buysItems) |
| 717 | { return true; } |
| 718 | if ((shop.catalog?.length ?? 0) > 0) |
| 719 | { return true; } |
| 720 | if (Object.keys(shop.boughtStock ?? {}).length > 0) |
| 721 | { return true; } |
| 722 | // Legacy shops spawned before catalog migration. |
| 723 | if ((shop.stock?.length ?? 0) > 0) |
| 724 | { return true; } |
| 725 | return false; |
| 726 | } |