BlueGit

timfa questward

Files

questward / server / tests / shop.test.js

shop.test.js

shop.test.js 42.5 KiB Download Raw
1import test from "node:test";
2import assert from "node:assert/strict";
3import
4 {
5 shopUnitPrice,
6 undiscountedMarketValue,
7 undiscountedMarketCoins,
8 marketValueAsCoins,
9 canSellInNpcShop,
10 canPlayerSellToNpc,
11 shopBuyFromPlayerPrice,
12 shopBoughtResalePrice,
13 shopChequeAdminFee,
14 resolveShopSellQuote,
15 shopRestockDayKey,
16 lerp
17 } from "../../shared/shop/pricing.js";
18import { ItemId, listAllItemPickerEntries } from "../../shared/definitions/items.js";
19import { CraftingItemId, tinderboxItemInstance } from "../../shared/definitions/craftingItems.js";
20import { MobId, normalizeSpawnerConfig, isHumanoidMob } from "../../shared/definitions/mobs.js";
21import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
22import { Component } from "../src/ecs/components.js";
23import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";
24import { ItemOriginKind } from "../../shared/items/origin.js";
25import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
26import { ensureShopRestocked, boughtStockKey } from "../src/shop/service.js";
27import { BlockType } from "../../shared/definitions/tiles.js";
28import { GatherOriginVerb, gatherOrigin } from "../../shared/items/origin.js";
29import { dyeItemInstance, DEFAULT_DYE_FILL, FlowerColorId } from "../../shared/definitions/dyes.js";
30
31function boughtQty (shop, itemId)
32{
33 const raw = shop?.boughtStock?.[itemId];
34 if (raw == null)
35 { return 0; }
36 if (typeof raw === "number")
37 { return raw | 0; }
38 return raw.quantity | 0 || 0;
39}
40
41test("listAllItemPickerEntries includes paper and bronze gather tools", () =>
42{
43 const ids = new Set(listAllItemPickerEntries().map((entry) => entry.itemId));
44 assert.ok(ids.has(ItemId.paper));
45 assert.ok(ids.has(CraftingItemId.bronzeAxe));
46 assert.ok(ids.has(CraftingItemId.bronzePickaxe));
47 assert.equal(canSellInNpcShop(ItemId.paper), false);
48 assert.equal(canSellInNpcShop(CraftingItemId.bronzeAxe), false);
49});
50
51test("buy paper from a shopkeeper with explicit catalog", () =>
52{
53 const harness = makeSimulation({ workerCount: 1 });
54 try
55 {
56 const data = createEmptyChunkData();
57 data.open = true;
58 data.spawners = [{
59 localX: 9,
60 localY: 8,
61 config: {
62 mobTypeId: MobId.humanoid,
63 maxAlive: 1,
64 spawnRangeTiles: 1,
65 maxWanderRangeTiles: 1,
66 sex: "male",
67 displayName: "Stationer",
68 sells: [{ itemId: ItemId.paper, quantity: 0 }],
69 hiddenDiscount: 1,
70 equipment: { chest: ItemId.clothShirt }
71 }
72 }];
73 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
74 harness.simulation.reloadWorld();
75
76 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
77 const funded = addCoinsToSlots(emptySlots(), 20);
78 assert.equal(funded.ok, true);
79 harness.stateDb.saveBag(character.character_id, {
80 inventory: funded.slots,
81 equipment: emptyEquipment(),
82 vault: [],
83 vaultReserved: []
84 });
85 const playerId = harness.simulation.spawnCharacter(1, character);
86 harness.simulation.step();
87 harness.advance(50);
88 harness.simulation.step();
89
90 const record = harness.simulation.entityRecord(playerId);
91 const worker = harness.simulation.workers[record.workerId];
92 let npcId = null;
93 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
94 {
95 if (entity.creature.mobTypeId === MobId.humanoid)
96 {
97 npcId = entity.entityId;
98 break;
99 }
100 }
101 assert.ok(npcId, "expected a humanoid shopkeeper");
102
103 const npcHandle = worker.world.ecs.handleOf(npcId);
104 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
105 const playerHandle = worker.world.ecs.handleOf(playerId);
106 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
107 playerPos.tileX = npcPos.tileX - 1;
108 playerPos.tileY = npcPos.tileY;
109
110 harness.simulation.enqueue(1, {
111 type: "interact",
112 characterId: character.character_id,
113 targetEntityId: npcId
114 });
115 const open = harness.simulation.step();
116 const shopOpen = open.events.find((event) => event.type === "shop-open");
117 assert.ok(shopOpen, JSON.stringify(open.events));
118 assert.ok(shopOpen.stock.some((row) => row.itemId === ItemId.paper));
119
120 harness.simulation.enqueue(1, {
121 type: "buy-from-shop",
122 characterId: character.character_id,
123 npcEntityId: npcId,
124 itemId: ItemId.paper,
125 quantity: 1,
126 listingId: `stock:${ItemId.paper}`
127 });
128 const buy = harness.simulation.step();
129 assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));
130 const bag = harness.simulation.bagOf(playerId);
131 const paper = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.paper);
132 assert.ok(paper, JSON.stringify(bag.inventory));
133 }
134 finally
135 { harness.close(); }
136});
137
138test("shop prices fall back to seedValue and apply hidden discount", () =>
139{
140 assert.equal(undiscountedMarketValue(ItemId.copperOre), 5);
141 assert.equal(undiscountedMarketValue(ItemId.tinOre), 5);
142 assert.equal(undiscountedMarketValue(ItemId.pineLog), 5);
143 assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.9 }), 5);
144 assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.5 }), 3);
145 assert.equal(shopBuyFromPlayerPrice(ItemId.copperOre), 3);
146 assert.equal(shopBoughtResalePrice(ItemId.copperOre), 6);
147 assert.equal(lerp(10, 20, 0.5), 15);
148 assert.equal(canSellInNpcShop(ItemId.copperOre), true);
149 assert.equal(canSellInNpcShop(ItemId.tinOre), true);
150 assert.equal(canSellInNpcShop(ItemId.stick), false);
151 assert.equal(canPlayerSellToNpc({ itemId: ItemId.copperOre, quantity: 1 }), true);
152 assert.equal(canPlayerSellToNpc({ itemId: ItemId.stick, quantity: 1 }), true);
153 assert.equal(canPlayerSellToNpc({ itemId: ItemId.blankCheque, quantity: 1 }), false);
154 assert.equal(canPlayerSellToNpc({ itemId: ItemId.coins, quantity: 10 }), false);
155 assert.equal(canPlayerSellToNpc({
156 itemId: ItemId.recipePaper,
157 quantity: 1,
158 instance: { kind: "recipe-paper", recipeId: "lesser-health-tonic" }
159 }), false);
160 assert.equal(canPlayerSellToNpc({
161 itemId: ItemId.filledCheque,
162 quantity: 1,
163 instance: { kind: "filled-cheque", itemId: ItemId.copperOre, quantity: 3 }
164 }), true);
165 assert.equal(shopChequeAdminFee(100), 5);
166 assert.equal(shopChequeAdminFee(10), 1);
167 assert.equal(shopChequeAdminFee(1), 1);
168 const chequeQuote = resolveShopSellQuote({
169 itemId: ItemId.filledCheque,
170 quantity: 1,
171 instance: { kind: "filled-cheque", itemId: ItemId.copperOre, quantity: 2 }
172 });
173 assert.equal(chequeQuote.baseTotal, shopBuyFromPlayerPrice(ItemId.copperOre) * 2);
174 assert.equal(chequeQuote.adminFee, shopChequeAdminFee(chequeQuote.baseTotal));
175 assert.equal(chequeQuote.payout, chequeQuote.baseTotal - chequeQuote.adminFee);
176});
177
178test("charge-worn tools scale merchant buy and resale prices by remaining uses", () =>
179{
180 const full = {
181 itemId: CraftingItemId.tinderbox,
182 quantity: 1,
183 instance: tinderboxItemInstance(6)
184 };
185 const worn = {
186 itemId: CraftingItemId.tinderbox,
187 quantity: 1,
188 instance: tinderboxItemInstance(1)
189 };
190 const fullBuy = shopBuyFromPlayerPrice(CraftingItemId.tinderbox, { stack: full });
191 const wornBuy = shopBuyFromPlayerPrice(CraftingItemId.tinderbox, { stack: worn });
192 assert.equal(fullBuy, shopBuyFromPlayerPrice(CraftingItemId.tinderbox));
193 assert.equal(wornBuy, marketValueAsCoins(
194 undiscountedMarketValue(CraftingItemId.tinderbox) * 0.5 * (1 / 6)
195 ));
196 const fullResale = shopBoughtResalePrice(CraftingItemId.tinderbox, { stack: full });
197 const wornResale = shopBoughtResalePrice(CraftingItemId.tinderbox, { stack: worn });
198 assert.equal(fullResale, shopBoughtResalePrice(CraftingItemId.tinderbox));
199 assert.equal(wornResale, marketValueAsCoins(
200 undiscountedMarketValue(CraftingItemId.tinderbox) * 1.2 * (1 / 6)
201 ));
202 const quote = resolveShopSellQuote(worn);
203 assert.equal(quote.unitPrice, wornBuy);
204});
205
206test("market value display and shop use ceil fractional lerps", () =>
207{
208 const now = 1_000_000;
209 const lastSale = {
210 lastTradePrice: 10,
211 lastTradeAt: now - 500,
212 priceFrom: 5
213 };
214 // Halfway from 5 → 10 over 1000ms → 7.5 internally.
215 const raw = undiscountedMarketValue(ItemId.copperOre, lastSale, now, 1000);
216 assert.equal(raw, 7.5);
217 assert.equal(marketValueAsCoins(raw), 8);
218 assert.equal(undiscountedMarketCoins(ItemId.copperOre, lastSale, now, 1000), 8);
219 assert.equal(shopBuyFromPlayerPrice(ItemId.copperOre, { lastSale, now, lerpDurationMs: 1000 }), 4);
220 assert.equal(shopBoughtResalePrice(ItemId.copperOre, { lastSale, now, lerpDurationMs: 1000 }), 9);
221 assert.equal(shopUnitPrice(ItemId.copperOre, {
222 lastSale,
223 now,
224 lerpDurationMs: 1000,
225 hiddenDiscount: 1
226 }), 8);
227});
228
229test("humanoid spawner config keeps sex equipment sells quantities and buysItems", () =>
230{
231 assert.equal(isHumanoidMob(MobId.humanoid), true);
232 const config = normalizeSpawnerConfig({
233 mobTypeId: MobId.humanoid,
234 sex: "female",
235 displayName: "Ore trader",
236 equipment: { chest: ItemId.clothShirt, weapon: ItemId.stick },
237 sells: [
238 { itemId: ItemId.copperOre, quantity: 10 },
239 { itemId: ItemId.tinOre, quantity: 0 },
240 ItemId.copperOre
241 ],
242 buysItems: true,
243 hiddenDiscount: 0.85
244 }, "shop-1");
245 assert.equal(config.sex, "female");
246 assert.equal(config.displayName, "Ore trader");
247 assert.equal(config.equipment.chest, ItemId.clothShirt);
248 assert.deepEqual(config.sells, [
249 { itemId: ItemId.copperOre, quantity: 10 },
250 { itemId: ItemId.tinOre, quantity: 0 }
251 ]);
252 assert.equal(config.buysItems, true);
253 assert.equal(config.hiddenDiscount, 0.85);
254 assert.equal(config.maxAlive, 1);
255});
256
257test("shopkeeper with buysItems accepts paper from the player", () =>
258{
259 const harness = makeSimulation({ workerCount: 1 });
260 try
261 {
262 const data = createEmptyChunkData();
263 data.open = true;
264 data.spawners = [{
265 localX: 9,
266 localY: 8,
267 config: {
268 mobTypeId: MobId.humanoid,
269 maxAlive: 1,
270 spawnRangeTiles: 0,
271 maxWanderRangeTiles: 0,
272 displayName: "Stationer",
273 buysItems: true
274 }
275 }];
276 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
277 harness.simulation.reloadWorld();
278
279 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
280 const slots = emptySlots(INVENTORY_SLOTS);
281 slots[0] = { itemId: ItemId.paper, quantity: 3 };
282 harness.stateDb.saveBag(character.character_id, {
283 inventory: slots,
284 equipment: emptyEquipment(),
285 vault: [],
286 vaultReserved: []
287 });
288 const playerId = harness.simulation.spawnCharacter(1, character);
289 harness.simulation.step();
290 harness.advance(50);
291 harness.simulation.step();
292
293 const record = harness.simulation.entityRecord(playerId);
294 const worker = harness.simulation.workers[record.workerId];
295 let npcId = null;
296 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
297 {
298 if (entity.creature.mobTypeId === MobId.humanoid)
299 {
300 npcId = entity.entityId;
301 break;
302 }
303 }
304 assert.ok(npcId);
305 const npcHandle = worker.world.ecs.handleOf(npcId);
306 const shop = worker.world.ecs.get(npcHandle, Component.shop);
307 assert.equal(shop.buysItems, true);
308 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
309 const playerHandle = worker.world.ecs.handleOf(playerId);
310 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
311 playerPos.tileX = npcPos.tileX - 1;
312 playerPos.tileY = npcPos.tileY;
313
314 const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
315 harness.simulation.enqueue(1, {
316 type: "sell-to-shop",
317 characterId: character.character_id,
318 npcEntityId: npcId,
319 slotIndex: 0,
320 quantity: 1
321 });
322 const sold = harness.simulation.step();
323 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
324 const inv = worker.world.ecs.get(playerHandle, Component.inventory);
325 assert.equal(inv.slots[0]?.quantity, 2);
326 assert.ok(countCoinsInSlots(inv.slots) >= beforeCoins + shopBuyFromPlayerPrice(ItemId.paper));
327 }
328 finally
329 { harness.close(); }
330});
331
332test("humanoid spawner equipment can store clothing dye color", () =>
333{
334 const dyeColor = { r: 0.2, g: 0.4, b: 0.8 };
335 const config = normalizeSpawnerConfig({
336 mobTypeId: MobId.humanoid,
337 equipment: {
338 chest: { itemId: ItemId.clothShirt, dyeColor },
339 weapon: ItemId.stick
340 }
341 }, "shop-dye");
342 assert.deepEqual(config.equipment.chest, {
343 itemId: ItemId.clothShirt,
344 dyeColor
345 });
346 assert.equal(config.equipment.weapon, ItemId.stick);
347});
348
349test("buy copper ore from a spawned shopkeeper", () =>
350{
351 const harness = makeSimulation({ workerCount: 1 });
352 try
353 {
354 const data = createEmptyChunkData();
355 data.open = true;
356 data.spawners = [{
357 localX: 9,
358 localY: 8,
359 config: {
360 mobTypeId: MobId.humanoid,
361 maxAlive: 1,
362 spawnRangeTiles: 1,
363 maxWanderRangeTiles: 1,
364 sex: "male",
365 displayName: "Ore trader",
366 sells: [
367 { itemId: ItemId.copperOre, quantity: 0 },
368 { itemId: ItemId.tinOre, quantity: 0 }
369 ],
370 hiddenDiscount: 1,
371 equipment: { chest: ItemId.clothShirt }
372 }
373 }];
374 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
375 harness.simulation.reloadWorld();
376
377 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
378 const funded = addCoinsToSlots(emptySlots(), 50);
379 assert.equal(funded.ok, true);
380 harness.stateDb.saveBag(character.character_id, {
381 inventory: funded.slots,
382 equipment: emptyEquipment(),
383 vault: [],
384 vaultReserved: []
385 });
386 const playerId = harness.simulation.spawnCharacter(1, character);
387 harness.simulation.step();
388 harness.advance(50);
389 harness.simulation.step();
390
391 const record = harness.simulation.entityRecord(playerId);
392 const worker = harness.simulation.workers[record.workerId];
393 let npcId = null;
394 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
395 {
396 if (entity.creature.mobTypeId === MobId.humanoid)
397 {
398 npcId = entity.entityId;
399 break;
400 }
401 }
402 assert.ok(npcId, "expected a humanoid shopkeeper");
403
404 const npcHandle = worker.world.ecs.handleOf(npcId);
405 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
406 const playerHandle = worker.world.ecs.handleOf(playerId);
407 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
408 playerPos.tileX = npcPos.tileX - 1;
409 playerPos.tileY = npcPos.tileY;
410
411 harness.simulation.enqueue(1, {
412 type: "interact",
413 characterId: character.character_id,
414 targetEntityId: npcId
415 });
416 const open = harness.simulation.step();
417 const shopOpen = open.events.find((event) => event.type === "shop-open");
418 assert.ok(shopOpen, JSON.stringify(open.events));
419 assert.ok(shopOpen.stock.some((row) => row.itemId === ItemId.copperOre));
420
421 harness.simulation.enqueue(1, {
422 type: "buy-from-shop",
423 characterId: character.character_id,
424 npcEntityId: npcId,
425 itemId: ItemId.copperOre,
426 quantity: 1,
427 listingId: `stock:${ItemId.copperOre}`
428 });
429 const buy = harness.simulation.step();
430 assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));
431 const bag = harness.simulation.bagOf(playerId);
432 const ore = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.copperOre);
433 assert.ok(ore, JSON.stringify(bag.inventory));
434 assert.equal(ore.origins?.[0]?.origin?.kind, ItemOriginKind.shop);
435 assert.equal(ore.origins?.[0]?.origin?.displayName, "Ore trader");
436 }
437 finally
438 { harness.close(); }
439});
440
441test("limited shop stock depletes and restocks on a new day", () =>
442{
443 const shop = {
444 catalog: [{ itemId: ItemId.copperOre, quantity: 2 }],
445 buysItems: false,
446 hiddenDiscount: 1,
447 remaining: Object.create(null),
448 boughtStock: Object.create(null),
449 restockDay: null
450 };
451 const dayA = new Date(2026, 7, 25, 12, 0, 0, 0).getTime();
452 ensureShopRestocked(shop, dayA);
453 assert.equal(shop.restockDay, shopRestockDayKey(dayA));
454 assert.equal(shop.remaining[ItemId.copperOre], 2);
455 shop.remaining[ItemId.copperOre] = 0;
456 shop.boughtStock[ItemId.tinOre] = 3;
457 ensureShopRestocked(shop, dayA);
458 assert.equal(shop.remaining[ItemId.copperOre], 0);
459 assert.equal(shop.boughtStock[ItemId.tinOre], 3);
460 const dayB = new Date(2026, 7, 26, 0, 0, 1, 0).getTime();
461 ensureShopRestocked(shop, dayB);
462 assert.equal(shop.remaining[ItemId.copperOre], 2);
463 assert.equal(shop.boughtStock[ItemId.tinOre], undefined);
464});
465
466test("shop overflow goes to bank vault when inventory is full", () =>
467{
468 const harness = makeSimulation({ workerCount: 1 });
469 try
470 {
471 const data = createEmptyChunkData();
472 data.open = true;
473 data.spawners = [{
474 localX: 9,
475 localY: 8,
476 config: {
477 mobTypeId: MobId.humanoid,
478 maxAlive: 1,
479 spawnRangeTiles: 0,
480 maxWanderRangeTiles: 0,
481 displayName: "Ore trader",
482 sells: [{ itemId: ItemId.copperOre, quantity: 0 }],
483 hiddenDiscount: 1
484 }
485 }];
486 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
487 harness.simulation.reloadWorld();
488
489 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
490 const slots = emptySlots();
491 const funded = addCoinsToSlots(slots, 50);
492 assert.equal(funded.ok, true);
493 for (let i = 0; i < funded.slots.length; i++)
494 {
495 if (!funded.slots[i])
496 { funded.slots[i] = { itemId: ItemId.stick, quantity: 1 }; }
497 }
498 harness.stateDb.saveBag(character.character_id, {
499 inventory: funded.slots,
500 equipment: emptyEquipment(),
501 vault: [],
502 vaultReserved: []
503 });
504 const playerId = harness.simulation.spawnCharacter(1, character);
505 harness.simulation.step();
506 harness.advance(50);
507 harness.simulation.step();
508
509 const record = harness.simulation.entityRecord(playerId);
510 const worker = harness.simulation.workers[record.workerId];
511 let npcId = null;
512 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
513 {
514 if (entity.creature.mobTypeId === MobId.humanoid)
515 {
516 npcId = entity.entityId;
517 break;
518 }
519 }
520 assert.ok(npcId);
521 const npcHandle = worker.world.ecs.handleOf(npcId);
522 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
523 const playerHandle = worker.world.ecs.handleOf(playerId);
524 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
525 playerPos.tileX = npcPos.tileX - 1;
526 playerPos.tileY = npcPos.tileY;
527
528 harness.simulation.enqueue(1, {
529 type: "buy-from-shop",
530 characterId: character.character_id,
531 npcEntityId: npcId,
532 itemId: ItemId.copperOre,
533 quantity: 1,
534 listingId: `stock:${ItemId.copperOre}`
535 });
536 const buy = harness.simulation.step();
537 assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));
538 const bag = harness.simulation.bagOf(playerId);
539 assert.equal((bag.inventory ?? []).some((slot) => slot?.itemId === ItemId.copperOre), false);
540 assert.ok((bag.vault ?? []).some((slot) => slot?.itemId === ItemId.copperOre));
541 }
542 finally
543 { harness.close(); }
544});
545
546test("buysItems refills limited catalog then stores extras for 120% resale", () =>
547{
548 const harness = makeSimulation({ workerCount: 1 });
549 try
550 {
551 const data = createEmptyChunkData();
552 data.open = true;
553 data.spawners = [{
554 localX: 9,
555 localY: 8,
556 config: {
557 mobTypeId: MobId.humanoid,
558 maxAlive: 1,
559 spawnRangeTiles: 0,
560 maxWanderRangeTiles: 0,
561 displayName: "Buyer",
562 sells: [{ itemId: ItemId.copperOre, quantity: 2 }],
563 buysItems: true,
564 hiddenDiscount: 1
565 }
566 }];
567 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
568 harness.simulation.reloadWorld();
569
570 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
571 harness.stateDb.saveBag(character.character_id, {
572 inventory: emptySlots(INVENTORY_SLOTS),
573 equipment: emptyEquipment(),
574 vault: [],
575 vaultReserved: []
576 });
577 const playerId = harness.simulation.spawnCharacter(1, character);
578 harness.simulation.step();
579 harness.advance(50);
580 harness.simulation.step();
581
582 const record = harness.simulation.entityRecord(playerId);
583 const worker = harness.simulation.workers[record.workerId];
584 let npcId = null;
585 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
586 {
587 if (entity.creature.mobTypeId === MobId.humanoid)
588 {
589 npcId = entity.entityId;
590 break;
591 }
592 }
593 assert.ok(npcId);
594 const npcHandle = worker.world.ecs.handleOf(npcId);
595 const shop = worker.world.ecs.get(npcHandle, Component.shop);
596 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
597 const playerHandle = worker.world.ecs.handleOf(playerId);
598 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
599 playerPos.tileX = npcPos.tileX - 1;
600 playerPos.tileY = npcPos.tileY;
601
602 // Fund coins and buy out limited stock first.
603 const inv = worker.world.ecs.get(playerHandle, Component.inventory);
604 const funded = addCoinsToSlots(inv.slots, 50);
605 assert.equal(funded.ok, true);
606 inv.slots = funded.slots;
607 inv.slots[1] = { itemId: ItemId.copperOre, quantity: 5 };
608
609 harness.simulation.enqueue(1, {
610 type: "buy-from-shop",
611 characterId: character.character_id,
612 npcEntityId: npcId,
613 itemId: ItemId.copperOre,
614 quantity: 2,
615 listingId: `stock:${ItemId.copperOre}`
616 });
617 const boughtOut = harness.simulation.step();
618 assert.equal(boughtOut.events.some((event) => event.type === "command-error"), false, JSON.stringify(boughtOut.events));
619 assert.equal(shop.remaining[ItemId.copperOre], 0);
620
621 const oreSlot = inv.slots.findIndex((slot) => slot?.itemId === ItemId.copperOre && (slot.quantity | 0) >= 5);
622 assert.ok(oreSlot >= 0);
623
624 harness.simulation.enqueue(1, {
625 type: "sell-to-shop",
626 characterId: character.character_id,
627 npcEntityId: npcId,
628 slotIndex: oreSlot,
629 quantity: 5
630 });
631 const sold = harness.simulation.step();
632 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
633 assert.equal(shop.remaining[ItemId.copperOre], 2);
634 assert.equal(boughtQty(shop, ItemId.copperOre), 3);
635
636 const open = sold.events.find((event) => event.type === "shop-open");
637 assert.ok(open.stock.some((row) => row.source === "stock" && row.available === 2));
638 assert.ok(open.stock.some((row) => row.source === "bought" && row.available === 3));
639 }
640 finally
641 { harness.close(); }
642});
643
644test("shop adjacency errors use gendered pronouns", () =>
645{
646 const harness = makeSimulation({ workerCount: 1 });
647 try
648 {
649 const data = createEmptyChunkData();
650 data.open = true;
651 data.spawners = [{
652 localX: 9,
653 localY: 8,
654 config: {
655 mobTypeId: MobId.humanoid,
656 maxAlive: 1,
657 spawnRangeTiles: 0,
658 maxWanderRangeTiles: 0,
659 sex: "female",
660 displayName: "Trader",
661 sells: [{ itemId: ItemId.copperOre, quantity: 0 }],
662 hiddenDiscount: 1
663 }
664 }];
665 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
666 harness.simulation.reloadWorld();
667
668 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 2 });
669 harness.stateDb.saveBag(character.character_id, {
670 inventory: emptySlots(INVENTORY_SLOTS),
671 equipment: emptyEquipment(),
672 vault: [],
673 vaultReserved: []
674 });
675 const playerId = harness.simulation.spawnCharacter(1, character);
676 harness.simulation.step();
677 harness.advance(50);
678 harness.simulation.step();
679
680 const record = harness.simulation.entityRecord(playerId);
681 const worker = harness.simulation.workers[record.workerId];
682 let npcId = null;
683 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
684 {
685 if (entity.creature.mobTypeId === MobId.humanoid)
686 {
687 npcId = entity.entityId;
688 break;
689 }
690 }
691 assert.ok(npcId);
692
693 harness.simulation.enqueue(1, {
694 type: "interact",
695 characterId: character.character_id,
696 targetEntityId: npcId
697 });
698 const open = harness.simulation.step();
699 const err = open.events.find((event) => event.type === "command-error");
700 assert.ok(err, JSON.stringify(open.events));
701 assert.match(err.message, /stand next to her/i);
702 assert.doesNotMatch(err.message, /\bthem\b/i);
703 }
704 finally
705 { harness.close(); }
706});
707
708test("shopkeeper stops wandering while a player has the shop open", () =>
709{
710 const harness = makeSimulation({ workerCount: 1 });
711 try
712 {
713 const data = createEmptyChunkData();
714 data.open = true;
715 data.spawners = [{
716 localX: 8,
717 localY: 8,
718 config: {
719 mobTypeId: MobId.humanoid,
720 maxAlive: 1,
721 spawnRangeTiles: 4,
722 maxWanderRangeTiles: 8,
723 sex: "male",
724 displayName: "Stay put",
725 sells: [{ itemId: ItemId.copperOre, quantity: 0 }],
726 hiddenDiscount: 1
727 }
728 }];
729 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
730 harness.simulation.reloadWorld();
731
732 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
733 harness.stateDb.saveBag(character.character_id, {
734 inventory: emptySlots(INVENTORY_SLOTS),
735 equipment: emptyEquipment(),
736 vault: [],
737 vaultReserved: []
738 });
739 const playerId = harness.simulation.spawnCharacter(1, character);
740 harness.simulation.step();
741 harness.advance(50);
742 harness.simulation.step();
743
744 const record = harness.simulation.entityRecord(playerId);
745 const worker = harness.simulation.workers[record.workerId];
746 let npc = null;
747 for (const entity of worker.world.ecs.query(Component.shop, Component.creature, Component.position, Component.path))
748 {
749 if (entity.creature.mobTypeId === MobId.humanoid)
750 {
751 npc = entity;
752 break;
753 }
754 }
755 assert.ok(npc);
756
757 const npcStartX = npc.position.tileX;
758 const npcStartY = npc.position.tileY;
759 const playerHandle = worker.world.ecs.handleOf(playerId);
760 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
761 playerPos.tileX = npcStartX - 1;
762 playerPos.tileY = npcStartY;
763
764 harness.simulation.enqueue(1, {
765 type: "interact",
766 characterId: character.character_id,
767 targetEntityId: npc.entityId
768 });
769 const open = harness.simulation.step();
770 assert.ok(open.events.some((event) => event.type === "shop-open"));
771 assert.equal(!!npc.shop.browsers?.[character.character_id], true);
772
773 npc.path.tiles = [{ x: npc.position.tileX + 1, y: npc.position.tileY }];
774 for (let i = 0; i < 20; i++)
775 { harness.simulation.step(); }
776 assert.equal(npc.path.tiles.length, 0);
777 assert.equal(npc.position.tileX, npcStartX);
778 assert.equal(npc.position.tileY, npcStartY);
779
780 harness.simulation.enqueue(1, {
781 type: "close-shop",
782 characterId: character.character_id,
783 npcEntityId: npc.entityId
784 });
785 harness.simulation.step();
786 assert.equal(!!npc.shop.browsers?.[character.character_id], false);
787 }
788 finally
789 { harness.close(); }
790});
791
792test("buysItems accepts non-ingredient tools like sticks", () =>
793{
794 const harness = makeSimulation({ workerCount: 1 });
795 try
796 {
797 const data = createEmptyChunkData();
798 data.open = true;
799 data.spawners = [{
800 localX: 9,
801 localY: 8,
802 config: {
803 mobTypeId: MobId.humanoid,
804 maxAlive: 1,
805 spawnRangeTiles: 0,
806 maxWanderRangeTiles: 0,
807 displayName: "Buyer",
808 buysItems: true,
809 hiddenDiscount: 1
810 }
811 }];
812 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
813 harness.simulation.reloadWorld();
814
815 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
816 const slots = emptySlots(INVENTORY_SLOTS);
817 slots[0] = { itemId: ItemId.stick, quantity: 1 };
818 harness.stateDb.saveBag(character.character_id, {
819 inventory: slots,
820 equipment: emptyEquipment(),
821 vault: [],
822 vaultReserved: []
823 });
824 const playerId = harness.simulation.spawnCharacter(1, character);
825 harness.simulation.step();
826 harness.advance(50);
827 harness.simulation.step();
828
829 const record = harness.simulation.entityRecord(playerId);
830 const worker = harness.simulation.workers[record.workerId];
831 let npcId = null;
832 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
833 {
834 if (entity.creature.mobTypeId === MobId.humanoid)
835 {
836 npcId = entity.entityId;
837 break;
838 }
839 }
840 assert.ok(npcId);
841 const npcHandle = worker.world.ecs.handleOf(npcId);
842 const shop = worker.world.ecs.get(npcHandle, Component.shop);
843 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
844 const playerHandle = worker.world.ecs.handleOf(playerId);
845 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
846 playerPos.tileX = npcPos.tileX - 1;
847 playerPos.tileY = npcPos.tileY;
848
849 const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
850 harness.simulation.enqueue(1, {
851 type: "sell-to-shop",
852 characterId: character.character_id,
853 npcEntityId: npcId,
854 slotIndex: 0,
855 quantity: 1
856 });
857 const sold = harness.simulation.step();
858 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
859 const inv = worker.world.ecs.get(playerHandle, Component.inventory);
860 assert.equal(inv.slots[0]?.itemId === ItemId.stick, false);
861 assert.ok(countCoinsInSlots(inv.slots) >= beforeCoins + shopBuyFromPlayerPrice(ItemId.stick));
862 assert.equal(boughtQty(shop, ItemId.stick), 1);
863 }
864 finally
865 { harness.close(); }
866});
867
868test("selling a filled cheque pays reserved-goods price minus 5% admin fee", () =>
869{
870 const harness = makeSimulation({ workerCount: 1 });
871 try
872 {
873 const data = createEmptyChunkData();
874 data.open = true;
875 data.blocks[8 * 16 + 8] = { typeId: BlockType.bank, state: 0 };
876 data.spawners = [{
877 localX: 9,
878 localY: 8,
879 config: {
880 mobTypeId: MobId.humanoid,
881 maxAlive: 1,
882 spawnRangeTiles: 0,
883 maxWanderRangeTiles: 0,
884 displayName: "Buyer",
885 sells: [{ itemId: ItemId.copperOre, quantity: 0 }],
886 buysItems: true,
887 hiddenDiscount: 1
888 }
889 }];
890 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
891 harness.simulation.reloadWorld();
892
893 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
894 const slots = emptySlots(INVENTORY_SLOTS);
895 slots[0] = { itemId: ItemId.copperOre, quantity: 2 };
896 harness.stateDb.saveBag(character.character_id, {
897 inventory: slots,
898 equipment: emptyEquipment(),
899 vault: [],
900 vaultReserved: []
901 });
902 const playerId = harness.simulation.spawnCharacter(1, character);
903 harness.simulation.step();
904
905 harness.simulation.enqueue(1, {
906 type: "get-blank-cheques",
907 characterId: character.character_id
908 });
909 harness.simulation.step();
910 harness.simulation.enqueue(1, {
911 type: "bank-deposit",
912 characterId: character.character_id,
913 slotIndex: 0,
914 quantity: null
915 });
916 harness.simulation.step();
917 let bag = harness.simulation.bagOf(playerId);
918 const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
919 const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.copperOre);
920 harness.simulation.enqueue(1, {
921 type: "write-cheque",
922 characterId: character.character_id,
923 slotIndex: blankIndex,
924 vaultSlotIndex: vaultIndex,
925 quantity: 2
926 });
927 harness.simulation.step();
928 bag = harness.simulation.bagOf(playerId);
929 const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
930 assert.ok(chequeIndex >= 0);
931
932 const record = harness.simulation.entityRecord(playerId);
933 const worker = harness.simulation.workers[record.workerId];
934 let npcId = null;
935 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
936 {
937 if (entity.creature.mobTypeId === MobId.humanoid)
938 {
939 npcId = entity.entityId;
940 break;
941 }
942 }
943 assert.ok(npcId);
944 const npcHandle = worker.world.ecs.handleOf(npcId);
945 const shop = worker.world.ecs.get(npcHandle, Component.shop);
946 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
947 const playerHandle = worker.world.ecs.handleOf(playerId);
948 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
949 playerPos.tileX = npcPos.tileX - 1;
950 playerPos.tileY = npcPos.tileY;
951
952 const quote = resolveShopSellQuote(bag.inventory[chequeIndex]);
953 assert.ok(quote?.isCheque);
954 const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
955 harness.simulation.enqueue(1, {
956 type: "sell-to-shop",
957 characterId: character.character_id,
958 npcEntityId: npcId,
959 slotIndex: chequeIndex,
960 quantity: 1
961 });
962 const sold = harness.simulation.step();
963 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
964 bag = harness.simulation.bagOf(playerId);
965 assert.equal(bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque), -1);
966 assert.equal((bag.vaultReserved ?? []).length, 0);
967 const afterCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
968 assert.equal(afterCoins - beforeCoins, quote.payout);
969 // Infinite catalog absorbs goods without bought-from-player resale stock.
970 assert.equal(boughtQty(shop, ItemId.copperOre), 0);
971 }
972 finally
973 { harness.close(); }
974});
975
976test("resale stock keeps the seller origin instead of Bought from NPC", () =>
977{
978 const harness = makeSimulation({ workerCount: 1 });
979 try
980 {
981 const data = createEmptyChunkData();
982 data.open = true;
983 data.spawners = [{
984 localX: 9,
985 localY: 8,
986 config: {
987 mobTypeId: MobId.humanoid,
988 maxAlive: 1,
989 spawnRangeTiles: 0,
990 maxWanderRangeTiles: 0,
991 displayName: "Fence",
992 sells: [],
993 buysItems: true,
994 hiddenDiscount: 1
995 }
996 }];
997 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
998 harness.simulation.reloadWorld();
999
1000 const minerOrigin = gatherOrigin(GatherOriginVerb.mined, "Ada Miner");
1001 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1002 const funded = addCoinsToSlots(emptySlots(), 50);
1003 assert.equal(funded.ok, true);
1004 funded.slots[1] = {
1005 itemId: ItemId.copperOre,
1006 quantity: 2,
1007 origins: [{ origin: minerOrigin, quantity: 2 }]
1008 };
1009 harness.stateDb.saveBag(character.character_id, {
1010 inventory: funded.slots,
1011 equipment: emptyEquipment(),
1012 vault: [],
1013 vaultReserved: []
1014 });
1015 const playerId = harness.simulation.spawnCharacter(1, character);
1016 harness.simulation.step();
1017 harness.advance(50);
1018 harness.simulation.step();
1019
1020 const record = harness.simulation.entityRecord(playerId);
1021 const worker = harness.simulation.workers[record.workerId];
1022 let npcId = null;
1023 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
1024 {
1025 if (entity.creature.mobTypeId === MobId.humanoid)
1026 {
1027 npcId = entity.entityId;
1028 break;
1029 }
1030 }
1031 assert.ok(npcId);
1032 const npcHandle = worker.world.ecs.handleOf(npcId);
1033 const shop = worker.world.ecs.get(npcHandle, Component.shop);
1034 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
1035 const playerHandle = worker.world.ecs.handleOf(playerId);
1036 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
1037 playerPos.tileX = npcPos.tileX - 1;
1038 playerPos.tileY = npcPos.tileY;
1039
1040 harness.simulation.enqueue(1, {
1041 type: "sell-to-shop",
1042 characterId: character.character_id,
1043 npcEntityId: npcId,
1044 slotIndex: 1,
1045 quantity: 2
1046 });
1047 const sold = harness.simulation.step();
1048 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
1049 assert.equal(boughtQty(shop, ItemId.copperOre), 2);
1050 assert.deepEqual(shop.boughtStock[ItemId.copperOre].origins, [
1051 { origin: minerOrigin, quantity: 2 }
1052 ]);
1053
1054 harness.simulation.enqueue(1, {
1055 type: "buy-from-shop",
1056 characterId: character.character_id,
1057 npcEntityId: npcId,
1058 itemId: ItemId.copperOre,
1059 quantity: 2,
1060 listingId: `bought:${ItemId.copperOre}`,
1061 source: "bought"
1062 });
1063 const buy = harness.simulation.step();
1064 assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));
1065 const bag = harness.simulation.bagOf(playerId);
1066 const ore = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.copperOre);
1067 assert.ok(ore);
1068 assert.equal(ore.origins?.[0]?.origin?.kind, ItemOriginKind.gathered);
1069 assert.equal(ore.origins?.[0]?.origin?.displayName, "Ada Miner");
1070 assert.equal(ore.origins?.[0]?.origin?.kind === ItemOriginKind.shop, false);
1071 }
1072 finally
1073 { harness.close(); }
1074});
1075
1076test("NPC letter sales pay out and destroy the letter without stock", () =>
1077{
1078 const harness = makeSimulation({ workerCount: 1 });
1079 try
1080 {
1081 const data = createEmptyChunkData();
1082 data.open = true;
1083 data.spawners = [{
1084 localX: 9,
1085 localY: 8,
1086 config: {
1087 mobTypeId: MobId.humanoid,
1088 maxAlive: 1,
1089 spawnRangeTiles: 0,
1090 maxWanderRangeTiles: 0,
1091 displayName: "Fence",
1092 sells: [],
1093 buysItems: true,
1094 hiddenDiscount: 1
1095 }
1096 }];
1097 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
1098 harness.simulation.reloadWorld();
1099
1100 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1101 const funded = addCoinsToSlots(emptySlots(), 10);
1102 assert.equal(funded.ok, true);
1103 funded.slots[1] = {
1104 itemId: ItemId.letter,
1105 quantity: 1,
1106 instance: {
1107 kind: "letter",
1108 letterId: "sell-me",
1109 authorCharacterId: character.character_id,
1110 authorDisplayName: "Ada",
1111 body: "For sale",
1112 opened: true,
1113 writtenAt: Date.now()
1114 }
1115 };
1116 harness.stateDb.saveBag(character.character_id, {
1117 inventory: funded.slots,
1118 equipment: emptyEquipment(),
1119 vault: [],
1120 vaultReserved: []
1121 });
1122 const playerId = harness.simulation.spawnCharacter(1, character);
1123 harness.simulation.step();
1124 harness.advance(50);
1125 harness.simulation.step();
1126
1127 const record = harness.simulation.entityRecord(playerId);
1128 const worker = harness.simulation.workers[record.workerId];
1129 let npcId = null;
1130 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
1131 {
1132 if (entity.creature.mobTypeId === MobId.humanoid)
1133 {
1134 npcId = entity.entityId;
1135 break;
1136 }
1137 }
1138 assert.ok(npcId);
1139 const npcHandle = worker.world.ecs.handleOf(npcId);
1140 const shop = worker.world.ecs.get(npcHandle, Component.shop);
1141 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
1142 const playerHandle = worker.world.ecs.handleOf(playerId);
1143 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
1144 playerPos.tileX = npcPos.tileX - 1;
1145 playerPos.tileY = npcPos.tileY;
1146
1147 const letterSlot = harness.simulation.bagOf(playerId).inventory
1148 .findIndex((slot) => slot?.itemId === ItemId.letter);
1149 assert.ok(letterSlot >= 0);
1150 const quote = resolveShopSellQuote(harness.simulation.bagOf(playerId).inventory[letterSlot]);
1151 assert.ok(quote);
1152 const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
1153
1154 harness.simulation.enqueue(1, {
1155 type: "sell-to-shop",
1156 characterId: character.character_id,
1157 npcEntityId: npcId,
1158 slotIndex: letterSlot,
1159 quantity: 1
1160 });
1161 const sold = harness.simulation.step();
1162 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
1163 const bag = harness.simulation.bagOf(playerId);
1164 assert.equal(bag.inventory.some((slot) => slot?.itemId === ItemId.letter), false);
1165 assert.equal(boughtQty(shop, ItemId.letter), 0);
1166 assert.equal(shop.boughtStock?.[ItemId.letter], undefined);
1167 const afterCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
1168 assert.equal(afterCoins - beforeCoins, quote.payout);
1169 }
1170 finally
1171 { harness.close(); }
1172});
1173
1174test("vendor bought dye stays split by colour and resells that colour", () =>
1175{
1176 const harness = makeSimulation({ workerCount: 1 });
1177 try
1178 {
1179 const data = createEmptyChunkData();
1180 data.open = true;
1181 data.spawners = [{
1182 localX: 9,
1183 localY: 8,
1184 config: {
1185 mobTypeId: MobId.humanoid,
1186 maxAlive: 1,
1187 spawnRangeTiles: 0,
1188 maxWanderRangeTiles: 0,
1189 displayName: "Dyer",
1190 sells: [],
1191 buysItems: true,
1192 hiddenDiscount: 1
1193 }
1194 }];
1195 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
1196 harness.simulation.reloadWorld();
1197
1198 const yellow = dyeItemInstance(
1199 { r: 240 / 255, g: 210 / 255, b: 40 / 255 },
1200 DEFAULT_DYE_FILL,
1201 FlowerColorId.yellow
1202 );
1203 const magenta = dyeItemInstance(
1204 { r: 220 / 255, g: 40 / 255, b: 180 / 255 },
1205 DEFAULT_DYE_FILL,
1206 FlowerColorId.magenta
1207 );
1208 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1209 const funded = addCoinsToSlots(emptySlots(), 200);
1210 assert.equal(funded.ok, true);
1211 funded.slots[1] = { itemId: ItemId.dye, quantity: 1, instance: structuredClone(yellow) };
1212 funded.slots[2] = { itemId: ItemId.dye, quantity: 1, instance: structuredClone(magenta) };
1213 harness.stateDb.saveBag(character.character_id, {
1214 inventory: funded.slots,
1215 equipment: emptyEquipment(),
1216 vault: [],
1217 vaultReserved: []
1218 });
1219 const playerId = harness.simulation.spawnCharacter(1, character);
1220 harness.simulation.step();
1221 harness.advance(50);
1222 harness.simulation.step();
1223
1224 const record = harness.simulation.entityRecord(playerId);
1225 const worker = harness.simulation.workers[record.workerId];
1226 let npcId = null;
1227 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
1228 {
1229 if (entity.creature.mobTypeId === MobId.humanoid)
1230 {
1231 npcId = entity.entityId;
1232 break;
1233 }
1234 }
1235 assert.ok(npcId);
1236 const npcHandle = worker.world.ecs.handleOf(npcId);
1237 const shop = worker.world.ecs.get(npcHandle, Component.shop);
1238 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
1239 const playerHandle = worker.world.ecs.handleOf(playerId);
1240 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
1241 playerPos.tileX = npcPos.tileX - 1;
1242 playerPos.tileY = npcPos.tileY;
1243
1244 for (const slotIndex of [1, 2])
1245 {
1246 harness.simulation.enqueue(1, {
1247 type: "sell-to-shop",
1248 characterId: character.character_id,
1249 npcEntityId: npcId,
1250 slotIndex,
1251 quantity: 1
1252 });
1253 const sold = harness.simulation.step();
1254 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
1255 }
1256
1257 const yellowKey = boughtStockKey(ItemId.dye, yellow);
1258 const magentaKey = boughtStockKey(ItemId.dye, magenta);
1259 assert.notEqual(yellowKey, magentaKey);
1260 assert.equal(shop.boughtStock[yellowKey]?.quantity, 1);
1261 assert.equal(shop.boughtStock[magentaKey]?.quantity, 1);
1262 assert.equal(shop.boughtStock[yellowKey]?.instance?.colorId, FlowerColorId.yellow);
1263 assert.equal(shop.boughtStock[magentaKey]?.instance?.colorId, FlowerColorId.magenta);
1264 assert.equal(shop.boughtStock[ItemId.dye], undefined);
1265
1266 harness.simulation.enqueue(1, {
1267 type: "buy-from-shop",
1268 characterId: character.character_id,
1269 npcEntityId: npcId,
1270 itemId: ItemId.dye,
1271 quantity: 1,
1272 listingId: `bought:${magentaKey}`,
1273 source: "bought"
1274 });
1275 const bought = harness.simulation.step();
1276 assert.equal(bought.events.some((event) => event.type === "command-error"), false, JSON.stringify(bought.events));
1277 const bag = harness.simulation.bagOf(playerId);
1278 const dye = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.dye);
1279 assert.ok(dye);
1280 assert.equal(dye.instance?.colorId, FlowerColorId.magenta);
1281 assert.equal(shop.boughtStock[magentaKey], undefined);
1282 assert.equal(shop.boughtStock[yellowKey]?.quantity, 1);
1283 }
1284 finally
1285 { harness.close(); }
1286});