BlueGit

timfa questward

Files

questward / server / src / gifts / service.js

service.js

service.js 8.8 KiB Download Raw
1import { randomUUID } from "node:crypto";
2import { ItemId, itemDefinition, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";
3import { alchemyPotionDefinition } from "../../../shared/definitions/alchemy.js";
4import { recipePaperBody, potionItemInstance } from "../../../shared/alchemy/recipes.js";
5import {
6 normalizeBuyListingKey,
7 potionKeyFromListingKey,
8 potionKeyFromPotionListingKey,
9 recipePaperDisplayName
10} from "../../../shared/market/listingKey.js";
11import { insertStackGrowable, normalizeVault } from "../../../shared/items/inventory.js";
12import { stackRulesFor } from "../../../shared/items/stackRules.js";
13import { attachOrigins, writtenOrigin } from "../../../shared/items/origin.js";
14import {
15 formatGiftLetterBody,
16 QUESTWARD_GIFT_AUTHOR,
17 QUESTWARD_GIFT_ORG
18} from "../../../shared/courier/giftLetters.js";
19import { giftItemOrigin } from "../../../shared/courier/giftOrigin.js";
20
21function userError (message)
22{
23 const error = new Error(message);
24 error.userFacing = true;
25 return error;
26}
27
28export class GiftService
29{
30 constructor (stateDb, simulation)
31 {
32 this.stateDb = stateDb;
33 this.simulation = simulation;
34 }
35
36 search (query)
37 {
38 const rows = this.stateDb.searchCharactersForGift(query);
39 return {
40 characters: rows.map((row) => ({
41 characterId: row.character_id,
42 firstName: row.first_name,
43 lastName: row.last_name,
44 accountId: row.account_id,
45 accountUsername: row.account_username ?? null
46 }))
47 };
48 }
49
50 /**
51 * Credit gift items to the character bank and queue a signed Questward letter.
52 * @param {{
53 * characterId: number,
54 * message?: string,
55 * items?: Array<{ itemId: number, quantity: number, listingKey?: string|null, potionKey?: string|null }>
56 * }} payload
57 */
58 sendGift (payload)
59 {
60 const characterId = payload?.characterId | 0;
61 const character = this.stateDb.getCharacter(characterId);
62 if (!character)
63 { throw userError("Character not found."); }
64
65 const items = normalizeGiftItems(payload?.items);
66 if (!items.length)
67 { throw userError("Pick at least one item to gift."); }
68
69 const message = String(payload?.message ?? "").replace(/\r\n/g, "\n").trim();
70 if (message.length > LETTER_MAX_BODY_CHARS)
71 { throw userError("Gift message is too long."); }
72
73 const displayName = `${character.first_name} ${character.last_name}`.trim();
74 const credited = [];
75 for (const entry of items)
76 {
77 const def = itemDefinition(entry.itemId);
78 if (!def)
79 { throw userError(`Unknown item ${entry.itemId}.`); }
80 if (entry.itemId === ItemId.recipePaper)
81 {
82 const potion = alchemyPotionDefinition(entry.potionKey);
83 if (!potion)
84 { throw userError("Pick a specific alchemy recipe, not blank recipe paper."); }
85 const paperName = recipePaperDisplayName(entry.potionKey);
86 for (let i = 0; i < entry.quantity; i++)
87 {
88 const stack = attachOrigins({
89 itemId: ItemId.recipePaper,
90 quantity: 1,
91 origins: [{ origin: writtenOrigin(QUESTWARD_GIFT_AUTHOR), quantity: 1 }],
92 instance: {
93 kind: "recipe-paper",
94 recipeId: randomUUID(),
95 potionKey: entry.potionKey,
96 displayName: paperName,
97 authorCharacterId: 0,
98 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
99 minAlchemyLevel: potion.minAlchemyLevel ?? 1,
100 body: recipePaperBody(potion),
101 writtenAt: Date.now()
102 }
103 });
104 this.#creditBank(characterId, stack, def);
105 }
106 credited.push({
107 itemId: entry.itemId,
108 quantity: entry.quantity,
109 displayName: paperName,
110 potionKey: entry.potionKey
111 });
112 continue;
113 }
114
115 if (entry.itemId === ItemId.potion)
116 {
117 const potion = alchemyPotionDefinition(entry.potionKey);
118 if (!potion || potion.outputItemId)
119 { throw userError("Pick a specific potion brew, not a blank potion bottle."); }
120 const instance = potionItemInstance({
121 potionKey: potion.potionKey,
122 unstable: false,
123 displayName: potion.displayName,
124 color: potion.color,
125 fillLevel: potion.fillLevel,
126 effect: potion.effect,
127 effectKey: potion.effect?.type ?? potion.potionKey,
128 minAlchemyLevel: potion.minAlchemyLevel ?? 1
129 });
130 const stack = attachOrigins({
131 itemId: ItemId.potion,
132 quantity: entry.quantity,
133 instance,
134 origins: [{ origin: giftItemOrigin(ItemId.potion), quantity: entry.quantity }]
135 });
136 this.#creditBank(characterId, stack, def);
137 credited.push({
138 itemId: entry.itemId,
139 quantity: entry.quantity,
140 displayName: potion.displayName,
141 potionKey: entry.potionKey
142 });
143 continue;
144 }
145
146 const rules = stackRulesFor(def, { inVault: true });
147 if (rules.uniqueInstance || !rules.stackable)
148 {
149 for (let i = 0; i < entry.quantity; i++)
150 {
151 const stack = attachOrigins({
152 itemId: entry.itemId,
153 quantity: 1,
154 origins: [{ origin: giftItemOrigin(entry.itemId), quantity: 1 }]
155 });
156 this.#creditBank(characterId, stack, def);
157 }
158 }
159 else
160 {
161 const stack = attachOrigins({
162 itemId: entry.itemId,
163 quantity: entry.quantity,
164 origins: [{ origin: giftItemOrigin(entry.itemId), quantity: entry.quantity }]
165 });
166 this.#creditBank(characterId, stack, def);
167 }
168 credited.push({
169 itemId: entry.itemId,
170 quantity: entry.quantity,
171 displayName: def.displayName ?? `Item ${entry.itemId}`
172 });
173 }
174
175 const body = formatGiftLetterBody({
176 characterDisplayName: displayName,
177 message,
178 items: credited
179 });
180 this.#dispatchGiftLetter(character, body);
181
182 return {
183 ok: true,
184 characterId,
185 firstName: character.first_name,
186 lastName: character.last_name,
187 items: credited
188 };
189 }
190
191 #creditBank (characterId, stack, def)
192 {
193 const bag = this.#loadBag(characterId);
194 if (!bag)
195 { throw userError("Character bag not found."); }
196 const vault = normalizeVault(
197 bag.vaultReserved != null
198 ? { slots: bag.vault, reserved: bag.vaultReserved }
199 : bag.vault
200 );
201 const result = insertStackGrowable(vault.slots, stack, def);
202 if ((result.remainder | 0) > 0)
203 { throw userError("That character's bank is full."); }
204 bag.vault = result.slots;
205 bag.vaultReserved = vault.reserved;
206 this.#persistBag(characterId, bag);
207 }
208
209 #dispatchGiftLetter (character, body)
210 {
211 const originTileX = character.tile_x | 0;
212 const originTileY = character.tile_y | 0;
213 const originDim = character.dimension_id ?? undefined;
214 const bank = this.simulation.courier?.nearestBank?.(originTileX, originTileY, originDim);
215 this.simulation.courier.enqueueSystemLetter({
216 characterId: character.character_id,
217 originTileX: bank?.tileX ?? originTileX,
218 originTileY: bank?.tileY ?? originTileY,
219 originDimensionId: bank?.dimensionId ?? originDim,
220 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
221 authorOrganization: QUESTWARD_GIFT_ORG,
222 body
223 });
224 }
225
226 #loadBag (characterId)
227 {
228 const onlineId = this.simulation.characterEntities.get(characterId | 0);
229 return onlineId
230 ? this.simulation.bagOf(onlineId)
231 : this.stateDb.getBag(characterId);
232 }
233
234 #persistBag (characterId, bag)
235 {
236 this.stateDb.saveBag(characterId, bag);
237 const onlineId = this.simulation.characterEntities.get(characterId | 0);
238 if (onlineId)
239 {
240 this.simulation.applyBag?.(onlineId, bag);
241 this.simulation.pushInventory?.(characterId, bag);
242 }
243 }
244}
245
246function normalizeGiftItems (raw)
247{
248 if (!Array.isArray(raw))
249 { return []; }
250 /** @type {Map<string, { itemId: number, quantity: number, potionKey?: string|null }>} */
251 const merged = new Map();
252 for (const row of raw)
253 {
254 const itemId = row?.itemId | 0;
255 const quantity = Math.max(1, Math.min(100_000, row?.quantity | 0 || 1));
256 if (!itemId || !itemDefinition(itemId))
257 { continue; }
258 if (itemId === ItemId.recipePaper)
259 {
260 const listingKey = normalizeBuyListingKey(itemId, row?.listingKey ?? null);
261 const potionKey = String(row?.potionKey ?? "").trim()
262 || potionKeyFromListingKey(listingKey)
263 || "";
264 if (!potionKey || !alchemyPotionDefinition(potionKey))
265 { continue; }
266 const key = `recipe:${potionKey}`;
267 const prev = merged.get(key);
268 if (prev)
269 { prev.quantity += quantity; }
270 else
271 {
272 merged.set(key, {
273 itemId,
274 quantity,
275 potionKey
276 });
277 }
278 continue;
279 }
280 if (itemId === ItemId.potion)
281 {
282 const listingKey = normalizeBuyListingKey(itemId, row?.listingKey ?? null);
283 const potionKey = String(row?.potionKey ?? "").trim()
284 || potionKeyFromPotionListingKey(listingKey)
285 || "";
286 const potion = potionKey ? alchemyPotionDefinition(potionKey) : null;
287 if (!potion || potion.outputItemId)
288 { continue; }
289 const key = `potion:${potionKey}`;
290 const prev = merged.get(key);
291 if (prev)
292 { prev.quantity += quantity; }
293 else
294 {
295 merged.set(key, {
296 itemId,
297 quantity,
298 potionKey
299 });
300 }
301 continue;
302 }
303 const key = `item:${itemId}`;
304 const prev = merged.get(key);
305 if (prev)
306 { prev.quantity += quantity; }
307 else
308 { merged.set(key, { itemId, quantity, potionKey: null }); }
309 }
310 return [...merged.values()];
311}