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