Fix dye confirm, vendor dye colour lots, and shop buy/sell panes.
Forward cauldron dyeConfirm to the client, keep bought dye split by colour for resale, and hide inactive shop panes so buy/sell tabs do not stack.
@@ -183,7 +183,7 @@ export function initShop ({
183
183
return Math.min(affordable, available);
184
184
}
185
185
186
function inventoryFits (itemId, quantity)
186
function inventoryFits (itemId, quantity, instance = null)
187
187
{
188
188
const def = itemDefinition(itemId);
189
189
if (!def)
@@ -191,7 +191,8 @@ export function initShop ({
191
191
const slots = getInventorySlots?.() ?? [];
192
192
const added = insertStack(slots.map((slot) => (slot ? structuredClone(slot) : null)), {
193
193
itemId,
194
quantity: Math.max(1, quantity | 0 || 1)
194
quantity: Math.max(1, quantity | 0 || 1),
195
instance: instance ? structuredClone(instance) : null
195
196
}, def);
196
197
return added.ok && added.remainder === 0;
197
198
}
@@ -508,7 +509,8 @@ export function initShop ({
508
509
509
510
for (const entry of stock)
510
511
{
511
const name = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });
512
const stack = { itemId: entry.itemId, instance: entry.instance ?? null };
513
const name = entry.displayName ?? itemDisplayName(stack);
512
514
const btn = document.createElement("button");
513
515
btn.type = "button";
514
516
btn.className = "shop-cell";
@@ -517,7 +519,7 @@ export function initShop ({
517
519
btn.title = name;
518
520
const img = document.createElement("img");
519
521
img.alt = name;
520
applyItemIcon(img, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));
522
applyItemIcon(img, stack, itemAssetPathForStack(stack));
521
523
btn.append(img);
522
524
btn.addEventListener("click", () =>
523
525
{
@@ -536,13 +538,14 @@ export function initShop ({
536
538
}
537
539
538
540
detail.hidden = false;
539
const name = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });
541
const detailStack = { itemId: entry.itemId, instance: entry.instance ?? null };
542
const name = entry.displayName ?? itemDisplayName(detailStack);
540
543
detailName.textContent = name;
541
544
detailPrice.textContent = `${formatQuantity(entry.unitPrice)} coins each`;
542
545
detailStock.textContent = entry.available == null
543
546
? "In stock"
544
547
: `Stock: ${formatQuantity(entry.available)}`;
545
applyItemIcon(detailIcon, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));
548
applyItemIcon(detailIcon, detailStack, itemAssetPathForStack(detailStack));
546
549
547
550
const max = maxBuyable(entry);
548
551
const setBuy = (id, qty) =>
@@ -559,7 +562,7 @@ export function initShop ({
559
562
if (buyX)
560
563
{ buyX.disabled = max < 1; }
561
564
562
bagWarn.hidden = inventoryFits(entry.itemId, 1);
565
bagWarn.hidden = inventoryFits(entry.itemId, 1, entry.instance ?? null);
563
566
}
564
567
565
568
function render ()
@@ -183,7 +183,7 @@ export function initShop ({183
return Math.min(affordable, available);183
return Math.min(affordable, available);184
}184
}185
185
186
function inventoryFits (itemId, quantity)186
function inventoryFits (itemId, quantity, instance = null)187
{187
{188
const def = itemDefinition(itemId);188
const def = itemDefinition(itemId);189
if (!def)189
if (!def)@@ -191,7 +191,8 @@ export function initShop ({191
const slots = getInventorySlots?.() ?? [];191
const slots = getInventorySlots?.() ?? [];192
const added = insertStack(slots.map((slot) => (slot ? structuredClone(slot) : null)), {192
const added = insertStack(slots.map((slot) => (slot ? structuredClone(slot) : null)), {193
itemId,193
itemId,194
quantity: Math.max(1, quantity | 0 || 1)194
quantity: Math.max(1, quantity | 0 || 1),195
instance: instance ? structuredClone(instance) : null195
}, def);196
}, def);196
return added.ok && added.remainder === 0;197
return added.ok && added.remainder === 0;197
}198
}@@ -508,7 +509,8 @@ export function initShop ({508
509
509
for (const entry of stock)510
for (const entry of stock)510
{511
{511
const name = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });512
const stack = { itemId: entry.itemId, instance: entry.instance ?? null };513
const name = entry.displayName ?? itemDisplayName(stack);512
const btn = document.createElement("button");514
const btn = document.createElement("button");513
btn.type = "button";515
btn.type = "button";514
btn.className = "shop-cell";516
btn.className = "shop-cell";@@ -517,7 +519,7 @@ export function initShop ({517
btn.title = name;519
btn.title = name;518
const img = document.createElement("img");520
const img = document.createElement("img");519
img.alt = name;521
img.alt = name;520
applyItemIcon(img, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));522
applyItemIcon(img, stack, itemAssetPathForStack(stack));521
btn.append(img);523
btn.append(img);522
btn.addEventListener("click", () =>524
btn.addEventListener("click", () =>523
{525
{@@ -536,13 +538,14 @@ export function initShop ({536
}538
}537
539
538
detail.hidden = false;540
detail.hidden = false;539
const name = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });541
const detailStack = { itemId: entry.itemId, instance: entry.instance ?? null };542
const name = entry.displayName ?? itemDisplayName(detailStack);540
detailName.textContent = name;543
detailName.textContent = name;541
detailPrice.textContent = `${formatQuantity(entry.unitPrice)} coins each`;544
detailPrice.textContent = `${formatQuantity(entry.unitPrice)} coins each`;542
detailStock.textContent = entry.available == null545
detailStock.textContent = entry.available == null543
? "In stock"546
? "In stock"544
: `Stock: ${formatQuantity(entry.available)}`;547
: `Stock: ${formatQuantity(entry.available)}`;545
applyItemIcon(detailIcon, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));548
applyItemIcon(detailIcon, detailStack, itemAssetPathForStack(detailStack));546
549
547
const max = maxBuyable(entry);550
const max = maxBuyable(entry);548
const setBuy = (id, qty) =>551
const setBuy = (id, qty) =>@@ -559,7 +562,7 @@ export function initShop ({559
if (buyX)562
if (buyX)560
{ buyX.disabled = max < 1; }563
{ buyX.disabled = max < 1; }561
564
562
bagWarn.hidden = inventoryFits(entry.itemId, 1);565
bagWarn.hidden = inventoryFits(entry.itemId, 1, entry.instance ?? null);563
}566
}564
567
565
function render ()568
function render ()@@ -1440,6 +1440,7 @@ a {
1440
1440
#shop-qty-backdrop[hidden],
1441
1441
#nametag[hidden],
1442
1442
#chat-bar[hidden],
1443
.shop-pane[hidden],
1443
1444
.shop-detail[hidden],
1444
1445
.shop-bag-warn[hidden] {
1445
1446
display: none !important;
@@ -1440,6 +1440,7 @@ a {1440
#shop-qty-backdrop[hidden],1440
#shop-qty-backdrop[hidden],1441
#nametag[hidden],1441
#nametag[hidden],1442
#chat-bar[hidden],1442
#chat-bar[hidden],1443
.shop-pane[hidden],1443
.shop-detail[hidden],1444
.shop-detail[hidden],1444
.shop-bag-warn[hidden] {1445
.shop-bag-warn[hidden] {1445
display: none !important;1446
display: none !important;@@ -1,6 +1,6 @@
1
1
import { Component } from "../ecs/components.js";
2
2
import { bagView, findReservedChequeIndex } from "../items/bags.js";
3
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
3
import { ItemId, itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
4
4
import {
5
5
ItemOriginKind,
6
6
attachOrigins,
@@ -14,8 +14,10 @@ import {
14
14
addCoinsToSlots,
15
15
cloneStack,
16
16
countCoinsInSlots,
17
dyeStackIdentity,
17
18
insertStack,
18
19
insertStackGrowable,
20
potionStackIdentity,
19
21
takeCoinsFromSlots,
20
22
takeFromSlot
21
23
} from "../../../shared/items/inventory.js";
@@ -215,20 +217,63 @@ function catalogAvailable (shop, itemId)
215
217
return Math.max(0, shop.remaining?.[itemId] | 0 || 0);
216
218
}
217
219
218
/** Normalize legacy qty-only boughtStock entries into `{ quantity, origins }`. */
219
function boughtLot (shop, itemId)
220
/**
221
* Bought-stock map key. Plain items use `${itemId}`; dyes/potions/flowers keep
222
* colour / recipe identity so resale lots do not merge across variants.
223
*/
224
export function boughtStockKey (itemId, instance = null)
225
{
226
const id = itemId | 0;
227
const def = itemDefinition(id);
228
if (def?.dye)
229
{
230
const identity = dyeStackIdentity(instance);
231
return identity ? `${id}#dye:${identity}` : String(id);
232
}
233
if (def?.potion)
234
{
235
const identity = potionStackIdentity(instance);
236
return identity ? `${id}#potion:${identity}` : String(id);
237
}
238
if (def?.flower && instance?.colorId)
239
{ return `${id}#flower:${instance.colorId}`; }
240
return String(id);
241
}
242
243
function itemIdFromStockKey (stockKey)
244
{
245
if (stockKey == null)
246
{ return 0; }
247
const text = String(stockKey);
248
const hash = text.indexOf("#");
249
return (hash >= 0 ? text.slice(0, hash) : text) | 0;
250
}
251
252
/** Normalize legacy qty-only boughtStock entries into `{ itemId, quantity, origins, instance }`. */
253
function boughtLot (shop, stockKey)
220
254
{
221
const raw = shop.boughtStock?.[itemId];
255
const key = stockKey == null ? null : String(stockKey);
256
if (!key)
257
{ return null; }
258
let raw = shop.boughtStock?.[key];
259
if (raw == null && /^\d+$/.test(key))
260
{ raw = shop.boughtStock?.[Number(key)]; }
222
261
if (raw == null)
223
262
{ return null; }
263
const itemId = (typeof raw === "object" && raw.itemId != null)
264
? (raw.itemId | 0)
265
: itemIdFromStockKey(key);
224
266
if (typeof raw === "number")
225
267
{
226
268
const quantity = Math.max(0, raw | 0);
227
269
if (quantity <= 0)
228
270
{ return null; }
229
271
return {
272
stockKey: key,
273
itemId,
230
274
quantity,
231
origins: [{ origin: shopOrigin("a shop"), quantity }]
275
origins: [{ origin: shopOrigin("a shop"), quantity }],
276
instance: null
232
277
};
233
278
}
234
279
const quantity = Math.max(0, raw.quantity | 0 || 0);
@@ -240,49 +285,68 @@ function boughtLot (shop, itemId)
240
285
{
241
286
origins.push({ origin: shopOrigin("a shop"), quantity: quantity - originQty });
242
287
}
243
return { quantity, origins };
288
return {
289
stockKey: key,
290
itemId,
291
quantity,
292
origins,
293
instance: raw.instance ? structuredClone(raw.instance) : null
294
};
244
295
}
245
296
246
function boughtAvailable (shop, itemId)
297
function boughtAvailable (shop, stockKey)
247
298
{
248
return boughtLot(shop, itemId)?.quantity ?? 0;
299
return boughtLot(shop, stockKey)?.quantity ?? 0;
249
300
}
250
301
251
function addBoughtLot (shop, itemId, quantity, origins)
302
function addBoughtLot (shop, itemId, quantity, origins, instance = null)
252
303
{
253
304
const qty = Math.max(0, quantity | 0 || 0);
254
305
if (qty <= 0)
255
306
{ return; }
256
const existing = boughtLot(shop, itemId);
307
const key = boughtStockKey(itemId, instance);
308
const existing = boughtLot(shop, key);
257
309
const nextOrigins = mergeOriginLists(
258
310
existing?.origins ?? [],
259
311
normalizeOrigins({ quantity: qty, origins })
260
312
);
261
shop.boughtStock[itemId] = {
313
const keptInstance = existing?.instance
314
?? (instance ? structuredClone(instance) : null);
315
shop.boughtStock[key] = {
316
itemId: itemId | 0,
262
317
quantity: (existing?.quantity ?? 0) + qty,
263
origins: nextOrigins
318
origins: nextOrigins,
319
instance: keptInstance
264
320
};
265
321
}
266
322
267
323
/** Pull FIFO origins from bought stock; returns null if insufficient. */
268
function takeBoughtLot (shop, itemId, quantity)
324
function takeBoughtLot (shop, stockKey, quantity)
269
325
{
270
326
const qty = Math.max(0, quantity | 0 || 0);
271
const lot = boughtLot(shop, itemId);
327
const lot = boughtLot(shop, stockKey);
272
328
if (!lot || lot.quantity < qty)
273
329
{ return null; }
274
330
const split = splitOrigins(lot.origins, qty);
275
331
const remainQty = lot.quantity - qty;
332
const key = lot.stockKey;
276
333
if (remainQty <= 0)
277
{ delete shop.boughtStock[itemId]; }
334
{ delete shop.boughtStock[key]; }
278
335
else
279
336
{
280
shop.boughtStock[itemId] = {
337
shop.boughtStock[key] = {
338
itemId: lot.itemId,
281
339
quantity: remainQty,
282
origins: split.remain
340
origins: split.remain,
341
instance: lot.instance ? structuredClone(lot.instance) : null
283
342
};
284
343
}
285
return { quantity: qty, origins: split.taken };
344
return {
345
quantity: qty,
346
origins: split.taken,
347
instance: lot.instance ? structuredClone(lot.instance) : null,
348
itemId: lot.itemId
349
};
286
350
}
287
351
288
352
function shopStockView (world, shop, now)
@@ -313,25 +377,28 @@ function shopStockView (world, shop, now)
313
377
hiddenDiscount: shop.hiddenDiscount ?? 1
314
378
}),
315
379
available: Number.isFinite(available) ? available : null,
316
source: "stock"
380
source: "stock",
381
instance: null
317
382
});
318
383
}
319
384
for (const key of Object.keys(shop.boughtStock ?? {}))
320
385
{
321
const itemId = key | 0;
322
const available = boughtAvailable(shop, itemId);
323
if (available <= 0)
386
const lot = boughtLot(shop, key);
387
if (!lot || lot.quantity <= 0)
324
388
{ continue; }
389
const itemId = lot.itemId;
325
390
const def = itemDefinition(itemId);
326
391
if (!def)
327
392
{ continue; }
393
const stack = { itemId, quantity: lot.quantity, instance: lot.instance };
328
394
stock.push({
329
listingId: `bought:${itemId}`,
395
listingId: `bought:${lot.stockKey}`,
330
396
itemId,
331
displayName: def.displayName,
397
displayName: itemDisplayName(stack, def),
332
398
unitPrice: shopBoughtResalePrice(itemId, lastSaleOpts(itemId)),
333
available,
334
source: "bought"
399
available: lot.quantity,
400
source: "bought",
401
instance: lot.instance ? structuredClone(lot.instance) : null
335
402
});
336
403
}
337
404
return stock;
@@ -413,14 +480,32 @@ export function closeShop (world, sessionId, characterId, npcEntityId)
413
480
414
481
function parseListing (listingId, itemId, source)
415
482
{
416
if (typeof listingId === "string" && listingId.includes(":"))
483
if (typeof listingId === "string")
417
484
{
418
const [kind, id] = listingId.split(":");
419
return { source: kind === "bought" ? "bought" : "stock", itemId: id | 0 };
485
if (listingId.startsWith("bought:"))
486
{
487
const stockKey = listingId.slice("bought:".length);
488
return {
489
source: "bought",
490
itemId: itemIdFromStockKey(stockKey),
491
stockKey
492
};
493
}
494
if (listingId.startsWith("stock:"))
495
{
496
return {
497
source: "stock",
498
itemId: listingId.slice("stock:".length) | 0,
499
stockKey: null
500
};
501
}
420
502
}
421
503
if (source === "bought")
422
{ return { source: "bought", itemId: itemId | 0 }; }
423
return { source: "stock", itemId: itemId | 0 };
504
{
505
const id = itemId | 0;
506
return { source: "bought", itemId: id, stockKey: String(id) };
507
}
508
return { source: "stock", itemId: itemId | 0, stockKey: null };
424
509
}
425
510
426
511
export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now(), listingId = null, source = null)
@@ -434,7 +519,7 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,
434
519
if (!catalogLine(shop, buyItemId))
435
520
{ throw userError("That item cannot be sold here."); }
436
521
}
437
else if (boughtAvailable(shop, buyItemId) <= 0)
522
else if (boughtAvailable(shop, listing.stockKey) <= 0)
438
523
{ throw userError("Not enough stock."); }
439
524
440
525
const qty = Math.max(1, quantity | 0 || 1);
@@ -443,7 +528,7 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,
443
528
{ throw userError("Unknown item."); }
444
529
445
530
const available = listing.source === "bought"
446
? boughtAvailable(shop, buyItemId)
531
? boughtAvailable(shop, listing.stockKey)
447
532
: catalogAvailable(shop, buyItemId);
448
533
if (available < qty)
449
534
{ throw userError("Not enough stock."); }
@@ -477,13 +562,14 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,
477
562
let stack;
478
563
if (listing.source === "bought")
479
564
{
480
const lot = boughtLot(shop, buyItemId);
565
const lot = boughtLot(shop, listing.stockKey);
481
566
if (!lot || lot.quantity < qty)
482
567
{ throw userError("Not enough stock."); }
483
568
const split = splitOrigins(lot.origins, qty);
484
569
stack = attachOrigins({
485
570
itemId: buyItemId,
486
571
quantity: qty,
572
instance: lot.instance ? structuredClone(lot.instance) : null,
487
573
origins: split.taken
488
574
});
489
575
}
@@ -504,6 +590,7 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,
504
590
const overflow = attachOrigins({
505
591
itemId: buyItemId,
506
592
quantity: added.remainder,
593
instance: stack.instance ? structuredClone(stack.instance) : null,
507
594
origins: overflowOrigins
508
595
});
509
596
const vault = ensureVault(world.ecs, handle);
@@ -515,7 +602,7 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,
515
602
516
603
if (listing.source === "bought")
517
604
{
518
if (!takeBoughtLot(shop, buyItemId, qty))
605
if (!takeBoughtLot(shop, listing.stockKey, qty))
519
606
{ throw userError("Not enough stock."); }
520
607
}
521
608
else
@@ -677,7 +764,13 @@ export function sellToShop (world, sessionId, characterId, npcEntityId, slotInde
677
764
const soldOrigins = normalizeOrigins(soldStack);
678
765
// Catalog refill absorbs first; leftover keeps remaining origins for resale.
679
766
const { remain: resaleOrigins } = splitOrigins(soldOrigins, refill);
680
addBoughtLot(shop, goodsItemId, leftover, resaleOrigins);
767
addBoughtLot(
768
shop,
769
goodsItemId,
770
leftover,
771
resaleOrigins,
772
soldStack?.instance ?? null
773
);
681
774
}
682
775
683
776
const displayName = shopDisplayName(shop, npcHandle, world);
@@ -1,6 +1,6 @@1
import { Component } from "../ecs/components.js";1
import { Component } from "../ecs/components.js";2
import { bagView, findReservedChequeIndex } from "../items/bags.js";2
import { bagView, findReservedChequeIndex } from "../items/bags.js";3
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";3
import { ItemId, itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";4
import {4
import {5
ItemOriginKind,5
ItemOriginKind,6
attachOrigins,6
attachOrigins,@@ -14,8 +14,10 @@ import {14
addCoinsToSlots,14
addCoinsToSlots,15
cloneStack,15
cloneStack,16
countCoinsInSlots,16
countCoinsInSlots,17
dyeStackIdentity,17
insertStack,18
insertStack,18
insertStackGrowable,19
insertStackGrowable,20
potionStackIdentity,19
takeCoinsFromSlots,21
takeCoinsFromSlots,20
takeFromSlot22
takeFromSlot21
} from "../../../shared/items/inventory.js";23
} from "../../../shared/items/inventory.js";@@ -215,20 +217,63 @@ function catalogAvailable (shop, itemId)215
return Math.max(0, shop.remaining?.[itemId] | 0 || 0);217
return Math.max(0, shop.remaining?.[itemId] | 0 || 0);216
}218
}217
219
218
/** Normalize legacy qty-only boughtStock entries into `{ quantity, origins }`. */220
/**219
function boughtLot (shop, itemId)221
* Bought-stock map key. Plain items use `${itemId}`; dyes/potions/flowers keep222
* colour / recipe identity so resale lots do not merge across variants.223
*/224
export function boughtStockKey (itemId, instance = null)225
{226
const id = itemId | 0;227
const def = itemDefinition(id);228
if (def?.dye)229
{230
const identity = dyeStackIdentity(instance);231
return identity ? `${id}#dye:${identity}` : String(id);232
}233
if (def?.potion)234
{235
const identity = potionStackIdentity(instance);236
return identity ? `${id}#potion:${identity}` : String(id);237
}238
if (def?.flower && instance?.colorId)239
{ return `${id}#flower:${instance.colorId}`; }240
return String(id);241
}242
243
function itemIdFromStockKey (stockKey)244
{245
if (stockKey == null)246
{ return 0; }247
const text = String(stockKey);248
const hash = text.indexOf("#");249
return (hash >= 0 ? text.slice(0, hash) : text) | 0;250
}251
252
/** Normalize legacy qty-only boughtStock entries into `{ itemId, quantity, origins, instance }`. */253
function boughtLot (shop, stockKey)220
{254
{221
const raw = shop.boughtStock?.[itemId];255
const key = stockKey == null ? null : String(stockKey);256
if (!key)257
{ return null; }258
let raw = shop.boughtStock?.[key];259
if (raw == null && /^\d+$/.test(key))260
{ raw = shop.boughtStock?.[Number(key)]; }222
if (raw == null)261
if (raw == null)223
{ return null; }262
{ return null; }263
const itemId = (typeof raw === "object" && raw.itemId != null)264
? (raw.itemId | 0)265
: itemIdFromStockKey(key);224
if (typeof raw === "number")266
if (typeof raw === "number")225
{267
{226
const quantity = Math.max(0, raw | 0);268
const quantity = Math.max(0, raw | 0);227
if (quantity <= 0)269
if (quantity <= 0)228
{ return null; }270
{ return null; }229
return {271
return {272
stockKey: key,273
itemId,230
quantity,274
quantity,231
origins: [{ origin: shopOrigin("a shop"), quantity }]275
origins: [{ origin: shopOrigin("a shop"), quantity }],276
instance: null232
};277
};233
}278
}234
const quantity = Math.max(0, raw.quantity | 0 || 0);279
const quantity = Math.max(0, raw.quantity | 0 || 0);@@ -240,49 +285,68 @@ function boughtLot (shop, itemId)240
{285
{241
origins.push({ origin: shopOrigin("a shop"), quantity: quantity - originQty });286
origins.push({ origin: shopOrigin("a shop"), quantity: quantity - originQty });242
}287
}243
return { quantity, origins };288
return {289
stockKey: key,290
itemId,291
quantity,292
origins,293
instance: raw.instance ? structuredClone(raw.instance) : null294
};244
}295
}245
296
246
function boughtAvailable (shop, itemId)297
function boughtAvailable (shop, stockKey)247
{298
{248
return boughtLot(shop, itemId)?.quantity ?? 0;299
return boughtLot(shop, stockKey)?.quantity ?? 0;249
}300
}250
301
251
function addBoughtLot (shop, itemId, quantity, origins)302
function addBoughtLot (shop, itemId, quantity, origins, instance = null)252
{303
{253
const qty = Math.max(0, quantity | 0 || 0);304
const qty = Math.max(0, quantity | 0 || 0);254
if (qty <= 0)305
if (qty <= 0)255
{ return; }306
{ return; }256
const existing = boughtLot(shop, itemId);307
const key = boughtStockKey(itemId, instance);308
const existing = boughtLot(shop, key);257
const nextOrigins = mergeOriginLists(309
const nextOrigins = mergeOriginLists(258
existing?.origins ?? [],310
existing?.origins ?? [],259
normalizeOrigins({ quantity: qty, origins })311
normalizeOrigins({ quantity: qty, origins })260
);312
);261
shop.boughtStock[itemId] = {313
const keptInstance = existing?.instance314
?? (instance ? structuredClone(instance) : null);315
shop.boughtStock[key] = {316
itemId: itemId | 0,262
quantity: (existing?.quantity ?? 0) + qty,317
quantity: (existing?.quantity ?? 0) + qty,263
origins: nextOrigins318
origins: nextOrigins,319
instance: keptInstance264
};320
};265
}321
}266
322
267
/** Pull FIFO origins from bought stock; returns null if insufficient. */323
/** Pull FIFO origins from bought stock; returns null if insufficient. */268
function takeBoughtLot (shop, itemId, quantity)324
function takeBoughtLot (shop, stockKey, quantity)269
{325
{270
const qty = Math.max(0, quantity | 0 || 0);326
const qty = Math.max(0, quantity | 0 || 0);271
const lot = boughtLot(shop, itemId);327
const lot = boughtLot(shop, stockKey);272
if (!lot || lot.quantity < qty)328
if (!lot || lot.quantity < qty)273
{ return null; }329
{ return null; }274
const split = splitOrigins(lot.origins, qty);330
const split = splitOrigins(lot.origins, qty);275
const remainQty = lot.quantity - qty;331
const remainQty = lot.quantity - qty;332
const key = lot.stockKey;276
if (remainQty <= 0)333
if (remainQty <= 0)277
{ delete shop.boughtStock[itemId]; }334
{ delete shop.boughtStock[key]; }278
else335
else279
{336
{280
shop.boughtStock[itemId] = {337
shop.boughtStock[key] = {338
itemId: lot.itemId,281
quantity: remainQty,339
quantity: remainQty,282
origins: split.remain340
origins: split.remain,341
instance: lot.instance ? structuredClone(lot.instance) : null283
};342
};284
}343
}285
return { quantity: qty, origins: split.taken };344
return {345
quantity: qty,346
origins: split.taken,347
instance: lot.instance ? structuredClone(lot.instance) : null,348
itemId: lot.itemId349
};286
}350
}287
351
288
function shopStockView (world, shop, now)352
function shopStockView (world, shop, now)@@ -313,25 +377,28 @@ function shopStockView (world, shop, now)313
hiddenDiscount: shop.hiddenDiscount ?? 1377
hiddenDiscount: shop.hiddenDiscount ?? 1314
}),378
}),315
available: Number.isFinite(available) ? available : null,379
available: Number.isFinite(available) ? available : null,316
source: "stock"380
source: "stock",381
instance: null317
});382
});318
}383
}319
for (const key of Object.keys(shop.boughtStock ?? {}))384
for (const key of Object.keys(shop.boughtStock ?? {}))320
{385
{321
const itemId = key | 0;386
const lot = boughtLot(shop, key);322
const available = boughtAvailable(shop, itemId);387
if (!lot || lot.quantity <= 0)323
if (available <= 0)324
{ continue; }388
{ continue; }389
const itemId = lot.itemId;325
const def = itemDefinition(itemId);390
const def = itemDefinition(itemId);326
if (!def)391
if (!def)327
{ continue; }392
{ continue; }393
const stack = { itemId, quantity: lot.quantity, instance: lot.instance };328
stock.push({394
stock.push({329
listingId: `bought:${itemId}`,395
listingId: `bought:${lot.stockKey}`,330
itemId,396
itemId,331
displayName: def.displayName,397
displayName: itemDisplayName(stack, def),332
unitPrice: shopBoughtResalePrice(itemId, lastSaleOpts(itemId)),398
unitPrice: shopBoughtResalePrice(itemId, lastSaleOpts(itemId)),333
available,399
available: lot.quantity,334
source: "bought"400
source: "bought",401
instance: lot.instance ? structuredClone(lot.instance) : null335
});402
});336
}403
}337
return stock;404
return stock;@@ -413,14 +480,32 @@ export function closeShop (world, sessionId, characterId, npcEntityId)413
480
414
function parseListing (listingId, itemId, source)481
function parseListing (listingId, itemId, source)415
{482
{416
if (typeof listingId === "string" && listingId.includes(":"))483
if (typeof listingId === "string")417
{484
{418
const [kind, id] = listingId.split(":");485
if (listingId.startsWith("bought:"))419
return { source: kind === "bought" ? "bought" : "stock", itemId: id | 0 };486
{487
const stockKey = listingId.slice("bought:".length);488
return {489
source: "bought",490
itemId: itemIdFromStockKey(stockKey),491
stockKey492
};493
}494
if (listingId.startsWith("stock:"))495
{496
return {497
source: "stock",498
itemId: listingId.slice("stock:".length) | 0,499
stockKey: null500
};501
}420
}502
}421
if (source === "bought")503
if (source === "bought")422
{ return { source: "bought", itemId: itemId | 0 }; }504
{423
return { source: "stock", itemId: itemId | 0 };505
const id = itemId | 0;506
return { source: "bought", itemId: id, stockKey: String(id) };507
}508
return { source: "stock", itemId: itemId | 0, stockKey: null };424
}509
}425
510
426
export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now(), listingId = null, source = null)511
export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now(), listingId = null, source = null)@@ -434,7 +519,7 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,434
if (!catalogLine(shop, buyItemId))519
if (!catalogLine(shop, buyItemId))435
{ throw userError("That item cannot be sold here."); }520
{ throw userError("That item cannot be sold here."); }436
}521
}437
else if (boughtAvailable(shop, buyItemId) <= 0)522
else if (boughtAvailable(shop, listing.stockKey) <= 0)438
{ throw userError("Not enough stock."); }523
{ throw userError("Not enough stock."); }439
524
440
const qty = Math.max(1, quantity | 0 || 1);525
const qty = Math.max(1, quantity | 0 || 1);@@ -443,7 +528,7 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,443
{ throw userError("Unknown item."); }528
{ throw userError("Unknown item."); }444
529
445
const available = listing.source === "bought"530
const available = listing.source === "bought"446
? boughtAvailable(shop, buyItemId)531
? boughtAvailable(shop, listing.stockKey)447
: catalogAvailable(shop, buyItemId);532
: catalogAvailable(shop, buyItemId);448
if (available < qty)533
if (available < qty)449
{ throw userError("Not enough stock."); }534
{ throw userError("Not enough stock."); }@@ -477,13 +562,14 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,477
let stack;562
let stack;478
if (listing.source === "bought")563
if (listing.source === "bought")479
{564
{480
const lot = boughtLot(shop, buyItemId);565
const lot = boughtLot(shop, listing.stockKey);481
if (!lot || lot.quantity < qty)566
if (!lot || lot.quantity < qty)482
{ throw userError("Not enough stock."); }567
{ throw userError("Not enough stock."); }483
const split = splitOrigins(lot.origins, qty);568
const split = splitOrigins(lot.origins, qty);484
stack = attachOrigins({569
stack = attachOrigins({485
itemId: buyItemId,570
itemId: buyItemId,486
quantity: qty,571
quantity: qty,572
instance: lot.instance ? structuredClone(lot.instance) : null,487
origins: split.taken573
origins: split.taken488
});574
});489
}575
}@@ -504,6 +590,7 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,504
const overflow = attachOrigins({590
const overflow = attachOrigins({505
itemId: buyItemId,591
itemId: buyItemId,506
quantity: added.remainder,592
quantity: added.remainder,593
instance: stack.instance ? structuredClone(stack.instance) : null,507
origins: overflowOrigins594
origins: overflowOrigins508
});595
});509
const vault = ensureVault(world.ecs, handle);596
const vault = ensureVault(world.ecs, handle);@@ -515,7 +602,7 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,515
602
516
if (listing.source === "bought")603
if (listing.source === "bought")517
{604
{518
if (!takeBoughtLot(shop, buyItemId, qty))605
if (!takeBoughtLot(shop, listing.stockKey, qty))519
{ throw userError("Not enough stock."); }606
{ throw userError("Not enough stock."); }520
}607
}521
else608
else@@ -677,7 +764,13 @@ export function sellToShop (world, sessionId, characterId, npcEntityId, slotInde677
const soldOrigins = normalizeOrigins(soldStack);764
const soldOrigins = normalizeOrigins(soldStack);678
// Catalog refill absorbs first; leftover keeps remaining origins for resale.765
// Catalog refill absorbs first; leftover keeps remaining origins for resale.679
const { remain: resaleOrigins } = splitOrigins(soldOrigins, refill);766
const { remain: resaleOrigins } = splitOrigins(soldOrigins, refill);680
addBoughtLot(shop, goodsItemId, leftover, resaleOrigins);767
addBoughtLot(768
shop,769
goodsItemId,770
leftover,771
resaleOrigins,772
soldStack?.instance ?? null773
);681
}774
}682
775
683
const displayName = shopDisplayName(shop, npcHandle, world);776
const displayName = shopDisplayName(shop, npcHandle, world);@@ -1,26 +1,28 @@
1
import {
2
CHUNK_SIZE,
3
DEFAULT_CHUNK_LOADER,
4
GAIT,
5
REGION_RUNTIME_STATE,
6
VISIBLE_CHUNK_RADIUS,
7
STATIC_CHUNK_RADIUS,
8
WORLD_YEAR_OFFSET
9
} from "../../../shared/protocol/constants.js";
1
import
2
{
3
CHUNK_SIZE,
4
DEFAULT_CHUNK_LOADER,
5
GAIT,
6
REGION_RUNTIME_STATE,
7
VISIBLE_CHUNK_RADIUS,
8
STATIC_CHUNK_RADIUS,
9
WORLD_YEAR_OFFSET
10
} from "../../../shared/protocol/constants.js";
10
11
import { OVERWORLD_ID, normalizeDimensionId, defaultDimensionRecord } from "../../../shared/world/dimensions.js";
11
import {
12
chunkKey,
13
chunkToRegion,
14
chunksInRegion,
15
parseChunkKey,
16
parseRegionKey,
17
regionKey,
18
regionTileBounds,
19
tileToChunk,
20
tileToLocal,
21
tileToRegion,
22
visibleChunkCoords
23
} from "../world/coordinates.js";
12
import
13
{
14
chunkKey,
15
chunkToRegion,
16
chunksInRegion,
17
parseChunkKey,
18
parseRegionKey,
19
regionKey,
20
regionTileBounds,
21
tileToChunk,
22
tileToLocal,
23
tileToRegion,
24
visibleChunkCoords
25
} from "../world/coordinates.js";
24
26
import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";
25
27
import { closedNeighborEdges } from "../world/chunkFlags.js";
26
28
import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js";
@@ -50,7 +52,7 @@ import { chebyshev } from "../combat/service.js";
50
52
51
53
export class Simulation
52
54
{
53
constructor (worldDb, stateDb, options = {})
55
constructor(worldDb, stateDb, options = {})
54
56
{
55
57
this.worldDb = worldDb;
56
58
this.stateDb = stateDb;
@@ -1223,6 +1225,7 @@ export class Simulation
1223
1225
cauldron: result.cauldron,
1224
1226
cauldronState: result.cauldronState ?? null,
1225
1227
alchemyResult: result.alchemyResult ?? null,
1228
dyeConfirm: result.dyeConfirm ?? null,
1226
1229
...result.private
1227
1230
});
1228
1231
}
@@ -1,26 +1,28 @@1
import {1
import2
CHUNK_SIZE,2
{3
DEFAULT_CHUNK_LOADER,3
CHUNK_SIZE,4
GAIT,4
DEFAULT_CHUNK_LOADER,5
REGION_RUNTIME_STATE,5
GAIT,6
VISIBLE_CHUNK_RADIUS,6
REGION_RUNTIME_STATE,7
STATIC_CHUNK_RADIUS,7
VISIBLE_CHUNK_RADIUS,8
WORLD_YEAR_OFFSET8
STATIC_CHUNK_RADIUS,9
} from "../../../shared/protocol/constants.js";9
WORLD_YEAR_OFFSET10
} from "../../../shared/protocol/constants.js";10
import { OVERWORLD_ID, normalizeDimensionId, defaultDimensionRecord } from "../../../shared/world/dimensions.js";11
import { OVERWORLD_ID, normalizeDimensionId, defaultDimensionRecord } from "../../../shared/world/dimensions.js";11
import {12
import12
chunkKey,13
{13
chunkToRegion,14
chunkKey,14
chunksInRegion,15
chunkToRegion,15
parseChunkKey,16
chunksInRegion,16
parseRegionKey,17
parseChunkKey,17
regionKey,18
parseRegionKey,18
regionTileBounds,19
regionKey,19
tileToChunk,20
regionTileBounds,20
tileToLocal,21
tileToChunk,21
tileToRegion,22
tileToLocal,22
visibleChunkCoords23
tileToRegion,23
} from "../world/coordinates.js";24
visibleChunkCoords25
} from "../world/coordinates.js";24
import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";26
import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";25
import { closedNeighborEdges } from "../world/chunkFlags.js";27
import { closedNeighborEdges } from "../world/chunkFlags.js";26
import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js";28
import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js";@@ -50,7 +52,7 @@ import { chebyshev } from "../combat/service.js";50
52
51
export class Simulation53
export class Simulation52
{54
{53
constructor (worldDb, stateDb, options = {})55
constructor(worldDb, stateDb, options = {})54
{56
{55
this.worldDb = worldDb;57
this.worldDb = worldDb;56
this.stateDb = stateDb;58
this.stateDb = stateDb;@@ -1223,6 +1225,7 @@ export class Simulation1223
cauldron: result.cauldron,1225
cauldron: result.cauldron,1224
cauldronState: result.cauldronState ?? null,1226
cauldronState: result.cauldronState ?? null,1225
alchemyResult: result.alchemyResult ?? null,1227
alchemyResult: result.alchemyResult ?? null,1228
dyeConfirm: result.dyeConfirm ?? null,1226
...result.private1229
...result.private1227
});1230
});1228
}1231
}@@ -4,21 +4,23 @@ import { BlockType } from "../../shared/definitions/tiles.js";
4
4
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
5
5
import { flowerItemInstance } from "../../shared/definitions/dyes.js";
6
6
import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";
7
import {
8
evaluateAlchemyBottle,
9
hashAlchemySteps,
10
resolvedAlchemyPotions,
11
unstablePotionFromSteps,
12
potionItemInstance
13
} from "../../shared/alchemy/recipes.js";
7
import
8
{
9
evaluateAlchemyBottle,
10
hashAlchemySteps,
11
resolvedAlchemyPotions,
12
unstablePotionFromSteps,
13
potionItemInstance
14
} from "../../shared/alchemy/recipes.js";
14
15
import { emptyEquipment, emptySlots, insertStack } from "../../shared/items/inventory.js";
15
16
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
16
17
import { Component } from "../src/ecs/components.js";
17
import {
18
makeCharacter,
19
makeSimulation,
20
stepTimes
21
} from "./helpers/simulationHarness.js";
18
import
19
{
20
makeCharacter,
21
makeSimulation,
22
stepTimes
23
} from "./helpers/simulationHarness.js";
22
24
23
25
function placeCauldron (worldDb, tileX, tileY)
24
26
{
@@ -363,3 +365,62 @@ test("creating dye awards 1 alchemy XP per flower and caps a slot at 16", () =>
363
365
finally
364
366
{ harness.close(); }
365
367
});
368
369
test("create dye with fewer bottles than flowers returns dyeConfirm on inventory", () =>
370
{
371
const harness = makeSimulation({ workerCount: 1 });
372
try
373
{
374
placeCauldron(harness.worldDb, 8, 8);
375
harness.simulation.reloadWorld();
376
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
377
const yellow = flowerItemInstance("yellow");
378
const magenta = flowerItemInstance("magenta");
379
let slots = emptySlots();
380
slots = insertStack(
381
slots,
382
{ itemId: ItemId.flower, quantity: 1, instance: yellow },
383
itemDefinition(ItemId.flower)
384
).slots;
385
slots = insertStack(
386
slots,
387
{ itemId: ItemId.flower, quantity: 1, instance: magenta },
388
itemDefinition(ItemId.flower)
389
).slots;
390
slots = insertStack(
391
slots,
392
{ itemId: ItemId.glassBottle, quantity: 1 },
393
itemDefinition(ItemId.glassBottle)
394
).slots;
395
harness.stateDb.saveBag(character.character_id, {
396
inventory: slots,
397
equipment: emptyEquipment(),
398
vault: [],
399
vaultReserved: []
400
});
401
const entityId = harness.simulation.spawnCharacter(1, character);
402
const cid = character.character_id;
403
404
harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid });
405
harness.simulation.step();
406
harness.simulation.enqueue(1, {
407
type: "cauldron-create-dye",
408
characterId: cid,
409
confirmOverflow: false,
410
flowers: [
411
{ itemId: ItemId.flower, quantity: 1, instance: yellow },
412
{ itemId: ItemId.flower, quantity: 1, instance: magenta }
413
]
414
});
415
const made = harness.simulation.step();
416
const inv = made.events.find((event) => event.type === "inventory" && event.dyeConfirm);
417
assert.ok(inv, JSON.stringify(made.events));
418
assert.deepEqual(inv.dyeConfirm, { wanted: 2, bottles: 1, lost: 1 });
419
const bag = harness.simulation.bagOf(entityId);
420
assert.equal(countItem(bag.inventory, ItemId.flower), 2);
421
assert.equal(countItem(bag.inventory, ItemId.dye), 0);
422
assert.equal(countItem(bag.inventory, ItemId.glassBottle), 1);
423
}
424
finally
425
{ harness.close(); }
426
});
@@ -4,21 +4,23 @@ import { BlockType } from "../../shared/definitions/tiles.js";4
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";4
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";5
import { flowerItemInstance } from "../../shared/definitions/dyes.js";5
import { flowerItemInstance } from "../../shared/definitions/dyes.js";6
import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";6
import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";7
import {7
import8
evaluateAlchemyBottle,8
{9
hashAlchemySteps,9
evaluateAlchemyBottle,10
resolvedAlchemyPotions,10
hashAlchemySteps,11
unstablePotionFromSteps,11
resolvedAlchemyPotions,12
potionItemInstance12
unstablePotionFromSteps,13
} from "../../shared/alchemy/recipes.js";13
potionItemInstance14
} from "../../shared/alchemy/recipes.js";14
import { emptyEquipment, emptySlots, insertStack } from "../../shared/items/inventory.js";15
import { emptyEquipment, emptySlots, insertStack } from "../../shared/items/inventory.js";15
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";16
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";16
import { Component } from "../src/ecs/components.js";17
import { Component } from "../src/ecs/components.js";17
import {18
import18
makeCharacter,19
{19
makeSimulation,20
makeCharacter,20
stepTimes21
makeSimulation,21
} from "./helpers/simulationHarness.js";22
stepTimes23
} from "./helpers/simulationHarness.js";22
24
23
function placeCauldron (worldDb, tileX, tileY)25
function placeCauldron (worldDb, tileX, tileY)24
{26
{@@ -363,3 +365,62 @@ test("creating dye awards 1 alchemy XP per flower and caps a slot at 16", () =>363
finally365
finally364
{ harness.close(); }366
{ harness.close(); }365
});367
});368
369
test("create dye with fewer bottles than flowers returns dyeConfirm on inventory", () =>370
{371
const harness = makeSimulation({ workerCount: 1 });372
try373
{374
placeCauldron(harness.worldDb, 8, 8);375
harness.simulation.reloadWorld();376
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });377
const yellow = flowerItemInstance("yellow");378
const magenta = flowerItemInstance("magenta");379
let slots = emptySlots();380
slots = insertStack(381
slots,382
{ itemId: ItemId.flower, quantity: 1, instance: yellow },383
itemDefinition(ItemId.flower)384
).slots;385
slots = insertStack(386
slots,387
{ itemId: ItemId.flower, quantity: 1, instance: magenta },388
itemDefinition(ItemId.flower)389
).slots;390
slots = insertStack(391
slots,392
{ itemId: ItemId.glassBottle, quantity: 1 },393
itemDefinition(ItemId.glassBottle)394
).slots;395
harness.stateDb.saveBag(character.character_id, {396
inventory: slots,397
equipment: emptyEquipment(),398
vault: [],399
vaultReserved: []400
});401
const entityId = harness.simulation.spawnCharacter(1, character);402
const cid = character.character_id;403
404
harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid });405
harness.simulation.step();406
harness.simulation.enqueue(1, {407
type: "cauldron-create-dye",408
characterId: cid,409
confirmOverflow: false,410
flowers: [411
{ itemId: ItemId.flower, quantity: 1, instance: yellow },412
{ itemId: ItemId.flower, quantity: 1, instance: magenta }413
]414
});415
const made = harness.simulation.step();416
const inv = made.events.find((event) => event.type === "inventory" && event.dyeConfirm);417
assert.ok(inv, JSON.stringify(made.events));418
assert.deepEqual(inv.dyeConfirm, { wanted: 2, bottles: 1, lost: 1 });419
const bag = harness.simulation.bagOf(entityId);420
assert.equal(countItem(bag.inventory, ItemId.flower), 2);421
assert.equal(countItem(bag.inventory, ItemId.dye), 0);422
assert.equal(countItem(bag.inventory, ItemId.glassBottle), 1);423
}424
finally425
{ harness.close(); }426
});@@ -23,9 +23,10 @@ import { Component } from "../src/ecs/components.js";
23
23
import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";
24
24
import { ItemOriginKind } from "../../shared/items/origin.js";
25
25
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
26
import { ensureShopRestocked } from "../src/shop/service.js";
26
import { ensureShopRestocked, boughtStockKey } from "../src/shop/service.js";
27
27
import { BlockType } from "../../shared/definitions/tiles.js";
28
28
import { GatherOriginVerb, gatherOrigin } from "../../shared/items/origin.js";
29
import { dyeItemInstance, DEFAULT_DYE_FILL, FlowerColorId } from "../../shared/definitions/dyes.js";
29
30
30
31
function boughtQty (shop, itemId)
31
32
{
@@ -1139,3 +1140,117 @@ test("NPC letter sales pay out and destroy the letter without stock", () =>
1139
1140
finally
1140
1141
{ harness.close(); }
1141
1142
});
1143
1144
test("vendor bought dye stays split by colour and resells that colour", () =>
1145
{
1146
const harness = makeSimulation({ workerCount: 1 });
1147
try
1148
{
1149
const data = createEmptyChunkData();
1150
data.open = true;
1151
data.spawners = [{
1152
localX: 9,
1153
localY: 8,
1154
config: {
1155
mobTypeId: MobId.humanoid,
1156
maxAlive: 1,
1157
spawnRangeTiles: 0,
1158
maxWanderRangeTiles: 0,
1159
displayName: "Dyer",
1160
sells: [],
1161
buysItems: true,
1162
hiddenDiscount: 1
1163
}
1164
}];
1165
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
1166
harness.simulation.reloadWorld();
1167
1168
const yellow = dyeItemInstance(
1169
{ r: 240 / 255, g: 210 / 255, b: 40 / 255 },
1170
DEFAULT_DYE_FILL,
1171
FlowerColorId.yellow
1172
);
1173
const magenta = dyeItemInstance(
1174
{ r: 220 / 255, g: 40 / 255, b: 180 / 255 },
1175
DEFAULT_DYE_FILL,
1176
FlowerColorId.magenta
1177
);
1178
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1179
const funded = addCoinsToSlots(emptySlots(), 200);
1180
assert.equal(funded.ok, true);
1181
funded.slots[1] = { itemId: ItemId.dye, quantity: 1, instance: structuredClone(yellow) };
1182
funded.slots[2] = { itemId: ItemId.dye, quantity: 1, instance: structuredClone(magenta) };
1183
harness.stateDb.saveBag(character.character_id, {
1184
inventory: funded.slots,
1185
equipment: emptyEquipment(),
1186
vault: [],
1187
vaultReserved: []
1188
});
1189
const playerId = harness.simulation.spawnCharacter(1, character);
1190
harness.simulation.step();
1191
harness.advance(50);
1192
harness.simulation.step();
1193
1194
const record = harness.simulation.entityRecord(playerId);
1195
const worker = harness.simulation.workers[record.workerId];
1196
let npcId = null;
1197
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
1198
{
1199
if (entity.creature.mobTypeId === MobId.humanoid)
1200
{
1201
npcId = entity.entityId;
1202
break;
1203
}
1204
}
1205
assert.ok(npcId);
1206
const npcHandle = worker.world.ecs.handleOf(npcId);
1207
const shop = worker.world.ecs.get(npcHandle, Component.shop);
1208
const npcPos = worker.world.ecs.get(npcHandle, Component.position);
1209
const playerHandle = worker.world.ecs.handleOf(playerId);
1210
const playerPos = worker.world.ecs.get(playerHandle, Component.position);
1211
playerPos.tileX = npcPos.tileX;
1212
playerPos.tileY = npcPos.tileY;
1213
1214
for (const slotIndex of [1, 2])
1215
{
1216
harness.simulation.enqueue(1, {
1217
type: "sell-to-shop",
1218
characterId: character.character_id,
1219
npcEntityId: npcId,
1220
slotIndex,
1221
quantity: 1
1222
});
1223
const sold = harness.simulation.step();
1224
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
1225
}
1226
1227
const yellowKey = boughtStockKey(ItemId.dye, yellow);
1228
const magentaKey = boughtStockKey(ItemId.dye, magenta);
1229
assert.notEqual(yellowKey, magentaKey);
1230
assert.equal(shop.boughtStock[yellowKey]?.quantity, 1);
1231
assert.equal(shop.boughtStock[magentaKey]?.quantity, 1);
1232
assert.equal(shop.boughtStock[yellowKey]?.instance?.colorId, FlowerColorId.yellow);
1233
assert.equal(shop.boughtStock[magentaKey]?.instance?.colorId, FlowerColorId.magenta);
1234
assert.equal(shop.boughtStock[ItemId.dye], undefined);
1235
1236
harness.simulation.enqueue(1, {
1237
type: "buy-from-shop",
1238
characterId: character.character_id,
1239
npcEntityId: npcId,
1240
itemId: ItemId.dye,
1241
quantity: 1,
1242
listingId: `bought:${magentaKey}`,
1243
source: "bought"
1244
});
1245
const bought = harness.simulation.step();
1246
assert.equal(bought.events.some((event) => event.type === "command-error"), false, JSON.stringify(bought.events));
1247
const bag = harness.simulation.bagOf(playerId);
1248
const dye = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.dye);
1249
assert.ok(dye);
1250
assert.equal(dye.instance?.colorId, FlowerColorId.magenta);
1251
assert.equal(shop.boughtStock[magentaKey], undefined);
1252
assert.equal(shop.boughtStock[yellowKey]?.quantity, 1);
1253
}
1254
finally
1255
{ harness.close(); }
1256
});
@@ -23,9 +23,10 @@ import { Component } from "../src/ecs/components.js";23
import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";23
import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";24
import { ItemOriginKind } from "../../shared/items/origin.js";24
import { ItemOriginKind } from "../../shared/items/origin.js";25
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";25
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";26
import { ensureShopRestocked } from "../src/shop/service.js";26
import { ensureShopRestocked, boughtStockKey } from "../src/shop/service.js";27
import { BlockType } from "../../shared/definitions/tiles.js";27
import { BlockType } from "../../shared/definitions/tiles.js";28
import { GatherOriginVerb, gatherOrigin } from "../../shared/items/origin.js";28
import { GatherOriginVerb, gatherOrigin } from "../../shared/items/origin.js";29
import { dyeItemInstance, DEFAULT_DYE_FILL, FlowerColorId } from "../../shared/definitions/dyes.js";29
30
30
function boughtQty (shop, itemId)31
function boughtQty (shop, itemId)31
{32
{@@ -1139,3 +1140,117 @@ test("NPC letter sales pay out and destroy the letter without stock", () =>1139
finally1140
finally1140
{ harness.close(); }1141
{ harness.close(); }1141
});1142
});1143
1144
test("vendor bought dye stays split by colour and resells that colour", () =>1145
{1146
const harness = makeSimulation({ workerCount: 1 });1147
try1148
{1149
const data = createEmptyChunkData();1150
data.open = true;1151
data.spawners = [{1152
localX: 9,1153
localY: 8,1154
config: {1155
mobTypeId: MobId.humanoid,1156
maxAlive: 1,1157
spawnRangeTiles: 0,1158
maxWanderRangeTiles: 0,1159
displayName: "Dyer",1160
sells: [],1161
buysItems: true,1162
hiddenDiscount: 11163
}1164
}];1165
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));1166
harness.simulation.reloadWorld();1167
1168
const yellow = dyeItemInstance(1169
{ r: 240 / 255, g: 210 / 255, b: 40 / 255 },1170
DEFAULT_DYE_FILL,1171
FlowerColorId.yellow1172
);1173
const magenta = dyeItemInstance(1174
{ r: 220 / 255, g: 40 / 255, b: 180 / 255 },1175
DEFAULT_DYE_FILL,1176
FlowerColorId.magenta1177
);1178
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });1179
const funded = addCoinsToSlots(emptySlots(), 200);1180
assert.equal(funded.ok, true);1181
funded.slots[1] = { itemId: ItemId.dye, quantity: 1, instance: structuredClone(yellow) };1182
funded.slots[2] = { itemId: ItemId.dye, quantity: 1, instance: structuredClone(magenta) };1183
harness.stateDb.saveBag(character.character_id, {1184
inventory: funded.slots,1185
equipment: emptyEquipment(),1186
vault: [],1187
vaultReserved: []1188
});1189
const playerId = harness.simulation.spawnCharacter(1, character);1190
harness.simulation.step();1191
harness.advance(50);1192
harness.simulation.step();1193
1194
const record = harness.simulation.entityRecord(playerId);1195
const worker = harness.simulation.workers[record.workerId];1196
let npcId = null;1197
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))1198
{1199
if (entity.creature.mobTypeId === MobId.humanoid)1200
{1201
npcId = entity.entityId;1202
break;1203
}1204
}1205
assert.ok(npcId);1206
const npcHandle = worker.world.ecs.handleOf(npcId);1207
const shop = worker.world.ecs.get(npcHandle, Component.shop);1208
const npcPos = worker.world.ecs.get(npcHandle, Component.position);1209
const playerHandle = worker.world.ecs.handleOf(playerId);1210
const playerPos = worker.world.ecs.get(playerHandle, Component.position);1211
playerPos.tileX = npcPos.tileX;1212
playerPos.tileY = npcPos.tileY;1213
1214
for (const slotIndex of [1, 2])1215
{1216
harness.simulation.enqueue(1, {1217
type: "sell-to-shop",1218
characterId: character.character_id,1219
npcEntityId: npcId,1220
slotIndex,1221
quantity: 11222
});1223
const sold = harness.simulation.step();1224
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));1225
}1226
1227
const yellowKey = boughtStockKey(ItemId.dye, yellow);1228
const magentaKey = boughtStockKey(ItemId.dye, magenta);1229
assert.notEqual(yellowKey, magentaKey);1230
assert.equal(shop.boughtStock[yellowKey]?.quantity, 1);1231
assert.equal(shop.boughtStock[magentaKey]?.quantity, 1);1232
assert.equal(shop.boughtStock[yellowKey]?.instance?.colorId, FlowerColorId.yellow);1233
assert.equal(shop.boughtStock[magentaKey]?.instance?.colorId, FlowerColorId.magenta);1234
assert.equal(shop.boughtStock[ItemId.dye], undefined);1235
1236
harness.simulation.enqueue(1, {1237
type: "buy-from-shop",1238
characterId: character.character_id,1239
npcEntityId: npcId,1240
itemId: ItemId.dye,1241
quantity: 1,1242
listingId: `bought:${magentaKey}`,1243
source: "bought"1244
});1245
const bought = harness.simulation.step();1246
assert.equal(bought.events.some((event) => event.type === "command-error"), false, JSON.stringify(bought.events));1247
const bag = harness.simulation.bagOf(playerId);1248
const dye = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.dye);1249
assert.ok(dye);1250
assert.equal(dye.instance?.colorId, FlowerColorId.magenta);1251
assert.equal(shop.boughtStock[magentaKey], undefined);1252
assert.equal(shop.boughtStock[yellowKey]?.quantity, 1);1253
}1254
finally1255
{ harness.close(); }1256
});