From e78b591daffb4f2f5a54a2a44d5424e5b8a63a45 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:05:53 +0200 Subject: [PATCH] Finish CHOAM exchange menus, SQL trades and website demo market --- DuneEss/EXCHANGE.md | 32 ++ DuneEss/build.gradle.kts | 9 +- .../java/com/example/duneess/DuneEconomy.java | 6 +- .../java/com/example/duneess/DuneEss.java | 14 +- .../com/example/duneess/ExchangeMenu.java | 318 +++++++++++++++--- .../com/example/duneess/ExchangeStore.java | 109 ++++++ DuneEss/src/main/resources/plugin.yml | 2 +- .../com/example/duneess/ExchangeMenuTest.java | 62 ++++ .../example/duneess/ExchangeStoreTest.java | 101 ++++++ website/EXCHANGE-HANDOFF.md | 9 + website/tests/exchange.test.mjs | 44 +++ website/web/exchange-data.js | 47 +++ website/web/exchange-market.css | 27 ++ website/web/exchange-market.js | 67 +++- website/web/exchange.html | 2 +- 15 files changed, 800 insertions(+), 49 deletions(-) create mode 100644 DuneEss/EXCHANGE.md create mode 100644 DuneEss/src/main/java/com/example/duneess/ExchangeStore.java create mode 100644 DuneEss/src/test/java/com/example/duneess/ExchangeMenuTest.java create mode 100644 DuneEss/src/test/java/com/example/duneess/ExchangeStoreTest.java create mode 100644 website/tests/exchange.test.mjs create mode 100644 website/web/exchange-data.js diff --git a/DuneEss/EXCHANGE.md b/DuneEss/EXCHANGE.md new file mode 100644 index 00000000..ff5d30a5 --- /dev/null +++ b/DuneEss/EXCHANGE.md @@ -0,0 +1,32 @@ +# CHOAM exchange — DuneEss 1.0.2 + +Install `DuneEss-1.0.2.jar` with Vault and the existing DuneCore/DuneTerrain/DuneNPC suite on Paper 1.21.4 / Java 21. Replace the previous DuneEss JAR while the server is stopped. Existing wallet and listing tables are retained; startup adds nullable item-payload and display-name columns to the listing table. + +## Player controls + +- `/exchange` (also `/choam` or `/market`): faction-themed standard inventory menu. Actual DuneCore faction selection controls its appearance, including Ordos and unaffiliated Guild styling. Uses vanilla inventory slots; no Java-only client UI is required. +- `/exchange sell `: reserve 1–64 held items, priced per item, maximum 1,000,000 Solaris with two decimal places. You cannot offer more than the held stack. Item names, enchantments, Dune tags and other serialized item data are preserved. Operator admin rods cannot be sold. +- `/exchange buy `: review a listing, then confirm purchase of **one** item. The inventory GUI uses the same confirmation. Self-purchases are refused. +- `/exchange mine`: view your offers; select one to confirm cancellation and reclaim all unsold items. Only the seller can cancel. Your offers span all planets regardless of the browsing filter. +- `/exchange cancel `: open the reclaim confirmation directly. +- `/exchange admin`: permission `dune.admin`, with all-planet listing inspection and a real connection check. Normal ownership rules still apply. + +Category filters, all-items browsing, planet filters and pagination work together. The GUI identifies its own inventories through holders, cancels item transfers and drags, and prevents queued duplicate confirmations after a screen changes. + +## Shared database + +Enable PostgreSQL in `plugins/DuneCore/config.yml`, using the same database on every backend. Leave `database.use-core-database: true` in DuneEss. DuneEss first initializes the existing shared `dune_economy_balances` ledger, then initializes the exchange. Restart after configuration changes. The exchange refuses to trade against fallback local wallets or an unavailable shared economy. Menu/guide access still works when unconnected, and no demo items are sold in-game. + +Payments, seller credit and stock changes share one SQL transaction with a locked listing row. Buying the final item deletes the row instead of attempting an invalid zero quantity. Insufficient funds, a missing seller wallet or another transaction failure rolls back the database changes. Legacy material-only listings remain readable. Unsold item payloads are stored in PostgreSQL. + +**Verification limits:** automated SQL tests use H2 in PostgreSQL compatibility mode, and GUI tests use mocked Paper events. A live PostgreSQL + Paper/Velocity/Geyser staging run has not been performed. Queries are bounded and have five-second query/connect/socket timeouts but currently run on the server thread. Bukkit inventory/player-file writes and SQL commits are separate operations: abrupt process loss between them is not an exactly-once transfer guarantee. Keep normal backups and test staging before opening a public multi-backend economy. This change does not alter the wider Core profile/transfer synchronization system. + +## Website + +The website uses 40 clearly labelled fictional offers while the game-market gateway is unavailable. Demo offers never display purchase commands. When the configured gateway returns a valid live response, it switches to read-only live listings automatically on page load or Refresh; a valid empty live response remains an empty live market. + +The current gateway expects an HTTPS read-only bridge in `EXCHANGE_LISTINGS_URL`, authenticated server-to-server with `EXCHANGE_READ_TOKEN`. These are runtime secrets, never browser code. No bridge or production database is provisioned by this change. The response is `{ "listings": [{ "id": 1, "material": "IRON_INGOT", "category": "ores", "origin": "giedi_prime", "seller": "Trader", "quantity": 16, "price": 90 }] }`. Category and planet IDs must match the website's documented filter IDs. The bridge reads `dune_exchange_listings`; the website never executes a purchase or writes to SQL. + +## Checks + +Run `gradle build` in DuneEss and `npm run build` / `npm test` in website. SQL coverage includes the final item, partial purchases, insufficient funds, rollback after debit, concurrent buyers, ownership, filters/pagination and validation. GUI coverage includes holder isolation, bottom-inventory transfers, drags, stale duplicate confirmation and admin permission enforcement. diff --git a/DuneEss/build.gradle.kts b/DuneEss/build.gradle.kts index fe32f7f2..c129cba2 100644 --- a/DuneEss/build.gradle.kts +++ b/DuneEss/build.gradle.kts @@ -1,6 +1,6 @@ plugins { java } group = "com.example" -version = "1.0.1" +version = "1.0.2" repositories { mavenCentral() maven("https://repo.papermc.io/repository/maven-public/") @@ -12,6 +12,12 @@ dependencies { exclude(group = "org.bukkit", module = "bukkit") } implementation("org.postgresql:postgresql:42.7.4") + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") + testImplementation("com.h2database:h2:2.3.232") + testImplementation("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT") + testImplementation("org.mockito:mockito-core:5.15.2") + testRuntimeOnly("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") } + testRuntimeOnly("org.junit.platform:junit-platform-launcher") } tasks.jar { archiveBaseName.set("DuneEss") @@ -20,3 +26,4 @@ tasks.jar { } java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } tasks.withType { options.encoding = "UTF-8" } +tasks.test { useJUnitPlatform() } diff --git a/DuneEss/src/main/java/com/example/duneess/DuneEconomy.java b/DuneEss/src/main/java/com/example/duneess/DuneEconomy.java index fdac7cf4..aa53852a 100644 --- a/DuneEss/src/main/java/com/example/duneess/DuneEconomy.java +++ b/DuneEss/src/main/java/com/example/duneess/DuneEconomy.java @@ -57,6 +57,8 @@ final class DuneEconomy implements Economy { databaseEnabled = !jdbcUrl.isBlank(); } + boolean sharedDatabaseReady() { return databaseEnabled; } + private Connection connect() throws SQLException { return DriverManager.getConnection(jdbcUrl, dbUser, dbPassword); } @@ -196,8 +198,8 @@ final class DuneEconomy implements Economy { @Override public boolean isEnabled() { return plugin.isEnabled(); } @Override public String getName() { return "DuneEss"; } @Override public boolean hasBankSupport() { return false; } - @Override public int fractionalDigits() { return 0; } - @Override public String format(double amount) { return String.format(java.util.Locale.US, "%,.0f %s", amount, Math.abs(amount) == 1 ? singular : plural); } + @Override public int fractionalDigits() { return 2; } + @Override public String format(double amount) { return String.format(java.util.Locale.US, "%,.2f %s", amount, Math.abs(amount) == 1 ? singular : plural); } @Override public String currencyNamePlural() { return plural; } @Override public String currencyNameSingular() { return singular; } @Override public boolean hasAccount(String name) { return hasAccount(Bukkit.getOfflinePlayer(name)); } diff --git a/DuneEss/src/main/java/com/example/duneess/DuneEss.java b/DuneEss/src/main/java/com/example/duneess/DuneEss.java index d97951c9..a2d5335c 100644 --- a/DuneEss/src/main/java/com/example/duneess/DuneEss.java +++ b/DuneEss/src/main/java/com/example/duneess/DuneEss.java @@ -136,9 +136,17 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom localPlanet = useCore ? core.getString("network.local-planet", getConfig().getString("network.local-planet", "arrakis")) : getConfig().getString("network.local-planet", "arrakis"); } - Connection connectEconomyDatabase() throws Exception { - if (jdbcUrl.isBlank()) throw new IllegalStateException("No shared economy database configured"); - return DriverManager.getConnection(jdbcUrl, dbUser, dbPassword); + String localPlanet() { return localPlanet; } + + Connection connectEconomyDatabase() throws java.sql.SQLException { + if (jdbcUrl.isBlank() || !economy.sharedDatabaseReady()) + throw new java.sql.SQLException("No shared economy database configured"); + Properties properties = new Properties(); + properties.setProperty("user", dbUser); + properties.setProperty("password", dbPassword); + properties.setProperty("connectTimeout", "5"); + properties.setProperty("socketTimeout", "5"); + return DriverManager.getConnection(jdbcUrl, properties); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { diff --git a/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java b/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java index 8277773f..dd6c3022 100644 --- a/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java +++ b/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java @@ -5,48 +5,286 @@ import org.bukkit.command.*; import org.bukkit.entity.Player; import org.bukkit.event.*; import org.bukkit.event.inventory.*; +import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.*; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.plugin.java.JavaPlugin; -import java.sql.*; -import java.util.*; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.plugin.Plugin; import java.math.BigDecimal; +import java.sql.SQLException; +import java.util.*; -/** Vanilla inventory menus: compatible with Java and Geyser/Bedrock. */ -public final class ExchangeMenu implements Listener, CommandExecutor { - private final DuneEss plugin; - private final Map views=new HashMap<>(); - private final Map pages=new HashMap<>(); - private final Map filters=new HashMap<>(); - private static final List CATS=List.of("ores","spice","building","equipment","farming","misc"); - private static final List ICONS=List.of(Material.IRON_PICKAXE,Material.ORANGE_DYE,Material.BRICKS,Material.IRON_SWORD,Material.WHEAT,Material.CHEST); - ExchangeMenu(DuneEss p){plugin=p;} - void register(){Objects.requireNonNull(plugin.getCommand("exchange")).setExecutor(this);Bukkit.getPluginManager().registerEvents(this,plugin);try(Connection c=plugin.connectEconomyDatabase();Statement s=c.createStatement()){s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_exchange_listings(id BIGSERIAL PRIMARY KEY,seller UUID NOT NULL,seller_name VARCHAR(32) NOT NULL,origin VARCHAR(48) NOT NULL,category VARCHAR(24) NOT NULL,material VARCHAR(80) NOT NULL,quantity INT NOT NULL CHECK(quantity>0),price NUMERIC(20,2) NOT NULL CHECK(price>0))");}catch(Exception e){plugin.getLogger().warning("Exchange database unavailable: "+e.getMessage());}} - private String faction(Player p){String world=p.getWorld().getName().toLowerCase(Locale.ROOT);if(world.contains("giedi"))return "Harkonnen";if(world.contains("caladan"))return "Atreides";if(world.contains("kaitain"))return "Corrino";if(world.contains("arrakis"))return "Fremen";return "Guild";} - private ChatColor tint(Player p){return switch(faction(p)){case "Harkonnen"->ChatColor.RED;case "Atreides"->ChatColor.AQUA;case "Corrino"->ChatColor.GOLD;case "Guild"->ChatColor.LIGHT_PURPLE;default->ChatColor.YELLOW;};} - private ItemStack item(Material m,String name,String... lore){ItemStack i=new ItemStack(m);ItemMeta meta=i.getItemMeta();meta.setDisplayName(name);meta.setLore(Arrays.asList(lore));i.setItemMeta(meta);return i;} - private Inventory menu(Player p,String id,String title){views.put(p.getUniqueId(),id);Inventory inv=Bukkit.createInventory(null,54,tint(p)+title);ItemStack border=item(switch(faction(p)){case "Harkonnen"->Material.RED_STAINED_GLASS_PANE;case "Atreides"->Material.CYAN_STAINED_GLASS_PANE;case "Corrino"->Material.YELLOW_STAINED_GLASS_PANE;case "Guild"->Material.PURPLE_STAINED_GLASS_PANE;default->Material.ORANGE_STAINED_GLASS_PANE;},ChatColor.DARK_GRAY+" ");for(int s=0;s<54;s++)if(s<9||s>=45||s%9==0||s%9==8)inv.setItem(s,border);inv.setItem(49,item(Material.BARRIER,ChatColor.RED+"Back / Close"));return inv;} - private void show(Player p,Inventory i){p.openInventory(i);} - private void home(Player p){Inventory i=menu(p,"home","CHOAM | "+faction(p));for(int n=0;n<6;n++)i.setItem(10+n,item(ICONS.get(n),ChatColor.GOLD+CATS.get(n).toUpperCase(),ChatColor.GRAY+"Browse interplanetary offers"));i.setItem(29,item(Material.EMERALD,ChatColor.GREEN+"Buy Items"));i.setItem(31,item(Material.CHEST,ChatColor.YELLOW+"Sell Held Item",ChatColor.GRAY+"Use /exchange sell "));i.setItem(33,item(Material.BOOK,ChatColor.AQUA+"My Listings"));i.setItem(40,item(Material.COMPASS,ChatColor.LIGHT_PURPLE+"Planet Filter",ChatColor.GRAY+filters.getOrDefault(p.getUniqueId(),"all")));if(p.hasPermission("dune.admin"))i.setItem(42,item(Material.COMMAND_BLOCK,ChatColor.RED+"Admin Exchange"));show(p,i);} - private void categories(Player p){Inventory i=menu(p,"categories","Exchange Categories");for(int n=0;n<6;n++)i.setItem(11+n,item(ICONS.get(n),ChatColor.GOLD+CATS.get(n).toUpperCase()));show(p,i);} - private void planets(Player p){Inventory i=menu(p,"planets","Planet Filter");String[] planets={"all","arrakis","giedi_prime","caladan","kaitain","sigma_draconis_iv"};for(int n=0;n=44)break;Material m=Material.matchMaterial(r.getString("material"));if(m==null)m=Material.PAPER;String action=mine?"Click to cancel and reclaim":"Click to buy ONE item";i.setItem(slot++,item(m,ChatColor.GOLD+"#"+r.getLong("id")+" "+m.name(),ChatColor.WHITE+"Quantity: "+r.getInt("quantity"),ChatColor.YELLOW+"Each: "+r.getBigDecimal("price")+" Solaris",ChatColor.GRAY+"Seller: "+r.getString("seller_name"),ChatColor.GRAY+"Planet: "+r.getString("origin"),ChatColor.GREEN+action));}}}catch(Exception ex){p.sendMessage(ChatColor.RED+"Exchange SQL error: "+ex.getMessage());} - i.setItem(45,item(Material.ARROW,ChatColor.YELLOW+"Previous"));i.setItem(53,item(Material.ARROW,ChatColor.YELLOW+"Next"));show(p,i);} - private void admin(Player p){Inventory i=menu(p,"admin","CHOAM Administration");i.setItem(20,item(Material.BOOK,ChatColor.GOLD+"All Listings"));i.setItem(24,item(Material.REDSTONE,ChatColor.RED+"Database Status"));show(p,i);} - @Override public boolean onCommand(CommandSender sender,Command cmd,String label,String[] args){if(!(sender instanceof Player p)){sender.sendMessage("Use in-game.");return true;}if(args.length==0){home(p);return true;}try{switch(args[0].toLowerCase(Locale.ROOT)){ - case "sell"->{if(args.length<3){p.sendMessage("/exchange sell ");return true;}sell(p,Integer.parseInt(args[1]),new BigDecimal(args[2]));} - case "buy"->{if(args.length<2)return true;buy(p,Long.parseLong(args[1]));} - case "cancel"->{if(args.length<2)return true;cancel(p,Long.parseLong(args[1]));} - case "admin"->{if(p.hasPermission("dune.admin"))admin(p);} - case "mine"->browse(p,"",0,true); - default->home(p); - }}catch(Exception e){p.sendMessage(ChatColor.RED+"Exchange: "+e.getMessage());}return true;} - private String category(Material m){String n=m.name();if(n.contains("ORE")||n.contains("INGOT")||n.contains("DEBRIS")||n.contains("DIAMOND")||n.contains("EMERALD")||n.contains("COAL")||n.contains("REDSTONE"))return "ores";if(n.contains("SAND")||n.contains("STONE")||n.contains("BRICK")||n.contains("PLANK"))return "building";if(n.contains("SWORD")||n.contains("PICKAXE")||n.contains("ARMOR")||n.contains("HELMET"))return "equipment";if(n.contains("WHEAT")||n.contains("CARROT")||n.contains("POTATO")||n.contains("SEED"))return "farming";return "misc";} - private void sell(Player p,int amount,BigDecimal price)throws Exception{ItemStack held=p.getInventory().getItemInMainHand();if(held.getType().isAir()||amount<1||amount>held.getAmount()||price.signum()<=0||price.scale()>2||price.compareTo(new BigDecimal("1000000"))>0)throw new IllegalArgumentException("Invalid amount or price.");if(held.hasItemMeta()&&(held.getItemMeta().hasDisplayName()||held.getItemMeta().hasEnchants()||!held.getItemMeta().getPersistentDataContainer().isEmpty()))throw new IllegalArgumentException("Only plain vanilla items can be listed.");String cat=category(held.getType());try(Connection c=plugin.connectEconomyDatabase();PreparedStatement q=c.prepareStatement("INSERT INTO dune_exchange_listings(seller,seller_name,origin,category,material,quantity,price) VALUES(?,?,?,?,?,?,?)")){q.setObject(1,p.getUniqueId());q.setString(2,p.getName());q.setString(3,p.getWorld().getName().toLowerCase(Locale.ROOT));q.setString(4,cat);q.setString(5,held.getType().name());q.setInt(6,amount);q.setBigDecimal(7,price);q.executeUpdate();}held.setAmount(held.getAmount()-amount);p.sendMessage(ChatColor.GREEN+"Listed "+amount+" "+held.getType()+" at "+price+" Solaris each.");} - private void buy(Player p,long id)throws Exception{if(id<1)return;try(Connection c=plugin.connectEconomyDatabase()){c.setAutoCommit(false);try(PreparedStatement q=c.prepareStatement("SELECT seller,material,quantity,price FROM dune_exchange_listings WHERE id=? FOR UPDATE")){q.setLong(1,id);try(ResultSet r=q.executeQuery()){if(!r.next())throw new IllegalArgumentException("Listing unavailable.");UUID seller=r.getObject(1,UUID.class);Material m=Material.matchMaterial(r.getString(2));BigDecimal price=r.getBigDecimal(4);if(seller.equals(p.getUniqueId()))throw new IllegalArgumentException("Cannot buy your own listing.");if(m==null||p.getInventory().firstEmpty()<0)throw new IllegalArgumentException("No inventory space.");try(PreparedStatement debit=c.prepareStatement("UPDATE dune_economy_balances SET balance=balance-? WHERE uuid=? AND balance>=?");PreparedStatement credit=c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES(?,?) ON CONFLICT(uuid) DO UPDATE SET balance=dune_economy_balances.balance+EXCLUDED.balance");PreparedStatement reduce=c.prepareStatement("UPDATE dune_exchange_listings SET quantity=quantity-1 WHERE id=?");PreparedStatement clean=c.prepareStatement("DELETE FROM dune_exchange_listings WHERE id=? AND quantity=0")){debit.setBigDecimal(1,price);debit.setObject(2,p.getUniqueId());debit.setBigDecimal(3,price);if(debit.executeUpdate()!=1)throw new IllegalArgumentException("Insufficient Solaris.");credit.setObject(1,seller);credit.setBigDecimal(2,price);credit.executeUpdate();reduce.setLong(1,id);reduce.executeUpdate();clean.setLong(1,id);clean.executeUpdate();c.commit();p.getInventory().addItem(new ItemStack(m));p.sendMessage(ChatColor.GREEN+"Purchased 1 "+m+" for "+price+" Solaris.");}}}catch(Exception ex){c.rollback();throw ex;}}} - private void cancel(Player p,long id)throws Exception{try(Connection c=plugin.connectEconomyDatabase()){c.setAutoCommit(false);try(PreparedStatement q=c.prepareStatement("SELECT material,quantity FROM dune_exchange_listings WHERE id=? AND seller=? FOR UPDATE")){q.setLong(1,id);q.setObject(2,p.getUniqueId());try(ResultSet r=q.executeQuery()){if(!r.next())throw new IllegalArgumentException("Listing not found.");Material m=Material.matchMaterial(r.getString(1));int qty=r.getInt(2);if(m==null||p.getInventory().firstEmpty()<0)throw new IllegalArgumentException("Clear inventory space.");try(PreparedStatement d=c.prepareStatement("DELETE FROM dune_exchange_listings WHERE id=?")){d.setLong(1,id);d.executeUpdate();}c.commit();while(qty>0){int n=Math.min(qty,m.getMaxStackSize());Map leftovers=p.getInventory().addItem(new ItemStack(m,n));for(ItemStack left:leftovers.values())p.getWorld().dropItemNaturally(p.getLocation(),left);qty-=n;}p.sendMessage(ChatColor.GREEN+"Listing cancelled and items returned.");}}}catch(Exception ex){c.rollback();throw ex;}}} - @EventHandler public void click(InventoryClickEvent e){if(!(e.getWhoClicked() instanceof Player p))return;String view=views.get(p.getUniqueId());if(view==null||!e.getView().getTitle().contains("CHOAM")&&!e.getView().getTitle().contains("Exchange")&&!e.getView().getTitle().contains("Planet"))return;e.setCancelled(true);if(e.getClickedInventory()!=e.getView().getTopInventory())return;int slot=e.getRawSlot();ItemStack clicked=e.getCurrentItem();if(clicked==null||clicked.getType().name().endsWith("GLASS_PANE"))return;Bukkit.getScheduler().runTask(plugin,()->{if(slot==49){home(p);return;}if(view.equals("home")){if(slot>=10&&slot<=15){browse(p,CATS.get(slot-10),0,false);return;}if(slot==29){categories(p);return;}if(slot==31){p.closeInventory();p.sendMessage(ChatColor.YELLOW+"Hold an item, then /exchange sell ");return;}if(slot==33){browse(p,"",0,true);return;}if(slot==40){planets(p);return;}if(slot==42&&p.hasPermission("dune.admin"))admin(p);return;}if(view.equals("categories")&&slot>=11&&slot<=16){browse(p,CATS.get(slot-11),0,false);return;}if(view.equals("planets")&&slot>=11&&slot<=16){filters.put(p.getUniqueId(),new String[]{"all","arrakis","giedi_prime","caladan","kaitain","sigma_draconis_iv"}[slot-11]);home(p);return;}if(view.equals("admin")){if(slot==20)browse(p,"",0,true);if(slot==24)p.sendMessage(ChatColor.YELLOW+"Exchange database configured: "+!plugin.getConfig().getBoolean("database.use-core-database",true));return;}if(slot==45||slot==53){browse(p,view.equals("mine")?"":view,pages.getOrDefault(p.getUniqueId(),0)+(slot==53?1:-1),view.equals("mine"));return;}if(clicked.hasItemMeta()){String name=ChatColor.stripColor(clicked.getItemMeta().getDisplayName());if(name.startsWith("#")){try{long id=Long.parseLong(name.split(" ")[0].substring(1));p.closeInventory();p.sendMessage(ChatColor.YELLOW+(view.equals("mine")?"Confirm cancellation: /exchange cancel ":"Confirm purchase: /exchange buy ")+id);}catch(NumberFormatException ignored){}}}});} - @EventHandler public void drag(InventoryDragEvent e){if(views.containsKey(e.getWhoClicked().getUniqueId())&&(e.getView().getTitle().contains("CHOAM")||e.getView().getTitle().contains("Exchange")||e.getView().getTitle().contains("Planet")))e.setCancelled(true);} - @EventHandler public void quit(org.bukkit.event.player.PlayerQuitEvent e){views.remove(e.getPlayer().getUniqueId());pages.remove(e.getPlayer().getUniqueId());} +/** Standard inventory slots work on Java and through Geyser without custom client interfaces. */ +@SuppressWarnings("deprecation") +final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { + private static final List CATEGORIES=List.of("ores","spice","building","equipment","farming","misc"); + private static final List PLANETS=List.of("all","arrakis","giedi_prime","caladan","kaitain","sigma_draconis_iv"); + private static final List ICONS=List.of(Material.IRON_PICKAXE,Material.ORANGE_DYE,Material.BRICKS,Material.IRON_SWORD,Material.WHEAT,Material.CHEST); + private final DuneEss plugin; + private final ExchangeStore store; + private final Map planets=new HashMap<>(); + private boolean ready; + static final class Screen implements InventoryHolder { + final UUID owner; + final Map actions=new HashMap<>(); + Inventory inventory; + Screen(UUID owner) { this.owner=owner; } + @Override public Inventory getInventory() { return inventory; } + } + ExchangeMenu(DuneEss plugin) { + this.plugin=plugin; + this.store=new ExchangeStore(plugin::connectEconomyDatabase); + } + void register() { + PluginCommand command=Objects.requireNonNull(plugin.getCommand("exchange")); + command.setExecutor(this); command.setTabCompleter(this); + Bukkit.getPluginManager().registerEvents(this,plugin); + try { store.initialize(); ready=true; } + catch(SQLException ex) { plugin.getLogger().warning("CHOAM is offline until the shared PostgreSQL economy is connected."); } + } + private boolean connected(Player p) { + // Retry after a transient startup outage; never trade against a fallback local wallet. + if(!ready) try { store.initialize(); ready=true; } catch(SQLException ignored) { } + if(!ready) p.sendMessage(ChatColor.YELLOW+"CHOAM is not connected. Ask an operator to configure DuneCore PostgreSQL and restart DuneEss. No items or Solaris were taken."); + return ready; + } + private String faction(Player p) { + Plugin core=Bukkit.getPluginManager().getPlugin("DuneCore"); + if(core!=null) try { + String house=String.valueOf(core.getClass().getMethod("factionOf",Player.class).invoke(core,p)); + if(List.of("Fremen","Atreides","Harkonnen","Corrino","Ordos").contains(house)) return house; + } catch(ReflectiveOperationException ignored) { } + return "Spacing Guild"; + } + private ChatColor tint(Player p) { + return switch(faction(p)) { + case "Atreides" -> ChatColor.AQUA; + case "Harkonnen" -> ChatColor.RED; + case "Corrino" -> ChatColor.GOLD; + case "Fremen" -> ChatColor.YELLOW; + case "Ordos" -> ChatColor.GREEN; + default -> ChatColor.LIGHT_PURPLE; + }; + } + private ItemStack icon(Material material,String name,String... lore) { + ItemStack item=new ItemStack(material); ItemMeta meta=item.getItemMeta(); + meta.setDisplayName(name); meta.setLore(Arrays.asList(lore)); item.setItemMeta(meta); return item; + } + private Screen screen(Player p,String title) { + Screen s=new Screen(p.getUniqueId()); + s.inventory=Bukkit.createInventory(s,54,tint(p)+"CHOAM | "+title); + Material glass=switch(faction(p)) { + case "Atreides" -> Material.CYAN_STAINED_GLASS_PANE; + case "Harkonnen" -> Material.RED_STAINED_GLASS_PANE; + case "Corrino" -> Material.YELLOW_STAINED_GLASS_PANE; + case "Ordos" -> Material.GREEN_STAINED_GLASS_PANE; + case "Fremen" -> Material.ORANGE_STAINED_GLASS_PANE; + default -> Material.PURPLE_STAINED_GLASS_PANE; + }; + for(int i=0;i<54;i++) if(i<9||i>=45||i%9==0||i%9==8) + s.inventory.setItem(i,icon(glass," ")); + button(s,49,Material.BARRIER,"Back to Exchange",()->home(p)); return s; + } + private void button(Screen s,int slot,Material material,String title,Runnable action,String... lore) { + s.inventory.setItem(slot,icon(material,ChatColor.GOLD+title,lore)); s.actions.put(slot,action); + } + private void home(Player p) { + Screen s=screen(p,faction(p)); + for(int i=0;ibrowse(p,category,0,false,false)); + } + button(s,29,Material.EMERALD,"Buy / All Items",()->browse(p,"all",0,false,false)); + button(s,31,Material.CHEST,"Sell Held Item",()->{ + p.closeInventory(); p.sendMessage(ChatColor.YELLOW+"Hold the item to list, then /exchange sell . Example: /exchange sell 16 25"); + },"Tagged Dune items and their attributes are preserved.","Price is for ONE item."); + button(s,33,Material.BOOK,"My Listings",()->browse(p,"all",0,true,false),"Cancel and reclaim your unsold items."); + button(s,40,Material.COMPASS,"Planet: "+planets.getOrDefault(p.getUniqueId(),"all"),()->planetMenu(p)); + button(s,38,Material.PAPER,"Trading Guide",()->{ + p.sendMessage(ChatColor.YELLOW+"/exchange sell · /exchange buy · /exchange cancel · /exchange mine"); + p.sendMessage(ChatColor.GRAY+"Purchases buy one item. Listings reserve the offered items. Website demo offers cannot be purchased."); + }); + if(p.hasPermission("dune.admin")) button(s,42,Material.COMMAND_BLOCK,"Exchange Administration",()->admin(p)); + button(s,49,Material.BARRIER,"Close",p::closeInventory); + p.openInventory(s.inventory); + } + private void planetMenu(Player p) { + Screen s=screen(p,"Planet Filter"); + for(int i=0;i{planets.put(p.getUniqueId(),planet); browse(p,"all",0,false,false);}); + } + p.openInventory(s.inventory); + } + private void admin(Player p) { + if(!p.hasPermission("dune.admin")) return; + Screen s=screen(p,"Administration"); + button(s,20,Material.BOOK,"All Listings",()->browse(p,"all",0,false,true),"All planets. Read-only inspection; normal ownership rules apply."); + button(s,24,Material.REDSTONE,"Check Database",()->{ + if(connected(p)) p.sendMessage(ChatColor.GREEN+"Shared CHOAM database connected."); + }); + p.openInventory(s.inventory); + } + private ItemStack decode(ExchangeStore.Listing offer) { + ItemStack item; + if(offer.payload()!=null&&!offer.payload().isBlank()) item=ItemStack.deserializeBytes(Base64.getDecoder().decode(offer.payload())); + else { + Material material=Material.matchMaterial(offer.material()); + if(material==null||material.isAir()||!material.isItem()) throw new IllegalArgumentException("This item is unsupported on this server; contact an operator."); + item=new ItemStack(material); + } + item.setAmount(1); return item; + } + private void browse(Player p,String category,int page,boolean mine,boolean admin) { + if(admin&&!p.hasPermission("dune.admin")) return; + if(!connected(p)) return; + execute(p,()->{ + int current=Math.max(0,page); + String planet=mine||admin?"all":planets.getOrDefault(p.getUniqueId(),"all"); + List rows=store.browse(category,planet,mine?p.getUniqueId():null,current); + Screen s=screen(p,(mine?"My Listings":admin?"All Listings":category)+" · "+(current+1)); + int slot=10; + for(ExchangeStore.Listing row:rows.subList(0,Math.min(28,rows.size()))) { + while(slot%9==0||slot%9==8) slot++; + ItemStack item; + try { item=decode(row); } catch(RuntimeException ex) { item=new ItemStack(Material.PAPER); } + ItemMeta meta=item.getItemMeta(); + meta.setDisplayName(ChatColor.GOLD+"#"+row.id()+" "+(row.displayName()==null?row.material():row.displayName())); + meta.setLore(List.of("Quantity: "+row.quantity(),"Each: "+row.price()+" Solaris","Seller: "+row.sellerName(),"Planet: "+row.origin(), + row.seller().equals(p.getUniqueId())?"Click to reclaim unsold items":"Click to review purchase")); + item.setItemMeta(meta); s.inventory.setItem(slot,item); + s.actions.put(slot,()->confirm(p,row.id(),row.seller().equals(p.getUniqueId()))); slot++; + } + if(rows.isEmpty()) s.inventory.setItem(22,icon(Material.PAPER,"No matching listings","Try another planet or list a held item.")); + if(current>0) button(s,45,Material.ARROW,"Previous",()->browse(p,category,current-1,mine,admin)); + if(rows.size()>28) button(s,53,Material.ARROW,"Next",()->browse(p,category,current+1,mine,admin)); + p.openInventory(s.inventory); + }); + } + private void confirm(Player p,long id,boolean reclaim) { + execute(p,()->{ + ExchangeStore.Listing row=store.find(id); + if(reclaim&&!row.seller().equals(p.getUniqueId())) throw new IllegalArgumentException("You can reclaim only your own listings."); + Screen s=screen(p,reclaim?"Reclaim Listing":"Confirm Purchase"); + s.inventory.setItem(22,icon(decode(row).getType(),"#"+id+" "+(row.displayName()==null?row.material():row.displayName()), + "Seller: "+row.sellerName(),reclaim?"Return "+row.quantity()+" unsold items":"Buy ONE for "+row.price()+" Solaris")); + button(s,30,Material.LIME_CONCRETE,reclaim?"Confirm Reclaim":"Confirm Purchase",()->{ + p.closeInventory(); if(reclaim) cancel(p,id); else buy(p,id); + }); + button(s,32,Material.RED_CONCRETE,"Never Mind",()->home(p)); p.openInventory(s.inventory); + }); + } + private boolean fits(Player p,ItemStack item,int amount) { + int remaining=amount; + for(ItemStack slot:p.getInventory().getStorageContents()) { + if(slot==null||slot.getType().isAir()) remaining-=item.getMaxStackSize(); + else if(slot.isSimilar(item)) remaining-=Math.max(0,item.getMaxStackSize()-slot.getAmount()); + if(remaining<=0) return true; + } + return false; + } + private void deliver(Player p,ItemStack item,int amount) { + item.setAmount(amount); + Map excess=p.getInventory().addItem(item); + // Capacity is checked immediately before the transaction on this same server thread. + for(ItemStack left:excess.values()) p.getWorld().dropItemNaturally(p.getLocation(),left); + p.saveData(); + } + private void sell(Player p,int amount,BigDecimal price) throws SQLException { + ExchangeStore.validate(amount,price); + ItemStack held=p.getInventory().getItemInMainHand(); + if(held.getType().isAir()||amount>held.getAmount()) throw new IllegalArgumentException("Hold at least that many items in your main hand."); + // Never let operator tools become tradeable through the public exchange. + if(held.hasItemMeta()) for(NamespacedKey key:held.getItemMeta().getPersistentDataContainer().getKeys()) + if(key.getKey().contains("admin")) throw new IllegalArgumentException("Administrative tools cannot be listed."); + ItemStack unit=held.clone(); unit.setAmount(1); + String name=unit.hasItemMeta()&&unit.getItemMeta().hasDisplayName()?ChatColor.stripColor(unit.getItemMeta().getDisplayName()):unit.getType().name(); + if(name.length()>120) name=name.substring(0,120); + store.list(p.getUniqueId(),p.getName(),origin(p),category(unit),unit.getType().name(),amount,price, + Base64.getEncoder().encodeToString(unit.serializeAsBytes()),name); + held.setAmount(held.getAmount()-amount); p.saveData(); + p.sendMessage(ChatColor.GREEN+"Listed "+amount+" "+name+" at "+price+" Solaris each."); + } + private String origin(Player p) { + String world=p.getWorld().getName().toLowerCase(Locale.ROOT).replace('-','_'); + for(String planet:PLANETS) if(!planet.equals("all")&&world.contains(planet)) return planet; + return plugin.localPlanet(); + } + static String category(ItemStack item) { + if(item.hasItemMeta()) { + String kind=item.getItemMeta().getPersistentDataContainer().get(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING); + if(kind!=null&&kind.toLowerCase(Locale.ROOT).contains("spice")) return "spice"; + } + String n=item.getType().name(); + if(n.contains("ORE")||n.contains("INGOT")||n.contains("DEBRIS")||n.contains("DIAMOND")||n.contains("EMERALD")||n.contains("COAL")||n.contains("REDSTONE")||n.contains("RAW_")||n.contains("LAPIS")||n.contains("QUARTZ")) return "ores"; + if(n.contains("SWORD")||n.contains("PICKAXE")||n.endsWith("AXE")||n.contains("HELMET")||n.contains("CHESTPLATE")||n.contains("LEGGINGS")||n.contains("BOOTS")||n.contains("ELYTRA")||n.contains("BOW")||n.contains("SHOVEL")||n.contains("HOE")||n.equals("SHIELD")||n.equals("TRIDENT")||n.equals("FISHING_ROD")||n.equals("ENCHANTED_BOOK")) return "equipment"; + if(item.getType().isEdible()||n.contains("WHEAT")||n.contains("SEED")||n.contains("SAPLING")) return "farming"; + return item.getType().isBlock()?"building":"misc"; + } + private void buy(Player p,long id) { + if(!connected(p)) return; + execute(p,()->{ + ExchangeStore.Listing before=store.find(id); ItemStack item=decode(before); + if(!fits(p,item,1)) throw new IllegalArgumentException("Make room in your inventory first."); + ExchangeStore.Listing bought=store.buy(p.getUniqueId(),id); + deliver(p,item,1); p.sendMessage(ChatColor.GREEN+"Purchased one item for "+bought.price()+" Solaris."); + }); + } + private void cancel(Player p,long id) { + if(!connected(p)) return; + execute(p,()->{ + ExchangeStore.Listing before=store.find(id); ItemStack item=decode(before); + if(!fits(p,item,before.quantity())) throw new IllegalArgumentException("Make room for all "+before.quantity()+" items first."); + ExchangeStore.Listing cancelled=store.cancel(p.getUniqueId(),id); + deliver(p,item,cancelled.quantity()); p.sendMessage(ChatColor.GREEN+"Listing cancelled. Unsold items returned."); + }); + } + private interface Operation { void run() throws SQLException; } + private void execute(Player p,Operation action) { + try { action.run(); } + catch(IllegalArgumentException ex) { p.sendMessage(ChatColor.YELLOW+ex.getMessage()); } + catch(SQLException ex) { + ready=false; plugin.getLogger().warning("CHOAM SQL operation failed: "+ex.getSQLState()); + p.sendMessage(ChatColor.RED+"The market database is unavailable. Please try again later."); + } + } + @Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args) { + if(!(sender instanceof Player p)) { sender.sendMessage("Open the CHOAM exchange in-game with /exchange."); return true; } + if(args.length==0) { home(p); return true; } + String action=args[0].toLowerCase(Locale.ROOT); + if(action.equals("admin")) { if(p.hasPermission("dune.admin")) admin(p); else p.sendMessage(ChatColor.RED+"Operators only."); return true; } + if(action.equals("help")) { home(p); return true; } + if(!connected(p)) return true; + execute(p,()->{ + try { + switch(action) { + case "sell" -> { if(args.length!=3) throw new IllegalArgumentException("/exchange sell "); sell(p,Integer.parseInt(args[1]),new BigDecimal(args[2])); } + case "buy","cancel" -> { if(args.length!=2) throw new IllegalArgumentException("/exchange "+action+" "); long id=Long.parseLong(args[1]); if(id<1) throw new IllegalArgumentException("Listing IDs are positive numbers."); confirm(p,id,action.equals("cancel")); } + case "mine" -> browse(p,"all",0,true,false); + default -> p.sendMessage(ChatColor.YELLOW+"Use /exchange, /exchange sell , /exchange buy , /exchange cancel , or /exchange mine."); + } + } catch(NumberFormatException ex) { throw new IllegalArgumentException("Enter a valid amount, price and listing ID."); } + }); + return true; + } + @Override public List onTabComplete(CommandSender sender,Command command,String alias,String[] args) { + if(args.length!=1) return List.of(); + return List.of("help","sell","buy","cancel","mine","admin").stream() + .filter(s->!s.equals("admin")||sender.hasPermission("dune.admin")) + .filter(s->s.startsWith(args[0].toLowerCase(Locale.ROOT))).toList(); + } + @EventHandler public void click(InventoryClickEvent e) { + if(!(e.getView().getTopInventory().getHolder() instanceof Screen screen)) return; + e.setCancelled(true); + if(!(e.getWhoClicked() instanceof Player p)||!screen.owner.equals(p.getUniqueId()) + ||e.getClickedInventory()!=e.getView().getTopInventory()||e.getClick()==ClickType.DOUBLE_CLICK) return; + Runnable action=screen.actions.get(e.getRawSlot()); + if(action!=null) Bukkit.getScheduler().runTask(plugin,()->{ + if(p.isOnline()&&p.getOpenInventory().getTopInventory()==screen.inventory) action.run(); + }); + } + @EventHandler public void drag(InventoryDragEvent e) { + if(e.getView().getTopInventory().getHolder() instanceof Screen) e.setCancelled(true); + } + @EventHandler public void quit(PlayerQuitEvent e) { planets.remove(e.getPlayer().getUniqueId()); } } diff --git a/DuneEss/src/main/java/com/example/duneess/ExchangeStore.java b/DuneEss/src/main/java/com/example/duneess/ExchangeStore.java new file mode 100644 index 00000000..d71acead --- /dev/null +++ b/DuneEss/src/main/java/com/example/duneess/ExchangeStore.java @@ -0,0 +1,109 @@ +package com.example.duneess; + +import java.math.BigDecimal; +import java.sql.*; +import java.util.*; + +/** SQL escrow and wallet changes share one transaction. Bukkit inventory work stays on its server thread. */ +final class ExchangeStore { + interface Connections { Connection open() throws SQLException; } + record Listing(long id, UUID seller, String sellerName, String origin, String category, + String material, int quantity, BigDecimal price, String payload, String displayName) {} + private final Connections connections; + ExchangeStore(Connections connections) { this.connections = connections; } + void initialize() throws SQLException { + try (Connection c = connections.open(); Statement s = c.createStatement()) { + s.setQueryTimeout(5); + s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_exchange_listings (id BIGSERIAL PRIMARY KEY, seller UUID NOT NULL, seller_name VARCHAR(32) NOT NULL, origin VARCHAR(48) NOT NULL, category VARCHAR(24) NOT NULL, material VARCHAR(80) NOT NULL, quantity INT NOT NULL CHECK(quantity>0), price NUMERIC(20,2) NOT NULL CHECK(price>0))"); + s.executeUpdate("ALTER TABLE dune_exchange_listings ADD COLUMN IF NOT EXISTS payload TEXT"); + s.executeUpdate("ALTER TABLE dune_exchange_listings ADD COLUMN IF NOT EXISTS display_name VARCHAR(120)"); + } + } + private PreparedStatement prepare(Connection c, String sql) throws SQLException { + PreparedStatement q = c.prepareStatement(sql); q.setQueryTimeout(5); return q; + } + static void validate(int amount, BigDecimal price) { + if (amount < 1 || amount > 64 || price == null || price.signum() <= 0 || price.scale() > 2 + || price.compareTo(new BigDecimal("1000000")) > 0) + throw new IllegalArgumentException("Use 1–64 items and a price from 0.01 to 1,000,000 Solaris (two decimals maximum)."); + } + void list(UUID seller, String name, String origin, String category, String material, + int amount, BigDecimal price, String payload, String displayName) throws SQLException { + validate(amount, price); + try (Connection c = connections.open(); PreparedStatement q = prepare(c, + "INSERT INTO dune_exchange_listings(seller,seller_name,origin,category,material,quantity,price,payload,display_name) VALUES(?,?,?,?,?,?,?,?,?)")) { + q.setObject(1,seller); q.setString(2,name); q.setString(3,origin); q.setString(4,category); + q.setString(5,material); q.setInt(6,amount); q.setBigDecimal(7,price); q.setString(8,payload); q.setString(9,displayName); + q.executeUpdate(); + } + } + List browse(String category, String planet, UUID owner, int page) throws SQLException { + String sql = "SELECT * FROM dune_exchange_listings WHERE 1=1"; + if (!category.equals("all")) sql += " AND category=?"; + if (!planet.equals("all")) sql += " AND origin=?"; + if (owner != null) sql += " AND seller=?"; + sql += " ORDER BY id DESC LIMIT 29 OFFSET ?"; + try (Connection c = connections.open(); PreparedStatement q = prepare(c,sql)) { + int k=1; + if (!category.equals("all")) q.setString(k++,category); + if (!planet.equals("all")) q.setString(k++,planet); + if (owner!=null) q.setObject(k++,owner); + q.setInt(k,Math.max(0,page)*28); + try (ResultSet r=q.executeQuery()) { + List rows=new ArrayList<>(); while(r.next()) rows.add(read(r)); return rows; + } + } + } + Listing find(long id) throws SQLException { + try(Connection c=connections.open(); PreparedStatement q=prepare(c,"SELECT * FROM dune_exchange_listings WHERE id=?")) { + q.setLong(1,id); try(ResultSet r=q.executeQuery()) { + if(!r.next()) throw new IllegalArgumentException("That listing has already been sold or cancelled."); + return read(r); + } + } + } + private Listing read(ResultSet r) throws SQLException { + return new Listing(r.getLong("id"),r.getObject("seller",UUID.class),r.getString("seller_name"), + r.getString("origin"),r.getString("category"),r.getString("material"),r.getInt("quantity"), + r.getBigDecimal("price"),r.getString("payload"),r.getString("display_name")); + } + /** On SQL failure, no wallet or listing changes survive. Never set quantity to zero under CHECK(quantity>0). */ + Listing buy(UUID buyer, long id) throws SQLException { + try(Connection c=connections.open()) { + c.setAutoCommit(false); + try(PreparedStatement q=prepare(c,"SELECT * FROM dune_exchange_listings WHERE id=? FOR UPDATE")) { + q.setLong(1,id); + try(ResultSet r=q.executeQuery()) { + if(!r.next()) throw new IllegalArgumentException("Listing unavailable."); + Listing offer=read(r); + if(offer.seller().equals(buyer)) throw new IllegalArgumentException("Use My Listings to reclaim your own offer."); + try(PreparedStatement debit=prepare(c,"UPDATE dune_economy_balances SET balance=balance-? WHERE uuid=? AND balance>=?"); + PreparedStatement credit=prepare(c,"UPDATE dune_economy_balances SET balance=balance+? WHERE uuid=?"); + PreparedStatement stock=prepare(c,offer.quantity()==1?"DELETE FROM dune_exchange_listings WHERE id=?":"UPDATE dune_exchange_listings SET quantity=quantity-1 WHERE id=?")) { + debit.setBigDecimal(1,offer.price()); debit.setObject(2,buyer); debit.setBigDecimal(3,offer.price()); + if(debit.executeUpdate()!=1) throw new IllegalArgumentException("Insufficient Solaris or shared wallet unavailable."); + credit.setBigDecimal(1,offer.price()); credit.setObject(2,offer.seller()); + if(credit.executeUpdate()!=1) throw new IllegalArgumentException("Seller wallet unavailable; no payment taken."); + stock.setLong(1,id); if(stock.executeUpdate()!=1) throw new SQLException("Listing changed."); + c.commit(); return offer; + } + } + } catch(SQLException|RuntimeException ex) { c.rollback(); throw ex; } + } + } + Listing cancel(UUID owner, long id) throws SQLException { + try(Connection c=connections.open()) { + c.setAutoCommit(false); + try(PreparedStatement q=prepare(c,"SELECT * FROM dune_exchange_listings WHERE id=? AND seller=? FOR UPDATE")) { + q.setLong(1,id); q.setObject(2,owner); + try(ResultSet r=q.executeQuery()) { + if(!r.next()) throw new IllegalArgumentException("This listing is unavailable or belongs to another player."); + Listing offer=read(r); + try(PreparedStatement d=prepare(c,"DELETE FROM dune_exchange_listings WHERE id=?")) { + d.setLong(1,id); d.executeUpdate(); c.commit(); return offer; + } + } + } catch(SQLException|RuntimeException ex) { c.rollback(); throw ex; } + } + } +} diff --git a/DuneEss/src/main/resources/plugin.yml b/DuneEss/src/main/resources/plugin.yml index 7d3f213d..cb82cb41 100644 --- a/DuneEss/src/main/resources/plugin.yml +++ b/DuneEss/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ name: DuneEss -version: 1.0.1 +version: 1.0.2 main: com.example.duneess.DuneEss api-version: '1.21' depend: [Vault] diff --git a/DuneEss/src/test/java/com/example/duneess/ExchangeMenuTest.java b/DuneEss/src/test/java/com/example/duneess/ExchangeMenuTest.java new file mode 100644 index 00000000..e99788bf --- /dev/null +++ b/DuneEss/src/test/java/com/example/duneess/ExchangeMenuTest.java @@ -0,0 +1,62 @@ +package com.example.duneess; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.*; +import org.bukkit.inventory.*; +import org.bukkit.scheduler.BukkitScheduler; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +class ExchangeMenuTest { + @Test void ordinaryInventoriesAreNeverHijackedByTitle() { + ExchangeMenu menu=new ExchangeMenu(mock(DuneEss.class)); + InventoryClickEvent click=mock(InventoryClickEvent.class); + InventoryView view=mock(InventoryView.class);Inventory inventory=mock(Inventory.class); + when(click.getView()).thenReturn(view);when(view.getTopInventory()).thenReturn(inventory); + menu.click(click);verify(click,never()).setCancelled(anyBoolean()); + } + @Test void bottomInventoryTransfersAndDragsAreCancelledWithoutRunningAnAction() { + ExchangeMenu menu=new ExchangeMenu(mock(DuneEss.class));UUID owner=UUID.randomUUID(); + ExchangeMenu.Screen screen=new ExchangeMenu.Screen(owner); + Inventory top=mock(Inventory.class),bottom=mock(Inventory.class);InventoryView view=mock(InventoryView.class); + screen.inventory=top;when(top.getHolder()).thenReturn(screen);when(view.getTopInventory()).thenReturn(top); + Player player=mock(Player.class);when(player.getUniqueId()).thenReturn(owner); + InventoryClickEvent click=mock(InventoryClickEvent.class);when(click.getView()).thenReturn(view); + when(click.getWhoClicked()).thenReturn(player);when(click.getClickedInventory()).thenReturn(bottom); + AtomicInteger actions=new AtomicInteger();screen.actions.put(10,actions::incrementAndGet); + menu.click(click);verify(click).setCancelled(true);assertEquals(0,actions.get()); + InventoryDragEvent drag=mock(InventoryDragEvent.class);when(drag.getView()).thenReturn(view); + menu.drag(drag);verify(drag).setCancelled(true); + } + @Test void queuedSecondConfirmationCannotExecuteAfterFirstClosesScreen() { + DuneEss plugin=mock(DuneEss.class);ExchangeMenu menu=new ExchangeMenu(plugin); + UUID owner=UUID.randomUUID();ExchangeMenu.Screen screen=new ExchangeMenu.Screen(owner); + Inventory top=mock(Inventory.class),closed=mock(Inventory.class);screen.inventory=top; + InventoryView view=mock(InventoryView.class);when(view.getTopInventory()).thenReturn(top); + when(top.getHolder()).thenReturn(screen); + Player player=mock(Player.class);when(player.getUniqueId()).thenReturn(owner);when(player.isOnline()).thenReturn(true); + when(player.getOpenInventory()).thenReturn(view); + InventoryClickEvent click=mock(InventoryClickEvent.class);when(click.getView()).thenReturn(view); + when(click.getWhoClicked()).thenReturn(player);when(click.getClickedInventory()).thenReturn(top); + when(click.getClick()).thenReturn(ClickType.LEFT);when(click.getRawSlot()).thenReturn(30); + AtomicInteger actions=new AtomicInteger();screen.actions.put(30,()->{actions.incrementAndGet();when(view.getTopInventory()).thenReturn(closed);}); + BukkitScheduler scheduler=mock(BukkitScheduler.class);List queued=new ArrayList<>(); + try(MockedStatic bukkit=mockStatic(Bukkit.class)) { + bukkit.when(Bukkit::getScheduler).thenReturn(scheduler); + when(scheduler.runTask(eq(plugin),any(Runnable.class))).thenAnswer(invocation->{queued.add(invocation.getArgument(1));return null;}); + menu.click(click);menu.click(click);queued.forEach(Runnable::run); + } + assertEquals(1,actions.get()); + } + @Test void administratorCommandRechecksPermission() { + ExchangeMenu menu=new ExchangeMenu(mock(DuneEss.class));Player player=mock(Player.class); + assertTrue(menu.onCommand(player,null,"exchange",new String[]{"admin"})); + verify(player).sendMessage(contains("Operators only")); + } +} diff --git a/DuneEss/src/test/java/com/example/duneess/ExchangeStoreTest.java b/DuneEss/src/test/java/com/example/duneess/ExchangeStoreTest.java new file mode 100644 index 00000000..7bdde66b --- /dev/null +++ b/DuneEss/src/test/java/com/example/duneess/ExchangeStoreTest.java @@ -0,0 +1,101 @@ +package com.example.duneess; + +import org.junit.jupiter.api.*; +import java.math.BigDecimal; +import java.sql.*; +import java.util.*; +import java.util.concurrent.*; +import static org.junit.jupiter.api.Assertions.*; + +class ExchangeStoreTest { + private String url; + private ExchangeStore store; + private final UUID seller=UUID.randomUUID(),buyer=UUID.randomUUID(); + @BeforeEach void setup() throws Exception { + url="jdbc:h2:mem:"+UUID.randomUUID()+";MODE=PostgreSQL;DB_CLOSE_DELAY=-1"; + store=new ExchangeStore(()->DriverManager.getConnection(url)); + try(Connection c=DriverManager.getConnection(url);Statement s=c.createStatement()) { + s.execute("CREATE TABLE dune_economy_balances(uuid UUID PRIMARY KEY,balance NUMERIC(20,2) NOT NULL)"); + } + wallet(seller,"0"); wallet(buyer,"100"); store.initialize(); store.initialize(); + } + private void wallet(UUID id,String amount) throws SQLException { + try(Connection c=DriverManager.getConnection(url);PreparedStatement q=c.prepareStatement("INSERT INTO dune_economy_balances VALUES(?,?)")) { + q.setObject(1,id);q.setBigDecimal(2,new BigDecimal(amount));q.executeUpdate(); + } + } + private BigDecimal balance(UUID id) throws SQLException { + try(Connection c=DriverManager.getConnection(url);PreparedStatement q=c.prepareStatement("SELECT balance FROM dune_economy_balances WHERE uuid=?")) { + q.setObject(1,id);try(ResultSet r=q.executeQuery()){assertTrue(r.next());return r.getBigDecimal(1);} + } + } + private long listing(int amount,String price) throws SQLException { + store.list(seller,"Seller","arrakis","spice","ORANGE_DYE",amount,new BigDecimal(price),"preserved-payload","Melange"); + return store.browse("all","all",null,0).getFirst().id(); + } + @Test void finalItemIsDeletedAndBothWalletsChangeExactlyOnce() throws Exception { + long id=listing(1,"12.50"); + assertEquals("preserved-payload",store.buy(buyer,id).payload()); + assertEquals(new BigDecimal("87.50"),balance(buyer)); + assertEquals(new BigDecimal("12.50"),balance(seller)); + assertTrue(store.browse("all","all",null,0).isEmpty()); + assertThrows(IllegalArgumentException.class,()->store.buy(buyer,id)); + assertEquals(new BigDecimal("87.50"),balance(buyer)); + } + @Test void partiallyFilledStockRemainsAndCancellationReturnsOnlyUnsoldQuantity() throws Exception { + long id=listing(3,"10");store.buy(buyer,id); + assertEquals(2,store.find(id).quantity()); + assertEquals(2,store.cancel(seller,id).quantity()); + assertTrue(store.browse("all","all",null,0).isEmpty()); + assertEquals(new BigDecimal("10.00"),balance(seller)); + } + @Test void insufficientFundsAndSelfPurchaseCannotChangeStock() throws Exception { + long id=listing(2,"101"); + assertThrows(IllegalArgumentException.class,()->store.buy(buyer,id)); + assertThrows(IllegalArgumentException.class,()->store.buy(seller,id)); + assertEquals(2,store.find(id).quantity());assertEquals(new BigDecimal("100.00"),balance(buyer)); + } + @Test void wrongOwnerCannotCancelOrReclaim() throws Exception { + long id=listing(2,"1"); + assertThrows(IllegalArgumentException.class,()->store.cancel(buyer,id)); + assertEquals(2,store.find(id).quantity()); + } + @Test void failedSellerCreditRollsBackBuyerDebit() throws Exception { + long id=listing(1,"10"); + try(Connection c=DriverManager.getConnection(url);PreparedStatement q=c.prepareStatement("DELETE FROM dune_economy_balances WHERE uuid=?")) { + q.setObject(1,seller);q.executeUpdate(); + } + assertThrows(IllegalArgumentException.class,()->store.buy(buyer,id)); + assertEquals(new BigDecimal("100.00"),balance(buyer));assertEquals(1,store.find(id).quantity()); + } + @Test void filtersAndPaginationIncludeAllCategoriesWithoutEmptyCategoryPredicate() throws Exception { + listing(1,"1"); + store.list(seller,"Seller","caladan","building","OAK_LOG",64,new BigDecimal("2"),null,null); + assertEquals(2,store.browse("all","all",null,0).size()); + assertEquals(1,store.browse("spice","arrakis",null,0).size()); + assertTrue(store.browse("spice","caladan",null,0).isEmpty()); + assertTrue(store.browse("all","all",buyer,0).isEmpty()); + for(int i=0;i<30;i++) listing(1,"1"); + assertEquals(29,store.browse("all","all",seller,0).size()); + assertEquals(4,store.browse("all","all",seller,1).size()); + } + @Test void concurrentBuyersCannotBothBuyTheLastItem() throws Exception { + UUID other=UUID.randomUUID(); wallet(other,"100");long id=listing(1,"25"); + try(ExecutorService pool=Executors.newFixedThreadPool(2)) { + CountDownLatch start=new CountDownLatch(1); + List> results=new ArrayList<>(); + for(UUID player:List.of(buyer,other)) results.add(pool.submit(()->{ + start.await();try{store.buy(player,id);return true;}catch(IllegalArgumentException ex){return false;} + })); + start.countDown();int successes=0;for(Future result:results)if(result.get(5,TimeUnit.SECONDS)) successes++; + assertEquals(1,successes);assertEquals(new BigDecimal("25.00"),balance(seller)); + assertEquals(new BigDecimal("175.00"),balance(buyer).add(balance(other))); + } + } + @Test void invalidAmountsAndPricesAreRejectedBeforeWriting() { + for(String price:List.of("0","-1","1000001","0.001")) + assertThrows(IllegalArgumentException.class,()->listing(1,price)); + assertThrows(IllegalArgumentException.class,()->listing(0,"1")); + assertThrows(IllegalArgumentException.class,()->listing(65,"1")); + } +} diff --git a/website/EXCHANGE-HANDOFF.md b/website/EXCHANGE-HANDOFF.md index 096da173..3d6a900d 100644 --- a/website/EXCHANGE-HANDOFF.md +++ b/website/EXCHANGE-HANDOFF.md @@ -1,5 +1,14 @@ # CHOAM Exchange — handoff notes (18 October 2026) +## Completion update — supersedes the old pre-deployment checklist below + +- Website: 40 clearly labelled fictional offers, all five planets and six categories, working sidebar/select/tile filters, search (including category and planet names), sorting, pagination and retry. Demo offers never show a purchase command. A valid empty live market remains empty. Matching responsive CSS is implemented; mobile planet controls no longer inherit absolute navigation positioning. Planet artwork is in external CSS to comply with the production Content Security Policy. +- In-game: DuneEss 1.0.2 compiles. Replaced the broken exchange class with holder-based faction menus, buy/reclaim confirmation screens, all-items/admin browsing, actual faction identity (including Ordos), item payload preservation and inventory-space checks. A locked SQL transaction handles payment/credit/stock; final-item purchase deletes the row without violating the positive-quantity constraint. Offline/local fallback wallets cannot trade. +- Verification: 12 passing Java tests (8 SQL transaction tests and 4 GUI/security tests); 37 website tests pass. Desktop filters/pagination and 390px mobile layout/menu verified in a browser. SQL tests use H2 PostgreSQL mode; live PostgreSQL/Paper/Velocity/Geyser staging is not claimed. +- Source is developed on a separate `exchange-completion` GitHub branch for review; main is not overwritten. Website publication uses the existing Sites project and public audience, separate from GitHub. +- Read `../DuneEss/EXCHANGE.md` for commands, configuration, legacy schema migration, payload support and remaining server-thread/crash-boundary limitations. Installing the built JAR and configuring the production database/HTTPS read-only bridge require server access; no game server or database has been changed in this task. +- The original notes below are historical. CSS, all-world handling, sidebar handling, demo labels and local build/tests are completed. Publishing result and source commit are recorded in the completion response. + ## Goal Match the existing Project Dune website at https://project-dune.bonnystoat9.chatgpt.site rather than a new design. Preserve the original horizontal illustrated menu, PROJECT DUNE wordmark, Cormorant Garamond / Manrope typography, dark teal (#10201f / #142a28), gold (#d5ab63), parchment (#f5eddd), and Minecraft Arrakis imagery. Use the latest approved exchange mockup as inspiration only. diff --git a/website/tests/exchange.test.mjs b/website/tests/exchange.test.mjs new file mode 100644 index 00000000..7cbbb714 --- /dev/null +++ b/website/tests/exchange.test.mjs @@ -0,0 +1,44 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {demoListings,validListings,filterListings,listingInstruction,categories,planets} from '../web/exchange-data.js'; +import {handleExchange} from '../worker/exchange-api.mjs'; +test('Demo market covers every category and planet, with enough listings for pagination',()=>{ + assert.ok(demoListings.length>24); + assert.equal(validListings(demoListings).length,demoListings.length); + for(const category of Object.keys(categories)) assert.ok(filterListings(demoListings,{category}).length,category); + for(const planet of Object.keys(planets)) assert.ok(filterListings(demoListings,{planet}).length,planet); + for(const row of demoListings){assert.match(row.seller,/demo/);assert.doesNotMatch(listingInstruction(row,true),/exchange buy/);} +}); +test('Search includes material names, categories, planets and sellers without mutating source',()=>{ + const original=demoListings.map(x=>x.id); + assert.ok(filterListings(demoListings,{search:'iron ingot'}).length); + assert.equal(filterListings(demoListings,{search:'caladan'}).length,filterListings(demoListings,{planet:'caladan'}).length); + assert.ok(filterListings(demoListings,{search:'ores & minerals'}).length); + const sorted=filterListings(demoListings,{sort:'price'}); + assert.ok(sorted.every((x,i)=>i===0||x.price>=sorted[i-1].price)); + assert.deepEqual(demoListings.map(x=>x.id),original); + assert.equal(filterListings(demoListings,{category:'equipment',planet:'arrakis'}).length,2); +}); +test('Live validation rejects invalid data and duplicate IDs; empty live market stays empty',()=>{ + const good=demoListings[0]; + assert.deepEqual(validListings([]),[]); + assert.throws(()=>validListings(null)); + assert.equal(validListings([good,good,null,{...good,id:2,quantity:0},{...good,id:3,origin:'unknown'}]).length,1); + assert.match(listingInstruction(good,false),/exchange buy 1$/); +}); +test('Unconnected API stays unavailable, never fabricates live listings or allows trading',async()=>{ + const offline=await handleExchange(new Request('https://example.test/api/exchange/listings'),{}); + assert.equal(offline.status,503);assert.equal((await offline.json()).error,'market_not_configured'); + const write=await handleExchange(new Request('https://example.test/api/exchange/listings',{method:'POST'}),{}); + assert.equal(write.status,405); +}); +test('Connected gateway sends the token only upstream and exposes sanitized read-only offers',async()=>{ + const original=globalThis.fetch;let received; + globalThis.fetch=async(url,options)=>{received={url:String(url),options};return Response.json({listings:[{...demoListings[0],seller:'Trader',secret:'never expose'}]});}; + try { + const response=await handleExchange(new Request('https://example.test/api/exchange/listings'),{EXCHANGE_LISTINGS_URL:'https://game.test/listings',EXCHANGE_READ_TOKEN:'test-token'}); + assert.equal(response.status,200);assert.equal(received.options.headers.Authorization,'Bearer test-token'); + const body=await response.text();assert.ok(!body.includes('test-token'));assert.ok(!body.includes('never expose')); + const rows=JSON.parse(body).listings;assert.equal(validListings(rows).length,1);assert.match(listingInstruction(rows[0],false),/exchange buy/); + } finally {globalThis.fetch=original;} +}); diff --git a/website/web/exchange-data.js b/website/web/exchange-data.js new file mode 100644 index 00000000..e228ee89 --- /dev/null +++ b/website/web/exchange-data.js @@ -0,0 +1,47 @@ +export const categories = {ores:'Ores & Minerals',spice:'Spice & Rare',building:'Building Blocks',equipment:'Equipment',farming:'Food & Farming',misc:'Miscellaneous'}; +export const planets = {arrakis:'Arrakis',caladan:'Caladan',giedi_prime:'Giedi Prime',kaitain:'Kaitain',sigma_draconis_iv:'Sigma Draconis IV'}; +const samples = [ + ['spice_melange','spice','arrakis',1250,16], ['arrakis_water','spice','arrakis',180,4], + ['spice_harvest_shovel','equipment','arrakis',420,1], ['fremen_stillsuit','equipment','arrakis',950,1], + ['sandstone','building','arrakis',25,64], ['smooth_sandstone','building','arrakis',32,64], + ['glass','building','arrakis',12,32], ['cactus','farming','arrakis',8,32], + ['iron_ingot','ores','giedi_prime',90,64], ['ancient_debris','ores','giedi_prime',2800,4], + ['netherite_scrap','ores','giedi_prime',1800,2], ['coal','ores','giedi_prime',15,64], + ['blackstone','building','giedi_prime',20,64], ['iron_pickaxe','equipment','giedi_prime',320,1], + ['blast_furnace','misc','giedi_prime',240,3], ['gold_ingot','ores','kaitain',160,32], + ['diamond','ores','kaitain',650,12], ['quartz','ores','kaitain',35,48], + ['quartz_block','building','kaitain',140,32], ['golden_carrot','farming','kaitain',45,16], + ['enchanted_book','equipment','kaitain',850,1], ['lantern','misc','kaitain',35,16], + ['copper_ingot','ores','caladan',30,64], ['oak_log','building','caladan',18,64], + ['spruce_planks','building','caladan',12,64], ['wheat','farming','caladan',18,32], + ['cooked_cod','farming','caladan',28,24], ['potato','farming','caladan',7,64], + ['bow','equipment','caladan',125,1], ['fishing_rod','equipment','caladan',85,1], + ['redstone','ores','sigma_draconis_iv',75,48], ['lapis_lazuli','ores','sigma_draconis_iv',55,32], + ['emerald','ores','sigma_draconis_iv',220,16], ['observer','misc','sigma_draconis_iv',320,4], + ['piston','misc','sigma_draconis_iv',180,8], ['repeater','misc','sigma_draconis_iv',110,16], + ['tinted_glass','building','sigma_draconis_iv',65,32], ['ender_pearl','spice','sigma_draconis_iv',240,8], + ['paper','misc','caladan',8,64], ['shield','equipment','kaitain',210,1] +]; +export const demoListings = samples.map(([material,category,origin,price,quantity],i)=>({ + id:i+1, material, category, origin, price, quantity, + seller:({arrakis:'Sietch Supply',caladan:'Caladan Farms',giedi_prime:'Foundry Depot',kaitain:'Imperial Emporium',sigma_draconis_iv:'Ordos Research'})[origin]+' (demo)' +})); +export function validListings(rows) { + if(!Array.isArray(rows)) throw Error('Invalid market response'); + const seen=new Set(); + return rows.slice(0,500).filter(x=>{ + if(!x||!Number.isSafeInteger(x.id)||x.id<1||seen.has(x.id)||typeof x.material!=='string'||!x.material.trim() + ||x.material.length>80||typeof x.seller!=='string'||x.seller.length>48||!Object.hasOwn(categories,x.category) + ||!Object.hasOwn(planets,x.origin)||!Number.isFinite(x.price)||x.price<=0||!Number.isSafeInteger(x.quantity)||x.quantity<1) return false; + seen.add(x.id); return true; + }); +} +export function filterListings(rows,{search='',category='all',planet='all',sort='new'}={}) { + const term=search.trim().toLowerCase(); + return rows.filter(x=>(category==='all'||x.category===category)&&(planet==='all'||x.origin===planet) + &&(!term||[x.material.replaceAll('_',' '),x.material,x.seller,categories[x.category],planets[x.origin]].some(value=>value.toLowerCase().includes(term)))) + .sort((a,b)=>sort==='price'?a.price-b.price||b.id-a.id:sort==='quantity'?b.quantity-a.quantity||b.id-a.id:b.id-a.id); +} +export function listingInstruction(offer,demo) { + return demo?'DEMO · Illustrative offer · Not purchasable':'Buy in Minecraft: /exchange buy '+offer.id; +} diff --git a/website/web/exchange-market.css b/website/web/exchange-market.css index 91eab276..c06efe5b 100644 --- a/website/web/exchange-market.css +++ b/website/web/exchange-market.css @@ -69,3 +69,30 @@ .market-pages button:disabled{opacity:.35;cursor:not-allowed} @media(max-width:1150px){.planet-tiles{grid-template-columns:repeat(3,1fr)}.market-results{grid-template-columns:repeat(2,minmax(0,1fr))}.market-toolbar{grid-template-columns:repeat(2,1fr)}.market-toolbar input{grid-column:1/-1}} @media(max-width:680px){.choam-hero{min-height:340px;padding:55px 6%}.planet-tiles{grid-template-columns:repeat(2,1fr)}.market-layout{display:block}.market-side{margin-bottom:16px}.market-results{grid-template-columns:1fr}.market-toolbar{display:flex}.market-toolbar>*{flex:1 1 100%}} + +.category-links button[aria-pressed=true]{background:#203d34;border-left-color:#d5ab63;color:#f3cd86} +.choam button:focus-visible,.choam input:focus-visible,.choam select:focus-visible{outline:2px solid #f4d99c;outline-offset:4px} +.market-toolbar label.sr-only{position:absolute;display:block} +.market-card{display:flex;flex-direction:column;overflow-wrap:anywhere} +.market-item-art{height:108px;display:grid;place-items:center;background:radial-gradient(ellipse at center,#40514388,transparent 70%),linear-gradient(135deg,#203d34,#0b1716);border:1px solid #3a4a3d;margin:-1px -1px 14px;color:#d5ab63;font-family:Georgia,serif;font-size:54px} +.market-card[data-planet=caladan] .market-item-art{color:#90bfc9;background:radial-gradient(ellipse at center,#315b6888,transparent 70%),#10201f} +.market-card[data-planet=giedi_prime] .market-item-art{color:#df9b88;background:radial-gradient(ellipse at center,#773e3a88,transparent 70%),#10201f} +.market-card[data-planet=kaitain] .market-item-art{color:#eed99c} +.market-card[data-planet=sigma_draconis_iv] .market-item-art{color:#b5addb;background:radial-gradient(ellipse at center,#51466a88,transparent 70%),#10201f} +.market-card .market-card-category{text-transform:uppercase;letter-spacing:.1em;font-size:9px;color:#d5ab63} +.market-card h3{font-size:clamp(24px,2.2vw,30px);line-height:1.1;min-height:2.2em} +.market-card .market-unit{font-size:10px;margin-bottom:14px;color:#a9b7a7} +.market-card .market-seller{color:#e4d8be} +.market-card .market-origin{font-size:10px;text-transform:uppercase;letter-spacing:.08em;color:#aabca9} +.market-card .market-instruction{display:block;margin-top:auto;padding-top:14px;border-top:1px solid #3b4d40;line-height:1.6} +.market-heading{align-items:start}.demo-banner{max-width:310px;line-height:1.6;background:#10201f} +.market-empty{grid-column:1/-1;line-height:1.7}.market-results{align-items:stretch} +.market-toolbar{align-items:center}.market-toolbar>*{min-width:0} +.choam .planet-tiles{position:static;inset:auto;padding:0;background:transparent;border:0;align-items:stretch} +.planet-tiles button[data-planet=arrakis]{background-image:linear-gradient(0deg,#071917ee,#07191725),url('assets/arrakis.webp')} +.planet-tiles button[data-planet=caladan]{background-image:linear-gradient(0deg,#071917ee,#07191725),url('assets/caladan.webp')} +.planet-tiles button[data-planet=giedi_prime]{background-image:linear-gradient(0deg,#071917ee,#07191725),url('assets/giedi.webp')} +.planet-tiles button[data-planet=kaitain]{background-image:linear-gradient(0deg,#071917ee,#07191725),url('assets/kaitain.webp')} +.planet-tiles button[data-planet=sigma_draconis_iv]{background-image:linear-gradient(0deg,#071917ee,#07191725),url('assets/sigma.webp')} +.choam-hero .choam-desc{text-transform:none;letter-spacing:normal;color:#e7d9bf;font-size:14px} +@media(max-width:680px){.choam-hero h1{font-size:clamp(48px,13vw,72px)}.exchange-content{padding-inline:5%}.market-side{padding:20px}.category-links{grid-template-columns:repeat(2,minmax(0,1fr))}.category-links button{font-size:11px;padding:10px 8px}.market-help{margin-top:18px;padding-top:14px}.market-item-art{height:100px}.market-card h3{min-height:0}.market-pages{gap:8px;margin-inline:0;font-size:11px}.market-pages button{padding:10px}.planet-tiles button{font-size:10px;min-height:104px}} diff --git a/website/web/exchange-market.js b/website/web/exchange-market.js index 43e617d7..2d1cb0d9 100644 --- a/website/web/exchange-market.js +++ b/website/web/exchange-market.js @@ -1 +1,66 @@ -(()=>{'use strict';const $=id=>document.getElementById(id);const state={items:[],page:0,ready:false};const perPage=12;const demoListings=[{id:1,material:'spice_melange',category:'spice',origin:'arrakis',seller:'Fremen Trader',price:1250,quantity:16},{id:2,material:'iron_ingot',category:'ores',origin:'caladan',seller:'Atreides Supply',price:90,quantity:64},{id:3,material:'ancient_debris',category:'ores',origin:'giedi_prime',seller:'Harkonnen Mining',price:2800,quantity:4},{id:4,material:'diamond',category:'ores',origin:'kaitain',seller:'Imperial Merchant',price:650,quantity:12},{id:5,material:'redstone',category:'ores',origin:'sigma_draconis_iv',seller:'Ordos Exchange',price:75,quantity:48},{id:6,material:'sandstone',category:'building',origin:'arrakis',seller:'Desert Builder',price:25,quantity:64},{id:7,material:'wheat',category:'farming',origin:'caladan',seller:'Caladan Farms',price:18,quantity:32},{id:8,material:'netherite_scrap',category:'equipment',origin:'giedi_prime',seller:'Foundry Guild',price:1800,quantity:2}];let demoMode=false;const planets={arrakis:'Arrakis',giedi_prime:'Giedi Prime',caladan:'Caladan',kaitain:'Kaitain',sigma_draconis_iv:'Sigma Draconis IV'};function text(el,value){el.textContent=String(value)}function render(){const term=$('market-search').value.trim().toLowerCase(),cat=$('market-category').value,planet=$('market-planet').value,sort=$('market-sort').value;let items=state.items.filter(x=>(cat==='all'||x.category===cat)&&(planet==='all'||x.origin===planet)&&(!term||x.material.toLowerCase().includes(term)||x.seller.toLowerCase().includes(term)));if(sort==='price')items.sort((a,b)=>a.price-b.price);else if(sort==='quantity')items.sort((a,b)=>b.quantity-a.quantity);else items.sort((a,b)=>b.id-a.id);const pages=Math.max(1,Math.ceil(items.length/perPage));state.page=Math.max(0,Math.min(state.page,pages-1));text($('market-count'),items.length+' listings');text($('market-page'),'Page '+(state.page+1)+' of '+pages);$('market-prev').disabled=state.page===0;$('market-next').disabled=state.page>=pages-1;const root=$('market-results');root.replaceChildren();if(!items.length){const p=document.createElement('p');p.className='market-empty';text(p,state.ready?'No matching listings.':'Live listings are not connected yet.');root.append(p);return;}for(const offer of items.slice(state.page*perPage,(state.page+1)*perPage)){const card=document.createElement('article');card.className='market-card';card.dataset.planet=offer.origin;const heading=document.createElement('h3');text(heading,offer.material.replaceAll('_',' '));card.append(heading);for(const line of ['#'+offer.id+' · '+offer.category,offer.price.toLocaleString()+' Solaris each','Quantity: '+offer.quantity,'Seller: '+offer.seller,'Planet: '+(planets[offer.origin]||offer.origin)]){const p=document.createElement('p');text(p,line);if(line.includes('Solaris'))p.className='market-price';card.append(p);}const small=document.createElement('small');text(small,demoMode?'DEMO LISTING · illustrative item and price · not purchasable':'Buy in Minecraft: /exchange buy '+offer.id);card.append(small);root.append(card);}}async function load(){text($('market-status'),'Connecting to the Guild market…');try{const r=await fetch('/api/exchange/listings',{cache:'no-store'});if(!r.ok)throw Error('Market API unavailable ('+r.status+')');const data=await r.json();if(!Array.isArray(data.listings))throw Error('Invalid market response');state.items=data.listings.filter(x=>Number.isSafeInteger(x.id)&&x.id>0&&typeof x.material==='string'&&typeof x.category==='string'&&typeof x.origin==='string'&&typeof x.seller==='string'&&Number.isFinite(x.price)&&x.price>0&&Number.isInteger(x.quantity)&&x.quantity>0);state.ready=true;demoMode=false;text($('market-status'),'Live market · read-only · '+state.items.length+' recent listings');}catch(e){state.ready=true;demoMode=true;state.items=demoListings;text($('market-status'),'DEMO MODE · Sample listings only · Marketplace database not connected');}render();}for(const id of ['market-search','market-category','market-planet','market-sort'])$(id).addEventListener(id==='market-search'?'input':'change',()=>{state.page=0;render()});document.querySelectorAll('.planet-tiles button[data-planet]').forEach(button=>{button.addEventListener('click',()=>{const selected=$('market-planet');selected.value=selected.value===button.dataset.planet?'all':button.dataset.planet;document.querySelectorAll('.planet-tiles button[data-planet]').forEach(b=>b.setAttribute('aria-pressed',String(selected.value===b.dataset.planet)));state.page=0;render();});});$('market-planet').addEventListener('change',()=>document.querySelectorAll('.planet-tiles button[data-planet]').forEach(b=>b.setAttribute('aria-pressed',String($('market-planet').value===b.dataset.planet))));$('market-refresh').addEventListener('click',load);$('market-prev').addEventListener('click',()=>{state.page--;render()});$('market-next').addEventListener('click',()=>{state.page++;render()});load();})(); \ No newline at end of file +import {categories,planets,demoListings,validListings,filterListings,listingInstruction} from './exchange-data.js'; +const $=id=>document.getElementById(id); +const state={items:[],page:0,demo:true,loading:false}; +const perPage=12; +const categoryIcons={ores:'◆',spice:'✦',building:'▦',equipment:'⚒',farming:'❧',misc:'◎'}; +function element(tag,className,value) { + const el=document.createElement(tag); if(className) el.className=className; + if(value!==undefined) el.textContent=String(value); return el; +} +function render() { + const filters={search:$('market-search').value,category:$('market-category').value,planet:$('market-planet').value,sort:$('market-sort').value}; + const matches=filterListings(state.items,filters); + const pages=Math.max(1,Math.ceil(matches.length/perPage)); + state.page=Math.max(0,Math.min(state.page,pages-1)); + $('market-count').textContent=matches.length+' '+(state.demo?'demo offers':'live listings'); + $('market-page').textContent='Page '+(state.page+1)+' of '+pages; + $('market-prev').disabled=state.page===0; $('market-next').disabled=state.page>=pages-1; + $('market-mode').textContent=state.demo?'DEMONSTRATION MARKET':'LIVE MARKET · READ ONLY'; + $('market-mode-detail').textContent=state.demo?'Fictional sellers, items and prices. No purchases or payments.':'Verified listings from the connected game market. Trade inside Minecraft.'; + document.querySelectorAll('button[data-planet]').forEach(b=>b.setAttribute('aria-pressed',String(filters.planet===b.dataset.planet))); + document.querySelectorAll('button[data-category]').forEach(b=>b.setAttribute('aria-pressed',String(filters.category===b.dataset.category))); + const root=$('market-results'); root.replaceChildren(); + if(!matches.length) { + root.append(element('p','market-empty',state.items.length?'No matching offers. Try another filter or clear your search.':'The connected market has no listings yet. List your held item with /exchange sell .')); + return; + } + for(const offer of matches.slice(state.page*perPage,(state.page+1)*perPage)) { + const card=element('article','market-card'); card.dataset.planet=offer.origin; + const art=element('div','market-item-art'); art.setAttribute('aria-hidden','true'); + art.append(element('span','',categoryIcons[offer.category])); + card.append(art,element('p','market-card-category',categories[offer.category]),element('h3','',offer.material.replaceAll('_',' ')), + element('p','market-price',offer.price.toLocaleString(undefined,{maximumFractionDigits:2})+' Solaris'), + element('p','market-unit','per item · '+offer.quantity+' available'),element('p','market-seller',offer.seller), + element('p','market-origin',planets[offer.origin]),element('small','market-instruction',listingInstruction(offer,state.demo))); + root.append(card); + } +} +async function load() { + if(state.loading) return; + state.loading=true; $('market-refresh').disabled=true; + $('market-status').textContent='Checking for live market listings…'; + try { + const response=await fetch('/api/exchange/listings',{cache:'no-store',signal:AbortSignal.timeout(10000)}); + if(!response.ok) throw Error('Market unavailable'); + const data=await response.json(),items=validListings(data.listings); + if(data.listings.length&&!items.length) throw Error('Invalid listings'); + state.items=items; state.demo=false; + $('market-status').textContent='Connected to the game market · Read only · Updated '+new Date().toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'}); + } catch { + state.items=demoListings; state.demo=true; + $('market-status').textContent='Game market not connected — showing '+demoListings.length+' fictional demo offers. Refresh to check the connection.'; + } finally { + state.loading=false; state.page=0; $('market-refresh').disabled=false; render(); + } +} +for(const id of ['market-search','market-category','market-planet','market-sort']) { + $(id).addEventListener(id==='market-search'?'input':'change',()=>{state.page=0;render();}); +} +for(const kind of ['planet','category']) document.querySelectorAll('button[data-'+kind+']').forEach(button=>{ + button.addEventListener('click',()=>{$('market-'+kind).value=button.dataset[kind];state.page=0;render();}); +}); +$('market-refresh').addEventListener('click',load); +$('market-prev').addEventListener('click',()=>{state.page--;render();}); +$('market-next').addEventListener('click',()=>{state.page++;render();}); +// Render the demonstration immediately while the first connection check is in flight. +state.items=demoListings; render(); load(); diff --git a/website/web/exchange.html b/website/web/exchange.html index 8f3fd248..59cc66d7 100644 --- a/website/web/exchange.html +++ b/website/web/exchange.html @@ -1 +1 @@ -Interplanetary Exchange — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

CHOAM · COMMERCE ACROSS WORLDS

Interplanetary
Exchange.

Trade resources, technology and goods across the known worlds. Browse the Great Houses' marketplace.

THE SPICE MUST FLOW ✦ PROJECT DUNE

THE IMPERIAL COMMERCE NETWORK

Market Listings

DEMO MODE WHEN OFFLINESample listings are illustrative, not purchasable.

Connecting to the Guild market…

Page 1

The CHOAM exchange is read-only on the website. All trades take place in-game. Demo prices are not real offers.

\ No newline at end of file +Interplanetary Exchange — Project Dune
✦ PROJECT DUNEMINECRAFT REALMS

CHOAM · COMMERCE ACROSS WORLDS

Interplanetary
Exchange.

Trade resources, technology and goods across the known worlds. Browse the Great Houses' marketplace.

THE SPICE MUST FLOW ✦ PROJECT DUNE

THE IMPERIAL COMMERCE NETWORK

Market Listings

DEMONSTRATION MARKETFictional sellers, items and prices. No purchases or payments.

Checking the game market. Demo offers are shown until connected.

Page 1

The CHOAM exchange is read-only on the website. All trades take place in-game. Demo prices are not real offers.

\ No newline at end of file