import { randomUUID } from "node:crypto"; import { ItemId, itemDefinition, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js"; import { alchemyPotionDefinition } from "../../../shared/definitions/alchemy.js"; import { recipePaperBody, potionItemInstance } from "../../../shared/alchemy/recipes.js"; import { normalizeBuyListingKey, potionKeyFromListingKey, potionKeyFromPotionListingKey, recipePaperDisplayName } from "../../../shared/market/listingKey.js"; import { insertStackGrowable, normalizeVault } from "../../../shared/items/inventory.js"; import { stackRulesFor } from "../../../shared/items/stackRules.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, listingKey?: string|null, potionKey?: string|null }> * }} 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}.`); } if (entry.itemId === ItemId.recipePaper) { const potion = alchemyPotionDefinition(entry.potionKey); if (!potion) { throw userError("Pick a specific alchemy recipe, not blank recipe paper."); } const paperName = recipePaperDisplayName(entry.potionKey); for (let i = 0; i < entry.quantity; i++) { const stack = attachOrigins({ itemId: ItemId.recipePaper, quantity: 1, origins: [{ origin: writtenOrigin(QUESTWARD_GIFT_AUTHOR), quantity: 1 }], instance: { kind: "recipe-paper", recipeId: randomUUID(), potionKey: entry.potionKey, displayName: paperName, authorCharacterId: 0, authorDisplayName: QUESTWARD_GIFT_AUTHOR, minAlchemyLevel: potion.minAlchemyLevel ?? 1, body: recipePaperBody(potion), writtenAt: Date.now() } }); this.#creditBank(characterId, stack, def); } credited.push({ itemId: entry.itemId, quantity: entry.quantity, displayName: paperName, potionKey: entry.potionKey }); continue; } if (entry.itemId === ItemId.potion) { const potion = alchemyPotionDefinition(entry.potionKey); if (!potion || potion.outputItemId) { throw userError("Pick a specific potion brew, not a blank potion bottle."); } const instance = potionItemInstance({ potionKey: potion.potionKey, unstable: false, displayName: potion.displayName, color: potion.color, fillLevel: potion.fillLevel, effect: potion.effect, effectKey: potion.effect?.type ?? potion.potionKey, minAlchemyLevel: potion.minAlchemyLevel ?? 1 }); const stack = attachOrigins({ itemId: ItemId.potion, quantity: entry.quantity, instance, origins: [{ origin: giftItemOrigin(ItemId.potion), quantity: entry.quantity }] }); this.#creditBank(characterId, stack, def); credited.push({ itemId: entry.itemId, quantity: entry.quantity, displayName: potion.displayName, potionKey: entry.potionKey }); continue; } const rules = stackRulesFor(def, { inVault: true }); if (rules.uniqueInstance || !rules.stackable) { for (let i = 0; i < entry.quantity; i++) { const stack = attachOrigins({ itemId: entry.itemId, quantity: 1, origins: [{ origin: giftItemOrigin(entry.itemId), quantity: 1 }] }); this.#creditBank(characterId, stack, def); } } else { 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 originTileX = character.tile_x | 0; const originTileY = character.tile_y | 0; const originDim = character.dimension_id ?? undefined; const bank = this.simulation.courier?.nearestBank?.(originTileX, originTileY, originDim); this.simulation.courier.enqueueSystemLetter({ characterId: character.character_id, originTileX: bank?.tileX ?? originTileX, originTileY: bank?.tileY ?? originTileY, originDimensionId: bank?.dimensionId ?? originDim, authorDisplayName: QUESTWARD_GIFT_AUTHOR, authorOrganization: QUESTWARD_GIFT_ORG, body }); } #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; } if (itemId === ItemId.recipePaper) { const listingKey = normalizeBuyListingKey(itemId, row?.listingKey ?? null); const potionKey = String(row?.potionKey ?? "").trim() || potionKeyFromListingKey(listingKey) || ""; if (!potionKey || !alchemyPotionDefinition(potionKey)) { continue; } const key = `recipe:${potionKey}`; const prev = merged.get(key); if (prev) { prev.quantity += quantity; } else { merged.set(key, { itemId, quantity, potionKey }); } continue; } if (itemId === ItemId.potion) { const listingKey = normalizeBuyListingKey(itemId, row?.listingKey ?? null); const potionKey = String(row?.potionKey ?? "").trim() || potionKeyFromPotionListingKey(listingKey) || ""; const potion = potionKey ? alchemyPotionDefinition(potionKey) : null; if (!potion || potion.outputItemId) { continue; } const key = `potion:${potionKey}`; const prev = merged.get(key); if (prev) { prev.quantity += quantity; } else { merged.set(key, { itemId, quantity, potionKey }); } continue; } const key = `item:${itemId}`; const prev = merged.get(key); if (prev) { prev.quantity += quantity; } else { merged.set(key, { itemId, quantity, potionKey: null }); } } return [...merged.values()]; }