BlueGit

timfa questward

Files

questward / shared / shop / pricing.js

pricing.js

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