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