Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ca939be6c | ||
|
|
9344390599 | ||
|
|
a09a0a3163 |
@@ -6,7 +6,7 @@ The approved behavior is specified in the [OKF knowledge bundle](knowledge/index
|
|||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
Administrators can register persistent shared quest boards by targeting a block within five blocks and running `/questadmin createboard`. Right-clicking any registered board opens a native dialog where a player can request a block and quantity while escrowing the exact reward stack held in their main hand. Delivery and claims remain under development.
|
Administrators can register persistent shared quest boards by targeting a block within five blocks and running `/questadmin createboard`. Right-clicking any registered board opens a native dialog where 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>`; exact rewards are held for later claim collection. Claim collection remains under development.
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
|
|||||||
@@ -40,3 +40,24 @@ description: Chronological record of material decisions affecting Spigot Quest B
|
|||||||
- Escrow preserves full Bukkit item metadata in durable Base64-backed YAML and rolls inventory removal back if persistence fails.
|
- Escrow preserves full Bukkit item metadata in durable Base64-backed YAML and rolls inventory removal back if persistence fails.
|
||||||
- Quests receive UUID identifiers and UTC creation and seven-day expiration timestamps.
|
- Quests receive UUID identifiers and UTC creation and seven-day expiration timestamps.
|
||||||
- Verified 26 tests and the plugin JAR with `./gradlew clean check jar`.
|
- Verified 26 tests and the plugin JAR with `./gradlew clean check jar`.
|
||||||
|
|
||||||
|
## 2026-09-05 — Shared quest browsing
|
||||||
|
|
||||||
|
- Added globally shared active-quest listings to every board and to `/quests` and `/quests list`.
|
||||||
|
- Listings include requested blocks, exact reward summaries, issuer names, and boundary-safe remaining durations.
|
||||||
|
- Added persisted lifecycle status with backward-compatible active defaults and filtered stale quest IDs from contextual completion and cancellation suggestions.
|
||||||
|
- Verified 37 tests and the plugin JAR with `./gradlew clean check jar`.
|
||||||
|
|
||||||
|
## 2026-09-05 — Block delivery and quest completion
|
||||||
|
|
||||||
|
- Added board actions and `/quests complete <quest>` for exact requested-material delivery from player inventories.
|
||||||
|
- Completion serializes state transitions, holds delivered blocks in durable issuer claims, and grants exact escrowed rewards with owner-protected overflow drops.
|
||||||
|
- Added durable online and next-login issuer notifications and rollback before persistence succeeds.
|
||||||
|
- Verified 49 tests and the plugin JAR with `./gradlew clean check jar`.
|
||||||
|
|
||||||
|
## 2026-09-05 — Issuer quest cancellation
|
||||||
|
|
||||||
|
- Added issuer-only board actions and `/quests cancel <quest>` with ownership-filtered autocomplete.
|
||||||
|
- Cancellation atomically moves exact reward escrow into an issuer claim without directly changing inventory.
|
||||||
|
- Serialized cancellation against completion and retained active state when persistence fails.
|
||||||
|
- Verified 58 tests and the plugin JAR with `./gradlew clean check jar`.
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
type: User Story
|
type: User Story
|
||||||
title: "US-004: Browse available quests"
|
title: "US-004: Browse available quests"
|
||||||
description: Let players inspect globally available quests and their essential terms.
|
description: Let players inspect globally available quests and their essential terms.
|
||||||
status: backlog
|
status: done
|
||||||
---
|
---
|
||||||
|
|
||||||
# US-004: Browse available quests
|
# US-004: Browse available quests
|
||||||
@@ -11,13 +11,13 @@ As a **player**, I want to browse current quests so that I can decide which bloc
|
|||||||
|
|
||||||
## Acceptance criteria
|
## Acceptance criteria
|
||||||
|
|
||||||
- [ ] Every registered board lists the same active quests.
|
- [x] Every registered board lists the same active quests.
|
||||||
- [ ] Each listing shows the requested block material, quantity, reward, issuer, and time remaining.
|
- [x] Each listing shows the requested block material, quantity, reward, issuer, and time remaining.
|
||||||
- [ ] Remaining durations are clear and never display an expired quest as active.
|
- [x] Remaining durations are clear and never display an expired quest as active.
|
||||||
- [ ] Completed, cancelled, and expired quests are excluded from the active listing.
|
- [x] Completed, cancelled, and expired quests are excluded from the active listing.
|
||||||
- [ ] When player commands are enabled, `/quests` and `/quests list` provide the same active quest information in chat.
|
- [x] When player commands are enabled, `/quests` and `/quests list` provide the same active quest information in chat.
|
||||||
- [ ] Listing and autocomplete do not expose stale quest identifiers as completable or cancellable.
|
- [x] Listing and autocomplete do not expose stale quest identifiers as completable or cancellable.
|
||||||
- [ ] Automated tests verify filtering, displayed fields, duration boundaries, and command aliases.
|
- [x] Automated tests verify filtering, displayed fields, duration boundaries, and command aliases.
|
||||||
|
|
||||||
## Related
|
## Related
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
type: User Story
|
type: User Story
|
||||||
title: "US-005: Deliver blocks and complete a quest"
|
title: "US-005: Deliver blocks and complete a quest"
|
||||||
description: Let a player deliver requested blocks at a quest board and receive the escrowed reward.
|
description: Let a player deliver requested blocks at a quest board and receive the escrowed reward.
|
||||||
status: backlog
|
status: done
|
||||||
---
|
---
|
||||||
|
|
||||||
# US-005: Deliver blocks and complete a quest
|
# US-005: Deliver blocks and complete a quest
|
||||||
@@ -11,17 +11,17 @@ As a **player**, I want to deliver requested blocks to a quest board so that I r
|
|||||||
|
|
||||||
## Acceptance criteria
|
## Acceptance criteria
|
||||||
|
|
||||||
- [ ] An active quest offers a Complete Quest action through every registered board.
|
- [x] An active quest offers a Complete Quest action through every registered board.
|
||||||
- [ ] Completion requires the delivering player to possess the full requested quantity of the exact block material.
|
- [x] Completion requires the delivering player to possess the full requested quantity of the exact block material.
|
||||||
- [ ] Successful completion removes the requested blocks from the delivering player's inventory and stores them as a claim for the issuer.
|
- [x] Successful completion removes the requested blocks from the delivering player's inventory and stores them as a claim for the issuer.
|
||||||
- [ ] Successful completion gives the exact escrowed reward items to the delivering player.
|
- [x] Successful completion gives the exact escrowed reward items to the delivering player.
|
||||||
- [ ] Reward items that do not fit are dropped safely at the delivering player's feet with a clear message.
|
- [x] Reward items that do not fit are dropped safely at the delivering player's feet with a clear message.
|
||||||
- [ ] The issuer is notified immediately when online or on their next login when offline that delivered blocks can be claimed at a quest board.
|
- [x] The issuer is notified immediately when online or on their next login when offline that delivered blocks can be claimed at a quest board.
|
||||||
- [ ] When player commands are enabled, `/quests complete <quest>` provides equivalent behavior with contextual autocomplete.
|
- [x] When player commands are enabled, `/quests complete <quest>` provides equivalent behavior with contextual autocomplete.
|
||||||
- [ ] Completion is atomic and exactly one player can complete a quest, including simultaneous attempts.
|
- [x] Completion is atomic and exactly one player can complete a quest, including simultaneous attempts.
|
||||||
- [ ] Validation or persistence failure does not consume delivered blocks, release rewards, or change quest state.
|
- [x] Validation or persistence failure does not consume delivered blocks, release rewards, or change quest state.
|
||||||
- [ ] Completed quests are no longer shown as active or completable.
|
- [x] Completed quests are no longer shown as active or completable.
|
||||||
- [ ] Automated tests verify inventory validation, settlement, overflow, notifications, rollback, and concurrent completion protection.
|
- [x] Automated tests verify inventory validation, settlement, overflow, notifications, rollback, and concurrent completion protection.
|
||||||
|
|
||||||
## Related
|
## Related
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
type: User Story
|
type: User Story
|
||||||
title: "US-006: Cancel an owned quest"
|
title: "US-006: Cancel an owned quest"
|
||||||
description: Let an issuer cancel an active quest and reclaim its escrowed reward safely.
|
description: Let an issuer cancel an active quest and reclaim its escrowed reward safely.
|
||||||
status: backlog
|
status: done
|
||||||
---
|
---
|
||||||
|
|
||||||
# US-006: Cancel an owned quest
|
# US-006: Cancel an owned quest
|
||||||
@@ -11,15 +11,15 @@ As a **quest issuer**, I want to cancel my active quest so that I can reclaim th
|
|||||||
|
|
||||||
## Acceptance criteria
|
## Acceptance criteria
|
||||||
|
|
||||||
- [ ] An issuer can cancel their own active quest through any registered board.
|
- [x] An issuer can cancel their own active quest through any registered board.
|
||||||
- [ ] A player cannot cancel a quest issued by another player.
|
- [x] A player cannot cancel a quest issued by another player.
|
||||||
- [ ] Completed, cancelled, and expired quests cannot be cancelled.
|
- [x] Completed, cancelled, and expired quests cannot be cancelled.
|
||||||
- [ ] Cancellation removes the quest from active listings and converts its exact escrowed reward into a claim for the issuer.
|
- [x] Cancellation removes the quest from active listings and converts its exact escrowed reward into a claim for the issuer.
|
||||||
- [ ] The reward is not inserted directly into the issuer's inventory during cancellation.
|
- [x] The reward is not inserted directly into the issuer's inventory during cancellation.
|
||||||
- [ ] When player commands are enabled, `/quests cancel <quest>` provides equivalent behavior and only autocompletes the player's cancellable quest identifiers.
|
- [x] When player commands are enabled, `/quests cancel <quest>` provides equivalent behavior and only autocompletes the player's cancellable quest identifiers.
|
||||||
- [ ] Cancellation and simultaneous completion are serialized so items cannot be duplicated or lost.
|
- [x] Cancellation and simultaneous completion are serialized so items cannot be duplicated or lost.
|
||||||
- [ ] Persistence failure leaves the quest active and its reward escrowed.
|
- [x] Persistence failure leaves the quest active and its reward escrowed.
|
||||||
- [ ] Automated tests verify ownership, state validation, claim creation, autocomplete, rollback, and completion races.
|
- [x] Automated tests verify ownership, state validation, claim creation, autocomplete, rollback, and completion races.
|
||||||
|
|
||||||
## Related
|
## Related
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
import org.bukkit.Server;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
import org.bukkit.event.EventHandler;
|
||||||
|
import org.bukkit.event.Listener;
|
||||||
|
import org.bukkit.event.player.PlayerJoinEvent;
|
||||||
|
|
||||||
|
final class BukkitIssuerNotifier implements IssuerNotifier, Listener {
|
||||||
|
private final QuestService quests;
|
||||||
|
private final Server server;
|
||||||
|
private final Logger logger;
|
||||||
|
|
||||||
|
BukkitIssuerNotifier(QuestService quests, Server server, Logger logger) {
|
||||||
|
this.quests = Objects.requireNonNull(quests, "quests");
|
||||||
|
this.server = Objects.requireNonNull(server, "server");
|
||||||
|
this.logger = Objects.requireNonNull(logger, "logger");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void notifyIfOnline(UUID issuerId) {
|
||||||
|
Player player = server.getPlayer(issuerId);
|
||||||
|
if (player != null && player.isOnline()) {
|
||||||
|
deliver(player);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler
|
||||||
|
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||||
|
deliver(event.getPlayer());
|
||||||
|
}
|
||||||
|
|
||||||
|
void deliver(Player player) {
|
||||||
|
for (IssuerNotification notification
|
||||||
|
: quests.pendingNotifications(player.getUniqueId())) {
|
||||||
|
player.sendMessage(notification.message());
|
||||||
|
try {
|
||||||
|
quests.markNotificationDelivered(notification.id());
|
||||||
|
} catch (IOException exception) {
|
||||||
|
logger.log(
|
||||||
|
Level.WARNING,
|
||||||
|
"Could not persist delivery of issuer notification " + notification.id()
|
||||||
|
+ "; it will be retried",
|
||||||
|
exception
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import org.bukkit.Material;
|
||||||
|
import org.bukkit.entity.Item;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
import org.bukkit.inventory.ItemStack;
|
||||||
|
import org.bukkit.inventory.PlayerInventory;
|
||||||
|
|
||||||
|
final class BukkitQuestCompletionInventory implements QuestCompletionInventory {
|
||||||
|
@Override
|
||||||
|
public RemovedDelivery remove(Player player, String materialName, int amount) {
|
||||||
|
Objects.requireNonNull(player, "player");
|
||||||
|
Material material = Objects.requireNonNull(Material.matchMaterial(materialName), "material");
|
||||||
|
PlayerInventory inventory = player.getInventory();
|
||||||
|
ItemStack[] contents = inventory.getStorageContents();
|
||||||
|
int available = 0;
|
||||||
|
for (ItemStack stack : contents) {
|
||||||
|
if (stack != null && stack.getType() == material) {
|
||||||
|
available += stack.getAmount();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (available < amount) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"You need exactly " + amount + " " + material.name()
|
||||||
|
+ " to complete this quest (you have " + available + ")."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<Integer, ItemStack> snapshots = new LinkedHashMap<>();
|
||||||
|
List<EscrowItem> removedItems = new ArrayList<>();
|
||||||
|
int remaining = amount;
|
||||||
|
for (int slot = 0; slot < contents.length && remaining > 0; slot++) {
|
||||||
|
ItemStack stack = contents[slot];
|
||||||
|
if (stack == null || stack.getType() != material) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
snapshots.put(slot, stack.clone());
|
||||||
|
int removedAmount = Math.min(stack.getAmount(), remaining);
|
||||||
|
ItemStack removed = stack.clone();
|
||||||
|
removed.setAmount(removedAmount);
|
||||||
|
removedItems.add(EscrowItem.fromItemStack(removed));
|
||||||
|
if (removedAmount == stack.getAmount()) {
|
||||||
|
inventory.clear(slot);
|
||||||
|
} else {
|
||||||
|
ItemStack reduced = stack.clone();
|
||||||
|
reduced.setAmount(stack.getAmount() - removedAmount);
|
||||||
|
inventory.setItem(slot, reduced);
|
||||||
|
}
|
||||||
|
remaining -= removedAmount;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new RemovedDelivery() {
|
||||||
|
private boolean rolledBack;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<EscrowItem> items() {
|
||||||
|
return List.copyOf(removedItems);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void rollback() {
|
||||||
|
if (rolledBack) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
snapshots.forEach(inventory::setItem);
|
||||||
|
rolledBack = true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PreparedReward prepare(List<EscrowItem> reward) {
|
||||||
|
List<ItemStack> stacks = reward.stream().map(EscrowItem::toItemStack).toList();
|
||||||
|
return player -> {
|
||||||
|
int overflow = 0;
|
||||||
|
for (ItemStack stack : stacks) {
|
||||||
|
Map<Integer, ItemStack> leftovers = player.getInventory().addItem(stack.clone());
|
||||||
|
for (ItemStack leftover : leftovers.values()) {
|
||||||
|
Item dropped = player.getWorld().dropItem(player.getLocation(), leftover);
|
||||||
|
dropped.setOwner(player.getUniqueId());
|
||||||
|
overflow += leftover.getAmount();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return overflow;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
record IssuerNotification(
|
||||||
|
UUID id,
|
||||||
|
UUID questId,
|
||||||
|
UUID recipientId,
|
||||||
|
String message,
|
||||||
|
Instant createdAt
|
||||||
|
) {
|
||||||
|
IssuerNotification {
|
||||||
|
Objects.requireNonNull(id, "id");
|
||||||
|
Objects.requireNonNull(questId, "questId");
|
||||||
|
Objects.requireNonNull(recipientId, "recipientId");
|
||||||
|
if (Objects.requireNonNull(message, "message").isBlank()) {
|
||||||
|
throw new IllegalArgumentException("Notification message must not be blank");
|
||||||
|
}
|
||||||
|
Objects.requireNonNull(createdAt, "createdAt");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
interface IssuerNotifier {
|
||||||
|
void notifyIfOnline(UUID issuerId);
|
||||||
|
}
|
||||||
@@ -13,7 +13,8 @@ record Quest(
|
|||||||
int requestedAmount,
|
int requestedAmount,
|
||||||
List<EscrowItem> reward,
|
List<EscrowItem> reward,
|
||||||
Instant createdAt,
|
Instant createdAt,
|
||||||
Instant expiresAt
|
Instant expiresAt,
|
||||||
|
QuestStatus status
|
||||||
) {
|
) {
|
||||||
Quest {
|
Quest {
|
||||||
Objects.requireNonNull(id, "id");
|
Objects.requireNonNull(id, "id");
|
||||||
@@ -33,8 +34,25 @@ record Quest(
|
|||||||
}
|
}
|
||||||
Objects.requireNonNull(createdAt, "createdAt");
|
Objects.requireNonNull(createdAt, "createdAt");
|
||||||
Objects.requireNonNull(expiresAt, "expiresAt");
|
Objects.requireNonNull(expiresAt, "expiresAt");
|
||||||
|
Objects.requireNonNull(status, "status");
|
||||||
if (!expiresAt.isAfter(createdAt)) {
|
if (!expiresAt.isAfter(createdAt)) {
|
||||||
throw new IllegalArgumentException("Expiration must follow creation");
|
throw new IllegalArgumentException("Expiration must follow creation");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Quest(
|
||||||
|
UUID id,
|
||||||
|
UUID issuerId,
|
||||||
|
String issuerName,
|
||||||
|
String requestedMaterial,
|
||||||
|
int requestedAmount,
|
||||||
|
List<EscrowItem> reward,
|
||||||
|
Instant createdAt,
|
||||||
|
Instant expiresAt
|
||||||
|
) {
|
||||||
|
this(
|
||||||
|
id, issuerId, issuerName, requestedMaterial, requestedAmount, reward,
|
||||||
|
createdAt, expiresAt, QuestStatus.ACTIVE
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import io.papermc.paper.registry.data.dialog.type.DialogType;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.time.Clock;
|
import java.time.Clock;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import net.kyori.adventure.text.Component;
|
import net.kyori.adventure.text.Component;
|
||||||
@@ -18,10 +19,35 @@ import org.bukkit.entity.Player;
|
|||||||
|
|
||||||
final class QuestBoardDialogUi implements QuestBoardUi {
|
final class QuestBoardDialogUi implements QuestBoardUi {
|
||||||
private final QuestCreationGateway creator;
|
private final QuestCreationGateway creator;
|
||||||
|
private final QuestBrowser browser;
|
||||||
|
private final QuestCompletionGateway completer;
|
||||||
|
private final QuestCancellationGateway canceller;
|
||||||
private final Clock clock;
|
private final Clock clock;
|
||||||
|
|
||||||
QuestBoardDialogUi(QuestCreationGateway creator, Clock clock) {
|
QuestBoardDialogUi(QuestCreationGateway creator, QuestBrowser browser, Clock clock) {
|
||||||
|
this(creator, browser, null, null, clock);
|
||||||
|
}
|
||||||
|
|
||||||
|
QuestBoardDialogUi(
|
||||||
|
QuestCreationGateway creator,
|
||||||
|
QuestBrowser browser,
|
||||||
|
QuestCompletionGateway completer,
|
||||||
|
Clock clock
|
||||||
|
) {
|
||||||
|
this(creator, browser, completer, null, clock);
|
||||||
|
}
|
||||||
|
|
||||||
|
QuestBoardDialogUi(
|
||||||
|
QuestCreationGateway creator,
|
||||||
|
QuestBrowser browser,
|
||||||
|
QuestCompletionGateway completer,
|
||||||
|
QuestCancellationGateway canceller,
|
||||||
|
Clock clock
|
||||||
|
) {
|
||||||
this.creator = Objects.requireNonNull(creator, "creator");
|
this.creator = Objects.requireNonNull(creator, "creator");
|
||||||
|
this.browser = Objects.requireNonNull(browser, "browser");
|
||||||
|
this.completer = completer;
|
||||||
|
this.canceller = canceller;
|
||||||
this.clock = Objects.requireNonNull(clock, "clock");
|
this.clock = Objects.requireNonNull(clock, "clock");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,12 +69,26 @@ final class QuestBoardDialogUi implements QuestBoardUi {
|
|||||||
.lifetime(Duration.ofMinutes(10))
|
.lifetime(Duration.ofMinutes(10))
|
||||||
.build()))
|
.build()))
|
||||||
.build();
|
.build();
|
||||||
DialogBase base = DialogBase.builder(Component.text("Create a block-delivery quest"))
|
java.time.Instant now = clock.instant();
|
||||||
.externalTitle(Component.text("Quest Board — Create"))
|
List<Quest> activeQuests = browser.activeQuests(now);
|
||||||
|
String listing = QuestListingFormatter.formatAll(activeQuests, now);
|
||||||
|
List<ActionButton> actions = new ArrayList<>();
|
||||||
|
actions.add(create);
|
||||||
|
for (Quest quest : activeQuests) {
|
||||||
|
if (completer != null) {
|
||||||
|
actions.add(completionButton(quest));
|
||||||
|
}
|
||||||
|
if (canceller != null && quest.issuerId().equals(player.getUniqueId())) {
|
||||||
|
actions.add(cancellationButton(quest));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DialogBase base = DialogBase.builder(Component.text("Quest Board"))
|
||||||
|
.externalTitle(Component.text("Quest Board — Active quests and create"))
|
||||||
.body(List.of(DialogBody.plainMessage(Component.text(
|
.body(List.of(DialogBody.plainMessage(Component.text(
|
||||||
"Hold the reward in your main hand. The entire exact stack, including all item metadata, "
|
"ACTIVE QUESTS\n" + listing + "\n\nCREATE A QUEST\n"
|
||||||
|
+ "Hold the reward in your main hand. The entire exact stack, including all item metadata, "
|
||||||
+ "will be removed and held in escrow only if this quest saves successfully."
|
+ "will be removed and held in escrow only if this quest saves successfully."
|
||||||
), 420)))
|
), 800)))
|
||||||
.inputs(List.of(
|
.inputs(List.of(
|
||||||
DialogInput.text("requested_material", Component.text("Requested block"))
|
DialogInput.text("requested_material", Component.text("Requested block"))
|
||||||
.initial("")
|
.initial("")
|
||||||
@@ -65,7 +105,84 @@ final class QuestBoardDialogUi implements QuestBoardUi {
|
|||||||
.build();
|
.build();
|
||||||
player.showDialog(Dialog.create(factory -> factory.empty()
|
player.showDialog(Dialog.create(factory -> factory.empty()
|
||||||
.base(base)
|
.base(base)
|
||||||
.type(DialogType.notice(create))));
|
.type(DialogType.multiAction(actions).columns(1).build())));
|
||||||
|
}
|
||||||
|
|
||||||
|
String listingText() {
|
||||||
|
java.time.Instant now = clock.instant();
|
||||||
|
return QuestListingFormatter.formatAll(browser.activeQuests(now), now);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ActionButton completionButton(Quest quest) {
|
||||||
|
String id = quest.id().toString();
|
||||||
|
return ActionButton.builder(Component.text(
|
||||||
|
"Complete " + quest.requestedAmount() + " " + quest.requestedMaterial()
|
||||||
|
))
|
||||||
|
.tooltip(Component.text("Deliver blocks for quest " + id))
|
||||||
|
.width(250)
|
||||||
|
.action(DialogAction.customClick((response, audience) -> {
|
||||||
|
if (audience instanceof Player respondingPlayer) {
|
||||||
|
submitCompletion(respondingPlayer, id);
|
||||||
|
}
|
||||||
|
}, ClickCallback.Options.builder()
|
||||||
|
.uses(1)
|
||||||
|
.lifetime(Duration.ofMinutes(10))
|
||||||
|
.build()))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ActionButton cancellationButton(Quest quest) {
|
||||||
|
String id = quest.id().toString();
|
||||||
|
return ActionButton.builder(Component.text(
|
||||||
|
"Cancel " + quest.requestedAmount() + " " + quest.requestedMaterial()
|
||||||
|
))
|
||||||
|
.tooltip(Component.text("Return the escrowed reward to claims for quest " + id))
|
||||||
|
.width(250)
|
||||||
|
.action(DialogAction.customClick((response, audience) -> {
|
||||||
|
if (audience instanceof Player respondingPlayer) {
|
||||||
|
submitCancellation(respondingPlayer, id);
|
||||||
|
}
|
||||||
|
}, ClickCallback.Options.builder()
|
||||||
|
.uses(1)
|
||||||
|
.lifetime(Duration.ofMinutes(10))
|
||||||
|
.build()))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> cancellableQuestIds(Player player) {
|
||||||
|
return browser.cancellableQuestIds(player.getUniqueId(), clock.instant());
|
||||||
|
}
|
||||||
|
|
||||||
|
void submitCancellation(Player player, String questId) {
|
||||||
|
if (canceller == null) {
|
||||||
|
player.sendMessage("Quest cancellation is unavailable.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
canceller.cancel(player, questId, clock.instant());
|
||||||
|
} catch (IllegalArgumentException | IllegalStateException exception) {
|
||||||
|
player.sendMessage(exception.getMessage());
|
||||||
|
} catch (IOException exception) {
|
||||||
|
player.sendMessage(
|
||||||
|
"The quest could not be saved. It remains active and its reward remains escrowed."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void submitCompletion(Player player, String questId) {
|
||||||
|
if (completer == null) {
|
||||||
|
player.sendMessage("Quest completion is unavailable.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
completer.complete(player, questId, clock.instant());
|
||||||
|
} catch (IllegalArgumentException | IllegalStateException exception) {
|
||||||
|
player.sendMessage(exception.getMessage());
|
||||||
|
} catch (IOException exception) {
|
||||||
|
player.sendMessage(
|
||||||
|
"The quest could not be saved. Your delivered blocks were restored."
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void submit(Player player, String material, String quantityText) {
|
void submit(Player player, String material, String quantityText) {
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
interface QuestBrowser {
|
||||||
|
List<Quest> activeQuests(Instant now);
|
||||||
|
|
||||||
|
default List<String> completableQuestIds(Instant now) {
|
||||||
|
return activeQuests(now).stream().map(Quest::id).map(UUID::toString).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
default List<String> cancellableQuestIds(UUID issuerId, Instant now) {
|
||||||
|
return activeQuests(now).stream()
|
||||||
|
.filter(quest -> quest.issuerId().equals(issuerId))
|
||||||
|
.map(Quest::id)
|
||||||
|
.map(UUID::toString)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
|
final class QuestCancellationController implements QuestCancellationGateway {
|
||||||
|
private final QuestService quests;
|
||||||
|
|
||||||
|
QuestCancellationController(QuestService quests) {
|
||||||
|
this.quests = Objects.requireNonNull(quests, "quests");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public QuestClaim cancel(Player player, String questId, Instant cancelledAt) throws IOException {
|
||||||
|
Objects.requireNonNull(player, "player");
|
||||||
|
final UUID id;
|
||||||
|
try {
|
||||||
|
id = UUID.fromString(Objects.requireNonNull(questId, "questId"));
|
||||||
|
} catch (IllegalArgumentException exception) {
|
||||||
|
throw new IllegalArgumentException("Quest identifier must be a valid UUID.", exception);
|
||||||
|
}
|
||||||
|
QuestClaim claim = quests.cancel(id, player.getUniqueId(), cancelledAt);
|
||||||
|
player.sendMessage(
|
||||||
|
"Quest " + id + " cancelled. Your exact escrowed reward is ready to claim at a quest board."
|
||||||
|
);
|
||||||
|
return claim;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.time.Instant;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
|
interface QuestCancellationGateway {
|
||||||
|
QuestClaim cancel(Player player, String questId, Instant cancelledAt) throws IOException;
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
record QuestClaim(
|
||||||
|
UUID id,
|
||||||
|
UUID questId,
|
||||||
|
UUID ownerId,
|
||||||
|
List<EscrowItem> items,
|
||||||
|
Instant createdAt
|
||||||
|
) {
|
||||||
|
QuestClaim {
|
||||||
|
Objects.requireNonNull(id, "id");
|
||||||
|
Objects.requireNonNull(questId, "questId");
|
||||||
|
Objects.requireNonNull(ownerId, "ownerId");
|
||||||
|
items = List.copyOf(Objects.requireNonNull(items, "items"));
|
||||||
|
if (items.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("Claim items must not be empty");
|
||||||
|
}
|
||||||
|
Objects.requireNonNull(createdAt, "createdAt");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package games.dmg.spigotquestboard;
|
|||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.time.Clock;
|
import java.time.Clock;
|
||||||
|
import java.time.Instant;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
@@ -14,10 +15,35 @@ import org.bukkit.entity.Player;
|
|||||||
final class QuestCommand implements CommandExecutor, TabCompleter {
|
final class QuestCommand implements CommandExecutor, TabCompleter {
|
||||||
private static final List<String> QUANTITIES = List.of("1", "16", "32", "64");
|
private static final List<String> QUANTITIES = List.of("1", "16", "32", "64");
|
||||||
private final QuestCreationGateway creator;
|
private final QuestCreationGateway creator;
|
||||||
|
private final QuestBrowser browser;
|
||||||
|
private final QuestCompletionGateway completer;
|
||||||
|
private final QuestCancellationGateway canceller;
|
||||||
private final Clock clock;
|
private final Clock clock;
|
||||||
|
|
||||||
QuestCommand(QuestCreationGateway creator, Clock clock) {
|
QuestCommand(QuestCreationGateway creator, QuestBrowser browser, Clock clock) {
|
||||||
|
this(creator, browser, null, null, clock);
|
||||||
|
}
|
||||||
|
|
||||||
|
QuestCommand(
|
||||||
|
QuestCreationGateway creator,
|
||||||
|
QuestBrowser browser,
|
||||||
|
QuestCompletionGateway completer,
|
||||||
|
Clock clock
|
||||||
|
) {
|
||||||
|
this(creator, browser, completer, null, clock);
|
||||||
|
}
|
||||||
|
|
||||||
|
QuestCommand(
|
||||||
|
QuestCreationGateway creator,
|
||||||
|
QuestBrowser browser,
|
||||||
|
QuestCompletionGateway completer,
|
||||||
|
QuestCancellationGateway canceller,
|
||||||
|
Clock clock
|
||||||
|
) {
|
||||||
this.creator = Objects.requireNonNull(creator, "creator");
|
this.creator = Objects.requireNonNull(creator, "creator");
|
||||||
|
this.browser = Objects.requireNonNull(browser, "browser");
|
||||||
|
this.completer = completer;
|
||||||
|
this.canceller = canceller;
|
||||||
this.clock = Objects.requireNonNull(clock, "clock");
|
this.clock = Objects.requireNonNull(clock, "clock");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,14 +51,60 @@ final class QuestCommand implements CommandExecutor, TabCompleter {
|
|||||||
public boolean onCommand(
|
public boolean onCommand(
|
||||||
CommandSender sender, Command command, String label, String[] arguments
|
CommandSender sender, Command command, String label, String[] arguments
|
||||||
) {
|
) {
|
||||||
|
if (arguments.length == 0
|
||||||
|
|| (arguments.length == 1 && "list".equalsIgnoreCase(arguments[0]))) {
|
||||||
|
Instant now = clock.instant();
|
||||||
|
sender.sendMessage(QuestListingFormatter.formatAll(browser.activeQuests(now), now));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (arguments.length == 2 && "complete".equalsIgnoreCase(arguments[0])) {
|
||||||
if (!(sender instanceof Player player)) {
|
if (!(sender instanceof Player player)) {
|
||||||
sender.sendMessage("Only players can create quests with inventory rewards.");
|
sender.sendMessage("Only players can complete quests with inventory items.");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (completer == null) {
|
||||||
|
sender.sendMessage("Quest completion is unavailable.");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
completer.complete(player, arguments[1], clock.instant());
|
||||||
|
} catch (IllegalArgumentException | IllegalStateException exception) {
|
||||||
|
sender.sendMessage(exception.getMessage());
|
||||||
|
} catch (IOException exception) {
|
||||||
|
sender.sendMessage(
|
||||||
|
"The quest could not be saved. Your delivered blocks were restored."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (arguments.length == 2 && "cancel".equalsIgnoreCase(arguments[0])) {
|
||||||
|
if (!(sender instanceof Player player)) {
|
||||||
|
sender.sendMessage("Only players can cancel quests.");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (canceller == null) {
|
||||||
|
sender.sendMessage("Quest cancellation is unavailable.");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
canceller.cancel(player, arguments[1], clock.instant());
|
||||||
|
} catch (IllegalArgumentException | IllegalStateException exception) {
|
||||||
|
sender.sendMessage(exception.getMessage());
|
||||||
|
} catch (IOException exception) {
|
||||||
|
sender.sendMessage(
|
||||||
|
"The quest could not be saved. It remains active and its reward remains escrowed."
|
||||||
|
);
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (arguments.length != 3 || !"create".equalsIgnoreCase(arguments[0])) {
|
if (arguments.length != 3 || !"create".equalsIgnoreCase(arguments[0])) {
|
||||||
usage(sender);
|
usage(sender);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
if (!(sender instanceof Player player)) {
|
||||||
|
sender.sendMessage("Only players can create quests with inventory rewards.");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
final int quantity;
|
final int quantity;
|
||||||
try {
|
try {
|
||||||
quantity = Integer.parseInt(arguments[2]);
|
quantity = Integer.parseInt(arguments[2]);
|
||||||
@@ -59,7 +131,7 @@ final class QuestCommand implements CommandExecutor, TabCompleter {
|
|||||||
return List.of();
|
return List.of();
|
||||||
}
|
}
|
||||||
if (arguments.length == 1) {
|
if (arguments.length == 1) {
|
||||||
return startsWith(List.of("create"), arguments[0]);
|
return startsWith(List.of("create", "list", "complete", "cancel"), arguments[0]);
|
||||||
}
|
}
|
||||||
if (arguments.length == 2 && "create".equalsIgnoreCase(arguments[0])) {
|
if (arguments.length == 2 && "create".equalsIgnoreCase(arguments[0])) {
|
||||||
return creator.suggestBlockMaterials(arguments[1]);
|
return creator.suggestBlockMaterials(arguments[1]);
|
||||||
@@ -67,6 +139,15 @@ final class QuestCommand implements CommandExecutor, TabCompleter {
|
|||||||
if (arguments.length == 3 && "create".equalsIgnoreCase(arguments[0])) {
|
if (arguments.length == 3 && "create".equalsIgnoreCase(arguments[0])) {
|
||||||
return startsWith(QUANTITIES, arguments[2]);
|
return startsWith(QUANTITIES, arguments[2]);
|
||||||
}
|
}
|
||||||
|
if (arguments.length == 2 && "complete".equalsIgnoreCase(arguments[0])) {
|
||||||
|
return startsWith(browser.completableQuestIds(clock.instant()), arguments[1]);
|
||||||
|
}
|
||||||
|
if (arguments.length == 2 && "cancel".equalsIgnoreCase(arguments[0])) {
|
||||||
|
Player player = (Player) sender;
|
||||||
|
return startsWith(
|
||||||
|
browser.cancellableQuestIds(player.getUniqueId(), clock.instant()), arguments[1]
|
||||||
|
);
|
||||||
|
}
|
||||||
return List.of();
|
return List.of();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,7 +159,10 @@ final class QuestCommand implements CommandExecutor, TabCompleter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static void usage(CommandSender sender) {
|
private static void usage(CommandSender sender) {
|
||||||
sender.sendMessage("Usage: /quests create <block> <quantity>");
|
sender.sendMessage(
|
||||||
|
"Usage: /quests [list] | /quests create <block> <quantity> | "
|
||||||
|
+ "/quests complete <quest> | /quests cancel <quest>"
|
||||||
|
);
|
||||||
sender.sendMessage("Hold the entire reward stack in your main hand; its exact metadata will be escrowed.");
|
sender.sendMessage("Hold the entire reward stack in your main hand; its exact metadata will be escrowed.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
record QuestCompletion(Quest quest, QuestClaim claim, List<EscrowItem> reward) {
|
||||||
|
QuestCompletion {
|
||||||
|
reward = List.copyOf(reward);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
|
final class QuestCompletionController implements QuestCompletionGateway {
|
||||||
|
private final QuestService quests;
|
||||||
|
private final QuestCompletionInventory inventory;
|
||||||
|
private final IssuerNotifier notifier;
|
||||||
|
|
||||||
|
QuestCompletionController(
|
||||||
|
QuestService quests, QuestCompletionInventory inventory, IssuerNotifier notifier
|
||||||
|
) {
|
||||||
|
this.quests = Objects.requireNonNull(quests, "quests");
|
||||||
|
this.inventory = Objects.requireNonNull(inventory, "inventory");
|
||||||
|
this.notifier = Objects.requireNonNull(notifier, "notifier");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public QuestCompletion complete(Player player, String questId, Instant completedAt)
|
||||||
|
throws IOException {
|
||||||
|
Objects.requireNonNull(player, "player");
|
||||||
|
final UUID id;
|
||||||
|
try {
|
||||||
|
id = UUID.fromString(Objects.requireNonNull(questId, "questId"));
|
||||||
|
} catch (IllegalArgumentException exception) {
|
||||||
|
throw new IllegalArgumentException("Quest identifier must be a valid UUID.", exception);
|
||||||
|
}
|
||||||
|
Quest quest = quests.completionCandidate(id, completedAt);
|
||||||
|
QuestCompletionInventory.PreparedReward reward = inventory.prepare(quest.reward());
|
||||||
|
QuestCompletionInventory.RemovedDelivery delivery = inventory.remove(
|
||||||
|
player, quest.requestedMaterial(), quest.requestedAmount()
|
||||||
|
);
|
||||||
|
final QuestCompletion completion;
|
||||||
|
try {
|
||||||
|
completion = quests.complete(id, delivery.items(), completedAt);
|
||||||
|
} catch (IOException | RuntimeException exception) {
|
||||||
|
delivery.rollback();
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
int overflow = reward.grantAndDropOverflow(player);
|
||||||
|
player.sendMessage(
|
||||||
|
"Quest " + id + " completed. You received the exact escrowed reward."
|
||||||
|
);
|
||||||
|
if (overflow > 0) {
|
||||||
|
player.sendMessage(
|
||||||
|
overflow + " reward item(s) did not fit and were dropped safely at your feet."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
notifier.notifyIfOnline(completion.quest().issuerId());
|
||||||
|
return completion;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.time.Instant;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
|
interface QuestCompletionGateway {
|
||||||
|
QuestCompletion complete(Player player, String questId, Instant completedAt) throws IOException;
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
|
||||||
|
interface QuestCompletionInventory {
|
||||||
|
RemovedDelivery remove(Player player, String material, int amount);
|
||||||
|
|
||||||
|
PreparedReward prepare(List<EscrowItem> reward);
|
||||||
|
|
||||||
|
interface RemovedDelivery {
|
||||||
|
List<EscrowItem> items();
|
||||||
|
void rollback();
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PreparedReward {
|
||||||
|
int grantAndDropOverflow(Player player);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
final class QuestListingFormatter {
|
||||||
|
private QuestListingFormatter() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static String formatAll(List<Quest> quests, Instant now) {
|
||||||
|
Objects.requireNonNull(quests, "quests");
|
||||||
|
Objects.requireNonNull(now, "now");
|
||||||
|
if (quests.isEmpty()) {
|
||||||
|
return "No active quests.";
|
||||||
|
}
|
||||||
|
return quests.stream()
|
||||||
|
.map(quest -> format(quest, now))
|
||||||
|
.collect(Collectors.joining("\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
static String format(Quest quest, Instant now) {
|
||||||
|
Objects.requireNonNull(quest, "quest");
|
||||||
|
Objects.requireNonNull(now, "now");
|
||||||
|
if (quest.status() != QuestStatus.ACTIVE || !now.isBefore(quest.expiresAt())) {
|
||||||
|
throw new IllegalArgumentException("Only active, unexpired quests can be listed");
|
||||||
|
}
|
||||||
|
String reward = quest.reward().stream()
|
||||||
|
.map(QuestListingFormatter::formatReward)
|
||||||
|
.collect(Collectors.joining(" + "));
|
||||||
|
return quest.id() + " — " + quest.requestedAmount() + " × "
|
||||||
|
+ quest.requestedMaterial() + " | Reward: " + reward
|
||||||
|
+ " | Issuer: " + quest.issuerName()
|
||||||
|
+ " | Time remaining: " + formatRemaining(now, quest.expiresAt());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String formatReward(EscrowItem item) {
|
||||||
|
return item.amount() + " × " + item.material()
|
||||||
|
+ (item.serializedItem() == null ? "" : " (with exact item data)");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String formatRemaining(Instant now, Instant expiresAt) {
|
||||||
|
Duration duration = Duration.between(now, expiresAt);
|
||||||
|
long seconds = duration.getSeconds() + (duration.getNano() == 0 ? 0 : 1);
|
||||||
|
long days = seconds / 86_400;
|
||||||
|
long hours = seconds % 86_400 / 3_600;
|
||||||
|
long minutes = seconds % 3_600 / 60;
|
||||||
|
long remainingSeconds = seconds % 60;
|
||||||
|
StringBuilder result = new StringBuilder();
|
||||||
|
appendUnit(result, days, "d");
|
||||||
|
appendUnit(result, hours, "h");
|
||||||
|
appendUnit(result, minutes, "m");
|
||||||
|
appendUnit(result, remainingSeconds, "s");
|
||||||
|
return result.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void appendUnit(StringBuilder result, long amount, String unit) {
|
||||||
|
if (amount == 0 && !result.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (amount > 0) {
|
||||||
|
if (!result.isEmpty()) {
|
||||||
|
result.append(' ');
|
||||||
|
}
|
||||||
|
result.append(amount).append(unit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,20 +3,21 @@ package games.dmg.spigotquestboard;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.time.temporal.ChronoUnit;
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
final class QuestService {
|
final class QuestService implements QuestBrowser {
|
||||||
private final QuestRepository repository;
|
private final QuestRepository repository;
|
||||||
private Map<UUID, Quest> quests;
|
private QuestState state;
|
||||||
|
|
||||||
QuestService(QuestRepository repository) throws IOException {
|
QuestService(QuestRepository repository) throws IOException {
|
||||||
this.repository = Objects.requireNonNull(repository, "repository");
|
this.repository = Objects.requireNonNull(repository, "repository");
|
||||||
quests = new LinkedHashMap<>(repository.load().quests());
|
state = repository.load();
|
||||||
}
|
}
|
||||||
|
|
||||||
synchronized Quest create(
|
synchronized Quest create(
|
||||||
@@ -38,14 +39,141 @@ final class QuestService {
|
|||||||
UUID.randomUUID(), issuerId, issuerName, material, requestedAmount,
|
UUID.randomUUID(), issuerId, issuerName, material, requestedAmount,
|
||||||
reward, createdAt, createdAt.plus(7, ChronoUnit.DAYS)
|
reward, createdAt, createdAt.plus(7, ChronoUnit.DAYS)
|
||||||
);
|
);
|
||||||
Map<UUID, Quest> candidate = new LinkedHashMap<>(quests);
|
Map<UUID, Quest> quests = new LinkedHashMap<>(state.quests());
|
||||||
candidate.put(quest.id(), quest);
|
quests.put(quest.id(), quest);
|
||||||
repository.save(new QuestState(candidate));
|
save(new QuestState(quests, state.claims(), state.notifications()));
|
||||||
quests = Map.copyOf(candidate);
|
|
||||||
return quest;
|
return quest;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
synchronized Quest completionCandidate(UUID questId, Instant now) {
|
||||||
|
Objects.requireNonNull(questId, "questId");
|
||||||
|
Objects.requireNonNull(now, "now");
|
||||||
|
Quest quest = state.quests().get(questId);
|
||||||
|
if (quest == null) {
|
||||||
|
throw new IllegalArgumentException("Quest not found: " + questId);
|
||||||
|
}
|
||||||
|
if (quest.status() != QuestStatus.ACTIVE || !now.isBefore(quest.expiresAt())) {
|
||||||
|
throw new IllegalStateException("That quest is no longer active or has expired.");
|
||||||
|
}
|
||||||
|
return quest;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized QuestCompletion complete(
|
||||||
|
UUID questId, EscrowItem delivered, Instant completedAt
|
||||||
|
) throws IOException {
|
||||||
|
return complete(questId, List.of(delivered), completedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized QuestCompletion complete(
|
||||||
|
UUID questId, List<EscrowItem> delivered, Instant completedAt
|
||||||
|
) throws IOException {
|
||||||
|
Quest active = completionCandidate(questId, completedAt);
|
||||||
|
List<EscrowItem> delivery = List.copyOf(Objects.requireNonNull(delivered, "delivered"));
|
||||||
|
if (delivery.isEmpty()
|
||||||
|
|| delivery.stream().anyMatch(item -> !item.material().equals(active.requestedMaterial()))
|
||||||
|
|| delivery.stream().mapToInt(EscrowItem::amount).sum() != active.requestedAmount()) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Delivery must contain exactly " + active.requestedAmount() + " "
|
||||||
|
+ active.requestedMaterial() + "."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Quest completed = new Quest(
|
||||||
|
active.id(), active.issuerId(), active.issuerName(), active.requestedMaterial(),
|
||||||
|
active.requestedAmount(), active.reward(), active.createdAt(), active.expiresAt(),
|
||||||
|
QuestStatus.COMPLETED
|
||||||
|
);
|
||||||
|
QuestClaim claim = new QuestClaim(
|
||||||
|
UUID.randomUUID(), active.id(), active.issuerId(), delivery, completedAt
|
||||||
|
);
|
||||||
|
IssuerNotification notification = new IssuerNotification(
|
||||||
|
UUID.randomUUID(), active.id(), active.issuerId(),
|
||||||
|
"Quest " + active.id() + " was completed. Your delivered "
|
||||||
|
+ active.requestedMaterial() + " blocks can be claimed at a quest board.",
|
||||||
|
completedAt
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<UUID, Quest> quests = new LinkedHashMap<>(state.quests());
|
||||||
|
quests.put(active.id(), completed);
|
||||||
|
Map<UUID, List<QuestClaim>> claims = new LinkedHashMap<>(state.claims());
|
||||||
|
List<QuestClaim> ownerClaims = new ArrayList<>(
|
||||||
|
claims.getOrDefault(active.issuerId(), List.of())
|
||||||
|
);
|
||||||
|
ownerClaims.add(claim);
|
||||||
|
claims.put(active.issuerId(), ownerClaims);
|
||||||
|
Map<UUID, IssuerNotification> notifications = new LinkedHashMap<>(state.notifications());
|
||||||
|
notifications.put(notification.id(), notification);
|
||||||
|
save(new QuestState(quests, claims, notifications));
|
||||||
|
return new QuestCompletion(completed, claim, completed.reward());
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized QuestClaim cancel(UUID questId, UUID issuerId, Instant cancelledAt)
|
||||||
|
throws IOException {
|
||||||
|
Objects.requireNonNull(questId, "questId");
|
||||||
|
Objects.requireNonNull(issuerId, "issuerId");
|
||||||
|
Objects.requireNonNull(cancelledAt, "cancelledAt");
|
||||||
|
Quest active = state.quests().get(questId);
|
||||||
|
if (active == null) {
|
||||||
|
throw new IllegalArgumentException("Quest not found: " + questId);
|
||||||
|
}
|
||||||
|
if (!active.issuerId().equals(issuerId)) {
|
||||||
|
throw new IllegalArgumentException("Only the quest issuer can cancel this quest.");
|
||||||
|
}
|
||||||
|
if (active.status() != QuestStatus.ACTIVE || !cancelledAt.isBefore(active.expiresAt())) {
|
||||||
|
throw new IllegalStateException("That quest is no longer active or has expired.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Quest cancelled = new Quest(
|
||||||
|
active.id(), active.issuerId(), active.issuerName(), active.requestedMaterial(),
|
||||||
|
active.requestedAmount(), active.reward(), active.createdAt(), active.expiresAt(),
|
||||||
|
QuestStatus.CANCELLED
|
||||||
|
);
|
||||||
|
QuestClaim claim = new QuestClaim(
|
||||||
|
UUID.randomUUID(), active.id(), active.issuerId(), active.reward(), cancelledAt
|
||||||
|
);
|
||||||
|
Map<UUID, Quest> quests = new LinkedHashMap<>(state.quests());
|
||||||
|
quests.put(active.id(), cancelled);
|
||||||
|
Map<UUID, List<QuestClaim>> claims = new LinkedHashMap<>(state.claims());
|
||||||
|
List<QuestClaim> ownerClaims = new ArrayList<>(
|
||||||
|
claims.getOrDefault(active.issuerId(), List.of())
|
||||||
|
);
|
||||||
|
ownerClaims.add(claim);
|
||||||
|
claims.put(active.issuerId(), ownerClaims);
|
||||||
|
save(new QuestState(quests, claims, state.notifications()));
|
||||||
|
return claim;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized List<IssuerNotification> pendingNotifications(UUID recipientId) {
|
||||||
|
Objects.requireNonNull(recipientId, "recipientId");
|
||||||
|
return state.notifications().values().stream()
|
||||||
|
.filter(notification -> notification.recipientId().equals(recipientId))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized void markNotificationDelivered(UUID notificationId) throws IOException {
|
||||||
|
if (!state.notifications().containsKey(notificationId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Map<UUID, IssuerNotification> notifications = new LinkedHashMap<>(state.notifications());
|
||||||
|
notifications.remove(notificationId);
|
||||||
|
save(new QuestState(state.quests(), state.claims(), notifications));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public synchronized List<Quest> activeQuests(Instant now) {
|
||||||
|
Objects.requireNonNull(now, "now");
|
||||||
|
return state.quests().values().stream()
|
||||||
|
.filter(quest -> quest.status() == QuestStatus.ACTIVE)
|
||||||
|
.filter(quest -> now.isBefore(quest.expiresAt()))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
synchronized QuestState state() {
|
synchronized QuestState state() {
|
||||||
return new QuestState(quests);
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void save(QuestState candidate) throws IOException {
|
||||||
|
repository.save(candidate);
|
||||||
|
state = candidate;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,16 @@
|
|||||||
package games.dmg.spigotquestboard;
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
record QuestState(Map<UUID, Quest> quests) {
|
record QuestState(
|
||||||
|
Map<UUID, Quest> quests,
|
||||||
|
Map<UUID, List<QuestClaim>> claims,
|
||||||
|
Map<UUID, IssuerNotification> notifications
|
||||||
|
) {
|
||||||
QuestState {
|
QuestState {
|
||||||
quests = Map.copyOf(Objects.requireNonNull(quests, "quests"));
|
quests = Map.copyOf(Objects.requireNonNull(quests, "quests"));
|
||||||
for (Map.Entry<UUID, Quest> entry : quests.entrySet()) {
|
for (Map.Entry<UUID, Quest> entry : quests.entrySet()) {
|
||||||
@@ -12,9 +18,29 @@ record QuestState(Map<UUID, Quest> quests) {
|
|||||||
throw new IllegalArgumentException("Quest map key does not match quest id");
|
throw new IllegalArgumentException("Quest map key does not match quest id");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Map<UUID, List<QuestClaim>> immutableClaims = new LinkedHashMap<>();
|
||||||
|
for (Map.Entry<UUID, List<QuestClaim>> entry
|
||||||
|
: Objects.requireNonNull(claims, "claims").entrySet()) {
|
||||||
|
List<QuestClaim> ownerClaims = List.copyOf(entry.getValue());
|
||||||
|
if (ownerClaims.stream().anyMatch(claim -> !claim.ownerId().equals(entry.getKey()))) {
|
||||||
|
throw new IllegalArgumentException("Claim map key does not match owner id");
|
||||||
|
}
|
||||||
|
immutableClaims.put(entry.getKey(), ownerClaims);
|
||||||
|
}
|
||||||
|
claims = Map.copyOf(immutableClaims);
|
||||||
|
notifications = Map.copyOf(Objects.requireNonNull(notifications, "notifications"));
|
||||||
|
for (Map.Entry<UUID, IssuerNotification> entry : notifications.entrySet()) {
|
||||||
|
if (!entry.getKey().equals(entry.getValue().id())) {
|
||||||
|
throw new IllegalArgumentException("Notification map key does not match id");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
QuestState(Map<UUID, Quest> quests) {
|
||||||
|
this(quests, Map.of(), Map.of());
|
||||||
}
|
}
|
||||||
|
|
||||||
static QuestState empty() {
|
static QuestState empty() {
|
||||||
return new QuestState(Map.of());
|
return new QuestState(Map.of(), Map.of(), Map.of());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
enum QuestStatus {
|
||||||
|
ACTIVE,
|
||||||
|
COMPLETED,
|
||||||
|
CANCELLED,
|
||||||
|
EXPIRED
|
||||||
|
}
|
||||||
@@ -31,12 +31,23 @@ public final class SpigotQuestBoardPlugin extends JavaPlugin {
|
|||||||
QuestCreationGateway creator = new QuestCreationController(
|
QuestCreationGateway creator = new QuestCreationController(
|
||||||
quests, new BukkitBlockMaterialCatalog(), new BukkitHeldRewardInventory()
|
quests, new BukkitBlockMaterialCatalog(), new BukkitHeldRewardInventory()
|
||||||
);
|
);
|
||||||
QuestCommand questCommand = new QuestCommand(creator, Clock.systemUTC());
|
Clock clock = Clock.systemUTC();
|
||||||
|
BukkitIssuerNotifier notifier = new BukkitIssuerNotifier(
|
||||||
|
quests, getServer(), getLogger()
|
||||||
|
);
|
||||||
|
QuestCompletionGateway completer = new QuestCompletionController(
|
||||||
|
quests, new BukkitQuestCompletionInventory(), notifier
|
||||||
|
);
|
||||||
|
QuestCancellationGateway canceller = new QuestCancellationController(quests);
|
||||||
|
QuestCommand questCommand = new QuestCommand(
|
||||||
|
creator, quests, completer, canceller, clock
|
||||||
|
);
|
||||||
command("quests").setExecutor(questCommand);
|
command("quests").setExecutor(questCommand);
|
||||||
command("quests").setTabCompleter(questCommand);
|
command("quests").setTabCompleter(questCommand);
|
||||||
|
getServer().getPluginManager().registerEvents(notifier, this);
|
||||||
getServer().getPluginManager().registerEvents(
|
getServer().getPluginManager().registerEvents(
|
||||||
new QuestBoardInteractionListener(
|
new QuestBoardInteractionListener(
|
||||||
boards, new QuestBoardDialogUi(creator, Clock.systemUTC())
|
boards, new QuestBoardDialogUi(creator, quests, completer, canceller, clock)
|
||||||
),
|
),
|
||||||
this
|
this
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -34,6 +34,8 @@ final class YamlQuestRepository implements QuestRepository {
|
|||||||
throw new IOException("Invalid quest state", exception);
|
throw new IOException("Invalid quest state", exception);
|
||||||
}
|
}
|
||||||
Map<UUID, Quest> quests = new LinkedHashMap<>();
|
Map<UUID, Quest> quests = new LinkedHashMap<>();
|
||||||
|
Map<UUID, List<QuestClaim>> claims = new LinkedHashMap<>();
|
||||||
|
Map<UUID, IssuerNotification> notifications = new LinkedHashMap<>();
|
||||||
try {
|
try {
|
||||||
for (Map<?, ?> entry : yaml.getMapList("quests")) {
|
for (Map<?, ?> entry : yaml.getMapList("quests")) {
|
||||||
UUID id = UUID.fromString(requiredString(entry, "id"));
|
UUID id = UUID.fromString(requiredString(entry, "id"));
|
||||||
@@ -43,18 +45,43 @@ final class YamlQuestRepository implements QuestRepository {
|
|||||||
requiredString(entry, "issuer-name"),
|
requiredString(entry, "issuer-name"),
|
||||||
requiredString(entry, "requested-material"),
|
requiredString(entry, "requested-material"),
|
||||||
requiredInteger(entry, "requested-amount"),
|
requiredInteger(entry, "requested-amount"),
|
||||||
readRewards(entry.get("reward")),
|
readItems(entry.get("reward"), "reward"),
|
||||||
Instant.parse(requiredString(entry, "created-at")),
|
Instant.parse(requiredString(entry, "created-at")),
|
||||||
Instant.parse(requiredString(entry, "expires-at"))
|
Instant.parse(requiredString(entry, "expires-at")),
|
||||||
|
readStatus(entry.get("status"))
|
||||||
);
|
);
|
||||||
if (quests.put(id, quest) != null) {
|
if (quests.put(id, quest) != null) {
|
||||||
throw new IllegalArgumentException("Duplicate quest id: " + id);
|
throw new IllegalArgumentException("Duplicate quest id: " + id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for (Map<?, ?> entry : yaml.getMapList("claims")) {
|
||||||
|
QuestClaim claim = new QuestClaim(
|
||||||
|
UUID.fromString(requiredString(entry, "id")),
|
||||||
|
UUID.fromString(requiredString(entry, "quest-id")),
|
||||||
|
UUID.fromString(requiredString(entry, "owner-id")),
|
||||||
|
readItems(entry.get("items"), "claim items"),
|
||||||
|
Instant.parse(requiredString(entry, "created-at"))
|
||||||
|
);
|
||||||
|
claims.computeIfAbsent(claim.ownerId(), ignored -> new ArrayList<>()).add(claim);
|
||||||
|
}
|
||||||
|
for (Map<?, ?> entry : yaml.getMapList("notifications")) {
|
||||||
|
IssuerNotification notification = new IssuerNotification(
|
||||||
|
UUID.fromString(requiredString(entry, "id")),
|
||||||
|
UUID.fromString(requiredString(entry, "quest-id")),
|
||||||
|
UUID.fromString(requiredString(entry, "recipient-id")),
|
||||||
|
requiredString(entry, "message"),
|
||||||
|
Instant.parse(requiredString(entry, "created-at"))
|
||||||
|
);
|
||||||
|
if (notifications.put(notification.id(), notification) != null) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Duplicate notification id: " + notification.id()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch (IllegalArgumentException | DateTimeParseException exception) {
|
} catch (IllegalArgumentException | DateTimeParseException exception) {
|
||||||
throw new IOException("Invalid quest record", exception);
|
throw new IOException("Invalid quest record", exception);
|
||||||
}
|
}
|
||||||
return new QuestState(quests);
|
return new QuestState(quests, claims, notifications);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -70,20 +97,37 @@ final class YamlQuestRepository implements QuestRepository {
|
|||||||
serialized.put("requested-amount", quest.requestedAmount());
|
serialized.put("requested-amount", quest.requestedAmount());
|
||||||
serialized.put("created-at", quest.createdAt().toString());
|
serialized.put("created-at", quest.createdAt().toString());
|
||||||
serialized.put("expires-at", quest.expiresAt().toString());
|
serialized.put("expires-at", quest.expiresAt().toString());
|
||||||
List<Map<String, Object>> rewards = new ArrayList<>();
|
serialized.put("status", quest.status().name());
|
||||||
for (EscrowItem reward : quest.reward()) {
|
serialized.put("reward", writeItems(quest.reward()));
|
||||||
Map<String, Object> serializedReward = new LinkedHashMap<>();
|
|
||||||
serializedReward.put("material", reward.material());
|
|
||||||
serializedReward.put("amount", reward.amount());
|
|
||||||
if (reward.serializedItem() != null) {
|
|
||||||
serializedReward.put("item-data", reward.serializedItem());
|
|
||||||
}
|
|
||||||
rewards.add(serializedReward);
|
|
||||||
}
|
|
||||||
serialized.put("reward", rewards);
|
|
||||||
serializedQuests.add(serialized);
|
serializedQuests.add(serialized);
|
||||||
}
|
}
|
||||||
yaml.set("quests", serializedQuests);
|
yaml.set("quests", serializedQuests);
|
||||||
|
|
||||||
|
List<Map<String, Object>> serializedClaims = new ArrayList<>();
|
||||||
|
for (List<QuestClaim> ownerClaims : state.claims().values()) {
|
||||||
|
for (QuestClaim claim : ownerClaims) {
|
||||||
|
Map<String, Object> serialized = new LinkedHashMap<>();
|
||||||
|
serialized.put("id", claim.id().toString());
|
||||||
|
serialized.put("quest-id", claim.questId().toString());
|
||||||
|
serialized.put("owner-id", claim.ownerId().toString());
|
||||||
|
serialized.put("created-at", claim.createdAt().toString());
|
||||||
|
serialized.put("items", writeItems(claim.items()));
|
||||||
|
serializedClaims.add(serialized);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
yaml.set("claims", serializedClaims);
|
||||||
|
|
||||||
|
List<Map<String, Object>> serializedNotifications = new ArrayList<>();
|
||||||
|
for (IssuerNotification notification : state.notifications().values()) {
|
||||||
|
Map<String, Object> serialized = new LinkedHashMap<>();
|
||||||
|
serialized.put("id", notification.id().toString());
|
||||||
|
serialized.put("quest-id", notification.questId().toString());
|
||||||
|
serialized.put("recipient-id", notification.recipientId().toString());
|
||||||
|
serialized.put("message", notification.message());
|
||||||
|
serialized.put("created-at", notification.createdAt().toString());
|
||||||
|
serializedNotifications.add(serialized);
|
||||||
|
}
|
||||||
|
yaml.set("notifications", serializedNotifications);
|
||||||
writeAtomically(yaml);
|
writeAtomically(yaml);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,24 +148,48 @@ final class YamlQuestRepository implements QuestRepository {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static List<EscrowItem> readRewards(Object value) {
|
private static List<EscrowItem> readItems(Object value, String description) {
|
||||||
if (!(value instanceof List<?> entries) || entries.isEmpty()) {
|
if (!(value instanceof List<?> entries) || entries.isEmpty()) {
|
||||||
throw new IllegalArgumentException("Missing reward");
|
throw new IllegalArgumentException("Missing " + description);
|
||||||
}
|
}
|
||||||
List<EscrowItem> rewards = new ArrayList<>();
|
List<EscrowItem> items = new ArrayList<>();
|
||||||
for (Object rawEntry : entries) {
|
for (Object rawEntry : entries) {
|
||||||
if (!(rawEntry instanceof Map<?, ?> entry)) {
|
if (!(rawEntry instanceof Map<?, ?> entry)) {
|
||||||
throw new IllegalArgumentException("Invalid reward");
|
throw new IllegalArgumentException("Invalid " + description);
|
||||||
}
|
}
|
||||||
Object data = entry.get("item-data");
|
Object data = entry.get("item-data");
|
||||||
if (data != null && !(data instanceof String)) {
|
if (data != null && !(data instanceof String)) {
|
||||||
throw new IllegalArgumentException("Invalid item-data");
|
throw new IllegalArgumentException("Invalid item-data");
|
||||||
}
|
}
|
||||||
rewards.add(new EscrowItem(
|
items.add(new EscrowItem(
|
||||||
requiredString(entry, "material"), requiredInteger(entry, "amount"), (String) data
|
requiredString(entry, "material"), requiredInteger(entry, "amount"), (String) data
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
return rewards;
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Map<String, Object>> writeItems(List<EscrowItem> items) {
|
||||||
|
List<Map<String, Object>> serializedItems = new ArrayList<>();
|
||||||
|
for (EscrowItem item : items) {
|
||||||
|
Map<String, Object> serialized = new LinkedHashMap<>();
|
||||||
|
serialized.put("material", item.material());
|
||||||
|
serialized.put("amount", item.amount());
|
||||||
|
if (item.serializedItem() != null) {
|
||||||
|
serialized.put("item-data", item.serializedItem());
|
||||||
|
}
|
||||||
|
serializedItems.add(serialized);
|
||||||
|
}
|
||||||
|
return serializedItems;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static QuestStatus readStatus(Object value) {
|
||||||
|
if (value == null) {
|
||||||
|
return QuestStatus.ACTIVE;
|
||||||
|
}
|
||||||
|
if (!(value instanceof String status)) {
|
||||||
|
throw new IllegalArgumentException("Invalid status");
|
||||||
|
}
|
||||||
|
return QuestStatus.valueOf(status);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String requiredString(Map<?, ?> entry, String key) {
|
private static String requiredString(Map<?, ?> entry, String key) {
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
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.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
import org.bukkit.Server;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
final class BukkitIssuerNotifierTest {
|
||||||
|
@Test
|
||||||
|
void onlineIssuerIsNotifiedImmediatelyAndDurablePendingStateIsCleared() throws Exception {
|
||||||
|
Repository repository = new Repository();
|
||||||
|
QuestService service = completedService(repository);
|
||||||
|
UUID issuer = service.state().notifications().values().iterator().next().recipientId();
|
||||||
|
Server server = mock(Server.class);
|
||||||
|
Player player = mock(Player.class);
|
||||||
|
when(server.getPlayer(issuer)).thenReturn(player);
|
||||||
|
when(player.isOnline()).thenReturn(true);
|
||||||
|
when(player.getUniqueId()).thenReturn(issuer);
|
||||||
|
BukkitIssuerNotifier notifier = new BukkitIssuerNotifier(
|
||||||
|
service, server, Logger.getAnonymousLogger()
|
||||||
|
);
|
||||||
|
|
||||||
|
notifier.notifyIfOnline(issuer);
|
||||||
|
|
||||||
|
verify(player).sendMessage(contains("can be claimed at a quest board"));
|
||||||
|
assertTrue(service.state().notifications().isEmpty());
|
||||||
|
assertTrue(repository.state.notifications().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void offlineNotificationRemainsDurableUntilNextLogin() throws Exception {
|
||||||
|
Repository repository = new Repository();
|
||||||
|
QuestService service = completedService(repository);
|
||||||
|
IssuerNotification notification = service.state().notifications().values().iterator().next();
|
||||||
|
Server server = mock(Server.class);
|
||||||
|
when(server.getPlayer(notification.recipientId())).thenReturn(null);
|
||||||
|
BukkitIssuerNotifier notifier = new BukkitIssuerNotifier(
|
||||||
|
service, server, Logger.getAnonymousLogger()
|
||||||
|
);
|
||||||
|
|
||||||
|
notifier.notifyIfOnline(notification.recipientId());
|
||||||
|
assertEquals(1, service.state().notifications().size());
|
||||||
|
|
||||||
|
Player player = mock(Player.class);
|
||||||
|
when(player.getUniqueId()).thenReturn(notification.recipientId());
|
||||||
|
notifier.deliver(player);
|
||||||
|
|
||||||
|
verify(player).sendMessage(notification.message());
|
||||||
|
assertTrue(service.state().notifications().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static QuestService completedService(Repository repository) throws Exception {
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
Quest quest = service.create(
|
||||||
|
UUID.randomUUID(), "Issuer", "STONE", 1,
|
||||||
|
List.of(new EscrowItem("DIAMOND", 1, null)), Instant.EPOCH
|
||||||
|
);
|
||||||
|
service.complete(
|
||||||
|
quest.id(), new EscrowItem("STONE", 1, null), Instant.EPOCH.plusSeconds(1)
|
||||||
|
);
|
||||||
|
return service;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Repository implements QuestRepository {
|
||||||
|
private QuestState state = QuestState.empty();
|
||||||
|
@Override public QuestState load() { return state; }
|
||||||
|
@Override public void save(QuestState candidate) { state = candidate; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,7 +20,7 @@ final class QuestBoardDialogUiTest {
|
|||||||
void dialogSubmissionUsesEquivalentCreationFlow() {
|
void dialogSubmissionUsesEquivalentCreationFlow() {
|
||||||
RecordingCreator creator = new RecordingCreator(false);
|
RecordingCreator creator = new RecordingCreator(false);
|
||||||
QuestBoardDialogUi ui = new QuestBoardDialogUi(
|
QuestBoardDialogUi ui = new QuestBoardDialogUi(
|
||||||
creator, Clock.fixed(NOW, ZoneOffset.UTC)
|
creator, now -> List.of(), Clock.fixed(NOW, ZoneOffset.UTC)
|
||||||
);
|
);
|
||||||
Player player = mock(Player.class);
|
Player player = mock(Player.class);
|
||||||
|
|
||||||
@@ -35,10 +35,73 @@ final class QuestBoardDialogUiTest {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void completionActionUsesEquivalentCompletionFlow() {
|
||||||
|
RecordingCreator creator = new RecordingCreator(false);
|
||||||
|
RecordingCompleter completer = new RecordingCompleter();
|
||||||
|
QuestBoardDialogUi ui = new QuestBoardDialogUi(
|
||||||
|
creator, now -> List.of(), completer, Clock.fixed(NOW, ZoneOffset.UTC)
|
||||||
|
);
|
||||||
|
Player player = mock(Player.class);
|
||||||
|
String id = UUID.randomUUID().toString();
|
||||||
|
|
||||||
|
ui.submitCompletion(player, id);
|
||||||
|
|
||||||
|
assertEquals(player, completer.player);
|
||||||
|
assertEquals(id, completer.questId);
|
||||||
|
assertEquals(NOW, completer.completedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void cancellationActionUsesEquivalentCancellationFlow() {
|
||||||
|
RecordingCreator creator = new RecordingCreator(false);
|
||||||
|
RecordingCanceller canceller = new RecordingCanceller();
|
||||||
|
QuestBoardDialogUi ui = new QuestBoardDialogUi(
|
||||||
|
creator, now -> List.of(), null, canceller, Clock.fixed(NOW, ZoneOffset.UTC)
|
||||||
|
);
|
||||||
|
Player player = mock(Player.class);
|
||||||
|
String id = UUID.randomUUID().toString();
|
||||||
|
|
||||||
|
ui.submitCancellation(player, id);
|
||||||
|
|
||||||
|
assertEquals(player, canceller.player);
|
||||||
|
assertEquals(id, canceller.questId);
|
||||||
|
assertEquals(NOW, canceller.cancelledAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void boardOnlyOffersCancellationActionsForPlayersOwnedActiveQuests() {
|
||||||
|
RecordingCreator creator = new RecordingCreator(false);
|
||||||
|
Quest owned = creator.quest(NOW);
|
||||||
|
Quest other = new Quest(
|
||||||
|
UUID.randomUUID(), UUID.randomUUID(), "Other", "DIRT", 1,
|
||||||
|
List.of(new EscrowItem("COAL", 1, null)), NOW, NOW.plusSeconds(604800)
|
||||||
|
);
|
||||||
|
QuestBoardDialogUi ui = new QuestBoardDialogUi(
|
||||||
|
creator, now -> List.of(owned, other), null, new RecordingCanceller(),
|
||||||
|
Clock.fixed(NOW, ZoneOffset.UTC)
|
||||||
|
);
|
||||||
|
Player issuer = mock(Player.class);
|
||||||
|
org.mockito.Mockito.when(issuer.getUniqueId()).thenReturn(owned.issuerId());
|
||||||
|
|
||||||
|
assertEquals(List.of(owned.id().toString()), ui.cancellableQuestIds(issuer));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void everyOpeningBuildsAListingFromTheCurrentActiveQuests() {
|
||||||
|
RecordingCreator creator = new RecordingCreator(false);
|
||||||
|
Quest active = creator.quest(NOW);
|
||||||
|
QuestBoardDialogUi ui = new QuestBoardDialogUi(
|
||||||
|
creator, now -> List.of(active), Clock.fixed(NOW, ZoneOffset.UTC)
|
||||||
|
);
|
||||||
|
|
||||||
|
assertEquals(QuestListingFormatter.format(active, NOW), ui.listingText());
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void persistenceFailureExplainsThatRewardWasRestored() {
|
void persistenceFailureExplainsThatRewardWasRestored() {
|
||||||
QuestBoardDialogUi ui = new QuestBoardDialogUi(
|
QuestBoardDialogUi ui = new QuestBoardDialogUi(
|
||||||
new RecordingCreator(true), Clock.fixed(NOW, ZoneOffset.UTC)
|
new RecordingCreator(true), now -> List.of(), Clock.fixed(NOW, ZoneOffset.UTC)
|
||||||
);
|
);
|
||||||
Player player = mock(Player.class);
|
Player player = mock(Player.class);
|
||||||
|
|
||||||
@@ -49,6 +112,34 @@ final class QuestBoardDialogUiTest {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static final class RecordingCanceller implements QuestCancellationGateway {
|
||||||
|
private Player player;
|
||||||
|
private String questId;
|
||||||
|
private Instant cancelledAt;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public QuestClaim cancel(Player cancellingPlayer, String id, Instant instant) {
|
||||||
|
player = cancellingPlayer;
|
||||||
|
questId = id;
|
||||||
|
cancelledAt = instant;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class RecordingCompleter implements QuestCompletionGateway {
|
||||||
|
private Player player;
|
||||||
|
private String questId;
|
||||||
|
private Instant completedAt;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public QuestCompletion complete(Player completingPlayer, String id, Instant instant) {
|
||||||
|
player = completingPlayer;
|
||||||
|
questId = id;
|
||||||
|
completedAt = instant;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static final class RecordingCreator implements QuestCreationGateway {
|
private static final class RecordingCreator implements QuestCreationGateway {
|
||||||
private final boolean fail;
|
private final boolean fail;
|
||||||
private String material;
|
private String material;
|
||||||
@@ -69,10 +160,14 @@ final class QuestBoardDialogUiTest {
|
|||||||
material = requestedMaterial;
|
material = requestedMaterial;
|
||||||
quantity = requestedAmount;
|
quantity = requestedAmount;
|
||||||
createdAt = instant;
|
createdAt = instant;
|
||||||
|
return quest(instant);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Quest quest(Instant instant) {
|
||||||
return new Quest(
|
return new Quest(
|
||||||
UUID.fromString("00000000-0000-0000-0000-000000000010"),
|
UUID.fromString("00000000-0000-0000-0000-000000000010"),
|
||||||
UUID.fromString("00000000-0000-0000-0000-000000000001"),
|
UUID.fromString("00000000-0000-0000-0000-000000000001"),
|
||||||
"Issuer", "STONE", requestedAmount,
|
"Issuer", "STONE", 64,
|
||||||
List.of(new EscrowItem("DIAMOND", 1, null)),
|
List.of(new EscrowItem("DIAMOND", 1, null)),
|
||||||
instant, instant.plusSeconds(604800)
|
instant, instant.plusSeconds(604800)
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.mockito.ArgumentMatchers.contains;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
final class QuestCancellationControllerTest {
|
||||||
|
@Test
|
||||||
|
void cancelsAsPlayerIdentityAndCreatesClaimWithoutInventorySettlement() throws Exception {
|
||||||
|
Repository repository = new Repository();
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
UUID issuer = UUID.randomUUID();
|
||||||
|
Quest quest = service.create(
|
||||||
|
issuer, "Issuer", "STONE", 1,
|
||||||
|
List.of(new EscrowItem("DIAMOND", 2, "exact-data")), Instant.EPOCH
|
||||||
|
);
|
||||||
|
Player player = mock(Player.class);
|
||||||
|
when(player.getUniqueId()).thenReturn(issuer);
|
||||||
|
|
||||||
|
QuestClaim claim = new QuestCancellationController(service).cancel(
|
||||||
|
player, quest.id().toString(), Instant.EPOCH.plusSeconds(1)
|
||||||
|
);
|
||||||
|
|
||||||
|
assertEquals(quest.reward(), claim.items());
|
||||||
|
assertEquals(List.of(claim), service.state().claims().get(issuer));
|
||||||
|
verify(player).sendMessage(contains("claim"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsMalformedQuestIdentifier() throws Exception {
|
||||||
|
QuestCancellationController controller = new QuestCancellationController(
|
||||||
|
new QuestService(new Repository())
|
||||||
|
);
|
||||||
|
|
||||||
|
IllegalArgumentException exception = assertThrows(
|
||||||
|
IllegalArgumentException.class,
|
||||||
|
() -> controller.cancel(mock(Player.class), "not-a-uuid", Instant.EPOCH)
|
||||||
|
);
|
||||||
|
|
||||||
|
assertEquals("Quest identifier must be a valid UUID.", exception.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Repository implements QuestRepository {
|
||||||
|
private QuestState state = QuestState.empty();
|
||||||
|
@Override public QuestState load() { return state; }
|
||||||
|
@Override public void save(QuestState candidate) throws IOException { state = candidate; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
final class QuestCancellationServiceTest {
|
||||||
|
@Test
|
||||||
|
void onlyIssuerCanCancelAndExactRewardBecomesClaim() throws Exception {
|
||||||
|
Repository repository = new Repository();
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
UUID issuer = UUID.randomUUID();
|
||||||
|
EscrowItem reward = new EscrowItem("DIAMOND", 3, "exact-item-data");
|
||||||
|
Quest quest = service.create(
|
||||||
|
issuer, "Issuer", "STONE", 64, List.of(reward), Instant.EPOCH
|
||||||
|
);
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> service.cancel(
|
||||||
|
quest.id(), UUID.randomUUID(), Instant.EPOCH.plusSeconds(1)
|
||||||
|
));
|
||||||
|
QuestClaim claim = service.cancel(
|
||||||
|
quest.id(), issuer, Instant.EPOCH.plusSeconds(1)
|
||||||
|
);
|
||||||
|
|
||||||
|
assertEquals(QuestStatus.CANCELLED, service.state().quests().get(quest.id()).status());
|
||||||
|
assertEquals(List.of(reward), claim.items());
|
||||||
|
assertEquals(List.of(claim), service.state().claims().get(issuer));
|
||||||
|
assertTrue(service.activeQuests(Instant.EPOCH.plusSeconds(1)).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void completedCancelledAndExpiredQuestsCannotBeCancelled() throws Exception {
|
||||||
|
Repository repository = new Repository();
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
UUID issuer = UUID.randomUUID();
|
||||||
|
Quest completed = quest(service, issuer);
|
||||||
|
service.complete(
|
||||||
|
completed.id(), new EscrowItem("STONE", 1, null), Instant.EPOCH.plusSeconds(1)
|
||||||
|
);
|
||||||
|
Quest cancelled = quest(service, issuer);
|
||||||
|
service.cancel(cancelled.id(), issuer, Instant.EPOCH.plusSeconds(1));
|
||||||
|
Quest expired = quest(service, issuer);
|
||||||
|
|
||||||
|
assertThrows(IllegalStateException.class, () -> service.cancel(
|
||||||
|
completed.id(), issuer, Instant.EPOCH.plusSeconds(2)
|
||||||
|
));
|
||||||
|
assertThrows(IllegalStateException.class, () -> service.cancel(
|
||||||
|
cancelled.id(), issuer, Instant.EPOCH.plusSeconds(2)
|
||||||
|
));
|
||||||
|
assertThrows(IllegalStateException.class, () -> service.cancel(
|
||||||
|
expired.id(), issuer, expired.expiresAt()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void persistenceFailureLeavesQuestActiveAndRewardEscrowed() throws Exception {
|
||||||
|
Repository repository = new Repository();
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
UUID issuer = UUID.randomUUID();
|
||||||
|
Quest quest = quest(service, issuer);
|
||||||
|
QuestState before = service.state();
|
||||||
|
repository.fail = true;
|
||||||
|
|
||||||
|
assertThrows(IOException.class, () -> service.cancel(
|
||||||
|
quest.id(), issuer, Instant.EPOCH.plusSeconds(1)
|
||||||
|
));
|
||||||
|
|
||||||
|
assertEquals(before, service.state());
|
||||||
|
assertEquals(before, repository.state);
|
||||||
|
assertEquals(QuestStatus.ACTIVE, service.state().quests().get(quest.id()).status());
|
||||||
|
assertTrue(service.state().claims().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void simultaneousCancellationAndCompletionSettleEscrowExactlyOnce() throws Exception {
|
||||||
|
Repository repository = new Repository();
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
UUID issuer = UUID.randomUUID();
|
||||||
|
Quest quest = quest(service, issuer);
|
||||||
|
CountDownLatch start = new CountDownLatch(1);
|
||||||
|
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
|
||||||
|
List<Future<Boolean>> attempts = new ArrayList<>();
|
||||||
|
attempts.add(executor.submit(() -> {
|
||||||
|
start.await();
|
||||||
|
try {
|
||||||
|
service.cancel(quest.id(), issuer, Instant.EPOCH.plusSeconds(1));
|
||||||
|
return true;
|
||||||
|
} catch (IllegalStateException exception) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
attempts.add(executor.submit(() -> {
|
||||||
|
start.await();
|
||||||
|
try {
|
||||||
|
service.complete(
|
||||||
|
quest.id(), new EscrowItem("STONE", 1, null),
|
||||||
|
Instant.EPOCH.plusSeconds(1)
|
||||||
|
);
|
||||||
|
return true;
|
||||||
|
} catch (IllegalStateException exception) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
start.countDown();
|
||||||
|
assertEquals(1, attempts.stream().filter(attempt -> {
|
||||||
|
try {
|
||||||
|
return attempt.get();
|
||||||
|
} catch (Exception exception) {
|
||||||
|
throw new AssertionError(exception);
|
||||||
|
}
|
||||||
|
}).count());
|
||||||
|
}
|
||||||
|
|
||||||
|
QuestStatus status = service.state().quests().get(quest.id()).status();
|
||||||
|
assertTrue(status == QuestStatus.CANCELLED || status == QuestStatus.COMPLETED);
|
||||||
|
assertEquals(1, service.state().claims().get(issuer).size());
|
||||||
|
QuestClaim settlement = service.state().claims().get(issuer).getFirst();
|
||||||
|
if (status == QuestStatus.CANCELLED) {
|
||||||
|
assertEquals(quest.reward(), settlement.items());
|
||||||
|
assertTrue(service.state().notifications().isEmpty());
|
||||||
|
} else {
|
||||||
|
assertEquals(List.of(new EscrowItem("STONE", 1, null)), settlement.items());
|
||||||
|
assertEquals(1, service.state().notifications().size());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Quest quest(QuestService service, UUID issuer) throws IOException {
|
||||||
|
return service.create(
|
||||||
|
issuer, "Issuer", "STONE", 1,
|
||||||
|
List.of(new EscrowItem("DIAMOND", 2, null)), Instant.EPOCH
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Repository implements QuestRepository {
|
||||||
|
private QuestState state = QuestState.empty();
|
||||||
|
private boolean fail;
|
||||||
|
|
||||||
|
@Override public QuestState load() { return state; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void save(QuestState candidate) throws IOException {
|
||||||
|
if (fail) {
|
||||||
|
throw new IOException("disk full");
|
||||||
|
}
|
||||||
|
state = candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
|||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.mockito.ArgumentMatchers.contains;
|
import static org.mockito.ArgumentMatchers.contains;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
import java.time.Clock;
|
import java.time.Clock;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
@@ -35,6 +37,41 @@ final class QuestCommandTest {
|
|||||||
verify(player).sendMessage(contains("exact held stack"));
|
verify(player).sendMessage(contains("exact held stack"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void bareCommandAndListAliasShowTheSameActiveQuestTerms() {
|
||||||
|
RecordingCreator creator = new RecordingCreator();
|
||||||
|
Quest quest = creator.quest(64);
|
||||||
|
QuestCommand executor = command(creator, now -> List.of(quest));
|
||||||
|
Player player = mock(Player.class);
|
||||||
|
String expected = QuestListingFormatter.format(quest, NOW);
|
||||||
|
|
||||||
|
assertTrue(executor.onCommand(
|
||||||
|
player, mock(Command.class), "quests", new String[] {}
|
||||||
|
));
|
||||||
|
assertTrue(executor.onCommand(
|
||||||
|
player, mock(Command.class), "quests", new String[] {"list"}
|
||||||
|
));
|
||||||
|
|
||||||
|
verify(player, times(2)).sendMessage(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listNeverDisplaysExpiredOrStaleQuestIdentifiers() {
|
||||||
|
RecordingCreator creator = new RecordingCreator();
|
||||||
|
Quest active = creator.quest(64);
|
||||||
|
Quest expired = new Quest(
|
||||||
|
UUID.randomUUID(), UUID.randomUUID(), "OldIssuer", "DIRT", 1,
|
||||||
|
List.of(new EscrowItem("COAL", 1, null)), NOW.minusSeconds(604800), NOW
|
||||||
|
);
|
||||||
|
QuestCommand executor = command(creator, instant -> List.of(active));
|
||||||
|
Player player = mock(Player.class);
|
||||||
|
|
||||||
|
executor.onCommand(player, mock(Command.class), "quests", new String[] {"list"});
|
||||||
|
|
||||||
|
verify(player).sendMessage(contains(active.id().toString()));
|
||||||
|
verify(player, org.mockito.Mockito.never()).sendMessage(contains(expired.id().toString()));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void invalidQuantityNeverReachesCreation() {
|
void invalidQuantityNeverReachesCreation() {
|
||||||
RecordingCreator creator = new RecordingCreator();
|
RecordingCreator creator = new RecordingCreator();
|
||||||
@@ -49,6 +86,67 @@ final class QuestCommandTest {
|
|||||||
verify(player).sendMessage("Quest quantity must be a positive whole number.");
|
verify(player).sendMessage("Quest quantity must be a positive whole number.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void completeCommandRoutesPlayerAndCurrentTimeToEquivalentGateway() {
|
||||||
|
RecordingCreator creator = new RecordingCreator();
|
||||||
|
RecordingCompleter completer = new RecordingCompleter();
|
||||||
|
QuestCommand executor = new QuestCommand(
|
||||||
|
creator, now -> List.of(), completer, Clock.fixed(NOW, ZoneOffset.UTC)
|
||||||
|
);
|
||||||
|
Player player = mock(Player.class);
|
||||||
|
String id = UUID.randomUUID().toString();
|
||||||
|
|
||||||
|
assertTrue(executor.onCommand(
|
||||||
|
player, mock(Command.class), "quests", new String[] {"complete", id}
|
||||||
|
));
|
||||||
|
|
||||||
|
assertEquals(player, completer.player);
|
||||||
|
assertEquals(id, completer.questId);
|
||||||
|
assertEquals(NOW, completer.completedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void cancelCommandRoutesPlayerAndCurrentTimeToEquivalentGateway() {
|
||||||
|
RecordingCreator creator = new RecordingCreator();
|
||||||
|
RecordingCanceller canceller = new RecordingCanceller();
|
||||||
|
QuestCommand executor = new QuestCommand(
|
||||||
|
creator, now -> List.of(), null, canceller, Clock.fixed(NOW, ZoneOffset.UTC)
|
||||||
|
);
|
||||||
|
Player player = mock(Player.class);
|
||||||
|
String id = UUID.randomUUID().toString();
|
||||||
|
|
||||||
|
assertTrue(executor.onCommand(
|
||||||
|
player, mock(Command.class), "quests", new String[] {"cancel", id}
|
||||||
|
));
|
||||||
|
|
||||||
|
assertEquals(player, canceller.player);
|
||||||
|
assertEquals(id, canceller.questId);
|
||||||
|
assertEquals(NOW, canceller.cancelledAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void questIdentifierAutocompleteOnlyUsesActiveAndOwnedQuests() {
|
||||||
|
RecordingCreator creator = new RecordingCreator();
|
||||||
|
UUID issuerId = UUID.fromString("00000000-0000-0000-0000-000000000001");
|
||||||
|
Quest active = creator.quest(64);
|
||||||
|
QuestCommand executor = command(creator, now -> List.of(active));
|
||||||
|
Player issuer = mock(Player.class);
|
||||||
|
when(issuer.getUniqueId()).thenReturn(issuerId);
|
||||||
|
Player otherPlayer = mock(Player.class);
|
||||||
|
when(otherPlayer.getUniqueId()).thenReturn(UUID.randomUUID());
|
||||||
|
Command command = mock(Command.class);
|
||||||
|
|
||||||
|
assertEquals(List.of(active.id().toString()), executor.onTabComplete(
|
||||||
|
issuer, command, "quests", new String[] {"complete", ""}
|
||||||
|
));
|
||||||
|
assertEquals(List.of(active.id().toString()), executor.onTabComplete(
|
||||||
|
issuer, command, "quests", new String[] {"cancel", ""}
|
||||||
|
));
|
||||||
|
assertTrue(executor.onTabComplete(
|
||||||
|
otherPlayer, command, "quests", new String[] {"cancel", ""}
|
||||||
|
).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void autocompleteIsPlayerOnlyAndContextual() {
|
void autocompleteIsPlayerOnlyAndContextual() {
|
||||||
RecordingCreator creator = new RecordingCreator();
|
RecordingCreator creator = new RecordingCreator();
|
||||||
@@ -58,6 +156,10 @@ final class QuestCommandTest {
|
|||||||
|
|
||||||
assertEquals(List.of("create"),
|
assertEquals(List.of("create"),
|
||||||
executor.onTabComplete(player, command, "quests", new String[] {"cr"}));
|
executor.onTabComplete(player, command, "quests", new String[] {"cr"}));
|
||||||
|
assertEquals(List.of("list"),
|
||||||
|
executor.onTabComplete(player, command, "quests", new String[] {"li"}));
|
||||||
|
assertEquals(List.of("cancel"),
|
||||||
|
executor.onTabComplete(player, command, "quests", new String[] {"ca"}));
|
||||||
assertEquals(List.of("STONE", "STONE_BRICKS"), executor.onTabComplete(
|
assertEquals(List.of("STONE", "STONE_BRICKS"), executor.onTabComplete(
|
||||||
player, command, "quests", new String[] {"create", "sto"}
|
player, command, "quests", new String[] {"create", "sto"}
|
||||||
));
|
));
|
||||||
@@ -71,7 +173,39 @@ final class QuestCommandTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static QuestCommand command(RecordingCreator creator) {
|
private static QuestCommand command(RecordingCreator creator) {
|
||||||
return new QuestCommand(creator, Clock.fixed(NOW, ZoneOffset.UTC));
|
return command(creator, now -> List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static QuestCommand command(RecordingCreator creator, QuestBrowser browser) {
|
||||||
|
return new QuestCommand(creator, browser, Clock.fixed(NOW, ZoneOffset.UTC));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class RecordingCanceller implements QuestCancellationGateway {
|
||||||
|
private Player player;
|
||||||
|
private String questId;
|
||||||
|
private Instant cancelledAt;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public QuestClaim cancel(Player cancellingPlayer, String id, Instant instant) {
|
||||||
|
player = cancellingPlayer;
|
||||||
|
questId = id;
|
||||||
|
cancelledAt = instant;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class RecordingCompleter implements QuestCompletionGateway {
|
||||||
|
private Player player;
|
||||||
|
private String questId;
|
||||||
|
private Instant completedAt;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public QuestCompletion complete(Player completingPlayer, String id, Instant instant) {
|
||||||
|
player = completingPlayer;
|
||||||
|
questId = id;
|
||||||
|
completedAt = instant;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final class RecordingCreator implements QuestCreationGateway {
|
private static final class RecordingCreator implements QuestCreationGateway {
|
||||||
@@ -91,12 +225,17 @@ final class QuestCommandTest {
|
|||||||
quantity = requestedAmount;
|
quantity = requestedAmount;
|
||||||
this.createdAt = createdAt;
|
this.createdAt = createdAt;
|
||||||
calls++;
|
calls++;
|
||||||
|
return quest(requestedAmount);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Quest quest(int requestedAmount) {
|
||||||
|
Instant instant = createdAt == null ? NOW : createdAt;
|
||||||
return new Quest(
|
return new Quest(
|
||||||
UUID.fromString("00000000-0000-0000-0000-000000000010"),
|
UUID.fromString("00000000-0000-0000-0000-000000000010"),
|
||||||
UUID.fromString("00000000-0000-0000-0000-000000000001"),
|
UUID.fromString("00000000-0000-0000-0000-000000000001"),
|
||||||
"Issuer", "STONE", requestedAmount,
|
"Issuer", "STONE", requestedAmount,
|
||||||
List.of(new EscrowItem("DIAMOND", 1, null)),
|
List.of(new EscrowItem("DIAMOND", 1, null)),
|
||||||
createdAt, createdAt.plusSeconds(604800)
|
instant, instant.plusSeconds(604800)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
final class QuestCompletionAtomicityTest {
|
||||||
|
@Test
|
||||||
|
void persistenceFailureChangesNoDurableOrInMemoryState() throws Exception {
|
||||||
|
FailingRepository repository = new FailingRepository();
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
Quest quest = service.create(
|
||||||
|
UUID.randomUUID(), "Issuer", "STONE", 2,
|
||||||
|
List.of(new EscrowItem("DIAMOND", 1, null)), Instant.EPOCH
|
||||||
|
);
|
||||||
|
QuestState before = service.state();
|
||||||
|
repository.fail = true;
|
||||||
|
|
||||||
|
assertThrows(IOException.class, () -> service.complete(
|
||||||
|
quest.id(), new EscrowItem("STONE", 2, null), Instant.EPOCH.plusSeconds(1)
|
||||||
|
));
|
||||||
|
|
||||||
|
assertEquals(before, service.state());
|
||||||
|
assertEquals(before, repository.state);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsWrongMaterialQuantityExpiredAndAlreadyCompleted() throws Exception {
|
||||||
|
FailingRepository repository = new FailingRepository();
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
Quest quest = service.create(
|
||||||
|
UUID.randomUUID(), "Issuer", "STONE", 2,
|
||||||
|
List.of(new EscrowItem("DIAMOND", 1, null)), Instant.EPOCH
|
||||||
|
);
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> service.complete(
|
||||||
|
quest.id(), new EscrowItem("DIRT", 2, null), Instant.EPOCH.plusSeconds(1)
|
||||||
|
));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> service.complete(
|
||||||
|
quest.id(), new EscrowItem("STONE", 1, null), Instant.EPOCH.plusSeconds(1)
|
||||||
|
));
|
||||||
|
assertThrows(IllegalStateException.class, () -> service.complete(
|
||||||
|
quest.id(), new EscrowItem("STONE", 2, null), quest.expiresAt()
|
||||||
|
));
|
||||||
|
service.complete(
|
||||||
|
quest.id(), new EscrowItem("STONE", 2, null), Instant.EPOCH.plusSeconds(1)
|
||||||
|
);
|
||||||
|
assertThrows(IllegalStateException.class, () -> service.complete(
|
||||||
|
quest.id(), new EscrowItem("STONE", 2, null), Instant.EPOCH.plusSeconds(2)
|
||||||
|
));
|
||||||
|
assertTrue(service.activeQuests(Instant.EPOCH.plusSeconds(2)).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void simultaneousAttemptsSettleExactlyOnce() throws Exception {
|
||||||
|
FailingRepository repository = new FailingRepository();
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
UUID issuer = UUID.randomUUID();
|
||||||
|
Quest quest = service.create(
|
||||||
|
issuer, "Issuer", "STONE", 1,
|
||||||
|
List.of(new EscrowItem("DIAMOND", 1, null)), Instant.EPOCH
|
||||||
|
);
|
||||||
|
CountDownLatch start = new CountDownLatch(1);
|
||||||
|
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
|
||||||
|
List<Future<Boolean>> attempts = new ArrayList<>();
|
||||||
|
for (int index = 0; index < 2; index++) {
|
||||||
|
attempts.add(executor.submit(() -> {
|
||||||
|
start.await();
|
||||||
|
try {
|
||||||
|
service.complete(
|
||||||
|
quest.id(), new EscrowItem("STONE", 1, null),
|
||||||
|
Instant.EPOCH.plusSeconds(1)
|
||||||
|
);
|
||||||
|
return true;
|
||||||
|
} catch (IllegalStateException exception) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
start.countDown();
|
||||||
|
assertEquals(1, attempts.stream().filter(attempt -> {
|
||||||
|
try {
|
||||||
|
return attempt.get();
|
||||||
|
} catch (Exception exception) {
|
||||||
|
throw new AssertionError(exception);
|
||||||
|
}
|
||||||
|
}).count());
|
||||||
|
}
|
||||||
|
assertEquals(1, service.state().claims().get(issuer).size());
|
||||||
|
assertEquals(1, service.state().notifications().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class FailingRepository implements QuestRepository {
|
||||||
|
private QuestState state = QuestState.empty();
|
||||||
|
private boolean fail;
|
||||||
|
|
||||||
|
@Override public QuestState load() { return state; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void save(QuestState candidate) throws IOException {
|
||||||
|
if (fail) {
|
||||||
|
throw new IOException("disk full");
|
||||||
|
}
|
||||||
|
state = candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
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.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
final class QuestCompletionControllerTest {
|
||||||
|
@Test
|
||||||
|
void removesExactDeliverySettlesRewardReportsOverflowAndNotifies() throws Exception {
|
||||||
|
Repository repository = new Repository();
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
UUID issuer = UUID.randomUUID();
|
||||||
|
Quest quest = quest(service, issuer);
|
||||||
|
Inventory inventory = new Inventory();
|
||||||
|
inventory.overflow = 2;
|
||||||
|
RecordingNotifier notifier = new RecordingNotifier();
|
||||||
|
QuestCompletionController controller = new QuestCompletionController(
|
||||||
|
service, inventory, notifier
|
||||||
|
);
|
||||||
|
Player player = mock(Player.class);
|
||||||
|
|
||||||
|
controller.complete(player, quest.id().toString(), Instant.EPOCH.plusSeconds(1));
|
||||||
|
|
||||||
|
assertEquals("STONE", inventory.material);
|
||||||
|
assertEquals(3, inventory.amount);
|
||||||
|
assertTrue(inventory.granted);
|
||||||
|
assertFalse(inventory.rolledBack);
|
||||||
|
assertEquals(issuer, notifier.issuer);
|
||||||
|
assertEquals(
|
||||||
|
List.of(new EscrowItem("STONE", 3, null)),
|
||||||
|
service.state().claims().get(issuer).getFirst().items()
|
||||||
|
);
|
||||||
|
verify(player).sendMessage(contains("exact escrowed reward"));
|
||||||
|
verify(player).sendMessage(contains("dropped safely at your feet"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void inventoryValidationFailureConsumesAndReleasesNothing() throws Exception {
|
||||||
|
Repository repository = new Repository();
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
Quest quest = quest(service, UUID.randomUUID());
|
||||||
|
Inventory inventory = new Inventory();
|
||||||
|
inventory.insufficient = true;
|
||||||
|
Player player = mock(Player.class);
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new QuestCompletionController(
|
||||||
|
service, inventory, ignored -> { }
|
||||||
|
).complete(player, quest.id().toString(), Instant.EPOCH.plusSeconds(1)));
|
||||||
|
|
||||||
|
assertFalse(inventory.granted);
|
||||||
|
assertEquals(QuestStatus.ACTIVE, service.state().quests().get(quest.id()).status());
|
||||||
|
assertTrue(service.state().claims().isEmpty());
|
||||||
|
verify(player, never()).sendMessage(contains("completed"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void persistenceFailureRollsBackDeliveryAndDoesNotGrantReward() throws Exception {
|
||||||
|
Repository repository = new Repository();
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
Quest quest = quest(service, UUID.randomUUID());
|
||||||
|
Inventory inventory = new Inventory();
|
||||||
|
repository.fail = true;
|
||||||
|
|
||||||
|
assertThrows(IOException.class, () -> new QuestCompletionController(
|
||||||
|
service, inventory, ignored -> { }
|
||||||
|
).complete(mock(Player.class), quest.id().toString(), Instant.EPOCH.plusSeconds(1)));
|
||||||
|
|
||||||
|
assertTrue(inventory.rolledBack);
|
||||||
|
assertFalse(inventory.granted);
|
||||||
|
assertEquals(QuestStatus.ACTIVE, service.state().quests().get(quest.id()).status());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Quest quest(QuestService service, UUID issuer) throws IOException {
|
||||||
|
return service.create(
|
||||||
|
issuer, "Issuer", "STONE", 3,
|
||||||
|
List.of(new EscrowItem("DIAMOND", 2, null)), Instant.EPOCH
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Inventory implements QuestCompletionInventory {
|
||||||
|
private String material;
|
||||||
|
private int amount;
|
||||||
|
private boolean insufficient;
|
||||||
|
private boolean rolledBack;
|
||||||
|
private boolean granted;
|
||||||
|
private int overflow;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public RemovedDelivery remove(Player player, String requestedMaterial, int requestedAmount) {
|
||||||
|
material = requestedMaterial;
|
||||||
|
amount = requestedAmount;
|
||||||
|
if (insufficient) {
|
||||||
|
throw new IllegalArgumentException("not enough blocks");
|
||||||
|
}
|
||||||
|
return new RemovedDelivery() {
|
||||||
|
@Override
|
||||||
|
public List<EscrowItem> items() {
|
||||||
|
return List.of(new EscrowItem(requestedMaterial, requestedAmount, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public void rollback() { rolledBack = true; }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PreparedReward prepare(List<EscrowItem> reward) {
|
||||||
|
return player -> {
|
||||||
|
granted = true;
|
||||||
|
return overflow;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class RecordingNotifier implements IssuerNotifier {
|
||||||
|
private UUID issuer;
|
||||||
|
@Override public void notifyIfOnline(UUID issuerId) { issuer = issuerId; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Repository implements QuestRepository {
|
||||||
|
private QuestState state = QuestState.empty();
|
||||||
|
private boolean fail;
|
||||||
|
@Override public QuestState load() { return state; }
|
||||||
|
@Override public void save(QuestState candidate) throws IOException {
|
||||||
|
if (fail) {
|
||||||
|
throw new IOException("disk full");
|
||||||
|
}
|
||||||
|
state = candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
final class QuestCompletionServiceTest {
|
||||||
|
@Test
|
||||||
|
void completesOnceAndHoldsDeliveredBlocksForIssuer() throws Exception {
|
||||||
|
MemoryQuestRepository repository = new MemoryQuestRepository();
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
UUID issuer = UUID.randomUUID();
|
||||||
|
Quest quest = service.create(
|
||||||
|
issuer, "Issuer", "STONE", 64,
|
||||||
|
List.of(new EscrowItem("DIAMOND", 3, null)), Instant.EPOCH
|
||||||
|
);
|
||||||
|
|
||||||
|
QuestCompletion completion = service.complete(
|
||||||
|
quest.id(), new EscrowItem("STONE", 64, null), Instant.EPOCH.plusSeconds(1)
|
||||||
|
);
|
||||||
|
|
||||||
|
assertEquals(QuestStatus.COMPLETED, service.state().quests().get(quest.id()).status());
|
||||||
|
assertEquals(quest.reward(), completion.reward());
|
||||||
|
assertTrue(service.state().claims().get(issuer).stream()
|
||||||
|
.anyMatch(claim -> claim.items().equals(List.of(new EscrowItem("STONE", 64, null)))));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class MemoryQuestRepository implements QuestRepository {
|
||||||
|
private QuestState state = QuestState.empty();
|
||||||
|
@Override public QuestState load() { return state; }
|
||||||
|
@Override public void save(QuestState state) { this.state = state; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package games.dmg.spigotquestboard;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
final class QuestListingFormatterTest {
|
||||||
|
private static final Instant NOW = Instant.parse("2026-09-05T03:00:00Z");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void describesEveryEssentialTermAndEachExactRewardStack() {
|
||||||
|
Quest quest = quest(
|
||||||
|
NOW.plusSeconds(90061),
|
||||||
|
List.of(
|
||||||
|
new EscrowItem("DIAMOND", 3, null),
|
||||||
|
new EscrowItem("DIAMOND_SWORD", 1, "opaque-exact-data")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
String listing = QuestListingFormatter.format(quest, NOW);
|
||||||
|
|
||||||
|
assertTrue(listing.contains(quest.id().toString()));
|
||||||
|
assertTrue(listing.contains("64 × STONE"));
|
||||||
|
assertTrue(listing.contains("3 × DIAMOND"));
|
||||||
|
assertTrue(listing.contains("1 × DIAMOND_SWORD (with exact item data)"));
|
||||||
|
assertTrue(listing.contains("Issuer: Issuer"));
|
||||||
|
assertTrue(listing.contains("Time remaining: 1d 1h 1m 1s"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void roundsAnActiveSubsecondBoundaryUpToOneSecond() {
|
||||||
|
Quest quest = quest(NOW.plusNanos(1), List.of(new EscrowItem("DIAMOND", 1, null)));
|
||||||
|
|
||||||
|
String listing = QuestListingFormatter.format(quest, NOW);
|
||||||
|
|
||||||
|
assertTrue(listing.contains("Time remaining: 1s"));
|
||||||
|
assertFalse(listing.contains("0s"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void formatsAnEmptyListingClearly() {
|
||||||
|
assertEquals("No active quests.", QuestListingFormatter.formatAll(List.of(), NOW));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Quest quest(Instant expiresAt, List<EscrowItem> rewards) {
|
||||||
|
return new Quest(
|
||||||
|
UUID.fromString("00000000-0000-0000-0000-000000000010"),
|
||||||
|
UUID.fromString("00000000-0000-0000-0000-000000000001"),
|
||||||
|
"Issuer", "STONE", 64, rewards, NOW.minusSeconds(60), expiresAt
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -66,6 +66,44 @@ final class QuestServiceTest {
|
|||||||
assertEquals(0, repository.saveCount);
|
assertEquals(0, repository.saveCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listsOnlyQuestsThatHaveNotReachedTheirExpiration() throws Exception {
|
||||||
|
MemoryQuestRepository repository = new MemoryQuestRepository();
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
Instant createdAt = Instant.parse("2026-09-05T00:00:00Z");
|
||||||
|
Quest quest = service.create(
|
||||||
|
UUID.randomUUID(), "Issuer", "STONE", 1,
|
||||||
|
List.of(new EscrowItem("DIAMOND", 1, null)), createdAt
|
||||||
|
);
|
||||||
|
|
||||||
|
assertEquals(List.of(quest), service.activeQuests(quest.expiresAt().minusNanos(1)));
|
||||||
|
assertTrue(service.activeQuests(quest.expiresAt()).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void activeListingExcludesNonActiveLifecycleStatuses() throws Exception {
|
||||||
|
Instant now = Instant.parse("2026-09-06T00:00:00Z");
|
||||||
|
Quest active = questWithStatus(QuestStatus.ACTIVE);
|
||||||
|
Quest completed = questWithStatus(QuestStatus.COMPLETED);
|
||||||
|
Quest cancelled = questWithStatus(QuestStatus.CANCELLED);
|
||||||
|
Quest expired = questWithStatus(QuestStatus.EXPIRED);
|
||||||
|
MemoryQuestRepository repository = new MemoryQuestRepository();
|
||||||
|
repository.state = new QuestState(java.util.stream.Stream.of(
|
||||||
|
active, completed, cancelled, expired
|
||||||
|
).collect(java.util.stream.Collectors.toMap(
|
||||||
|
Quest::id, quest -> quest, (left, right) -> left, java.util.LinkedHashMap::new
|
||||||
|
)));
|
||||||
|
|
||||||
|
QuestService service = new QuestService(repository);
|
||||||
|
|
||||||
|
assertEquals(List.of(active), service.activeQuests(now));
|
||||||
|
assertEquals(List.of(active.id().toString()), service.completableQuestIds(now));
|
||||||
|
assertEquals(
|
||||||
|
List.of(active.id().toString()), service.cancellableQuestIds(active.issuerId(), now)
|
||||||
|
);
|
||||||
|
assertTrue(service.cancellableQuestIds(UUID.randomUUID(), now).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void persistenceFailureDoesNotPublishQuest() throws Exception {
|
void persistenceFailureDoesNotPublishQuest() throws Exception {
|
||||||
QuestRepository repository = new QuestRepository() {
|
QuestRepository repository = new QuestRepository() {
|
||||||
@@ -83,6 +121,15 @@ final class QuestServiceTest {
|
|||||||
assertTrue(service.state().quests().isEmpty());
|
assertTrue(service.state().quests().isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static Quest questWithStatus(QuestStatus status) {
|
||||||
|
Instant createdAt = Instant.parse("2026-09-05T00:00:00Z");
|
||||||
|
return new Quest(
|
||||||
|
UUID.randomUUID(), UUID.randomUUID(), "Issuer", "STONE", 1,
|
||||||
|
List.of(new EscrowItem("DIAMOND", 1, null)), createdAt,
|
||||||
|
createdAt.plus(7, ChronoUnit.DAYS), status
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private static final class MemoryQuestRepository implements QuestRepository {
|
private static final class MemoryQuestRepository implements QuestRepository {
|
||||||
private QuestState state = QuestState.empty();
|
private QuestState state = QuestState.empty();
|
||||||
private int saveCount;
|
private int saveCount;
|
||||||
|
|||||||
@@ -53,6 +53,80 @@ final class YamlQuestRepositoryTest {
|
|||||||
assertTrue(yaml.contains(itemData));
|
assertTrue(yaml.contains(itemData));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void missingLifecycleStatusDefaultsToActiveForExistingYaml() throws Exception {
|
||||||
|
Path path = temporaryDirectory.resolve("quests.yml");
|
||||||
|
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: 64
|
||||||
|
created-at: '2026-09-05T03:00:00Z'
|
||||||
|
expires-at: '2026-09-12T03:00:00Z'
|
||||||
|
reward:
|
||||||
|
- material: DIAMOND
|
||||||
|
amount: 2
|
||||||
|
""");
|
||||||
|
|
||||||
|
Quest quest = new YamlQuestRepository(path).load().quests().values().iterator().next();
|
||||||
|
|
||||||
|
assertEquals(QuestStatus.ACTIVE, quest.status());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void roundTripsNonActiveLifecycleStatus() throws Exception {
|
||||||
|
Path path = temporaryDirectory.resolve("quests.yml");
|
||||||
|
YamlQuestRepository repository = new YamlQuestRepository(path);
|
||||||
|
UUID id = UUID.fromString("00000000-0000-0000-0000-000000000010");
|
||||||
|
Quest quest = new Quest(
|
||||||
|
id, UUID.randomUUID(), "Issuer", "STONE", 1,
|
||||||
|
List.of(new EscrowItem("DIAMOND", 1, null)),
|
||||||
|
Instant.parse("2026-09-05T03:00:00Z"),
|
||||||
|
Instant.parse("2026-09-12T03:00:00Z"), QuestStatus.COMPLETED
|
||||||
|
);
|
||||||
|
|
||||||
|
repository.save(new QuestState(Map.of(id, quest)));
|
||||||
|
|
||||||
|
assertEquals(QuestStatus.COMPLETED, repository.load().quests().get(id).status());
|
||||||
|
assertTrue(Files.readString(path).contains("status: COMPLETED"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void roundTripsClaimsAndPendingNotificationsWhileOldFilesDefaultThemEmpty() throws Exception {
|
||||||
|
Path path = temporaryDirectory.resolve("quests.yml");
|
||||||
|
YamlQuestRepository repository = new YamlQuestRepository(path);
|
||||||
|
UUID issuer = UUID.randomUUID();
|
||||||
|
UUID questId = UUID.randomUUID();
|
||||||
|
Quest quest = new Quest(
|
||||||
|
questId, issuer, "Issuer", "STONE", 2,
|
||||||
|
List.of(new EscrowItem("DIAMOND", 1, null)),
|
||||||
|
Instant.parse("2026-09-05T03:00:00Z"),
|
||||||
|
Instant.parse("2026-09-12T03:00:00Z"), QuestStatus.COMPLETED
|
||||||
|
);
|
||||||
|
QuestClaim claim = new QuestClaim(
|
||||||
|
UUID.randomUUID(), questId, issuer,
|
||||||
|
List.of(new EscrowItem("STONE", 2, null)),
|
||||||
|
Instant.parse("2026-09-05T03:01:00Z")
|
||||||
|
);
|
||||||
|
IssuerNotification notification = new IssuerNotification(
|
||||||
|
UUID.randomUUID(), questId, issuer, "Your delivery can be claimed.",
|
||||||
|
Instant.parse("2026-09-05T03:01:00Z")
|
||||||
|
);
|
||||||
|
QuestState expected = new QuestState(
|
||||||
|
Map.of(questId, quest), Map.of(issuer, List.of(claim)),
|
||||||
|
Map.of(notification.id(), notification)
|
||||||
|
);
|
||||||
|
|
||||||
|
repository.save(expected);
|
||||||
|
|
||||||
|
assertEquals(expected, repository.load());
|
||||||
|
String yaml = Files.readString(path);
|
||||||
|
assertTrue(yaml.contains("claims:"));
|
||||||
|
assertTrue(yaml.contains("notifications:"));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void malformedStateIsRejectedRatherThanPartiallyLoaded() throws Exception {
|
void malformedStateIsRejectedRatherThanPartiallyLoaded() throws Exception {
|
||||||
Path path = temporaryDirectory.resolve("quests.yml");
|
Path path = temporaryDirectory.resolve("quests.yml");
|
||||||
|
|||||||
Reference in New Issue
Block a user