From 646874e963729406bce37c90fc7b50261c8b9fba Mon Sep 17 00:00:00 2001 From: Warley Date: Wed, 9 Oct 2024 12:02:55 -0300 Subject: [PATCH] feat: top donors and reload command --- config.yml | 2 +- mensagens.yml | 6 ++ plugin.yml | 2 +- src/io/github/warleysr/autopix/AutoPix.java | 99 +++++++++++-------- src/io/github/warleysr/autopix/DonorInfo.java | 21 ++++ .../github/warleysr/autopix/OrderManager.java | 19 ++++ .../autopix/commands/AutoPixCommand.java | 64 ++++++++++-- 7 files changed, 163 insertions(+), 50 deletions(-) create mode 100644 src/io/github/warleysr/autopix/DonorInfo.java diff --git a/config.yml b/config.yml index 94f2861..4fa8215 100644 --- a/config.yml +++ b/config.yml @@ -32,7 +32,7 @@ tempos: validar: 60 lista: 30 criar-pedido: 300 - + # Mapa de pagamento mapa: nome: '&aQR code de pagamento' diff --git a/mensagens.yml b/mensagens.yml index 2b9449e..0a7f152 100644 --- a/mensagens.yml +++ b/mensagens.yml @@ -25,6 +25,11 @@ sem-ordens: '&b[AutoPix] &cNenhuma ordem PIX encontrada. Use &f/comprarpix&c.' cabecalho: '&7========== &bSuas ordens por PIX &7===========' corpo: '&7[&c{id}&7] {data} - &f{produto} (&cR${preco}&f) &7- {status}' +# Top +sem-doadores: '&b[AutoPix] &c7Ainda nao tivemos nenhum doador. Seja o primeiro!' +cabecalho-top: '&7========== &bTop Doadores por PIX &7===========' +corpo-top: '&a{doador} &f- Total: &cR${total}' + # Validar ajuda-validar: '&b[AutoPix] &cUse &f/ap validar &c.' pix-invalido: '&b[AutoPix] &cO codigo informado nao e um PIX valido.' @@ -33,6 +38,7 @@ erro-validar: '&b[AutoPix] &cOcorreu um erro ao validar. Tente novamente mais ta pix-nao-validado: '&b[AutoPix] &cNao foi possivel validar o PIX. Verifique o codigo e tente novamente.' mao-vazia: '&b[AutoPix] &cVoce precisa estar com a mao vazia para receber o item.' validando: '&b[AutoPix] &aValidando seu PIX. Aguarde um pouco.' +reload-executado: '&b[AutoPix] &aReload executado com sucesso.' # Desconto inserir-cupom: diff --git a/plugin.yml b/plugin.yml index 2b3b3b4..9cb4dd5 100644 --- a/plugin.yml +++ b/plugin.yml @@ -1,5 +1,5 @@ name: AutoPix -version: 1.0.18 +version: 1.0.19 main: io.github.warleysr.autopix.AutoPix author: warleysr api-version: 1.13 diff --git a/src/io/github/warleysr/autopix/AutoPix.java b/src/io/github/warleysr/autopix/AutoPix.java index aaa9d38..93a4cc3 100644 --- a/src/io/github/warleysr/autopix/AutoPix.java +++ b/src/io/github/warleysr/autopix/AutoPix.java @@ -7,6 +7,7 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; import io.github.warleysr.autopix.commands.APMenuCommand; import io.github.warleysr.autopix.commands.AutoPixCommand; @@ -17,6 +18,8 @@ public class AutoPix extends JavaPlugin { private static String PIX_KEY; private static String PIX_NAME; + private static BukkitTask VALIDATE_TASK; + private static BukkitTask MAPS_TASK; private static AutoPix instance; @@ -25,48 +28,80 @@ public void onEnable() { instance = this; saveDefaultConfig(); - reloadConfig(); + reloadPlugin(); - PIX_KEY = getConfig().getString("pix.chave"); - PIX_NAME = getConfig().getString("pix.nome"); + getCommand("autopix").setExecutor(new AutoPixCommand()); + getCommand("autopixmenu").setExecutor(new APMenuCommand()); + + Bukkit.getPluginManager().registerEvents(new InventoryListener(), this); + } + + public static AutoPix getInstance() { + return instance; + } + + public static String getPixKey() { + return PIX_KEY; + } + + public static String getPixName() { + return PIX_NAME; + } + + public static int getRunningVersion() { + String[] version = Bukkit.getBukkitVersion().split("-")[0].split("\\."); + int major = Integer.valueOf(version[0]); + int minor = Integer.valueOf(version[1]); - MSG.loadMessages(this); + return major * 1000 + minor; + } + + public static void reloadPlugin() { + AutoPix plugin = getInstance(); + plugin.reloadConfig(); + + PIX_KEY = plugin.getConfig().getString("pix.chave"); + PIX_NAME = plugin.getConfig().getString("pix.nome"); + + MSG.loadMessages(plugin); try { - if (!(OrderManager.startOrderManager(this))) { - setEnabled(false); + if (!(OrderManager.startOrderManager(plugin))) { + plugin.setEnabled(false); return; } } catch (SQLException e) { Bukkit.getConsoleSender().sendMessage(MSG.getMessage("erro-sql") .replace("{mensagem}", e.getMessage())); - setEnabled(false); + plugin.setEnabled(false); return; } - InventoryManager.createMenuInventory(this); - - getCommand("autopix").setExecutor(new AutoPixCommand()); - getCommand("autopixmenu").setExecutor(new APMenuCommand()); - - Bukkit.getPluginManager().registerEvents(new InventoryListener(), this); + InventoryManager.createMenuInventory(plugin); // Start async task to validate transactions automatically - if (getConfig().getBoolean("automatico.ativado")) { - int interval = getConfig().getInt("automatico.intervalo"); + if (plugin.getConfig().getBoolean("automatico.ativado")) { + if (VALIDATE_TASK != null) + VALIDATE_TASK.cancel(); - new BukkitRunnable() { + int interval = plugin.getConfig().getInt("automatico.intervalo"); + + VALIDATE_TASK = new BukkitRunnable() { @Override public void run() { - OrderManager.validatePendings(AutoPix.this); + OrderManager.validatePendings(plugin); } - }.runTaskTimerAsynchronously(this, interval * 20L, interval * 20L); + }.runTaskTimerAsynchronously(plugin, interval * 20L, interval * 20L); } // Start task to remove unpaid maps - int remInterval = getConfig().getInt("mapa.intervalo"); - new BukkitRunnable() { + if (MAPS_TASK != null) + MAPS_TASK.cancel(); + + int remInterval = plugin.getConfig().getInt("mapa.intervalo"); + + MAPS_TASK = new BukkitRunnable() { @Override public void run() { for (Player p : Bukkit.getOnlinePlayers()) { @@ -76,31 +111,11 @@ public void run() { long diff = System.currentTimeMillis() - order.getCreated().getTime(); long minutes = TimeUnit.MILLISECONDS.toMinutes(diff); - if (minutes >= getInstance().getConfig().getInt("mapa.tempo-pagar")) + if (minutes >= plugin.getConfig().getInt("mapa.tempo-pagar")) InventoryManager.removeUnpaidMaps(p); } } - }.runTaskTimerAsynchronously(this, remInterval * 20L, remInterval * 20L); - } - - public static AutoPix getInstance() { - return instance; - } - - public static String getPixKey() { - return PIX_KEY; - } - - public static String getPixName() { - return PIX_NAME; - } - - public static int getRunningVersion() { - String[] version = Bukkit.getBukkitVersion().split("-")[0].split("\\."); - int major = Integer.valueOf(version[0]); - int minor = Integer.valueOf(version[1]); - - return major * 1000 + minor; + }.runTaskTimerAsynchronously(plugin, remInterval * 20L, remInterval * 20L); } } diff --git a/src/io/github/warleysr/autopix/DonorInfo.java b/src/io/github/warleysr/autopix/DonorInfo.java new file mode 100644 index 0000000..3721191 --- /dev/null +++ b/src/io/github/warleysr/autopix/DonorInfo.java @@ -0,0 +1,21 @@ +package io.github.warleysr.autopix; + +public class DonorInfo { + + private String donor; + private float total; + + public DonorInfo(String donor, float total) { + this.donor = donor; + this.total = total; + } + + public String getDonor() { + return this.donor; + } + + public float getTotal() { + return this.total; + } + +} diff --git a/src/io/github/warleysr/autopix/OrderManager.java b/src/io/github/warleysr/autopix/OrderManager.java index 3dfdf27..9b8ddef 100644 --- a/src/io/github/warleysr/autopix/OrderManager.java +++ b/src/io/github/warleysr/autopix/OrderManager.java @@ -219,5 +219,24 @@ private static void deletePending(String id) throws SQLException { st.setString(1, id); st.executeUpdate(); } + + public static List getTopDonors(){ + ArrayList topDonors = new ArrayList<>(); + + try { + PreparedStatement st = conn.prepareStatement( + "SELECT DISTINCT player AS donor, " + + "(SELECT SUM(price) FROM autopix_orders WHERE player = donor AND pix != 'NULL') " + + "AS total FROM autopix_orders WHERE pix != 'NULL' ORDER BY total DESC LIMIT 5;"); + ResultSet rs = st.executeQuery(); + while (rs.next()) { + topDonors.add(new DonorInfo(rs.getString("donor"), rs.getFloat("total"))); + } + } catch (SQLException e) { + e.printStackTrace(); + } + + return topDonors; + } } diff --git a/src/io/github/warleysr/autopix/commands/AutoPixCommand.java b/src/io/github/warleysr/autopix/commands/AutoPixCommand.java index 87a5476..3045d06 100644 --- a/src/io/github/warleysr/autopix/commands/AutoPixCommand.java +++ b/src/io/github/warleysr/autopix/commands/AutoPixCommand.java @@ -10,6 +10,7 @@ import org.bukkit.entity.Player; import io.github.warleysr.autopix.AutoPix; +import io.github.warleysr.autopix.DonorInfo; import io.github.warleysr.autopix.MSG; import io.github.warleysr.autopix.Order; import io.github.warleysr.autopix.OrderManager; @@ -81,6 +82,53 @@ public boolean onCommand(CommandSender sender, Command cmd, String command, Stri }).start(); return true; } + else if (args[0].equalsIgnoreCase("cancelar")) { + if (args.length == 1) { + MSG.sendMessage(sender, "ajuda-cancelar"); + return false; + } + } + else if (args[0].equalsIgnoreCase("reload")) { + if (!sender.hasPermission("autopix.admin")) { + MSG.sendMessage(sender, "sem-permissao"); + return false; + } + AutoPix.reloadPlugin(); + MSG.sendMessage(sender, "reload-executado"); + return false; + } + else if (args[0].equalsIgnoreCase("top")) { + if (sender instanceof Player + && !TimeManager.canExecute(AutoPix.getInstance(), (Player) sender, "list")) + return false; + + + new Thread(() -> { + List topDonors = OrderManager.getTopDonors(); + + if (topDonors.size() == 0) { + MSG.sendMessage(sender, "sem-doadores"); + return; + } + + StringBuilder message = new StringBuilder(); + message.append(MSG.getMessage("cabecalho-top")); + message.append("\n"); + + for (DonorInfo info : topDonors) { + message.append(MSG.getMessage("corpo-top") + .replace("{doador}", info.getDonor()) + .replace("{total}", String.format("%.2f", info.getTotal()).replace('.', ',')) + ); + message.append("\n"); + } + message.append("\n"); + + sender.sendMessage(message.toString()); + + }).start(); + return false; + } } // Caso nenhum subcomando seja identificado, envia a mensagem de ajuda. @@ -97,17 +145,21 @@ public void run() { MSG.sendMessage(sender, "sem-ordens"); return; } - String msg = MSG.getMessage("cabecalho") + "\n"; - for (Order ord : orders) - msg += MSG.getMessage("corpo") + StringBuilder message = new StringBuilder(); + message.append(MSG.getMessage("cabecalho")); + message.append("\n"); + for (Order ord : orders) { + message.append(MSG.getMessage("corpo") .replace("{id}", Integer.toString(ord.getId())) .replace("{data}", DATE_FORMAT.format(new Date(ord.getCreated().getTime()))) .replace("{preco}", String.format("%.2f", ord.getPrice()).replace('.', ',')) .replace("{produto}", ord.getProduct()) - .replace("{status}", ord.isValidated() ? "\u00a7aAPROVADO" : "\u00a7ePENDENTE") + "\n"; + .replace("{status}", ord.isValidated() ? "\u00a7aAPROVADO" : "\u00a7ePENDENTE")); + message.append("\n"); + } - msg += "\n"; - sender.sendMessage(msg); + message.append("\n"); + sender.sendMessage(message.toString()); } }).start(); }