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