web/DuneRealmsGUI/src/main/java/com/dunerealms/gui/ExchangeMenus.java

84 lines
22 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.dunerealms.gui;
import com.google.gson.*;
import java.util.*;
import java.util.function.*;
import java.math.BigDecimal;
import org.bukkit.*;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.event.inventory.*;
import org.bukkit.event.player.*;
import org.bukkit.inventory.*;
import org.bukkit.plugin.java.JavaPlugin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
/** Presentation only. Bank payments stay central; physical items use Core's checkpoint. */
final class ExchangeMenus implements Listener,AutoCloseable {
private final JavaPlugin plugin;private final HouseBridge bridge;private final Consumer<Player> back;private final Predicate<Player> artwork;
private final Map<UUID,UUID> pending=new HashMap<>();private final Set<UUID> delivering=new HashSet<>();
private final Map<UUID,Purchase> retries=new HashMap<>();
private record Draft(ItemStack item,int slot,int amount,long price){Draft quantity(int n){return new Draft(item,slot,n,price);}Draft price(long n){return new Draft(item,slot,amount,n);}}
private record Purchase(JsonObject row,int amount,UUID request){Purchase quantity(int n){return new Purchase(row,n,UUID.randomUUID());}}
private static final class Panel implements DuneMenuInventory {
final UUID owner,world;final GuiSession gate;final Map<Integer,Runnable> actions=new HashMap<>();final List<BedrockForms.Choice> choices=new ArrayList<>();final Inventory inventory;final String title;final boolean artwork;String description="Central bank · J.A.R.V.I.S. Exchange";
Panel(Player p,String title,boolean artwork,int screen){owner=p.getUniqueId();world=p.getWorld().getUID();gate=new GuiSession(owner);this.title=title;this.artwork=artwork;inventory=Bukkit.createInventory(this,54,artwork?Component.text(ExchangeArtwork.background(screen),NamedTextColor.WHITE).font(net.kyori.adventure.key.Key.key("dunerealms:exchange")):Component.text(title,NamedTextColor.GOLD));}
public Inventory getInventory(){return inventory;}
}
private final java.util.concurrent.ConcurrentMap<UUID,org.bukkit.conversations.Conversation> priceInputs=new java.util.concurrent.ConcurrentHashMap<>();
ExchangeMenus(JavaPlugin plugin,HouseBridge bridge,Consumer<Player> back,Predicate<Player> artwork){this.plugin=plugin;this.bridge=bridge;this.back=back;this.artwork=artwork;Bukkit.getPluginManager().registerEvents(this,plugin);Bukkit.getScheduler().runTaskTimer(plugin,()->{for(Player p:Bukkit.getOnlinePlayers())deliver(p,false);},80L,1200L);}
void open(Player p){deliver(p,false);var retry=retries.get(p.getUniqueId());if(retry!=null){purchase(p,retry);return;}list(p,false,0);}
void openKits(Player p){deliver(p,false);kits(p,0);}
private static String money(long value){return BigDecimal.valueOf(value,2).toPlainString()+" DM";}
static long price(String text){return ExchangePrice.parse(text);}
private static ItemStack icon(Material material,String title,String... lore){var item=new ItemStack(material);var meta=item.getItemMeta();meta.displayName(Component.text(title,NamedTextColor.GOLD));meta.lore(Arrays.stream(lore).map(s->Component.text(s,NamedTextColor.GRAY)).toList());item.setItemMeta(meta);return item;}
private Panel panel(Player p,String title){int screen=title.endsWith("Your listings")?1:title.endsWith("Add item")?2:title.endsWith("Purchase details")?3:title.endsWith("Withdraw listing")?4:0;var s=new Panel(p,title,artwork.test(p)&&!BedrockForms.isBedrock(p),screen);if(!s.artwork){var pane=icon(Material.GREEN_STAINED_GLASS_PANE," ");for(int i=0;i<54;i++)s.inventory.setItem(i,pane);}return s;}
private void button(Panel s,int slot,Material material,String title,String description,Runnable action){s.inventory.setItem(slot,icon(material,title,description));s.actions.put(slot,action);s.choices.add(new BedrockForms.Choice(title,description,action));}
private void show(Player p,Panel s){if(BedrockForms.isBedrock(p)){s.gate.expire();BedrockForms.show(plugin,p,s.title,s.description,s.choices);}else{if(MCGUIMenus.show(p,s.title,s.description,s.inventory,s.actions,s.gate))return;p.openInventory(s.inventory);Bukkit.getScheduler().runTaskLater(plugin,s.gate::expire,2400L);}}
private void request(Player p,JsonObject input,Consumer<JsonObject> success,Consumer<String> failure){
UUID id=p.getUniqueId(),world=p.getWorld().getUID();if(pending.containsKey(id)){p.sendMessage("J.A.R.V.I.S. is processing your Exchange action.");return;}UUID token=UUID.randomUUID();pending.put(id,token);p.closeInventory();
Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject result=null;String error=null;try{result=bridge.exchange(id,input);}catch(Exception e){error=e.getMessage();}var response=result;String message=error;if(!plugin.isEnabled())return;Bukkit.getScheduler().runTask(plugin,()->{if(!token.equals(pending.get(id)))return;pending.remove(id);if(!p.isOnline()||!world.equals(p.getWorld().getUID()))return;if(response==null){failure.accept(message==null?"The Exchange is temporarily unavailable.":message);return;}if(response.has("rejectedStatus")){if(Set.of("buy","buy_kit").contains(input.get("action").getAsString()))retries.remove(id);failure.accept(response.has("message")?response.get("message").getAsString():"The Exchange rejected this action.");return;}success.accept(response);});});
}
private void request(Player p,JsonObject input,Consumer<JsonObject> done){request(p,input,done,p::sendMessage);}
private JsonObject action(String action){var q=new JsonObject();q.addProperty("action",action);return q;}
private void list(Player p,boolean mine,int page){var q=action("read");q.addProperty("mine",mine);q.addProperty("page",page);request(p,q,data->{var s=panel(p,mine?"Exchange · Your listings":"Exchange · Buy");button(s,1,Material.EMERALD,"Buy","Browse all available items",()->list(p,false,0));button(s,4,Material.NETHERITE_CHESTPLATE,"Kits","Published organisation stillsuit kits",()->kits(p,0));button(s,7,Material.CHEST,"Sell","Your listings and add held item",()->list(p,true,0));int index=0;for(var value:data.getAsJsonArray("listings")){var row=value.getAsJsonObject();int slot=10+(index/6)*9+index%6;index++;try{var item=bridge.exchangeIcon(row);var meta=item.getItemMeta();List<Component> lore=new ArrayList<>(meta.hasLore()?meta.lore():List.of());lore.add(Component.text(" "));lore.add(Component.text("Seller: "+row.get("seller").getAsString(),NamedTextColor.GRAY));lore.add(Component.text(row.get("quantity").getAsInt()+" available · "+money(row.get("priceMinor").getAsLong())+" each",NamedTextColor.GOLD));meta.lore(lore);item.setItemMeta(meta);s.inventory.setItem(slot,item);Runnable pick=()->{if(row.get("sellerUuid").getAsString().equals(p.getUniqueId().toString()))withdraw(p,row);else purchase(p,new Purchase(row,1,UUID.randomUUID()));};s.actions.put(slot,pick);s.choices.add(new BedrockForms.Choice(row.get("title").getAsString(),money(row.get("priceMinor").getAsLong())+" · "+row.get("quantity").getAsInt()+" available",pick));}catch(Exception unsupported){s.inventory.setItem(slot,icon(Material.BARRIER,"Unsupported item","This version cannot display the stored item."));}}
if(index==0)s.inventory.setItem(22,icon(Material.PAPER,"No listings",mine?"Hold an item and choose Add held item.":"Check again after players publish goods."));
if(page>0)button(s,45,Material.ARROW,"Previous","Page "+page,()->list(p,mine,page-1));if(data.get("hasNext").getAsBoolean())button(s,53,Material.ARROW,"Next","More listings",()->list(p,mine,page+1));button(s,48,Material.BOOK,"Imperial Codex","Return to your services",()->back.accept(p));button(s,49,Material.HOPPER,"Add held item","List an item from your main hand",()->draft(p));button(s,50,Material.CHEST_MINECART,"Collect purchases","Deliver paid items waiting for inventory space",()->{deliver(p,true);list(p,mine,page);});show(p,s);
});}
private void draft(Player p){var item=p.getInventory().getItemInMainHand();if(item.isEmpty()){p.sendMessage("Hold the item you want to sell first.");return;}sell(p,new Draft(item.clone(),p.getInventory().getHeldItemSlot(),Math.min(64,item.getAmount()),100));}
private void sell(Player p,Draft draft){var s=panel(p,"Exchange · Add item");s.description=draft.item.getType().name()+" · "+draft.amount+" items\n"+money(draft.price)+" per item\nTotal: "+money(draft.price*draft.amount);s.inventory.setItem(13,draft.item.clone());quantityPresets(s,Math.min(64,draft.item.getAmount()),amount->sell(p,draft.quantity(amount)));button(s,30,Material.RED_DYE,"− Quantity","Sell "+draft.amount+" items",()->sell(p,draft.quantity(Math.max(1,draft.amount-1))));button(s,31,Material.PAPER,"Quantity: "+draft.amount,"Maximum "+Math.min(64,draft.item.getAmount()),()->sell(p,draft));button(s,32,Material.LIME_DYE,"+ Quantity","Add one item",()->sell(p,draft.quantity(Math.min(Math.min(64,draft.item.getAmount()),draft.amount+1))));button(s,40,Material.GOLD_INGOT,"Price: "+money(draft.price),"Price per item · total "+money(draft.price*draft.amount),()->editPrice(p,draft));button(s,45,Material.ARROW,"Back","Return to your listings",()->list(p,true,0));button(s,49,Material.EMERALD,"Publish listing","Move "+draft.amount+" items into the Exchange",()->{UUID id=UUID.randomUUID();var q=action("prepare_sale");q.addProperty("requestId",id.toString());q.addProperty("amount",draft.amount);q.addProperty("priceMinor",draft.price);request(p,q,permit->{try{bridge.exchangePublish(p,permit,id,draft.item,draft.slot,draft.amount,draft.price);p.sendMessage("Listing published. Items are held by the Exchange until sold or withdrawn.");list(p,true,0);}catch(Exception e){p.sendMessage(e.getMessage()==null?"The listing was not confirmed.":e.getMessage());}});});show(p,s);}
private void editPrice(Player p,Draft draft){
var s=panel(p,"Exchange · Price");s.description=money(draft.price)+" per item · "+draft.amount+" items\nTotal: "+money(draft.price*draft.amount);s.inventory.setItem(13,icon(Material.GOLD_INGOT,"Price: "+money(draft.price),"Per item · total "+money(draft.price*draft.amount)));
long[] steps={1,100,1000,10000};for(int i=0;i<steps.length;i++){long step=steps[i];button(s,27+i,Material.RED_DYE,"− "+money(step),"Decrease the price per item",()->editPrice(p,draft.price(Math.max(1,draft.price-step))));button(s,32+i,Material.LIME_DYE,"+ "+money(step),"Increase the price per item",()->editPrice(p,draft.price(Math.min(100000000,draft.price+step))));}
button(s,45,Material.ARROW,"Back to listing","Review the current price before publishing",()->sell(p,draft));button(s,49,Material.EMERALD,"Use price: "+money(draft.price),"Review the listing before publishing",()->sell(p,draft));button(s,53,Material.NAME_TAG,"Type exact price","Optional private text entry",()->typePrice(p,draft));show(p,s);
}
private void quantityPresets(Panel s,int available,IntConsumer choose){for(int i=0;i<3;i++){int amount=new int[]{16,32,64}[i];button(s,21+i,Material.CHEST,String.valueOf(amount),"Set quantity · maximum "+available,()->choose.accept(Math.min(amount,available)));}}
private void typePrice(Player p,Draft draft){
if(BedrockForms.isBedrock(p)){BedrockForms.input(plugin,p,"Listing price","Dunemarks per item",BigDecimal.valueOf(draft.price,2).toPlainString(),text->{try{sell(p,draft.price(price(text.trim())));}catch(IllegalArgumentException e){p.sendMessage(e.getMessage());sell(p,draft);}});return;}
if(p.isConversing()){p.sendMessage("Finish your current text entry first, or type cancel.");return;}
UUID owner=p.getUniqueId(),world=p.getWorld().getUID();p.closeInventory();
var prompt=new org.bukkit.conversations.ValidatingPrompt(){
public String getPromptText(org.bukkit.conversations.ConversationContext context){return "Type the price per item in chat, for example 1.00 DM (enter 1.00). Type cancel to return. Your price is private.";}
protected boolean isInputValid(org.bukkit.conversations.ConversationContext context,String input){try{price(input.trim());return true;}catch(IllegalArgumentException invalid){return false;}}
protected String getFailedValidationText(org.bukkit.conversations.ConversationContext context,String input){return "Enter a price from 0.01 to 1000000.00, such as 1.00, or type cancel.";}
protected org.bukkit.conversations.Prompt acceptValidatedInput(org.bukkit.conversations.ConversationContext context,String input){context.setSessionData("priceMinor",price(input.trim()));return org.bukkit.conversations.Prompt.END_OF_CONVERSATION;}
};
var conversation=new org.bukkit.conversations.ConversationFactory(plugin).withModality(true).withLocalEcho(false).withTimeout(120).withEscapeSequence("cancel").withFirstPrompt(prompt).addConversationAbandonedListener(event->{
priceInputs.computeIfPresent(owner,(id,current)->current.getContext()==event.getContext()?null:current);
Object value=event.getContext().getSessionData("priceMinor");if(!plugin.isEnabled())return;
Bukkit.getScheduler().runTask(plugin,()->{if(!p.isOnline()||!world.equals(p.getWorld().getUID()))return;if(event.gracefulExit()&&value instanceof Long amount){sell(p,draft.price(amount));}else{p.sendMessage("Price entry cancelled. Your listing has not been published.");sell(p,draft);}});
}).buildConversation(p);
priceInputs.put(owner,conversation);conversation.begin();
}
private void purchase(Player p,Purchase purchase){if(purchase.row.has("kitsetId")){kitPurchase(p,purchase);return;}var row=purchase.row;var s=panel(p,"Exchange · Purchase details");s.description=row.get("title").getAsString()+"\nSeller: "+row.get("seller").getAsString()+"\nQuantity: "+purchase.amount+" · Total: "+money(row.get("priceMinor").getAsLong()*purchase.amount);try{s.inventory.setItem(13,bridge.exchangeIcon(row));}catch(Exception bad){p.sendMessage("This item cannot be delivered by your current version.");return;}quantityPresets(s,Math.min(64,row.get("quantity").getAsInt()),amount->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(amount)));button(s,30,Material.RED_DYE,"− Quantity","Buy "+purchase.amount,()->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(Math.max(1,purchase.amount-1))));button(s,31,Material.PAPER,"Quantity: "+purchase.amount,money(row.get("priceMinor").getAsLong())+" per item",()->purchase(p,purchase));button(s,32,Material.LIME_DYE,"+ Quantity","Maximum "+Math.min(64,row.get("quantity").getAsInt()),()->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(Math.min(Math.min(64,row.get("quantity").getAsInt()),purchase.amount+1))));button(s,45,Material.ARROW,"Back","Return to the Exchange",()->{if(retries.containsKey(p.getUniqueId())){p.sendMessage("Retry the previous purchase first.");purchase(p,purchase);}else list(p,false,0);});button(s,49,Material.EMERALD,(retries.containsKey(p.getUniqueId())?"Retry purchase · ":"Buy · ")+money(row.get("priceMinor").getAsLong()*purchase.amount),"Pay from your central personal bank account",()->{retries.put(p.getUniqueId(),purchase);var q=action("buy");q.addProperty("requestId",purchase.request.toString());q.addProperty("listingId",row.get("id").getAsString());q.addProperty("amount",purchase.amount);q.addProperty("priceMinor",row.get("priceMinor").getAsLong());q.addProperty("confirmed",true);request(p,q,receipt->{retries.remove(p.getUniqueId());p.sendMessage("Purchase confirmed: "+money(receipt.get("totalMinor").getAsLong())+". Your items are ready for delivery.");if(receipt.has("rebateMinor")&&receipt.get("rebateMinor").getAsLong()>0)p.sendMessage("Ordos trade incentive credited: "+money(receipt.get("rebateMinor").getAsLong())+".");deliver(p,true);list(p,false,0);},error->{p.sendMessage(error+" Retry with the same purchase reference.");purchase(p,purchase);});});show(p,s);}
private void kits(Player p,int page){var q=action("read_kits");q.addProperty("page",page);request(p,q,data->{var s=panel(p,"Exchange · Kits");button(s,1,Material.EMERALD,"Buy items","Browse loose goods",()->list(p,false,0));button(s,4,Material.NETHERITE_CHESTPLATE,"Kits","Published organisation designs",()->kits(p,0));button(s,7,Material.CHEST,"Sell","Your listings",()->list(p,true,0));int index=0;for(var value:data.getAsJsonArray("listings")){var row=value.getAsJsonObject();int slot=10+(index/6)*9+index%6;index++;String title=row.get("title").getAsString(),description=row.get("seller").getAsString()+" · "+row.get("items").getAsInt()+" items · "+money(row.get("priceMinor").getAsLong());if(row.get("purchaseAvailable").getAsBoolean())button(s,slot,Material.NETHERITE_CHESTPLATE,title,description,()->kitPurchase(p,new Purchase(row.deepCopy(),1,UUID.randomUUID())));else{s.inventory.setItem(slot,icon(Material.GRAY_DYE,title,description,"Organisation banking is unavailable"));s.description+="\n"+title+" · unavailable";}}if(page>0)button(s,45,Material.ARROW,"Previous","Previous kits",()->kits(p,page-1));button(s,49,Material.ARROW,"Back","Imperial Codex",()->back.accept(p));if(data.get("hasNext").getAsBoolean())button(s,53,Material.ARROW,"Next","More kits",()->kits(p,page+1));show(p,s);});}
private void kitPurchase(Player p,Purchase purchase){var row=purchase.row;var s=panel(p,"Exchange · Purchase details");s.description=row.get("title").getAsString()+"\nOrganisation: "+row.get("seller").getAsString()+"\n"+row.get("items").getAsInt()+" items · "+money(row.get("priceMinor").getAsLong());s.inventory.setItem(13,icon(Material.NETHERITE_CHESTPLATE,row.get("title").getAsString(),row.get("seller").getAsString(),row.get("items").getAsInt()+" items"));button(s,45,Material.ARROW,"Back","Kit catalogue",()->{if(retries.containsKey(p.getUniqueId())){p.sendMessage("Resolve the previous purchase with the same reference first.");kitPurchase(p,purchase);}else kits(p,0);});button(s,49,Material.EMERALD,(retries.containsKey(p.getUniqueId())?"Retry kit · ":"Buy kit · ")+money(row.get("priceMinor").getAsLong()),"Pay personally; proceeds go to the organisation",()->{retries.put(p.getUniqueId(),purchase);var q=action("buy_kit");q.addProperty("requestId",purchase.request.toString());q.addProperty("kitsetId",row.get("kitsetId").getAsString());q.add("listingVersion",row.get("listingVersion"));q.add("priceMinor",row.get("priceMinor"));q.addProperty("confirmed",true);request(p,q,receipt->{retries.remove(p.getUniqueId());p.sendMessage("Kit purchased: "+money(receipt.get("totalMinor").getAsLong())+". Delivery follows automatically; make room for the complete kit.");try{bridge.refreshKits(p);}catch(Exception unavailable){p.sendMessage("Your kit remains owed until the next inventory sync.");}kits(p,0);},error->{p.sendMessage(error+" Retry this confirmation with the same reference.");kitPurchase(p,purchase);});});show(p,s);}
private void withdraw(Player p,JsonObject row){var s=panel(p,"Exchange · Withdraw listing");try{s.inventory.setItem(13,bridge.exchangeIcon(row));}catch(Exception bad){p.sendMessage("This stored item cannot be decoded.");return;}button(s,45,Material.ARROW,"Back","Your listings",()->list(p,true,0));button(s,49,Material.CHEST,"Withdraw "+row.get("quantity").getAsInt()+" items","Return all unsold stock to your inventory",()->{UUID id=UUID.randomUUID();var q=action("prepare_cancel");q.addProperty("requestId",id.toString());request(p,q,permit->{try{int quantity=bridge.exchangeCancel(p,permit,id,Long.parseLong(row.get("id").getAsString()));p.sendMessage("Listing withdrawn. Returned "+quantity+" items.");list(p,true,0);}catch(Exception e){p.sendMessage(e.getMessage()==null?"The listing was not withdrawn.":e.getMessage());}});});show(p,s);}
private void deliver(Player p,boolean explain){if(!p.isOnline()||!delivering.add(p.getUniqueId()))return;UUID id=p.getUniqueId();var q=action("pending");Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject response=null;try{response=bridge.exchange(id,q);}catch(Exception ignored){}var data=response;if(!plugin.isEnabled())return;Bukkit.getScheduler().runTask(plugin,()->{delivering.remove(id);if(!p.isOnline())return;if(data==null||!data.has("pending")){if(explain)p.sendMessage("Paid deliveries remain queued. Reopen the Exchange to try again.");return;}if(data.getAsJsonArray("pending").isEmpty()){if(explain)p.sendMessage("No paid items are waiting for delivery.");return;}try{int count=bridge.exchangeDeliver(p);if(explain||count>0)p.sendMessage(count>0?"J.A.R.V.I.S. delivered "+count+" purchased items.":"Make inventory space. Your paid items remain queued.");}catch(Exception unavailable){if(explain)p.sendMessage("Paid items remain queued until your shared inventory is ready.");}});});}
@EventHandler public void join(PlayerJoinEvent e){Bukkit.getScheduler().runTaskLater(plugin,()->deliver(e.getPlayer(),false),60L);}
@EventHandler(priority=EventPriority.HIGHEST) public void click(InventoryClickEvent e){var holder=e.getView().getTopInventory().getHolder();if(!(holder instanceof Panel s))return;e.setCancelled(true);if(!(e.getWhoClicked() instanceof Player p)||!Set.of(ClickType.LEFT,ClickType.RIGHT).contains(e.getClick())||!s.owner.equals(p.getUniqueId())||!s.world.equals(p.getWorld().getUID())||!s.actions.containsKey(e.getRawSlot())||!s.gate.claim(p.getUniqueId()))return;Bukkit.getScheduler().runTask(plugin,s.actions.get(e.getRawSlot()));}
@EventHandler(priority=EventPriority.HIGHEST) public void drag(InventoryDragEvent e){if(e.getView().getTopInventory().getHolder() instanceof Panel)e.setCancelled(true);}
@EventHandler public void changeWorld(PlayerChangedWorldEvent e){var conversation=priceInputs.remove(e.getPlayer().getUniqueId());if(conversation!=null)conversation.abandon();}
@EventHandler public void quit(PlayerQuitEvent e){var conversation=priceInputs.remove(e.getPlayer().getUniqueId());if(conversation!=null)conversation.abandon();pending.remove(e.getPlayer().getUniqueId());delivering.remove(e.getPlayer().getUniqueId());}
@Override public void close(){for(var conversation:List.copyOf(priceInputs.values()))conversation.abandon();priceInputs.clear();pending.clear();delivering.clear();retries.clear();for(Player p:Bukkit.getOnlinePlayers())if(p.getOpenInventory().getTopInventory().getHolder() instanceof Panel)p.closeInventory();}
}