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