BlueGit

timfa questward

Files

questward / server / src / gifts / service.js

service.js

service.js 5.0 KiB Download Raw
1import { randomUUID } from "node:crypto";
2import { ItemId, itemDefinition, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";
3import { insertStackGrowable, normalizeVault } from "../../../shared/items/inventory.js";
4import { attachOrigins, writtenOrigin } from "../../../shared/items/origin.js";
5import {
6 formatGiftLetterBody,
7 QUESTWARD_GIFT_AUTHOR,
8 QUESTWARD_GIFT_ORG
9} from "../../../shared/courier/giftLetters.js";
10import { giftItemOrigin } from "../../../shared/courier/giftOrigin.js";
11
12function userError (message)
13{
14 const error = new Error(message);
15 error.userFacing = true;
16 return error;
17}
18
19export class GiftService
20{
21 constructor (stateDb, simulation)
22 {
23 this.stateDb = stateDb;
24 this.simulation = simulation;
25 }
26
27 search (query)
28 {
29 const rows = this.stateDb.searchCharactersForGift(query);
30 return {
31 characters: rows.map((row) => ({
32 characterId: row.character_id,
33 firstName: row.first_name,
34 lastName: row.last_name,
35 accountId: row.account_id,
36 accountUsername: row.account_username ?? null
37 }))
38 };
39 }
40
41 /**
42 * Credit gift items to the character bank and queue a signed Questward letter.
43 * @param {{ characterId: number, message?: string, items?: Array<{ itemId: number, quantity: number }> }} payload
44 */
45 sendGift (payload)
46 {
47 const characterId = payload?.characterId | 0;
48 const character = this.stateDb.getCharacter(characterId);
49 if (!character)
50 { throw userError("Character not found."); }
51
52 const items = normalizeGiftItems(payload?.items);
53 if (!items.length)
54 { throw userError("Pick at least one item to gift."); }
55
56 const message = String(payload?.message ?? "").replace(/\r\n/g, "\n").trim();
57 if (message.length > LETTER_MAX_BODY_CHARS)
58 { throw userError("Gift message is too long."); }
59
60 const displayName = `${character.first_name} ${character.last_name}`.trim();
61 const credited = [];
62 for (const entry of items)
63 {
64 const def = itemDefinition(entry.itemId);
65 if (!def)
66 { throw userError(`Unknown item ${entry.itemId}.`); }
67 const stack = attachOrigins({
68 itemId: entry.itemId,
69 quantity: entry.quantity,
70 origins: [{ origin: giftItemOrigin(entry.itemId), quantity: entry.quantity }]
71 });
72 this.#creditBank(characterId, stack, def);
73 credited.push({
74 itemId: entry.itemId,
75 quantity: entry.quantity,
76 displayName: def.displayName ?? `Item ${entry.itemId}`
77 });
78 }
79
80 const body = formatGiftLetterBody({
81 characterDisplayName: displayName,
82 message,
83 items: credited
84 });
85 this.#dispatchGiftLetter(character, body);
86
87 return {
88 ok: true,
89 characterId,
90 firstName: character.first_name,
91 lastName: character.last_name,
92 items: credited
93 };
94 }
95
96 #creditBank (characterId, stack, def)
97 {
98 const bag = this.#loadBag(characterId);
99 if (!bag)
100 { throw userError("Character bag not found."); }
101 const vault = normalizeVault(
102 bag.vaultReserved != null
103 ? { slots: bag.vault, reserved: bag.vaultReserved }
104 : bag.vault
105 );
106 const result = insertStackGrowable(vault.slots, stack, def);
107 if ((result.remainder | 0) > 0)
108 { throw userError("That character's bank is full."); }
109 bag.vault = result.slots;
110 bag.vaultReserved = vault.reserved;
111 this.#persistBag(characterId, bag);
112 }
113
114 #dispatchGiftLetter (character, body)
115 {
116 const trimmed = String(body ?? "").replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
117 const stack = attachOrigins({
118 itemId: ItemId.letter,
119 quantity: 1,
120 origins: [{ origin: writtenOrigin(QUESTWARD_GIFT_AUTHOR), quantity: 1 }],
121 instance: {
122 kind: "letter",
123 letterId: randomUUID(),
124 authorCharacterId: 0,
125 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
126 authorOrganization: QUESTWARD_GIFT_ORG,
127 body: trimmed,
128 opened: false,
129 writtenAt: Date.now()
130 }
131 });
132 const originTileX = character.tile_x | 0;
133 const originTileY = character.tile_y | 0;
134 const bank = this.simulation.courier?.nearestBank?.(originTileX, originTileY);
135 this.simulation.courier.dispatchSystemLetter({
136 characterId: character.character_id,
137 originTileX: bank?.tileX ?? originTileX,
138 originTileY: bank?.tileY ?? originTileY,
139 stack
140 });
141 }
142
143 #loadBag (characterId)
144 {
145 const onlineId = this.simulation.characterEntities.get(characterId | 0);
146 return onlineId
147 ? this.simulation.bagOf(onlineId)
148 : this.stateDb.getBag(characterId);
149 }
150
151 #persistBag (characterId, bag)
152 {
153 this.stateDb.saveBag(characterId, bag);
154 const onlineId = this.simulation.characterEntities.get(characterId | 0);
155 if (onlineId)
156 {
157 this.simulation.applyBag?.(onlineId, bag);
158 this.simulation.pushInventory?.(characterId, bag);
159 }
160 }
161}
162
163function normalizeGiftItems (raw)
164{
165 if (!Array.isArray(raw))
166 { return []; }
167 /** @type {Map<number, number>} */
168 const merged = new Map();
169 for (const row of raw)
170 {
171 const itemId = row?.itemId | 0;
172 const quantity = Math.max(1, Math.min(100_000, row?.quantity | 0 || 1));
173 if (!itemId || !itemDefinition(itemId))
174 { continue; }
175 merged.set(itemId, (merged.get(itemId) ?? 0) + quantity);
176 }
177 return [...merged.entries()].map(([itemId, quantity]) => ({ itemId, quantity }));
178}