Skip to content

Commit

Permalink
feat: top donors and reload command
Browse files Browse the repository at this point in the history
  • Loading branch information
warleysr committed Oct 9, 2024
1 parent 1131f3e commit 646874e
Show file tree
Hide file tree
Showing 7 changed files with 163 additions and 50 deletions.
2 changes: 1 addition & 1 deletion config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ tempos:
validar: 60
lista: 30
criar-pedido: 300

# Mapa de pagamento
mapa:
nome: '&aQR code de pagamento'
Expand Down
6 changes: 6 additions & 0 deletions mensagens.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 <ID do PIX>&c.'
pix-invalido: '&b[AutoPix] &cO codigo informado nao e um PIX valido.'
Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion plugin.yml
Original file line number Diff line number Diff line change
@@ -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
Expand Down
99 changes: 57 additions & 42 deletions src/io/github/warleysr/autopix/AutoPix.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand All @@ -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()) {
Expand All @@ -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);
}

}
21 changes: 21 additions & 0 deletions src/io/github/warleysr/autopix/DonorInfo.java
Original file line number Diff line number Diff line change
@@ -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;
}

}
19 changes: 19 additions & 0 deletions src/io/github/warleysr/autopix/OrderManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -219,5 +219,24 @@ private static void deletePending(String id) throws SQLException {
st.setString(1, id);
st.executeUpdate();
}

public static List<DonorInfo> getTopDonors(){
ArrayList<DonorInfo> 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;
}

}
64 changes: 58 additions & 6 deletions src/io/github/warleysr/autopix/commands/AutoPixCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<DonorInfo> 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.
Expand All @@ -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();
}
Expand Down

0 comments on commit 646874e

Please sign in to comment.