diff --git a/IngameShopSpigot/pom.xml b/IngameShopSpigot/pom.xml index 34a2318..508d93f 100644 --- a/IngameShopSpigot/pom.xml +++ b/IngameShopSpigot/pom.xml @@ -6,7 +6,7 @@ de.mviper IngameShopSpigot - 1.2 + 1.3 jar IngameShopSpigot @@ -35,6 +35,16 @@ 1.7 provided + + + com.intellectualsites.plotsquared + plotsquared-core + 7.6.0 + provided + + ** + + diff --git a/IngameShopSpigot/src/main/java/de/mviper/spigot/IngameShopSpigot.java b/IngameShopSpigot/src/main/java/de/mviper/spigot/IngameShopSpigot.java index b762987..beb6e6f 100644 --- a/IngameShopSpigot/src/main/java/de/mviper/spigot/IngameShopSpigot.java +++ b/IngameShopSpigot/src/main/java/de/mviper/spigot/IngameShopSpigot.java @@ -19,6 +19,7 @@ import org.bukkit.inventory.AnvilInventory; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.boss.BarColor; import org.bukkit.boss.BarStyle; @@ -113,6 +114,28 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { private Map plotRankDefaults = new HashMap<>(); private static final String GUI_FLYCODES = ChatColor.GOLD + "✈ Deine Fly-Gutscheine"; + private static final String GUI_ORDERS = ChatColor.DARK_GREEN + "🧾 Deine Kaufbelege"; + private static final String GUI_ABOS = ChatColor.DARK_AQUA + "⚙ Deine Abonnements"; + private static final String GUI_ABO_CONFIRM = ChatColor.RED + "Abo wirklich kündigen?"; + private static final String GUI_ABO_SHOP = ChatColor.DARK_GREEN + "🛒 Abo abschließen"; + private final Map> aboOffers = new HashMap<>(); + private static final int[] ABO_ITEM_SLOTS = {19, 20, 21, 22, 23, 24, 25}; + private final Map aboGuiData = new HashMap<>(); + private final Map aboPending = new HashMap<>(); + + private static class AboGuiData { + FlyAboManager.AboEntry fly; + PlotSlotManager.PlotAboEntry plot; + List items = new ArrayList<>(); + int flyUsed; + } + + private static class AboAction { + String kind, mode, label; // kind: fly|plot|item mode: cancel|reactivate + int itemId; + } + private final Map ordersPage = new HashMap<>(); + private final Map> ordersCache = new HashMap<>(); private final Map flyCodesPage = new HashMap<>(); private final Map> flyCodesCache = new HashMap<>(); private final Map pendingTransferAnvil = new HashMap<>(); @@ -194,6 +217,7 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { flyAboManager.startDailyResetChecker(); plotSlotManager = new PlotSlotManager(this, flyCodeManager); plotSlotManager.startBillingChecker(); + plotSlotManager.startMaintenance(); int intervalSeconds = getConfig().getInt("check-interval", 10); long pollInterval = intervalSeconds * 20L; @@ -936,6 +960,38 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { return; } + // ── Abo-GUI ─────────────────────────────────────────────────────── + if (GUI_ABOS.equals(title) || GUI_ABO_CONFIRM.equals(title) || GUI_ABO_SHOP.equals(title)) { + event.setCancelled(true); + if (!(event.getWhoClicked() instanceof Player)) return; + if (event.getClickedInventory() == null + || event.getClickedInventory() != event.getView().getTopInventory()) return; + Player p = (Player) event.getWhoClicked(); + if (GUI_ABOS.equals(title)) handleAboGuiClick(p, event.getRawSlot()); + else if (GUI_ABO_SHOP.equals(title)) handleAboShopClick(p, event.getRawSlot()); + else handleAboConfirmClick(p, event.getRawSlot()); + return; + } + + // ── Kaufbelege GUI ──────────────────────────────────────────────── + if (GUI_ORDERS.equals(title)) { + event.setCancelled(true); + if (!(event.getWhoClicked() instanceof Player)) return; + Player p = (Player) event.getWhoClicked(); + int slot = event.getRawSlot(); + List list = ordersCache.get(p.getUniqueId()); + if (list == null) return; + int page = ordersPage.getOrDefault(p.getUniqueId(), 0); + int total = Math.max(1, (int) Math.ceil(list.size() / 45.0)); + if (slot == 45 && page > 0) { openOrdersGUI(p, list, page - 1); return; } + if (slot == 53 && page < total - 1) { openOrdersGUI(p, list, page + 1); return; } + if (slot >= 0 && slot < 45) { + int idx = page * 45 + slot; + if (idx < list.size()) openReceiptBook(p, list.get(idx)); + } + return; + } + // ── Sell GUI ────────────────────────────────────────────────────── if (handleSellClick(event)) return; @@ -1221,7 +1277,18 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { return; } econ.withdrawPlayer(player, data.price); - player.sendMessage(ChatColor.GREEN + "💰 " + data.price + " " + currency + " abgezogen."); + // Kaufbeleg im Chat + String beleg = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm").format(new java.util.Date()); + player.sendMessage(""); + player.sendMessage(ChatColor.DARK_GREEN + "🧾 ════════ " + ChatColor.GREEN + "" + ChatColor.BOLD + + "KAUFBELEG #" + orderId + ChatColor.RESET + ChatColor.DARK_GREEN + " ════════"); + player.sendMessage(ChatColor.GRAY + " Datum: " + ChatColor.WHITE + beleg); + player.sendMessage(ChatColor.GRAY + " Artikel: " + ChatColor.AQUA + data.itemTitle); + player.sendMessage(ChatColor.GRAY + " Betrag: " + ChatColor.YELLOW + fmtPrice(data.price) + + ChatColor.GRAY + " abgezogen"); + player.sendMessage(ChatColor.GRAY + " Alle Belege: " + ChatColor.WHITE + "/belege"); + player.sendMessage(ChatColor.DARK_GREEN + "═══════════════════════════════"); + player.sendMessage(""); } // Einnahmen an Empfänger-Account gutschreiben (nicht bei Gift-Lieferung – bereits bei A gebucht) @@ -1619,65 +1686,34 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { // BEFEHLE // =========================================================== - /** /orders */ + /** /orders (/belege) – öffnet das Kaufbeleg-GUI */ private class OrdersCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage("Nur für Spieler."); return true; } Player p = (Player) sender; - p.sendMessage(ChatColor.GOLD + "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"); - p.sendMessage(ChatColor.YELLOW + "📦 Deine letzten Bestellungen:"); - p.sendMessage(ChatColor.GOLD + "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"); + p.sendMessage(ChatColor.GRAY + "🧾 Lade deine Kaufbelege …"); new BukkitRunnable() { @Override public void run() { try { HttpURLConnection conn = openAuthConnection( - wpBase + "/orders_history?player=" + p.getName(), "GET"); + wpBase + "/orders_history?limit=200&player=" + + java.net.URLEncoder.encode(p.getName(), "UTF-8"), "GET"); int code = conn.getResponseCode(); if (code == 200) { - String body = readResponse(conn); - JsonObject json = JsonParser.parseString(body).getAsJsonObject(); + JsonObject json = JsonParser.parseString(readResponse(conn)).getAsJsonObject(); JsonArray orders = json.getAsJsonArray("orders"); + List list = new ArrayList<>(); + if (orders != null) + for (JsonElement el : orders) list.add(el.getAsJsonObject()); Bukkit.getScheduler().runTask(IngameShopSpigot.this, () -> { - if (orders == null || orders.size() == 0) { - p.sendMessage(ChatColor.GRAY + "Noch keine Bestellungen vorhanden."); - } else { - for (int i = 0; i < Math.min(orders.size(), 10); i++) { - JsonObject o = orders.get(i).getAsJsonObject(); - String t = o.get("item_title").getAsString(); - double pr = o.get("price").getAsDouble(); - String status = o.get("status").getAsString(); - String date = o.has("created_at") - ? o.get("created_at").getAsString().substring(0, 10) : "?"; - String sc; - switch (status) { - case "completed": sc = ChatColor.GREEN + "✔ Geliefert"; break; - case "cancelled": sc = ChatColor.RED + "✘ Storniert"; break; - case "processing": sc = ChatColor.AQUA + "⟳ In Arbeit"; break; - default: sc = ChatColor.YELLOW + "⌛ Ausstehend"; break; - } - String display = t.length() > 35 - ? t.substring(0, 32) + "…" : t; - p.sendMessage( - ChatColor.WHITE + " #" + o.get("id").getAsInt() + " " - + ChatColor.AQUA + display - + ChatColor.GRAY + " | " - + ChatColor.YELLOW + pr + " " + currency - + ChatColor.GRAY + " | " + sc - + ChatColor.GRAY + " (" + date + ")"); - } - } - p.sendMessage(ChatColor.GOLD + "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"); + if (list.isEmpty()) p.sendMessage(ChatColor.GRAY + "Noch keine Belege vorhanden."); + else openOrdersGUI(p, list, 0); }); - } else if (code == 404) { - Bukkit.getScheduler().runTask(IngameShopSpigot.this, () -> - p.sendMessage(ChatColor.GRAY - + "Bestellhistorie nicht verfügbar (WP-Plugin zu alt?).")); } else { Bukkit.getScheduler().runTask(IngameShopSpigot.this, () -> - p.sendMessage(ChatColor.RED - + "Fehler beim Laden (HTTP " + code + ").")); + p.sendMessage(ChatColor.RED + "Belege nicht verfügbar (HTTP " + code + ").")); } } catch (Exception e) { getLogger().log(Level.WARNING, "/orders Fehler", e); @@ -1690,6 +1726,497 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { } } + // =========================================================== + // ABO-VERWALTUNG (GUI) + // =========================================================== + + private ItemStack aboItem(Material mat, String name, List lore) { + ItemStack it = new ItemStack(mat); + ItemMeta m = it.getItemMeta(); + m.setDisplayName(name); + m.setLore(lore); + it.setItemMeta(m); + return it; + } + + /** "cancel" | "reactivate" | "none" */ + private String aboMode(boolean cancelled, String reason) { + if (!cancelled) return "cancel"; + return "payment_failed".equals(reason) ? "none" : "reactivate"; + } + + private String aboActionLine(String mode) { + switch (mode) { + case "cancel": return ChatColor.YELLOW + "▶ Klick: " + ChatColor.RED + "Kündigen"; + case "reactivate": return ChatColor.YELLOW + "▶ Klick: " + ChatColor.GREEN + "Kündigung zurücknehmen (verlängern)"; + default: return ChatColor.GRAY + "Zahlung fehlgeschlagen – neu im Shop abschließen"; + } + } + + private void openAboGUI(Player p) { + p.sendMessage(ChatColor.GRAY + "⚙ Lade deine Abos …"); + new BukkitRunnable() { + @Override public void run() { + try { + AboGuiData d = new AboGuiData(); + d.fly = flyAboManager.getActiveAbo(p.getName()); + d.plot = plotSlotManager.getActiveAbo(p.getName()); + d.flyUsed = flyAboManager.getUsedTodaySec(p.getName()); + d.items = fetchItemAbos(p.getName()); + Bukkit.getScheduler().runTask(IngameShopSpigot.this, () -> { + try { + showAboGUI(p, d); + } catch (Throwable t) { + getLogger().log(Level.SEVERE, "[AboGUI] Anzeige fehlgeschlagen", t); + p.sendMessage(ChatColor.RED + "✗ Abo-GUI konnte nicht angezeigt werden: " + + t.getClass().getSimpleName() + " (Details im Server-Log). Nutze /abo text."); + } + }); + } catch (Throwable t) { + getLogger().log(Level.SEVERE, "[AboGUI] Laden fehlgeschlagen", t); + Bukkit.getScheduler().runTask(IngameShopSpigot.this, () -> + p.sendMessage(ChatColor.RED + "✗ Abos konnten nicht geladen werden: " + + t.getClass().getSimpleName() + " (Details im Server-Log). Nutze /abo text.")); + } + } + }.runTaskAsynchronously(this); + } + + private void showAboGUI(Player p, AboGuiData d) { + aboGuiData.put(p.getUniqueId(), d); + Inventory gui = Bukkit.createInventory(null, 36, GUI_ABOS); + + ItemStack pane = aboItem(Material.BLACK_STAINED_GLASS_PANE, " ", new ArrayList<>()); + for (int i = 0; i < 36; i++) gui.setItem(i, pane); + + // ── Fly-Abo (Slot 10) ── + if (d.fly == null) { + gui.setItem(10, aboItem(Material.GRAY_DYE, ChatColor.GRAY + "✈ Kein Fly-Abo", + Arrays.asList(ChatColor.GRAY + "Im Shop erhältlich:", ChatColor.AQUA + "viper-network.de"))); + } else { + FlyAboManager.AboEntry a = d.fly; + String mode = aboMode(a.cancelled, a.cancellationReason); + List lore = new ArrayList<>(Arrays.asList( + ChatColor.GRAY + "Paket: " + ChatColor.WHITE + a.label, + ChatColor.GRAY + "Preis: " + ChatColor.WHITE + a.monthlyPrice + " " + currency + " / Monat", + ChatColor.GRAY + "Status: " + (a.cancelled ? ChatColor.RED + "⚠ Gekündigt" : ChatColor.GREEN + "✔ Aktiv"), + ChatColor.GRAY + "Aktiv bis: " + ChatColor.YELLOW + a.periodEnd)); + if (!a.cancelled) lore.add(ChatColor.GRAY + "Nächste Abbuchung: " + ChatColor.WHITE + a.nextBillingDate); + lore.add(ChatColor.GRAY + "Heute: " + ChatColor.WHITE + flyManager.formatTime(d.flyUsed) + + ChatColor.GRAY + " / " + ChatColor.WHITE + flyManager.formatTime(flyAboMaxDailySec)); + lore.add(""); + lore.add(aboActionLine(mode)); + gui.setItem(10, aboItem(Material.FEATHER, ChatColor.AQUA + "" + ChatColor.BOLD + "✈ Fly-Abo", lore)); + } + + // ── Plot-Abo (Slot 12) ── + if (d.plot == null) { + gui.setItem(12, aboItem(Material.GRAY_DYE, ChatColor.GRAY + "📦 Kein Plot-Abo", + Arrays.asList(ChatColor.GRAY + "Im Shop erhältlich:", ChatColor.AQUA + "viper-network.de"))); + } else { + PlotSlotManager.PlotAboEntry a = d.plot; + String mode = aboMode(a.cancelled, a.cancellationReason); + List lore = new ArrayList<>(Arrays.asList( + ChatColor.GRAY + "Paket: " + ChatColor.WHITE + a.label, + ChatColor.GRAY + "Slots: " + ChatColor.WHITE + "+" + a.aboSlots, + ChatColor.GRAY + "Preis: " + ChatColor.WHITE + a.monthlyPrice + " " + currency + " / Monat", + ChatColor.GRAY + "Status: " + (a.cancelled ? ChatColor.RED + "⚠ Gekündigt" : ChatColor.GREEN + "✔ Aktiv"), + ChatColor.GRAY + "Aktiv bis: " + ChatColor.YELLOW + a.periodEnd)); + if (!a.cancelled) lore.add(ChatColor.GRAY + "Nächste Abbuchung: " + ChatColor.WHITE + a.nextBillingDate); + lore.add(""); + lore.add(aboActionLine(mode)); + gui.setItem(12, aboItem(Material.OAK_SIGN, ChatColor.AQUA + "" + ChatColor.BOLD + "📦 Plot-Abo", lore)); + } + + // ── Belege (Slot 14) ── + gui.setItem(14, aboItem(Material.BOOK, ChatColor.GREEN + "" + ChatColor.BOLD + "🧾 Kaufbelege", + Arrays.asList(ChatColor.GRAY + "Alle deine Käufe ansehen", "", ChatColor.YELLOW + "▶ Klick: " + ChatColor.WHITE + "öffnen"))); + + // ── Abo abschließen (Slot 16) ── + gui.setItem(16, aboItem(Material.EMERALD, ChatColor.GREEN + "" + ChatColor.BOLD + "➕ Abo abschließen", + Arrays.asList(ChatColor.GRAY + "Alle Abos mit Preis aus dem Shop", "", + ChatColor.YELLOW + "▶ Klick: " + ChatColor.WHITE + "Angebote ansehen"))); + + // ── Item-Abos (Slots 19–25) ── + for (int i = 0; i < d.items.size() && i < ABO_ITEM_SLOTS.length; i++) { + JsonObject o = d.items.get(i); + boolean cancelled = jsonFlag(o, "cancelled"); + String mode = aboMode(cancelled, null); + List lore = new ArrayList<>(Arrays.asList( + ChatColor.GRAY + "Item: " + ChatColor.WHITE + str(o, "item_id", "?"), + ChatColor.GRAY + "Täglich: " + ChatColor.AQUA + str(o, "daily_qty", "?") + "x", + ChatColor.GRAY + "Status: " + (cancelled ? ChatColor.RED + "⚠ Gekündigt" : ChatColor.GREEN + "✔ Aktiv"), + ChatColor.GRAY + "Läuft bis: " + ChatColor.YELLOW + str(o, "expires_at", "?"), + "", aboActionLine(mode))); + gui.setItem(ABO_ITEM_SLOTS[i], aboItem(Material.CHEST_MINECART, + ChatColor.AQUA + "" + ChatColor.BOLD + "📦 " + str(o, "label", "Item-Abo"), lore)); + } + if (d.items.isEmpty()) { + gui.setItem(ABO_ITEM_SLOTS[0], aboItem(Material.GRAY_DYE, ChatColor.GRAY + "📦 Keine Item-Abos", + Arrays.asList(ChatColor.GRAY + "Im Shop erhältlich:", ChatColor.AQUA + "viper-network.de"))); + } + + gui.setItem(31, aboItem(Material.BARRIER, ChatColor.RED + "Schließen", new ArrayList<>())); + p.openInventory(gui); + } + + private void handleAboGuiClick(Player p, int slot) { + AboGuiData d = aboGuiData.get(p.getUniqueId()); + if (d == null) return; + if (slot == 31) { p.closeInventory(); return; } + if (slot == 14) { p.closeInventory(); Bukkit.dispatchCommand(p, "belege"); return; } + if (slot == 16) { openAboShopGUI(p); return; } + + AboAction a = new AboAction(); + if (slot == 10 && d.fly != null) { + a.kind = "fly"; a.label = d.fly.label; + a.mode = aboMode(d.fly.cancelled, d.fly.cancellationReason); + } else if (slot == 12 && d.plot != null) { + a.kind = "plot"; a.label = d.plot.label; + a.mode = aboMode(d.plot.cancelled, d.plot.cancellationReason); + } else { + int idx = -1; + for (int i = 0; i < ABO_ITEM_SLOTS.length; i++) if (ABO_ITEM_SLOTS[i] == slot) idx = i; + if (idx < 0 || idx >= d.items.size()) return; + JsonObject o = d.items.get(idx); + a.kind = "item"; a.label = str(o, "label", "Item-Abo"); + a.itemId = o.has("id") ? o.get("id").getAsInt() : 0; + boolean cancelled = jsonFlag(o, "cancelled"); + a.mode = aboMode(cancelled, null); + } + if ("none".equals(a.mode)) { + p.sendMessage(ChatColor.RED + "✗ Dieses Abo wurde wegen fehlgeschlagener Zahlung beendet. Bitte im Shop neu abschließen."); + return; + } + if ("cancel".equals(a.mode)) { + aboPending.put(p.getUniqueId(), a); + openAboConfirm(p, a); + } else { + runAboAction(p, a); + } + } + + private void openAboShopGUI(Player p) { + new BukkitRunnable() { + @Override public void run() { + List offers = new ArrayList<>(); + int code = -1; + try { + HttpURLConnection conn = openAuthConnection( + wpBase + "/abo_offers?server=" + java.net.URLEncoder.encode(targetServer, "UTF-8"), "GET"); + code = conn.getResponseCode(); + if (code == 200) { + JsonObject resp = JsonParser.parseString(readResponse(conn)).getAsJsonObject(); + for (JsonElement el : resp.getAsJsonArray("offers")) offers.add(el.getAsJsonObject()); + } + } catch (Exception e) { + getLogger().log(Level.WARNING, "[AboShop] Angebote laden fehlgeschlagen", e); + } + final int fCode = code; + Bukkit.getScheduler().runTask(IngameShopSpigot.this, () -> { + if (fCode != 200) { + p.sendMessage(ChatColor.RED + "✗ Abo-Angebote nicht verfügbar" + + (fCode > 0 ? " (HTTP " + fCode + ")." : ".")); + return; + } + if (offers.isEmpty()) { + p.sendMessage(ChatColor.GRAY + "Auf diesem Server gibt es keine Abo-Angebote."); + return; + } + aboOffers.put(p.getUniqueId(), offers); + showAboShopGUI(p, offers); + }); + } + }.runTaskAsynchronously(this); + } + + private void showAboShopGUI(Player p, List offers) { + AboGuiData d = aboGuiData.get(p.getUniqueId()); + Inventory gui = Bukkit.createInventory(null, 36, GUI_ABO_SHOP); + ItemStack pane = aboItem(Material.BLACK_STAINED_GLASS_PANE, " ", new ArrayList<>()); + for (int i = 0; i < 36; i++) gui.setItem(i, pane); + for (int i = 0; i < offers.size() && i < 18; i++) { + JsonObject o = offers.get(i); + String type = str(o, "type", "item"); + boolean owned = d != null + && (("fly".equals(type) && d.fly != null && !d.fly.cancelled) + || ("plot".equals(type) && d.plot != null && !d.plot.cancelled)); + Material mat = "fly".equals(type) ? Material.FEATHER : "plot".equals(type) ? Material.OAK_SIGN : Material.CHEST_MINECART; + int price = o.has("price") ? o.get("price").getAsInt() : 0; + int total = o.has("total") ? o.get("total").getAsInt() : price; + List lore = new ArrayList<>(); + lore.add(ChatColor.GRAY + "Preis: " + ChatColor.YELLOW + total + " " + currency + " / Monat"); + if (total != price) lore.add(ChatColor.DARK_GRAY + "(" + price + " + " + (total - price) + " Steuer)"); + if ("plot".equals(type)) lore.add(ChatColor.GRAY + "Slots: " + ChatColor.WHITE + "+" + str(o, "slots", "?")); + String srv = str(o, "servers", ""); + if (!srv.isEmpty()) lore.add(ChatColor.GRAY + "Nutzbar auf: " + ChatColor.WHITE + srv); + lore.add(""); + lore.add(owned ? ChatColor.RED + "✗ Du hast dieses Abo bereits aktiv" + : ChatColor.YELLOW + "▶ Klick: " + ChatColor.GREEN + "Kaufen"); + gui.setItem(i < 9 ? 9 + i : 18 + (i - 9), aboItem(mat, + ChatColor.AQUA + "" + ChatColor.BOLD + str(o, "title", "Abo"), lore)); + } + gui.setItem(31, aboItem(Material.ARROW, ChatColor.YELLOW + "◀ Zurück", new ArrayList<>())); + p.openInventory(gui); + } + + private void handleAboShopClick(Player p, int slot) { + if (slot == 31) { openAboGUI(p); return; } + List offers = aboOffers.get(p.getUniqueId()); + if (offers == null) return; + int idx = (slot >= 9 && slot < 18) ? slot - 9 : (slot >= 18 && slot < 27) ? 9 + (slot - 18) : -1; + if (idx < 0 || idx >= offers.size()) return; + JsonObject o = offers.get(idx); + String type = str(o, "type", "item"); + AboGuiData d = aboGuiData.get(p.getUniqueId()); + if (d != null && (("fly".equals(type) && d.fly != null && !d.fly.cancelled) + || ("plot".equals(type) && d.plot != null && !d.plot.cancelled))) { + p.sendMessage(ChatColor.RED + "✗ Du hast dieses Abo bereits aktiv."); + return; + } + if (activeOrderIds.containsKey(p.getUniqueId())) { + p.sendMessage(ChatColor.RED + "✗ Bitte schließe zuerst deinen offenen Kauf ab."); + return; + } + final int wpId = o.get("id").getAsInt(); + final String title = str(o, "title", "Abo"); + p.closeInventory(); + p.sendMessage(ChatColor.GRAY + "Bestellung »" + title + "« wird angelegt …"); + new BukkitRunnable() { + @Override public void run() { + int code = -1; + try { + JsonObject item = new JsonObject(); + item.addProperty("id", wpId); + item.addProperty("quantity", 1); + JsonArray cart = new JsonArray(); + cart.add(item); + JsonObject body = new JsonObject(); + body.addProperty("player", p.getName()); + body.addProperty("server", targetServer); + body.add("cart", cart); + HttpURLConnection conn = openAuthConnection(wpBase + "/order", "POST"); + writeJson(conn, body.toString()); + code = conn.getResponseCode(); + } catch (Exception e) { + getLogger().log(Level.WARNING, "[AboShop] Bestellung fehlgeschlagen", e); + } + if (code == 200 || code == 201) { + // Normaler Kauf-Ablauf: Bestätigungs-GUI mit Preis, Abbuchung, Beleg + fetchPendingOrders(p, wpUrlPending); + } else { + final int fCode = code; + Bukkit.getScheduler().runTask(IngameShopSpigot.this, () -> + p.sendMessage(ChatColor.RED + "✗ Bestellung nicht möglich" + + (fCode > 0 ? " (HTTP " + fCode + ")." : "."))); + } + } + }.runTaskAsynchronously(this); + } + + private void openAboConfirm(Player p, AboAction a) { + Inventory gui = Bukkit.createInventory(null, 27, GUI_ABO_CONFIRM); + ItemStack pane = aboItem(Material.BLACK_STAINED_GLASS_PANE, " ", new ArrayList<>()); + for (int i = 0; i < 27; i++) gui.setItem(i, pane); + List info = new ArrayList<>(); + info.add(ChatColor.GRAY + "Das Abo läuft bis zum Ende der"); + info.add(ChatColor.GRAY + "bezahlten Laufzeit weiter."); + if ("plot".equals(a.kind)) { + info.add(ChatColor.GRAY + "Danach werden überzählige Plots"); + info.add(ChatColor.GRAY + "eingefroren und nach 7 Tagen freigegeben."); + } + info.add(ChatColor.GRAY + "Du kannst die Kündigung bis dahin"); + info.add(ChatColor.GRAY + "wieder zurücknehmen."); + gui.setItem(13, aboItem(Material.PAPER, ChatColor.YELLOW + a.label, info)); + gui.setItem(11, aboItem(Material.LIME_WOOL, ChatColor.GREEN + "" + ChatColor.BOLD + "Ja, kündigen", new ArrayList<>())); + gui.setItem(15, aboItem(Material.RED_WOOL, ChatColor.RED + "" + ChatColor.BOLD + "Abbrechen", new ArrayList<>())); + p.openInventory(gui); + } + + private void handleAboConfirmClick(Player p, int slot) { + AboAction a = aboPending.get(p.getUniqueId()); + if (a == null) { p.closeInventory(); return; } + if (slot == 11) { + aboPending.remove(p.getUniqueId()); + runAboAction(p, a); + } else if (slot == 15) { + aboPending.remove(p.getUniqueId()); + openAboGUI(p); + } + } + + /** Führt Kündigen/Reaktivieren aus und öffnet danach die Übersicht neu. */ + private void runAboAction(Player p, AboAction a) { + p.closeInventory(); + new BukkitRunnable() { + @Override public void run() { + boolean ok; + String err = null; + boolean cancel = "cancel".equals(a.mode); + try { + switch (a.kind) { + case "fly": + ok = cancel ? flyAboManager.cancelAbo(p.getName()) : flyAboManager.reactivateAbo(p.getName()); + break; + case "plot": + ok = cancel ? plotSlotManager.cancelAbo(p.getName()) : plotSlotManager.reactivateAbo(p.getName()); + break; + default: { + HttpURLConnection conn = openAuthConnection( + wpBase + (cancel ? "/item_abo_cancel" : "/item_abo_reactivate"), "POST"); + writeJson(conn, "{\"player\":\"" + p.getName() + "\",\"abo_id\":" + a.itemId + "}"); + int code = conn.getResponseCode(); + ok = code == 200; + if (!ok) err = "HTTP " + code; + } + } + } catch (Exception e) { + getLogger().log(Level.WARNING, "[AboGUI] Aktion fehlgeschlagen", e); + ok = false; + err = "Verbindungsfehler"; + } + final boolean fOk = ok; + final String fErr = err; + Bukkit.getScheduler().runTask(IngameShopSpigot.this, () -> { + if (fOk) { + p.sendMessage(cancel + ? ChatColor.YELLOW + "✔ »" + a.label + "« wurde gekündigt und läuft bis Laufzeitende weiter." + : ChatColor.GREEN + "✔ Kündigung von »" + a.label + "« zurückgenommen – das Abo läuft weiter."); + p.playSound(p.getLocation(), cancel ? Sound.BLOCK_NOTE_BLOCK_BASS : Sound.ENTITY_PLAYER_LEVELUP, 1.0F, cancel ? 0.8F : 1.2F); + } else { + p.sendMessage(ChatColor.RED + "✗ Aktion nicht möglich" + + (fErr != null ? " (" + fErr + ")" : " – Abo nicht gefunden oder Zeitraum abgelaufen") + "."); + } + openAboGUI(p); + }); + } + }.runTaskAsynchronously(this); + } + + /** true/false, 1/0 oder "1"/"true" – WP liefert je nach Endpunkt unterschiedliche Formen. */ + private static boolean jsonFlag(JsonObject o, String key) { + if (!o.has(key) || o.get(key).isJsonNull()) return false; + String v = o.get(key).getAsString(); + return "1".equals(v) || "true".equalsIgnoreCase(v); + } + + private static String str(JsonObject o, String key, String def) { + return (o.has(key) && !o.get(key).isJsonNull()) ? o.get(key).getAsString() : def; + } + + private String fmtPrice(double v) { + return (v == Math.floor(v) ? String.valueOf((long) v) : String.valueOf(v)) + " " + currency; + } + + private String fmtDate(String raw) { + // "2026-09-30 02:02:11" → "30.09.2026 02:02" + if (raw == null || raw.length() < 16) return raw == null ? "?" : raw; + return raw.substring(8, 10) + "." + raw.substring(5, 7) + "." + raw.substring(0, 4) + " " + raw.substring(11, 16); + } + + private String statusLabel(String status) { + switch (status) { + case "completed": return ChatColor.GREEN + "✔ Geliefert"; + case "cancelled": return ChatColor.RED + "✘ Storniert"; + case "processing": return ChatColor.AQUA + "⟳ In Arbeit"; + default: return ChatColor.YELLOW + "⌛ Ausstehend"; + } + } + + private void openOrdersGUI(Player player, List list, int page) { + final int pageSize = 45; + final int totalPages = Math.max(1, (int) Math.ceil(list.size() / (double) pageSize)); + page = Math.max(0, Math.min(page, totalPages - 1)); + ordersPage.put(player.getUniqueId(), page); + ordersCache.put(player.getUniqueId(), list); + + Inventory gui = Bukkit.createInventory(null, 54, GUI_ORDERS); + ItemStack pane = new ItemStack(Material.BLACK_STAINED_GLASS_PANE); + ItemMeta pM = pane.getItemMeta(); + pM.setDisplayName(" "); + pane.setItemMeta(pM); + for (int i = 45; i < 54; i++) gui.setItem(i, pane); + + int start = page * pageSize; + int end = Math.min(start + pageSize, list.size()); + for (int i = start; i < end; i++) { + JsonObject o = list.get(i); + String status = str(o, "status", "pending"); + Material mat = "completed".equals(status) ? Material.PAPER + : "cancelled".equals(status) ? Material.BARRIER : Material.CLOCK; + ItemStack item = new ItemStack(mat); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(ChatColor.WHITE + "" + ChatColor.BOLD + "Beleg #" + str(o, "id", "?")); + String title = str(o, "item_title", "?"); + if (title.length() > 40) title = title.substring(0, 37) + "…"; + meta.setLore(Arrays.asList( + ChatColor.GRAY + "──────────────────────", + ChatColor.GRAY + "Datum: " + ChatColor.WHITE + fmtDate(str(o, "created_at", null)), + ChatColor.GRAY + "Artikel: " + ChatColor.AQUA + title, + ChatColor.GRAY + "Preis: " + ChatColor.YELLOW + fmtPrice(o.has("price") ? o.get("price").getAsDouble() : 0), + ChatColor.GRAY + "Status: " + statusLabel(status), + ChatColor.GRAY + (str(o, "usable_servers", "").isEmpty() ? "Server: " : "Nutzbar: ") + + ChatColor.WHITE + (str(o, "usable_servers", "").isEmpty() + ? str(o, "server", "–") : str(o, "usable_servers", "")), + ChatColor.GRAY + "──────────────────────", + ChatColor.YELLOW + "▶ Klick: " + ChatColor.WHITE + "Beleg als Buch öffnen")); + item.setItemMeta(meta); + gui.setItem(i - start, item); + } + + ItemStack info = new ItemStack(Material.BOOK); + ItemMeta im = info.getItemMeta(); + im.setDisplayName(ChatColor.WHITE + "Seite " + (page + 1) + " / " + totalPages); + im.setLore(Arrays.asList(ChatColor.GRAY + "" + list.size() + " Beleg(e) insgesamt")); + info.setItemMeta(im); + gui.setItem(49, info); + + if (page > 0) { + ItemStack prev = new ItemStack(Material.ARROW); + ItemMeta pm2 = prev.getItemMeta(); + pm2.setDisplayName(ChatColor.YELLOW + "◀ Vorherige Seite"); + prev.setItemMeta(pm2); + gui.setItem(45, prev); + } + if (page < totalPages - 1) { + ItemStack next = new ItemStack(Material.ARROW); + ItemMeta nm = next.getItemMeta(); + nm.setDisplayName(ChatColor.YELLOW + "Nächste Seite ▶"); + next.setItemMeta(nm); + gui.setItem(53, next); + } + player.openInventory(gui); + } + + @SuppressWarnings("deprecation") + private void openReceiptBook(Player player, JsonObject o) { + String status = str(o, "status", "pending"); + double price = o.has("price") ? o.get("price").getAsDouble() : 0; + ItemStack book = new ItemStack(Material.WRITTEN_BOOK); + BookMeta bm = (BookMeta) book.getItemMeta(); + bm.setTitle("Beleg #" + str(o, "id", "?")); + bm.setAuthor("Shop"); + String qty = str(o, "quantity", ""); + bm.addPage( + ChatColor.BOLD + "KAUFBELEG\n" + ChatColor.RESET + + "Nr. " + str(o, "id", "?") + "\n\n" + + "Datum:\n" + fmtDate(str(o, "created_at", null)) + "\n\n" + + "Käufer:\n" + player.getName() + "\n\n" + + (str(o, "usable_servers", "").isEmpty() + ? "Server:\n" + str(o, "server", "–") + : "Nutzbar auf:\n" + str(o, "usable_servers", ""))); + bm.addPage( + ChatColor.BOLD + "Artikel\n" + ChatColor.RESET + + str(o, "item_title", "?") + + (qty.isEmpty() ? "" : "\n\nMenge: " + qty) + "\n\n" + + ChatColor.BOLD + "Preis\n" + ChatColor.RESET + fmtPrice(price) + "\n\n" + + ChatColor.BOLD + "Status\n" + ChatColor.RESET + + ChatColor.stripColor(statusLabel(status))); + book.setItemMeta(bm); + player.closeInventory(); + player.openBook(book); + } + /** /flytime */ private class FlyTimeCommand implements CommandExecutor { @Override @@ -1948,6 +2475,10 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { String label, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage("Nur für Spieler."); return true; } Player p = (Player) sender; + if (args.length == 0 || !args[0].equalsIgnoreCase("text")) { + openAboGUI(p); // Chat-Version weiter über "/abo text" + return true; + } new BukkitRunnable() { @Override public void run() { @@ -3416,6 +3947,21 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { * Abo durch Spieler kündigen – bleibt bis period_end aktiv. * period_end wird auf LAST_DAY(CURDATE()) gesetzt (Ende des laufenden Monats). */ + /** Kündigung durch den Spieler zurücknehmen (solange das Abo noch läuft). */ + boolean reactivateAbo(String playerName) { + String sql = + "UPDATE wis_fly_abos SET cancelled = 0, cancellation_reason = NULL" + + " WHERE player_name = ? AND period_end >= CURDATE() AND cancelled = 1" + + " AND (cancellation_reason IS NULL OR cancellation_reason = 'user')"; + try (PreparedStatement ps = connection.prepareStatement(sql)) { + ps.setString(1, playerName); + return ps.executeUpdate() == 1; + } catch (SQLException e) { + plugin.getLogger().log(Level.WARNING, "reactivateAbo SQL Fehler", e); + return false; + } + } + boolean cancelAbo(String playerName) { String sql = "UPDATE wis_fly_abos SET cancelled = 1, cancellation_reason = 'user'," @@ -3591,6 +4137,9 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { // Migration: last_perm Spalte ergänzen falls Tabelle schon existiert try { stmt.execute("ALTER TABLE wis_plot_extra_slots ADD COLUMN IF NOT EXISTS last_perm INT NOT NULL DEFAULT 0 AFTER extra_slots"); } catch (SQLException ignored) {} + // Migration: frozen_at (Datum, ab dem Plots eingefroren sind) + try { stmt.execute("ALTER TABLE wis_plot_abos ADD COLUMN IF NOT EXISTS frozen_at DATE NULL"); } + catch (SQLException ignored) {} } catch (SQLException e) { plugin.getLogger().log(Level.SEVERE, "Plot-Slot-Tabellen Erstellung fehlgeschlagen", e); } @@ -3665,7 +4214,7 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { + " LAST_DAY(CURDATE()))" + " ON DUPLICATE KEY UPDATE" + " label = ?, abo_slots = ?, monthly_price = ?," - + " cancelled = 0, cancellation_reason = NULL," + + " cancelled = 0, cancellation_reason = NULL, frozen_at = NULL," + " next_billing_date = DATE_FORMAT(DATE_ADD(CURDATE(), INTERVAL 1 MONTH), '%Y-%m-01')," + " period_end = LAST_DAY(CURDATE()), granted_at = NOW()"; try (PreparedStatement ps = connection.prepareStatement(sql)) { @@ -3679,6 +4228,20 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { } } + boolean reactivatePlotAbo(String playerName) { + String sql = + "UPDATE wis_plot_abos SET cancelled = 0, cancellation_reason = NULL, frozen_at = NULL" + + " WHERE player_name = ? AND period_end >= CURDATE() AND cancelled = 1" + + " AND (cancellation_reason IS NULL OR cancellation_reason = 'user')"; + try (PreparedStatement ps = connection.prepareStatement(sql)) { + ps.setString(1, playerName); + return ps.executeUpdate() == 1; + } catch (SQLException e) { + plugin.getLogger().log(Level.WARNING, "reactivatePlotAbo SQL Fehler", e); + return false; + } + } + boolean cancelPlotAbo(String playerName) { String sql = "UPDATE wis_plot_abos SET cancelled = 1, cancellation_reason = 'user'," @@ -3696,7 +4259,7 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { void cancelPlotAboPaymentFailed(String playerName) { String sql = "UPDATE wis_plot_abos SET cancelled = 1, cancellation_reason = 'payment_failed'," - + " period_end = LAST_DAY(CURDATE())" + + " period_end = DATE_SUB(CURDATE(), INTERVAL 1 DAY)" + " WHERE player_name = ? AND cancelled = 0"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setString(1, playerName); @@ -3723,7 +4286,7 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { int getPlotAboSlots(String playerName) { String sql = "SELECT abo_slots FROM wis_plot_abos" - + " WHERE player_name = ? AND period_end >= CURDATE() AND cancelled = 0"; + + " WHERE player_name = ? AND period_end >= CURDATE()"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setString(1, playerName); try (ResultSet rs = ps.executeQuery()) { @@ -3762,6 +4325,115 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { return null; } + JsonArray getAllFlyAbosJson() { + JsonArray arr = new JsonArray(); + String sql = "SELECT player_name, label, monthly_price, cancelled, cancellation_reason," + + " next_billing_date, period_end, granted_at FROM wis_fly_abos"; + try (PreparedStatement ps = connection.prepareStatement(sql); + ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + JsonObject o = new JsonObject(); + o.addProperty("player_name", rs.getString("player_name")); + o.addProperty("label", rs.getString("label")); + o.addProperty("monthly_price", rs.getInt("monthly_price")); + o.addProperty("cancelled", rs.getInt("cancelled")); + o.addProperty("cancellation_reason", rs.getString("cancellation_reason")); + o.addProperty("next_billing_date", String.valueOf(rs.getDate("next_billing_date"))); + o.addProperty("period_end", String.valueOf(rs.getDate("period_end"))); + o.addProperty("granted_at", String.valueOf(rs.getTimestamp("granted_at"))); + arr.add(o); + } + } catch (SQLException e) { + plugin.getLogger().log(Level.WARNING, "getAllFlyAbosJson SQL Fehler", e); + } + return arr; + } + + JsonArray getAllPlotAbosJson() { + JsonArray arr = new JsonArray(); + String sql = "SELECT player_name, label, abo_slots, monthly_price, cancelled, cancellation_reason," + + " next_billing_date, period_end, frozen_at, granted_at FROM wis_plot_abos"; + try (PreparedStatement ps = connection.prepareStatement(sql); + ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + JsonObject o = new JsonObject(); + o.addProperty("player_name", rs.getString("player_name")); + o.addProperty("label", rs.getString("label")); + o.addProperty("abo_slots", rs.getInt("abo_slots")); + o.addProperty("monthly_price", rs.getInt("monthly_price")); + o.addProperty("cancelled", rs.getInt("cancelled")); + o.addProperty("cancellation_reason", rs.getString("cancellation_reason")); + o.addProperty("next_billing_date", String.valueOf(rs.getDate("next_billing_date"))); + o.addProperty("period_end", String.valueOf(rs.getDate("period_end"))); + java.sql.Date fz = rs.getDate("frozen_at"); + o.addProperty("frozen_at", fz == null ? "" : fz.toString()); + o.addProperty("granted_at", String.valueOf(rs.getTimestamp("granted_at"))); + arr.add(o); + } + } catch (SQLException e) { + plugin.getLogger().log(Level.WARNING, "getAllPlotAbosJson SQL Fehler", e); + } + return arr; + } + + /** Abos, deren Laufzeit vorbei ist und die noch nicht als eingefroren markiert sind. */ + List getExpiredUnfrozenAbos() { + return queryNames("SELECT player_name FROM wis_plot_abos" + + " WHERE period_end < CURDATE() AND frozen_at IS NULL"); + } + + /** Abos, die seit mindestens 7 Tagen eingefroren sind. */ + List getAbosFrozenOverDays(int days) { + return queryNames("SELECT player_name FROM wis_plot_abos" + + " WHERE frozen_at IS NOT NULL AND frozen_at <= DATE_SUB(CURDATE(), INTERVAL " + days + " DAY)"); + } + + private List queryNames(String sql) { + List list = new ArrayList<>(); + try (PreparedStatement ps = connection.prepareStatement(sql); + ResultSet rs = ps.executeQuery()) { + while (rs.next()) list.add(rs.getString("player_name")); + } catch (SQLException e) { + plugin.getLogger().log(Level.WARNING, "queryNames SQL Fehler", e); + } + return list; + } + + void markPlotAboFrozen(String playerName) { + try (PreparedStatement ps = connection.prepareStatement( + "UPDATE wis_plot_abos SET frozen_at = CURDATE() WHERE player_name = ? AND frozen_at IS NULL")) { + ps.setString(1, playerName); + ps.executeUpdate(); + } catch (SQLException e) { + plugin.getLogger().log(Level.WARNING, "markPlotAboFrozen SQL Fehler", e); + } + } + + void deletePlotAbo(String playerName) { + try (PreparedStatement ps = connection.prepareStatement( + "DELETE FROM wis_plot_abos WHERE player_name = ?")) { + ps.setString(1, playerName); + ps.executeUpdate(); + } catch (SQLException e) { + plugin.getLogger().log(Level.WARNING, "deletePlotAbo SQL Fehler", e); + } + } + + /** Verbleibende Tage bis zur Freigabe der Plots (7 - Tage seit Einfrieren), -1 = nicht eingefroren. */ + int getFrozenDaysLeft(String playerName) { + try (PreparedStatement ps = connection.prepareStatement( + "SELECT 7 - DATEDIFF(CURDATE(), frozen_at) AS d FROM wis_plot_abos" + + " WHERE player_name = ? AND frozen_at IS NOT NULL")) { + ps.setString(1, playerName); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) return Math.max(0, rs.getInt("d")); + } + } catch (SQLException e) { + plugin.getLogger().log(Level.WARNING, "getFrozenDaysLeft SQL Fehler", e); + } + return -1; + } + List getDuePlotBillings() { List list = new ArrayList<>(); String sql = @@ -4516,6 +5188,7 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { void grantAbo(Player player, String label, int monthlyPrice) { db.saveAbo(player.getName(), label, monthlyPrice); + plotSlotManager.syncToWp(); Bukkit.getScheduler().runTask(plugin, () -> { player.sendMessage(""); player.sendMessage(ChatColor.GOLD + "✈ ════════════════════════════"); @@ -4534,6 +5207,7 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { void grantAboByName(String playerName, String label, int monthlyPrice) { db.saveAbo(playerName, label, monthlyPrice); + plotSlotManager.syncToWp(); } void notifyGranted(Player player, String label, int monthlyPrice) { @@ -4554,8 +5228,16 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { // ── Kündigung durch Spieler ──────────────────────────────────── + boolean reactivateAbo(String playerName) { + boolean ok = db.reactivateAbo(playerName); + if (ok) plotSlotManager.syncToWp(); + return ok; + } + boolean cancelAbo(String playerName) { - return db.cancelAbo(playerName); + boolean ok = db.cancelAbo(playerName); + if (ok) plotSlotManager.syncToWp(); + return ok; } // ── Status lesen ────────────────────────────────────────────── @@ -4684,6 +5366,7 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { new BukkitRunnable() { @Override public void run() { db.renewAbo(playerName); + plotSlotManager.syncToWp(); getLogger().info("[FlyAbo] ✔ Abo verlängert: " + playerName + " (" + price + " " + currency + ")"); } @@ -4709,6 +5392,7 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { new BukkitRunnable() { @Override public void run() { db.cancelAboPaymentFailed(playerName); + plotSlotManager.syncToWp(); getLogger().warning("[FlyAbo] ✘ Zahlung fehlgeschlagen: " + playerName + " (benötigt: " + price + " " + currency + ")"); } @@ -4849,7 +5533,9 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { void grantAbo(Player player, int slots, String label, int monthlyPrice) { db.savePlotAbo(player.getName(), slots, label, monthlyPrice); + unfreezeExcessPlots(player.getName()); applyLimit(player.getName()); + syncToWp(); Bukkit.getScheduler().runTask(plugin, () -> { player.sendMessage(""); player.sendMessage(ChatColor.GOLD + "📦 ════════════════════════════"); @@ -4867,12 +5553,20 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { void grantAboByName(String playerName, int slots, String label, int monthlyPrice) { db.savePlotAbo(playerName, slots, label, monthlyPrice); + unfreezeExcessPlots(playerName); applyLimit(playerName); + syncToWp(); + } + + boolean reactivateAbo(String playerName) { + boolean ok = db.reactivatePlotAbo(playerName); + if (ok) { unfreezeExcessPlots(playerName); applyLimit(playerName); syncToWp(); } + return ok; } boolean cancelAbo(String playerName) { boolean ok = db.cancelPlotAbo(playerName); - if (ok) applyLimit(playerName); + if (ok) { unfreezeExcessPlots(playerName); applyLimit(playerName); syncToWp(); } return ok; } @@ -4883,26 +5577,100 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { // ── Einfrieren überzähliger Plots ───────────────────────────── void freezeExcessPlots(String playerName, int newLimit) { + db.markPlotAboFrozen(playerName); Bukkit.getScheduler().runTask(plugin, () -> { - if (Bukkit.getPluginManager().getPlugin("PlotSquared") == null) return; Player online = Bukkit.getPlayer(playerName); - if (online != null) { - online.sendMessage(""); - online.sendMessage(ChatColor.RED + "📦 ════════════════════════════"); - online.sendMessage(ChatColor.RED + " Plot-Abo abgelaufen!"); - online.sendMessage(ChatColor.GRAY + " Limit reduziert auf: " - + ChatColor.WHITE + newLimit); - online.sendMessage(ChatColor.YELLOW + " Überzählige Plots sind eingefroren."); - online.sendMessage(ChatColor.GRAY + " Abo erneuern: " + ChatColor.AQUA + "viper-network.de"); - online.sendMessage(ChatColor.RED + " ════════════════════════════"); - online.sendMessage(""); - online.playSound(online.getLocation(), Sound.BLOCK_NOTE_BLOCK_BASS, 1.0F, 0.5F); - } + if (online != null) sendFrozenNotice(online); Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "lp user " + playerName + " meta set frozen_excess_plots true"); }); } + private void sendFrozenNotice(Player p) { + int left = db.getFrozenDaysLeft(p.getName()); + if (left < 0) return; + p.sendMessage(ChatColor.RED + "📦 Dein Plot-Abo ist abgelaufen – überzählige Plots sind eingefroren."); + p.sendMessage(ChatColor.GRAY + " Noch " + ChatColor.WHITE + left + ChatColor.GRAY + + " Tag(e) bis zur Freigabe. Erneuern: " + ChatColor.AQUA + "viper-network.de"); + } + + // ── Täglicher Cleanup: einfrieren nach Ablauf, nach 7 Tagen freigeben ── + + void startMaintenance() { + new BukkitRunnable() { + @Override public void run() { runMaintenance(); } + }.runTaskTimerAsynchronously(plugin, 20L * 60 * 10, 20L * 60 * 60 * 24); + // Abgleich mit WordPress: kurz nach dem Start, danach stündlich + new BukkitRunnable() { + @Override public void run() { syncToWp(); } + }.runTaskTimer(plugin, 20L * 30, 20L * 60 * 60); + } + + /** Schickt alle Plot-Abos (Snapshot) an WordPress für die Abo-Verwaltung. */ + void syncToWp() { + if (apiKey.isEmpty() || wpBase == null) return; + new BukkitRunnable() { + @Override public void run() { + try { + JsonObject body = new JsonObject(); + JsonArray all = db.getAllPlotAbosJson(); + body.add("abos", all); + JsonArray fly = db.getAllFlyAbosJson(); + body.add("fly", fly); + HttpURLConnection conn = openAuthConnection(wpBase + "/plot_abo_sync", "POST"); + writeJson(conn, body.toString()); + int code = conn.getResponseCode(); + if (code != 200) plugin.getLogger().warning("[PlotSlots] WP-Sync HTTP " + code); + else plugin.getLogger().info("[PlotSlots] WP-Sync OK: " + all.size() + " Plot-Abo(s), " + fly.size() + " Fly-Abo(s) übertragen."); + conn.disconnect(); + } catch (Exception e) { + plugin.getLogger().log(Level.WARNING, "[PlotSlots] WP-Sync fehlgeschlagen: " + e.getMessage()); + } + } + }.runTaskAsynchronously(plugin); + } + + /** Gibt alle Plots des Spielers frei, die über dem Limit liegen (neueste zuerst). */ + void releaseExcessPlots(String playerName, int keep) { + if (Bukkit.getPluginManager().getPlugin("PlotSquared") == null) return; + try { + @SuppressWarnings("deprecation") + java.util.UUID uuid = Bukkit.getOfflinePlayer(playerName).getUniqueId(); + List owned = new ArrayList<>(); + com.plotsquared.core.PlotSquared.get().forEachPlotRaw(pl -> { + if (uuid.equals(pl.getOwnerAbs()) && pl.isBasePlot()) owned.add(pl); + }); + owned.sort(java.util.Comparator.comparingLong(com.plotsquared.core.plot.Plot::getTimestamp)); + int released = 0; + for (int i = keep; i < owned.size(); i++) { + owned.get(i).getPlotModificationManager().deletePlot(null, () -> {}); + released++; + } + plugin.getLogger().info("[PlotSlots] " + playerName + ": " + released + + " Plot(s) freigegeben (Limit " + keep + ", besaß " + owned.size() + ")."); + } catch (Throwable t) { + plugin.getLogger().log(Level.WARNING, "[PlotSlots] Plots von " + playerName + " konnten nicht freigegeben werden", t); + } + } + + void runMaintenance() { + for (String name : db.getExpiredUnfrozenAbos()) { + int newLimit = getRankBaseByName(name) + db.getExtraSlots(name); + freezeExcessPlots(name, newLimit); + applyLimit(name); + plugin.getLogger().info("[PlotSlots] Abo abgelaufen, eingefroren: " + name); + } + for (String name : db.getAbosFrozenOverDays(7)) { + db.deletePlotAbo(name); + applyLimit(name); + unfreezeExcessPlots(name); + final int keep = getRankBaseByName(name) + db.getExtraSlots(name); + Bukkit.getScheduler().runTask(plugin, () -> releaseExcessPlots(name, keep)); + plugin.getLogger().info("[PlotSlots] Frist abgelaufen, Abo entfernt: " + name); + } + syncToWp(); + } + void unfreezeExcessPlots(String playerName) { Bukkit.getScheduler().runTask(plugin, () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), @@ -4941,6 +5709,7 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { new BukkitRunnable() { @Override public void run() { db.renewPlotAbo(pName); + syncToWp(); } }.runTaskAsynchronously(plugin); unfreezeExcessPlots(pName); @@ -4959,13 +5728,8 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { } }.runTaskAsynchronously(plugin); new BukkitRunnable() { - @Override public void run() { - int newLimit = getRankBaseByName(pName) + db.getExtraSlots(pName); - freezeExcessPlots(pName, newLimit); - // applyLimit kümmert sich um die Permission - applyLimit(pName); - } - }.runTaskAsynchronously(plugin); + @Override public void run() { runMaintenance(); } + }.runTaskLaterAsynchronously(plugin, 40L); } }); } @@ -4979,10 +5743,13 @@ public class IngameShopSpigot extends JavaPlugin implements Listener { void onPlayerJoin(Player player) { applyLimit(player.getName()); - if (player.hasPermission("meta.frozen_excess_plots.true")) { - player.sendMessage(ChatColor.RED + "📦 Einige deiner Plots sind eingefroren!"); - player.sendMessage(ChatColor.GRAY + " Grund: Plot-Abo abgelaufen."); - player.sendMessage(ChatColor.WHITE + " Erneuern: " + ChatColor.AQUA + "viper-network.de"); + boolean flagged = player.hasPermission("meta.frozen_excess_plots.true"); + int left = db.getFrozenDaysLeft(player.getName()); + if (left >= 0) { + if (db.getPlotAboSlots(player.getName()) > 0) { unfreezeExcessPlots(player.getName()); return; } + sendFrozenNotice(player); + } else if (flagged) { + unfreezeExcessPlots(player.getName()); } } diff --git a/IngameShopSpigot/src/main/resources/config.yml b/IngameShopSpigot/src/main/resources/config.yml index bdc7acd..7150adb 100644 --- a/IngameShopSpigot/src/main/resources/config.yml +++ b/IngameShopSpigot/src/main/resources/config.yml @@ -71,4 +71,4 @@ plot-slots: member: 2 vip: 3 scout: 4 - primo: 5 \ No newline at end of file + primo: 5 diff --git a/IngameShopSpigot/src/main/resources/plugin.yml b/IngameShopSpigot/src/main/resources/plugin.yml index 8375d8e..a6a3b55 100644 --- a/IngameShopSpigot/src/main/resources/plugin.yml +++ b/IngameShopSpigot/src/main/resources/plugin.yml @@ -1,16 +1,17 @@ name: IngameShopSpigot -version: 1.2 +version: 1.3 main: de.mviper.spigot.IngameShopSpigot api-version: 1.19 depend: [Vault] -softdepend: [BCEconomy, NexEco] +softdepend: [BCEconomy, NexEco, PlotSquared] description: Verbindet den WP Ingame Shop Pro mit dem Spigot-Server author: M_Viper commands: orders: - description: Zeigt deine letzten Bestellungen im Shop an + description: Öffnet deine Kaufbelege als GUI usage: /orders + aliases: [belege] permission: ingameshop.orders flytime: description: Zeigt deine aktive verbleibende Fly-Zeit an @@ -45,8 +46,9 @@ commands: usage: /wpis permission: ingameshop.reload abo: - description: Zeigt eine Übersicht aller deiner laufenden Abonnements - usage: /abo + description: Öffnet die Abo-Verwaltung (Kündigen, Verlängern, Belege) + usage: /abo [text] + aliases: [abos] permission: ingameshop.abo flyabo: description: Zeigt deinen Fly-Abo Status und heutiges Tageslimit