BlueGit

timfa questward

Files

questward / server / src / courier / service.js

service.js

service.js 22.9 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, 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 {
13 BANK_LETTER_AUTHOR,
14 bankRestNoticeLetterBody,
15 isBankRestNoticeLetter,
16 isCentralExchangeLetter,
17 itemNameForNotice,
18 mergeBankRestNoticeLines,
19 sourceNameForVaultDeposit
20} from "../../../shared/courier/bankNotice.js";
21import { makeSystemLetterStack } from "./systemLetter.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 * Shared entry for system letters (gift / CE / bounty / church / cowardice / …).
181 * Online (not combat-logout): pigeon flies immediately.
182 * Offline / combat-logout: held until the character enters the world.
183 */
184 enqueueSystemLetter ({
185 characterId,
186 originTileX,
187 originTileY,
188 authorDisplayName,
189 authorOrganization = null,
190 body,
191 centralExchange = false,
192 bankRestNotice = false
193 })
194 {
195 const stack = makeSystemLetterStack({
196 authorDisplayName,
197 authorOrganization,
198 body,
199 centralExchange,
200 bankRestNotice
201 });
202 return this.dispatchSystemLetter({
203 characterId,
204 originTileX,
205 originTileY,
206 stack
207 });
208 }
209
210 /**
211 * System letters (gift / CE / bounty): pigeon to the player (inventory; bank if full).
212 * While offline, hold with player destination so login flies from the bank to the character
213 * — never deposit the letter straight into the vault.
214 * Prefer enqueueSystemLetter when building a new system letter from author/body fields.
215 */
216 dispatchSystemLetter ({ characterId, originTileX, originTileY, stack })
217 {
218 const recipientId = characterId | 0;
219 const cargo = { kind: "item", stack };
220 const row = this.stateDb.getCharacter(recipientId);
221 return this.dispatchHeldCargo({
222 senderCharacterId: recipientId,
223 originTileX,
224 originTileY,
225 destination: {
226 kind: "player",
227 firstName: row?.first_name ?? "Unknown",
228 lastName: row?.last_name ?? ""
229 },
230 cargo,
231 vaultCharacterId: recipientId
232 });
233 }
234
235 /**
236 * Market / system dispatch already holding cargo (no bag take).
237 * When the recipient is offline, holds delivery until login (CE letters, etc.).
238 * Player-bound holds keep destinationKind "player" even though resolve would route to bank
239 * while offline — on login the pigeon then delivers to the character, not the vault.
240 */
241 dispatchHeldCargo ({ senderCharacterId, originTileX, originTileY, destination, cargo, vaultCharacterId = null })
242 {
243 const recipientId = vaultCharacterId ?? senderCharacterId;
244 if (!this.simulation.isCharacterOnline(recipientId))
245 {
246 const dest = this.#resolveDestination(destination, originTileX, originTileY);
247 const intendedKind = destination?.kind === "player" ? "player" : dest.kind;
248 this.stateDb.insertHeldCourierDelivery({
249 characterId: recipientId,
250 senderCharacterId,
251 originTileX,
252 originTileY,
253 destinationKind: intendedKind,
254 destinationCharacterId: dest.characterId ?? recipientId,
255 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? recipientId,
256 cargo
257 });
258 return null;
259 }
260 const dest = this.#resolveDestination(destination, originTileX, originTileY);
261 return this.stateDb.insertCourierTransit({
262 senderCharacterId,
263 destinationKind: dest.kind,
264 destinationCharacterId: dest.characterId ?? null,
265 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? null,
266 cargo,
267 originX: originTileX + 0.5,
268 originY: originTileY + 0.5,
269 destX: dest.tileX + 0.5,
270 destY: dest.tileY + 0.5,
271 traveled: 0,
272 status: "in_transit",
273 entityId: null
274 });
275 }
276
277 /** Flush offline-held deliveries and send a bank resting notice when the player enters the world. */
278 onCharacterEnteredWorld (characterId, tileX, tileY)
279 {
280 for (const held of this.stateDb.listHeldCourierDeliveries(characterId))
281 {
282 this.stateDb.deleteHeldCourierDelivery(held.holdId);
283 const row = this.stateDb.getCharacter(held.destinationCharacterId ?? characterId);
284 this.dispatchHeldCargo({
285 senderCharacterId: held.senderCharacterId,
286 originTileX: held.originTileX,
287 originTileY: held.originTileY,
288 destination: held.destinationKind === "bank"
289 ? { kind: "bank" }
290 : {
291 kind: "player",
292 firstName: row?.first_name ?? "Unknown",
293 lastName: row?.last_name ?? ""
294 },
295 cargo: held.cargo,
296 vaultCharacterId: held.vaultCharacterId ?? characterId
297 });
298 }
299 const noticeTransit = this.#dispatchBankRestNotice(characterId, tileX, tileY);
300 void noticeTransit;
301 }
302
303 step (now, dt)
304 {
305 const events = [];
306 const settings = this.simulation.settings;
307 for (const transit of this.stateDb.listActiveCourierTransits())
308 {
309 this.#retargetPlayerDest(transit);
310 const advanced = advanceCourierFlight({
311 originX: transit.originX,
312 originY: transit.originY,
313 destX: transit.destX,
314 destY: transit.destY,
315 traveled: transit.traveled,
316 dt,
317 settings
318 });
319 transit.traveled = advanced.traveled;
320 transit.updatedAt = now;
321
322 if (advanced.arrived)
323 {
324 events.push(...this.#deliver(transit, now));
325 continue;
326 }
327
328 events.push(...this.#syncVisiblePigeon(transit, advanced, now));
329 this.stateDb.updateCourierTransit(transit);
330 }
331 return events;
332 }
333
334 #retargetPlayerDest (transit)
335 {
336 if (transit.destinationKind !== "player" || !transit.destinationCharacterId)
337 { return; }
338 const onlineId = this.simulation.characterEntities.get(transit.destinationCharacterId);
339 if (onlineId)
340 {
341 const pos = this.simulation.positionOf(onlineId);
342 if (pos)
343 {
344 transit.destX = pos.tileX + 0.5;
345 transit.destY = pos.tileY + 0.5;
346 }
347 return;
348 }
349 this.#routeTransitToBank(transit, transit.destinationCharacterId);
350 }
351
352 #routeTransitToBank (transit, vaultCharacterId)
353 {
354 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY))
355 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY));
356 if (!bank)
357 { return; }
358 transit.destinationKind = "bank";
359 transit.vaultCharacterId = vaultCharacterId ?? transit.vaultCharacterId ?? transit.destinationCharacterId ?? transit.senderCharacterId;
360 transit.destX = bank.tileX + 0.5;
361 transit.destY = bank.tileY + 0.5;
362 }
363
364 #resolveDestination (destination, originTileX, originTileY)
365 {
366 if (destination?.kind === "player")
367 {
368 const character = this.stateDb.getCharacterByName(destination.firstName, destination.lastName);
369 if (!character)
370 {
371 const error = new Error("No character with that name.");
372 error.userFacing = true;
373 throw error;
374 }
375 const onlineId = this.simulation.characterEntities.get(character.character_id);
376 if (!onlineId)
377 {
378 const bank = this.nearestBank(originTileX, originTileY)
379 ?? this.nearestBank(character.tile_x, character.tile_y);
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 {
387 kind: "bank",
388 characterId: character.character_id,
389 vaultCharacterId: character.character_id,
390 tileX: bank.tileX,
391 tileY: bank.tileY
392 };
393 }
394 const pos = this.simulation.positionOf(onlineId);
395 return {
396 kind: "player",
397 characterId: character.character_id,
398 tileX: pos.tileX,
399 tileY: pos.tileY
400 };
401 }
402 if (destination?.kind === "bank")
403 {
404 const bank = this.nearestBank(originTileX, originTileY);
405 if (!bank)
406 {
407 const error = new Error("No bank exists in the world yet.");
408 error.userFacing = true;
409 throw error;
410 }
411 return { kind: "bank", tileX: bank.tileX, tileY: bank.tileY };
412 }
413 const error = new Error("Pigeon destination must be bank or player.");
414 error.userFacing = true;
415 throw error;
416 }
417
418 #syncVisiblePigeon (transit, advanced, now)
419 {
420 const events = [];
421 const tileX = Math.floor(advanced.x);
422 const tileY = Math.floor(advanced.y);
423 if (!this.simulation.chunkIsSimulating(tileX, tileY))
424 {
425 if (transit.entityId)
426 {
427 this.simulation.despawnEntity(transit.entityId);
428 events.push({ type: "entity-despawn", entityId: transit.entityId, tileX, tileY });
429 transit.entityId = null;
430 }
431 return events;
432 }
433
434 if (!transit.entityId || !this.simulation.entityRecord(transit.entityId))
435 {
436 transit.entityId = null;
437 const def = mobDefinition(MobId.pigeon);
438 const entityId = this.simulation.spawnEntity({
439 position: { tileX, tileY },
440 movement: { gait: GAIT.walk, walkCarry: 0 },
441 path: { tiles: [] },
442 flight: {
443 x: advanced.x,
444 y: advanced.y,
445 targetX: transit.destX,
446 targetY: transit.destY,
447 speed: advanced.speed,
448 nextPickAt: now + 60_000,
449 lastAt: now,
450 courierId: transit.courierId
451 },
452 appearance: {
453 sex: def.sex,
454 firstName: def.displayName,
455 lastName: "",
456 sprite: mobSpriteName(MobId.pigeon)
457 },
458 creature: { mobTypeId: MobId.pigeon },
459 health: { current: 1, max: 1 }
460 }, { requireResident: true });
461 if (entityId != null)
462 { transit.entityId = entityId; }
463 return events;
464 }
465
466 const moved = this.simulation.updateCourierFlight(transit.entityId, {
467 x: advanced.x,
468 y: advanced.y,
469 targetX: transit.destX,
470 targetY: transit.destY,
471 speed: advanced.speed,
472 lastAt: now,
473 courierId: transit.courierId
474 }, now);
475 if (moved?.despawned)
476 {
477 transit.entityId = null;
478 events.push({ type: "entity-despawn", entityId: moved.entityId, tileX, tileY });
479 }
480 else if (moved?.event)
481 { events.push(moved.event); }
482 return events;
483 }
484
485 #deliver (transit, now)
486 {
487 const events = [];
488 if (transit.entityId)
489 {
490 this.simulation.despawnEntity(transit.entityId);
491 events.push({
492 type: "entity-despawn",
493 entityId: transit.entityId,
494 tileX: Math.floor(transit.destX),
495 tileY: Math.floor(transit.destY)
496 });
497 transit.entityId = null;
498 }
499
500 if (transit.destinationKind === "bank")
501 {
502 const vaultCharacterId = transit.vaultCharacterId
503 ?? transit.destinationCharacterId
504 ?? transit.senderCharacterId;
505 const toast = this.#creditVault(vaultCharacterId, transit.cargo, {
506 senderCharacterId: transit.senderCharacterId
507 });
508 if (toast)
509 { events.push(toast); }
510 }
511 else if (transit.destinationKind === "player")
512 {
513 const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo);
514 if (!delivered)
515 {
516 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY))
517 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY));
518 if (bank)
519 {
520 transit.originX = transit.destX;
521 transit.originY = transit.destY;
522 transit.destX = bank.tileX + 0.5;
523 transit.destY = bank.tileY + 0.5;
524 transit.traveled = 0;
525 transit.destinationKind = "bank";
526 transit.vaultCharacterId = transit.destinationCharacterId;
527 transit.updatedAt = now;
528 this.stateDb.updateCourierTransit(transit);
529 events.push({
530 type: "pigeon-reroute-bank",
531 courierId: transit.courierId,
532 characterId: transit.destinationCharacterId
533 });
534 return events;
535 }
536 const toast = this.#creditVault(transit.destinationCharacterId, transit.cargo, {
537 senderCharacterId: transit.senderCharacterId
538 });
539 if (toast)
540 { events.push(toast); }
541 }
542 else
543 {
544 events.push({
545 type: "item-bubble",
546 entityId: delivered.entityId,
547 itemId: delivered.itemId,
548 quantity: delivered.quantity
549 });
550 }
551 }
552
553 transit.status = "delivered";
554 transit.traveled = Math.hypot(transit.destX - transit.originX, transit.destY - transit.originY);
555 transit.updatedAt = now;
556 this.stateDb.updateCourierTransit(transit);
557 events.push({
558 type: "pigeon-delivered",
559 courierId: transit.courierId,
560 senderCharacterId: transit.senderCharacterId,
561 destinationKind: transit.destinationKind,
562 destinationCharacterId: transit.destinationCharacterId,
563 cargo: transit.cargo
564 });
565 return events;
566 }
567
568 #normalizeCargo (cargo)
569 {
570 if (cargo?.kind === "money")
571 {
572 return {
573 kind: "item",
574 stack: attachOrigins({ itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) })
575 };
576 }
577 return cargo;
578 }
579
580 #tryDeliverToPlayer (characterId, cargo)
581 {
582 cargo = this.#normalizeCargo(cargo);
583 const onlineId = this.simulation.characterEntities.get(characterId);
584 if (!onlineId)
585 { return null; }
586 if (cargo.kind === "item")
587 {
588 const bag = this.simulation.bagOf(onlineId);
589 if (!bag)
590 { return null; }
591 const def = itemDefinition(cargo.stack.itemId);
592 const result = insertStack(bag.inventory, cargo.stack, def);
593 if (!result.ok || result.remainder)
594 { return null; }
595 bag.inventory = result.slots;
596 this.#persistBag(characterId, bag);
597 return {
598 entityId: onlineId,
599 itemId: cargo.stack.itemId,
600 quantity: Math.max(1, cargo.stack.quantity | 0 || 1)
601 };
602 }
603 return null;
604 }
605
606 #creditVault (characterId, cargo, { senderCharacterId = null, recordRestNotice = true } = {})
607 {
608 cargo = this.#normalizeCargo(cargo);
609 const onlineId = this.simulation.characterEntities.get(characterId);
610 const bag = onlineId
611 ? this.simulation.bagOf(onlineId)
612 : this.stateDb.getBag(characterId);
613 if (!bag)
614 { return null; }
615 if (cargo.kind !== "item")
616 { return null; }
617
618 const stack = cargo.stack;
619 const isCeLetter = stack?.itemId === ItemId.letter && isCentralExchangeLetter(stack.instance);
620 const isRestNoticeLetter = stack?.itemId === ItemId.letter && isBankRestNoticeLetter(stack.instance);
621
622 if (stack?.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
623 {
624 this.#redeemChequeIntoVault(characterId, bag, stack);
625 this.#maybeRecordRestNotice({
626 characterId,
627 stack,
628 senderCharacterId,
629 recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter
630 });
631 return null;
632 }
633
634 const def = itemDefinition(stack.itemId);
635 const vault = normalizeVault(
636 bag.vaultReserved != null
637 ? { slots: bag.vault, reserved: bag.vaultReserved }
638 : bag.vault
639 );
640 const result = insertStackGrowable(vault.slots, stack, def);
641 bag.vault = result.slots;
642 bag.vaultReserved = vault.reserved;
643 this.#persistBag(characterId, bag);
644
645 this.#maybeRecordRestNotice({
646 characterId,
647 stack,
648 senderCharacterId,
649 recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter
650 });
651
652 if (onlineId && isRestNoticeLetter)
653 {
654 return {
655 type: "toast",
656 characterId,
657 message: "A letter arrived for you at the bank."
658 };
659 }
660 return null;
661 }
662
663 #maybeRecordRestNotice ({ characterId, stack, senderCharacterId, recordRestNotice })
664 {
665 if (!recordRestNotice || !stack)
666 { return; }
667 const sender = senderCharacterId ? this.stateDb.getCharacter(senderCharacterId) : null;
668 const senderDisplayName = sender
669 ? `${sender.first_name} ${sender.last_name}`.trim()
670 : null;
671 this.stateDb.appendBankRestNotice(characterId, {
672 itemId: stack.itemId,
673 itemName: itemNameForNotice(stack),
674 quantity: stack.quantity | 0 || 1,
675 sourceName: sourceNameForVaultDeposit(stack, senderCharacterId, senderDisplayName)
676 });
677 }
678
679 /** Pigeon/bank delivery of a filled cheque deposits the reserved goods, not the paper. */
680 #redeemChequeIntoVault (characterId, bag, chequeStack)
681 {
682 const instance = chequeStack.instance;
683 const issuerId = instance.issuerCharacterId;
684 const goodsDef = itemDefinition(instance.itemId);
685 if (!goodsDef)
686 { return; }
687
688 let reservedStack = null;
689 if (Number(issuerId) === Number(characterId))
690 {
691 const reserved = [...(bag.vaultReserved ?? [])];
692 const index = findReservedChequeIndex(reserved, instance);
693 if (index < 0)
694 {
695 // Paper arrived but reservation is gone — keep the cheque so it isn't silently lost.
696 const def = itemDefinition(ItemId.filledCheque);
697 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
698 const result = insertStackGrowable(vault.slots, chequeStack, def);
699 bag.vault = result.slots;
700 bag.vaultReserved = vault.reserved;
701 this.#persistBag(characterId, bag);
702 return;
703 }
704 reservedStack = reserved[index];
705 reserved.splice(index, 1);
706 bag.vaultReserved = reserved;
707 }
708 else
709 {
710 const release = this.simulation.releaseChequeReservation(issuerId, instance.chequeId, instance);
711 if (!release?.ok)
712 {
713 const def = itemDefinition(ItemId.filledCheque);
714 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
715 const result = insertStackGrowable(vault.slots, chequeStack, def);
716 bag.vault = result.slots;
717 bag.vaultReserved = vault.reserved;
718 this.#persistBag(characterId, bag);
719 return;
720 }
721 reservedStack = release.stack;
722 }
723
724 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
725 const goodsStack = attachOrigins({
726 itemId: reservedStack.itemId,
727 quantity: reservedStack.quantity,
728 origins: normalizeOrigins(reservedStack),
729 instance: reservedStack.instance ?? null
730 });
731 const inserted = insertStackGrowable(vault.slots, goodsStack, goodsDef);
732 bag.vault = inserted.slots;
733 bag.vaultReserved = vault.reserved;
734 this.#persistBag(characterId, bag);
735 this.#maybeRecordRestNotice({
736 characterId,
737 stack: goodsStack,
738 senderCharacterId: null,
739 recordRestNotice: !this.simulation.characterEntities.get(characterId)
740 });
741 }
742
743 #persistBag (characterId, bag)
744 {
745 this.stateDb.saveBag(characterId, bag);
746 const onlineId = this.simulation.characterEntities.get(characterId);
747 if (onlineId)
748 {
749 this.simulation.applyBag(onlineId, bag);
750 this.simulation.pushInventory(characterId, bag);
751 }
752 }
753
754 #characterDisplayName (characterId)
755 {
756 const row = this.stateDb.getCharacter(characterId);
757 return {
758 firstName: row?.first_name ?? "Unknown",
759 lastName: row?.last_name ?? "",
760 full: row ? `${row.first_name} ${row.last_name}`.trim() : "Adventurer"
761 };
762 }
763
764 #dispatchBankRestNotice (characterId, tileX, tileY)
765 {
766 const entries = this.stateDb.listBankRestNotices(characterId);
767 if (!entries.length)
768 { return null; }
769 const bank = this.nearestBank(tileX, tileY);
770 if (!bank)
771 { return null; }
772
773 const lines = mergeBankRestNoticeLines(entries.map((entry) => ({
774 quantity: entry.quantity,
775 itemName: entry.itemName,
776 sourceName: entry.sourceName
777 })));
778 const { full: playerName } = this.#characterDisplayName(characterId);
779 const body = bankRestNoticeLetterBody({ playerName, lines });
780 const stack = makeSystemLetterStack({
781 authorDisplayName: BANK_LETTER_AUTHOR,
782 body,
783 bankRestNotice: true
784 });
785 this.stateDb.clearBankRestNotices(characterId);
786 return this.dispatchSystemLetter({
787 characterId,
788 originTileX: bank.tileX,
789 originTileY: bank.tileY,
790 stack
791 });
792 }
793}