BlueGit

timfa questward

Files

questward / shared / shop / pricing.js

pricing.js

pricing.js 8.9 KiB Download Raw
1/**
2 * Shop / tooltip pricing from seedValue and optional player-market last sale.
3 * Matches design §27.6 — lerp toward lastTradePrice over shopPriceLerpDurationMs.
4 */
5
6import { ItemId, itemDefinition, ITEM_DEFINITIONS } from "../definitions/items.js";
7import { ItemCategory } from "../definitions/itemCategories.js";
8import { DEFAULT_WORLD_SETTINGS } from "../protocol/constants.js";
9
10export function lerp (a, b, t)
11{
12 return a + (b - a) * t;
13}
14
15/** Normalize sparse itemId → seed overrides from world settings. */
16export function normalizeItemSeedValues (raw)
17{
18 const out = {};
19 if (!raw || typeof raw !== "object")
20 { return out; }
21 for (const [key, value] of Object.entries(raw))
22 {
23 const itemId = Number(key);
24 if (!Number.isInteger(itemId) || itemId <= 0 || !itemDefinition(itemId))
25 { continue; }
26 const seed = Math.round(Number(value));
27 if (!Number.isFinite(seed))
28 { continue; }
29 const defSeed = Math.max(1, Number(itemDefinition(itemId)?.seedValue) || 1);
30 const next = Math.max(1, seed);
31 // Only store overrides that differ from the item definition default.
32 if (next !== defSeed)
33 { out[String(itemId)] = next; }
34 }
35 return out;
36}
37
38/** Effective world seed for an item (override or definition). */
39export function effectiveSeedValue (itemId, settings = null)
40{
41 const def = itemDefinition(itemId);
42 const defSeed = Math.max(1, Number(def?.seedValue) || 1);
43 const overrides = settings?.itemSeedValues;
44 if (!overrides || typeof overrides !== "object")
45 { return defSeed; }
46 const key = String(itemId | 0);
47 if (!Object.prototype.hasOwnProperty.call(overrides, key)
48 && !Object.prototype.hasOwnProperty.call(overrides, itemId | 0))
49 { return defSeed; }
50 const raw = overrides[key] ?? overrides[itemId | 0];
51 const seed = Math.round(Number(raw));
52 if (!Number.isFinite(seed))
53 { return defSeed; }
54 return Math.max(1, seed);
55}
56
57/**
58 * @param {object|null} lastSale `{ lastTradePrice, lastTradeAt, priceFrom }`
59 * @param {object|null} settings world settings (reads itemSeedValues + lerp duration)
60 */
61export function undiscountedMarketValue (
62 itemId,
63 lastSale = null,
64 now = Date.now(),
65 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
66 settings = null
67)
68{
69 const seed = effectiveSeedValue(itemId, settings);
70 if (!lastSale?.lastTradeAt || lastSale.lastTradePrice == null)
71 { return seed; }
72 const duration = Math.max(
73 1,
74 Number(lerpDurationMs)
75 || Number(settings?.shopPriceLerpDurationMs)
76 || DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs
77 );
78 const t = Math.min(1, Math.max(0, (now - lastSale.lastTradeAt) / duration));
79 const from = lastSale.priceFrom != null ? Number(lastSale.priceFrom) : seed;
80 const to = Number(lastSale.lastTradePrice);
81 if (!Number.isFinite(from) || !Number.isFinite(to))
82 { return seed; }
83 return lerp(from, to, t);
84}
85
86/** Integer shop purchase price (player buying catalog stock). */
87export function shopUnitPrice (itemId, {
88 lastSale = null,
89 now = Date.now(),
90 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
91 hiddenDiscount = 1,
92 settings = null
93} = {})
94{
95 const undiscounted = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings);
96 const discount = Math.min(1, Math.max(0.01, Number(hiddenDiscount) || 1));
97 return Math.max(1, Math.round(undiscounted * discount));
98}
99
100/** NPC pays the player this much when buying (80% of market). */
101export function shopBuyFromPlayerPrice (itemId, {
102 lastSale = null,
103 now = Date.now(),
104 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
105 settings = null
106} = {})
107{
108 return Math.max(1, Math.round(undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 0.8));
109}
110
111/** Resale price for goods the NPC bought from players today (120% of market). */
112export function shopBoughtResalePrice (itemId, {
113 lastSale = null,
114 now = Date.now(),
115 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
116 settings = null
117} = {})
118{
119 return Math.max(1, Math.round(undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 1.2));
120}
121
122/**
123 * Editor / tooltip snapshot for one item.
124 * `marketKnown` is true when a last-sale record exists; otherwise market equals seed.
125 */
126export function itemPriceSnapshot (itemId, {
127 settings = null,
128 lastSale = null,
129 now = Date.now(),
130 hiddenDiscount = 1
131} = {})
132{
133 const def = itemDefinition(itemId);
134 if (!def)
135 { return null; }
136 const lerpDurationMs = settings?.shopPriceLerpDurationMs
137 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
138 const seedValue = effectiveSeedValue(itemId, settings);
139 const marketKnown = !!(lastSale?.lastTradeAt && lastSale.lastTradePrice != null);
140 const marketValue = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings);
141 const shopPrice = shopUnitPrice(itemId, {
142 lastSale,
143 now,
144 lerpDurationMs,
145 hiddenDiscount,
146 settings
147 });
148 return {
149 itemId: def.itemId,
150 displayName: def.displayName ?? String(def.itemId),
151 key: def.key ?? String(def.itemId),
152 definitionSeedValue: Math.max(1, Number(def.seedValue) || 1),
153 seedValue,
154 marketValue: Math.max(1, Math.round(marketValue)),
155 marketKnown,
156 shopPrice
157 };
158}
159
160/** All items with a price row for the base-prices editor. */
161export function listPricedItems ()
162{
163 return Object.values(ITEM_DEFINITIONS)
164 .filter((def) => def?.itemId != null && def.seedValue != null)
165 .map((def) => ({
166 itemId: def.itemId,
167 displayName: def.displayName ?? String(def.itemId),
168 key: def.key ?? String(def.itemId),
169 definitionSeedValue: Math.max(1, Number(def.seedValue) || 1)
170 }))
171 .sort((a, b) => a.displayName.localeCompare(b.displayName));
172}
173
174/** NPC shops sell ingredients (and items explicitly flagged) in their catalog. */
175export function canSellInNpcShop (itemId)
176{
177 const def = itemDefinition(itemId);
178 if (!def)
179 { return false; }
180 if (def.npcShopAllowed === false)
181 { return false; }
182 if (def.npcShopAllowed === true)
183 { return true; }
184 return def.category === ItemCategory.ingredient || def.category === "ingredient";
185}
186
187/**
188 * What a buysItems shopkeeper will purchase from a player bag slot.
189 * All transferable goods except blank cheques (and coins).
190 * Filled cheques are sold as their reserved goods (+ admin fee).
191 */
192export function canPlayerSellToNpc (stack)
193{
194 if (!stack?.itemId)
195 { return false; }
196 const itemId = stack.itemId | 0;
197 if (itemId === ItemId.blankCheque || itemId === ItemId.coins)
198 { return false; }
199 if (itemId === ItemId.filledCheque)
200 {
201 const instance = stack.instance;
202 if (instance?.kind !== "filled-cheque")
203 { return false; }
204 const goodsId = instance.itemId | 0;
205 return goodsId > 0 && !!itemDefinition(goodsId) && goodsId !== ItemId.coins;
206 }
207 return !!itemDefinition(itemId);
208}
209
210/** Administrative fee rate when selling a filled cheque to an NPC. */
211export const CHEQUE_SHOP_ADMIN_FEE_RATE = 0.05;
212
213/** Fee deducted from cheque shop payout (5% of base, rounded up). */
214export function shopChequeAdminFee (basePayout)
215{
216 const base = Math.max(0, Math.round(Number(basePayout)) || 0);
217 if (base <= 0)
218 { return 0; }
219 return Math.ceil(base * CHEQUE_SHOP_ADMIN_FEE_RATE);
220}
221
222/**
223 * Quote for selling one bag unit (or one filled cheque) to a buysItems NPC.
224 * @returns {null | {
225 * isCheque: boolean,
226 * goodsItemId: number,
227 * goodsQuantity: number,
228 * unitPrice: number,
229 * baseTotal: number,
230 * adminFee: number,
231 * payout: number
232 * }}
233 */
234export function resolveShopSellQuote (stack, {
235 lastSale = null,
236 now = Date.now(),
237 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
238 settings = null,
239 quantity = 1
240} = {})
241{
242 if (!canPlayerSellToNpc(stack))
243 { return null; }
244 if ((stack.itemId | 0) === ItemId.filledCheque)
245 {
246 const goodsItemId = stack.instance.itemId | 0;
247 const goodsQuantity = Math.max(1, stack.instance.quantity | 0);
248 const unitPrice = shopBuyFromPlayerPrice(goodsItemId, {
249 lastSale,
250 now,
251 lerpDurationMs,
252 settings
253 });
254 const baseTotal = unitPrice * goodsQuantity;
255 const adminFee = shopChequeAdminFee(baseTotal);
256 return {
257 isCheque: true,
258 goodsItemId,
259 goodsQuantity,
260 unitPrice,
261 baseTotal,
262 adminFee,
263 payout: Math.max(0, baseTotal - adminFee)
264 };
265 }
266 const goodsItemId = stack.itemId | 0;
267 const goodsQuantity = Math.max(1, Math.min(stack.quantity | 0 || 1, quantity | 0 || 1));
268 const unitPrice = shopBuyFromPlayerPrice(goodsItemId, {
269 lastSale,
270 now,
271 lerpDurationMs,
272 settings
273 });
274 const baseTotal = unitPrice * goodsQuantity;
275 return {
276 isCheque: false,
277 goodsItemId,
278 goodsQuantity,
279 unitPrice,
280 baseTotal,
281 adminFee: 0,
282 payout: baseTotal
283 };
284}
285
286/** Items the editor may add to a shopkeeper sells list. */
287export function listNpcShopSellableItems ()
288{
289 return Object.values(ITEM_DEFINITIONS)
290 .filter((def) => canSellInNpcShop(def.itemId))
291 .map((def) => ({
292 itemId: def.itemId,
293 displayName: def.displayName ?? String(def.itemId),
294 key: def.key ?? String(def.itemId)
295 }))
296 .sort((a, b) => a.displayName.localeCompare(b.displayName));
297}
298
299/** Calendar day key used for midnight shop restock (UTC). */
300export function shopRestockDayKey (now = Date.now())
301{
302 return new Date(now).toISOString().slice(0, 10);
303}