BlueGit

timfa questward

Files

questward / server / src / courier / service.js

service.js

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