2 Commits
Author SHA1 Message Date
dmg de8ff83c3c feat(notifications): add login quest counts and claim reminders
Release / release (push) Successful in 2m40s
CI / build (push) Successful in 1m17s
2026-09-06 21:34:24 -04:00
dmg 02f74d1822 feat(quests): show custom reward item names
Release / release (push) Successful in 2m37s
CI / build (push) Successful in 1m11s
2026-09-05 11:39:01 -04:00
16 changed files with 452 additions and 10 deletions
+1 -1
View File
@@ -6,7 +6,7 @@ The approved behavior is specified in the [OKF knowledge bundle](knowledge/index
## Status
Administrators can register persistent shared quest boards by targeting a block within five blocks and running `/questadmin createboard`. They can instead run `/questadmin createboard physical` to generate a five-wide oak board above the targeted ground anchor, with glowing centered title and browsing-instruction signs above three decorative signs; its visible panel blocks and all five signs are registered. Right-clicking any registered board opens a compact native dashboard with dedicated browsing, creation, and claim screens. A player can request a block and quantity while escrowing the exact reward stack held in their main hand. Every board and `/quests list` show the same active quests with requested blocks, rewards, issuers, and time remaining. Players can complete quests at any board or with `/quests complete <quest>` by delivering the required blocks. Exact escrowed rewards are granted immediately, and delivered blocks are held for the issuer. Issuers can cancel their own active quests at any board or with `/quests cancel <quest>`. Completed deliveries and rewards from cancelled or seven-day-expired quests are held durably and can be collected at any board or with `/quests claim`; inventory overflow drops at the claimant's feet.
Administrators can register persistent shared quest boards by targeting a block within five blocks and running `/questadmin createboard`. They can instead run `/questadmin createboard physical` to generate a five-wide oak board above the targeted ground anchor, with glowing centered title and browsing-instruction signs above three decorative signs; its visible panel blocks and all five signs are registered. Right-clicking any registered board opens a compact native dashboard with dedicated browsing, creation, and claim screens. A player can request a block and quantity while escrowing the exact reward stack held in their main hand. Every board and `/quests list` show the same active quests with requested blocks, rewards, issuers, and time remaining; custom reward names are shown together with their material type. Players can complete quests at any board or with `/quests complete <quest>` by delivering the required blocks. Exact escrowed rewards are granted immediately, and delivered blocks are held for the issuer. Issuers can cancel their own active quests at any board or with `/quests cancel <quest>`. Completed deliveries and rewards from cancelled or seven-day-expired quests are held durably and can be collected at any board or with `/quests claim`; inventory overflow drops at the claimant's feet.
## Requirements
+2
View File
@@ -9,6 +9,8 @@ okf_version: "0.1"
This bundle specifies shared physical quest boards, reward escrow, block deliveries, item claims, player commands, administration, persistence, and plugin delivery requirements.
Login guidance is covered by [quest browsing](user-stories/us-004-browse-available-quests.md) and [recurring pending-item reminders](user-stories/us-007-expire-quests-and-claim-held-items.md).
## Explore
- [User stories](user-stories/index.md)
+14
View File
@@ -112,3 +112,17 @@ description: Chronological record of material decisions affecting Spigot Quest B
- Kept listing, completion, cancellation, and claiming commands disabled under that setting while preserving global command behavior when enabled.
- Enforced same-world Euclidean proximity with an inclusive five-block boundary for custom and generated boards.
- Verified 121 tests and the plugin JAR with `./gradlew clean check jar`.
## 2026-09-05 — Named reward identification
- Displayed custom reward names together with their material type in shared board details and command listings, such as `1 × Shopping List (PAPER)`.
- Stored safe plain-text custom names alongside unchanged exact item metadata and inferred names from valid historical escrow data when possible.
- Kept malformed or unavailable metadata from blocking quest browsing by falling back to material descriptions.
- Verified 128 tests and the plugin JAR with `./gradlew clean check jar`.
## 2026-09-07T01:31:27Z — Login quest guidance and recurring claim reminders
- Extended [US-004](user-stories/us-004-browse-available-quests.md) with a private active, unexpired quest count on every login and guidance to visit the quest board to accept or create a quest.
- Extended [US-007](user-stories/us-007-expire-quests-and-claim-held-items.md) with reminders on every login while actual pending claims remain, independently of notification acknowledgement and across reloads.
- Preserved existing real-time and durable notifications without changing claim storage or collection.
- Confirmed new behavior tests failed before implementation, then verified all 130 tests and the plugin JAR with `./gradlew clean check jar`.
+3 -2
View File
@@ -9,12 +9,13 @@ description: Catalog of user stories for the Spigot Quest Board plugin.
1. [US-001: Build and release the plugin](us-001-build-and-release-plugin.md)
2. [US-002: Create and use shared quest boards](us-002-create-and-use-shared-quest-boards.md)
3. [US-003: Create a block-delivery quest](us-003-create-a-block-delivery-quest.md)
4. [US-004: Browse available quests](us-004-browse-available-quests.md)
4. [US-004: Browse available quests](us-004-browse-available-quests.md) — includes login quest counts and board guidance.
5. [US-005: Deliver blocks and complete a quest](us-005-deliver-blocks-and-complete-a-quest.md)
6. [US-006: Cancel an owned quest](us-006-cancel-an-owned-quest.md)
7. [US-007: Expire quests and claim held items](us-007-expire-quests-and-claim-held-items.md)
7. [US-007: Expire quests and claim held items](us-007-expire-quests-and-claim-held-items.md) — includes recurring login reminders for unclaimed items.
8. [US-008: Control player quest commands](us-008-control-player-quest-commands.md)
9. [US-009: Use a screen-fitting quest-board interface](us-009-use-a-screen-fitting-quest-board-interface.md)
10. [US-010: Generate a physical quest-board structure](us-010-generate-a-physical-quest-board.md)
11. [US-011: Add readable physical-board signage](us-011-add-readable-physical-board-signage.md)
12. [US-012: Create quests by command near a board](us-012-create-quests-near-a-board.md)
13. [US-013: Show custom reward item names](us-013-show-custom-reward-item-names.md)
@@ -19,7 +19,11 @@ As a **player**, I want to browse current quests so that I can decide which bloc
- [x] Listing and autocomplete do not expose stale quest identifiers as completable or cancellable.
- [x] Automated tests verify filtering, displayed fields, duration boundaries, and command aliases.
- [x] Every login privately reports the global active, unexpired quest count with natural zero and singular wording, followed by “Visit the quest board to accept or create a quest.”
- [x] Automated tests verify repeated login summaries, count wording, and exclusion of completed, cancelled, and expired quests.
## Related
- [US-002: Create and use shared quest boards](us-002-create-and-use-shared-quest-boards.md)
- [US-005: Deliver blocks and complete a quest](us-005-deliver-blocks-and-complete-a-quest.md)
- [US-013: Show custom reward item names](us-013-show-custom-reward-item-names.md)
@@ -24,6 +24,10 @@ As a **quest issuer**, I want delivered blocks and returned rewards held at the
- [x] Pending claims and notification state survive logout and server restart without duplication or loss.
- [x] Automated tests verify expiry boundaries, each claim source, notifications, overflow, failure recovery, and persistence.
- [x] Every login with pending claims shows “You have items waiting to be claimed. Visit the quest board to collect them.” independently of previous notification delivery.
- [x] Reminders stop once all items are claimed, preserve real-time notifications, and do not change claims or item storage.
- [x] Automated tests verify recurring reminders across logins and reloads, isolation by player, and silence after collection.
## Related
- [US-005: Deliver blocks and complete a quest](us-005-deliver-blocks-and-complete-a-quest.md)
@@ -0,0 +1,26 @@
---
type: User Story
title: "US-013: Show custom reward item names"
description: Display a reward item's custom name together with its material type when browsing quests.
status: done
---
# US-013: Show custom reward item names
As a **player**, I want named reward items identified by both custom name and material so that I understand exactly what a quest will award.
## Acceptance criteria
- [x] A reward with a custom display name is shown as amount, readable custom name, and material type, such as `1 × Shopping List (PAPER)`.
- [x] An unnamed reward continues to show its amount and material type, such as `3 × DIAMOND`.
- [x] Styled custom names are converted to safe readable plain text without changing the escrowed item's exact metadata.
- [x] Quest-board detail dialogs and `/quests` listings use the same reward representation.
- [x] Newly escrowed rewards persist the readable custom name alongside their exact serialized item data.
- [x] Existing persisted named rewards derive their custom name from valid stored item metadata when possible.
- [x] Missing, malformed, or unreadable item metadata safely falls back to the material type without preventing quest browsing.
- [x] Automated tests verify named, unnamed, styled, persisted, historical, and malformed reward metadata.
## Related
- [US-003: Create a block-delivery quest](us-003-create-a-block-delivery-quest.md)
- [US-004: Browse available quests](us-004-browse-available-quests.md)
@@ -1,6 +1,7 @@
package games.dmg.spigotquestboard;
import java.io.IOException;
import java.time.Clock;
import java.util.Objects;
import java.util.UUID;
import java.util.logging.Level;
@@ -15,11 +16,17 @@ final class BukkitIssuerNotifier implements IssuerNotifier, Listener {
private final QuestService quests;
private final Server server;
private final Logger logger;
private final Clock clock;
BukkitIssuerNotifier(QuestService quests, Server server, Logger logger) {
this(quests, server, logger, Clock.systemUTC());
}
BukkitIssuerNotifier(QuestService quests, Server server, Logger logger, Clock clock) {
this.quests = Objects.requireNonNull(quests, "quests");
this.server = Objects.requireNonNull(server, "server");
this.logger = Objects.requireNonNull(logger, "logger");
this.clock = Objects.requireNonNull(clock, "clock");
}
@Override
@@ -32,7 +39,20 @@ final class BukkitIssuerNotifier implements IssuerNotifier, Listener {
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
deliver(event.getPlayer());
Player player = event.getPlayer();
int count = quests.activeQuests(clock.instant()).size();
String summary = switch (count) {
case 0 -> "No quests are currently available.";
case 1 -> "1 quest is currently available.";
default -> count + " quests are currently available.";
};
player.sendMessage(summary + " Visit the quest board to accept or create a quest.");
if (!quests.claimsFor(player.getUniqueId()).isEmpty()) {
player.sendMessage(
"You have items waiting to be claimed. Visit the quest board to collect them."
);
}
deliver(player);
}
void deliver(Player player) {
@@ -2,10 +2,17 @@ package games.dmg.spigotquestboard;
import java.util.Base64;
import java.util.Objects;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
record EscrowItem(String material, int amount, String serializedItem, String customName) {
EscrowItem(String material, int amount, String serializedItem) {
this(material, amount, serializedItem, null);
}
record EscrowItem(String material, int amount, String serializedItem) {
EscrowItem {
Objects.requireNonNull(material, "material");
material = material.trim().toUpperCase(java.util.Locale.ROOT);
@@ -18,24 +25,43 @@ record EscrowItem(String material, int amount, String serializedItem) {
if (serializedItem != null && serializedItem.isBlank()) {
throw new IllegalArgumentException("Serialized item must not be blank");
}
customName = normalizeReadableName(customName);
}
static EscrowItem fromItemStack(ItemStack stack) {
Objects.requireNonNull(stack, "stack");
if (stack.getType().isAir() || stack.getAmount() <= 0) {
if (isAir(stack.getType()) || stack.getAmount() <= 0) {
throw new IllegalArgumentException("Reward stack must not be empty");
}
ItemStack snapshot = stack.clone();
return new EscrowItem(
snapshot.getType().name(), snapshot.getAmount(),
Base64.getEncoder().encodeToString(snapshot.serializeAsBytes())
Base64.getEncoder().encodeToString(snapshot.serializeAsBytes()),
readableCustomName(snapshot)
);
}
EscrowItem inferCustomName() {
if (customName != null || serializedItem == null) {
return this;
}
try {
String inferredName = readableCustomName(deserializeExactItem());
return inferredName == null
? this : new EscrowItem(material, amount, serializedItem, inferredName);
} catch (RuntimeException | LinkageError exception) {
return this;
}
}
ItemStack toItemStack() {
if (serializedItem == null) {
return new ItemStack(Objects.requireNonNull(Material.matchMaterial(material)), amount);
}
return deserializeExactItem();
}
private ItemStack deserializeExactItem() {
final ItemStack stack;
try {
stack = ItemStack.deserializeBytes(Base64.getDecoder().decode(serializedItem));
@@ -47,4 +73,34 @@ record EscrowItem(String material, int amount, String serializedItem) {
}
return stack;
}
private static boolean isAir(Material material) {
return material == Material.AIR || material == Material.CAVE_AIR
|| material == Material.VOID_AIR;
}
private static String readableCustomName(ItemStack stack) {
if (!stack.hasItemMeta()) {
return null;
}
ItemMeta metadata = stack.getItemMeta();
if (!metadata.hasCustomName()) {
return null;
}
Component name = metadata.customName();
if (name == null) {
return null;
}
return normalizeReadableName(
PlainTextComponentSerializer.plainText().serialize(name)
);
}
private static String normalizeReadableName(String name) {
if (name == null) {
return null;
}
String normalized = name.replaceAll("[\\p{Cntrl}\\s]+", " ").trim();
return normalized.isEmpty() ? null : normalized;
}
}
@@ -37,6 +37,9 @@ final class QuestListingFormatter {
}
private static String formatReward(EscrowItem item) {
if (item.customName() != null) {
return item.amount() + " × " + item.customName() + " (" + item.material() + ")";
}
return item.amount() + " × " + item.material()
+ (item.serializedItem() == null ? "" : " (with exact item data)");
}
@@ -41,7 +41,7 @@ public final class SpigotQuestBoardPlugin extends JavaPlugin {
);
Clock clock = Clock.systemUTC();
BukkitIssuerNotifier notifier = new BukkitIssuerNotifier(
quests, getServer(), getLogger()
quests, getServer(), getLogger(), clock
);
QuestCompletionGateway completer = new QuestCompletionController(
quests, new BukkitQuestCompletionInventory(), notifier
@@ -165,9 +165,14 @@ final class YamlQuestRepository implements QuestRepository {
if (data != null && !(data instanceof String)) {
throw new IllegalArgumentException("Invalid item-data");
}
Object customName = entry.get("custom-name");
if (customName != null && !(customName instanceof String)) {
throw new IllegalArgumentException("Invalid custom-name");
}
items.add(new EscrowItem(
requiredString(entry, "material"), requiredInteger(entry, "amount"), (String) data
));
requiredString(entry, "material"), requiredInteger(entry, "amount"),
(String) data, (String) customName
).inferCustomName());
}
return items;
}
@@ -181,6 +186,9 @@ final class YamlQuestRepository implements QuestRepository {
if (item.serializedItem() != null) {
serialized.put("item-data", item.serializedItem());
}
if (item.customName() != null) {
serialized.put("custom-name", item.customName());
}
serializedItems.add(serialized);
}
return serializedItems;
@@ -4,15 +4,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.List;
import java.util.UUID;
import java.util.logging.Logger;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerJoinEvent;
import org.junit.jupiter.api.Test;
final class BukkitIssuerNotifierTest {
@@ -82,6 +88,90 @@ final class BukkitIssuerNotifierTest {
assertTrue(service.state().notifications().isEmpty());
}
@Test
void everyLoginReportsAvailableQuestsWithNaturalWordingAndBoardHint() throws Exception {
QuestService service = new QuestService(new Repository());
Instant now = Instant.EPOCH.plusSeconds(604800);
BukkitIssuerNotifier notifier = new BukkitIssuerNotifier(
service, mock(Server.class), Logger.getAnonymousLogger(),
Clock.fixed(now, ZoneOffset.UTC)
);
Player player = mock(Player.class);
when(player.getUniqueId()).thenReturn(UUID.randomUUID());
PlayerJoinEvent event = mock(PlayerJoinEvent.class);
when(event.getPlayer()).thenReturn(player);
String hint = " Visit the quest board to accept or create a quest.";
// Expired at exactly login time, even before the expiry task runs.
createQuest(service, Instant.EPOCH);
Quest completed = createQuest(service, now);
service.complete(completed.id(), new EscrowItem("STONE", 1, null), now);
Quest cancelled = createQuest(service, now);
service.cancel(cancelled.id(), cancelled.issuerId(), now);
notifier.onPlayerJoin(event);
verify(player).sendMessage("No quests are currently available." + hint);
createQuest(service, now);
notifier.onPlayerJoin(event);
verify(player).sendMessage("1 quest is currently available." + hint);
createQuest(service, now);
notifier.onPlayerJoin(event);
notifier.onPlayerJoin(event);
verify(player, times(2)).sendMessage("2 quests are currently available." + hint);
verify(player, never()).sendMessage(contains("items waiting"));
}
@Test
void claimsAreRemindedOnEveryLoginAcrossReloadsUntilAllCollected() throws Exception {
Repository repository = new Repository();
QuestService service = completedService(repository);
UUID issuer = service.state().notifications().values().iterator().next().recipientId();
Quest cancelled = service.create(
issuer, "Issuer", "STONE", 1,
List.of(new EscrowItem("DIAMOND", 1, null)), Instant.EPOCH
);
service.cancel(cancelled.id(), issuer, Instant.EPOCH.plusSeconds(1));
Player player = mock(Player.class);
when(player.getUniqueId()).thenReturn(issuer);
PlayerJoinEvent event = mock(PlayerJoinEvent.class);
when(event.getPlayer()).thenReturn(player);
String reminder = "You have items waiting to be claimed. "
+ "Visit the quest board to collect them.";
BukkitIssuerNotifier notifier = new BukkitIssuerNotifier(
service, mock(Server.class), Logger.getAnonymousLogger()
);
notifier.onPlayerJoin(event);
notifier.onPlayerJoin(event);
verify(player, times(2)).sendMessage(reminder);
assertTrue(service.pendingNotifications(issuer).isEmpty());
assertEquals(2, service.claimsFor(issuer).size());
service = new QuestService(repository);
notifier = new BukkitIssuerNotifier(service, mock(Server.class), Logger.getAnonymousLogger());
notifier.onPlayerJoin(event);
verify(player, times(3)).sendMessage(reminder);
service.acknowledgeClaim(issuer, service.claimsFor(issuer).getFirst().id());
notifier.onPlayerJoin(event);
verify(player, times(4)).sendMessage(reminder);
clearInvocations(player);
when(player.getUniqueId()).thenReturn(UUID.randomUUID());
notifier.onPlayerJoin(event);
verify(player, never()).sendMessage(reminder);
when(player.getUniqueId()).thenReturn(issuer);
service.acknowledgeClaim(issuer, service.claimsFor(issuer).getFirst().id());
notifier.onPlayerJoin(event);
verify(player, never()).sendMessage(reminder);
}
private static Quest createQuest(QuestService service, Instant now) throws Exception {
return service.create(
UUID.randomUUID(), "Issuer", "STONE", 1,
List.of(new EscrowItem("DIAMOND", 1, null)), now
);
}
private static QuestService completedService(Repository repository) throws Exception {
QuestService service = new QuestService(repository);
Quest quest = service.create(
@@ -0,0 +1,82 @@
package games.dmg.spigotquestboard;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Base64;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
final class EscrowItemTest {
@Test
void capturesStyledCustomNameAsSafePlainTextWithoutChangingSerializedBytes() {
byte[] exactBytes = new byte[] {1, 2, 3, 4};
ItemStack original = mock(ItemStack.class);
ItemStack snapshot = mock(ItemStack.class);
ItemMeta metadata = mock(ItemMeta.class);
when(original.getType()).thenReturn(Material.PAPER);
when(original.getAmount()).thenReturn(2);
when(original.clone()).thenReturn(snapshot);
when(snapshot.getType()).thenReturn(Material.PAPER);
when(snapshot.getAmount()).thenReturn(2);
when(snapshot.serializeAsBytes()).thenReturn(exactBytes);
when(snapshot.hasItemMeta()).thenReturn(true);
when(snapshot.getItemMeta()).thenReturn(metadata);
when(metadata.hasCustomName()).thenReturn(true);
when(metadata.customName()).thenReturn(
Component.text(" Shopping", NamedTextColor.GOLD, TextDecoration.BOLD)
.append(Component.text("\nList ", NamedTextColor.BLUE))
);
EscrowItem escrow = EscrowItem.fromItemStack(original);
assertEquals("Shopping List", escrow.customName());
assertArrayEquals(exactBytes, Base64.getDecoder().decode(escrow.serializedItem()));
}
@Test
void ignoresVanillaDisplayNameWhenNoTrueCustomNameExists() {
ItemStack original = mock(ItemStack.class);
ItemStack snapshot = mock(ItemStack.class);
ItemMeta metadata = mock(ItemMeta.class);
when(original.getType()).thenReturn(Material.DIAMOND);
when(original.getAmount()).thenReturn(3);
when(original.clone()).thenReturn(snapshot);
when(snapshot.getType()).thenReturn(Material.DIAMOND);
when(snapshot.getAmount()).thenReturn(3);
when(snapshot.serializeAsBytes()).thenReturn(new byte[] {9});
when(snapshot.hasItemMeta()).thenReturn(true);
when(snapshot.getItemMeta()).thenReturn(metadata);
when(metadata.hasCustomName()).thenReturn(false);
assertNull(EscrowItem.fromItemStack(original).customName());
}
@Test
void historicalInferenceDoesNotWeakenExactEnvelopeValidation() {
String data = Base64.getEncoder().encodeToString(new byte[] {7});
EscrowItem escrow = new EscrowItem("PAPER", 1, data);
ItemStack mismatched = mock(ItemStack.class);
when(mismatched.getType()).thenReturn(Material.BOOK);
when(mismatched.getAmount()).thenReturn(1);
try (MockedStatic<ItemStack> itemStacks = Mockito.mockStatic(ItemStack.class)) {
itemStacks.when(() -> ItemStack.deserializeBytes(Mockito.any(byte[].class)))
.thenReturn(mismatched);
assertEquals(escrow, escrow.inferCustomName());
assertThrows(IllegalStateException.class, escrow::toItemStack);
}
}
}
@@ -32,6 +32,19 @@ final class QuestListingFormatterTest {
assertTrue(listing.contains("Time remaining: 1d 1h 1m 1s"));
}
@Test
void showsCustomRewardNameTogetherWithMaterialType() {
Quest quest = quest(
NOW.plusSeconds(60),
List.of(new EscrowItem("PAPER", 1, "opaque-exact-data", "Shopping List"))
);
String listing = QuestListingFormatter.format(quest, NOW);
assertTrue(listing.contains("1 × Shopping List (PAPER)"));
assertFalse(listing.contains("PAPER (with exact item data)"));
}
@Test
void roundsAnActiveSubsecondBoundaryUpToOneSecond() {
Quest quest = quest(NOW.plusNanos(1), List.of(new EscrowItem("DIAMOND", 1, null)));
@@ -1,8 +1,11 @@
package games.dmg.spigotquestboard;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.nio.file.Files;
@@ -12,8 +15,14 @@ import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.kyori.adventure.text.Component;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
final class YamlQuestRepositoryTest {
@TempDir Path temporaryDirectory;
@@ -53,6 +62,90 @@ final class YamlQuestRepositoryTest {
assertTrue(yaml.contains(itemData));
}
@Test
void persistsCustomNamesForRewardAndClaimItems() throws Exception {
Path path = temporaryDirectory.resolve("quests.yml");
YamlQuestRepository repository = new YamlQuestRepository(path);
UUID ownerId = UUID.randomUUID();
UUID questId = UUID.randomUUID();
Quest quest = new Quest(
questId, ownerId, "Issuer", "STONE", 1,
List.of(new EscrowItem("PAPER", 1, "reward-data", "Shopping List")),
Instant.parse("2026-09-05T03:00:00Z"),
Instant.parse("2026-09-12T03:00:00Z"), QuestStatus.COMPLETED
);
QuestClaim claim = new QuestClaim(
UUID.randomUUID(), questId, ownerId,
List.of(new EscrowItem("BOOK", 1, "claim-data", "Field Notes")),
Instant.parse("2026-09-05T03:01:00Z")
);
QuestState state = new QuestState(
Map.of(questId, quest), Map.of(ownerId, List.of(claim)), Map.of()
);
repository.save(state);
assertEquals(state, repository.load());
String yaml = Files.readString(path);
assertTrue(yaml.contains("custom-name: Shopping List"));
assertTrue(yaml.contains("custom-name: Field Notes"));
}
@Test
void infersHistoricalCustomNameFromExactDataAndPersistsItOnNextSave() throws Exception {
Path path = temporaryDirectory.resolve("quests.yml");
String itemData = Base64.getEncoder().encodeToString(new byte[] {7});
writeHistoricalQuest(path, itemData);
ItemStack stack = mock(ItemStack.class);
ItemMeta metadata = mock(ItemMeta.class);
when(stack.getType()).thenReturn(Material.PAPER);
when(stack.getAmount()).thenReturn(1);
when(stack.hasItemMeta()).thenReturn(true);
when(stack.getItemMeta()).thenReturn(metadata);
when(metadata.hasCustomName()).thenReturn(true);
when(metadata.customName()).thenReturn(Component.text("Archived List"));
YamlQuestRepository repository = new YamlQuestRepository(path);
QuestState loaded;
try (MockedStatic<ItemStack> itemStacks = Mockito.mockStatic(ItemStack.class)) {
itemStacks.when(() -> ItemStack.deserializeBytes(Mockito.any(byte[].class)))
.thenReturn(stack);
loaded = repository.load();
}
assertEquals("Archived List", loaded.quests().values().iterator().next()
.reward().getFirst().customName());
assertEquals("Archived List", loaded.claims().values().iterator().next()
.getFirst().items().getFirst().customName());
repository.save(loaded);
assertTrue(Files.readString(path).contains("custom-name: Archived List"));
}
@Test
void malformedOrUnavailableHistoricalItemDataFallsBackWithoutFailingLoad() throws Exception {
Path malformedPath = temporaryDirectory.resolve("malformed.yml");
writeHistoricalQuest(malformedPath, "not-base64%%% ");
Quest malformedQuest = new YamlQuestRepository(malformedPath).load()
.quests().values().iterator().next();
assertNull(malformedQuest.reward().getFirst().customName());
assertTrue(QuestListingFormatter.format(
malformedQuest, Instant.parse("2026-09-06T03:00:00Z")
).contains("1 × PAPER (with exact item data)"));
Path unavailablePath = temporaryDirectory.resolve("unavailable.yml");
writeHistoricalQuest(unavailablePath, Base64.getEncoder().encodeToString(new byte[] {8}));
Quest unavailableQuest;
try (MockedStatic<ItemStack> itemStacks = Mockito.mockStatic(ItemStack.class)) {
itemStacks.when(() -> ItemStack.deserializeBytes(Mockito.any(byte[].class)))
.thenThrow(new IllegalStateException("server item codec unavailable"));
unavailableQuest = new YamlQuestRepository(unavailablePath).load()
.quests().values().iterator().next();
}
assertNull(unavailableQuest.reward().getFirst().customName());
}
@Test
void missingLifecycleStatusDefaultsToActiveForExistingYaml() throws Exception {
Path path = temporaryDirectory.resolve("quests.yml");
@@ -161,6 +254,32 @@ final class YamlQuestRepositoryTest {
assertEquals(QuestClaimType.RETURNED_REWARD, claim.type());
}
private static void writeHistoricalQuest(Path path, String itemData) throws IOException {
Files.writeString(path, """
quests:
- id: 00000000-0000-0000-0000-000000000010
issuer-id: 00000000-0000-0000-0000-000000000001
issuer-name: Issuer
requested-material: STONE
requested-amount: 1
created-at: '2026-09-05T03:00:00Z'
expires-at: '2026-09-12T03:00:00Z'
reward:
- material: PAPER
amount: 1
item-data: '%s'
claims:
- id: 00000000-0000-0000-0000-000000000020
quest-id: 00000000-0000-0000-0000-000000000010
owner-id: 00000000-0000-0000-0000-000000000001
created-at: '2026-09-05T04:00:00Z'
items:
- material: PAPER
amount: 1
item-data: '%s'
""".formatted(itemData, itemData));
}
@Test
void malformedStateIsRejectedRatherThanPartiallyLoaded() throws Exception {
Path path = temporaryDirectory.resolve("quests.yml");