BlueGit

timfa questward

Files

questward / server / src / courier / service.js

service.js

service.js 23.7 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({
440 type: "entity-despawn",
441 entityId: transit.entityId,
442 tileX,
443 tileY,
444 dimensionId: OVERWORLD_ID
445 });
446 transit.entityId = null;
447 }
448 return events;
449 }
450
451 if (!transit.entityId || !this.simulation.entityRecord(transit.entityId))
452 {
453 transit.entityId = null;
454 const def = mobDefinition(MobId.pigeon);
455 const entityId = this.simulation.spawnEntity({
456 position: { tileX, tileY },
457 movement: { gait: GAIT.walk, walkCarry: 0 },
458 path: { tiles: [] },
459 flight: {
460 x: advanced.x,
461 y: advanced.y,
462 targetX: transit.destX,
463 targetY: transit.destY,
464 speed: advanced.speed,
465 nextPickAt: now + 60_000,
466 lastAt: now,
467 courierId: transit.courierId
468 },
469 appearance: {
470 sex: def.sex,
471 firstName: def.displayName,
472 lastName: "",
473 sprite: mobSpriteName(MobId.pigeon)
474 },
475 creature: { mobTypeId: MobId.pigeon },
476 health: { current: 1, max: 1 }
477 }, { requireResident: true });
478 if (entityId != null)
479 { transit.entityId = entityId; }
480 return events;
481 }
482
483 const moved = this.simulation.updateCourierFlight(transit.entityId, {
484 x: advanced.x,
485 y: advanced.y,
486 targetX: transit.destX,
487 targetY: transit.destY,
488 speed: advanced.speed,
489 lastAt: now,
490 courierId: transit.courierId
491 }, now);
492 if (moved?.despawned)
493 {
494 transit.entityId = null;
495 events.push({
496 type: "entity-despawn",
497 entityId: moved.entityId,
498 tileX,
499 tileY,
500 dimensionId: OVERWORLD_ID
501 });
502 }
503 else if (moved?.event)
504 { events.push(moved.event); }
505 return events;
506 }
507
508 #deliver (transit, now)
509 {
510 const events = [];
511 if (transit.entityId)
512 {
513 this.simulation.despawnEntity(transit.entityId);
514 events.push({
515 type: "entity-despawn",
516 entityId: transit.entityId,
517 tileX: Math.floor(transit.destX),
518 tileY: Math.floor(transit.destY),
519 dimensionId: OVERWORLD_ID
520 });
521 transit.entityId = null;
522 }
523
524 if (transit.destinationKind === "bank")
525 {
526 const vaultCharacterId = transit.vaultCharacterId
527 ?? transit.destinationCharacterId
528 ?? transit.senderCharacterId;
529 const toast = this.#creditVault(vaultCharacterId, transit.cargo, {
530 senderCharacterId: transit.senderCharacterId
531 });
532 if (toast)
533 { events.push(toast); }
534 }
535 else if (transit.destinationKind === "player")
536 {
537 const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo);
538 if (!delivered)
539 {
540 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY))
541 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY));
542 if (bank)
543 {
544 transit.originX = transit.destX;
545 transit.originY = transit.destY;
546 transit.destX = bank.tileX + 0.5;
547 transit.destY = bank.tileY + 0.5;
548 transit.traveled = 0;
549 transit.destinationKind = "bank";
550 transit.vaultCharacterId = transit.destinationCharacterId;
551 transit.updatedAt = now;
552 this.stateDb.updateCourierTransit(transit);
553 events.push({
554 type: "pigeon-reroute-bank",
555 courierId: transit.courierId,
556 characterId: transit.destinationCharacterId
557 });
558 return events;
559 }
560 const toast = this.#creditVault(transit.destinationCharacterId, transit.cargo, {
561 senderCharacterId: transit.senderCharacterId
562 });
563 if (toast)
564 { events.push(toast); }
565 }
566 else
567 {
568 events.push({
569 type: "item-bubble",
570 entityId: delivered.entityId,
571 itemId: delivered.itemId,
572 quantity: delivered.quantity
573 });
574 }
575 }
576
577 transit.status = "delivered";
578 transit.traveled = Math.hypot(transit.destX - transit.originX, transit.destY - transit.originY);
579 transit.updatedAt = now;
580 this.stateDb.updateCourierTransit(transit);
581 events.push({
582 type: "pigeon-delivered",
583 courierId: transit.courierId,
584 senderCharacterId: transit.senderCharacterId,
585 destinationKind: transit.destinationKind,
586 destinationCharacterId: transit.destinationCharacterId,
587 cargo: transit.cargo
588 });
589 return events;
590 }
591
592 #normalizeCargo (cargo)
593 {
594 if (cargo?.kind === "money")
595 {
596 return {
597 kind: "item",
598 stack: attachOrigins({ itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) })
599 };
600 }
601 return cargo;
602 }
603
604 #tryDeliverToPlayer (characterId, cargo)
605 {
606 cargo = this.#normalizeCargo(cargo);
607 const onlineId = this.simulation.characterEntities.get(characterId);
608 if (!onlineId)
609 { return null; }
610 if (cargo.kind === "item")
611 {
612 const bag = this.simulation.bagOf(onlineId);
613 if (!bag)
614 { return null; }
615 const def = itemDefinition(cargo.stack.itemId);
616 const result = insertStack(bag.inventory, cargo.stack, def);
617 if (!result.ok || result.remainder)
618 { return null; }
619 bag.inventory = result.slots;
620 this.#persistBag(characterId, bag);
621 return {
622 entityId: onlineId,
623 itemId: cargo.stack.itemId,
624 quantity: Math.max(1, cargo.stack.quantity | 0 || 1)
625 };
626 }
627 return null;
628 }
629
630 #creditVault (characterId, cargo, { senderCharacterId = null, recordRestNotice = true } = {})
631 {
632 cargo = this.#normalizeCargo(cargo);
633 const onlineId = this.simulation.characterEntities.get(characterId);
634 const bag = onlineId
635 ? this.simulation.bagOf(onlineId)
636 : this.stateDb.getBag(characterId);
637 if (!bag)
638 { return null; }
639 if (cargo.kind !== "item")
640 { return null; }
641
642 const stack = cargo.stack;
643 const isCeLetter = stack?.itemId === ItemId.letter && isCentralExchangeLetter(stack.instance);
644 const isRestNoticeLetter = stack?.itemId === ItemId.letter && isBankRestNoticeLetter(stack.instance);
645
646 if (stack?.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
647 {
648 this.#redeemChequeIntoVault(characterId, bag, stack);
649 this.#maybeRecordRestNotice({
650 characterId,
651 stack,
652 senderCharacterId,
653 recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter
654 });
655 return null;
656 }
657
658 const def = itemDefinition(stack.itemId);
659 const vault = normalizeVault(
660 bag.vaultReserved != null
661 ? { slots: bag.vault, reserved: bag.vaultReserved }
662 : bag.vault
663 );
664 const result = insertStackGrowable(vault.slots, stack, def);
665 bag.vault = result.slots;
666 bag.vaultReserved = vault.reserved;
667 this.#persistBag(characterId, bag);
668
669 this.#maybeRecordRestNotice({
670 characterId,
671 stack,
672 senderCharacterId,
673 recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter
674 });
675
676 if (onlineId && isRestNoticeLetter)
677 {
678 return {
679 type: "toast",
680 characterId,
681 message: "A letter arrived for you at the bank."
682 };
683 }
684 return null;
685 }
686
687 #maybeRecordRestNotice ({ characterId, stack, senderCharacterId, recordRestNotice })
688 {
689 if (!recordRestNotice || !stack)
690 { return; }
691 const sender = senderCharacterId ? this.stateDb.getCharacter(senderCharacterId) : null;
692 const senderDisplayName = sender
693 ? `${sender.first_name} ${sender.last_name}`.trim()
694 : null;
695 this.stateDb.appendBankRestNotice(characterId, {
696 itemId: stack.itemId,
697 itemName: itemNameForNotice(stack),
698 quantity: stack.quantity | 0 || 1,
699 sourceName: sourceNameForVaultDeposit(stack, senderCharacterId, senderDisplayName)
700 });
701 }
702
703 /** Pigeon/bank delivery of a filled cheque deposits the reserved goods, not the paper. */
704 #redeemChequeIntoVault (characterId, bag, chequeStack)
705 {
706 const instance = chequeStack.instance;
707 const issuerId = instance.issuerCharacterId;
708 const goodsDef = itemDefinition(instance.itemId);
709 if (!goodsDef)
710 { return; }
711
712 let reservedStack = null;
713 if (Number(issuerId) === Number(characterId))
714 {
715 const reserved = [...(bag.vaultReserved ?? [])];
716 const index = findReservedChequeIndex(reserved, instance);
717 if (index < 0)
718 {
719 // Paper arrived but reservation is gone — keep the cheque so it isn't silently lost.
720 const def = itemDefinition(ItemId.filledCheque);
721 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
722 const result = insertStackGrowable(vault.slots, chequeStack, def);
723 bag.vault = result.slots;
724 bag.vaultReserved = vault.reserved;
725 this.#persistBag(characterId, bag);
726 return;
727 }
728 reservedStack = reserved[index];
729 reserved.splice(index, 1);
730 bag.vaultReserved = reserved;
731 }
732 else
733 {
734 const release = this.simulation.releaseChequeReservation(issuerId, instance.chequeId, instance);
735 if (!release?.ok)
736 {
737 const def = itemDefinition(ItemId.filledCheque);
738 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
739 const result = insertStackGrowable(vault.slots, chequeStack, def);
740 bag.vault = result.slots;
741 bag.vaultReserved = vault.reserved;
742 this.#persistBag(characterId, bag);
743 return;
744 }
745 reservedStack = release.stack;
746 }
747
748 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
749 const goodsStack = attachOrigins({
750 itemId: reservedStack.itemId,
751 quantity: reservedStack.quantity,
752 origins: normalizeOrigins(reservedStack),
753 instance: reservedStack.instance ?? null
754 });
755 const inserted = insertStackGrowable(vault.slots, goodsStack, goodsDef);
756 bag.vault = inserted.slots;
757 bag.vaultReserved = vault.reserved;
758 this.#persistBag(characterId, bag);
759 this.#maybeRecordRestNotice({
760 characterId,
761 stack: goodsStack,
762 senderCharacterId: null,
763 recordRestNotice: !this.simulation.characterEntities.get(characterId)
764 });
765 }
766
767 #persistBag (characterId, bag)
768 {
769 this.stateDb.saveBag(characterId, bag);
770 const onlineId = this.simulation.characterEntities.get(characterId);
771 if (onlineId)
772 {
773 this.simulation.applyBag(onlineId, bag);
774 this.simulation.pushInventory(characterId, bag);
775 }
776 }
777
778 #characterDisplayName (characterId)
779 {
780 const row = this.stateDb.getCharacter(characterId);
781 return {
782 firstName: row?.first_name ?? "Unknown",
783 lastName: row?.last_name ?? "",
784 full: row ? `${row.first_name} ${row.last_name}`.trim() : "Adventurer"
785 };
786 }
787
788 #dispatchBankRestNotice (characterId, tileX, tileY)
789 {
790 const entries = this.stateDb.listBankRestNotices(characterId);
791 if (!entries.length)
792 { return null; }
793 const bank = this.nearestBank(tileX, tileY);
794 if (!bank)
795 { return null; }
796
797 const lines = mergeBankRestNoticeLines(entries.map((entry) => ({
798 quantity: entry.quantity,
799 itemName: entry.itemName,
800 sourceName: entry.sourceName
801 })));
802 const { full: playerName } = this.#characterDisplayName(characterId);
803 const body = bankRestNoticeLetterBody({ playerName, lines });
804 const stack = makeSystemLetterStack({
805 authorDisplayName: BANK_LETTER_AUTHOR,
806 body,
807 bankRestNotice: true
808 });
809 this.stateDb.clearBankRestNotices(characterId);
810 return this.dispatchSystemLetter({
811 characterId,
812 originTileX: bank.tileX,
813 originTileY: bank.tileY,
814 stack
815 });
816 }
817}