BlueGit

timfa questward

Files

questward / server / src / courier / service.js

service.js

service.js 22.3 KiB Download Raw
1import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";
6import { attachOrigins, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";
7import { advanceCourierFlight } from "../../../shared/courier/flight.js";
8import { GAIT } from "../../../shared/protocol/constants.js";
9import { decodeChunkBlob } from "../world/chunkData.js";
10import { findReservedChequeIndex } from "../items/bags.js";
11import { randomUUID } from "node:crypto";
12import {
13 BANK_LETTER_AUTHOR,
14 bankRestNoticeLetterBody,
15 isBankRestNoticeLetter,
16 isCentralExchangeLetter,
17 itemNameForNotice,
18 mergeBankRestNoticeLines,
19 sourceNameForVaultDeposit
20} from "../../../shared/courier/bankNotice.js";
21
22export class CourierService
23{
24 constructor ({ stateDb, worldDb, simulation })
25 {
26 this.stateDb = stateDb;
27 this.worldDb = worldDb;
28 this.simulation = simulation;
29 this.bankTiles = [];
30 this.bountyOfficeTiles = [];
31 this.refreshBankIndex();
32 this.refreshBountyOfficeIndex();
33 }
34
35 refreshBankIndex ()
36 {
37 this.bankTiles = this.#listBlockTiles(BlockType.bank);
38 }
39
40 refreshBountyOfficeIndex ()
41 {
42 this.bountyOfficeTiles = this.#listBlockTiles(BlockType.bountyOffice);
43 }
44
45 #listBlockTiles (typeId)
46 {
47 const revisionId = this.worldDb.getActiveRevisionId();
48 const tiles = [];
49 for (const coord of this.worldDb.listChunkCoords(revisionId))
50 {
51 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
52 if (!row)
53 { continue; }
54 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
55 for (let localY = 0; localY < CHUNK_SIZE; localY++)
56 {
57 for (let localX = 0; localX < CHUNK_SIZE; localX++)
58 {
59 const block = data.blocks[localY * CHUNK_SIZE + localX];
60 if (block?.typeId !== typeId)
61 { continue; }
62 tiles.push({
63 tileX: coord.chunk_x * CHUNK_SIZE + localX,
64 tileY: coord.chunk_y * CHUNK_SIZE + localY
65 });
66 }
67 }
68 }
69 return tiles;
70 }
71
72 nearestBank (tileX, tileY)
73 {
74 return this.#nearestTile(this.bankTiles, tileX, tileY);
75 }
76
77 nearestBountyOffice (tileX, tileY)
78 {
79 return this.#nearestTile(this.bountyOfficeTiles, tileX, tileY);
80 }
81
82 isAdjacentToBountyOffice (tileX, tileY)
83 {
84 return this.bountyOfficeTiles.some((office) =>
85 Math.max(Math.abs(office.tileX - tileX), Math.abs(office.tileY - tileY)) <= 1);
86 }
87
88 #nearestTile (tiles, tileX, tileY)
89 {
90 if (!tiles.length)
91 { return null; }
92 let best = null;
93 let bestDist = Infinity;
94 for (const tile of tiles)
95 {
96 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
97 if (dist < bestDist)
98 {
99 bestDist = dist;
100 best = tile;
101 }
102 }
103 return best;
104 }
105
106 /**
107 * Player dispatch: cargo is money or one inventory stack.
108 * destination: { kind: "bank" } | { kind: "player", firstName, lastName }
109 */
110 dispatchFromPlayer ({ characterId, originTileX, originTileY, destination, cargo })
111 {
112 const onlineId = this.simulation.characterEntities.get(characterId);
113 const bag = onlineId
114 ? this.simulation.bagOf(onlineId)
115 : this.stateDb.getBag(characterId);
116 if (!bag)
117 {
118 const error = new Error("No bag.");
119 error.userFacing = true;
120 throw error;
121 }
122
123 let takenCargo;
124 if (cargo?.kind === "item")
125 {
126 const slot = bag.inventory?.[cargo.slotIndex | 0];
127 if (slot?.itemId === ItemId.blankCheque)
128 {
129 const error = new Error("Blank cheques cannot be sent by pigeon.");
130 error.userFacing = true;
131 throw error;
132 }
133 if (slot?.itemId === ItemId.letter)
134 {
135 if (Number(slot.instance?.authorCharacterId) !== Number(characterId))
136 {
137 const error = new Error("You can only send letters you wrote.");
138 error.userFacing = true;
139 throw error;
140 }
141 }
142 const taken = takeFromSlot(bag.inventory, cargo.slotIndex | 0, cargo.quantity ?? null);
143 if (!taken.ok || !taken.taken)
144 {
145 const error = new Error("That item is not available.");
146 error.userFacing = true;
147 throw error;
148 }
149 bag.inventory = taken.slots;
150 const stack = taken.taken;
151 if (stack.itemId === ItemId.letter && stack.instance)
152 { stack.instance = { ...stack.instance, opened: false }; }
153 takenCargo = { kind: "item", stack };
154 }
155 else
156 {
157 const error = new Error("Pigeon cargo must be money or one item stack.");
158 error.userFacing = true;
159 throw error;
160 }
161
162 const dest = this.#resolveDestination(destination, originTileX, originTileY);
163 this.#persistBag(characterId, bag);
164 const transit = this.stateDb.insertCourierTransit({
165 senderCharacterId: characterId,
166 destinationKind: dest.kind,
167 destinationCharacterId: dest.characterId ?? null,
168 vaultCharacterId: dest.vaultCharacterId ?? null,
169 cargo: takenCargo,
170 originX: originTileX + 0.5,
171 originY: originTileY + 0.5,
172 destX: dest.tileX + 0.5,
173 destY: dest.tileY + 0.5,
174 traveled: 0,
175 status: "in_transit",
176 entityId: null
177 });
178 return { transit, bag };
179 }
180
181 /**
182 * System letters (CE / bank / bounty): to inventory while online (bank if full),
183 * or straight to the bank vault while offline.
184 */
185 dispatchSystemLetter ({ characterId, originTileX, originTileY, stack })
186 {
187 const recipientId = characterId | 0;
188 const cargo = { kind: "item", stack };
189 if (this.simulation.isCharacterOnline(recipientId))
190 {
191 const row = this.stateDb.getCharacter(recipientId);
192 return this.dispatchHeldCargo({
193 senderCharacterId: recipientId,
194 originTileX,
195 originTileY,
196 destination: {
197 kind: "player",
198 firstName: row?.first_name ?? "Unknown",
199 lastName: row?.last_name ?? ""
200 },
201 cargo,
202 vaultCharacterId: recipientId
203 });
204 }
205 return this.dispatchHeldCargo({
206 senderCharacterId: recipientId,
207 originTileX,
208 originTileY,
209 destination: { kind: "bank" },
210 cargo,
211 vaultCharacterId: recipientId
212 });
213 }
214
215 /**
216 * Market / system dispatch already holding cargo (no bag take).
217 * When the recipient is offline, holds delivery until login (CE letters, etc.).
218 */
219 dispatchHeldCargo ({ senderCharacterId, originTileX, originTileY, destination, cargo, vaultCharacterId = null })
220 {
221 const recipientId = vaultCharacterId ?? senderCharacterId;
222 if (!this.simulation.isCharacterOnline(recipientId))
223 {
224 const dest = this.#resolveDestination(destination, originTileX, originTileY);
225 this.stateDb.insertHeldCourierDelivery({
226 characterId: recipientId,
227 senderCharacterId,
228 originTileX,
229 originTileY,
230 destinationKind: dest.kind,
231 destinationCharacterId: dest.characterId ?? recipientId,
232 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? recipientId,
233 cargo
234 });
235 return null;
236 }
237 const dest = this.#resolveDestination(destination, originTileX, originTileY);
238 return this.stateDb.insertCourierTransit({
239 senderCharacterId,
240 destinationKind: dest.kind,
241 destinationCharacterId: dest.characterId ?? null,
242 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? null,
243 cargo,
244 originX: originTileX + 0.5,
245 originY: originTileY + 0.5,
246 destX: dest.tileX + 0.5,
247 destY: dest.tileY + 0.5,
248 traveled: 0,
249 status: "in_transit",
250 entityId: null
251 });
252 }
253
254 /** Flush offline-held deliveries and send a bank resting notice when the player enters the world. */
255 onCharacterEnteredWorld (characterId, tileX, tileY)
256 {
257 for (const held of this.stateDb.listHeldCourierDeliveries(characterId))
258 {
259 this.stateDb.deleteHeldCourierDelivery(held.holdId);
260 const row = this.stateDb.getCharacter(held.destinationCharacterId ?? characterId);
261 this.dispatchHeldCargo({
262 senderCharacterId: held.senderCharacterId,
263 originTileX: held.originTileX,
264 originTileY: held.originTileY,
265 destination: held.destinationKind === "bank"
266 ? { kind: "bank" }
267 : {
268 kind: "player",
269 firstName: row?.first_name ?? "Unknown",
270 lastName: row?.last_name ?? ""
271 },
272 cargo: held.cargo,
273 vaultCharacterId: held.vaultCharacterId ?? characterId
274 });
275 }
276 const noticeTransit = this.#dispatchBankRestNotice(characterId, tileX, tileY);
277 void noticeTransit;
278 }
279
280 step (now, dt)
281 {
282 const events = [];
283 const settings = this.simulation.settings;
284 for (const transit of this.stateDb.listActiveCourierTransits())
285 {
286 this.#retargetPlayerDest(transit);
287 const advanced = advanceCourierFlight({
288 originX: transit.originX,
289 originY: transit.originY,
290 destX: transit.destX,
291 destY: transit.destY,
292 traveled: transit.traveled,
293 dt,
294 settings
295 });
296 transit.traveled = advanced.traveled;
297 transit.updatedAt = now;
298
299 if (advanced.arrived)
300 {
301 events.push(...this.#deliver(transit, now));
302 continue;
303 }
304
305 events.push(...this.#syncVisiblePigeon(transit, advanced, now));
306 this.stateDb.updateCourierTransit(transit);
307 }
308 return events;
309 }
310
311 #retargetPlayerDest (transit)
312 {
313 if (transit.destinationKind !== "player" || !transit.destinationCharacterId)
314 { return; }
315 const onlineId = this.simulation.characterEntities.get(transit.destinationCharacterId);
316 if (onlineId)
317 {
318 const pos = this.simulation.positionOf(onlineId);
319 if (pos)
320 {
321 transit.destX = pos.tileX + 0.5;
322 transit.destY = pos.tileY + 0.5;
323 }
324 return;
325 }
326 this.#routeTransitToBank(transit, transit.destinationCharacterId);
327 }
328
329 #routeTransitToBank (transit, vaultCharacterId)
330 {
331 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY))
332 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY));
333 if (!bank)
334 { return; }
335 transit.destinationKind = "bank";
336 transit.vaultCharacterId = vaultCharacterId ?? transit.vaultCharacterId ?? transit.destinationCharacterId ?? transit.senderCharacterId;
337 transit.destX = bank.tileX + 0.5;
338 transit.destY = bank.tileY + 0.5;
339 }
340
341 #resolveDestination (destination, originTileX, originTileY)
342 {
343 if (destination?.kind === "player")
344 {
345 const character = this.stateDb.getCharacterByName(destination.firstName, destination.lastName);
346 if (!character)
347 {
348 const error = new Error("No character with that name.");
349 error.userFacing = true;
350 throw error;
351 }
352 const onlineId = this.simulation.characterEntities.get(character.character_id);
353 if (!onlineId)
354 {
355 const bank = this.nearestBank(originTileX, originTileY)
356 ?? this.nearestBank(character.tile_x, character.tile_y);
357 if (!bank)
358 {
359 const error = new Error("No bank exists in the world yet.");
360 error.userFacing = true;
361 throw error;
362 }
363 return {
364 kind: "bank",
365 characterId: character.character_id,
366 vaultCharacterId: character.character_id,
367 tileX: bank.tileX,
368 tileY: bank.tileY
369 };
370 }
371 const pos = this.simulation.positionOf(onlineId);
372 return {
373 kind: "player",
374 characterId: character.character_id,
375 tileX: pos.tileX,
376 tileY: pos.tileY
377 };
378 }
379 if (destination?.kind === "bank")
380 {
381 const bank = this.nearestBank(originTileX, originTileY);
382 if (!bank)
383 {
384 const error = new Error("No bank exists in the world yet.");
385 error.userFacing = true;
386 throw error;
387 }
388 return { kind: "bank", tileX: bank.tileX, tileY: bank.tileY };
389 }
390 const error = new Error("Pigeon destination must be bank or player.");
391 error.userFacing = true;
392 throw error;
393 }
394
395 #syncVisiblePigeon (transit, advanced, now)
396 {
397 const events = [];
398 const tileX = Math.floor(advanced.x);
399 const tileY = Math.floor(advanced.y);
400 if (!this.simulation.chunkIsSimulating(tileX, tileY))
401 {
402 if (transit.entityId)
403 {
404 this.simulation.despawnEntity(transit.entityId);
405 events.push({ type: "entity-despawn", entityId: transit.entityId, tileX, tileY });
406 transit.entityId = null;
407 }
408 return events;
409 }
410
411 if (!transit.entityId || !this.simulation.entityRecord(transit.entityId))
412 {
413 transit.entityId = null;
414 const def = mobDefinition(MobId.pigeon);
415 const entityId = this.simulation.spawnEntity({
416 position: { tileX, tileY },
417 movement: { gait: GAIT.walk, walkCarry: 0 },
418 path: { tiles: [] },
419 flight: {
420 x: advanced.x,
421 y: advanced.y,
422 targetX: transit.destX,
423 targetY: transit.destY,
424 speed: advanced.speed,
425 nextPickAt: now + 60_000,
426 lastAt: now,
427 courierId: transit.courierId
428 },
429 appearance: {
430 sex: def.sex,
431 firstName: def.displayName,
432 lastName: "",
433 sprite: mobSpriteName(MobId.pigeon)
434 },
435 creature: { mobTypeId: MobId.pigeon },
436 health: { current: 1, max: 1 }
437 }, { requireResident: true });
438 if (entityId != null)
439 { transit.entityId = entityId; }
440 return events;
441 }
442
443 const moved = this.simulation.updateCourierFlight(transit.entityId, {
444 x: advanced.x,
445 y: advanced.y,
446 targetX: transit.destX,
447 targetY: transit.destY,
448 speed: advanced.speed,
449 lastAt: now,
450 courierId: transit.courierId
451 }, now);
452 if (moved?.despawned)
453 {
454 transit.entityId = null;
455 events.push({ type: "entity-despawn", entityId: moved.entityId, tileX, tileY });
456 }
457 else if (moved?.event)
458 { events.push(moved.event); }
459 return events;
460 }
461
462 #deliver (transit, now)
463 {
464 const events = [];
465 if (transit.entityId)
466 {
467 this.simulation.despawnEntity(transit.entityId);
468 events.push({
469 type: "entity-despawn",
470 entityId: transit.entityId,
471 tileX: Math.floor(transit.destX),
472 tileY: Math.floor(transit.destY)
473 });
474 transit.entityId = null;
475 }
476
477 if (transit.destinationKind === "bank")
478 {
479 const vaultCharacterId = transit.vaultCharacterId
480 ?? transit.destinationCharacterId
481 ?? transit.senderCharacterId;
482 const toast = this.#creditVault(vaultCharacterId, transit.cargo, {
483 senderCharacterId: transit.senderCharacterId
484 });
485 if (toast)
486 { events.push(toast); }
487 }
488 else if (transit.destinationKind === "player")
489 {
490 const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo);
491 if (!delivered)
492 {
493 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY))
494 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY));
495 if (bank)
496 {
497 transit.originX = transit.destX;
498 transit.originY = transit.destY;
499 transit.destX = bank.tileX + 0.5;
500 transit.destY = bank.tileY + 0.5;
501 transit.traveled = 0;
502 transit.destinationKind = "bank";
503 transit.vaultCharacterId = transit.destinationCharacterId;
504 transit.updatedAt = now;
505 this.stateDb.updateCourierTransit(transit);
506 events.push({
507 type: "pigeon-reroute-bank",
508 courierId: transit.courierId,
509 characterId: transit.destinationCharacterId
510 });
511 return events;
512 }
513 const toast = this.#creditVault(transit.destinationCharacterId, transit.cargo, {
514 senderCharacterId: transit.senderCharacterId
515 });
516 if (toast)
517 { events.push(toast); }
518 }
519 }
520
521 transit.status = "delivered";
522 transit.traveled = Math.hypot(transit.destX - transit.originX, transit.destY - transit.originY);
523 transit.updatedAt = now;
524 this.stateDb.updateCourierTransit(transit);
525 events.push({
526 type: "pigeon-delivered",
527 courierId: transit.courierId,
528 senderCharacterId: transit.senderCharacterId,
529 destinationKind: transit.destinationKind,
530 destinationCharacterId: transit.destinationCharacterId,
531 cargo: transit.cargo
532 });
533 return events;
534 }
535
536 #normalizeCargo (cargo)
537 {
538 if (cargo?.kind === "money")
539 {
540 return {
541 kind: "item",
542 stack: attachOrigins({ itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) })
543 };
544 }
545 return cargo;
546 }
547
548 #tryDeliverToPlayer (characterId, cargo)
549 {
550 cargo = this.#normalizeCargo(cargo);
551 const onlineId = this.simulation.characterEntities.get(characterId);
552 if (!onlineId)
553 { return false; }
554 if (cargo.kind === "item")
555 {
556 const bag = this.simulation.bagOf(onlineId);
557 if (!bag)
558 { return false; }
559 const def = itemDefinition(cargo.stack.itemId);
560 const result = insertStack(bag.inventory, cargo.stack, def);
561 if (!result.ok || result.remainder)
562 { return false; }
563 bag.inventory = result.slots;
564 this.#persistBag(characterId, bag);
565 return true;
566 }
567 return false;
568 }
569
570 #creditVault (characterId, cargo, { senderCharacterId = null, recordRestNotice = true } = {})
571 {
572 cargo = this.#normalizeCargo(cargo);
573 const onlineId = this.simulation.characterEntities.get(characterId);
574 const bag = onlineId
575 ? this.simulation.bagOf(onlineId)
576 : this.stateDb.getBag(characterId);
577 if (!bag)
578 { return null; }
579 if (cargo.kind !== "item")
580 { return null; }
581
582 const stack = cargo.stack;
583 const isCeLetter = stack?.itemId === ItemId.letter && isCentralExchangeLetter(stack.instance);
584 const isRestNoticeLetter = stack?.itemId === ItemId.letter && isBankRestNoticeLetter(stack.instance);
585
586 if (stack?.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
587 {
588 this.#redeemChequeIntoVault(characterId, bag, stack);
589 this.#maybeRecordRestNotice({
590 characterId,
591 stack,
592 senderCharacterId,
593 recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter
594 });
595 return null;
596 }
597
598 const def = itemDefinition(stack.itemId);
599 const vault = normalizeVault(
600 bag.vaultReserved != null
601 ? { slots: bag.vault, reserved: bag.vaultReserved }
602 : bag.vault
603 );
604 const result = insertStackGrowable(vault.slots, stack, def);
605 bag.vault = result.slots;
606 bag.vaultReserved = vault.reserved;
607 this.#persistBag(characterId, bag);
608
609 this.#maybeRecordRestNotice({
610 characterId,
611 stack,
612 senderCharacterId,
613 recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter
614 });
615
616 if (onlineId && isRestNoticeLetter)
617 {
618 return {
619 type: "toast",
620 characterId,
621 message: "A letter arrived for you at the bank."
622 };
623 }
624 return null;
625 }
626
627 #maybeRecordRestNotice ({ characterId, stack, senderCharacterId, recordRestNotice })
628 {
629 if (!recordRestNotice || !stack)
630 { return; }
631 const sender = senderCharacterId ? this.stateDb.getCharacter(senderCharacterId) : null;
632 const senderDisplayName = sender
633 ? `${sender.first_name} ${sender.last_name}`.trim()
634 : null;
635 this.stateDb.appendBankRestNotice(characterId, {
636 itemId: stack.itemId,
637 itemName: itemNameForNotice(stack),
638 quantity: stack.quantity | 0 || 1,
639 sourceName: sourceNameForVaultDeposit(stack, senderCharacterId, senderDisplayName)
640 });
641 }
642
643 /** Pigeon/bank delivery of a filled cheque deposits the reserved goods, not the paper. */
644 #redeemChequeIntoVault (characterId, bag, chequeStack)
645 {
646 const instance = chequeStack.instance;
647 const issuerId = instance.issuerCharacterId;
648 const goodsDef = itemDefinition(instance.itemId);
649 if (!goodsDef)
650 { return; }
651
652 let reservedStack = null;
653 if (Number(issuerId) === Number(characterId))
654 {
655 const reserved = [...(bag.vaultReserved ?? [])];
656 const index = findReservedChequeIndex(reserved, instance);
657 if (index < 0)
658 {
659 // Paper arrived but reservation is gone — keep the cheque so it isn't silently lost.
660 const def = itemDefinition(ItemId.filledCheque);
661 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
662 const result = insertStackGrowable(vault.slots, chequeStack, def);
663 bag.vault = result.slots;
664 bag.vaultReserved = vault.reserved;
665 this.#persistBag(characterId, bag);
666 return;
667 }
668 reservedStack = reserved[index];
669 reserved.splice(index, 1);
670 bag.vaultReserved = reserved;
671 }
672 else
673 {
674 const release = this.simulation.releaseChequeReservation(issuerId, instance.chequeId, instance);
675 if (!release?.ok)
676 {
677 const def = itemDefinition(ItemId.filledCheque);
678 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
679 const result = insertStackGrowable(vault.slots, chequeStack, def);
680 bag.vault = result.slots;
681 bag.vaultReserved = vault.reserved;
682 this.#persistBag(characterId, bag);
683 return;
684 }
685 reservedStack = release.stack;
686 }
687
688 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
689 const goodsStack = attachOrigins({
690 itemId: reservedStack.itemId,
691 quantity: reservedStack.quantity,
692 origins: normalizeOrigins(reservedStack),
693 instance: reservedStack.instance ?? null
694 });
695 const inserted = insertStackGrowable(vault.slots, goodsStack, goodsDef);
696 bag.vault = inserted.slots;
697 bag.vaultReserved = vault.reserved;
698 this.#persistBag(characterId, bag);
699 this.#maybeRecordRestNotice({
700 characterId,
701 stack: goodsStack,
702 senderCharacterId: null,
703 recordRestNotice: !this.simulation.characterEntities.get(characterId)
704 });
705 }
706
707 #persistBag (characterId, bag)
708 {
709 this.stateDb.saveBag(characterId, bag);
710 const onlineId = this.simulation.characterEntities.get(characterId);
711 if (onlineId)
712 {
713 this.simulation.applyBag(onlineId, bag);
714 this.simulation.pushInventory(characterId, bag);
715 }
716 }
717
718 #characterDisplayName (characterId)
719 {
720 const row = this.stateDb.getCharacter(characterId);
721 return {
722 firstName: row?.first_name ?? "Unknown",
723 lastName: row?.last_name ?? "",
724 full: row ? `${row.first_name} ${row.last_name}`.trim() : "Adventurer"
725 };
726 }
727
728 #dispatchBankRestNotice (characterId, tileX, tileY)
729 {
730 const entries = this.stateDb.listBankRestNotices(characterId);
731 if (!entries.length)
732 { return null; }
733 const bank = this.nearestBank(tileX, tileY);
734 if (!bank)
735 { return null; }
736
737 const lines = mergeBankRestNoticeLines(entries.map((entry) => ({
738 quantity: entry.quantity,
739 itemName: entry.itemName,
740 sourceName: entry.sourceName
741 })));
742 const { full: playerName } = this.#characterDisplayName(characterId);
743 const body = bankRestNoticeLetterBody({ playerName, lines });
744 const stack = attachOrigins({
745 itemId: ItemId.letter,
746 quantity: 1,
747 origins: [{ origin: writtenOrigin(BANK_LETTER_AUTHOR), quantity: 1 }],
748 instance: {
749 kind: "letter",
750 letterId: randomUUID(),
751 authorCharacterId: 0,
752 authorDisplayName: BANK_LETTER_AUTHOR,
753 body,
754 opened: false,
755 writtenAt: Date.now(),
756 bankRestNotice: true
757 }
758 });
759 this.stateDb.clearBankRestNotices(characterId);
760 return this.stateDb.insertCourierTransit({
761 senderCharacterId: characterId,
762 destinationKind: "player",
763 destinationCharacterId: characterId,
764 vaultCharacterId: characterId,
765 cargo: { kind: "item", stack },
766 originX: bank.tileX + 0.5,
767 originY: bank.tileY + 0.5,
768 destX: tileX + 0.5,
769 destY: tileY + 0.5,
770 traveled: 0,
771 status: "in_transit",
772 entityId: null
773 });
774 }
775}