import { randomUUID } from "node:crypto"; import { ItemId, itemDefinition, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js"; import { insertStackGrowable, normalizeVault } from "../../../shared/items/inventory.js"; import { attachOrigins, writtenOrigin } from "../../../shared/items/origin.js"; import { formatGiftLetterBody, QUESTWARD_GIFT_AUTHOR, QUESTWARD_GIFT_ORG } from "../../../shared/courier/giftLetters.js"; import { giftItemOrigin } from "../../../shared/courier/giftOrigin.js"; function userError (message) { const error = new Error(message); error.userFacing = true; return error; } export class GiftService { constructor (stateDb, simulation) { this.stateDb = stateDb; this.simulation = simulation; } search (query) { const rows = this.stateDb.searchCharactersForGift(query); return { characters: rows.map((row) => ({ characterId: row.character_id, firstName: row.first_name, lastName: row.last_name, accountId: row.account_id, accountUsername: row.account_username ?? null })) }; } /** * Credit gift items to the character bank and queue a signed Questward letter. * @param {{ characterId: number, message?: string, items?: Array<{ itemId: number, quantity: number }> }} payload */ sendGift (payload) { const characterId = payload?.characterId | 0; const character = this.stateDb.getCharacter(characterId); if (!character) { throw userError("Character not found."); } const items = normalizeGiftItems(payload?.items); if (!items.length) { throw userError("Pick at least one item to gift."); } const message = String(payload?.message ?? "").replace(/\r\n/g, "\n").trim(); if (message.length > LETTER_MAX_BODY_CHARS) { throw userError("Gift message is too long."); } const displayName = `${character.first_name} ${character.last_name}`.trim(); const credited = []; for (const entry of items) { const def = itemDefinition(entry.itemId); if (!def) { throw userError(`Unknown item ${entry.itemId}.`); } const stack = attachOrigins({ itemId: entry.itemId, quantity: entry.quantity, origins: [{ origin: giftItemOrigin(entry.itemId), quantity: entry.quantity }] }); this.#creditBank(characterId, stack, def); credited.push({ itemId: entry.itemId, quantity: entry.quantity, displayName: def.displayName ?? `Item ${entry.itemId}` }); } const body = formatGiftLetterBody({ characterDisplayName: displayName, message, items: credited }); this.#dispatchGiftLetter(character, body); return { ok: true, characterId, firstName: character.first_name, lastName: character.last_name, items: credited }; } #creditBank (characterId, stack, def) { const bag = this.#loadBag(characterId); if (!bag) { throw userError("Character bag not found."); } const vault = normalizeVault( bag.vaultReserved != null ? { slots: bag.vault, reserved: bag.vaultReserved } : bag.vault ); const result = insertStackGrowable(vault.slots, stack, def); if ((result.remainder | 0) > 0) { throw userError("That character's bank is full."); } bag.vault = result.slots; bag.vaultReserved = vault.reserved; this.#persistBag(characterId, bag); } #dispatchGiftLetter (character, body) { const trimmed = String(body ?? "").replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS); const stack = attachOrigins({ itemId: ItemId.letter, quantity: 1, origins: [{ origin: writtenOrigin(QUESTWARD_GIFT_AUTHOR), quantity: 1 }], instance: { kind: "letter", letterId: randomUUID(), authorCharacterId: 0, authorDisplayName: QUESTWARD_GIFT_AUTHOR, authorOrganization: QUESTWARD_GIFT_ORG, body: trimmed, opened: false, writtenAt: Date.now() } }); const originTileX = character.tile_x | 0; const originTileY = character.tile_y | 0; const bank = this.simulation.courier?.nearestBank?.(originTileX, originTileY); this.simulation.courier.dispatchSystemLetter({ characterId: character.character_id, originTileX: bank?.tileX ?? originTileX, originTileY: bank?.tileY ?? originTileY, stack }); } #loadBag (characterId) { const onlineId = this.simulation.characterEntities.get(characterId | 0); return onlineId ? this.simulation.bagOf(onlineId) : this.stateDb.getBag(characterId); } #persistBag (characterId, bag) { this.stateDb.saveBag(characterId, bag); const onlineId = this.simulation.characterEntities.get(characterId | 0); if (onlineId) { this.simulation.applyBag?.(onlineId, bag); this.simulation.pushInventory?.(characterId, bag); } } } function normalizeGiftItems (raw) { if (!Array.isArray(raw)) { return []; } /** @type {Map} */ const merged = new Map(); for (const row of raw) { const itemId = row?.itemId | 0; const quantity = Math.max(1, Math.min(100_000, row?.quantity | 0 || 1)); if (!itemId || !itemDefinition(itemId)) { continue; } merged.set(itemId, (merged.get(itemId) ?? 0) + quantity); } return [...merged.entries()].map(([itemId, quantity]) => ({ itemId, quantity })); }