BlueGit

timfa questward

Files

questward / server / src / gifts / service.js

service.js

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