BlueGit

timfa questward

Files

questward / server / src / shop / service.js

service.js

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