BlueGit

timfa questward

Files

questward / shared / shop / pricing.js

pricing.js

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