From 7b89ed9c36d4e04b70eab426055b926588f775ba Mon Sep 17 00:00:00 2001 From: gab4000 Date: Fri, 29 Aug 2025 13:00:07 +0200 Subject: [PATCH 1/9] =?UTF-8?q?S=C3=A9paration=20des=20shops=20et=20entrep?= =?UTF-8?q?rises?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/fr/openmc/core/CommandsManager.java | 4 +- .../java/fr/openmc/core/ListenersManager.java | 4 +- src/main/java/fr/openmc/core/OMCPlugin.java | 4 +- ...nyManager.java => CompanyManager.java.bak} | 22 +- ...ermission.java => CorpPermission.java.bak} | 0 ...nyCommand.java => CompanyCommand.java.bak} | 6 +- .../{Company.java => Company.java.bak} | 16 +- ...ompanyOwner.java => CompanyOwner.java.bak} | 0 .../listener/CustomItemsCompanyListener.java | 45 ---- .../corporation/listener/ShopListener.java | 209 --------------- ...opMenu.java => CompanyBaltopMenu.java.bak} | 4 +- ...a => CompanyBankTransactionsMenu.java.bak} | 2 +- ...{CompanyMenu.java => CompanyMenu.java.bak} | 2 +- ...chMenu.java => CompanySearchMenu.java.bak} | 2 +- ...anageMenu.java => ShopManageMenu.java.bak} | 4 +- .../corporation/menu/shop/ShopSearchMenu.java | 168 ------------ ...Merchant.java => CompanyMerchant.java.bak} | 0 ...ission.java => CompanyPermission.java.bak} | 0 .../{DBCompany.java => DBCompany.java.bak} | 0 .../disabled/corporation/shops/ShopOwner.java | 47 ---- .../corporation/ItemsAdderIntegration.java | 2 +- .../corporation/MethodState.java | 3 +- .../corporation/commands/ShopCommand.java | 241 ++++-------------- .../corporation/data/MerchantData.java | 2 +- .../corporation/data/TransactionData.java | 2 +- .../corporation/listener/ShopListener.java | 132 ++++++++++ .../manager/PlayerShopManager.java | 61 ++--- .../manager/ShopBlocksManager.java | 8 +- .../corporation/menu}/ShopCatalogueMenu.java | 6 +- .../corporation/menu}/ShopMenu.java | 70 ++--- .../corporation/menu}/ShopSalesMenu.java | 6 +- .../corporation/menu/ShopSearchMenu.java | 79 ++++++ .../corporation/menu}/ShopStocksMenu.java | 8 +- .../corporation/models/DBShop.java | 7 +- .../corporation/models/DBShopItem.java | 12 +- .../corporation/models/DBShopSale.java | 12 +- .../corporation/models/Merchant.java | 7 +- .../corporation/models/ShopSupplier.java | 7 +- .../corporation/shops/Shop.java | 148 +---------- .../corporation/shops/ShopItem.java | 44 ++-- .../features/corporation/shops/ShopOwner.java | 30 +++ .../corporation/shops/Supply.java | 2 +- 42 files changed, 448 insertions(+), 980 deletions(-) rename src/main/java/fr/openmc/core/disabled/corporation/{manager/CompanyManager.java => CompanyManager.java.bak} (97%) rename src/main/java/fr/openmc/core/disabled/corporation/{CorpPermission.java => CorpPermission.java.bak} (100%) rename src/main/java/fr/openmc/core/disabled/corporation/commands/{CompanyCommand.java => CompanyCommand.java.bak} (99%) rename src/main/java/fr/openmc/core/disabled/corporation/company/{Company.java => Company.java.bak} (96%) rename src/main/java/fr/openmc/core/disabled/corporation/company/{CompanyOwner.java => CompanyOwner.java.bak} (100%) delete mode 100644 src/main/java/fr/openmc/core/disabled/corporation/listener/CustomItemsCompanyListener.java delete mode 100644 src/main/java/fr/openmc/core/disabled/corporation/listener/ShopListener.java rename src/main/java/fr/openmc/core/disabled/corporation/menu/company/{CompanyBaltopMenu.java => CompanyBaltopMenu.java.bak} (98%) rename src/main/java/fr/openmc/core/disabled/corporation/menu/company/{CompanyBankTransactionsMenu.java => CompanyBankTransactionsMenu.java.bak} (98%) rename src/main/java/fr/openmc/core/disabled/corporation/menu/company/{CompanyMenu.java => CompanyMenu.java.bak} (99%) rename src/main/java/fr/openmc/core/disabled/corporation/menu/company/{CompanySearchMenu.java => CompanySearchMenu.java.bak} (98%) rename src/main/java/fr/openmc/core/disabled/corporation/menu/company/{ShopManageMenu.java => ShopManageMenu.java.bak} (97%) delete mode 100644 src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopSearchMenu.java rename src/main/java/fr/openmc/core/disabled/corporation/models/{CompanyMerchant.java => CompanyMerchant.java.bak} (100%) rename src/main/java/fr/openmc/core/disabled/corporation/models/{CompanyPermission.java => CompanyPermission.java.bak} (100%) rename src/main/java/fr/openmc/core/disabled/corporation/models/{DBCompany.java => DBCompany.java.bak} (100%) delete mode 100644 src/main/java/fr/openmc/core/disabled/corporation/shops/ShopOwner.java rename src/main/java/fr/openmc/core/{disabled => features}/corporation/ItemsAdderIntegration.java (96%) rename src/main/java/fr/openmc/core/{disabled => features}/corporation/MethodState.java (74%) rename src/main/java/fr/openmc/core/{disabled => features}/corporation/commands/ShopCommand.java (52%) rename src/main/java/fr/openmc/core/{disabled => features}/corporation/data/MerchantData.java (94%) rename src/main/java/fr/openmc/core/{disabled => features}/corporation/data/TransactionData.java (69%) create mode 100644 src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java rename src/main/java/fr/openmc/core/{disabled => features}/corporation/manager/PlayerShopManager.java (53%) rename src/main/java/fr/openmc/core/{disabled => features}/corporation/manager/ShopBlocksManager.java (96%) rename src/main/java/fr/openmc/core/{disabled/corporation/menu/shop => features/corporation/menu}/ShopCatalogueMenu.java (96%) rename src/main/java/fr/openmc/core/{disabled/corporation/menu/shop => features/corporation/menu}/ShopMenu.java (79%) rename src/main/java/fr/openmc/core/{disabled/corporation/menu/shop => features/corporation/menu}/ShopSalesMenu.java (95%) create mode 100644 src/main/java/fr/openmc/core/features/corporation/menu/ShopSearchMenu.java rename src/main/java/fr/openmc/core/{disabled/corporation/menu/shop => features/corporation/menu}/ShopStocksMenu.java (96%) rename src/main/java/fr/openmc/core/{disabled => features}/corporation/models/DBShop.java (94%) rename src/main/java/fr/openmc/core/{disabled => features}/corporation/models/DBShopItem.java (91%) rename src/main/java/fr/openmc/core/{disabled => features}/corporation/models/DBShopSale.java (91%) rename src/main/java/fr/openmc/core/{disabled => features}/corporation/models/Merchant.java (91%) rename src/main/java/fr/openmc/core/{disabled => features}/corporation/models/ShopSupplier.java (94%) rename src/main/java/fr/openmc/core/{disabled => features}/corporation/shops/Shop.java (60%) rename src/main/java/fr/openmc/core/{disabled => features}/corporation/shops/ShopItem.java (83%) create mode 100644 src/main/java/fr/openmc/core/features/corporation/shops/ShopOwner.java rename src/main/java/fr/openmc/core/{disabled => features}/corporation/shops/Supply.java (92%) diff --git a/src/main/java/fr/openmc/core/CommandsManager.java b/src/main/java/fr/openmc/core/CommandsManager.java index a00dc2c2e..fdf5e09ac 100644 --- a/src/main/java/fr/openmc/core/CommandsManager.java +++ b/src/main/java/fr/openmc/core/CommandsManager.java @@ -8,6 +8,7 @@ import fr.openmc.core.commands.fun.Playtime; import fr.openmc.core.commands.utils.*; import fr.openmc.core.features.adminshop.AdminShopCommand; +import fr.openmc.core.features.corporation.commands.ShopCommand; import fr.openmc.core.features.friend.FriendCommand; import fr.openmc.core.features.friend.FriendManager; import fr.openmc.core.features.mailboxes.MailboxCommand; @@ -54,7 +55,8 @@ private static void registerCommands() { new PrivateMessageCommand(), new SocialSpyCommand(), new SettingsCommand(), - new Cooldowns() + new Cooldowns(), + new ShopCommand() ); } diff --git a/src/main/java/fr/openmc/core/ListenersManager.java b/src/main/java/fr/openmc/core/ListenersManager.java index 112aadd1e..f731e1bc3 100644 --- a/src/main/java/fr/openmc/core/ListenersManager.java +++ b/src/main/java/fr/openmc/core/ListenersManager.java @@ -2,6 +2,7 @@ import fr.openmc.api.input.ChatInput; import fr.openmc.api.input.location.ItemInteraction; +import fr.openmc.core.features.corporation.listener.ShopListener; import fr.openmc.core.features.displays.bossbar.listeners.BossbarListener; import fr.openmc.core.features.mailboxes.MailboxListener; import fr.openmc.core.features.settings.PlayerSettingsManager; @@ -34,7 +35,8 @@ public ListenersManager() { new PlayerSettingsManager(), new InteractListener(), new ItemsAddersListener(), - new TicketListener() + new TicketListener(), + new ShopListener() ); } diff --git a/src/main/java/fr/openmc/core/OMCPlugin.java b/src/main/java/fr/openmc/core/OMCPlugin.java index f74fab07d..f634acf35 100644 --- a/src/main/java/fr/openmc/core/OMCPlugin.java +++ b/src/main/java/fr/openmc/core/OMCPlugin.java @@ -111,7 +111,6 @@ public void onEnable() { if (!OMCPlugin.isUnitTestVersion()) { // Tous les trucs faits par misieur qui fonctionne à peu près new LeaderboardManager(); new MainMenu(this); - new HologramLoader(); } new AdminShopManager(); new BossbarManager(); @@ -136,6 +135,9 @@ public void loadWithItemsAdder() { new CustomUsableItemRegistry(); new MilestonesManager(); new QuestsManager(); + if (! OMCPlugin.isUnitTestVersion()) { + new HologramLoader(); + } } @Override diff --git a/src/main/java/fr/openmc/core/disabled/corporation/manager/CompanyManager.java b/src/main/java/fr/openmc/core/disabled/corporation/CompanyManager.java.bak similarity index 97% rename from src/main/java/fr/openmc/core/disabled/corporation/manager/CompanyManager.java rename to src/main/java/fr/openmc/core/disabled/corporation/CompanyManager.java.bak index 891695767..ab2d4a175 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/manager/CompanyManager.java +++ b/src/main/java/fr/openmc/core/disabled/corporation/CompanyManager.java.bak @@ -1,4 +1,4 @@ -package fr.openmc.core.disabled.corporation.manager; +package fr.openmc.core.disabled.corporation; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.DaoManager; @@ -8,22 +8,22 @@ import fr.openmc.api.hooks.ItemsAdderHook; import fr.openmc.core.CommandsManager; import fr.openmc.core.OMCPlugin; -import fr.openmc.core.disabled.corporation.models.*; import fr.openmc.core.features.city.City; import fr.openmc.core.features.city.CityManager; -import fr.openmc.core.disabled.corporation.CorpPermission; -import fr.openmc.core.disabled.corporation.MethodState; +import fr.openmc.core.features.corporation.MethodState; import fr.openmc.core.disabled.corporation.commands.CompanyCommand; -import fr.openmc.core.disabled.corporation.commands.ShopCommand; +import fr.openmc.core.features.corporation.commands.ShopCommand; import fr.openmc.core.disabled.corporation.company.Company; import fr.openmc.core.disabled.corporation.company.CompanyOwner; -import fr.openmc.core.disabled.corporation.data.MerchantData; -import fr.openmc.core.disabled.corporation.listener.CustomItemsCompanyListener; -import fr.openmc.core.disabled.corporation.listener.ShopListener; +import fr.openmc.core.features.corporation.data.MerchantData; +import fr.openmc.core.features.corporation.listener.ShopListener; import fr.openmc.core.disabled.corporation.models.*; -import fr.openmc.core.disabled.corporation.shops.Shop; -import fr.openmc.core.disabled.corporation.shops.ShopItem; -import fr.openmc.core.disabled.corporation.shops.Supply; +import fr.openmc.core.features.corporation.manager.PlayerShopManager; +import fr.openmc.core.features.corporation.manager.ShopBlocksManager; +import fr.openmc.core.features.corporation.models.*; +import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.features.corporation.shops.ShopItem; +import fr.openmc.core.features.corporation.shops.Supply; import fr.openmc.core.utils.Queue; import fr.openmc.core.utils.database.DatabaseManager; import fr.openmc.core.utils.serializer.BukkitSerializer; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/CorpPermission.java b/src/main/java/fr/openmc/core/disabled/corporation/CorpPermission.java.bak similarity index 100% rename from src/main/java/fr/openmc/core/disabled/corporation/CorpPermission.java rename to src/main/java/fr/openmc/core/disabled/corporation/CorpPermission.java.bak diff --git a/src/main/java/fr/openmc/core/disabled/corporation/commands/CompanyCommand.java b/src/main/java/fr/openmc/core/disabled/corporation/commands/CompanyCommand.java.bak similarity index 99% rename from src/main/java/fr/openmc/core/disabled/corporation/commands/CompanyCommand.java rename to src/main/java/fr/openmc/core/disabled/corporation/commands/CompanyCommand.java.bak index 9214f95a5..2d3c6dbf0 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/commands/CompanyCommand.java +++ b/src/main/java/fr/openmc/core/disabled/corporation/commands/CompanyCommand.java.bak @@ -3,11 +3,11 @@ import fr.openmc.core.features.city.City; import fr.openmc.core.features.city.CityManager; import fr.openmc.core.disabled.corporation.CorpPermission; -import fr.openmc.core.disabled.corporation.MethodState; +import fr.openmc.core.features.corporation.MethodState; import fr.openmc.core.disabled.corporation.company.Company; import fr.openmc.core.disabled.corporation.company.CompanyOwner; -import fr.openmc.core.disabled.corporation.manager.CompanyManager; -import fr.openmc.core.disabled.corporation.manager.PlayerShopManager; +import fr.openmc.core.disabled.corporation.CompanyManager; +import fr.openmc.core.features.corporation.manager.PlayerShopManager; import fr.openmc.core.disabled.corporation.menu.company.CompanyBaltopMenu; import fr.openmc.core.disabled.corporation.menu.company.CompanyMenu; import fr.openmc.core.disabled.corporation.menu.company.CompanySearchMenu; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/company/Company.java b/src/main/java/fr/openmc/core/disabled/corporation/company/Company.java.bak similarity index 96% rename from src/main/java/fr/openmc/core/disabled/corporation/company/Company.java rename to src/main/java/fr/openmc/core/disabled/corporation/company/Company.java.bak index 4f1f7c204..b5ba06ac8 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/company/Company.java +++ b/src/main/java/fr/openmc/core/disabled/corporation/company/Company.java.bak @@ -6,14 +6,14 @@ import fr.openmc.core.features.city.CityManager; import fr.openmc.core.features.city.CityPermission; import fr.openmc.core.disabled.corporation.CorpPermission; -import fr.openmc.core.disabled.corporation.MethodState; -import fr.openmc.core.disabled.corporation.data.MerchantData; -import fr.openmc.core.disabled.corporation.data.TransactionData; -import fr.openmc.core.disabled.corporation.manager.CompanyManager; -import fr.openmc.core.disabled.corporation.manager.ShopBlocksManager; +import fr.openmc.core.features.corporation.MethodState; +import fr.openmc.core.features.corporation.data.MerchantData; +import fr.openmc.core.features.corporation.data.TransactionData; +import fr.openmc.core.disabled.corporation.CompanyManager; +import fr.openmc.core.features.corporation.manager.ShopBlocksManager; import fr.openmc.core.disabled.corporation.models.DBCompany; -import fr.openmc.core.disabled.corporation.shops.Shop; -import fr.openmc.core.disabled.corporation.shops.ShopOwner; +import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.features.corporation.shops.ShopOwner; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.utils.Queue; import fr.openmc.core.utils.messages.MessageType; @@ -255,7 +255,7 @@ public boolean createShop(UUID playerUUID, Block barrel, Block cash) { return false; } - Shop newShop = new Shop(new ShopOwner(this), shopCounter); + Shop newShop = new Shop(new ShopOwner(), shopCounter); EconomyManager.withdrawBalance(whoCreated.getUniqueId(), 100); shops.add(newShop); diff --git a/src/main/java/fr/openmc/core/disabled/corporation/company/CompanyOwner.java b/src/main/java/fr/openmc/core/disabled/corporation/company/CompanyOwner.java.bak similarity index 100% rename from src/main/java/fr/openmc/core/disabled/corporation/company/CompanyOwner.java rename to src/main/java/fr/openmc/core/disabled/corporation/company/CompanyOwner.java.bak diff --git a/src/main/java/fr/openmc/core/disabled/corporation/listener/CustomItemsCompanyListener.java b/src/main/java/fr/openmc/core/disabled/corporation/listener/CustomItemsCompanyListener.java deleted file mode 100644 index 76506afc1..000000000 --- a/src/main/java/fr/openmc/core/disabled/corporation/listener/CustomItemsCompanyListener.java +++ /dev/null @@ -1,45 +0,0 @@ -package fr.openmc.core.disabled.corporation.listener; - -import dev.lone.itemsadder.api.CustomFurniture; -import dev.lone.itemsadder.api.Events.FurnitureBreakEvent; -import dev.lone.itemsadder.api.Events.FurnitureInteractEvent; -import fr.openmc.core.disabled.corporation.shops.Shop; -import fr.openmc.core.disabled.corporation.manager.ShopBlocksManager; -import fr.openmc.core.disabled.corporation.menu.shop.ShopMenu; -import org.bukkit.Location; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; - -public class CustomItemsCompanyListener implements Listener { - - @EventHandler - public void onFurnitureBreak(FurnitureBreakEvent event){ - CustomFurniture furniture = event.getFurniture(); - - if (furniture!=null && furniture.getNamespacedID().equals("omc_company:caisse") && !event.getPlayer().isOp()){ - event.setCancelled(true); - } - } - - @EventHandler - public void onFurnitureInteract(FurnitureInteractEvent e){ - if (e.getFurniture() == null) { - return; - } - - if (e.getFurniture().getNamespacedID().equals("omc_company:caisse")){ - - double x = e.getFurniture().getEntity().getLocation().getBlockX(); - double y = e.getFurniture().getEntity().getLocation().getBlockY(); - double z = e.getFurniture().getEntity().getLocation().getBlockZ(); - - Shop shop = ShopBlocksManager.getShop(new Location(e.getFurniture().getEntity().getWorld(), x, y, z)); - if (shop == null) { - return; - } - e.setCancelled(true); - ShopMenu menu = new ShopMenu(e.getPlayer(), shop, 0); - menu.open(); - } - } -} diff --git a/src/main/java/fr/openmc/core/disabled/corporation/listener/ShopListener.java b/src/main/java/fr/openmc/core/disabled/corporation/listener/ShopListener.java deleted file mode 100644 index 992069b16..000000000 --- a/src/main/java/fr/openmc/core/disabled/corporation/listener/ShopListener.java +++ /dev/null @@ -1,209 +0,0 @@ -package fr.openmc.core.disabled.corporation.listener; - -import fr.openmc.core.disabled.corporation.CorpPermission; -import fr.openmc.core.disabled.corporation.company.Company; -import fr.openmc.core.disabled.corporation.manager.CompanyManager; -import fr.openmc.core.disabled.corporation.manager.ShopBlocksManager; -import fr.openmc.core.disabled.corporation.menu.shop.ShopMenu; -import fr.openmc.core.disabled.corporation.shops.Shop; -import fr.openmc.core.utils.messages.MessageType; -import fr.openmc.core.utils.messages.MessagesManager; -import fr.openmc.core.utils.messages.Prefix; -import net.kyori.adventure.text.Component; -import org.bukkit.Material; -import org.bukkit.Tag; -import org.bukkit.block.Barrel; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockExplodeEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryDragEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.persistence.PersistentDataType; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -public class ShopListener implements Listener { - - private final Map inShopBarrel = new HashMap<>(); - - @EventHandler - public void onShopBreak(BlockBreakEvent event) { - if (ShopBlocksManager.getShop(event.getBlock().getLocation()) != null) { - event.setCancelled(true); - } - } - - @EventHandler - public void onShopExplode(BlockExplodeEvent event){ - event.blockList().removeIf(block -> ShopBlocksManager.getShop(block.getLocation()) != null); - } - - @EventHandler - public void onEntityExplode(EntityExplodeEvent event) { - event.blockList().removeIf(block -> ShopBlocksManager.getShop(block.getLocation()) != null); - } - - @EventHandler - public void onShopClick(PlayerInteractEvent event) { - if (event.getClickedBlock() == null) { - return; - } - - // Check if the clicked block is a sign with tags - // Instead of getting the entire state of the block - // This is much faster and avoids unnecessary overhead - if (!Tag.SIGNS.isTagged(event.getClickedBlock().getType())) - return; - - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) - return; - - Shop shop = ShopBlocksManager.getShop(event.getClickedBlock().getLocation()); - if (shop == null) - return; - - event.setCancelled(true); - ShopMenu menu = new ShopMenu(event.getPlayer(), shop, 0); - menu.open(); - } - - @EventHandler - public void onInteractWithBlock(PlayerInteractEvent e) { - Block block = e.getClickedBlock(); - if (block != null && block.getType() == Material.BARREL) { - Shop shop = ShopBlocksManager.getShop(block.getLocation()); - boolean isShop = shop!=null; - if (isShop){ - Company company = CompanyManager.getCompany(e.getPlayer().getUniqueId()); - if (company==null){ - if (shop.getOwner().getPlayer()==null){ - e.setCancelled(true); - return; - } - if (!shop.getOwner().getPlayer().equals(e.getPlayer().getUniqueId())){ - e.setCancelled(true); - return; - } - } else { - if (!company.hasShop(shop.getUuid())){ - e.setCancelled(true); - MessagesManager.sendMessage(e.getPlayer(), Component.text("Tu n'es pas dans l'entrprise possédant ce shop"), Prefix.SHOP, MessageType.INFO, false); - return; - } - - if (!company.hasPermission(e.getPlayer().getUniqueId(), CorpPermission.SUPPLY)){ - e.setCancelled(true); - MessagesManager.sendMessage(e.getPlayer(), Component.text("Tu n'as pas la permission de réapprovisionner le shop"), Prefix.SHOP, MessageType.INFO, false); - return; - } - } - } - inShopBarrel.put(e.getPlayer().getUniqueId(), isShop); - } - } - - @EventHandler - public void onShopPutItem(InventoryClickEvent e) { - UUID playerUUID = e.getWhoClicked().getUniqueId(); - if (inShopBarrel.getOrDefault(playerUUID, false)) { - Player player = (Player) e.getWhoClicked(); - Company company = CompanyManager.getCompany(playerUUID); - if (company!=null){ - if (!company.hasPermission(playerUUID, CorpPermission.SUPPLY)){ - MessagesManager.sendMessage(player, Component.text("Vous n'avez pas la permission de réapprovisionner les shops dans l'entreprise"), Prefix.SHOP, MessageType.INFO, false); - player.closeInventory(); - return; - } - } - - Inventory clickedInventory = e.getClickedInventory(); - - if (clickedInventory == null) return; - - if (clickedInventory.getHolder(false) instanceof Barrel) { - ItemStack currentItem = e.getCurrentItem(); - ItemStack cursorItem = e.getCursor(); - - if (e.isShiftClick() && isValidItem(currentItem)) { - removeSupplierKey(currentItem); - } - // Vérifier si un item est retiré - else if (e.getAction().name().contains("PICKUP") && isValidItem(currentItem)) { - removeSupplierKey(currentItem); - } - else if (e.getAction().name().contains("SWAP") && isValidItem(currentItem)) { - removeSupplierKey(currentItem); - } - // Vérifier si un item est placé avec la souris - else if (e.getAction().name().contains("PLACE") && isValidItem(cursorItem)) { - setSupplierKey(cursorItem, player.getUniqueId().toString()); - } - } else if (clickedInventory.getHolder(false) instanceof Player) { - ItemStack currentItem = e.getCurrentItem(); - - if (e.isShiftClick() && !e.getAction().name().contains("SWAP") && isValidItem(currentItem)) { - setSupplierKey(currentItem, player.getUniqueId().toString()); - } - } - } - } - - @EventHandler - public void onItemDrag(InventoryDragEvent e) { - UUID playerUUID = e.getWhoClicked().getUniqueId(); - if (inShopBarrel.getOrDefault(playerUUID, false) && e.getInventory().getHolder(false) instanceof Barrel) { - ItemStack item = e.getOldCursor(); - if (isValidItem(item)) { - removeSupplierKey(item); - } - } - } - - /** - * check if an item is valid - * - * @param item the item to check - * @return true if it's a valid item - */ - private boolean isValidItem(ItemStack item) { - return item != null && item.getType() != Material.AIR; - } - - /** - * add the SUPPLIER_KEY to an item - * - * @param item the item to add the key - * @param uuid the uuid of the player ( the supplier_key ) - */ - private void setSupplierKey(ItemStack item, String uuid) { - ItemMeta meta = item.getItemMeta(); - if (meta != null) { - meta.getPersistentDataContainer().set(CompanyManager.SUPPLIER_KEY, PersistentDataType.STRING, uuid); - item.setItemMeta(meta); - } - } - - /** - * remove the SUPPLIER_KEY to an item - * - * @param item the item to remove the key - */ - private void removeSupplierKey(ItemStack item) { - ItemMeta meta = item.getItemMeta(); - if (meta != null && meta.getPersistentDataContainer().has(CompanyManager.SUPPLIER_KEY)) { - meta.getPersistentDataContainer().remove(CompanyManager.SUPPLIER_KEY); - item.setItemMeta(meta); - } - } -} diff --git a/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyBaltopMenu.java b/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyBaltopMenu.java.bak similarity index 98% rename from src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyBaltopMenu.java rename to src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyBaltopMenu.java.bak index a7a4934b2..692731cb3 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyBaltopMenu.java +++ b/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyBaltopMenu.java.bak @@ -7,8 +7,8 @@ import fr.openmc.api.menulib.utils.ItemUtils; import fr.openmc.core.features.city.CityPermission; import fr.openmc.core.disabled.corporation.company.Company; -import fr.openmc.core.disabled.corporation.data.MerchantData; -import fr.openmc.core.disabled.corporation.manager.CompanyManager; +import fr.openmc.core.features.corporation.data.MerchantData; +import fr.openmc.core.disabled.corporation.CompanyManager; import fr.openmc.core.features.economy.EconomyManager; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyBankTransactionsMenu.java b/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyBankTransactionsMenu.java.bak similarity index 98% rename from src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyBankTransactionsMenu.java rename to src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyBankTransactionsMenu.java.bak index e15dbad2b..f0616daac 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyBankTransactionsMenu.java +++ b/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyBankTransactionsMenu.java.bak @@ -7,7 +7,7 @@ import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.api.menulib.utils.StaticSlots; import fr.openmc.core.disabled.corporation.company.Company; -import fr.openmc.core.disabled.corporation.data.TransactionData; +import fr.openmc.core.features.corporation.data.TransactionData; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.items.CustomItemRegistry; import org.bukkit.Bukkit; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyMenu.java b/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyMenu.java.bak similarity index 99% rename from src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyMenu.java rename to src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyMenu.java.bak index 1f15ab61f..3c2787d9a 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyMenu.java +++ b/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanyMenu.java.bak @@ -7,7 +7,7 @@ import fr.openmc.api.menulib.utils.ItemUtils; import fr.openmc.api.menulib.utils.StaticSlots; import fr.openmc.core.disabled.corporation.company.Company; -import fr.openmc.core.disabled.corporation.data.MerchantData; +import fr.openmc.core.features.corporation.data.MerchantData; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.items.CustomItemRegistry; import org.bukkit.Bukkit; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanySearchMenu.java b/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanySearchMenu.java.bak similarity index 98% rename from src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanySearchMenu.java rename to src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanySearchMenu.java.bak index 3a1187a00..6d1585b47 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanySearchMenu.java +++ b/src/main/java/fr/openmc/core/disabled/corporation/menu/company/CompanySearchMenu.java.bak @@ -7,7 +7,7 @@ import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.api.menulib.utils.StaticSlots; import fr.openmc.core.disabled.corporation.company.Company; -import fr.openmc.core.disabled.corporation.manager.CompanyManager; +import fr.openmc.core.disabled.corporation.CompanyManager; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.items.CustomItemRegistry; import org.bukkit.Material; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/menu/company/ShopManageMenu.java b/src/main/java/fr/openmc/core/disabled/corporation/menu/company/ShopManageMenu.java.bak similarity index 97% rename from src/main/java/fr/openmc/core/disabled/corporation/menu/company/ShopManageMenu.java rename to src/main/java/fr/openmc/core/disabled/corporation/menu/company/ShopManageMenu.java.bak index c8f5c1a28..143992ae1 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/menu/company/ShopManageMenu.java +++ b/src/main/java/fr/openmc/core/disabled/corporation/menu/company/ShopManageMenu.java.bak @@ -6,8 +6,8 @@ import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.api.menulib.utils.StaticSlots; import fr.openmc.core.disabled.corporation.company.Company; -import fr.openmc.core.disabled.corporation.manager.ShopBlocksManager; -import fr.openmc.core.disabled.corporation.shops.Shop; +import fr.openmc.core.features.corporation.manager.ShopBlocksManager; +import fr.openmc.core.features.corporation.shops.Shop; import fr.openmc.core.items.CustomItemRegistry; import net.kyori.adventure.text.Component; import org.bukkit.Material; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopSearchMenu.java b/src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopSearchMenu.java deleted file mode 100644 index b71488f9d..000000000 --- a/src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopSearchMenu.java +++ /dev/null @@ -1,168 +0,0 @@ -package fr.openmc.core.disabled.corporation.menu.shop; - -import dev.lone.itemsadder.api.FontImages.FontImageWrapper; -import fr.openmc.api.input.DialogInput; -import fr.openmc.api.menulib.PaginatedMenu; -import fr.openmc.api.menulib.utils.InventorySize; -import fr.openmc.api.menulib.utils.ItemBuilder; -import fr.openmc.api.menulib.utils.StaticSlots; -import fr.openmc.core.disabled.corporation.company.Company; -import fr.openmc.core.disabled.corporation.manager.CompanyManager; -import fr.openmc.core.disabled.corporation.manager.ShopBlocksManager; -import fr.openmc.core.disabled.corporation.shops.Shop; -import fr.openmc.core.items.CustomItemRegistry; -import fr.openmc.core.utils.ItemUtils; -import fr.openmc.core.utils.messages.MessageType; -import fr.openmc.core.utils.messages.MessagesManager; -import fr.openmc.core.utils.messages.Prefix; -import net.kyori.adventure.text.Component; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static fr.openmc.core.utils.InputUtils.MAX_LENGTH; - -public class ShopSearchMenu extends PaginatedMenu { - - public ShopSearchMenu(Player owner) { - super(owner); - } - - @Override - public @NotNull InventorySize getInventorySize() { - return InventorySize.LARGEST; - } - - @Override - public int getSizeOfItems() { - return getItems().size(); - } - - @Override - public @Nullable Material getBorderMaterial() { - return null; - } - - @Override - public @NotNull List getStaticSlots() { - return StaticSlots.getStandardSlots(getInventorySize()); - } - - @Override - public List getItems() { - List items = new java.util.ArrayList<>(); - - for (Shop shops : CompanyManager.shops){ - - if (shops==null){continue;} - - List loc = new ArrayList<>(); - double x = ShopBlocksManager.getMultiblock(shops.getUuid()).stockBlock().getBlockX(); - double y = ShopBlocksManager.getMultiblock(shops.getUuid()).stockBlock().getBlockY(); - double z = ShopBlocksManager.getMultiblock(shops.getUuid()).stockBlock().getBlockZ(); - - loc.add(Component.text("§lLocation : §r x : " + x + " y : " + y + " z : " + z)); - - items.add(new ItemBuilder(this, ItemUtils.getPlayerHead(getOwner().getUniqueId()) ,itemMeta -> { - itemMeta.setDisplayName("§lshop :§r" + shops.getName()); - itemMeta.lore(loc); - })); - } - - return items; - } - - @Override - public Map getButtons() { - Map buttons = new HashMap<>(); - buttons.put(49, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_cancel").getBest(), itemMeta -> itemMeta.setDisplayName("§7Fermer")) - .setCloseButton()); - ItemBuilder nextPageButton = new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_next_orange").getBest(), itemMeta -> itemMeta.setDisplayName("§aPage suivante")); - ItemBuilder searchButton = new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_search").getBest().getType(), itemMeta -> - itemMeta.setDisplayName("Rechercher")); - if ((getPage() != 0 && !isLastPage()) || !CompanyManager.getShops().isEmpty()) { - buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.setDisplayName("§cPage précédente")) - .setPreviousPageButton()); - buttons.put(50, nextPageButton.setNextPageButton()); - buttons.put(45, searchButton.setOnClick(inventoryClick -> { - DialogInput.send(getOwner(), Component.text("Entrez le nom du shop ou bien du joueur pour le rechercher"), MAX_LENGTH, input -> { - boolean shopFind = false; - - for (Shop shop : CompanyManager.shops) { - double x = ShopBlocksManager.getMultiblock(shop.getUuid()).stockBlock().getBlockX(); - double y = ShopBlocksManager.getMultiblock(shop.getUuid()).stockBlock().getBlockY(); - double z = ShopBlocksManager.getMultiblock(shop.getUuid()).stockBlock().getBlockZ(); - - if (shop.getName().contains(input)) { - MessagesManager.sendMessage(getOwner(), Component.text("§lLocation du shop §a" + shop.getName() + " : §r x : " + x + " y : " + y + " z : " + z), Prefix.SHOP, MessageType.INFO, false); - shopFind = true; - break; - } - Player player = Bukkit.getPlayer(input); - if (player == null) continue; - if (shop.getOwner().isCompany()) { - Company company = shop.getOwner().getCompany(); - if (company.getAllMembers().contains(player.getUniqueId())) { - MessagesManager.sendMessage(getOwner(), Component.text("§lLocation du shop §a" + shop.getName() + " : §r x : " + x + " y : " + y + " z : " + z), Prefix.SHOP, MessageType.INFO, false); - shopFind = true; - break; - } - } - if (shop.getOwner().isPlayer()) { - Player shopPlayer = Bukkit.getPlayer(shop.getOwner().getPlayer()); - if (shopPlayer == null) { - continue; - } - if (shopPlayer.equals(player)) { - MessagesManager.sendMessage(getOwner(), Component.text("§lLocation du shop §a" + shop.getName() + " : §r x : " + x + " y : " + y + " z : " + z), Prefix.SHOP, MessageType.INFO, false); - shopFind = true; - break; - } - } - } - - if (!shopFind) { - MessagesManager.sendMessage(getOwner(), Component.text("§cAucun shop trouvé !"), Prefix.SHOP, MessageType.INFO, false); - } - - }); - })); - } - return buttons; - } - - @Override - public @NotNull String getName() { - return "§l§6Menu de Recherche de Shop"; - } - - @Override - public String getTexture() { - return FontImageWrapper.replaceFontImages("§r§f:offset_-11::large_shop_menu:"); - } - - @Override - public void onInventoryClick(InventoryClickEvent inventoryClickEvent) { - - } - - @Override - public void onClose(InventoryCloseEvent event) { - - } - - @Override - public List getTakableSlot() { - return List.of(); - } -} diff --git a/src/main/java/fr/openmc/core/disabled/corporation/models/CompanyMerchant.java b/src/main/java/fr/openmc/core/disabled/corporation/models/CompanyMerchant.java.bak similarity index 100% rename from src/main/java/fr/openmc/core/disabled/corporation/models/CompanyMerchant.java rename to src/main/java/fr/openmc/core/disabled/corporation/models/CompanyMerchant.java.bak diff --git a/src/main/java/fr/openmc/core/disabled/corporation/models/CompanyPermission.java b/src/main/java/fr/openmc/core/disabled/corporation/models/CompanyPermission.java.bak similarity index 100% rename from src/main/java/fr/openmc/core/disabled/corporation/models/CompanyPermission.java rename to src/main/java/fr/openmc/core/disabled/corporation/models/CompanyPermission.java.bak diff --git a/src/main/java/fr/openmc/core/disabled/corporation/models/DBCompany.java b/src/main/java/fr/openmc/core/disabled/corporation/models/DBCompany.java.bak similarity index 100% rename from src/main/java/fr/openmc/core/disabled/corporation/models/DBCompany.java rename to src/main/java/fr/openmc/core/disabled/corporation/models/DBCompany.java.bak diff --git a/src/main/java/fr/openmc/core/disabled/corporation/shops/ShopOwner.java b/src/main/java/fr/openmc/core/disabled/corporation/shops/ShopOwner.java deleted file mode 100644 index bdd5493d4..000000000 --- a/src/main/java/fr/openmc/core/disabled/corporation/shops/ShopOwner.java +++ /dev/null @@ -1,47 +0,0 @@ -package fr.openmc.core.disabled.corporation.shops; - -import fr.openmc.core.disabled.corporation.company.Company; -import lombok.Getter; - -import java.util.UUID; - -@Getter -public class ShopOwner { - - private final Company company; - private final UUID player; - - /** - * ShopOwner for a company or a player - * @param company to set a company as the owner - */ - - public ShopOwner(Company company) { - this.company = company; - this.player = null; - } - - /** - * ShopOwner for a company or a player - * @param owner to set a player as the owner - */ - public ShopOwner(UUID owner) { - this.company = null; - this.player = owner; - } - - /** - * know if it's a company - */ - public boolean isCompany() { - return company != null; - } - - /** - * know if it's a player - */ - public boolean isPlayer() { - return player != null; - } - -} diff --git a/src/main/java/fr/openmc/core/disabled/corporation/ItemsAdderIntegration.java b/src/main/java/fr/openmc/core/features/corporation/ItemsAdderIntegration.java similarity index 96% rename from src/main/java/fr/openmc/core/disabled/corporation/ItemsAdderIntegration.java rename to src/main/java/fr/openmc/core/features/corporation/ItemsAdderIntegration.java index 543bfbc51..23ae6a3e6 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/ItemsAdderIntegration.java +++ b/src/main/java/fr/openmc/core/features/corporation/ItemsAdderIntegration.java @@ -1,4 +1,4 @@ -package fr.openmc.core.disabled.corporation; +package fr.openmc.core.features.corporation; import dev.lone.itemsadder.api.CustomFurniture; import dev.lone.itemsadder.api.CustomStack; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/MethodState.java b/src/main/java/fr/openmc/core/features/corporation/MethodState.java similarity index 74% rename from src/main/java/fr/openmc/core/disabled/corporation/MethodState.java rename to src/main/java/fr/openmc/core/features/corporation/MethodState.java index daecc69cf..9df6ca207 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/MethodState.java +++ b/src/main/java/fr/openmc/core/features/corporation/MethodState.java @@ -1,4 +1,4 @@ -package fr.openmc.core.disabled.corporation; +package fr.openmc.core.features.corporation; import lombok.Getter; @@ -10,5 +10,4 @@ public enum MethodState { FAILURE, ESCAPE, SPECIAL - } diff --git a/src/main/java/fr/openmc/core/disabled/corporation/commands/ShopCommand.java b/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java similarity index 52% rename from src/main/java/fr/openmc/core/disabled/corporation/commands/ShopCommand.java rename to src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java index ed1d099e4..3d4e382cf 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/commands/ShopCommand.java +++ b/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java @@ -1,17 +1,12 @@ -package fr.openmc.core.disabled.corporation.commands; - - -import fr.openmc.core.disabled.corporation.CorpPermission; -import fr.openmc.core.disabled.corporation.MethodState; -import fr.openmc.core.disabled.corporation.company.Company; -import fr.openmc.core.disabled.corporation.manager.CompanyManager; -import fr.openmc.core.disabled.corporation.manager.PlayerShopManager; -import fr.openmc.core.disabled.corporation.menu.company.ShopManageMenu; -import fr.openmc.core.disabled.corporation.menu.shop.ShopMenu; -import fr.openmc.core.disabled.corporation.menu.shop.ShopSearchMenu; -import fr.openmc.core.disabled.corporation.shops.Shop; -import fr.openmc.core.disabled.corporation.shops.ShopItem; -import fr.openmc.core.disabled.corporation.shops.Supply; +package fr.openmc.core.features.corporation.commands; + +import fr.openmc.core.features.corporation.MethodState; +import fr.openmc.core.features.corporation.manager.PlayerShopManager; +import fr.openmc.core.features.corporation.menu.ShopMenu; +import fr.openmc.core.features.corporation.menu.ShopSearchMenu; +import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.features.corporation.shops.ShopItem; +import fr.openmc.core.features.corporation.shops.Supply; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.utils.ItemUtils; import fr.openmc.core.utils.messages.MessageType; @@ -30,18 +25,21 @@ import java.util.Objects; import java.util.UUID; -@Command({"shop", "shops"}) +@Command("shop") @Description("Manage shops") @CommandPermission("omc.commands.shop") public class ShopCommand { - @DefaultFor("~") - public void onCommand(Player player) { - boolean isInCompany = CompanyManager.isInCompany(player.getUniqueId()); - if (isInCompany) { - ShopManageMenu shopManageMenu = new ShopManageMenu(player, CompanyManager.getCompany(player.getUniqueId())); - shopManageMenu.open(); + @Subcommand("manage") + @Description("Manage a shop") + public static void manageShop(Player player) { + + if (!PlayerShopManager.hasShop(player.getUniqueId())) { + MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.INFO, false); + return; } + ShopMenu shopMenu = new ShopMenu(player, PlayerShopManager.getPlayerShop(player.getUniqueId()), 0); + shopMenu.open(); } @Subcommand("help") @@ -61,84 +59,19 @@ public void help(Player player) { Prefix.ENTREPRISE, MessageType.INFO, false); } - @Subcommand("create") - @Description("Create a shop") - public void createShop(Player player) { - boolean isInCompany = CompanyManager.isInCompany(player.getUniqueId()); - Block targetBlock = player.getTargetBlockExact(5); - if (targetBlock == null || targetBlock.getType() != Material.BARREL) { - MessagesManager.sendMessage(player, Component.text("§cVous devez regarder un tonneau pour créer un shop"), Prefix.SHOP, MessageType.INFO, false); - return; - } - Block aboveBlock = Objects.requireNonNull(targetBlock.getLocation().getWorld()).getBlockAt(targetBlock.getLocation().clone().add(0, 1, 0)); - if (aboveBlock.getType() != Material.AIR) { - MessagesManager.sendMessage(player, Component.text("§cVous devez liberer de l'espace au dessus de votre tonneau pour créer un shop"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (isInCompany) { - Company company = CompanyManager.getCompany(player.getUniqueId()); - if (!company.hasPermission(player.getUniqueId(), CorpPermission.CREATESHOP)) { - MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas la permission pour créer un shop dans l'entreprise"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (!company.createShop(player.getUniqueId(), targetBlock, aboveBlock)) { - MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas assez d'argent dans la banque de votre entreprise pour créer un shop (100" + EconomyManager.getEconomyIcon() + ")"), Prefix.SHOP, MessageType.INFO, false); - return; - } - MessagesManager.sendMessage(player, Component.text("§6[Shop] §c -100" + EconomyManager.getEconomyIcon() + " sur la banque de l'entreprise"), Prefix.SHOP, MessageType.SUCCESS, false); - MessagesManager.sendMessage(player, Component.text("§aUn shop a bien été crée pour votre entreprise !"), Prefix.SHOP, MessageType.SUCCESS, false); - return; - } - if (PlayerShopManager.hasShop(player.getUniqueId())) { - MessagesManager.sendMessage(player, Component.text("§cVous avez déjà un shop"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (!PlayerShopManager.createShop(player.getUniqueId(), targetBlock, aboveBlock, null)) { - MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas assez d'argent pour créer un shop (500" + EconomyManager.getEconomyIcon() + ")"), Prefix.SHOP, MessageType.INFO, false); - return; - } - MessagesManager.sendMessage(player, Component.text("§6[Shop] §c -500" + EconomyManager.getEconomyIcon() +" sur votre compte personnel"), Prefix.SHOP, MessageType.SUCCESS, false); - MessagesManager.sendMessage(player, Component.text("§aVous avez bien crée un shop !"), Prefix.SHOP, MessageType.SUCCESS, false); + @DefaultFor("~") + public void onCommand(Player player) { + } @Subcommand("sell") @Description("Sell an item in your shop") public void sellItem(Player player, @Named("price") double price) { - boolean isInCompany = CompanyManager.isInCompany(player.getUniqueId()); - if (price<=0){ MessagesManager.sendMessage(player, Component.text("§cVeuillez mettre un prix supérieur à zéro !"), Prefix.SHOP, MessageType.INFO, false); return; } - if (isInCompany) { - UUID shopUUID = Shop.getShopPlayerLookingAt(player, false); - if (shopUUID == null) { - MessagesManager.sendMessage(player, Component.text("§cShop non reconnu"), Prefix.SHOP, MessageType.INFO, false); - return; - } - Shop shop = CompanyManager.getCompany(player.getUniqueId()).getShop(shopUUID); - if (shop == null) { - MessagesManager.sendMessage(player, Component.text("§cCe shop n'appartient pas à votre entreprise"), Prefix.SHOP, MessageType.INFO, false); - return; - } - - if (!CompanyManager.getCompany(player.getUniqueId()).hasPermission(player.getUniqueId(), CorpPermission.SELLER)) { - MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas l'autorisation de vendre un item dans ce shop de l'entrprise"), Prefix.SHOP, MessageType.INFO, false); - return; - } - - ItemStack item = player.getInventory().getItemInMainHand(); - boolean itemThere = shop.addItem(item, price, 1, null); - - if (itemThere) { - MessagesManager.sendMessage(player, Component.text("§cCet item est déjà dans le shop"), Prefix.SHOP, MessageType.INFO, false); - return; - } - - MessagesManager.sendMessage(player, Component.text("§aL'item a bien été ajouté au shop !"), Prefix.SHOP, MessageType.SUCCESS, false); - return; - } if (!PlayerShopManager.hasShop(player.getUniqueId())) { MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.INFO, false); return; @@ -157,63 +90,36 @@ public void sellItem(Player player, @Named("price") double price) { MessagesManager.sendMessage(player, Component.text("§aL'item a bien été ajouté au shop !"), Prefix.SHOP, MessageType.SUCCESS, false); } + @Subcommand("create") + @Description("Create a shop") + public void createShop(Player player) { + Block targetBlock = player.getTargetBlockExact(5); + if (targetBlock == null || targetBlock.getType() != Material.BARREL) { + MessagesManager.sendMessage(player, Component.text("§cVous devez regarder un tonneau pour créer un shop"), Prefix.SHOP, MessageType.INFO, false); + return; + } + Block aboveBlock = Objects.requireNonNull(targetBlock.getLocation().getWorld()).getBlockAt(targetBlock.getLocation().clone().add(0, 1, 0)); + if (aboveBlock.getType() != Material.AIR) { + MessagesManager.sendMessage(player, Component.text("§cVous devez liberer de l'espace au dessus de votre tonneau pour créer un shop"), Prefix.SHOP, MessageType.INFO, false); + return; + } + + if (PlayerShopManager.hasShop(player.getUniqueId())) { + MessagesManager.sendMessage(player, Component.text("§cVous avez déjà un shop"), Prefix.SHOP, MessageType.INFO, false); + return; + } + if (!PlayerShopManager.createShop(player.getUniqueId(), targetBlock, aboveBlock, null)) { + MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas assez d'argent pour créer un shop (500" + EconomyManager.getEconomyIcon() + ")"), Prefix.SHOP, MessageType.INFO, false); + return; + } + MessagesManager.sendMessage(player, Component.text("§6[Shop] §c -500" + EconomyManager.getEconomyIcon() +" sur votre compte personnel"), Prefix.SHOP, MessageType.SUCCESS, false); + MessagesManager.sendMessage(player, Component.text("§aVous avez bien crée un shop !"), Prefix.SHOP, MessageType.SUCCESS, false); + } + @Subcommand("unsell") @Description("Unsell an item in your shop") public void unsellItem(Player player, @Named("item number") int itemIndex) { - boolean isInCompany = CompanyManager.isInCompany(player.getUniqueId()); - if (isInCompany) { - UUID shopUUID = Shop.getShopPlayerLookingAt(player, false); - if (shopUUID == null) { - MessagesManager.sendMessage(player, Component.text("§cShop non reconnu"), Prefix.SHOP, MessageType.INFO, false); - return; - } - - Shop shop = CompanyManager.getCompany(player.getUniqueId()).getShop(shopUUID); - if (shop == null) { - MessagesManager.sendMessage(player, Component.text("§cCe shop n'appartient pas à votre entreprise"), Prefix.SHOP, MessageType.INFO, false); - return; - } - - if (!CompanyManager.getCompany(player.getUniqueId()).hasPermission(player.getUniqueId(), CorpPermission.SELLER)) { - MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas l'autorisation de retirer un item en vente dans ce shop de l'entrprise"), Prefix.SHOP, MessageType.INFO, false); - } - - if (itemIndex < 1 || itemIndex >= shop.getItems().size() + 1) { - MessagesManager.sendMessage(player, Component.text("§cCet item n'est pas dans le shop"), Prefix.SHOP, MessageType.INFO, false); - return; - } - - ShopItem item = shop.getItem(itemIndex - 1); - if (item == null) { - MessagesManager.sendMessage(player, Component.text("§cCet item n'est pas dans le shop"), Prefix.SHOP, MessageType.INFO, false); - return; - } - - if (CompanyManager.getCompany(player.getUniqueId()).hasPermission(player.getUniqueId(), CorpPermission.OWNER)){ - recoverStock(player, item, shop); - return; - } - - if (shop.isSupplier(player.getUniqueId()) ){ - int toTake = shop.recoverItemOf(item, player); - - if (toTake == 0) return; - - if (item.getAmount() >= 0) { - ItemStack toGive = item.getItem().clone(); - toGive.setAmount(toTake); - player.getInventory().addItem(toGive); - if (item.getAmount() > 0){ - MessagesManager.sendMessage(player, Component.text("§6Vous avez récupéré §a" + toTake + "§6 dans le stock de cet item"), Prefix.SHOP, MessageType.SUCCESS, false); - } else { - MessagesManager.sendMessage(player, Component.text("§6Vous avez récupéré le stock restant de cet item"), Prefix.SHOP, MessageType.SUCCESS, false); - } - return; - } - } - - return; - } + if (!PlayerShopManager.hasShop(player.getUniqueId())) { MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.INFO, false); return; @@ -241,41 +147,13 @@ public void unsellItem(Player player, @Named("item number") int itemIndex) { @Subcommand("delete") @Description("Delete a shop") public void deleteShop(Player player) { - boolean isInCompany = CompanyManager.isInCompany(player.getUniqueId()); + UUID shopUUID = Shop.getShopPlayerLookingAt(player, false); if (shopUUID == null) { MessagesManager.sendMessage(player, Component.text("§cShop non reconnu"), Prefix.SHOP, MessageType.INFO, false); return; } - if (isInCompany) { - Shop shop = CompanyManager.getCompany(player.getUniqueId()).getShop(shopUUID); - if (shop == null) { - MessagesManager.sendMessage(player, Component.text("§cCe shop n'appartient pas à votre entreprise"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (!CompanyManager.getCompany(player.getUniqueId()).hasPermission(player.getUniqueId(), CorpPermission.DELETESHOP)) { - MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas la permission pour supprimer un shop de l'entreprise"), Prefix.SHOP, MessageType.INFO, false); - return; - } - MethodState deleteState = CompanyManager.getCompany(player.getUniqueId()).deleteShop(player, shop.getUuid()); - if (deleteState == MethodState.ERROR) { - MessagesManager.sendMessage(player, Component.text("§cCe shop n'existe pas dans votre entreprise"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (deleteState == MethodState.WARNING) { - MessagesManager.sendMessage(player, Component.text("§cCe shop n'est pas vide"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (deleteState == MethodState.SPECIAL) { - MessagesManager.sendMessage(player, Component.text("§cIl vous faut au minimum le nombre d'argent remboursable pour supprimer un shop et obtenir un remboursement dans la banque de votre entreprise"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (deleteState == MethodState.ESCAPE) { - MessagesManager.sendMessage(player, Component.text("§cCaisse introuvable (appelez un admin)"), Prefix.SHOP, MessageType.INFO, false); - } - MessagesManager.sendMessage(player, Component.text("§a" + shop.getName() + " supprimé !"), Prefix.SHOP, MessageType.SUCCESS, false); - MessagesManager.sendMessage(player, Component.text("§6[Shop] §a +75" + EconomyManager.getEconomyIcon() + " de remboursés sur la banque de l'entreprise"), Prefix.SHOP, MessageType.SUCCESS, false); - } + if (!PlayerShopManager.hasShop(player.getUniqueId())) { MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.INFO, false); return; @@ -293,23 +171,6 @@ public void deleteShop(Player player) { MessagesManager.sendMessage(player, Component.text("§6[Shop] §a +400" + EconomyManager.getEconomyIcon() + " de remboursés sur votre compte personnel"), Prefix.SHOP, MessageType.SUCCESS, false); } - @Subcommand("manage") - @Description("Manage a shop") - public static void manageShop(Player player) { - boolean isInCompany = CompanyManager.isInCompany(player.getUniqueId()); - if (isInCompany) { - ShopManageMenu shopManageMenu = new ShopManageMenu(player, CompanyManager.getCompany(player.getUniqueId())); - shopManageMenu.open(); - return; - } - if (!PlayerShopManager.hasShop(player.getUniqueId())) { - MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.INFO, false); - return; - } - ShopMenu shopMenu = new ShopMenu(player, PlayerShopManager.getPlayerShop(player.getUniqueId()), 0); - shopMenu.open(); - } - @Subcommand("search") @Description("Recherche un shop") public void searchShop(Player player){ diff --git a/src/main/java/fr/openmc/core/disabled/corporation/data/MerchantData.java b/src/main/java/fr/openmc/core/features/corporation/data/MerchantData.java similarity index 94% rename from src/main/java/fr/openmc/core/disabled/corporation/data/MerchantData.java rename to src/main/java/fr/openmc/core/features/corporation/data/MerchantData.java index a728471a5..b547922a4 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/data/MerchantData.java +++ b/src/main/java/fr/openmc/core/features/corporation/data/MerchantData.java @@ -1,4 +1,4 @@ -package fr.openmc.core.disabled.corporation.data; +package fr.openmc.core.features.corporation.data; import lombok.Getter; import org.bukkit.inventory.ItemStack; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/data/TransactionData.java b/src/main/java/fr/openmc/core/features/corporation/data/TransactionData.java similarity index 69% rename from src/main/java/fr/openmc/core/disabled/corporation/data/TransactionData.java rename to src/main/java/fr/openmc/core/features/corporation/data/TransactionData.java index 0a9617487..2f6ca2cb5 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/data/TransactionData.java +++ b/src/main/java/fr/openmc/core/features/corporation/data/TransactionData.java @@ -1,4 +1,4 @@ -package fr.openmc.core.disabled.corporation.data; +package fr.openmc.core.features.corporation.data; import java.util.UUID; diff --git a/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java b/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java new file mode 100644 index 000000000..ea4f8e67c --- /dev/null +++ b/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java @@ -0,0 +1,132 @@ +package fr.openmc.core.features.corporation.listener; + +import dev.lone.itemsadder.api.CustomFurniture; +import dev.lone.itemsadder.api.Events.FurnitureBreakEvent; +import dev.lone.itemsadder.api.Events.FurnitureInteractEvent; +import fr.openmc.core.features.corporation.manager.ShopBlocksManager; +import fr.openmc.core.features.corporation.menu.ShopMenu; +import fr.openmc.core.features.corporation.shops.Shop; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Tag; +import org.bukkit.block.Block; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockExplodeEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class ShopListener implements Listener { + + private final Map inShopBarrel = new HashMap<>(); + + @EventHandler + public void onShopBreak(BlockBreakEvent event) { + if (ShopBlocksManager.getShop(event.getBlock().getLocation()) != null) { + event.setCancelled(true); + } + } + + @EventHandler + public void onShopExplode(BlockExplodeEvent event){ + event.blockList().removeIf(block -> ShopBlocksManager.getShop(block.getLocation()) != null); + } + + @EventHandler + public void onEntityExplode(EntityExplodeEvent event) { + event.blockList().removeIf(block -> ShopBlocksManager.getShop(block.getLocation()) != null); + } + + @EventHandler + public void onShopClick(PlayerInteractEvent event) { + if (event.getClickedBlock() == null) { + return; + } + + // Check if the clicked block is a sign with tags + // Instead of getting the entire state of the block + // This is much faster and avoids unnecessary overhead + if (!Tag.SIGNS.isTagged(event.getClickedBlock().getType())) + return; + + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) + return; + + Shop shop = ShopBlocksManager.getShop(event.getClickedBlock().getLocation()); + if (shop == null) + return; + + event.setCancelled(true); + ShopMenu menu = new ShopMenu(event.getPlayer(), shop, 0); + menu.open(); + } + + @EventHandler + public void onInteractWithBlock(PlayerInteractEvent e) { + Block block = e.getClickedBlock(); + if (block != null && block.getType() == Material.BARREL) { + Shop shop = ShopBlocksManager.getShop(block.getLocation()); + boolean isShop = shop != null; + if (isShop){ + if (shop.getOwner().getPlayer() == null) { + e.setCancelled(true); + return; + } + if (! shop.getOwner().getPlayer().equals(e.getPlayer().getUniqueId())) { + e.setCancelled(true); + return; + } + } + inShopBarrel.put(e.getPlayer().getUniqueId(), isShop); + } + } + + /** + * check if an item is valid + * + * @param item the item to check + * @return true if it's a valid item + */ + private boolean isValidItem(ItemStack item) { + return item != null && item.getType() != Material.AIR; + } + + @EventHandler + public void onFurnitureBreak(FurnitureBreakEvent event) { + CustomFurniture furniture = event.getFurniture(); + + if (furniture != null && furniture.getNamespacedID().equals("omc_company:caisse")) { + event.setCancelled(true); + } + } + + @EventHandler + public void onFurnitureInteract(FurnitureInteractEvent e) { + + if (e.getFurniture() == null) { + return; + } + + if (e.getFurniture().getNamespacedID().equals("omc_company:caisse")) { + + double x = e.getFurniture().getEntity().getLocation().getBlockX(); + double y = e.getFurniture().getEntity().getLocation().getBlockY(); + double z = e.getFurniture().getEntity().getLocation().getBlockZ(); + + Shop shop = ShopBlocksManager.getShop(new Location(e.getFurniture().getEntity().getWorld(), x, y, z)); + if (shop == null) { + return; + } + e.setCancelled(true); + new ShopMenu(e.getPlayer(), shop, 0).open(); + + } + } +} diff --git a/src/main/java/fr/openmc/core/disabled/corporation/manager/PlayerShopManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java similarity index 53% rename from src/main/java/fr/openmc/core/disabled/corporation/manager/PlayerShopManager.java rename to src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java index 46bcb6915..f0db7bbf2 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/manager/PlayerShopManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java @@ -1,8 +1,8 @@ -package fr.openmc.core.disabled.corporation.manager; +package fr.openmc.core.features.corporation.manager; -import fr.openmc.core.disabled.corporation.MethodState; -import fr.openmc.core.disabled.corporation.shops.Shop; -import fr.openmc.core.disabled.corporation.shops.ShopOwner; +import fr.openmc.core.features.corporation.MethodState; +import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.features.corporation.shops.ShopOwner; import fr.openmc.core.features.economy.EconomyManager; import lombok.Getter; import org.bukkit.Bukkit; @@ -18,40 +18,36 @@ public class PlayerShopManager { private static final Map playerShops = new HashMap<>(); /** - * create a shop + * Create a shop if the player has enough money and doesn't already have one * - * @param playerUUID the uuif of the player who create it - * @param barrel the barrel block - * @param cashRegister the cash register - * @param shop_uuid the uuid of the shop if it already has one + * @param playerUUID the UUID of the player who creates it + * @param barrel the barrel block of the shop + * @param cashRegister the cash register block of the shop + * @param shopUUID the UUID of the shop if it already has one * @return true if the shop has been created */ - public static boolean createShop(UUID playerUUID, Block barrel, Block cashRegister, UUID shop_uuid) { - if (!EconomyManager.withdrawBalance(playerUUID, 500) && shop_uuid==null) { + public static boolean createShop(UUID playerUUID, Block barrel, Block cashRegister, UUID shopUUID) { + if (! EconomyManager.withdrawBalance(playerUUID, 500) && shopUUID == null) { return false; } - Shop newShop; - if (shop_uuid != null) { - newShop = new Shop(new ShopOwner(playerUUID), 0, shop_uuid); - } else { - newShop = new Shop(new ShopOwner(playerUUID), 0); - } + + Shop newShop = new Shop(new ShopOwner(playerUUID), 0, shopUUID); playerShops.put(playerUUID, newShop); - CompanyManager.shops.add(newShop); ShopBlocksManager.registerMultiblock(newShop, new Shop.Multiblock(barrel.getLocation(), cashRegister.getLocation())); - if (shop_uuid == null) { + + if (shopUUID == null) { ShopBlocksManager.placeShop(newShop, Bukkit.getPlayer(playerUUID), false); } return true; } /** - * delete a shop + * Delete a shop if it's empty * - * @param playerUUID the uuid of the player who delete the shop - * @return a Methode state + * @param playerUUID The UUID of the player who deletes the shop + * @return a MethodeState indicating the result */ public static MethodState deleteShop(UUID playerUUID) { Shop shop = getPlayerShop(playerUUID); @@ -62,35 +58,34 @@ public static MethodState deleteShop(UUID playerUUID) { return MethodState.ESCAPE; } playerShops.remove(playerUUID); - CompanyManager.shops.remove(shop); EconomyManager.addBalance(playerUUID, 400); return MethodState.SUCCESS; } /** - * get a shop from the uuid of a player + * Get a shop from the UUID of a player * - * @param playerUUID the uuid we check - * @return a shop if found + * @param playerUUID the UUID of the player to check + * @return the Shop if found */ public static Shop getPlayerShop(UUID playerUUID) { return playerShops.get(playerUUID); } /** - * get a shop from a shop uuid + * Get a shop from a shop UUID * - * @param shop_uuid the uuid we check - * @return a shop if found + * @param shopUUID the UUID of the shop to check + * @return the Shop if found */ - public static Shop getShopByUUID(UUID shop_uuid) { - return playerShops.values().stream().filter(shop -> shop.getUuid().equals(shop_uuid)).findFirst().orElse(null); + public static Shop getShopByUUID(UUID shopUUID) { + return playerShops.values().stream().filter(shop -> shop.getUuid().equals(shopUUID)).findFirst().orElse(null); } /** - * know if a player has a shop + * Check if a player has a shop * - * @param playerUUID the player to check + * @param playerUUID the UUID of the player to check * @return true if a shop is found */ public static boolean hasShop(UUID playerUUID) { diff --git a/src/main/java/fr/openmc/core/disabled/corporation/manager/ShopBlocksManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/ShopBlocksManager.java similarity index 96% rename from src/main/java/fr/openmc/core/disabled/corporation/manager/ShopBlocksManager.java rename to src/main/java/fr/openmc/core/features/corporation/manager/ShopBlocksManager.java index 9c299c149..9f6e41d89 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/manager/ShopBlocksManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/ShopBlocksManager.java @@ -1,9 +1,9 @@ -package fr.openmc.core.disabled.corporation.manager; +package fr.openmc.core.features.corporation.manager; -import fr.openmc.core.OMCPlugin; -import fr.openmc.core.disabled.corporation.ItemsAdderIntegration; -import fr.openmc.core.disabled.corporation.shops.Shop; import fr.openmc.api.hooks.ItemsAdderHook; +import fr.openmc.core.OMCPlugin; +import fr.openmc.core.features.corporation.ItemsAdderIntegration; +import fr.openmc.core.features.corporation.shops.Shop; import fr.openmc.core.utils.world.WorldUtils; import fr.openmc.core.utils.world.Yaw; import org.bukkit.Location; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopCatalogueMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopCatalogueMenu.java similarity index 96% rename from src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopCatalogueMenu.java rename to src/main/java/fr/openmc/core/features/corporation/menu/ShopCatalogueMenu.java index b5c8cf52d..304092364 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopCatalogueMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopCatalogueMenu.java @@ -1,12 +1,12 @@ -package fr.openmc.core.disabled.corporation.menu.shop; +package fr.openmc.core.features.corporation.menu; import dev.lone.itemsadder.api.FontImages.FontImageWrapper; import fr.openmc.api.menulib.PaginatedMenu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.api.menulib.utils.StaticSlots; -import fr.openmc.core.disabled.corporation.shops.Shop; -import fr.openmc.core.disabled.corporation.shops.ShopItem; +import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.features.corporation.shops.ShopItem; import fr.openmc.core.items.CustomItemRegistry; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java similarity index 79% rename from src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopMenu.java rename to src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java index 5f75edddf..d6da1d029 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java @@ -1,16 +1,14 @@ -package fr.openmc.core.disabled.corporation.menu.shop; +package fr.openmc.core.features.corporation.menu; import dev.lone.itemsadder.api.FontImages.FontImageWrapper; import fr.openmc.api.menulib.Menu; import fr.openmc.api.menulib.default_menu.ConfirmMenu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; -import fr.openmc.core.disabled.corporation.MethodState; -import fr.openmc.core.disabled.corporation.company.Company; -import fr.openmc.core.disabled.corporation.manager.CompanyManager; -import fr.openmc.core.disabled.corporation.manager.PlayerShopManager; -import fr.openmc.core.disabled.corporation.shops.Shop; -import fr.openmc.core.disabled.corporation.shops.ShopItem; +import fr.openmc.core.features.corporation.MethodState; +import fr.openmc.core.features.corporation.manager.PlayerShopManager; +import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.features.corporation.shops.ShopItem; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.items.CustomItemRegistry; import fr.openmc.core.utils.ItemUtils; @@ -56,7 +54,7 @@ public ShopMenu(Player owner, Shop shop, int itemIndex) { @Override public String getTexture() { - // if (shop.getOwner().isCompany()){ +// if (shop.getOwner().isCompany()){ // Company company = shop.getOwner().getCompany(); // if (company.getAllMembers().contains(getOwner().getUniqueId())){ // return FontImageWrapper.replaceFontImages("§r§f:offset_-11::shop_menu:"); @@ -85,12 +83,8 @@ public void onClose(InventoryCloseEvent event) { @Override public @NotNull Map getContent() { Map content = new HashMap<>(); - Company company = null; - - if (shop.getOwner().isCompany()){ - company = shop.getOwner().getCompany(); - } - if ((company == null && shop.isOwner(getOwner().getUniqueId())) || (company != null && company.getAllMembers().contains(getOwner().getUniqueId()))) { + + if (shop.isOwner(getOwner().getUniqueId())) { putOwnerItems(content); } @@ -207,13 +201,6 @@ private void putOwnerItems(Map content) { content.put(8, new ItemBuilder(this, Material.LIME_WOOL, itemMeta -> { itemMeta.setDisplayName("§aCe shop vous appartient"); - if (shop.getOwner().isCompany()) { - if (shop.getOwner().getCompany().getOwner().isCity()) { - itemMeta.setLore(List.of( - "§7■ Car vous faites partie de l'entreprise" - )); - } - } })); content.put(36, new ItemBuilder(this, Material.WRITABLE_BOOK, itemMeta -> { @@ -310,40 +297,17 @@ private void buyAccept() { } private void accept () { - boolean isInCompany = CompanyManager.isInCompany(getOwner().getUniqueId()); - if (isInCompany) { - MethodState deleteState = CompanyManager.getCompany(getOwner().getUniqueId()).deleteShop(getOwner(), shop.getUuid()); - if (deleteState == MethodState.ERROR) { - MessagesManager.sendMessage(getOwner(), Component.text("§cCe shop n'existe pas dans votre entreprise"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (deleteState == MethodState.WARNING) { - MessagesManager.sendMessage(getOwner(), Component.text("§cCe shop n'est pas vide"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (deleteState == MethodState.SPECIAL) { - MessagesManager.sendMessage(getOwner(), Component.text("§cIl vous faut au minimum le nombre d'argent remboursable pour supprimer un shop et obtenir un remboursement dans la banque de votre entreprise"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (deleteState == MethodState.ESCAPE) { - MessagesManager.sendMessage(getOwner(), Component.text("§cCaisse introuvable (appelez un admin)"), Prefix.SHOP, MessageType.INFO, false); - } - MessagesManager.sendMessage(getOwner(), Component.text("§a" + shop.getName() + " a été supprimé !"), Prefix.SHOP, MessageType.INFO, false); - MessagesManager.sendMessage(getOwner(), Component.text("§6[Shop]§a +75" + EconomyManager.getEconomyIcon() + " de remboursés sur la banque de l'entreprise"), Prefix.SHOP, MessageType.INFO, false); + MethodState methodState = PlayerShopManager.deleteShop(getOwner().getUniqueId()); + if (methodState == MethodState.WARNING) { + MessagesManager.sendMessage(getOwner(), Component.text("§cVotre shop n'est pas vide"), Prefix.SHOP, MessageType.INFO, false); + return; } - else { - MethodState methodState = PlayerShopManager.deleteShop(getOwner().getUniqueId()); - if (methodState == MethodState.WARNING) { - MessagesManager.sendMessage(getOwner(), Component.text("§cVotre shop n'est pas vide"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (methodState == MethodState.ESCAPE) { - MessagesManager.sendMessage(getOwner(), Component.text("§cCaisse introuvable (appelez un admin)"), Prefix.SHOP, MessageType.INFO, false); - return; - } - MessagesManager.sendMessage(getOwner(), Component.text("§aVotre shop a bien été supprimé !"), Prefix.SHOP, MessageType.INFO, false); - MessagesManager.sendMessage(getOwner(), Component.text("§6[Shop]§a +400" + EconomyManager.getEconomyIcon() + " de remboursés sur votre compte personnel"), Prefix.SHOP, MessageType.INFO, false); + if (methodState == MethodState.ESCAPE) { + MessagesManager.sendMessage(getOwner(), Component.text("§cCaisse introuvable (appelez un admin)"), Prefix.SHOP, MessageType.INFO, false); + return; } + MessagesManager.sendMessage(getOwner(), Component.text("§aVotre shop a bien été supprimé !"), Prefix.SHOP, MessageType.INFO, false); + MessagesManager.sendMessage(getOwner(), Component.text("§6[Shop]§a +400" + EconomyManager.getEconomyIcon() + " de remboursés sur votre compte personnel"), Prefix.SHOP, MessageType.INFO, false); getOwner().closeInventory(); } diff --git a/src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopSalesMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopSalesMenu.java similarity index 95% rename from src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopSalesMenu.java rename to src/main/java/fr/openmc/core/features/corporation/menu/ShopSalesMenu.java index 96f0a4878..cbdc6aa05 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopSalesMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopSalesMenu.java @@ -1,12 +1,12 @@ -package fr.openmc.core.disabled.corporation.menu.shop; +package fr.openmc.core.features.corporation.menu; import dev.lone.itemsadder.api.FontImages.FontImageWrapper; import fr.openmc.api.menulib.PaginatedMenu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.api.menulib.utils.StaticSlots; -import fr.openmc.core.disabled.corporation.shops.Shop; -import fr.openmc.core.disabled.corporation.shops.ShopItem; +import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.features.corporation.shops.ShopItem; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.items.CustomItemRegistry; import net.kyori.adventure.text.format.NamedTextColor; diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/ShopSearchMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopSearchMenu.java new file mode 100644 index 000000000..0f2244506 --- /dev/null +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopSearchMenu.java @@ -0,0 +1,79 @@ +package fr.openmc.core.features.corporation.menu; + +import dev.lone.itemsadder.api.FontImages.FontImageWrapper; +import fr.openmc.api.menulib.PaginatedMenu; +import fr.openmc.api.menulib.utils.InventorySize; +import fr.openmc.api.menulib.utils.ItemBuilder; +import fr.openmc.api.menulib.utils.StaticSlots; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Map; + +public class ShopSearchMenu extends PaginatedMenu { + + public ShopSearchMenu(Player owner) { + super(owner); + } + + @Override + public @NotNull InventorySize getInventorySize() { + return InventorySize.LARGEST; + } + + @Override + public int getSizeOfItems() { + return getItems().size(); + } + + @Override + public @Nullable Material getBorderMaterial() { + return null; + } + + @Override + public @NotNull List getStaticSlots() { + return StaticSlots.getStandardSlots(getInventorySize()); + } + + @Override + public List getItems() { + return List.of(); + } + + @Override + public Map getButtons() { + return Map.of(); + } + + @Override + public @NotNull String getName() { + return "§l§6Menu de Recherche de Shop"; + } + + @Override + public String getTexture() { + return FontImageWrapper.replaceFontImages("§r§f:offset_-11::large_shop_menu:"); + } + + @Override + public void onInventoryClick(InventoryClickEvent inventoryClickEvent) { + + } + + @Override + public void onClose(InventoryCloseEvent event) { + + } + + @Override + public List getTakableSlot() { + return List.of(); + } +} diff --git a/src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopStocksMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java similarity index 96% rename from src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopStocksMenu.java rename to src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java index 494f69c05..9d10ae189 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/menu/shop/ShopStocksMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java @@ -1,4 +1,4 @@ -package fr.openmc.core.disabled.corporation.menu.shop; +package fr.openmc.core.features.corporation.menu; import dev.lone.itemsadder.api.FontImages.FontImageWrapper; import fr.openmc.api.menulib.PaginatedMenu; @@ -6,9 +6,9 @@ import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.api.menulib.utils.StaticSlots; -import fr.openmc.core.disabled.corporation.shops.Shop; -import fr.openmc.core.disabled.corporation.shops.ShopItem; -import fr.openmc.core.disabled.corporation.shops.Supply; +import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.features.corporation.shops.ShopItem; +import fr.openmc.core.features.corporation.shops.Supply; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.items.CustomItemRegistry; import fr.openmc.core.utils.ItemUtils; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/models/DBShop.java b/src/main/java/fr/openmc/core/features/corporation/models/DBShop.java similarity index 94% rename from src/main/java/fr/openmc/core/disabled/corporation/models/DBShop.java rename to src/main/java/fr/openmc/core/features/corporation/models/DBShop.java index 8c5301c88..d7f351ad0 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/models/DBShop.java +++ b/src/main/java/fr/openmc/core/features/corporation/models/DBShop.java @@ -1,12 +1,11 @@ -package fr.openmc.core.disabled.corporation.models; - -import java.util.UUID; +package fr.openmc.core.features.corporation.models; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; - import lombok.Getter; +import java.util.UUID; + @Getter @DatabaseTable(tableName = "shops") public class DBShop { diff --git a/src/main/java/fr/openmc/core/disabled/corporation/models/DBShopItem.java b/src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java similarity index 91% rename from src/main/java/fr/openmc/core/disabled/corporation/models/DBShopItem.java rename to src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java index 14dc7367d..90b2b1abd 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/models/DBShopItem.java +++ b/src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java @@ -1,15 +1,13 @@ -package fr.openmc.core.disabled.corporation.models; - -import java.util.UUID; - -import org.bukkit.inventory.ItemStack; +package fr.openmc.core.features.corporation.models; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; - -import fr.openmc.core.disabled.corporation.shops.ShopItem; +import fr.openmc.core.features.corporation.shops.ShopItem; import lombok.Getter; +import org.bukkit.inventory.ItemStack; + +import java.util.UUID; @Getter @DatabaseTable(tableName = "shop_items") diff --git a/src/main/java/fr/openmc/core/disabled/corporation/models/DBShopSale.java b/src/main/java/fr/openmc/core/features/corporation/models/DBShopSale.java similarity index 91% rename from src/main/java/fr/openmc/core/disabled/corporation/models/DBShopSale.java rename to src/main/java/fr/openmc/core/features/corporation/models/DBShopSale.java index 169c9b495..3d52941e4 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/models/DBShopSale.java +++ b/src/main/java/fr/openmc/core/features/corporation/models/DBShopSale.java @@ -1,15 +1,13 @@ -package fr.openmc.core.disabled.corporation.models; - -import java.util.UUID; - -import org.bukkit.inventory.ItemStack; +package fr.openmc.core.features.corporation.models; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; - -import fr.openmc.core.disabled.corporation.shops.ShopItem; +import fr.openmc.core.features.corporation.shops.ShopItem; import lombok.Getter; +import org.bukkit.inventory.ItemStack; + +import java.util.UUID; @Getter @DatabaseTable(tableName = "shop_sales") diff --git a/src/main/java/fr/openmc/core/disabled/corporation/models/Merchant.java b/src/main/java/fr/openmc/core/features/corporation/models/Merchant.java similarity index 91% rename from src/main/java/fr/openmc/core/disabled/corporation/models/Merchant.java rename to src/main/java/fr/openmc/core/features/corporation/models/Merchant.java index a300b4cac..c1f570856 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/models/Merchant.java +++ b/src/main/java/fr/openmc/core/features/corporation/models/Merchant.java @@ -1,13 +1,12 @@ -package fr.openmc.core.disabled.corporation.models; - -import java.util.UUID; +package fr.openmc.core.features.corporation.models; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; - import lombok.Getter; +import java.util.UUID; + @DatabaseTable(tableName = "merchants") public class Merchant { @DatabaseField(id = true) diff --git a/src/main/java/fr/openmc/core/disabled/corporation/models/ShopSupplier.java b/src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java similarity index 94% rename from src/main/java/fr/openmc/core/disabled/corporation/models/ShopSupplier.java rename to src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java index 786cdf48b..c4bc3b246 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/models/ShopSupplier.java +++ b/src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java @@ -1,12 +1,11 @@ -package fr.openmc.core.disabled.corporation.models; - -import java.util.UUID; +package fr.openmc.core.features.corporation.models; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; - import lombok.Getter; +import java.util.UUID; + @DatabaseTable(tableName = "shop_suppliers") @Getter public class ShopSupplier { diff --git a/src/main/java/fr/openmc/core/disabled/corporation/shops/Shop.java b/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java similarity index 60% rename from src/main/java/fr/openmc/core/disabled/corporation/shops/Shop.java rename to src/main/java/fr/openmc/core/features/corporation/shops/Shop.java index 2b0458dbd..e16d433d7 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/shops/Shop.java +++ b/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java @@ -1,10 +1,9 @@ -package fr.openmc.core.disabled.corporation.shops; +package fr.openmc.core.features.corporation.shops; import fr.openmc.api.menulib.Menu; import fr.openmc.api.menulib.utils.ItemBuilder; -import fr.openmc.core.disabled.corporation.MethodState; -import fr.openmc.core.disabled.corporation.manager.CompanyManager; -import fr.openmc.core.disabled.corporation.manager.ShopBlocksManager; +import fr.openmc.core.features.corporation.MethodState; +import fr.openmc.core.features.corporation.manager.ShopBlocksManager; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.utils.CacheOfflinePlayer; import fr.openmc.core.utils.ItemUtils; @@ -22,8 +21,6 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.persistence.PersistentDataContainer; -import org.bukkit.persistence.PersistentDataType; import java.util.*; @@ -40,15 +37,13 @@ public class Shop { private double turnover = 0; public Shop(ShopOwner owner, int index) { - this.owner = owner; - this.index = index; - this.uuid = UUID.randomUUID(); + this(owner, index, null); } public Shop(ShopOwner owner, int index, UUID uuid) { this.owner = owner; this.index = index; - this.uuid = uuid; + this.uuid = uuid != null ? uuid : UUID.randomUUID(); } /** @@ -82,41 +77,17 @@ public static void checkStock(Shop shop) { if (itemMeta == null) { continue; } - - PersistentDataContainer dataContainer = itemMeta.getPersistentDataContainer(); - if (dataContainer.has(CompanyManager.SUPPLIER_KEY, PersistentDataType.STRING)) { - - String supplierUUID = dataContainer.get(CompanyManager.SUPPLIER_KEY, PersistentDataType.STRING); - if (supplierUUID == null) { - continue; - } - - List possibleSuppliers = new ArrayList<>(); - if (shop.getOwner().isCompany()) { - possibleSuppliers.addAll(shop.getOwner().getCompany().getAllMembers()); - } - - if (shop.getOwner().isPlayer()) { - possibleSuppliers.add(shop.getOwner().getPlayer()); - } - - if (!possibleSuppliers.contains(UUID.fromString(supplierUUID))) { - continue; - } - boolean supplied = shop.supply(item, UUID.fromString(supplierUUID)); - if (supplied) inventory.remove(item); - } } } } public String getName() { - return owner.isCompany() ? ("Shop #" + index) : CacheOfflinePlayer.getOfflinePlayer(owner.getPlayer()).getName() + "'s Shop"; + return CacheOfflinePlayer.getOfflinePlayer(owner.getPlayer()).getName() + "'s Shop"; } public UUID getSupremeOwner() { - return owner.isCompany() ? owner.getCompany().getOwner().getPlayer() : owner.getPlayer(); + return owner.getPlayer(); } /** @@ -125,9 +96,6 @@ public UUID getSupremeOwner() { * @param uuid the uuid we check */ public boolean isOwner(UUID uuid) { - if (owner.isCompany()) { - return owner.getCompany().isOwner(uuid); - } return owner.getPlayer().equals(uuid); } @@ -261,103 +229,13 @@ public MethodState buy(ShopItem item, int amountToBuy, Player buyer) { if (!EconomyManager.withdrawBalance(buyer.getUniqueId(), item.getPrice(amountToBuy))) return MethodState.ERROR; double basePrice = item.getPrice(amountToBuy); turnover += item.getPrice(amountToBuy); - - if (owner.isCompany()) { - - double price = item.getPrice(amountToBuy);// prix total - - double companyCut = price * owner.getCompany().getCut();// prix après cut - - double suppliersCut = price - companyCut;// prix restant - - boolean supplied = false; - - List supplies = new ArrayList<>(); - for (Map.Entry entry : suppliers.entrySet()) { - if (entry.getValue().getItemId().equals(item.getItemID())) { - supplies.add(entry.getValue()); - } - } - - Map forSupplies = new HashMap<>(); - - if (!supplies.isEmpty()) { - - supplied = true; - - for (Supply supply : supplies) { - int suppliesAmount = supply.getAmount(); - - if (amountToBuy == suppliesAmount){// si la quantité achetée correspond au suppliesAmount ( ex : 32 = 32 ) - EconomyManager.addBalance(supply.getSupplier(), suppliersCut);// ajoutez prix restant - - if (forSupplies.containsKey(supply.getSupplier())){ - double supCut = forSupplies.get(supply.getSupplier()); - forSupplies.replace(supply.getSupplier(), supCut + suppliersCut); - } else { - forSupplies.put(supply.getSupplier(), suppliersCut); - } - removeLatestSupply();// retirer le supplier - break;// arrêter la boucle - } - - if (amountToBuy < suppliesAmount){// si la quantité achetée est inférieure au suppliesAmount ( ex : 32 < 64 ) - EconomyManager.addBalance(supply.getSupplier(), suppliersCut); - suppliesAmount -= amountToBuy; - supply.setAmount(suppliesAmount); - - if (forSupplies.containsKey(supply.getSupplier())){ - double supCut = forSupplies.get(supply.getSupplier()); - forSupplies.replace(supply.getSupplier(), supCut + suppliersCut); - } else { - forSupplies.put(supply.getSupplier(), suppliersCut); - } - break; - } - - else {// si la quantité achetée est supérieur au suppliesAmount ( ex : 64 > 32 ) - double supplierCut = (suppliesAmount * suppliersCut) / amountToBuy; - suppliersCut -= supplierCut; - amountToBuy -= suppliesAmount; - EconomyManager.addBalance(supply.getSupplier(), supplierCut); - - if (forSupplies.containsKey(supply.getSupplier())){ - double supCut = forSupplies.get(supply.getSupplier()); - forSupplies.replace(supply.getSupplier(), supCut + supplierCut); - } else { - forSupplies.put(supply.getSupplier(), supplierCut); - } - removeLatestSupply(); - } - - } - } - - if (!supplied) { - return MethodState.ESCAPE; - } - - for (Map.Entry entry : forSupplies.entrySet()) { - UUID supplier = entry.getKey(); - double supplierCut = entry.getValue(); - - Player player = Bukkit.getPlayer(supplier); - if (player!=null){ - MessagesManager.sendMessage(player, Component.text(buyer.getName() + " a acheté " + amountToBuy + " " + item.getItem().getType() + " pour " + basePrice + EconomyManager.getEconomyIcon() + ", vous avez reçu : " + supplierCut + EconomyManager.getEconomyIcon()), Prefix.SHOP, MessageType.SUCCESS, false); - } - } - - owner.getCompany().depositWithoutWithdraw(companyCut, buyer, "Vente", getName()); + + EconomyManager.addBalance(owner.getPlayer(), item.getPrice(amountToBuy)); + Player player = Bukkit.getPlayer(owner.getPlayer()); + if (player != null) { + MessagesManager.sendMessage(player, Component.text(buyer.getName() + " a acheté " + amountToBuy + " " + item.getItem().getType() + " pour " + item.getPrice(amountToBuy) + EconomyManager.getEconomyIcon() + ", l'argent vous a été transféré !"), Prefix.SHOP, MessageType.SUCCESS, false); } - - else { - EconomyManager.addBalance(owner.getPlayer(), item.getPrice(amountToBuy)); - Player player = Bukkit.getPlayer(owner.getPlayer()); - if (player!=null){ - MessagesManager.sendMessage(player, Component.text(buyer.getName() + " a acheté " + amountToBuy + " " + item.getItem().getType() + " pour " + item.getPrice(amountToBuy) + EconomyManager.getEconomyIcon() + ", l'argent vous a été transféré !"), Prefix.SHOP, MessageType.SUCCESS, false); - } - } - + ItemStack toGive = item.getItem().clone(); toGive.setAmount(amountToBuy); diff --git a/src/main/java/fr/openmc/core/disabled/corporation/shops/ShopItem.java b/src/main/java/fr/openmc/core/features/corporation/shops/ShopItem.java similarity index 83% rename from src/main/java/fr/openmc/core/disabled/corporation/shops/ShopItem.java rename to src/main/java/fr/openmc/core/features/corporation/shops/ShopItem.java index 0308f61a7..80843732c 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/shops/ShopItem.java +++ b/src/main/java/fr/openmc/core/features/corporation/shops/ShopItem.java @@ -1,4 +1,4 @@ -package fr.openmc.core.disabled.corporation.shops; +package fr.openmc.core.features.corporation.shops; import fr.openmc.core.utils.ItemUtils; import lombok.Getter; @@ -50,38 +50,38 @@ public ShopItem setAmount(int amount) { } /** - * copy an ShopItem + * Get the name of an item, either custom or default * - * @return a copy of the ShopItem + * @param itemStack the item to get the name from + * @return the name of the item */ - public ShopItem copy() { - return new ShopItem(item.clone(), pricePerItem); + public static Component getItemName(ItemStack itemStack) { + if (itemStack.hasItemMeta()) { + ItemMeta itemMeta = itemStack.getItemMeta(); + if (itemMeta.hasDisplayName()) { + return itemMeta.displayName(); + } + } + // If no custom name, return default name + return ItemUtils.getItemTranslation(itemStack).color(NamedTextColor.GRAY).decorate(TextDecoration.BOLD); } /** - * get the price of a certain amount of an item + * Create a copy of the ShopItem * - * @param amount amount of item - * @return a price + * @return the copied ShopItem */ - public double getPrice(int amount) { - return pricePerItem * amount; + public ShopItem copy() { + return new ShopItem(item.clone(), pricePerItem); } /** - * get the name of an item + * Get the price of an item based on the amount * - * @param itemStack the item - * @return default name if the item has no custom name + * @param amount the amount of the item + * @return the total price */ - public static Component getItemName(ItemStack itemStack) { - if (itemStack.hasItemMeta()) { - ItemMeta itemMeta = itemStack.getItemMeta(); - if (itemMeta.hasDisplayName()) { - return itemMeta.displayName(); - } - } - // If no custom name, return default name - return ItemUtils.getItemTranslation(itemStack).color(NamedTextColor.GRAY).decorate(TextDecoration.BOLD); + public double getPrice(int amount) { + return pricePerItem * amount; } } diff --git a/src/main/java/fr/openmc/core/features/corporation/shops/ShopOwner.java b/src/main/java/fr/openmc/core/features/corporation/shops/ShopOwner.java new file mode 100644 index 000000000..1681248fe --- /dev/null +++ b/src/main/java/fr/openmc/core/features/corporation/shops/ShopOwner.java @@ -0,0 +1,30 @@ +package fr.openmc.core.features.corporation.shops; + +import lombok.Getter; + +import java.util.UUID; + +@Getter +public class ShopOwner { + + private final UUID player; + + /** + * ShopOwner for a company or a player + * + * @param owner to set a player as the owner + */ + public ShopOwner(UUID owner) { + this.player = owner; + } + + /** + * Check if the owner is a player + * + * @return true if the owner is a player, false otherwise + */ + public boolean isPlayer() { + return player != null; + } + +} diff --git a/src/main/java/fr/openmc/core/disabled/corporation/shops/Supply.java b/src/main/java/fr/openmc/core/features/corporation/shops/Supply.java similarity index 92% rename from src/main/java/fr/openmc/core/disabled/corporation/shops/Supply.java rename to src/main/java/fr/openmc/core/features/corporation/shops/Supply.java index 7091aed94..7832dfdb1 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/shops/Supply.java +++ b/src/main/java/fr/openmc/core/features/corporation/shops/Supply.java @@ -1,4 +1,4 @@ -package fr.openmc.core.disabled.corporation.shops; +package fr.openmc.core.features.corporation.shops; import lombok.Getter; import lombok.Setter; From 4a47d299376bffa1f7b501f70bbfee2ee383645c Mon Sep 17 00:00:00 2001 From: gab4000 Date: Sat, 30 Aug 2025 19:02:29 +0200 Subject: [PATCH 2/9] refactor: rename ShopBlocksManager to ShopManager and update related references --- .../corporation/CompanyManager.java.bak | 2 +- .../corporation/company/Company.java.bak | 2 +- .../corporation/data/MerchantData.java.bak} | 2 +- .../data/TransactionData.java.bak} | 2 +- .../menu/company/ShopManageMenu.java.bak | 2 +- .../corporation/models/Merchant.java.bak} | 2 +- .../corporation/commands/ShopCommand.java | 19 +- .../corporation/listener/ShopListener.java | 85 ++++--- .../manager/PlayerShopManager.java | 32 +-- ...hopBlocksManager.java => ShopManager.java} | 88 ++++--- .../corporation/menu/ShopCatalogueMenu.java | 15 +- .../features/corporation/menu/ShopMenu.java | 81 ++++--- .../corporation/menu/ShopSalesMenu.java | 15 +- .../corporation/menu/ShopStocksMenu.java | 16 +- .../corporation/models/DBShopItem.java | 8 +- .../corporation/models/DBShopSale.java | 8 +- .../corporation/models/ShopSupplier.java | 8 +- .../core/features/corporation/shops/Shop.java | 216 ++++++++---------- .../features/corporation/shops/ShopItem.java | 11 +- .../features/corporation/shops/ShopOwner.java | 30 --- .../java/fr/openmc/core/items/CustomItem.java | 5 +- .../openmc/core/items/CustomItemRegistry.java | 5 +- .../core/utils/database/DatabaseManager.java | 3 + 23 files changed, 304 insertions(+), 353 deletions(-) rename src/main/java/fr/openmc/core/{features/corporation/data/MerchantData.java => disabled/corporation/data/MerchantData.java.bak} (94%) rename src/main/java/fr/openmc/core/{features/corporation/data/TransactionData.java => disabled/corporation/data/TransactionData.java.bak} (69%) rename src/main/java/fr/openmc/core/{features/corporation/models/Merchant.java => disabled/corporation/models/Merchant.java.bak} (91%) rename src/main/java/fr/openmc/core/features/corporation/manager/{ShopBlocksManager.java => ShopManager.java} (56%) delete mode 100644 src/main/java/fr/openmc/core/features/corporation/shops/ShopOwner.java diff --git a/src/main/java/fr/openmc/core/disabled/corporation/CompanyManager.java.bak b/src/main/java/fr/openmc/core/disabled/corporation/CompanyManager.java.bak index 00c7a3db9..7c6706540 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/CompanyManager.java.bak +++ b/src/main/java/fr/openmc/core/disabled/corporation/CompanyManager.java.bak @@ -19,7 +19,7 @@ import fr.openmc.core.features.corporation.data.MerchantData; import fr.openmc.core.features.corporation.listener.ShopListener; import fr.openmc.core.disabled.corporation.models.*; import fr.openmc.core.features.corporation.manager.PlayerShopManager; -import fr.openmc.core.features.corporation.manager.ShopBlocksManager; +import fr.openmc.core.features.corporation.manager.ShopManager; import fr.openmc.core.features.corporation.models.*; import fr.openmc.core.features.corporation.shops.Shop; import fr.openmc.core.features.corporation.shops.ShopItem; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/company/Company.java.bak b/src/main/java/fr/openmc/core/disabled/corporation/company/Company.java.bak index 4e378750a..6ce8bc3bf 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/company/Company.java.bak +++ b/src/main/java/fr/openmc/core/disabled/corporation/company/Company.java.bak @@ -10,7 +10,7 @@ import fr.openmc.core.features.corporation.MethodState; import fr.openmc.core.features.corporation.data.MerchantData; import fr.openmc.core.features.corporation.data.TransactionData; import fr.openmc.core.disabled.corporation.CompanyManager; -import fr.openmc.core.features.corporation.manager.ShopBlocksManager; +import fr.openmc.core.features.corporation.manager.ShopManager; import fr.openmc.core.disabled.corporation.models.DBCompany; import fr.openmc.core.features.corporation.shops.Shop; import fr.openmc.core.features.corporation.shops.ShopOwner; diff --git a/src/main/java/fr/openmc/core/features/corporation/data/MerchantData.java b/src/main/java/fr/openmc/core/disabled/corporation/data/MerchantData.java.bak similarity index 94% rename from src/main/java/fr/openmc/core/features/corporation/data/MerchantData.java rename to src/main/java/fr/openmc/core/disabled/corporation/data/MerchantData.java.bak index b547922a4..a728471a5 100644 --- a/src/main/java/fr/openmc/core/features/corporation/data/MerchantData.java +++ b/src/main/java/fr/openmc/core/disabled/corporation/data/MerchantData.java.bak @@ -1,4 +1,4 @@ -package fr.openmc.core.features.corporation.data; +package fr.openmc.core.disabled.corporation.data; import lombok.Getter; import org.bukkit.inventory.ItemStack; diff --git a/src/main/java/fr/openmc/core/features/corporation/data/TransactionData.java b/src/main/java/fr/openmc/core/disabled/corporation/data/TransactionData.java.bak similarity index 69% rename from src/main/java/fr/openmc/core/features/corporation/data/TransactionData.java rename to src/main/java/fr/openmc/core/disabled/corporation/data/TransactionData.java.bak index 2f6ca2cb5..0a9617487 100644 --- a/src/main/java/fr/openmc/core/features/corporation/data/TransactionData.java +++ b/src/main/java/fr/openmc/core/disabled/corporation/data/TransactionData.java.bak @@ -1,4 +1,4 @@ -package fr.openmc.core.features.corporation.data; +package fr.openmc.core.disabled.corporation.data; import java.util.UUID; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/menu/company/ShopManageMenu.java.bak b/src/main/java/fr/openmc/core/disabled/corporation/menu/company/ShopManageMenu.java.bak index 143992ae1..9df092b46 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/menu/company/ShopManageMenu.java.bak +++ b/src/main/java/fr/openmc/core/disabled/corporation/menu/company/ShopManageMenu.java.bak @@ -6,7 +6,7 @@ import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.api.menulib.utils.StaticSlots; import fr.openmc.core.disabled.corporation.company.Company; -import fr.openmc.core.features.corporation.manager.ShopBlocksManager; +import fr.openmc.core.features.corporation.manager.ShopManager; import fr.openmc.core.features.corporation.shops.Shop; import fr.openmc.core.items.CustomItemRegistry; import net.kyori.adventure.text.Component; diff --git a/src/main/java/fr/openmc/core/features/corporation/models/Merchant.java b/src/main/java/fr/openmc/core/disabled/corporation/models/Merchant.java.bak similarity index 91% rename from src/main/java/fr/openmc/core/features/corporation/models/Merchant.java rename to src/main/java/fr/openmc/core/disabled/corporation/models/Merchant.java.bak index c1f570856..574806b3d 100644 --- a/src/main/java/fr/openmc/core/features/corporation/models/Merchant.java +++ b/src/main/java/fr/openmc/core/disabled/corporation/models/Merchant.java.bak @@ -1,4 +1,4 @@ -package fr.openmc.core.features.corporation.models; +package fr.openmc.core.disabled.corporation.models; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; diff --git a/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java b/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java index 3d4e382cf..5e7ec9791 100644 --- a/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java +++ b/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java @@ -29,7 +29,7 @@ @Description("Manage shops") @CommandPermission("omc.commands.shop") public class ShopCommand { - + @Subcommand("manage") @Description("Manage a shop") public static void manageShop(Player player) { @@ -38,10 +38,15 @@ public static void manageShop(Player player) { MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.INFO, false); return; } - ShopMenu shopMenu = new ShopMenu(player, PlayerShopManager.getPlayerShop(player.getUniqueId()), 0); + ShopMenu shopMenu = new ShopMenu(player); shopMenu.open(); } + @DefaultFor("~") + public void onCommand(Player player) { + new ShopMenu(player).open(); + } + @Subcommand("help") @Description("Explique comment marche un shop") @Cooldown(30) @@ -59,11 +64,6 @@ public void help(Player player) { Prefix.ENTREPRISE, MessageType.INFO, false); } - @DefaultFor("~") - public void onCommand(Player player) { - - } - @Subcommand("sell") @Description("Sell an item in your shop") public void sellItem(Player player, @Named("price") double price) { @@ -108,7 +108,7 @@ public void createShop(Player player) { MessagesManager.sendMessage(player, Component.text("§cVous avez déjà un shop"), Prefix.SHOP, MessageType.INFO, false); return; } - if (!PlayerShopManager.createShop(player.getUniqueId(), targetBlock, aboveBlock, null)) { + if (! PlayerShopManager.createShop(player.getUniqueId(), targetBlock, aboveBlock)) { MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas assez d'argent pour créer un shop (500" + EconomyManager.getEconomyIcon() + ")"), Prefix.SHOP, MessageType.INFO, false); return; } @@ -198,12 +198,13 @@ private void recoverStock(Player owner, ShopItem stock, Shop shop){ toGive.setAmount(toTake); owner.getInventory().addItem(toGive); stock.setAmount(stock.getAmount() - toTake); - + if (stock.getAmount() > 0) { MessagesManager.sendMessage(owner, Component.text("§6Vous avez récupéré §a" + toTake + "§6 dans le stock de cet item"), Prefix.SHOP, MessageType.SUCCESS, false); } else { MessagesManager.sendMessage(owner, Component.text("§6Vous avez récupéré le stock restant de cet item"), Prefix.SHOP, MessageType.SUCCESS, false); } + // Mise à jour des suppliers int toRemove = toTake; diff --git a/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java b/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java index ea4f8e67c..802fe7ad3 100644 --- a/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java +++ b/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java @@ -3,9 +3,13 @@ import dev.lone.itemsadder.api.CustomFurniture; import dev.lone.itemsadder.api.Events.FurnitureBreakEvent; import dev.lone.itemsadder.api.Events.FurnitureInteractEvent; -import fr.openmc.core.features.corporation.manager.ShopBlocksManager; +import fr.openmc.core.features.corporation.manager.ShopManager; import fr.openmc.core.features.corporation.menu.ShopMenu; import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.utils.messages.MessageType; +import fr.openmc.core.utils.messages.MessagesManager; +import fr.openmc.core.utils.messages.Prefix; +import net.kyori.adventure.text.Component; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Tag; @@ -29,63 +33,57 @@ public class ShopListener implements Listener { @EventHandler public void onShopBreak(BlockBreakEvent event) { - if (ShopBlocksManager.getShop(event.getBlock().getLocation()) != null) { - event.setCancelled(true); - } + if (ShopManager.getShop(event.getBlock().getLocation()) != null) event.setCancelled(true); } @EventHandler public void onShopExplode(BlockExplodeEvent event){ - event.blockList().removeIf(block -> ShopBlocksManager.getShop(block.getLocation()) != null); + event.blockList().removeIf(block -> ShopManager.getShop(block.getLocation()) != null); } @EventHandler public void onEntityExplode(EntityExplodeEvent event) { - event.blockList().removeIf(block -> ShopBlocksManager.getShop(block.getLocation()) != null); + event.blockList().removeIf(block -> ShopManager.getShop(block.getLocation()) != null); } @EventHandler public void onShopClick(PlayerInteractEvent event) { - if (event.getClickedBlock() == null) { - return; - } + if (event.getClickedBlock() == null) return; + // Check if the clicked block is a sign with tags // Instead of getting the entire state of the block // This is much faster and avoids unnecessary overhead - if (!Tag.SIGNS.isTagged(event.getClickedBlock().getType())) - return; - - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) - return; - - Shop shop = ShopBlocksManager.getShop(event.getClickedBlock().getLocation()); - if (shop == null) - return; + if (! Tag.SIGNS.isTagged(event.getClickedBlock().getType())) return; + + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + + Shop shop = ShopManager.getShop(event.getClickedBlock().getLocation()); + if (shop == null) return; event.setCancelled(true); - ShopMenu menu = new ShopMenu(event.getPlayer(), shop, 0); + ShopMenu menu = new ShopMenu(event.getPlayer(), shop); menu.open(); } @EventHandler public void onInteractWithBlock(PlayerInteractEvent e) { Block block = e.getClickedBlock(); - if (block != null && block.getType() == Material.BARREL) { - Shop shop = ShopBlocksManager.getShop(block.getLocation()); - boolean isShop = shop != null; - if (isShop){ - if (shop.getOwner().getPlayer() == null) { - e.setCancelled(true); - return; - } - if (! shop.getOwner().getPlayer().equals(e.getPlayer().getUniqueId())) { - e.setCancelled(true); - return; - } - } - inShopBarrel.put(e.getPlayer().getUniqueId(), isShop); + if (block == null || block.getType() != Material.BARREL) return; + + Shop shop = ShopManager.getShop(block.getLocation()); + boolean isShop = shop != null; + if (! isShop) return; + + if (shop.getOwnerUUID() == null) { + e.setCancelled(true); + return; } + if (! shop.getOwnerUUID().equals(e.getPlayer().getUniqueId())) { + e.setCancelled(true); + return; + } + inShopBarrel.put(e.getPlayer().getUniqueId(), isShop); } /** @@ -102,31 +100,32 @@ private boolean isValidItem(ItemStack item) { public void onFurnitureBreak(FurnitureBreakEvent event) { CustomFurniture furniture = event.getFurniture(); - if (furniture != null && furniture.getNamespacedID().equals("omc_company:caisse")) { - event.setCancelled(true); - } + if (furniture != null && furniture.getNamespacedID().equals("omc_company:caisse")) event.setCancelled(true); } @EventHandler public void onFurnitureInteract(FurnitureInteractEvent e) { - - if (e.getFurniture() == null) { - return; - } + if (e.getFurniture() == null) return; if (e.getFurniture().getNamespacedID().equals("omc_company:caisse")) { + if (e.getFurniture().getEntity() == null) { + MessagesManager.sendMessage(e.getPlayer(), Component.text("§cErreur lors de l'ouverture du shop, veuillez contacter le staff. (Entity is null)"), Prefix.SHOP, MessageType.ERROR, true); + return; + } + double x = e.getFurniture().getEntity().getLocation().getBlockX(); double y = e.getFurniture().getEntity().getLocation().getBlockY(); double z = e.getFurniture().getEntity().getLocation().getBlockZ(); - Shop shop = ShopBlocksManager.getShop(new Location(e.getFurniture().getEntity().getWorld(), x, y, z)); + Shop shop = ShopManager.getShop(new Location(e.getFurniture().getEntity().getWorld(), x, y, z)); if (shop == null) { + MessagesManager.sendMessage(e.getPlayer(), Component.text("§cErreur lors de l'ouverture du shop, veuillez contacter le staff. (Shop is null)"), Prefix.SHOP, MessageType.ERROR, true); return; } - e.setCancelled(true); - new ShopMenu(e.getPlayer(), shop, 0).open(); + e.setCancelled(true); + new ShopMenu(e.getPlayer(), shop).open(); } } } diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java index f0db7bbf2..717f4f9d8 100644 --- a/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java @@ -2,7 +2,6 @@ import fr.openmc.core.features.corporation.MethodState; import fr.openmc.core.features.corporation.shops.Shop; -import fr.openmc.core.features.corporation.shops.ShopOwner; import fr.openmc.core.features.economy.EconomyManager; import lombok.Getter; import org.bukkit.Bukkit; @@ -23,23 +22,18 @@ public class PlayerShopManager { * @param playerUUID the UUID of the player who creates it * @param barrel the barrel block of the shop * @param cashRegister the cash register block of the shop - * @param shopUUID the UUID of the shop if it already has one * @return true if the shop has been created */ - public static boolean createShop(UUID playerUUID, Block barrel, Block cashRegister, UUID shopUUID) { - if (! EconomyManager.withdrawBalance(playerUUID, 500) && shopUUID == null) { - return false; - } + public static boolean createShop(UUID playerUUID, Block barrel, Block cashRegister) { + if (! EconomyManager.withdrawBalance(playerUUID, 500)) return false; - Shop newShop = new Shop(new ShopOwner(playerUUID), 0, shopUUID); + Shop newShop = new Shop(playerUUID, 0); playerShops.put(playerUUID, newShop); - ShopBlocksManager.registerMultiblock(newShop, + ShopManager.registerMultiblock(newShop, new Shop.Multiblock(barrel.getLocation(), cashRegister.getLocation())); - if (shopUUID == null) { - ShopBlocksManager.placeShop(newShop, Bukkit.getPlayer(playerUUID), false); - } + ShopManager.placeShop(newShop, Bukkit.getPlayer(playerUUID)); return true; } @@ -51,12 +45,10 @@ public static boolean createShop(UUID playerUUID, Block barrel, Block cashRegist */ public static MethodState deleteShop(UUID playerUUID) { Shop shop = getPlayerShop(playerUUID); - if (!shop.getItems().isEmpty()) { - return MethodState.WARNING; - } - if (!ShopBlocksManager.removeShop(shop)) { - return MethodState.ESCAPE; - } + if (! shop.getItems().isEmpty()) return MethodState.WARNING; + + if (! ShopManager.removeShop(shop)) return MethodState.ESCAPE; + playerShops.remove(playerUUID); EconomyManager.addBalance(playerUUID, 400); return MethodState.SUCCESS; @@ -75,11 +67,11 @@ public static Shop getPlayerShop(UUID playerUUID) { /** * Get a shop from a shop UUID * - * @param shopUUID the UUID of the shop to check + * @param shopOwnerUUID the UUID of the shop to check * @return the Shop if found */ - public static Shop getShopByUUID(UUID shopUUID) { - return playerShops.values().stream().filter(shop -> shop.getUuid().equals(shopUUID)).findFirst().orElse(null); + public static Shop getShopByUUID(UUID shopOwnerUUID) { + return playerShops.values().stream().filter(shop -> shop.getOwnerUUID().equals(shopOwnerUUID)).findFirst().orElse(null); } /** diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/ShopBlocksManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java similarity index 56% rename from src/main/java/fr/openmc/core/features/corporation/manager/ShopBlocksManager.java rename to src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java index 9f6e41d89..c1396d36b 100644 --- a/src/main/java/fr/openmc/core/features/corporation/manager/ShopBlocksManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java @@ -1,27 +1,41 @@ package fr.openmc.core.features.corporation.manager; +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.dao.DaoManager; +import com.j256.ormlite.support.ConnectionSource; +import com.j256.ormlite.table.TableUtils; import fr.openmc.api.hooks.ItemsAdderHook; import fr.openmc.core.OMCPlugin; import fr.openmc.core.features.corporation.ItemsAdderIntegration; +import fr.openmc.core.features.corporation.models.DBShop; +import fr.openmc.core.features.corporation.models.DBShopItem; +import fr.openmc.core.features.corporation.models.DBShopSale; +import fr.openmc.core.features.corporation.models.ShopSupplier; import fr.openmc.core.features.corporation.shops.Shop; import fr.openmc.core.utils.world.WorldUtils; import fr.openmc.core.utils.world.Yaw; +import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.data.BlockData; import org.bukkit.block.data.Directional; import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; +import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.UUID; -public class ShopBlocksManager { +public class ShopManager { private static final Map multiblocks = new HashMap<>(); private static final Map shopsByLocation = new HashMap<>(); + + private static Dao shopsDao; + private static Dao itemsDao; + private static Dao salesDao; + private static Dao suppliersDao; /** * Registers a shop's multiblock structure and maps its key locations. @@ -30,7 +44,7 @@ public class ShopBlocksManager { * @param multiblock The multiblock structure associated with the shop. */ public static void registerMultiblock(Shop shop, Shop.Multiblock multiblock) { - multiblocks.put(shop.getUuid(), multiblock); + multiblocks.put(shop.getOwnerUUID(), multiblock); Location stockLoc = multiblock.stockBlock(); Location cashLoc = multiblock.cashBlock(); shopsByLocation.put(stockLoc, shop); @@ -63,30 +77,24 @@ public static Shop getShop(Location location) { * * @param shop The shop to place. * @param player The player placing the shop. - * @param isCompany Whether the shop belongs to a company (unused here but may be relevant elsewhere). */ - public static void placeShop(Shop shop, Player player, boolean isCompany) { - Shop.Multiblock multiblock = multiblocks.get(shop.getUuid()); - if (multiblock == null) { - return; - } + public static void placeShop(Shop shop, Player player) { + Shop.Multiblock multiblock = multiblocks.get(shop.getOwnerUUID()); + if (multiblock == null) return; + Block cashBlock = multiblock.cashBlock().getBlock(); Yaw yaw = WorldUtils.getYaw(player); if (ItemsAdderHook.hasItemAdder()) { - boolean placed = ItemsAdderIntegration.placeShopFurniture(cashBlock); - if (!placed) { - cashBlock.setType(Material.OAK_SIGN); - } + if (! ItemsAdderIntegration.placeShopFurniture(cashBlock)) cashBlock.setType(Material.OAK_SIGN); } else { cashBlock.setType(Material.OAK_SIGN); } BlockData cashData = cashBlock.getBlockData(); - if (cashData instanceof Directional directional) { - directional.setFacing(yaw.getOpposite().toBlockFace()); - cashBlock.setBlockData(directional); - } + if (! (cashData instanceof Directional directional)) return; + directional.setFacing(yaw.getOpposite().toBlockFace()); + cashBlock.setBlockData(directional); } /** @@ -97,22 +105,15 @@ public static void placeShop(Shop shop, Player player, boolean isCompany) { * @return True if successfully removed, false otherwise. */ public static boolean removeShop(Shop shop) { - Shop.Multiblock multiblock = multiblocks.get(shop.getUuid()); - if (multiblock == null) { - return false; - } + Shop.Multiblock multiblock = multiblocks.get(shop.getOwnerUUID()); + if (multiblock == null) return false; + Block cashBlock = multiblock.cashBlock().getBlock(); Block stockBlock = multiblock.stockBlock().getBlock(); if (ItemsAdderHook.hasItemAdder()) { - - if (!ItemsAdderIntegration.hasFurniture(cashBlock)) { - return false; - } - if (!ItemsAdderIntegration.removeShopFurniture(cashBlock)){ - return false; - } - + if (! ItemsAdderIntegration.hasFurniture(cashBlock)) return false; + if (! ItemsAdderIntegration.removeShopFurniture(cashBlock)) return false; } else { if (cashBlock.getType() != Material.OAK_SIGN && cashBlock.getType() != Material.BARRIER || stockBlock.getType() != Material.BARREL) { return false; @@ -120,15 +121,28 @@ public static boolean removeShop(Shop shop) { } // Async cleanup of location mappings - multiblocks.remove(shop.getUuid()); + multiblocks.remove(shop.getOwnerUUID()); cashBlock.setType(Material.AIR); - new BukkitRunnable() { - @Override - public void run() { - shopsByLocation.entrySet().removeIf(entry -> entry.getValue().getUuid().equals(shop.getUuid())); - } - }.runTaskAsynchronously(OMCPlugin.getInstance()); + Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> + shopsByLocation.entrySet().removeIf(entry -> entry.getValue().getOwnerUUID().equals(shop.getOwnerUUID()))); return true; } - + + public static void initDB(ConnectionSource connectionSource) { + try { + TableUtils.createTableIfNotExists(connectionSource, DBShop.class); + shopsDao = DaoManager.createDao(connectionSource, DBShop.class); + + TableUtils.createTableIfNotExists(connectionSource, DBShopSale.class); + salesDao = DaoManager.createDao(connectionSource, DBShopSale.class); + + TableUtils.createTableIfNotExists(connectionSource, DBShopItem.class); + itemsDao = DaoManager.createDao(connectionSource, DBShopItem.class); + + TableUtils.createTableIfNotExists(connectionSource, ShopSupplier.class); + suppliersDao = DaoManager.createDao(connectionSource, ShopSupplier.class); + } catch (SQLException e) { + e.printStackTrace(); + } + } } diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/ShopCatalogueMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopCatalogueMenu.java index 304092364..54fde478a 100644 --- a/src/main/java/fr/openmc/core/features/corporation/menu/ShopCatalogueMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopCatalogueMenu.java @@ -8,6 +8,7 @@ import fr.openmc.core.features.corporation.shops.Shop; import fr.openmc.core.features.corporation.shops.ShopItem; import fr.openmc.core.items.CustomItemRegistry; +import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Material; @@ -71,15 +72,15 @@ public List getItems() { @Override public Map getButtons() { Map buttons = new HashMap<>(); - buttons.put(49, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_cancel").getBest(), itemMeta -> itemMeta.setDisplayName("§7Fermer")) + buttons.put(49, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_cancel").getBest(), itemMeta -> itemMeta.itemName(Component.text("§7Fermer"))) .setCloseButton()); - ItemBuilder nextPageButton = new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_next_orange").getBest(), itemMeta -> itemMeta.setDisplayName("§aPage suivante")); + ItemBuilder nextPageButton = new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_next_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§aPage suivante"))); if ((getPage() == 0 && isLastPage()) || shop.getItems().isEmpty()) { - buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.setDisplayName("§cRetour")) + buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§cRetour"))) .setOnClick(inventoryClickEvent -> new ShopMenu(getOwner(), shop, itemIndex).open())); buttons.put(50, nextPageButton); } else { - buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.setDisplayName("§cPage précédente")) + buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§cPage précédente"))) .setPreviousPageButton()); buttons.put(50, nextPageButton.setNextPageButton()); } @@ -120,10 +121,8 @@ public List getTakableSlot() { private int getIndex(ShopItem shopItem) { int index = 0; for (ShopItem items : shop.getItems()){ - if (items==shopItem){ - return index; - } - index ++; + if (items == shopItem) return index; + index++; } return index; } diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java index d6da1d029..79847dc25 100644 --- a/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java @@ -38,13 +38,21 @@ public class ShopMenu extends Menu { private final int itemIndex; private int amountToBuy = 1; - + + public ShopMenu(Player owner) { + this(owner, PlayerShopManager.getPlayerShop(owner.getUniqueId())); + } + + public ShopMenu(Player owner, Shop shop) { + this(owner, shop, 0); + } + public ShopMenu(Player owner, Shop shop, int itemIndex) { super(owner); this.shop = shop; this.itemIndex = itemIndex; items.addAll(shop.getItems()); - Shop.checkStock(shop); + shop.checkStock(); } @Override @@ -89,19 +97,19 @@ public void onClose(InventoryCloseEvent event) { } content.put(39, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> { - itemMeta.setDisplayName("§cItem précédent"); + itemMeta.itemName(Component.text("§cItem précédent")); }).setOnClick(inventoryClickEvent -> new ShopMenu(getOwner(), shop, onFirstItem() ? itemIndex : itemIndex - 1).open())); content.put(41, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_next_orange").getBest(), itemMeta -> { - itemMeta.setDisplayName("§aItem suivant"); + itemMeta.itemName(Component.text("§aItem suivant")); }).setOnClick(inventoryClickEvent -> new ShopMenu(getOwner(), shop, onLastItem() ? itemIndex : itemIndex + 1).open())); content.put(40, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_cancel").getBest(), itemMeta -> { - itemMeta.setDisplayName("§7Fermer"); + itemMeta.itemName(Component.text("§7Fermer")); }).setCloseButton()); content.put(19, new ItemBuilder(this, CustomItemRegistry.getByName("omc_menus:minus_btn").getBest(), itemMeta -> { - itemMeta.setDisplayName("§5Définir à 1"); + itemMeta.itemName(Component.text("§5Définir à 1")); }).setOnClick(inventoryClickEvent -> { if (getCurrentItem() == null) return; amountToBuy = 1; @@ -109,7 +117,7 @@ public void onClose(InventoryCloseEvent event) { })); content.put(20, new ItemBuilder(this, CustomItemRegistry.getByName("omc_company:10_btn").getBest(), itemMeta -> { - itemMeta.setDisplayName("§cRetirer 10"); + itemMeta.displayName(Component.text("§cRetirer 10")); }).setOnClick(inventoryClickEvent -> { if (getCurrentItem() == null) return; if (amountToBuy == 1) return; @@ -121,7 +129,7 @@ public void onClose(InventoryCloseEvent event) { open(); })); content.put(21, new ItemBuilder(this, CustomItemRegistry.getByName("omc_menus:1_btn").getBest(), itemMeta -> { - itemMeta.setDisplayName("§cRetirer 1"); + itemMeta.displayName(Component.text("§cRetirer 1")); }).setOnClick(inventoryClickEvent -> { if (getCurrentItem() == null) return; if (amountToBuy == 1) return; @@ -132,22 +140,22 @@ public void onClose(InventoryCloseEvent event) { if (getCurrentItem() != null) content.put(22, new ItemBuilder(this, getCurrentItem().getItem(), itemMeta -> { itemMeta.displayName(ItemUtils.getItemTranslation(getCurrentItem().getItem()).color(NamedTextColor.GRAY).decorate(TextDecoration.BOLD).decoration(TextDecoration.ITALIC, TextDecoration.State.FALSE)); - List lore = new ArrayList<>(); - lore.add("§7■ Prix: §c" + EconomyManager.getFormattedNumber(getCurrentItem().getPricePerItem() * amountToBuy)); - lore.add("§7■ En stock: " + EconomyManager.getFormattedSimplifiedNumber(getCurrentItem().getAmount())); - lore.add("§7■ Cliquez pour en acheter §f" + EconomyManager.getFormattedSimplifiedNumber(amountToBuy)); - itemMeta.setLore(lore); + itemMeta.lore(List.of( + Component.text("§7■ Prix: §c" + EconomyManager.getFormattedNumber(getCurrentItem().getPricePerItem() * amountToBuy)), + Component.text("§7■ En stock: " + EconomyManager.getFormattedSimplifiedNumber(getCurrentItem().getAmount())), + Component.text("§7■ Cliquez pour en acheter §f" + EconomyManager.getFormattedSimplifiedNumber(amountToBuy)) + )); }).setOnClick(inventoryClickEvent -> new ConfirmMenu(getOwner(), this::buyAccept, this::refuse, List.of(Component.text("§aAcheter")), List.of(Component.text("§cAnnuler l'achat"))).open())); content.put(23, new ItemBuilder(this, CustomItemRegistry.getByName("omc_menus:1_btn").getBest(), itemMeta -> { - itemMeta.setDisplayName("§aAjouter 1"); + itemMeta.displayName(Component.text("§aAjouter 1")); }).setOnClick(inventoryClickEvent -> { if (getCurrentItem() == null) return; amountToBuy = getCurrentItem().getAmount()<=amountToBuy ? getCurrentItem().getAmount() : amountToBuy + 1; open(); })); content.put(24, new ItemBuilder(this, CustomItemRegistry.getByName("omc_company:10_btn").getBest(), itemMeta -> { - itemMeta.setDisplayName("§aAjouter 10"); + itemMeta.displayName(Component.text("§aAjouter 10")); }).setOnClick(inventoryClickEvent -> { if (getCurrentItem() == null) return; amountToBuy = getCurrentItem().getAmount()<=amountToBuy ? getCurrentItem().getAmount() : amountToBuy + 10; @@ -155,7 +163,7 @@ public void onClose(InventoryCloseEvent event) { })); content.put(25, new ItemBuilder(this, CustomItemRegistry.getByName("omc_menus:64_btn").getBest(), itemMeta -> { - itemMeta.setDisplayName("§5Ajouter 64"); + itemMeta.displayName(Component.text("§5Ajouter 64")); }).setOnClick(inventoryClickEvent -> { if (getCurrentItem() == null) return; if (amountToBuy == 1) amountToBuy = 64; @@ -164,7 +172,7 @@ public void onClose(InventoryCloseEvent event) { })); content.put(44, new ItemBuilder(this, CustomItemRegistry.getByName("omc_company:company_box").getBest(), itemMeta -> { - itemMeta.setDisplayName("§7Catalogue"); + itemMeta.displayName(Component.text("§7Catalogue")); }).setOnClick(inventoryClickEvent -> new ShopCatalogueMenu(getOwner(), shop, itemIndex).open())); return content; @@ -178,41 +186,40 @@ public List getTakableSlot() { private void putOwnerItems(Map content) { content.put(0, new ItemBuilder(this, CustomItemRegistry.getByName("omc_homes:omc_homes_icon_bin_red").getBest(), itemMeta -> { - itemMeta.setDisplayName("§c§lSupprimer le shop"); + itemMeta.displayName(Component.text("§c§lSupprimer le shop")); }).setOnClick(inventoryClickEvent -> new ConfirmMenu(getOwner(), this::accept, this::refuse, List.of(Component.text("§aSupprimer")), List.of(Component.text("§cAnnuler la suppression"))).open())); content.put(3, new ItemBuilder(this, Material.PAPER, itemMeta -> { - itemMeta.setDisplayName("§a§lVos ventes"); - List lore = new ArrayList<>(); - lore.add("§7■ Ventes: §f" + shop.getSales().size()); - lore.add("§7■ Cliquer pour voir vos ventes sur ce shop"); - itemMeta.setLore(lore); + itemMeta.displayName(Component.text("§a§lVos ventes")); + itemMeta.lore(List.of( + Component.text("§7■ Ventes: §f" + shop.getSales().size()), + Component.text("§7■ Cliquer pour voir vos ventes sur ce shop") + )); }).setOnClick(inventoryClickEvent -> new ShopSalesMenu(getOwner(), shop, itemIndex).open())); content.put(4, shop.getIcon(this, true)); content.put(5, new ItemBuilder(this, Material.BARREL, itemMeta -> { - itemMeta.setDisplayName("§6§lVoir les stocks"); - List lore = new ArrayList<>(); - lore.add("§7■ Stocks: §f" + shop.getAllItemsAmount()); - lore.add("§7■ Cliquer pour voir les stocks de ce shop"); - itemMeta.setLore(lore); + itemMeta.displayName(Component.text("§6§lVoir les stocks")); + itemMeta.lore(List.of( + Component.text("§7■ Stocks: §f" + shop.getAllItemsAmount()), + Component.text("§7■ Cliquer pour voir les stocks de ce shop") + )); }).setOnClick(inventoryClickEvent -> new ShopStocksMenu(getOwner(), shop, itemIndex).open())); content.put(8, new ItemBuilder(this, Material.LIME_WOOL, itemMeta -> { - itemMeta.setDisplayName("§aCe shop vous appartient"); + itemMeta.displayName(Component.text("§aCe shop vous appartient")); })); content.put(36, new ItemBuilder(this, Material.WRITABLE_BOOK, itemMeta -> { - itemMeta.setDisplayName("§7Comment utiliser les shops"); + itemMeta.displayName(Component.text("§7Comment utiliser les shops")); }).setOnClick(inventoryClickEvent -> { ItemStack book = new ItemStack(Material.WRITTEN_BOOK); BookMeta meta = (BookMeta) book.getItemMeta(); if (meta != null) { - meta.setTitle("Guide des Shop"); - meta.setAuthor("Nocolm"); - meta.addPage( + meta = meta.toBuilder().title(Component.text("Guide des Shops")).author(Component.text("Nocolm")) + .addPage(Component.text( """ Comment utiliser les shops ! @@ -220,15 +227,15 @@ private void putOwnerItems(Map content) { 1. Utilisez la commande §d§l/shop sell §r§7 §r en tenant l'item en main 2. Ajoutez les items dans le barril §c§l* le raccourci avec les chiffres ne fonctionnera pas * """ - ); - meta.addPage( + )) + .addPage(Component.text( """ 3. Ouvrez une fois le shop pour renouveler son stock - Et voilà comment utiliser votre shops + Et voilà comment utiliser votre shop §6▪ Pour plus d'info : /shop help§r""" - ); + )).build(); book.setItemMeta(meta); } diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/ShopSalesMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopSalesMenu.java index cbdc6aa05..1bcfb7018 100644 --- a/src/main/java/fr/openmc/core/features/corporation/menu/ShopSalesMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopSalesMenu.java @@ -9,6 +9,7 @@ import fr.openmc.core.features.corporation.shops.ShopItem; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.items.CustomItemRegistry; +import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Material; @@ -60,9 +61,9 @@ public List getItems() { for (ShopItem sale : shop.getSales()) { items.add(new ItemBuilder(this, sale.getItem().getType(), itemMeta -> { itemMeta.displayName(ShopItem.getItemName(sale.getItem()).color(NamedTextColor.YELLOW).decorate(TextDecoration.BOLD)); - itemMeta.setLore(List.of( - "§7■ Prix : §a" + sale.getPrice() + EconomyManager.getEconomyIcon(), - "§7■ Quantité : §a" + sale.getAmount() + itemMeta.lore(List.of( + Component.text("§7■ Prix : §a" + sale.getPrice() + EconomyManager.getEconomyIcon()), + Component.text("§7■ Quantité : §a" + sale.getAmount()) )); })); } @@ -72,15 +73,15 @@ public List getItems() { @Override public Map getButtons() { Map buttons = new HashMap<>(); - buttons.put(49, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_cancel").getBest(), itemMeta -> itemMeta.setDisplayName("§7Fermer")) + buttons.put(49, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_cancel").getBest(), itemMeta -> itemMeta.itemName(Component.text("§7Fermer"))) .setCloseButton()); - ItemBuilder nextPageButton = new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_next_orange").getBest(), itemMeta -> itemMeta.setDisplayName("§aPage suivante")); + ItemBuilder nextPageButton = new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_next_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§aPage suivante"))); if ((getPage() == 0 && isLastPage()) || shop.getSales().isEmpty()) { - buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.setDisplayName("§cRetour")) + buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§cRetour"))) .setOnClick(inventoryClickEvent -> new ShopMenu(getOwner(), shop, itemIndex).open())); buttons.put(50, nextPageButton); } else { - buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.setDisplayName("§cPage précédente")) + buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§cPage précédente"))) .setPreviousPageButton()); buttons.put(50, nextPageButton.setNextPageButton()); } diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java index 9d10ae189..4b7181467 100644 --- a/src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java @@ -72,10 +72,10 @@ public List getItems() { for (ShopItem stock : shop.getItems()) { items.add(new ItemBuilder(this, stock.getItem().getType(), itemMeta -> { itemMeta.displayName(ShopItem.getItemName(stock.getItem()).color(NamedTextColor.GRAY).decorate(TextDecoration.BOLD)); - itemMeta.setLore(List.of( - "§7■ Quantité restante : " + EconomyManager.getFormattedSimplifiedNumber(stock.getAmount()), - "§7■ Prix de vente (par item) : " + EconomyManager.getFormattedNumber(stock.getPricePerItem()), - "§7" + (stock.getAmount() > 0 ? "■ Click gauche pour récupérer le stock" : "■ Click gauche pour retirer l'item de la vente") + itemMeta.lore(List.of( + Component.text("§7■ Quantité restante : " + EconomyManager.getFormattedSimplifiedNumber(stock.getAmount())), + Component.text("§7■ Prix de vente (par item) : " + EconomyManager.getFormattedNumber(stock.getPricePerItem())), + Component.text("§7" + (stock.getAmount() > 0 ? "■ Click gauche pour récupérer le stock" : "■ Click gauche pour retirer l'item de la vente")) )); }).setOnClick(inventoryClickEvent -> { this.stock = stock; @@ -88,15 +88,15 @@ public List getItems() { @Override public Map getButtons() { Map buttons = new HashMap<>(); - buttons.put(49, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_cancel").getBest(), itemMeta -> itemMeta.setDisplayName("§7Fermer")) + buttons.put(49, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_cancel").getBest(), itemMeta -> itemMeta.itemName(Component.text("§7Fermer"))) .setCloseButton()); - ItemBuilder nextPageButton = new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_next_orange").getBest(), itemMeta -> itemMeta.setDisplayName("§aPage suivante")); + ItemBuilder nextPageButton = new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_next_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§aPage suivante"))); if ((getPage() == 0 && isLastPage()) || shop.getSales().isEmpty()) { - buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.setDisplayName("§cRetour")) + buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§cRetour"))) .setOnClick(inventoryClickEvent -> new ShopMenu(getOwner(), shop, itemIndex).open())); buttons.put(50, nextPageButton); } else { - buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.setDisplayName("§cPage précédente")) + buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§cPage précédente"))) .setPreviousPageButton()); buttons.put(50, nextPageButton.setNextPageButton()); } diff --git a/src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java b/src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java index 90b2b1abd..06077f326 100644 --- a/src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java +++ b/src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java @@ -15,7 +15,7 @@ public class DBShopItem { @DatabaseField(canBeNull = false, dataType = DataType.BYTE_ARRAY) private byte[] items; @DatabaseField(canBeNull = false) - private UUID shop; + private UUID ownerUUID; @DatabaseField(canBeNull = false) private double price; @DatabaseField(canBeNull = false) @@ -26,10 +26,10 @@ public class DBShopItem { DBShopItem() { // required for ORMLite } - - public DBShopItem(byte[] items, UUID shop, double price, int amount, UUID itemUuid) { + + public DBShopItem(byte[] items, UUID ownerUUID, double price, int amount, UUID itemUuid) { this.items = items; - this.shop = shop; + this.ownerUUID = ownerUUID; this.price = price; this.amount = amount; this.itemUuid = itemUuid; diff --git a/src/main/java/fr/openmc/core/features/corporation/models/DBShopSale.java b/src/main/java/fr/openmc/core/features/corporation/models/DBShopSale.java index 3d52941e4..a1c9390c4 100644 --- a/src/main/java/fr/openmc/core/features/corporation/models/DBShopSale.java +++ b/src/main/java/fr/openmc/core/features/corporation/models/DBShopSale.java @@ -15,7 +15,7 @@ public class DBShopSale { @DatabaseField(canBeNull = false, dataType = DataType.BYTE_ARRAY) private byte[] items; @DatabaseField(canBeNull = false) - private UUID shop; + private UUID ownerUUID; @DatabaseField(canBeNull = false, columnName = "sale_uuid") private UUID saleUuid; @DatabaseField(canBeNull = false) @@ -26,10 +26,10 @@ public class DBShopSale { DBShopSale() { // required for ORMLite } - - public DBShopSale(byte[] items, UUID shop, double price, int amount, UUID saleUuid) { + + public DBShopSale(byte[] items, UUID ownerUUID, double price, int amount, UUID saleUuid) { this.items = items; - this.shop = shop; + this.ownerUUID = ownerUUID; this.price = price; this.amount = amount; this.saleUuid = saleUuid; diff --git a/src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java b/src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java index c4bc3b246..d824b5c99 100644 --- a/src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java +++ b/src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java @@ -12,7 +12,7 @@ public class ShopSupplier { @DatabaseField(id = true) private UUID id; // différencie les supplier (un joueur peut avoir plusieurs supplier) @DatabaseField(canBeNull = false) - private UUID shop; + private UUID ownerUUID; @DatabaseField(canBeNull = false) private UUID item; @DatabaseField(canBeNull = false) @@ -25,10 +25,10 @@ public class ShopSupplier { ShopSupplier() { // required for ORMLite } - - public ShopSupplier(UUID id, UUID shop, UUID item, UUID player, int amount, long time) { + + public ShopSupplier(UUID id, UUID ownerUUID, UUID item, UUID player, int amount, long time) { this.id = id; - this.shop = shop; + this.ownerUUID = ownerUUID; this.item = item; this.player = player; this.amount = amount; diff --git a/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java b/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java index e16d433d7..1830ba5c3 100644 --- a/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java +++ b/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java @@ -3,7 +3,7 @@ import fr.openmc.api.menulib.Menu; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.core.features.corporation.MethodState; -import fr.openmc.core.features.corporation.manager.ShopBlocksManager; +import fr.openmc.core.features.corporation.manager.ShopManager; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.utils.CacheOfflinePlayer; import fr.openmc.core.utils.ItemUtils; @@ -26,34 +26,46 @@ @Getter public class Shop { - - private final ShopOwner owner; + + private final UUID ownerUUID; private final List items = new ArrayList<>(); private final List sales = new ArrayList<>(); private final Map suppliers = new HashMap<>(); private final int index; - private final UUID uuid; private double turnover = 0; - - public Shop(ShopOwner owner, int index) { - this(owner, index, null); + + public Shop(UUID ownerUUID, int index) { + this.ownerUUID = ownerUUID; + this.index = index; } - public Shop(ShopOwner owner, int index, UUID uuid) { - this.owner = owner; - this.index = index; - this.uuid = uuid != null ? uuid : UUID.randomUUID(); + /** + * get the shop with what player looking + * + * @param player the player we check + * @param onlyCash if we only check the cach register + */ + public static UUID getShopPlayerLookingAt(Player player, boolean onlyCash) { + Block targetBlock = player.getTargetBlockExact(5); + + if (targetBlock == null) return null; + + if (targetBlock.getType() != Material.BARREL && targetBlock.getType() != Material.OAK_SIGN && targetBlock.getType() != Material.BARRIER) return null; + if (onlyCash) if (targetBlock.getType() == Material.BARREL) return null; + + Shop shop = ShopManager.getShop(targetBlock.getLocation()); + if (shop == null) return null; + return shop.getOwnerUUID(); } /** * requirement : item need the uuid of the player who restock the shop * quand un item est vendu un partie du profit reviens a celui qui a approvisionner - * @param shop the shop we want to check the stock */ - public static void checkStock(Shop shop) { - Multiblock multiblock = ShopBlocksManager.getMultiblock(shop.getUuid()); + public void checkStock() { + Multiblock multiblock = ShopManager.getMultiblock(ownerUUID); if (multiblock == null) { return; @@ -61,7 +73,7 @@ public static void checkStock(Shop shop) { Block stockBlock = multiblock.stockBlock().getBlock(); if (stockBlock.getType() != Material.BARREL) { - ShopBlocksManager.removeShop(shop); + ShopManager.removeShop(this); return; } @@ -81,13 +93,8 @@ public static void checkStock(Shop shop) { } } - public String getName() { - return CacheOfflinePlayer.getOfflinePlayer(owner.getPlayer()).getName() + "'s Shop"; - } - - public UUID getSupremeOwner() { - return owner.getPlayer(); + return CacheOfflinePlayer.getOfflinePlayer(ownerUUID).getName() + "'s Shop"; } /** @@ -96,29 +103,7 @@ public UUID getSupremeOwner() { * @param uuid the uuid we check */ public boolean isOwner(UUID uuid) { - return owner.getPlayer().equals(uuid); - } - - /** - * add an item to the shop - * - * @param itemStack the item - * @param price the price - * @param amount the amount of it - */ - public boolean addItem(ItemStack itemStack, double price, int amount, UUID itemID) { - - ShopItem item = itemID == null ? new ShopItem(itemStack, price) : new ShopItem(itemStack, price, itemID); - for (ShopItem shopItem : items) { - if (shopItem.getItem().isSimilar(itemStack)) { - return true; - } - } - if (amount>1){ - item.setAmount(amount); - } - items.add(item); - return false; + return ownerUUID.equals(uuid); } public void addItem(ShopItem item){ @@ -148,6 +133,23 @@ public void removeItem(ShopItem item) { suppliers.entrySet().removeIf(entry -> entry.getValue().getItemId().equals(item.getItemID())); } + /** + * add an item to the shop + * + * @param itemStack the item + * @param price the price + * @param amount the amount of it + */ + public boolean addItem(ItemStack itemStack, double price, int amount, UUID itemID) { + ShopItem item = itemID == null ? new ShopItem(itemStack, price) : new ShopItem(itemStack, price, itemID); + for (ShopItem shopItem : items) if (shopItem.getItem().isSimilar(itemStack)) return true; + + if (amount > 1) item.setAmount(amount); + + items.add(item); + return false; + } + public int recoverItemOf(ShopItem item, Player supplier) { int amount = item.getAmount(); @@ -161,53 +163,51 @@ public int recoverItemOf(ShopItem item, Player supplier) { Iterator> iterator = suppliers.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); - if (entry.getValue().getSupplierUUID().equals(supplier.getUniqueId())) { - if (entry.getValue().getItemId().equals(item.getItemID())){ - amount -= entry.getValue().getAmount(); - toRemove += entry.getValue().getAmount(); - if (amount >= 0){ - iterator.remove(); - } - else { - break; - } - } + + if (! entry.getValue().getSupplierUUID().equals(supplier.getUniqueId())) continue; + if (! entry.getValue().getItemId().equals(item.getItemID())) continue; + + amount -= entry.getValue().getAmount(); + toRemove += entry.getValue().getAmount(); + + if (amount < 0) { + break; + } else { + iterator.remove(); } } - - if (amount == 0){ + + if (amount == 0) { items.remove(item); MessagesManager.sendMessage(supplier, Component.text("§aL'item a bien été retiré du shop !"), Prefix.SHOP, MessageType.SUCCESS, false); } else { item.setAmount(amount); } - + return toRemove; } + public void addSupply(long time, Supply supply){ + suppliers.put(time, supply); + } + /** * update the amount of all the item in the shop according to the items in the barrel */ public boolean supply(ItemStack item, UUID supplier) { for (ShopItem shopItem : items) { - if (shopItem.getItem().getType().equals(item.getType())) { - int delay = 0; - shopItem.setAmount(shopItem.getAmount() + item.getAmount()); - while (suppliers.containsKey(System.currentTimeMillis() + delay)){ - delay ++; - } - suppliers.put(System.currentTimeMillis() + delay, new Supply(supplier, shopItem.getItemID(), item.getAmount())); - return true; - } + if (! shopItem.getItem().getType().equals(item.getType())) continue; + + int delay = 0; + shopItem.setAmount(shopItem.getAmount() + item.getAmount()); + while (suppliers.containsKey(System.currentTimeMillis() + delay)) delay++; + + suppliers.put(System.currentTimeMillis() + delay, new Supply(supplier, shopItem.getItemID(), item.getAmount())); + return true; } return false; } - public void addSupply(long time, Supply supply){ - suppliers.put(time, supply); - } - - /** * buy an item in the shop * @@ -217,21 +217,16 @@ public void addSupply(long time, Supply supply){ * @return a MethodState */ public MethodState buy(ShopItem item, int amountToBuy, Player buyer) { - if (!ItemUtils.hasAvailableSlot(buyer)) { - return MethodState.SPECIAL; - } - if (amountToBuy > item.getAmount()) { - return MethodState.WARNING; - } - if (isOwner(buyer.getUniqueId())) { - return MethodState.FAILURE; - } + if (! ItemUtils.hasAvailableSlot(buyer)) return MethodState.SPECIAL; + if (amountToBuy > item.getAmount()) return MethodState.WARNING; + if (isOwner(buyer.getUniqueId())) return MethodState.FAILURE; + if (!EconomyManager.withdrawBalance(buyer.getUniqueId(), item.getPrice(amountToBuy))) return MethodState.ERROR; double basePrice = item.getPrice(amountToBuy); turnover += item.getPrice(amountToBuy); - EconomyManager.addBalance(owner.getPlayer(), item.getPrice(amountToBuy)); - Player player = Bukkit.getPlayer(owner.getPlayer()); + EconomyManager.addBalance(ownerUUID, item.getPrice(amountToBuy)); + Player player = Bukkit.getPlayer(ownerUUID); if (player != null) { MessagesManager.sendMessage(player, Component.text(buyer.getName() + " a acheté " + amountToBuy + " " + item.getItem().getType() + " pour " + item.getPrice(amountToBuy) + EconomyManager.getEconomyIcon() + ", l'argent vous a été transféré !"), Prefix.SHOP, MessageType.SUCCESS, false); } @@ -240,10 +235,8 @@ public MethodState buy(ShopItem item, int amountToBuy, Player buyer) { toGive.setAmount(amountToBuy); List stacks = ItemUtils.splitAmountIntoStack(toGive); - for (ItemStack stack : stacks) { - buyer.getInventory().addItem(stack); - } - + for (ItemStack stack : stacks) buyer.getInventory().addItem(stack); + sales.add(item.copy().setAmount(amountToBuy)); item.setAmount(item.getAmount() - amountToBuy); @@ -259,16 +252,14 @@ private void removeLatestSupply() { supply = entry.getValue(); } } - if (supply != null) { - suppliers.remove(latest); - } + if (supply == null) return; + + suppliers.remove(latest); } public boolean isSupplier(UUID playerUUID){ for (Map.Entry entry : suppliers.entrySet()) { - if (entry.getValue().getSupplierUUID().equals(playerUUID)){ - return true; - } + if (entry.getValue().getSupplierUUID().equals(playerUUID)) return true; } return false; } @@ -281,44 +272,23 @@ public boolean isSupplier(UUID playerUUID){ */ public ItemBuilder getIcon(Menu menu, boolean fromShopMenu) { return new ItemBuilder(menu, fromShopMenu ? Material.GOLD_INGOT : Material.BARREL, itemMeta -> { - itemMeta.setDisplayName("§e§l" + (fromShopMenu ? "Informations" : getName())); - List lore = new ArrayList<>(); - lore.add("§7■ Chiffre d'affaire : " + EconomyManager.getFormattedNumber(turnover)); - lore.add("§7■ Ventes : §f" + sales.size()); - if (!fromShopMenu) - lore.add("§7■ Cliquez pour accéder au shop"); - itemMeta.setLore(lore); + itemMeta.displayName(Component.text("§e§l" + (fromShopMenu ? "Informations" : getName()))); + + List lore = new ArrayList<>(List.of( + Component.text("§7■ Chiffre d'affaire : " + EconomyManager.getFormattedNumber(turnover)), + Component.text("§7■ Ventes : §f" + sales.size()) + )); + if (! fromShopMenu) lore.add(Component.text("§7■ Cliquez pour accéder au shop")); + itemMeta.lore(lore); }); } public int getAllItemsAmount() { int amount = 0; - for (ShopItem item : items) { - amount += item.getAmount(); - } + for (ShopItem item : items) amount += item.getAmount(); return amount; } - /** - * get the shop with what player looking - * - * @param player the player we check - * @param onlyCash if we only check the cach register - */ - public static UUID getShopPlayerLookingAt(Player player, boolean onlyCash) { - Block targetBlock = player.getTargetBlockExact(5); - - if (targetBlock == null) return null; - - if (targetBlock.getType() != Material.BARREL && targetBlock.getType() != Material.OAK_SIGN && targetBlock.getType() != Material.BARRIER) return null; - if (onlyCash) { - if (targetBlock.getType() != Material.OAK_SIGN && targetBlock.getType() != Material.BARRIER) return null; - } - Shop shop = ShopBlocksManager.getShop(targetBlock.getLocation()); - if (shop == null) return null; - return shop.getUuid(); - } - public record Multiblock(Location stockBlock, Location cashBlock) { } diff --git a/src/main/java/fr/openmc/core/features/corporation/shops/ShopItem.java b/src/main/java/fr/openmc/core/features/corporation/shops/ShopItem.java index 80843732c..b03763407 100644 --- a/src/main/java/fr/openmc/core/features/corporation/shops/ShopItem.java +++ b/src/main/java/fr/openmc/core/features/corporation/shops/ShopItem.java @@ -20,12 +20,7 @@ public class ShopItem { private int amount; public ShopItem(ItemStack item, double pricePerItem) { - this.item = item.clone(); - this.pricePerItem = pricePerItem; - this.item.setAmount(1); - this.price = pricePerItem * amount; - this.amount = 0; - this.itemID = UUID.randomUUID(); + this(item, pricePerItem, UUID.randomUUID()); } public ShopItem(ItemStack item, double pricePerItem, UUID itemID) { @@ -58,9 +53,7 @@ public ShopItem setAmount(int amount) { public static Component getItemName(ItemStack itemStack) { if (itemStack.hasItemMeta()) { ItemMeta itemMeta = itemStack.getItemMeta(); - if (itemMeta.hasDisplayName()) { - return itemMeta.displayName(); - } + if (itemMeta.hasDisplayName()) return itemMeta.displayName(); } // If no custom name, return default name return ItemUtils.getItemTranslation(itemStack).color(NamedTextColor.GRAY).decorate(TextDecoration.BOLD); diff --git a/src/main/java/fr/openmc/core/features/corporation/shops/ShopOwner.java b/src/main/java/fr/openmc/core/features/corporation/shops/ShopOwner.java deleted file mode 100644 index 1681248fe..000000000 --- a/src/main/java/fr/openmc/core/features/corporation/shops/ShopOwner.java +++ /dev/null @@ -1,30 +0,0 @@ -package fr.openmc.core.features.corporation.shops; - -import lombok.Getter; - -import java.util.UUID; - -@Getter -public class ShopOwner { - - private final UUID player; - - /** - * ShopOwner for a company or a player - * - * @param owner to set a player as the owner - */ - public ShopOwner(UUID owner) { - this.player = owner; - } - - /** - * Check if the owner is a player - * - * @return true if the owner is a player, false otherwise - */ - public boolean isPlayer() { - return player != null; - } - -} diff --git a/src/main/java/fr/openmc/core/items/CustomItem.java b/src/main/java/fr/openmc/core/items/CustomItem.java index 268e0e335..513b0dde3 100644 --- a/src/main/java/fr/openmc/core/items/CustomItem.java +++ b/src/main/java/fr/openmc/core/items/CustomItem.java @@ -4,9 +4,10 @@ import fr.openmc.api.hooks.ItemsAdderHook; import lombok.Getter; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; public abstract class CustomItem { - public abstract ItemStack getVanilla(); + public abstract @NotNull ItemStack getVanilla(); @Getter private final String name; public CustomItem(String name) { @@ -44,7 +45,7 @@ public boolean equals(Object object) { * 2. Vanilla * @return Best ItemStack to use for the server */ - public ItemStack getBest() { + public @NotNull ItemStack getBest() { return !ItemsAdderHook.hasItemAdder() || getItemsAdder() == null ? getVanilla() : getItemsAdder(); } } \ No newline at end of file diff --git a/src/main/java/fr/openmc/core/items/CustomItemRegistry.java b/src/main/java/fr/openmc/core/items/CustomItemRegistry.java index 598b325f0..c6e7c40ad 100644 --- a/src/main/java/fr/openmc/core/items/CustomItemRegistry.java +++ b/src/main/java/fr/openmc/core/items/CustomItemRegistry.java @@ -9,6 +9,7 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataType; +import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; import java.util.HashMap; @@ -84,7 +85,7 @@ public static void registerItem(CustomItem item) { public static void registerSimpleItem(String name, ItemStack item) { register(name, new CustomItem(name) { @Override - public ItemStack getVanilla() { + public @NotNull ItemStack getVanilla() { return item; } }); @@ -97,7 +98,7 @@ public static void registerSimpleItem(String name, Material item) { public static void registerSimpleItem(String name, Material material, String displayName) { registerItem(new CustomItem(name) { @Override - public ItemStack getVanilla() { + public @NotNull ItemStack getVanilla() { ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); meta.displayName(Component.text(displayName).decoration(TextDecoration.ITALIC, false)); diff --git a/src/main/java/fr/openmc/core/utils/database/DatabaseManager.java b/src/main/java/fr/openmc/core/utils/database/DatabaseManager.java index aa5812f99..71222c518 100644 --- a/src/main/java/fr/openmc/core/utils/database/DatabaseManager.java +++ b/src/main/java/fr/openmc/core/utils/database/DatabaseManager.java @@ -10,6 +10,7 @@ import fr.openmc.core.features.city.sub.mayor.managers.MayorManager; import fr.openmc.core.features.city.sub.notation.NotationManager; import fr.openmc.core.features.contest.managers.ContestManager; +import fr.openmc.core.features.corporation.manager.ShopManager; import fr.openmc.core.features.economy.BankManager; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.features.economy.TransactionsManager; @@ -63,6 +64,8 @@ public DatabaseManager() { CityManager.initDB(connectionSource); MascotsManager.initDB(connectionSource); PlayerSettingsManager.initDB(connectionSource); + ShopManager.initDB(connectionSource); + } catch (SQLException e) { OMCPlugin.getInstance().getSLF4JLogger().error("Failed to initialize the database connection.", e); throw new RuntimeException(e); From 51998d2f66c84f68066253179caa7f0775a43ef8 Mon Sep 17 00:00:00 2001 From: gab4000 Date: Sun, 26 Oct 2025 11:09:18 +0100 Subject: [PATCH 3/9] resolve build error --- .../java/fr/openmc/core/features/corporation/menu/ShopMenu.java | 2 +- .../openmc/core/features/corporation/menu/ShopStocksMenu.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java index d54b5028b..b5b13e013 100644 --- a/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java @@ -2,7 +2,7 @@ import dev.lone.itemsadder.api.FontImages.FontImageWrapper; import fr.openmc.api.menulib.Menu; -import fr.openmc.api.menulib.defaultmenu.ConfirmMenu; +import fr.openmc.api.menulib.template.ConfirmMenu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.core.features.corporation.MethodState; diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java index f651d125d..2de1c0318 100644 --- a/src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java @@ -2,7 +2,7 @@ import dev.lone.itemsadder.api.FontImages.FontImageWrapper; import fr.openmc.api.menulib.PaginatedMenu; -import fr.openmc.api.menulib.defaultmenu.ConfirmMenu; +import fr.openmc.api.menulib.template.ConfirmMenu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.api.menulib.utils.StaticSlots; From 0b18023272fd954115da2e79cf3fad9fdb40a6c9 Mon Sep 17 00:00:00 2001 From: gab4000 Date: Sat, 1 Nov 2025 17:38:50 +0100 Subject: [PATCH 4/9] refactor: improve shop creation logic and validation messages --- .../city/conditions/CityCreateConditions.java | 2 +- .../corporation/commands/ShopCommand.java | 23 +++------ .../manager/PlayerShopManager.java | 49 ++++++++++++------- .../core/features/corporation/shops/Shop.java | 8 +-- .../core/features/economy/EconomyManager.java | 6 +++ 5 files changed, 51 insertions(+), 37 deletions(-) diff --git a/src/main/java/fr/openmc/core/features/city/conditions/CityCreateConditions.java b/src/main/java/fr/openmc/core/features/city/conditions/CityCreateConditions.java index 1211dd44d..fde71b351 100644 --- a/src/main/java/fr/openmc/core/features/city/conditions/CityCreateConditions.java +++ b/src/main/java/fr/openmc/core/features/city/conditions/CityCreateConditions.java @@ -52,7 +52,7 @@ public static boolean canCityCreate(Player player, String cityName) { } if (cityName != null && !InputUtils.isInputCityName(cityName)) { - MessagesManager.sendMessage(player, Component.text("Le nom de ville est invalide, il doit contenir uniquement des caractères alphanumerique et doit faire moins de 24 caractères"), Prefix.CITY, MessageType.ERROR, false); + MessagesManager.sendMessage(player, Component.text("Le nom de ville est invalide, il doit contenir uniquement des caractères alphanumériques et doit faire moins de 24 caractères"), Prefix.CITY, MessageType.ERROR, false); return false; } diff --git a/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java b/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java index 0212b5006..a7d5279fe 100644 --- a/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java +++ b/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java @@ -14,7 +14,6 @@ import fr.openmc.core.utils.messages.Prefix; import net.kyori.adventure.text.Component; import org.bukkit.Material; -import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import revxrsal.commands.annotation.*; @@ -22,7 +21,6 @@ import java.util.Iterator; import java.util.Map; -import java.util.Objects; import java.util.UUID; @Command("shop") @@ -32,6 +30,10 @@ public class ShopCommand { @CommandPlaceholder public void onCommand(Player player) { + if (!PlayerShopManager.hasShop(player.getUniqueId())) { + MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.INFO, false); + return; + } new ShopMenu(player).open(); } @@ -93,25 +95,16 @@ public void sellItem(Player player, @Named("price") double price) { @Subcommand("create") @Description("Create a shop") public void createShop(Player player) { - Block targetBlock = player.getTargetBlockExact(5); - if (targetBlock == null || targetBlock.getType() != Material.BARREL) { - MessagesManager.sendMessage(player, Component.text("§cVous devez regarder un tonneau pour créer un shop"), Prefix.SHOP, MessageType.INFO, false); - return; - } - Block aboveBlock = Objects.requireNonNull(targetBlock.getLocation().getWorld()).getBlockAt(targetBlock.getLocation().clone().add(0, 1, 0)); - if (aboveBlock.getType() != Material.AIR) { - MessagesManager.sendMessage(player, Component.text("§cVous devez liberer de l'espace au dessus de votre tonneau pour créer un shop"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (PlayerShopManager.hasShop(player.getUniqueId())) { MessagesManager.sendMessage(player, Component.text("§cVous avez déjà un shop"), Prefix.SHOP, MessageType.INFO, false); return; } - if (! PlayerShopManager.createShop(player.getUniqueId(), targetBlock, aboveBlock)) { - MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas assez d'argent pour créer un shop (500" + EconomyManager.getEconomyIcon() + ")"), Prefix.SHOP, MessageType.INFO, false); + if (! EconomyManager.hasEnoughMoney(player.getUniqueId(), 500)) { + MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas assez d'argent pour créer un shop (500" + EconomyManager.getEconomyIcon() + " nécessaires)"), Prefix.SHOP, MessageType.ERROR, false); return; } + + PlayerShopManager.startCreatingShop(player); MessagesManager.sendMessage(player, Component.text("§6[Shop] §c -500" + EconomyManager.getEconomyIcon() +" sur votre compte personnel"), Prefix.SHOP, MessageType.SUCCESS, false); MessagesManager.sendMessage(player, Component.text("§aVous avez bien crée un shop !"), Prefix.SHOP, MessageType.SUCCESS, false); } diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java index 717f4f9d8..13080a43f 100644 --- a/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java @@ -1,11 +1,19 @@ package fr.openmc.core.features.corporation.manager; +import fr.openmc.api.input.location.ItemInteraction; import fr.openmc.core.features.corporation.MethodState; import fr.openmc.core.features.corporation.shops.Shop; import fr.openmc.core.features.economy.EconomyManager; +import fr.openmc.core.features.economy.Transaction; +import fr.openmc.core.features.economy.TransactionsManager; +import fr.openmc.core.utils.messages.MessageType; +import fr.openmc.core.utils.messages.MessagesManager; +import fr.openmc.core.utils.messages.Prefix; import lombok.Getter; -import org.bukkit.Bukkit; -import org.bukkit.block.Block; +import net.kyori.adventure.text.Component; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import java.util.HashMap; import java.util.Map; @@ -17,24 +25,31 @@ public class PlayerShopManager { private static final Map playerShops = new HashMap<>(); /** - * Create a shop if the player has enough money and doesn't already have one + * Create a shop if the player has enough money and does not already have one * - * @param playerUUID the UUID of the player who creates it - * @param barrel the barrel block of the shop - * @param cashRegister the cash register block of the shop - * @return true if the shop has been created + * @param player the player who creates it */ - public static boolean createShop(UUID playerUUID, Block barrel, Block cashRegister) { - if (! EconomyManager.withdrawBalance(playerUUID, 500)) return false; + public static void startCreatingShop(Player player) { + if (! EconomyManager.withdrawBalance(player.getUniqueId(), 500)) return; - Shop newShop = new Shop(playerUUID, 0); - - playerShops.put(playerUUID, newShop); - ShopManager.registerMultiblock(newShop, - new Shop.Multiblock(barrel.getLocation(), cashRegister.getLocation())); - - ShopManager.placeShop(newShop, Bukkit.getPlayer(playerUUID)); - return true; + ItemInteraction.runLocationInteraction( + player, + new ItemStack(Material.BARREL), + "shop:shop_creator", + 300, + "Vous avez reçu un baril pour poser votre shop", + "§cCréation de shop annulée", + location -> { + Shop shop = new Shop(player.getUniqueId(), location); + playerShops.put(player.getUniqueId(), shop); + return true; + }, + () -> { + EconomyManager.addBalance(player.getUniqueId(), 500); + TransactionsManager.registerTransaction(new Transaction(player.getUniqueId().toString(), "CONSOLE", 500, "Annulation création shop")); + MessagesManager.sendMessage(player, Component.text("§cVous avez été remboursé de 500 " + EconomyManager.getEconomyIcon() + " §cpour l'annulation de la création de votre shop"), Prefix.SHOP, MessageType.INFO, true); + } + ); } /** diff --git a/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java b/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java index 1830ba5c3..8463e0b84 100644 --- a/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java +++ b/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java @@ -5,8 +5,8 @@ import fr.openmc.core.features.corporation.MethodState; import fr.openmc.core.features.corporation.manager.ShopManager; import fr.openmc.core.features.economy.EconomyManager; -import fr.openmc.core.utils.CacheOfflinePlayer; import fr.openmc.core.utils.ItemUtils; +import fr.openmc.core.utils.cache.CacheOfflinePlayer; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; @@ -31,13 +31,13 @@ public class Shop { private final List items = new ArrayList<>(); private final List sales = new ArrayList<>(); private final Map suppliers = new HashMap<>(); - private final int index; + private final Location location; private double turnover = 0; - public Shop(UUID ownerUUID, int index) { + public Shop(UUID ownerUUID, Location location) { this.ownerUUID = ownerUUID; - this.index = index; + this.location = location; } /** diff --git a/src/main/java/fr/openmc/core/features/economy/EconomyManager.java b/src/main/java/fr/openmc/core/features/economy/EconomyManager.java index f6d4ded70..486203444 100644 --- a/src/main/java/fr/openmc/core/features/economy/EconomyManager.java +++ b/src/main/java/fr/openmc/core/features/economy/EconomyManager.java @@ -13,6 +13,7 @@ import fr.openmc.core.features.economy.commands.Pay; import fr.openmc.core.features.economy.models.EconomyPlayer; import lombok.Getter; +import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.sql.SQLException; @@ -158,4 +159,9 @@ public static String getEconomyIcon() { return "Ⓐ"; } } + + public static boolean hasEnoughMoney(@NotNull UUID uniqueId, int requiredAmount) { + double balance = EconomyManager.getBalance(uniqueId); + return balance >= requiredAmount; + } } From 38067341b14a6872ab6dec0a6a8eb6f7dc035e19 Mon Sep 17 00:00:00 2001 From: gab4000 Date: Tue, 11 Nov 2025 21:16:45 +0100 Subject: [PATCH 5/9] finalize creation logic --- .../corporation/ItemsAdderIntegration.java | 9 +- .../corporation/commands/ShopCommand.java | 32 ++----- .../corporation/listener/ShopListener.java | 12 +-- .../manager/PlayerShopManager.java | 94 +++++++++++++------ .../corporation/manager/ShopManager.java | 62 +++++------- .../features/corporation/menu/ShopMenu.java | 18 ++-- .../core/features/corporation/shops/Shop.java | 6 +- .../core/utils/database/DatabaseManager.java | 2 +- .../openmc/core/utils/world/WorldUtils.java | 13 +-- .../java/fr/openmc/core/utils/world/Yaw.java | 17 +++- 10 files changed, 138 insertions(+), 127 deletions(-) diff --git a/src/main/java/fr/openmc/core/features/corporation/ItemsAdderIntegration.java b/src/main/java/fr/openmc/core/features/corporation/ItemsAdderIntegration.java index 7de733215..9bd0ed2f7 100644 --- a/src/main/java/fr/openmc/core/features/corporation/ItemsAdderIntegration.java +++ b/src/main/java/fr/openmc/core/features/corporation/ItemsAdderIntegration.java @@ -2,16 +2,17 @@ import dev.lone.itemsadder.api.CustomFurniture; import dev.lone.itemsadder.api.CustomStack; +import fr.openmc.core.utils.world.Yaw; import org.bukkit.block.Block; public class ItemsAdderIntegration { - public static boolean placeShopFurniture(Block block) { + public static boolean placeShopFurniture(Block block, Yaw playerYaw) { CustomStack customFurniture = CustomFurniture.getInstance("omc_company:caisse"); - if (customFurniture == null || block.getType() != org.bukkit.Material.AIR) - return false; + if (customFurniture == null || block.getType() != org.bukkit.Material.AIR) return false; - CustomFurniture.spawn("omc_company:caisse", block); + CustomFurniture furniture = CustomFurniture.spawn("omc_company:caisse", block); + furniture.getEntity().setRotation(playerYaw.getPlayerYaw(), 0); return true; } diff --git a/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java b/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java index a7d5279fe..1f5473584 100644 --- a/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java +++ b/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java @@ -1,6 +1,5 @@ package fr.openmc.core.features.corporation.commands; -import fr.openmc.core.features.corporation.MethodState; import fr.openmc.core.features.corporation.manager.PlayerShopManager; import fr.openmc.core.features.corporation.menu.ShopMenu; import fr.openmc.core.features.corporation.menu.ShopSearchMenu; @@ -21,7 +20,6 @@ import java.util.Iterator; import java.util.Map; -import java.util.UUID; @Command("shop") @Description("Manage shops") @@ -105,8 +103,6 @@ public void createShop(Player player) { } PlayerShopManager.startCreatingShop(player); - MessagesManager.sendMessage(player, Component.text("§6[Shop] §c -500" + EconomyManager.getEconomyIcon() +" sur votre compte personnel"), Prefix.SHOP, MessageType.SUCCESS, false); - MessagesManager.sendMessage(player, Component.text("§aVous avez bien crée un shop !"), Prefix.SHOP, MessageType.SUCCESS, false); } @Subcommand("unsell") @@ -114,7 +110,7 @@ public void createShop(Player player) { public void unsellItem(Player player, @Named("item number") int itemIndex) { if (!PlayerShopManager.hasShop(player.getUniqueId())) { - MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.INFO, false); + MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.WARNING, false); return; } @@ -122,7 +118,7 @@ public void unsellItem(Player player, @Named("item number") int itemIndex) { ShopItem item = shop.getItem(itemIndex - 1); if (item == null) { - MessagesManager.sendMessage(player, Component.text("§cCet item n'est pas dans le shop"), Prefix.SHOP, MessageType.INFO, false); + MessagesManager.sendMessage(player, Component.text("§cCet item n'est pas dans le shop"), Prefix.SHOP, MessageType.WARNING, false); return; } @@ -140,28 +136,12 @@ public void unsellItem(Player player, @Named("item number") int itemIndex) { @Subcommand("delete") @Description("Delete a shop") public void deleteShop(Player player) { - - UUID shopUUID = Shop.getShopPlayerLookingAt(player, false); - if (shopUUID == null) { - MessagesManager.sendMessage(player, Component.text("§cShop non reconnu"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (!PlayerShopManager.hasShop(player.getUniqueId())) { - MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.INFO, false); + MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.WARNING, false); return; } - MethodState methodState = PlayerShopManager.deleteShop(player.getUniqueId()); - if (methodState == MethodState.WARNING) { - MessagesManager.sendMessage(player, Component.text("§cVotre shop n'est pas vide"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (methodState == MethodState.ESCAPE) { - MessagesManager.sendMessage(player, Component.text("§cCaisse introuvable (appelez un admin)"), Prefix.SHOP, MessageType.INFO, false); - return; - } - MessagesManager.sendMessage(player, Component.text("§6Votre shop a bien été supprimé !"), Prefix.SHOP, MessageType.SUCCESS, false); - MessagesManager.sendMessage(player, Component.text("§6[Shop] §a +400" + EconomyManager.getEconomyIcon() + " de remboursés sur votre compte personnel"), Prefix.SHOP, MessageType.SUCCESS, false); + + PlayerShopManager.deleteShop(player); } @Subcommand("search") @@ -180,7 +160,7 @@ private void recoverStock(Player owner, ShopItem stock, Shop shop){ int maxPlace = ItemUtils.getFreePlacesForItem(owner, stock.getItem()); if (maxPlace <= 0) { - MessagesManager.sendMessage(owner, Component.text("§cVous n'avez pas assez de place"), Prefix.SHOP, MessageType.INFO, false); + MessagesManager.sendMessage(owner, Component.text("§cVous n'avez pas assez de place"), Prefix.SHOP, MessageType.WARNING, false); owner.closeInventory(); return; } diff --git a/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java b/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java index 802fe7ad3..a3771ad15 100644 --- a/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java +++ b/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java @@ -33,17 +33,17 @@ public class ShopListener implements Listener { @EventHandler public void onShopBreak(BlockBreakEvent event) { - if (ShopManager.getShop(event.getBlock().getLocation()) != null) event.setCancelled(true); + if (ShopManager.getShopAt(event.getBlock().getLocation()) != null) event.setCancelled(true); } @EventHandler public void onShopExplode(BlockExplodeEvent event){ - event.blockList().removeIf(block -> ShopManager.getShop(block.getLocation()) != null); + event.blockList().removeIf(block -> ShopManager.getShopAt(block.getLocation()) != null); } @EventHandler public void onEntityExplode(EntityExplodeEvent event) { - event.blockList().removeIf(block -> ShopManager.getShop(block.getLocation()) != null); + event.blockList().removeIf(block -> ShopManager.getShopAt(block.getLocation()) != null); } @EventHandler @@ -58,7 +58,7 @@ public void onShopClick(PlayerInteractEvent event) { if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; - Shop shop = ShopManager.getShop(event.getClickedBlock().getLocation()); + Shop shop = ShopManager.getShopAt(event.getClickedBlock().getLocation()); if (shop == null) return; event.setCancelled(true); @@ -71,7 +71,7 @@ public void onInteractWithBlock(PlayerInteractEvent e) { Block block = e.getClickedBlock(); if (block == null || block.getType() != Material.BARREL) return; - Shop shop = ShopManager.getShop(block.getLocation()); + Shop shop = ShopManager.getShopAt(block.getLocation()); boolean isShop = shop != null; if (! isShop) return; @@ -118,7 +118,7 @@ public void onFurnitureInteract(FurnitureInteractEvent e) { double y = e.getFurniture().getEntity().getLocation().getBlockY(); double z = e.getFurniture().getEntity().getLocation().getBlockZ(); - Shop shop = ShopManager.getShop(new Location(e.getFurniture().getEntity().getWorld(), x, y, z)); + Shop shop = ShopManager.getShopAt(new Location(e.getFurniture().getEntity().getWorld(), x, y, z)); if (shop == null) { MessagesManager.sendMessage(e.getPlayer(), Component.text("§cErreur lors de l'ouverture du shop, veuillez contacter le staff. (Shop is null)"), Prefix.SHOP, MessageType.ERROR, true); return; diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java index 13080a43f..7b5376826 100644 --- a/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java @@ -1,17 +1,22 @@ package fr.openmc.core.features.corporation.manager; +import fr.openmc.api.hooks.ItemsAdderHook; import fr.openmc.api.input.location.ItemInteraction; -import fr.openmc.core.features.corporation.MethodState; +import fr.openmc.core.OMCPlugin; +import fr.openmc.core.features.corporation.ItemsAdderIntegration; import fr.openmc.core.features.corporation.shops.Shop; import fr.openmc.core.features.economy.EconomyManager; -import fr.openmc.core.features.economy.Transaction; -import fr.openmc.core.features.economy.TransactionsManager; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; +import fr.openmc.core.utils.world.WorldUtils; import lombok.Getter; import net.kyori.adventure.text.Component; +import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.Directional; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -30,7 +35,7 @@ public class PlayerShopManager { * @param player the player who creates it */ public static void startCreatingShop(Player player) { - if (! EconomyManager.withdrawBalance(player.getUniqueId(), 500)) return; + if (!EconomyManager.withdrawBalance(player.getUniqueId(), 500)) return; ItemInteraction.runLocationInteraction( player, @@ -40,33 +45,76 @@ public static void startCreatingShop(Player player) { "Vous avez reçu un baril pour poser votre shop", "§cCréation de shop annulée", location -> { - Shop shop = new Shop(player.getUniqueId(), location); - playerShops.put(player.getUniqueId(), shop); - return true; + if (location == null) return false; + return createShop(player, location); }, () -> { - EconomyManager.addBalance(player.getUniqueId(), 500); - TransactionsManager.registerTransaction(new Transaction(player.getUniqueId().toString(), "CONSOLE", 500, "Annulation création shop")); + EconomyManager.addBalance(player.getUniqueId(), 500, "Annulation création shop"); MessagesManager.sendMessage(player, Component.text("§cVous avez été remboursé de 500 " + EconomyManager.getEconomyIcon() + " §cpour l'annulation de la création de votre shop"), Prefix.SHOP, MessageType.INFO, true); } ); } + + private static boolean createShop(Player player, Location location) { + Shop shop = new Shop(player.getUniqueId(), location); + + Block barrel = location.getBlock(); + Block cashBlock = location.add(0, 1, 0).getBlock(); + + try { + ShopManager.registerMultiblock(shop, new Shop.Multiblock(barrel.getLocation(), cashBlock.getLocation())); + } catch (RuntimeException e) { + MessagesManager.sendMessage(player, Component.text("§cErreur lors de la création du shop (cannot register multiblock) : §bappelez un admin"), Prefix.SHOP, MessageType.ERROR, true); + OMCPlugin.getInstance().getSLF4JLogger().error("Error registering multiblock for shop UUID: " + shop.getOwnerUUID().toString(), e); + return false; + } + + if (ShopManager.placeShop(player, shop)) { + barrel.setType(Material.BARREL); + BlockData barrelData = barrel.getBlockData(); + if (barrelData instanceof Directional directional) { + directional.setFacing(WorldUtils.getYaw(player).getOpposite().toBlockFace()); + barrel.setBlockData(barrelData); + } + + playerShops.put(player.getUniqueId(), shop); + + MessagesManager.sendMessage(player, Component.text("§aVotre shop a été créé avec succès ! Vous pouvez maintenant y ajouter des articles"), Prefix.SHOP, MessageType.SUCCESS, true); + MessagesManager.sendMessage(player, Component.text("§c500" + EconomyManager.getEconomyIcon() + " retirés de votre compte personnel"), Prefix.SHOP, MessageType.SUCCESS, false); + return true; + } else { + if (ItemsAdderHook.isHasItemAdder()) + if (ItemsAdderIntegration.removeShopFurniture(cashBlock)) { + cashBlock.setType(Material.AIR); + barrel.setType(Material.AIR); + } else { + MessagesManager.sendMessage(player, Component.text("§cErreur lors de la création du shop (cannot remove shop furniture) : §bappelez un admin"), Prefix.SHOP, MessageType.ERROR, false); + } + return false; + } + } /** * Delete a shop if it's empty * - * @param playerUUID The UUID of the player who deletes the shop - * @return a MethodeState indicating the result + * @param player The player who deletes the shop */ - public static MethodState deleteShop(UUID playerUUID) { - Shop shop = getPlayerShop(playerUUID); - if (! shop.getItems().isEmpty()) return MethodState.WARNING; + public static void deleteShop(Player player) { + Shop shop = getPlayerShop(player.getUniqueId()); + if (!shop.getItems().isEmpty()) { + MessagesManager.sendMessage(player, Component.text("§cVotre shop n'est pas vide"), Prefix.SHOP, MessageType.WARNING, false); + return; + } - if (! ShopManager.removeShop(shop)) return MethodState.ESCAPE; + if (!ShopManager.removeShop(shop)) { + MessagesManager.sendMessage(player, Component.text("§cCaisse introuvable (appelez un admin)"), Prefix.SHOP, MessageType.ERROR, false); + return; + } - playerShops.remove(playerUUID); - EconomyManager.addBalance(playerUUID, 400); - return MethodState.SUCCESS; + playerShops.remove(player.getUniqueId()); + EconomyManager.addBalance(player.getUniqueId(), 400); + MessagesManager.sendMessage(player, Component.text("§6Votre shop a bien été supprimé !"), Prefix.SHOP, MessageType.SUCCESS, false); + MessagesManager.sendMessage(player, Component.text("§a400" + EconomyManager.getEconomyIcon() + " remboursés sur votre compte personnel"), Prefix.SHOP, MessageType.SUCCESS, true); } /** @@ -79,16 +127,6 @@ public static Shop getPlayerShop(UUID playerUUID) { return playerShops.get(playerUUID); } - /** - * Get a shop from a shop UUID - * - * @param shopOwnerUUID the UUID of the shop to check - * @return the Shop if found - */ - public static Shop getShopByUUID(UUID shopOwnerUUID) { - return playerShops.values().stream().filter(shop -> shop.getOwnerUUID().equals(shopOwnerUUID)).findFirst().orElse(null); - } - /** * Check if a player has a shop * diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java index 36295d42b..bd178db67 100644 --- a/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java @@ -13,13 +13,10 @@ import fr.openmc.core.features.corporation.models.ShopSupplier; import fr.openmc.core.features.corporation.shops.Shop; import fr.openmc.core.utils.world.WorldUtils; -import fr.openmc.core.utils.world.Yaw; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.Directional; import org.bukkit.entity.Player; import java.sql.SQLException; @@ -67,7 +64,7 @@ public static Shop.Multiblock getMultiblock(UUID uuid) { * @param location The location to check. * @return The shop found at that location, or null if none exists. */ - public static Shop getShop(Location location) { + public static Shop getShopAt(Location location) { return shopsByLocation.get(location); } @@ -75,26 +72,21 @@ public static Shop getShop(Location location) { * Places the shop block (sign or ItemsAdder furniture) in the world, * oriented based on the player's direction. * - * @param shop The shop to place. * @param player The player placing the shop. + * @param shop The shop to place. */ - public static void placeShop(Shop shop, Player player) { + public static boolean placeShop(Player player, Shop shop) { Shop.Multiblock multiblock = multiblocks.get(shop.getOwnerUUID()); - if (multiblock == null) return; + if (multiblock == null) return false; Block cashBlock = multiblock.cashBlock().getBlock(); - Yaw yaw = WorldUtils.getYaw(player); - + if (ItemsAdderHook.isHasItemAdder()) { - if (! ItemsAdderIntegration.placeShopFurniture(cashBlock)) cashBlock.setType(Material.OAK_SIGN); - } else { - cashBlock.setType(Material.OAK_SIGN); - } - - BlockData cashData = cashBlock.getBlockData(); - if (! (cashData instanceof Directional directional)) return; - directional.setFacing(yaw.getOpposite().toBlockFace()); - cashBlock.setBlockData(directional); + if (!ItemsAdderIntegration.placeShopFurniture(cashBlock, WorldUtils.getYaw(player))) + cashBlock.setType(Material.OAK_SIGN); + } else cashBlock.setType(Material.OAK_SIGN); + + return true; } /** @@ -115,34 +107,32 @@ public static boolean removeShop(Shop shop) { if (! ItemsAdderIntegration.hasFurniture(cashBlock)) return false; if (! ItemsAdderIntegration.removeShopFurniture(cashBlock)) return false; } else { - if (cashBlock.getType() != Material.OAK_SIGN && cashBlock.getType() != Material.BARRIER || stockBlock.getType() != Material.BARREL) { + if ((cashBlock.getType() != Material.OAK_SIGN && cashBlock.getType() != Material.BARRIER) || stockBlock.getType() != Material.BARREL) { return false; } } + stockBlock.setType(Material.AIR); // Remove barrel block + // Async cleanup of location mappings multiblocks.remove(shop.getOwnerUUID()); - cashBlock.setType(Material.AIR); + cashBlock.setType(Material.AIR); // Remove sign or furniture block Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> shopsByLocation.entrySet().removeIf(entry -> entry.getValue().getOwnerUUID().equals(shop.getOwnerUUID()))); return true; } - public static void initDB(ConnectionSource connectionSource) { - try { - TableUtils.createTableIfNotExists(connectionSource, DBShop.class); - shopsDao = DaoManager.createDao(connectionSource, DBShop.class); - - TableUtils.createTableIfNotExists(connectionSource, DBShopSale.class); - salesDao = DaoManager.createDao(connectionSource, DBShopSale.class); - - TableUtils.createTableIfNotExists(connectionSource, DBShopItem.class); - itemsDao = DaoManager.createDao(connectionSource, DBShopItem.class); - - TableUtils.createTableIfNotExists(connectionSource, ShopSupplier.class); - suppliersDao = DaoManager.createDao(connectionSource, ShopSupplier.class); - } catch (SQLException e) { - e.printStackTrace(); - } + public static void initDB(ConnectionSource connectionSource) throws SQLException { + TableUtils.createTableIfNotExists(connectionSource, DBShop.class); + shopsDao = DaoManager.createDao(connectionSource, DBShop.class); + + TableUtils.createTableIfNotExists(connectionSource, DBShopSale.class); + salesDao = DaoManager.createDao(connectionSource, DBShopSale.class); + + TableUtils.createTableIfNotExists(connectionSource, DBShopItem.class); + itemsDao = DaoManager.createDao(connectionSource, DBShopItem.class); + + TableUtils.createTableIfNotExists(connectionSource, ShopSupplier.class); + suppliersDao = DaoManager.createDao(connectionSource, ShopSupplier.class); } } diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java index b5b13e013..808da4f68 100644 --- a/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java @@ -116,7 +116,7 @@ public void onClose(InventoryCloseEvent event) { open(); })); - content.put(20, new ItemBuilder(this, CustomItemRegistry.getByName("omc_company:10_btn").getBest(), itemMeta -> { + content.put(20, new ItemBuilder(this, CustomItemRegistry.getByName("omc_menus:10_btn").getBest(), itemMeta -> { itemMeta.displayName(Component.text("§cRetirer 10")); }).setOnClick(inventoryClickEvent -> { if (getCurrentItem() == null) return; @@ -154,7 +154,7 @@ public void onClose(InventoryCloseEvent event) { amountToBuy = getCurrentItem().getAmount()<=amountToBuy ? getCurrentItem().getAmount() : amountToBuy + 1; open(); })); - content.put(24, new ItemBuilder(this, CustomItemRegistry.getByName("omc_company:10_btn").getBest(), itemMeta -> { + content.put(24, new ItemBuilder(this, CustomItemRegistry.getByName("omc_menus:10_btn").getBest(), itemMeta -> { itemMeta.displayName(Component.text("§aAjouter 10")); }).setOnClick(inventoryClickEvent -> { if (getCurrentItem() == null) return; @@ -304,17 +304,13 @@ private void buyAccept() { } private void accept () { - MethodState methodState = PlayerShopManager.deleteShop(getOwner().getUniqueId()); - if (methodState == MethodState.WARNING) { - MessagesManager.sendMessage(getOwner(), Component.text("§cVotre shop n'est pas vide"), Prefix.SHOP, MessageType.INFO, false); - return; - } - if (methodState == MethodState.ESCAPE) { - MessagesManager.sendMessage(getOwner(), Component.text("§cCaisse introuvable (appelez un admin)"), Prefix.SHOP, MessageType.INFO, false); + if (shop == null) { + MessagesManager.sendMessage(getOwner(), Component.text("§cShop introuvable, impossible de le supprimer"), Prefix.SHOP, MessageType.INFO, false); + getOwner().closeInventory(); return; } - MessagesManager.sendMessage(getOwner(), Component.text("§aVotre shop a bien été supprimé !"), Prefix.SHOP, MessageType.INFO, false); - MessagesManager.sendMessage(getOwner(), Component.text("§6[Shop]§a +400" + EconomyManager.getEconomyIcon() + " de remboursés sur votre compte personnel"), Prefix.SHOP, MessageType.INFO, false); + + PlayerShopManager.deleteShop(getOwner()); getOwner().closeInventory(); } diff --git a/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java b/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java index 8463e0b84..4ee2c6414 100644 --- a/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java +++ b/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java @@ -54,7 +54,7 @@ public static UUID getShopPlayerLookingAt(Player player, boolean onlyCash) { if (targetBlock.getType() != Material.BARREL && targetBlock.getType() != Material.OAK_SIGN && targetBlock.getType() != Material.BARRIER) return null; if (onlyCash) if (targetBlock.getType() == Material.BARREL) return null; - Shop shop = ShopManager.getShop(targetBlock.getLocation()); + Shop shop = ShopManager.getShopAt(targetBlock.getLocation()); if (shop == null) return null; return shop.getOwnerUUID(); } @@ -289,7 +289,5 @@ public int getAllItemsAmount() { return amount; } - public record Multiblock(Location stockBlock, Location cashBlock) { - - } + public record Multiblock(Location stockBlock, Location cashBlock) {} } diff --git a/src/main/java/fr/openmc/core/utils/database/DatabaseManager.java b/src/main/java/fr/openmc/core/utils/database/DatabaseManager.java index ada0b8263..f77f4a0ce 100644 --- a/src/main/java/fr/openmc/core/utils/database/DatabaseManager.java +++ b/src/main/java/fr/openmc/core/utils/database/DatabaseManager.java @@ -71,7 +71,7 @@ public static void init() { MascotsManager.initDB(connectionSource); PlayerSettingsManager.initDB(connectionSource); CityStatisticsManager.initDB(connectionSource); - ShopManager.initDB(connectionSource); + ShopManager.initDB(connectionSource); HalloweenManager.initDB(connectionSource); } catch (SQLException e) { OMCPlugin.getInstance().getSLF4JLogger().error("Failed to initialize the database connection.", e); diff --git a/src/main/java/fr/openmc/core/utils/world/WorldUtils.java b/src/main/java/fr/openmc/core/utils/world/WorldUtils.java index b280318d1..a804bdb8b 100644 --- a/src/main/java/fr/openmc/core/utils/world/WorldUtils.java +++ b/src/main/java/fr/openmc/core/utils/world/WorldUtils.java @@ -6,16 +6,17 @@ public class WorldUtils { public static Yaw getYaw(Player p) { float yaw = p.getLocation().getYaw(); - yaw = (yaw % 360 + 360) % 360; // true modulo, as javas modulo is unique for negative values - if (yaw > 135 || yaw < -135) { + if (yaw < 0) yaw += 360; + if (yaw > 135 && yaw <= 225) { return Yaw.NORTH; - } else if (yaw < -45) { + } else if (yaw > 225 && yaw <= 315) { return Yaw.EAST; - } else if (yaw > 45) { + } else if (yaw > 45 && yaw <= 135) { return Yaw.WEST; - } else { + } else if (yaw > 315 || yaw <= 45) { return Yaw.SOUTH; + } else { + return Yaw.NORTH; // should never happen } } - } diff --git a/src/main/java/fr/openmc/core/utils/world/Yaw.java b/src/main/java/fr/openmc/core/utils/world/Yaw.java index 82b3ba4ed..368875ac4 100644 --- a/src/main/java/fr/openmc/core/utils/world/Yaw.java +++ b/src/main/java/fr/openmc/core/utils/world/Yaw.java @@ -1,13 +1,14 @@ package fr.openmc.core.utils.world; +import lombok.Getter; import org.bukkit.block.BlockFace; public enum Yaw { - NORTH, - EAST, - SOUTH, - WEST; + NORTH(180), + EAST(270), + SOUTH(0), + WEST(90); public Yaw getOpposite() { return switch (this) { @@ -26,5 +27,11 @@ public BlockFace toBlockFace() { case WEST -> BlockFace.WEST; }; } - + + @Getter + final float playerYaw; + + Yaw (float playerYaw) { + this.playerYaw = playerYaw; + } } From c759c005f99055dd99da077e8944be1e7bfb0ef6 Mon Sep 17 00:00:00 2001 From: gab4000 Date: Wed, 12 Nov 2025 14:01:21 +0100 Subject: [PATCH 6/9] refactor: streamline item interaction checks and improve shop creation messages --- .../api/input/location/ItemInteraction.java | 6 ++---- .../corporation/manager/PlayerShopManager.java | 15 +++++++++++++-- .../features/corporation/manager/ShopManager.java | 4 ++-- .../core/features/corporation/menu/ShopMenu.java | 2 +- 4 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/main/java/fr/openmc/api/input/location/ItemInteraction.java b/src/main/java/fr/openmc/api/input/location/ItemInteraction.java index 64ed42da0..1ff6f7e08 100644 --- a/src/main/java/fr/openmc/api/input/location/ItemInteraction.java +++ b/src/main/java/fr/openmc/api/input/location/ItemInteraction.java @@ -168,12 +168,10 @@ void onPlayerDeath(PlayerDeathEvent event) { * Méthode qui permet de verifier si l'item est celui avec qui on interagit */ private static boolean isItemInteraction(ItemStack item) { - if (item == null || item.getType() == Material.AIR) - return false; + if (item == null || item.getType() == Material.AIR) return false; ItemMeta meta = item.getItemMeta(); - if (meta == null) - return false; + if (meta == null) return false; if (item.hasItemMeta()) { PersistentDataContainer data = item.getItemMeta().getPersistentDataContainer(); diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java index 7b5376826..011f9511e 100644 --- a/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java @@ -42,7 +42,7 @@ public static void startCreatingShop(Player player) { new ItemStack(Material.BARREL), "shop:shop_creator", 300, - "Vous avez reçu un baril pour poser votre shop", + "Vous avez reçu un tonneau pour poser votre shop", "§cCréation de shop annulée", location -> { if (location == null) return false; @@ -61,6 +61,16 @@ private static boolean createShop(Player player, Location location) { Block barrel = location.getBlock(); Block cashBlock = location.add(0, 1, 0).getBlock(); + if (barrel.getType() != Material.AIR) { + MessagesManager.sendMessage(player, Component.text("§cImpossible de créer le shop ici, l'espace du tonneau doit être libre"), Prefix.SHOP, MessageType.ERROR, true); + return false; + } + + if (cashBlock.getType() != Material.AIR) { + MessagesManager.sendMessage(player, Component.text("§cImpossible de créer le shop ici, l'espace au-dessus du tonneau doit être libre"), Prefix.SHOP, MessageType.ERROR, true); + return false; + } + try { ShopManager.registerMultiblock(shop, new Shop.Multiblock(barrel.getLocation(), cashBlock.getLocation())); } catch (RuntimeException e) { @@ -107,11 +117,12 @@ public static void deleteShop(Player player) { } if (!ShopManager.removeShop(shop)) { - MessagesManager.sendMessage(player, Component.text("§cCaisse introuvable (appelez un admin)"), Prefix.SHOP, MessageType.ERROR, false); + MessagesManager.sendMessage(player, Component.text("§cShop introuvable (appelez un admin)"), Prefix.SHOP, MessageType.ERROR, false); return; } playerShops.remove(player.getUniqueId()); + EconomyManager.addBalance(player.getUniqueId(), 400); MessagesManager.sendMessage(player, Component.text("§6Votre shop a bien été supprimé !"), Prefix.SHOP, MessageType.SUCCESS, false); MessagesManager.sendMessage(player, Component.text("§a400" + EconomyManager.getEconomyIcon() + " remboursés sur votre compte personnel"), Prefix.SHOP, MessageType.SUCCESS, true); diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java index bd178db67..faf4b69fd 100644 --- a/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java @@ -104,8 +104,8 @@ public static boolean removeShop(Shop shop) { Block stockBlock = multiblock.stockBlock().getBlock(); if (ItemsAdderHook.isHasItemAdder()) { - if (! ItemsAdderIntegration.hasFurniture(cashBlock)) return false; - if (! ItemsAdderIntegration.removeShopFurniture(cashBlock)) return false; + if (!ItemsAdderIntegration.hasFurniture(cashBlock)) return false; + if (!ItemsAdderIntegration.removeShopFurniture(cashBlock)) return false; } else { if ((cashBlock.getType() != Material.OAK_SIGN && cashBlock.getType() != Material.BARRIER) || stockBlock.getType() != Material.BARREL) { return false; diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java index 808da4f68..318a0b88b 100644 --- a/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java @@ -303,7 +303,7 @@ private void buyAccept() { getOwner().closeInventory(); } - private void accept () { + private void accept() { if (shop == null) { MessagesManager.sendMessage(getOwner(), Component.text("§cShop introuvable, impossible de le supprimer"), Prefix.SHOP, MessageType.INFO, false); getOwner().closeInventory(); From 7e5ec0ad9c961c8c23917666be846e0ffa359298 Mon Sep 17 00:00:00 2001 From: gab4000 Date: Wed, 12 Nov 2025 16:52:25 +0100 Subject: [PATCH 7/9] refactor: DB management at creating/removing shops --- .../corporation/commands/ShopCommand.java | 2 +- .../manager/PlayerShopManager.java | 26 ++++++++++-- .../corporation/manager/ShopManager.java | 40 +++++++++++++----- .../features/corporation/menu/ShopMenu.java | 2 +- .../features/corporation/models/DBShop.java | 42 ------------------- .../corporation/models/DBShopItem.java | 12 +++--- .../corporation/models/DBShopLocation.java | 31 ++++++++++++++ .../corporation/models/DBShopSale.java | 12 +++--- .../corporation/models/ShopSupplier.java | 7 +--- 9 files changed, 99 insertions(+), 75 deletions(-) delete mode 100644 src/main/java/fr/openmc/core/features/corporation/models/DBShop.java create mode 100644 src/main/java/fr/openmc/core/features/corporation/models/DBShopLocation.java diff --git a/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java b/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java index 1f5473584..2033bed74 100644 --- a/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java +++ b/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java @@ -141,7 +141,7 @@ public void deleteShop(Player player) { return; } - PlayerShopManager.deleteShop(player); + PlayerShopManager.deleteShop(player, false); } @Subcommand("search") diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java index 011f9511e..d361efb11 100644 --- a/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java @@ -4,6 +4,7 @@ import fr.openmc.api.input.location.ItemInteraction; import fr.openmc.core.OMCPlugin; import fr.openmc.core.features.corporation.ItemsAdderIntegration; +import fr.openmc.core.features.corporation.models.DBShopLocation; import fr.openmc.core.features.corporation.shops.Shop; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.utils.messages.MessageType; @@ -12,6 +13,7 @@ import fr.openmc.core.utils.world.WorldUtils; import lombok.Getter; import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; @@ -89,6 +91,13 @@ private static boolean createShop(Player player, Location location) { playerShops.put(player.getUniqueId(), shop); + Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { + if (!ShopManager.saveShopLocation(new DBShopLocation(shop.getOwnerUUID(), barrel.getX(), barrel.getY(), barrel.getZ()))) { + MessagesManager.sendMessage(player, Component.text("§cErreur lors de la création du shop (cannot save shop location) : §bappelez un admin"), Prefix.SHOP, MessageType.ERROR, false); + deleteShop(player, true); + } + }); + MessagesManager.sendMessage(player, Component.text("§aVotre shop a été créé avec succès ! Vous pouvez maintenant y ajouter des articles"), Prefix.SHOP, MessageType.SUCCESS, true); MessagesManager.sendMessage(player, Component.text("§c500" + EconomyManager.getEconomyIcon() + " retirés de votre compte personnel"), Prefix.SHOP, MessageType.SUCCESS, false); return true; @@ -105,13 +114,13 @@ private static boolean createShop(Player player, Location location) { } /** - * Delete a shop if it's empty + * Delete a shop if it is empty * * @param player The player who deletes the shop */ - public static void deleteShop(Player player) { + public static void deleteShop(Player player, boolean fromError) { Shop shop = getPlayerShop(player.getUniqueId()); - if (!shop.getItems().isEmpty()) { + if (!fromError && !shop.getItems().isEmpty()) { MessagesManager.sendMessage(player, Component.text("§cVotre shop n'est pas vide"), Prefix.SHOP, MessageType.WARNING, false); return; } @@ -123,8 +132,17 @@ public static void deleteShop(Player player) { playerShops.remove(player.getUniqueId()); + if (!fromError) { + Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { + if (!ShopManager.deleteShopLocation(player.getUniqueId())) { + MessagesManager.sendMessage(player, Component.text("§cErreur lors de la suppression du shop (appelez un admin)"), Prefix.SHOP, MessageType.ERROR, false); + } + }); + + MessagesManager.sendMessage(player, Component.text("§6Votre shop a bien été supprimé !"), Prefix.SHOP, MessageType.SUCCESS, false); + } + EconomyManager.addBalance(player.getUniqueId(), 400); - MessagesManager.sendMessage(player, Component.text("§6Votre shop a bien été supprimé !"), Prefix.SHOP, MessageType.SUCCESS, false); MessagesManager.sendMessage(player, Component.text("§a400" + EconomyManager.getEconomyIcon() + " remboursés sur votre compte personnel"), Prefix.SHOP, MessageType.SUCCESS, true); } diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java index faf4b69fd..2939f0161 100644 --- a/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java @@ -7,8 +7,8 @@ import fr.openmc.api.hooks.ItemsAdderHook; import fr.openmc.core.OMCPlugin; import fr.openmc.core.features.corporation.ItemsAdderIntegration; -import fr.openmc.core.features.corporation.models.DBShop; import fr.openmc.core.features.corporation.models.DBShopItem; +import fr.openmc.core.features.corporation.models.DBShopLocation; import fr.openmc.core.features.corporation.models.DBShopSale; import fr.openmc.core.features.corporation.models.ShopSupplier; import fr.openmc.core.features.corporation.shops.Shop; @@ -29,10 +29,10 @@ public class ShopManager { private static final Map multiblocks = new HashMap<>(); private static final Map shopsByLocation = new HashMap<>(); - private static Dao shopsDao; - private static Dao itemsDao; - private static Dao salesDao; - private static Dao suppliersDao; + private static Dao shopLocationDao; + private static Dao shopItemsDao; + private static Dao shopSalesDao; + private static Dao shopSuppliersDao; /** * Registers a shop's multiblock structure and maps its key locations. @@ -123,16 +123,36 @@ public static boolean removeShop(Shop shop) { } public static void initDB(ConnectionSource connectionSource) throws SQLException { - TableUtils.createTableIfNotExists(connectionSource, DBShop.class); - shopsDao = DaoManager.createDao(connectionSource, DBShop.class); + TableUtils.createTableIfNotExists(connectionSource, DBShopLocation.class); + shopLocationDao = DaoManager.createDao(connectionSource, DBShopLocation.class); TableUtils.createTableIfNotExists(connectionSource, DBShopSale.class); - salesDao = DaoManager.createDao(connectionSource, DBShopSale.class); + shopSalesDao = DaoManager.createDao(connectionSource, DBShopSale.class); TableUtils.createTableIfNotExists(connectionSource, DBShopItem.class); - itemsDao = DaoManager.createDao(connectionSource, DBShopItem.class); + shopItemsDao = DaoManager.createDao(connectionSource, DBShopItem.class); TableUtils.createTableIfNotExists(connectionSource, ShopSupplier.class); - suppliersDao = DaoManager.createDao(connectionSource, ShopSupplier.class); + shopSuppliersDao = DaoManager.createDao(connectionSource, ShopSupplier.class); + } + + public static boolean saveShopLocation(DBShopLocation dbShopLocation) { + try { + shopLocationDao.createOrUpdate(dbShopLocation); + return true; + } catch (SQLException e) { + OMCPlugin.getInstance().getSLF4JLogger().error("Error saving shop location for owner UUID: " + dbShopLocation.getOwnerUUID().toString(), e); + return false; + } + } + + public static boolean deleteShopLocation(UUID ownerUUID) { + try { + shopLocationDao.deleteById(ownerUUID); + return true; + } catch (SQLException e) { + OMCPlugin.getInstance().getSLF4JLogger().error("Error deleting shop location for owner UUID: " + ownerUUID.toString(), e); + return false; + } } } diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java index 318a0b88b..51485832b 100644 --- a/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java @@ -310,7 +310,7 @@ private void accept() { return; } - PlayerShopManager.deleteShop(getOwner()); + PlayerShopManager.deleteShop(getOwner(), false); getOwner().closeInventory(); } diff --git a/src/main/java/fr/openmc/core/features/corporation/models/DBShop.java b/src/main/java/fr/openmc/core/features/corporation/models/DBShop.java deleted file mode 100644 index d7f351ad0..000000000 --- a/src/main/java/fr/openmc/core/features/corporation/models/DBShop.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.openmc.core.features.corporation.models; - -import com.j256.ormlite.field.DatabaseField; -import com.j256.ormlite.table.DatabaseTable; -import lombok.Getter; - -import java.util.UUID; - -@Getter -@DatabaseTable(tableName = "shops") -public class DBShop { - @DatabaseField(id = true) - private UUID id; - - @DatabaseField - private UUID owner; - @DatabaseField - private UUID city; - @DatabaseField - private UUID company; - - @DatabaseField(canBeNull = false) - private double x; - @DatabaseField(canBeNull = false) - private double y; - @DatabaseField(canBeNull = false) - private double z; - - DBShop() { - // required for ORMLite - } - - public DBShop(UUID id, UUID owner, UUID city, UUID company, double x, double y, double z) { - this.id = id; - this.owner = owner; - this.city = city; - this.company = company; - this.x = x; - this.y = y; - this.z = z; - } -} diff --git a/src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java b/src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java index 06077f326..92aa90d39 100644 --- a/src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java +++ b/src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java @@ -12,32 +12,32 @@ @Getter @DatabaseTable(tableName = "shop_items") public class DBShopItem { + @DatabaseField(id = true, columnName = "owner_uuid", canBeNull = false) + private UUID ownerUUID; @DatabaseField(canBeNull = false, dataType = DataType.BYTE_ARRAY) private byte[] items; @DatabaseField(canBeNull = false) - private UUID ownerUUID; - @DatabaseField(canBeNull = false) private double price; @DatabaseField(canBeNull = false) private int amount; @DatabaseField(canBeNull = false, columnName = "item_uuid") - private UUID itemUuid; + private UUID itemUUID; DBShopItem() { // required for ORMLite } - public DBShopItem(byte[] items, UUID ownerUUID, double price, int amount, UUID itemUuid) { + public DBShopItem(byte[] items, UUID ownerUUID, double price, int amount, UUID itemUUID) { this.items = items; this.ownerUUID = ownerUUID; this.price = price; this.amount = amount; - this.itemUuid = itemUuid; + this.itemUUID = itemUUID; } public ShopItem deserialize() { ItemStack item = ItemStack.deserializeBytes(items); - ShopItem shopItem = new ShopItem(item, price, itemUuid); + ShopItem shopItem = new ShopItem(item, price, itemUUID); shopItem.setAmount(amount); return shopItem; } diff --git a/src/main/java/fr/openmc/core/features/corporation/models/DBShopLocation.java b/src/main/java/fr/openmc/core/features/corporation/models/DBShopLocation.java new file mode 100644 index 000000000..0d5757223 --- /dev/null +++ b/src/main/java/fr/openmc/core/features/corporation/models/DBShopLocation.java @@ -0,0 +1,31 @@ +package fr.openmc.core.features.corporation.models; + +import com.j256.ormlite.field.DatabaseField; +import com.j256.ormlite.table.DatabaseTable; +import lombok.Getter; + +import java.util.UUID; + +@Getter +@DatabaseTable(tableName = "shop_location") +public class DBShopLocation { + @DatabaseField(id = true, columnName = "owner_uuid", canBeNull = false) + private UUID ownerUUID; + @DatabaseField(canBeNull = false) + private int x; + @DatabaseField(canBeNull = false) + private int y; + @DatabaseField(canBeNull = false) + private int z; + + DBShopLocation() { + // required for ORMLite + } + + public DBShopLocation(UUID ownerUUID, int x, int y, int z) { + this.ownerUUID = ownerUUID; + this.x = x; + this.y = y; + this.z = z; + } +} diff --git a/src/main/java/fr/openmc/core/features/corporation/models/DBShopSale.java b/src/main/java/fr/openmc/core/features/corporation/models/DBShopSale.java index a1c9390c4..3997bb12e 100644 --- a/src/main/java/fr/openmc/core/features/corporation/models/DBShopSale.java +++ b/src/main/java/fr/openmc/core/features/corporation/models/DBShopSale.java @@ -12,12 +12,12 @@ @Getter @DatabaseTable(tableName = "shop_sales") public class DBShopSale { + @DatabaseField(canBeNull = false, id = true, columnName = "owner_uuid") + private UUID ownerUUID; @DatabaseField(canBeNull = false, dataType = DataType.BYTE_ARRAY) private byte[] items; - @DatabaseField(canBeNull = false) - private UUID ownerUUID; @DatabaseField(canBeNull = false, columnName = "sale_uuid") - private UUID saleUuid; + private UUID saleUUID; @DatabaseField(canBeNull = false) private double price; @DatabaseField(canBeNull = false) @@ -27,17 +27,17 @@ public class DBShopSale { // required for ORMLite } - public DBShopSale(byte[] items, UUID ownerUUID, double price, int amount, UUID saleUuid) { + public DBShopSale(byte[] items, UUID ownerUUID, double price, int amount, UUID saleUUID) { this.items = items; this.ownerUUID = ownerUUID; this.price = price; this.amount = amount; - this.saleUuid = saleUuid; + this.saleUUID = saleUUID; } public ShopItem deserialize() { ItemStack item = ItemStack.deserializeBytes(items); - ShopItem shopItem = new ShopItem(item, price, saleUuid); + ShopItem shopItem = new ShopItem(item, price, saleUUID); shopItem.setAmount(amount); return shopItem; } diff --git a/src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java b/src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java index e8fb30a24..df00f1593 100644 --- a/src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java +++ b/src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java @@ -9,9 +9,7 @@ @DatabaseTable(tableName = "shop_suppliers") @Getter public class ShopSupplier { - @DatabaseField(id = true) - private UUID id; // différencie les supplier (un joueur peut avoir plusieurs suppliers) - @DatabaseField(canBeNull = false) + @DatabaseField(canBeNull = false, id = true, columnName = "owner_uuid") private UUID ownerUUID; @DatabaseField(canBeNull = false) private UUID item; @@ -26,8 +24,7 @@ public class ShopSupplier { // required for ORMLite } - public ShopSupplier(UUID id, UUID ownerUUID, UUID item, UUID player, int amount, long time) { - this.id = id; + public ShopSupplier(UUID ownerUUID, UUID item, UUID player, int amount, long time) { this.ownerUUID = ownerUUID; this.item = item; this.player = player; From f1dd92fd6dbbff21c86c6b54f1c1ba7fb39bcae7 Mon Sep 17 00:00:00 2001 From: gab4000 Date: Fri, 21 Nov 2025 18:49:45 +0100 Subject: [PATCH 8/9] refactor: rename shop-related classes and improve database management --- src/main/java/fr/openmc/core/OMCPlugin.java | 2 + .../corporation/company/Company.java.bak | 2 +- .../menu/company/ShopManageMenu.java.bak | 2 +- ...derIntegration.java => ShopFurniture.java} | 5 +- .../corporation/commands/ShopCommand.java | 128 +-------- .../corporation/listener/ShopListener.java | 56 ++-- .../manager/PlayerShopManager.java | 34 +-- .../manager/ShopDatabaseManager.java | 44 +++ .../corporation/manager/ShopManager.java | 133 +++------ .../corporation/menu/ShopCatalogueMenu.java | 69 +---- .../features/corporation/menu/ShopMenu.java | 267 +----------------- .../corporation/menu/ShopSalesMenu.java | 39 +-- .../corporation/menu/ShopStocksMenu.java | 116 +------- .../corporation/models/DBShopItem.java | 44 --- .../corporation/models/DBShopLocation.java | 31 -- .../corporation/{shops => models}/Shop.java | 164 +++-------- .../{shops => models}/ShopItem.java | 44 ++- .../models/{DBShopSale.java => ShopSale.java} | 7 +- .../corporation/models/ShopSupplier.java | 34 --- .../features/corporation/shops/Supply.java | 30 -- .../core/utils/database/DatabaseManager.java | 4 +- 21 files changed, 238 insertions(+), 1017 deletions(-) rename src/main/java/fr/openmc/core/features/corporation/{ItemsAdderIntegration.java => ShopFurniture.java} (88%) create mode 100644 src/main/java/fr/openmc/core/features/corporation/manager/ShopDatabaseManager.java delete mode 100644 src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java delete mode 100644 src/main/java/fr/openmc/core/features/corporation/models/DBShopLocation.java rename src/main/java/fr/openmc/core/features/corporation/{shops => models}/Shop.java (56%) rename src/main/java/fr/openmc/core/features/corporation/{shops => models}/ShopItem.java (62%) rename src/main/java/fr/openmc/core/features/corporation/models/{DBShopSale.java => ShopSale.java} (85%) delete mode 100644 src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java delete mode 100644 src/main/java/fr/openmc/core/features/corporation/shops/Supply.java diff --git a/src/main/java/fr/openmc/core/OMCPlugin.java b/src/main/java/fr/openmc/core/OMCPlugin.java index 2b4a542e7..06ed92594 100644 --- a/src/main/java/fr/openmc/core/OMCPlugin.java +++ b/src/main/java/fr/openmc/core/OMCPlugin.java @@ -16,6 +16,7 @@ import fr.openmc.core.features.city.sub.statistics.CityStatisticsManager; import fr.openmc.core.features.city.sub.war.WarManager; import fr.openmc.core.features.contest.managers.ContestManager; +import fr.openmc.core.features.corporation.manager.ShopManager; import fr.openmc.core.features.cube.multiblocks.MultiBlockManager; import fr.openmc.core.features.displays.TabList; import fr.openmc.core.features.displays.bossbar.BossbarManager; @@ -153,6 +154,7 @@ public void loadWithItemsAdder() { QuestsManager.init(); CityManager.init(); ContestManager.init(); + ShopManager.init(); if (WorldGuardHook.isHasWorldGuard()) { ParticleUtils.spawnParticlesInRegion("spawn", Bukkit.getWorld("world"), Particle.CHERRY_LEAVES, 50, 70, 130); ParticleUtils.spawnContestParticlesInRegion("spawn", Bukkit.getWorld("world"), 10, 70, 135); diff --git a/src/main/java/fr/openmc/core/disabled/corporation/company/Company.java.bak b/src/main/java/fr/openmc/core/disabled/corporation/company/Company.java.bak index d797933be..57ef1c744 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/company/Company.java.bak +++ b/src/main/java/fr/openmc/core/disabled/corporation/company/Company.java.bak @@ -12,7 +12,7 @@ import fr.openmc.core.disabled.corporation.models.DBCompany; import fr.openmc.core.features.city.City; import fr.openmc.core.features.city.CityManager; import fr.openmc.core.features.city.CityPermission; -import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.features.corporation.models.Shop; import fr.openmc.core.features.corporation.shops.ShopOwner; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.utils.Queue; diff --git a/src/main/java/fr/openmc/core/disabled/corporation/menu/company/ShopManageMenu.java.bak b/src/main/java/fr/openmc/core/disabled/corporation/menu/company/ShopManageMenu.java.bak index 9df092b46..c5b0818c1 100644 --- a/src/main/java/fr/openmc/core/disabled/corporation/menu/company/ShopManageMenu.java.bak +++ b/src/main/java/fr/openmc/core/disabled/corporation/menu/company/ShopManageMenu.java.bak @@ -7,7 +7,7 @@ import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.api.menulib.utils.StaticSlots; import fr.openmc.core.disabled.corporation.company.Company; import fr.openmc.core.features.corporation.manager.ShopManager; -import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.features.corporation.models.Shop; import fr.openmc.core.items.CustomItemRegistry; import net.kyori.adventure.text.Component; import org.bukkit.Material; diff --git a/src/main/java/fr/openmc/core/features/corporation/ItemsAdderIntegration.java b/src/main/java/fr/openmc/core/features/corporation/ShopFurniture.java similarity index 88% rename from src/main/java/fr/openmc/core/features/corporation/ItemsAdderIntegration.java rename to src/main/java/fr/openmc/core/features/corporation/ShopFurniture.java index 9bd0ed2f7..3716966c1 100644 --- a/src/main/java/fr/openmc/core/features/corporation/ItemsAdderIntegration.java +++ b/src/main/java/fr/openmc/core/features/corporation/ShopFurniture.java @@ -3,13 +3,14 @@ import dev.lone.itemsadder.api.CustomFurniture; import dev.lone.itemsadder.api.CustomStack; import fr.openmc.core.utils.world.Yaw; +import org.bukkit.Material; import org.bukkit.block.Block; -public class ItemsAdderIntegration { +public class ShopFurniture { public static boolean placeShopFurniture(Block block, Yaw playerYaw) { CustomStack customFurniture = CustomFurniture.getInstance("omc_company:caisse"); - if (customFurniture == null || block.getType() != org.bukkit.Material.AIR) return false; + if (customFurniture == null || block.getType() != Material.AIR) return false; CustomFurniture furniture = CustomFurniture.spawn("omc_company:caisse", block); furniture.getEntity().setRotation(playerYaw.getPlayerYaw(), 0); diff --git a/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java b/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java index 2033bed74..aa4725f0e 100644 --- a/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java +++ b/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java @@ -3,24 +3,15 @@ import fr.openmc.core.features.corporation.manager.PlayerShopManager; import fr.openmc.core.features.corporation.menu.ShopMenu; import fr.openmc.core.features.corporation.menu.ShopSearchMenu; -import fr.openmc.core.features.corporation.shops.Shop; -import fr.openmc.core.features.corporation.shops.ShopItem; -import fr.openmc.core.features.corporation.shops.Supply; import fr.openmc.core.features.economy.EconomyManager; -import fr.openmc.core.utils.ItemUtils; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; import net.kyori.adventure.text.Component; -import org.bukkit.Material; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; import revxrsal.commands.annotation.*; import revxrsal.commands.bukkit.annotation.CommandPermission; -import java.util.Iterator; -import java.util.Map; - @Command("shop") @Description("Manage shops") @CommandPermission("omc.commands.shop") @@ -34,60 +25,27 @@ public void onCommand(Player player) { } new ShopMenu(player).open(); } - - @Subcommand("manage") - @Description("Manage a shop") - public static void manageShop(Player player) { - - if (!PlayerShopManager.hasShop(player.getUniqueId())) { - MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.INFO, false); - return; - } - ShopMenu shopMenu = new ShopMenu(player); - shopMenu.open(); - } @Subcommand("help") @Description("Explique comment marche un shop") @Cooldown(30) public void help(Player player) { MessagesManager.sendMessage(player, Component.text(""" - §6§lListe des commandes entreprise : + §6§lListe des commandes shop : - §e▪ /shop create§7 - Crée un shop si vous regarder un tonneau + §e▪ /shop create§7 - Crée un shop si vous regardez un tonneau §e▪ /shop sell §7 - Permet de mettre en vente l'item dans votre main §e▪ /shop unsell§7 - Permet de retirer de la vente l'item que vous tenez en main §e▪ /shop delete§7 - Permet de supprimer votre shop en le regardant - §e▪ /shop manage§7 - Permet de gérer sont shop a distance seulement si vous n'êtes pas dans une entreprise §e▪ /shop search§7 - Permet de rechercher des shops par leur nom ou le nom du joueur """), - Prefix.ENTREPRISE, MessageType.INFO, false); + Prefix.SHOP, MessageType.INFO, false); } @Subcommand("sell") - @Description("Sell an item in your shop") + @Description("Sell an item in a shop") public void sellItem(Player player, @Named("price") double price) { - if (price<=0){ - MessagesManager.sendMessage(player, Component.text("§cVeuillez mettre un prix supérieur à zéro !"), Prefix.SHOP, MessageType.INFO, false); - return; - } - - if (!PlayerShopManager.hasShop(player.getUniqueId())) { - MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.INFO, false); - return; - } - Shop shop = PlayerShopManager.getPlayerShop(player.getUniqueId()); - ItemStack item = player.getInventory().getItemInMainHand(); - if (item.getType() == Material.AIR) { - MessagesManager.sendMessage(player, Component.text("§cVous devez tenir un item dans votre main"), Prefix.SHOP, MessageType.INFO, false); - return; - } - boolean itemThere = shop.addItem(item, price, 1, null); - if (itemThere) { - MessagesManager.sendMessage(player, Component.text("§cCet item est déjà dans le shop"), Prefix.SHOP, MessageType.INFO, false); - return; - } - MessagesManager.sendMessage(player, Component.text("§aL'item a bien été ajouté au shop !"), Prefix.SHOP, MessageType.SUCCESS, false); + } @Subcommand("create") @@ -106,31 +64,9 @@ public void createShop(Player player) { } @Subcommand("unsell") - @Description("Unsell an item in your shop") + @Description("Unsell an item of a shop") public void unsellItem(Player player, @Named("item number") int itemIndex) { - - if (!PlayerShopManager.hasShop(player.getUniqueId())) { - MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.WARNING, false); - return; - } - - Shop shop = PlayerShopManager.getPlayerShop(player.getUniqueId()); - ShopItem item = shop.getItem(itemIndex - 1); - - if (item == null) { - MessagesManager.sendMessage(player, Component.text("§cCet item n'est pas dans le shop"), Prefix.SHOP, MessageType.WARNING, false); - return; - } - - shop.removeItem(item); - MessagesManager.sendMessage(player, Component.text("§aL'item a bien été retiré du shop !"), Prefix.SHOP, MessageType.SUCCESS, false); - - if (item.getAmount() > 0) { - ItemStack toGive = item.getItem().clone(); - toGive.setAmount(item.getAmount()); - player.getInventory().addItem(toGive); - MessagesManager.sendMessage(player, Component.text("§6Vous avez récupéré le stock restant de cet item"), Prefix.SHOP, MessageType.SUCCESS, false); - } + } @Subcommand("delete") @@ -149,54 +85,4 @@ public void deleteShop(Player player) { public void searchShop(Player player){ new ShopSearchMenu(player).open(); } - - private void recoverStock(Player owner, ShopItem stock, Shop shop){ - if (stock.getAmount() <= 0) { - shop.removeItem(stock); - MessagesManager.sendMessage(owner, Component.text("§aL'item a bien été retiré du shop !"), Prefix.SHOP, MessageType.SUCCESS, false); - owner.closeInventory(); - return; - } - - int maxPlace = ItemUtils.getFreePlacesForItem(owner, stock.getItem()); - if (maxPlace <= 0) { - MessagesManager.sendMessage(owner, Component.text("§cVous n'avez pas assez de place"), Prefix.SHOP, MessageType.WARNING, false); - owner.closeInventory(); - return; - } - - int toTake = Math.min(stock.getAmount(), maxPlace); - - ItemStack toGive = stock.getItem().clone(); - toGive.setAmount(toTake); - owner.getInventory().addItem(toGive); - stock.setAmount(stock.getAmount() - toTake); - - if (stock.getAmount() > 0) { - MessagesManager.sendMessage(owner, Component.text("§6Vous avez récupéré §a" + toTake + "§6 dans le stock de cet item"), Prefix.SHOP, MessageType.SUCCESS, false); - } else { - MessagesManager.sendMessage(owner, Component.text("§6Vous avez récupéré le stock restant de cet item"), Prefix.SHOP, MessageType.SUCCESS, false); - } - - - // Mise à jour des suppliers - int toRemove = toTake; - Iterator> iterator = shop.getSuppliers().entrySet().iterator(); - while (iterator.hasNext() && toRemove > 0) { - Map.Entry entry = iterator.next(); - Supply supply = entry.getValue(); - - if (!supply.getItemId().equals(stock.getItemID())) continue; - - int supplyAmount = supply.getAmount(); - - if (supplyAmount <= toRemove) { - toRemove -= supplyAmount; - iterator.remove(); - } else { - supply.setAmount(supplyAmount - toRemove); - break; - } - } - } } diff --git a/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java b/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java index a3771ad15..2a652e5f3 100644 --- a/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java +++ b/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java @@ -5,12 +5,11 @@ import dev.lone.itemsadder.api.Events.FurnitureInteractEvent; import fr.openmc.core.features.corporation.manager.ShopManager; import fr.openmc.core.features.corporation.menu.ShopMenu; -import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.features.corporation.models.Shop; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; import net.kyori.adventure.text.Component; -import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Tag; import org.bukkit.block.Block; @@ -49,12 +48,11 @@ public void onEntityExplode(EntityExplodeEvent event) { @EventHandler public void onShopClick(PlayerInteractEvent event) { if (event.getClickedBlock() == null) return; - // Check if the clicked block is a sign with tags // Instead of getting the entire state of the block // This is much faster and avoids unnecessary overhead - if (! Tag.SIGNS.isTagged(event.getClickedBlock().getType())) return; + if (!Tag.SIGNS.isTagged(event.getClickedBlock().getType())) return; if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; @@ -62,7 +60,7 @@ public void onShopClick(PlayerInteractEvent event) { if (shop == null) return; event.setCancelled(true); - ShopMenu menu = new ShopMenu(event.getPlayer(), shop); + ShopMenu menu = new ShopMenu(event.getPlayer()); menu.open(); } @@ -72,18 +70,13 @@ public void onInteractWithBlock(PlayerInteractEvent e) { if (block == null || block.getType() != Material.BARREL) return; Shop shop = ShopManager.getShopAt(block.getLocation()); - boolean isShop = shop != null; - if (! isShop) return; + if (shop == null) return; if (shop.getOwnerUUID() == null) { e.setCancelled(true); return; } - if (! shop.getOwnerUUID().equals(e.getPlayer().getUniqueId())) { - e.setCancelled(true); - return; - } - inShopBarrel.put(e.getPlayer().getUniqueId(), isShop); + if (!shop.getOwnerUUID().equals(e.getPlayer().getUniqueId())) e.setCancelled(true); } /** @@ -107,25 +100,24 @@ public void onFurnitureBreak(FurnitureBreakEvent event) { public void onFurnitureInteract(FurnitureInteractEvent e) { if (e.getFurniture() == null) return; - if (e.getFurniture().getNamespacedID().equals("omc_company:caisse")) { - - if (e.getFurniture().getEntity() == null) { - MessagesManager.sendMessage(e.getPlayer(), Component.text("§cErreur lors de l'ouverture du shop, veuillez contacter le staff. (Entity is null)"), Prefix.SHOP, MessageType.ERROR, true); - return; - } - - double x = e.getFurniture().getEntity().getLocation().getBlockX(); - double y = e.getFurniture().getEntity().getLocation().getBlockY(); - double z = e.getFurniture().getEntity().getLocation().getBlockZ(); - - Shop shop = ShopManager.getShopAt(new Location(e.getFurniture().getEntity().getWorld(), x, y, z)); - if (shop == null) { - MessagesManager.sendMessage(e.getPlayer(), Component.text("§cErreur lors de l'ouverture du shop, veuillez contacter le staff. (Shop is null)"), Prefix.SHOP, MessageType.ERROR, true); - return; - } - - e.setCancelled(true); - new ShopMenu(e.getPlayer(), shop).open(); - } + if (!e.getFurniture().getNamespacedID().equals("omc_company:caisse")) return; + + if (e.getFurniture().getEntity() == null) { + MessagesManager.sendMessage(e.getPlayer(), Component.text("§cErreur lors de l'ouverture du shop, veuillez contacter le staff. (Entity is null)"), Prefix.SHOP, MessageType.ERROR, true); + return; + } + + int x = e.getFurniture().getEntity().getLocation().getBlockX(); + int y = e.getFurniture().getEntity().getLocation().getBlockY(); + int z = e.getFurniture().getEntity().getLocation().getBlockZ(); + + Shop shop = ShopManager.getShopAt(x, y, z); + if (shop == null) { + MessagesManager.sendMessage(e.getPlayer(), Component.text("§cErreur lors de l'ouverture du shop, veuillez contacter le staff. (Shop is null)"), Prefix.SHOP, MessageType.ERROR, true); + return; + } + + e.setCancelled(true); + new ShopMenu(e.getPlayer()).open(); } } diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java index d361efb11..9fa0baa4e 100644 --- a/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java @@ -3,9 +3,8 @@ import fr.openmc.api.hooks.ItemsAdderHook; import fr.openmc.api.input.location.ItemInteraction; import fr.openmc.core.OMCPlugin; -import fr.openmc.core.features.corporation.ItemsAdderIntegration; -import fr.openmc.core.features.corporation.models.DBShopLocation; -import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.features.corporation.ShopFurniture; +import fr.openmc.core.features.corporation.models.Shop; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.utils.messages.MessageType; import fr.openmc.core.utils.messages.MessagesManager; @@ -37,7 +36,10 @@ public class PlayerShopManager { * @param player the player who creates it */ public static void startCreatingShop(Player player) { - if (!EconomyManager.withdrawBalance(player.getUniqueId(), 500)) return; + if (!EconomyManager.withdrawBalance(player.getUniqueId(), 500)) { + MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas assez d'argent pour créer un shop (500 " + EconomyManager.getEconomyIcon() + " requis)"), Prefix.SHOP, MessageType.ERROR, true); + return; + } ItemInteraction.runLocationInteraction( player, @@ -48,7 +50,7 @@ public static void startCreatingShop(Player player) { "§cCréation de shop annulée", location -> { if (location == null) return false; - return createShop(player, location); + return createShop(player, location); }, () -> { EconomyManager.addBalance(player.getUniqueId(), 500, "Annulation création shop"); @@ -58,7 +60,7 @@ public static void startCreatingShop(Player player) { } private static boolean createShop(Player player, Location location) { - Shop shop = new Shop(player.getUniqueId(), location); + Shop shop = new Shop(player.getUniqueId(), location.setRotation(0, 0)); Block barrel = location.getBlock(); Block cashBlock = location.add(0, 1, 0).getBlock(); @@ -73,14 +75,6 @@ private static boolean createShop(Player player, Location location) { return false; } - try { - ShopManager.registerMultiblock(shop, new Shop.Multiblock(barrel.getLocation(), cashBlock.getLocation())); - } catch (RuntimeException e) { - MessagesManager.sendMessage(player, Component.text("§cErreur lors de la création du shop (cannot register multiblock) : §bappelez un admin"), Prefix.SHOP, MessageType.ERROR, true); - OMCPlugin.getInstance().getSLF4JLogger().error("Error registering multiblock for shop UUID: " + shop.getOwnerUUID().toString(), e); - return false; - } - if (ShopManager.placeShop(player, shop)) { barrel.setType(Material.BARREL); BlockData barrelData = barrel.getBlockData(); @@ -88,11 +82,11 @@ private static boolean createShop(Player player, Location location) { directional.setFacing(WorldUtils.getYaw(player).getOpposite().toBlockFace()); barrel.setBlockData(barrelData); } - - playerShops.put(player.getUniqueId(), shop); + + playerShops.put(player.getUniqueId(), shop); Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { - if (!ShopManager.saveShopLocation(new DBShopLocation(shop.getOwnerUUID(), barrel.getX(), barrel.getY(), barrel.getZ()))) { + if (!ShopDatabaseManager.saveShop(shop)) { MessagesManager.sendMessage(player, Component.text("§cErreur lors de la création du shop (cannot save shop location) : §bappelez un admin"), Prefix.SHOP, MessageType.ERROR, false); deleteShop(player, true); } @@ -103,7 +97,7 @@ private static boolean createShop(Player player, Location location) { return true; } else { if (ItemsAdderHook.isHasItemAdder()) - if (ItemsAdderIntegration.removeShopFurniture(cashBlock)) { + if (ShopFurniture.removeShopFurniture(cashBlock)) { cashBlock.setType(Material.AIR); barrel.setType(Material.AIR); } else { @@ -126,7 +120,7 @@ public static void deleteShop(Player player, boolean fromError) { } if (!ShopManager.removeShop(shop)) { - MessagesManager.sendMessage(player, Component.text("§cShop introuvable (appelez un admin)"), Prefix.SHOP, MessageType.ERROR, false); + MessagesManager.sendMessage(player, Component.text("§cShop introuvable (faites un screen de votre shop actuellement et appelez un admin)"), Prefix.SHOP, MessageType.ERROR, false); return; } @@ -134,7 +128,7 @@ public static void deleteShop(Player player, boolean fromError) { if (!fromError) { Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { - if (!ShopManager.deleteShopLocation(player.getUniqueId())) { + if (!ShopDatabaseManager.deleteShop(shop)) { MessagesManager.sendMessage(player, Component.text("§cErreur lors de la suppression du shop (appelez un admin)"), Prefix.SHOP, MessageType.ERROR, false); } }); diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/ShopDatabaseManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/ShopDatabaseManager.java new file mode 100644 index 000000000..3749abf69 --- /dev/null +++ b/src/main/java/fr/openmc/core/features/corporation/manager/ShopDatabaseManager.java @@ -0,0 +1,44 @@ +package fr.openmc.core.features.corporation.manager; + +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.dao.DaoManager; +import com.j256.ormlite.support.ConnectionSource; +import com.j256.ormlite.table.TableUtils; +import fr.openmc.core.OMCPlugin; +import fr.openmc.core.features.corporation.models.Shop; + +import java.sql.SQLException; + +public class ShopDatabaseManager { + + private static Dao shopDao; + + public static void initDB(ConnectionSource connectionSource) throws SQLException { + try { + TableUtils.createTableIfNotExists(connectionSource, Shop.class); + shopDao = DaoManager.createDao(connectionSource, Shop.class); + } catch (SQLException e) { + throw new SQLException(e); + } + } + + public static boolean saveShop(Shop shop) { + try { + shopDao.createOrUpdate(shop); + return true; + } catch (SQLException e) { + OMCPlugin.getInstance().getSLF4JLogger().error("Failed to save shop for owner UUID: {}", shop.getOwnerUUID(), e); + return false; + } + } + + public static boolean deleteShop(Shop shop) { + try { + shopDao.delete(shop); + return true; + } catch (SQLException e) { + OMCPlugin.getInstance().getSLF4JLogger().error("Failed to delete shop for owner UUID: {}", shop.getOwnerUUID(), e); + return false; + } + } +} diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java index 2939f0161..b7e3d9c45 100644 --- a/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java @@ -1,61 +1,25 @@ package fr.openmc.core.features.corporation.manager; -import com.j256.ormlite.dao.Dao; -import com.j256.ormlite.dao.DaoManager; -import com.j256.ormlite.support.ConnectionSource; -import com.j256.ormlite.table.TableUtils; import fr.openmc.api.hooks.ItemsAdderHook; import fr.openmc.core.OMCPlugin; -import fr.openmc.core.features.corporation.ItemsAdderIntegration; -import fr.openmc.core.features.corporation.models.DBShopItem; -import fr.openmc.core.features.corporation.models.DBShopLocation; -import fr.openmc.core.features.corporation.models.DBShopSale; -import fr.openmc.core.features.corporation.models.ShopSupplier; -import fr.openmc.core.features.corporation.shops.Shop; +import fr.openmc.core.features.corporation.ShopFurniture; +import fr.openmc.core.features.corporation.models.Shop; import fr.openmc.core.utils.world.WorldUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Player; -import java.sql.SQLException; import java.util.HashMap; import java.util.Map; -import java.util.UUID; public class ShopManager { - private static final Map multiblocks = new HashMap<>(); private static final Map shopsByLocation = new HashMap<>(); - private static Dao shopLocationDao; - private static Dao shopItemsDao; - private static Dao shopSalesDao; - private static Dao shopSuppliersDao; - - /** - * Registers a shop's multiblock structure and maps its key locations. - * - * @param shop The shop to register. - * @param multiblock The multiblock structure associated with the shop. - */ - public static void registerMultiblock(Shop shop, Shop.Multiblock multiblock) { - multiblocks.put(shop.getOwnerUUID(), multiblock); - Location stockLoc = multiblock.stockBlock(); - Location cashLoc = multiblock.cashBlock(); - shopsByLocation.put(stockLoc, shop); - shopsByLocation.put(cashLoc, shop); - } - - /** - * Retrieves the multiblock structure associated with a given UUID. - * - * @param uuid The UUID of the shop. - * @return The multiblock structure if it exists, otherwise null. - */ - public static Shop.Multiblock getMultiblock(UUID uuid) { - return multiblocks.get(uuid); + public static void init() { } /** @@ -65,8 +29,20 @@ public static Shop.Multiblock getMultiblock(UUID uuid) { * @return The shop found at that location, or null if none exists. */ public static Shop getShopAt(Location location) { - return shopsByLocation.get(location); + return shopsByLocation.get(location.setRotation(0, 0)); } + + /** + * Retrieves a shop located at a given location. + * + * @param x The x-coordinate of the location. + * @param y The y-coordinate of the location. + * @param z The z-coordinate of the location. + * @return The shop found at that location, or null if none exists. + */ + public static Shop getShopAt(int x, int y, int z) { + return shopsByLocation.get(new Location(Bukkit.getWorld("world"), x, y, z, 0, 0)); + } /** * Places the shop block (sign or ItemsAdder furniture) in the world, @@ -74,18 +50,20 @@ public static Shop getShopAt(Location location) { * * @param player The player placing the shop. * @param shop The shop to place. + * @return true if successfully placed, false otherwise. */ public static boolean placeShop(Player player, Shop shop) { - Shop.Multiblock multiblock = multiblocks.get(shop.getOwnerUUID()); + Shop.Multiblock multiblock = shop.getMultiblock(); if (multiblock == null) return false; Block cashBlock = multiblock.cashBlock().getBlock(); + + shopsByLocation.put(shop.getLocation(), shop); - if (ItemsAdderHook.isHasItemAdder()) { - if (!ItemsAdderIntegration.placeShopFurniture(cashBlock, WorldUtils.getYaw(player))) - cashBlock.setType(Material.OAK_SIGN); - } else cashBlock.setType(Material.OAK_SIGN); - + if (ItemsAdderHook.isHasItemAdder()) + if (!ShopFurniture.placeShopFurniture(cashBlock, WorldUtils.getYaw(player))) cashBlock.setType(Material.OAK_SIGN); + else cashBlock.setType(Material.OAK_SIGN); + return true; } @@ -94,65 +72,32 @@ public static boolean placeShop(Player player, Shop shop) { * Handles both ItemsAdder and fallback vanilla types. * * @param shop The shop to remove. - * @return True if successfully removed, false otherwise. + * @return true if successfully removed, false otherwise. */ public static boolean removeShop(Shop shop) { - Shop.Multiblock multiblock = multiblocks.get(shop.getOwnerUUID()); + Shop.Multiblock multiblock = shop.getMultiblock(); if (multiblock == null) return false; + + World world = Bukkit.getWorld("world"); + if (world == null) { + OMCPlugin.getInstance().getSLF4JLogger().error("World 'world' not found while removing shop at location: {}", shop.getLocation()); + return false; + } - Block cashBlock = multiblock.cashBlock().getBlock(); - Block stockBlock = multiblock.stockBlock().getBlock(); + Block cashBlock = world.getBlockAt(multiblock.cashBlock()); + Block stockBlock = world.getBlockAt(multiblock.stockBlock()); if (ItemsAdderHook.isHasItemAdder()) { - if (!ItemsAdderIntegration.hasFurniture(cashBlock)) return false; - if (!ItemsAdderIntegration.removeShopFurniture(cashBlock)) return false; - } else { - if ((cashBlock.getType() != Material.OAK_SIGN && cashBlock.getType() != Material.BARRIER) || stockBlock.getType() != Material.BARREL) { - return false; - } + if (!ShopFurniture.hasFurniture(cashBlock)) return false; + if (!ShopFurniture.removeShopFurniture(cashBlock)) return false; } - + else if ((cashBlock.getType() != Material.OAK_SIGN && cashBlock.getType() != Material.BARRIER) || stockBlock.getType() != Material.BARREL) return false; + cashBlock.setType(Material.AIR); // Remove sign or furniture block stockBlock.setType(Material.AIR); // Remove barrel block // Async cleanup of location mappings - multiblocks.remove(shop.getOwnerUUID()); - cashBlock.setType(Material.AIR); // Remove sign or furniture block Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> shopsByLocation.entrySet().removeIf(entry -> entry.getValue().getOwnerUUID().equals(shop.getOwnerUUID()))); return true; } - - public static void initDB(ConnectionSource connectionSource) throws SQLException { - TableUtils.createTableIfNotExists(connectionSource, DBShopLocation.class); - shopLocationDao = DaoManager.createDao(connectionSource, DBShopLocation.class); - - TableUtils.createTableIfNotExists(connectionSource, DBShopSale.class); - shopSalesDao = DaoManager.createDao(connectionSource, DBShopSale.class); - - TableUtils.createTableIfNotExists(connectionSource, DBShopItem.class); - shopItemsDao = DaoManager.createDao(connectionSource, DBShopItem.class); - - TableUtils.createTableIfNotExists(connectionSource, ShopSupplier.class); - shopSuppliersDao = DaoManager.createDao(connectionSource, ShopSupplier.class); - } - - public static boolean saveShopLocation(DBShopLocation dbShopLocation) { - try { - shopLocationDao.createOrUpdate(dbShopLocation); - return true; - } catch (SQLException e) { - OMCPlugin.getInstance().getSLF4JLogger().error("Error saving shop location for owner UUID: " + dbShopLocation.getOwnerUUID().toString(), e); - return false; - } - } - - public static boolean deleteShopLocation(UUID ownerUUID) { - try { - shopLocationDao.deleteById(ownerUUID); - return true; - } catch (SQLException e) { - OMCPlugin.getInstance().getSLF4JLogger().error("Error deleting shop location for owner UUID: " + ownerUUID.toString(), e); - return false; - } - } } diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/ShopCatalogueMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopCatalogueMenu.java index 54fde478a..d3d65f269 100644 --- a/src/main/java/fr/openmc/core/features/corporation/menu/ShopCatalogueMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopCatalogueMenu.java @@ -5,12 +5,6 @@ import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.api.menulib.utils.StaticSlots; -import fr.openmc.core.features.corporation.shops.Shop; -import fr.openmc.core.features.corporation.shops.ShopItem; -import fr.openmc.core.items.CustomItemRegistry; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.NamedTextColor; -import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; @@ -20,18 +14,13 @@ import org.jetbrains.annotations.Nullable; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; public class ShopCatalogueMenu extends PaginatedMenu { - private final Shop shop; - private final int itemIndex; - public ShopCatalogueMenu(Player owner, Shop shop, int itemIndex) { + public ShopCatalogueMenu(Player owner) { super(owner); - this.shop = shop; - this.itemIndex = itemIndex; } @Override @@ -56,40 +45,17 @@ public int getSizeOfItems() { @Override public List getItems() { - List items = new ArrayList<>(); - - for (ShopItem shopItem : shop.getItems()){ - items.add(new ItemBuilder(this, shopItem.getItem().getType(), itemMeta -> { - itemMeta.displayName(ShopItem.getItemName(shopItem.getItem()).color(NamedTextColor.GRAY).decorate(TextDecoration.BOLD)); - }).setOnClick(inventoryClickEvent -> { - new ShopMenu(getOwner(), shop, getIndex(shopItem)).open(); - })); - } - - return items; - } - - @Override - public Map getButtons() { - Map buttons = new HashMap<>(); - buttons.put(49, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_cancel").getBest(), itemMeta -> itemMeta.itemName(Component.text("§7Fermer"))) - .setCloseButton()); - ItemBuilder nextPageButton = new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_next_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§aPage suivante"))); - if ((getPage() == 0 && isLastPage()) || shop.getItems().isEmpty()) { - buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§cRetour"))) - .setOnClick(inventoryClickEvent -> new ShopMenu(getOwner(), shop, itemIndex).open())); - buttons.put(50, nextPageButton); - } else { - buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§cPage précédente"))) - .setPreviousPageButton()); - buttons.put(50, nextPageButton.setNextPageButton()); - } - return buttons; + return new ArrayList<>(); } - - @Override + + @Override + public Map getButtons() { + return Map.of(); + } + + @Override public @NotNull String getName() { - return "Menu du shop " + shop.getName(); + return "Menu du shop "; } @Override @@ -111,19 +77,4 @@ public void onClose(InventoryCloseEvent event) { public List getTakableSlot() { return List.of(); } - - /** - * get the index of a ShopItem - * - * @param shopItem the ShopItem - * @return the index of the ShopItem - */ - private int getIndex(ShopItem shopItem) { - int index = 0; - for (ShopItem items : shop.getItems()){ - if (items == shopItem) return index; - index++; - } - return index; - } } diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java index 51485832b..c9c7b3a6a 100644 --- a/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopMenu.java @@ -1,76 +1,33 @@ package fr.openmc.core.features.corporation.menu; -import dev.lone.itemsadder.api.FontImages.FontImageWrapper; import fr.openmc.api.menulib.Menu; -import fr.openmc.api.menulib.template.ConfirmMenu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; -import fr.openmc.core.features.corporation.MethodState; -import fr.openmc.core.features.corporation.manager.PlayerShopManager; -import fr.openmc.core.features.corporation.shops.Shop; -import fr.openmc.core.features.corporation.shops.ShopItem; -import fr.openmc.core.features.economy.EconomyManager; -import fr.openmc.core.items.CustomItemRegistry; -import fr.openmc.core.utils.ItemUtils; -import fr.openmc.core.utils.messages.MessageType; -import fr.openmc.core.utils.messages.MessagesManager; -import fr.openmc.core.utils.messages.Prefix; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.NamedTextColor; -import net.kyori.adventure.text.format.TextDecoration; -import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.BookMeta; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ShopMenu extends Menu { - private final List items = new ArrayList<>(); - private final Shop shop; - private final int itemIndex; - private int amountToBuy = 1; public ShopMenu(Player owner) { - this(owner, PlayerShopManager.getPlayerShop(owner.getUniqueId())); - } - - public ShopMenu(Player owner, Shop shop) { - this(owner, shop, 0); - } - - public ShopMenu(Player owner, Shop shop, int itemIndex) { super(owner); - this.shop = shop; - this.itemIndex = itemIndex; - items.addAll(shop.getItems()); - shop.checkStock(); } @Override public @NotNull String getName() { - return "Menu du shop " + shop.getName(); + return "Menu du shop "; } @Override public String getTexture() { -// if (shop.getOwner().isCompany()){ -// Company company = shop.getOwner().getCompany(); -// if (company.getAllMembers().contains(getOwner().getUniqueId())){ -// return FontImageWrapper.replaceFontImages("§r§f:offset_-11::shop_menu:"); -// } -// } -// if (!shop.isOwner(getOwner().getUniqueId())) -// return FontImageWrapper.replaceFontImages("§r§f:offset_-11::shop_menu:"); - return FontImageWrapper.replaceFontImages("§r§f:offset_-11::shop_menu:"); + return ""; } @Override @@ -91,90 +48,7 @@ public void onClose(InventoryCloseEvent event) { @Override public @NotNull Map getContent() { Map content = new HashMap<>(); - - if (shop.isOwner(getOwner().getUniqueId())) { - putOwnerItems(content); - } - - content.put(39, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> { - itemMeta.itemName(Component.text("§cItem précédent")); - }).setOnClick(inventoryClickEvent -> new ShopMenu(getOwner(), shop, onFirstItem() ? itemIndex : itemIndex - 1).open())); - - content.put(41, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_next_orange").getBest(), itemMeta -> { - itemMeta.itemName(Component.text("§aItem suivant")); - }).setOnClick(inventoryClickEvent -> new ShopMenu(getOwner(), shop, onLastItem() ? itemIndex : itemIndex + 1).open())); - - content.put(40, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_cancel").getBest(), itemMeta -> { - itemMeta.itemName(Component.text("§7Fermer")); - }).setCloseButton()); - - content.put(19, new ItemBuilder(this, CustomItemRegistry.getByName("omc_menus:minus_btn").getBest(), itemMeta -> { - itemMeta.itemName(Component.text("§5Définir à 1")); - }).setOnClick(inventoryClickEvent -> { - if (getCurrentItem() == null) return; - amountToBuy = 1; - open(); - })); - - content.put(20, new ItemBuilder(this, CustomItemRegistry.getByName("omc_menus:10_btn").getBest(), itemMeta -> { - itemMeta.displayName(Component.text("§cRetirer 10")); - }).setOnClick(inventoryClickEvent -> { - if (getCurrentItem() == null) return; - if (amountToBuy == 1) return; - if (amountToBuy - 10 < 1) { - amountToBuy = 1; - } else { - amountToBuy -= 10; - } - open(); - })); - content.put(21, new ItemBuilder(this, CustomItemRegistry.getByName("omc_menus:1_btn").getBest(), itemMeta -> { - itemMeta.displayName(Component.text("§cRetirer 1")); - }).setOnClick(inventoryClickEvent -> { - if (getCurrentItem() == null) return; - if (amountToBuy == 1) return; - amountToBuy--; - open(); - })); - - if (getCurrentItem() != null) - content.put(22, new ItemBuilder(this, getCurrentItem().getItem(), itemMeta -> { - itemMeta.displayName(ItemUtils.getItemTranslation(getCurrentItem().getItem()).color(NamedTextColor.GRAY).decorate(TextDecoration.BOLD).decoration(TextDecoration.ITALIC, TextDecoration.State.FALSE)); - itemMeta.lore(List.of( - Component.text("§7■ Prix: §c" + EconomyManager.getFormattedNumber(getCurrentItem().getPricePerItem() * amountToBuy)), - Component.text("§7■ En stock: " + EconomyManager.getFormattedSimplifiedNumber(getCurrentItem().getAmount())), - Component.text("§7■ Cliquez pour en acheter §f" + EconomyManager.getFormattedSimplifiedNumber(amountToBuy)) - )); - }).setOnClick(inventoryClickEvent -> new ConfirmMenu(getOwner(), this::buyAccept, this::refuse, List.of(Component.text("§aAcheter")), List.of(Component.text("§cAnnuler l'achat"))).open())); - - content.put(23, new ItemBuilder(this, CustomItemRegistry.getByName("omc_menus:1_btn").getBest(), itemMeta -> { - itemMeta.displayName(Component.text("§aAjouter 1")); - }).setOnClick(inventoryClickEvent -> { - if (getCurrentItem() == null) return; - amountToBuy = getCurrentItem().getAmount()<=amountToBuy ? getCurrentItem().getAmount() : amountToBuy + 1; - open(); - })); - content.put(24, new ItemBuilder(this, CustomItemRegistry.getByName("omc_menus:10_btn").getBest(), itemMeta -> { - itemMeta.displayName(Component.text("§aAjouter 10")); - }).setOnClick(inventoryClickEvent -> { - if (getCurrentItem() == null) return; - amountToBuy = getCurrentItem().getAmount()<=amountToBuy ? getCurrentItem().getAmount() : amountToBuy + 10; - open(); - })); - - content.put(25, new ItemBuilder(this, CustomItemRegistry.getByName("omc_menus:64_btn").getBest(), itemMeta -> { - itemMeta.displayName(Component.text("§5Ajouter 64")); - }).setOnClick(inventoryClickEvent -> { - if (getCurrentItem() == null) return; - if (amountToBuy == 1) amountToBuy = 64; - else amountToBuy = getCurrentItem().getAmount()<=amountToBuy ? getCurrentItem().getAmount() : amountToBuy + 64; - open(); - })); - - content.put(44, new ItemBuilder(this, CustomItemRegistry.getByName("omc_company:company_box").getBest(), itemMeta -> { - itemMeta.displayName(Component.text("§7Catalogue")); - }).setOnClick(inventoryClickEvent -> new ShopCatalogueMenu(getOwner(), shop, itemIndex).open())); - + return content; } @@ -182,139 +56,4 @@ public void onClose(InventoryCloseEvent event) { public List getTakableSlot() { return List.of(); } - - private void putOwnerItems(Map content) { - - content.put(0, new ItemBuilder(this, CustomItemRegistry.getByName("omc_homes:omc_homes_icon_bin_red").getBest(), itemMeta -> { - itemMeta.displayName(Component.text("§c§lSupprimer le shop")); - }).setOnClick(inventoryClickEvent -> new ConfirmMenu(getOwner(), this::accept, this::refuse, List.of(Component.text("§aSupprimer")), List.of(Component.text("§cAnnuler la suppression"))).open())); - - content.put(3, new ItemBuilder(this, Material.PAPER, itemMeta -> { - itemMeta.displayName(Component.text("§a§lVos ventes")); - itemMeta.lore(List.of( - Component.text("§7■ Ventes: §f" + shop.getSales().size()), - Component.text("§7■ Cliquer pour voir vos ventes sur ce shop") - )); - }).setOnClick(inventoryClickEvent -> new ShopSalesMenu(getOwner(), shop, itemIndex).open())); - - content.put(4, shop.getIcon(this, true)); - - content.put(5, new ItemBuilder(this, Material.BARREL, itemMeta -> { - itemMeta.displayName(Component.text("§6§lVoir les stocks")); - itemMeta.lore(List.of( - Component.text("§7■ Stocks: §f" + shop.getAllItemsAmount()), - Component.text("§7■ Cliquer pour voir les stocks de ce shop") - )); - }).setOnClick(inventoryClickEvent -> new ShopStocksMenu(getOwner(), shop, itemIndex).open())); - - content.put(8, new ItemBuilder(this, Material.LIME_WOOL, itemMeta -> { - itemMeta.displayName(Component.text("§aCe shop vous appartient")); - })); - - content.put(36, new ItemBuilder(this, Material.WRITABLE_BOOK, itemMeta -> { - itemMeta.displayName(Component.text("§7Comment utiliser les shops")); - }).setOnClick(inventoryClickEvent -> { - - ItemStack book = new ItemStack(Material.WRITTEN_BOOK); - BookMeta meta = (BookMeta) book.getItemMeta(); - if (meta != null) { - meta = meta.toBuilder().title(Component.text("Guide des Shops")).author(Component.text("Nocolm")) - .addPage(Component.text( - """ - Comment utiliser les shops ! - - §l§6Stock§r : - 1. Utilisez la commande §d§l/shop sell §r§7 §r en tenant l'item en main - 2. Ajoutez les items dans le barril §c§l* le raccourci avec les chiffres ne fonctionnera pas * - """ - )) - .addPage(Component.text( - """ - 3. Ouvrez une fois le shop pour renouveler son stock - - Et voilà comment utiliser votre shop - - §6▪ Pour plus d'info : /shop help§r""" - )).build(); - - book.setItemMeta(meta); - } - getOwner().closeInventory(); - getOwner().openBook(book); - - content.remove(44); - })); - } - - /** - * @return the current ShopItem - */ - private ShopItem getCurrentItem() { - if (itemIndex < 0 || itemIndex >= items.size()) { - return null; - } - return items.get(itemIndex); - } - - /** - * @return true if the menu is on the first item - */ - private boolean onFirstItem() { - return itemIndex == 0; - } - - /** - * @return true if the menu is on the last item - */ - private boolean onLastItem() { - return itemIndex == items.size() - 1; - } - - private void buyAccept() { - MethodState buyState = shop.buy(getCurrentItem(), amountToBuy, getOwner()); - if (buyState == MethodState.ERROR) { - MessagesManager.sendMessage(getOwner(), Component.text("§cVous n'avez pas assez d'argent pour acheter cet item"), Prefix.SHOP, MessageType.INFO, false); - getOwner().closeInventory(); - return; - } - - if (buyState == MethodState.FAILURE) { - MessagesManager.sendMessage(getOwner(), Component.text("§cVous ne pouvez pas acheter vos propres items"), Prefix.SHOP, MessageType.INFO, false); - getOwner().closeInventory(); - return; - } - - if (buyState == MethodState.WARNING) { - MessagesManager.sendMessage(getOwner(), Component.text("§cIl n'y a pas assez de stock pour acheter cet item"), Prefix.SHOP, MessageType.INFO, false); - getOwner().closeInventory(); - return; - } - if (buyState == MethodState.SPECIAL) { - MessagesManager.sendMessage(getOwner(), Component.text("§cVous n'avez pas assez de place dans votre inventaire"), Prefix.SHOP, MessageType.INFO, false); - getOwner().closeInventory(); - return; - } - if (buyState == MethodState.ESCAPE) { - MessagesManager.sendMessage(getOwner(), Component.text("§cErreur lors de l'achat"), Prefix.SHOP, MessageType.INFO, false); - getOwner().closeInventory(); - return; - } - MessagesManager.sendMessage(getOwner(), Component.text("§aVous avez bien acheté " + amountToBuy + " ").append( ItemUtils.getItemTranslation(getCurrentItem().getItem()).color(NamedTextColor.GREEN).decorate(TextDecoration.BOLD)).append(Component.text(" pour " + (getCurrentItem().getPricePerItem() * amountToBuy) + EconomyManager.getEconomyIcon())), Prefix.SHOP, MessageType.INFO, false); - getOwner().closeInventory(); - } - - private void accept() { - if (shop == null) { - MessagesManager.sendMessage(getOwner(), Component.text("§cShop introuvable, impossible de le supprimer"), Prefix.SHOP, MessageType.INFO, false); - getOwner().closeInventory(); - return; - } - - PlayerShopManager.deleteShop(getOwner(), false); - getOwner().closeInventory(); - } - - private void refuse() { - getOwner().closeInventory(); - } } diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/ShopSalesMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopSalesMenu.java index 1bcfb7018..760e956cb 100644 --- a/src/main/java/fr/openmc/core/features/corporation/menu/ShopSalesMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopSalesMenu.java @@ -5,13 +5,6 @@ import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.api.menulib.utils.StaticSlots; -import fr.openmc.core.features.corporation.shops.Shop; -import fr.openmc.core.features.corporation.shops.ShopItem; -import fr.openmc.core.features.economy.EconomyManager; -import fr.openmc.core.items.CustomItemRegistry; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.NamedTextColor; -import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; @@ -26,13 +19,8 @@ public class ShopSalesMenu extends PaginatedMenu { - private final Shop shop; - private final int itemIndex; - - public ShopSalesMenu(Player owner, Shop shop, int itemIndex) { + public ShopSalesMenu(Player owner) { super(owner); - this.shop = shop; - this.itemIndex = itemIndex; } @Override @@ -58,39 +46,20 @@ public int getSizeOfItems() { @Override public List getItems() { List items = new java.util.ArrayList<>(); - for (ShopItem sale : shop.getSales()) { - items.add(new ItemBuilder(this, sale.getItem().getType(), itemMeta -> { - itemMeta.displayName(ShopItem.getItemName(sale.getItem()).color(NamedTextColor.YELLOW).decorate(TextDecoration.BOLD)); - itemMeta.lore(List.of( - Component.text("§7■ Prix : §a" + sale.getPrice() + EconomyManager.getEconomyIcon()), - Component.text("§7■ Quantité : §a" + sale.getAmount()) - )); - })); - } + return items; } @Override public Map getButtons() { Map buttons = new HashMap<>(); - buttons.put(49, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_cancel").getBest(), itemMeta -> itemMeta.itemName(Component.text("§7Fermer"))) - .setCloseButton()); - ItemBuilder nextPageButton = new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_next_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§aPage suivante"))); - if ((getPage() == 0 && isLastPage()) || shop.getSales().isEmpty()) { - buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§cRetour"))) - .setOnClick(inventoryClickEvent -> new ShopMenu(getOwner(), shop, itemIndex).open())); - buttons.put(50, nextPageButton); - } else { - buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§cPage précédente"))) - .setPreviousPageButton()); - buttons.put(50, nextPageButton.setNextPageButton()); - } + return buttons; } @Override public @NotNull String getName() { - return "Ventes de " + shop.getName(); + return "Ventes de "; } @Override diff --git a/src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java b/src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java index 2de1c0318..30fdcceb1 100644 --- a/src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java +++ b/src/main/java/fr/openmc/core/features/corporation/menu/ShopStocksMenu.java @@ -2,22 +2,9 @@ import dev.lone.itemsadder.api.FontImages.FontImageWrapper; import fr.openmc.api.menulib.PaginatedMenu; -import fr.openmc.api.menulib.template.ConfirmMenu; import fr.openmc.api.menulib.utils.InventorySize; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.api.menulib.utils.StaticSlots; -import fr.openmc.core.features.corporation.shops.Shop; -import fr.openmc.core.features.corporation.shops.ShopItem; -import fr.openmc.core.features.corporation.shops.Supply; -import fr.openmc.core.features.economy.EconomyManager; -import fr.openmc.core.items.CustomItemRegistry; -import fr.openmc.core.utils.ItemUtils; -import fr.openmc.core.utils.messages.MessageType; -import fr.openmc.core.utils.messages.MessagesManager; -import fr.openmc.core.utils.messages.Prefix; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.NamedTextColor; -import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; @@ -26,23 +13,14 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class ShopStocksMenu extends PaginatedMenu { - private final Shop shop; - private final int itemIndex; - private ShopItem stock; - private final List accetpMsg = new ArrayList<>(); - private final List denyMsg = new ArrayList<>(); - - public ShopStocksMenu(Player owner, Shop shop, int itemIndex) { + public ShopStocksMenu(Player owner) { super(owner); - this.shop = shop; - this.itemIndex = itemIndex; - - accetpMsg.add(Component.text("§aRécupérer")); - denyMsg.add(Component.text("§cAnnuler")); } @Override @@ -69,43 +47,19 @@ public int getSizeOfItems() { public List getItems() { List items = new java.util.ArrayList<>(); - for (ShopItem stock : shop.getItems()) { - items.add(new ItemBuilder(this, stock.getItem().getType(), itemMeta -> { - itemMeta.displayName(ShopItem.getItemName(stock.getItem()).color(NamedTextColor.GRAY).decorate(TextDecoration.BOLD)); - itemMeta.lore(List.of( - Component.text("§7■ Quantité restante : " + EconomyManager.getFormattedSimplifiedNumber(stock.getAmount())), - Component.text("§7■ Prix de vente (par item) : " + EconomyManager.getFormattedNumber(stock.getPricePerItem())), - Component.text("§7" + (stock.getAmount() > 0 ? "■ Click gauche pour récupérer le stock" : "■ Click gauche pour retirer l'item de la vente")) - )); - }).setOnClick(inventoryClickEvent -> { - this.stock = stock; - new ConfirmMenu(getOwner(),this::accept, this::refuse,accetpMsg, denyMsg).open(); - })); - } return items; } @Override public Map getButtons() { Map buttons = new HashMap<>(); - buttons.put(49, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_cancel").getBest(), itemMeta -> itemMeta.itemName(Component.text("§7Fermer"))) - .setCloseButton()); - ItemBuilder nextPageButton = new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_next_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§aPage suivante"))); - if ((getPage() == 0 && isLastPage()) || shop.getSales().isEmpty()) { - buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§cRetour"))) - .setOnClick(inventoryClickEvent -> new ShopMenu(getOwner(), shop, itemIndex).open())); - buttons.put(50, nextPageButton); - } else { - buttons.put(48, new ItemBuilder(this, CustomItemRegistry.getByName("_iainternal:icon_back_orange").getBest(), itemMeta -> itemMeta.itemName(Component.text("§cPage précédente"))) - .setPreviousPageButton()); - buttons.put(50, nextPageButton.setNextPageButton()); - } + return buttons; } @Override public @NotNull String getName() { - return "Menu des Stocks de " + shop.getName(); + return "Menu des Stocks de "; } @Override @@ -127,62 +81,4 @@ public void onClose(InventoryCloseEvent event) { public List getTakableSlot() { return List.of(); } - - private void accept() { - Player owner = getOwner(); - - if (stock.getAmount() <= 0) { - shop.removeItem(stock); - MessagesManager.sendMessage(owner, Component.text("§aL'item a bien été retiré du shop !"), Prefix.SHOP, MessageType.SUCCESS, false); - owner.closeInventory(); - return; - } - - int maxPlace = ItemUtils.getFreePlacesForItem(owner, stock.getItem()); - if (maxPlace <= 0) { - MessagesManager.sendMessage(owner, Component.text("§cVous n'avez pas assez de place"), Prefix.SHOP, MessageType.INFO, false); - owner.closeInventory(); - return; - } - - int toTake = Math.min(stock.getAmount(), maxPlace); - - ItemStack toGive = stock.getItem().clone(); - toGive.setAmount(toTake); - owner.getInventory().addItem(toGive); - stock.setAmount(stock.getAmount() - toTake); - - if (stock.getAmount() > 0) { - MessagesManager.sendMessage(owner, Component.text("§6Vous avez récupéré §a" + toTake + "§6 dans le stock de cet item"), Prefix.SHOP, MessageType.SUCCESS, false); - } else { - MessagesManager.sendMessage(owner, Component.text("§6Vous avez récupéré le stock restant de cet item"), Prefix.SHOP, MessageType.SUCCESS, false); - } - - // Mise à jour des suppliers - int toRemove = toTake; - Iterator> iterator = shop.getSuppliers().entrySet().iterator(); - while (iterator.hasNext() && toRemove > 0) { - Map.Entry entry = iterator.next(); - Supply supply = entry.getValue(); - - if (!supply.getItemId().equals(stock.getItemID())) continue; - - int supplyAmount = supply.getAmount(); - - if (supplyAmount <= toRemove) { - toRemove -= supplyAmount; - iterator.remove(); - } else { - supply.setAmount(supplyAmount - toRemove); - break; - } - } - - owner.closeInventory(); - } - - - private void refuse() { - getOwner().closeInventory(); - } } diff --git a/src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java b/src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java deleted file mode 100644 index 92aa90d39..000000000 --- a/src/main/java/fr/openmc/core/features/corporation/models/DBShopItem.java +++ /dev/null @@ -1,44 +0,0 @@ -package fr.openmc.core.features.corporation.models; - -import com.j256.ormlite.field.DataType; -import com.j256.ormlite.field.DatabaseField; -import com.j256.ormlite.table.DatabaseTable; -import fr.openmc.core.features.corporation.shops.ShopItem; -import lombok.Getter; -import org.bukkit.inventory.ItemStack; - -import java.util.UUID; - -@Getter -@DatabaseTable(tableName = "shop_items") -public class DBShopItem { - @DatabaseField(id = true, columnName = "owner_uuid", canBeNull = false) - private UUID ownerUUID; - @DatabaseField(canBeNull = false, dataType = DataType.BYTE_ARRAY) - private byte[] items; - @DatabaseField(canBeNull = false) - private double price; - @DatabaseField(canBeNull = false) - private int amount; - @DatabaseField(canBeNull = false, columnName = "item_uuid") - private UUID itemUUID; - - DBShopItem() { - // required for ORMLite - } - - public DBShopItem(byte[] items, UUID ownerUUID, double price, int amount, UUID itemUUID) { - this.items = items; - this.ownerUUID = ownerUUID; - this.price = price; - this.amount = amount; - this.itemUUID = itemUUID; - } - - public ShopItem deserialize() { - ItemStack item = ItemStack.deserializeBytes(items); - ShopItem shopItem = new ShopItem(item, price, itemUUID); - shopItem.setAmount(amount); - return shopItem; - } -} diff --git a/src/main/java/fr/openmc/core/features/corporation/models/DBShopLocation.java b/src/main/java/fr/openmc/core/features/corporation/models/DBShopLocation.java deleted file mode 100644 index 0d5757223..000000000 --- a/src/main/java/fr/openmc/core/features/corporation/models/DBShopLocation.java +++ /dev/null @@ -1,31 +0,0 @@ -package fr.openmc.core.features.corporation.models; - -import com.j256.ormlite.field.DatabaseField; -import com.j256.ormlite.table.DatabaseTable; -import lombok.Getter; - -import java.util.UUID; - -@Getter -@DatabaseTable(tableName = "shop_location") -public class DBShopLocation { - @DatabaseField(id = true, columnName = "owner_uuid", canBeNull = false) - private UUID ownerUUID; - @DatabaseField(canBeNull = false) - private int x; - @DatabaseField(canBeNull = false) - private int y; - @DatabaseField(canBeNull = false) - private int z; - - DBShopLocation() { - // required for ORMLite - } - - public DBShopLocation(UUID ownerUUID, int x, int y, int z) { - this.ownerUUID = ownerUUID; - this.x = x; - this.y = y; - this.z = z; - } -} diff --git a/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java b/src/main/java/fr/openmc/core/features/corporation/models/Shop.java similarity index 56% rename from src/main/java/fr/openmc/core/features/corporation/shops/Shop.java rename to src/main/java/fr/openmc/core/features/corporation/models/Shop.java index 4ee2c6414..6c7f5448a 100644 --- a/src/main/java/fr/openmc/core/features/corporation/shops/Shop.java +++ b/src/main/java/fr/openmc/core/features/corporation/models/Shop.java @@ -1,5 +1,7 @@ -package fr.openmc.core.features.corporation.shops; +package fr.openmc.core.features.corporation.models; +import com.j256.ormlite.field.DatabaseField; +import com.j256.ormlite.table.DatabaseTable; import fr.openmc.api.menulib.Menu; import fr.openmc.api.menulib.utils.ItemBuilder; import fr.openmc.core.features.corporation.MethodState; @@ -22,41 +24,46 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; @Getter +@DatabaseTable(tableName = "shops") public class Shop { - private final UUID ownerUUID; + @DatabaseField(id = true, columnName = "owner_uuid", canBeNull = false) + private UUID ownerUUID; + @DatabaseField(canBeNull = false) + private int x; + @DatabaseField(canBeNull = false) + private int y; + @DatabaseField(canBeNull = false) + private int z; + private final List items = new ArrayList<>(); private final List sales = new ArrayList<>(); - private final Map suppliers = new HashMap<>(); - private final Location location; + + private Location location; + private Multiblock multiblock; private double turnover = 0; + Shop() { + // required for ORMLite + } + + public Shop(UUID ownerUUID, int x, int y, int z) { + this(ownerUUID, new Location(Bukkit.getWorld("world"), x, y, z)); + } + public Shop(UUID ownerUUID, Location location) { this.ownerUUID = ownerUUID; - this.location = location; - } - - /** - * get the shop with what player looking - * - * @param player the player we check - * @param onlyCash if we only check the cach register - */ - public static UUID getShopPlayerLookingAt(Player player, boolean onlyCash) { - Block targetBlock = player.getTargetBlockExact(5); - - if (targetBlock == null) return null; - - if (targetBlock.getType() != Material.BARREL && targetBlock.getType() != Material.OAK_SIGN && targetBlock.getType() != Material.BARRIER) return null; - if (onlyCash) if (targetBlock.getType() == Material.BARREL) return null; - - Shop shop = ShopManager.getShopAt(targetBlock.getLocation()); - if (shop == null) return null; - return shop.getOwnerUUID(); + this.x = location.getBlockX(); + this.y = location.getBlockY(); + this.z = location.getBlockZ(); + this.location = location.toBlockLocation(); + this.multiblock = new Multiblock(this.location, this.location.clone().add(0, 1, 0)); } /** @@ -65,11 +72,9 @@ public static UUID getShopPlayerLookingAt(Player player, boolean onlyCash) { * quand un item est vendu un partie du profit reviens a celui qui a approvisionner */ public void checkStock() { - Multiblock multiblock = ShopManager.getMultiblock(ownerUUID); + Multiblock multiblock = getMultiblock(); - if (multiblock == null) { - return; - } + if (multiblock == null) return; Block stockBlock = multiblock.stockBlock().getBlock(); if (stockBlock.getType() != Material.BARREL) { @@ -81,14 +86,10 @@ public void checkStock() { Inventory inventory = barrel.getInventory(); for (ItemStack item : inventory.getContents()) { - if (item == null || item.getType() == Material.AIR) { - continue; - } - + if (item == null || item.getType() == Material.AIR) continue; + ItemMeta itemMeta = item.getItemMeta(); - if (itemMeta == null) { - continue; - } + if (itemMeta == null) continue; } } } @@ -123,16 +124,6 @@ public ShopItem getItem(int index) { return items.get(index); } - /** - * remove an item from the shop - * - * @param item the item to remove - */ - public void removeItem(ShopItem item) { - items.remove(item); - suppliers.entrySet().removeIf(entry -> entry.getValue().getItemId().equals(item.getItemID())); - } - /** * add an item to the shop * @@ -150,64 +141,6 @@ public boolean addItem(ItemStack itemStack, double price, int amount, UUID itemI return false; } - public int recoverItemOf(ShopItem item, Player supplier) { - int amount = item.getAmount(); - - if (ItemUtils.getFreePlacesForItem(supplier,item.getItem()) < amount){ - MessagesManager.sendMessage(supplier, Component.text("§cVous n'avez pas assez de place"), Prefix.SHOP, MessageType.INFO, false); - return 0; - } - - int toRemove = 0; - - Iterator> iterator = suppliers.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry entry = iterator.next(); - - if (! entry.getValue().getSupplierUUID().equals(supplier.getUniqueId())) continue; - if (! entry.getValue().getItemId().equals(item.getItemID())) continue; - - amount -= entry.getValue().getAmount(); - toRemove += entry.getValue().getAmount(); - - if (amount < 0) { - break; - } else { - iterator.remove(); - } - } - - if (amount == 0) { - items.remove(item); - MessagesManager.sendMessage(supplier, Component.text("§aL'item a bien été retiré du shop !"), Prefix.SHOP, MessageType.SUCCESS, false); - } else { - item.setAmount(amount); - } - - return toRemove; - } - - public void addSupply(long time, Supply supply){ - suppliers.put(time, supply); - } - - /** - * update the amount of all the item in the shop according to the items in the barrel - */ - public boolean supply(ItemStack item, UUID supplier) { - for (ShopItem shopItem : items) { - if (! shopItem.getItem().getType().equals(item.getType())) continue; - - int delay = 0; - shopItem.setAmount(shopItem.getAmount() + item.getAmount()); - while (suppliers.containsKey(System.currentTimeMillis() + delay)) delay++; - - suppliers.put(System.currentTimeMillis() + delay, new Supply(supplier, shopItem.getItemID(), item.getAmount())); - return true; - } - return false; - } - /** * buy an item in the shop * @@ -243,27 +176,6 @@ public MethodState buy(ShopItem item, int amountToBuy, Player buyer) { return MethodState.SUCCESS; } - private void removeLatestSupply() { - long latest = 0; - Supply supply = null; - for (Map.Entry entry : suppliers.entrySet()) { - if (entry.getKey() > latest) { - latest = entry.getKey(); - supply = entry.getValue(); - } - } - if (supply == null) return; - - suppliers.remove(latest); - } - - public boolean isSupplier(UUID playerUUID){ - for (Map.Entry entry : suppliers.entrySet()) { - if (entry.getValue().getSupplierUUID().equals(playerUUID)) return true; - } - return false; - } - /** * get the shop Icon * @@ -275,7 +187,7 @@ public ItemBuilder getIcon(Menu menu, boolean fromShopMenu) { itemMeta.displayName(Component.text("§e§l" + (fromShopMenu ? "Informations" : getName()))); List lore = new ArrayList<>(List.of( - Component.text("§7■ Chiffre d'affaire : " + EconomyManager.getFormattedNumber(turnover)), + Component.text("§7■ Chiffre d'affaires : " + EconomyManager.getFormattedNumber(turnover)), Component.text("§7■ Ventes : §f" + sales.size()) )); if (! fromShopMenu) lore.add(Component.text("§7■ Cliquez pour accéder au shop")); diff --git a/src/main/java/fr/openmc/core/features/corporation/shops/ShopItem.java b/src/main/java/fr/openmc/core/features/corporation/models/ShopItem.java similarity index 62% rename from src/main/java/fr/openmc/core/features/corporation/shops/ShopItem.java rename to src/main/java/fr/openmc/core/features/corporation/models/ShopItem.java index b03763407..1644ca60d 100644 --- a/src/main/java/fr/openmc/core/features/corporation/shops/ShopItem.java +++ b/src/main/java/fr/openmc/core/features/corporation/models/ShopItem.java @@ -1,5 +1,7 @@ -package fr.openmc.core.features.corporation.shops; +package fr.openmc.core.features.corporation.models; +import com.j256.ormlite.field.DatabaseField; +import com.j256.ormlite.table.DatabaseTable; import fr.openmc.core.utils.ItemUtils; import lombok.Getter; import net.kyori.adventure.text.Component; @@ -10,14 +12,29 @@ import java.util.UUID; +import static com.j256.ormlite.field.DataType.BYTE_ARRAY; + @Getter +@DatabaseTable(tableName = "shop_items") public class ShopItem { - - private final UUID itemID; - private final ItemStack item; - private final double pricePerItem; - private double price; + + @DatabaseField(id = true, columnName = "owner_uuid", canBeNull = false) + private UUID ownerUUID; + @DatabaseField(canBeNull = false, columnName = "item_uuid") + private UUID itemUUID; + @DatabaseField(canBeNull = false) + private double pricePerItem; + @DatabaseField(canBeNull = false) private int amount; + @DatabaseField(canBeNull = false, dataType = BYTE_ARRAY) + private byte[] itemBytes; + + private double price; + private ItemStack item; + + ShopItem() { + // required for ORMLite + } public ShopItem(ItemStack item, double pricePerItem) { this(item, pricePerItem, UUID.randomUUID()); @@ -29,7 +46,15 @@ public ShopItem(ItemStack item, double pricePerItem, UUID itemID) { this.item.setAmount(1); this.price = pricePerItem * amount; this.amount = 0; - this.itemID = itemID; + this.itemUUID = itemID; + } + + public ShopItem(byte[] itemBytes, UUID ownerUUID, double price, int amount, UUID itemUUID) { + this.itemBytes = itemBytes; + this.ownerUUID = ownerUUID; + this.price = price; + this.amount = amount; + this.itemUUID = itemUUID; } /** @@ -77,4 +102,9 @@ public ShopItem copy() { public double getPrice(int amount) { return pricePerItem * amount; } + + public ShopItem deserialize() { + ItemStack item = ItemStack.deserializeBytes(itemBytes); + return new ShopItem(item, price, itemUUID).setAmount(amount); + } } diff --git a/src/main/java/fr/openmc/core/features/corporation/models/DBShopSale.java b/src/main/java/fr/openmc/core/features/corporation/models/ShopSale.java similarity index 85% rename from src/main/java/fr/openmc/core/features/corporation/models/DBShopSale.java rename to src/main/java/fr/openmc/core/features/corporation/models/ShopSale.java index 3997bb12e..496bbb250 100644 --- a/src/main/java/fr/openmc/core/features/corporation/models/DBShopSale.java +++ b/src/main/java/fr/openmc/core/features/corporation/models/ShopSale.java @@ -3,7 +3,6 @@ import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; -import fr.openmc.core.features.corporation.shops.ShopItem; import lombok.Getter; import org.bukkit.inventory.ItemStack; @@ -11,7 +10,7 @@ @Getter @DatabaseTable(tableName = "shop_sales") -public class DBShopSale { +public class ShopSale { @DatabaseField(canBeNull = false, id = true, columnName = "owner_uuid") private UUID ownerUUID; @DatabaseField(canBeNull = false, dataType = DataType.BYTE_ARRAY) @@ -23,11 +22,11 @@ public class DBShopSale { @DatabaseField(canBeNull = false) private int amount; - DBShopSale() { + ShopSale() { // required for ORMLite } - public DBShopSale(byte[] items, UUID ownerUUID, double price, int amount, UUID saleUUID) { + public ShopSale(byte[] items, UUID ownerUUID, double price, int amount, UUID saleUUID) { this.items = items; this.ownerUUID = ownerUUID; this.price = price; diff --git a/src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java b/src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java deleted file mode 100644 index df00f1593..000000000 --- a/src/main/java/fr/openmc/core/features/corporation/models/ShopSupplier.java +++ /dev/null @@ -1,34 +0,0 @@ -package fr.openmc.core.features.corporation.models; - -import com.j256.ormlite.field.DatabaseField; -import com.j256.ormlite.table.DatabaseTable; -import lombok.Getter; - -import java.util.UUID; - -@DatabaseTable(tableName = "shop_suppliers") -@Getter -public class ShopSupplier { - @DatabaseField(canBeNull = false, id = true, columnName = "owner_uuid") - private UUID ownerUUID; - @DatabaseField(canBeNull = false) - private UUID item; - @DatabaseField(canBeNull = false) - private UUID player; - @DatabaseField(defaultValue = "0") - private int amount; - @DatabaseField(defaultValue = "0") - private long time; - - ShopSupplier() { - // required for ORMLite - } - - public ShopSupplier(UUID ownerUUID, UUID item, UUID player, int amount, long time) { - this.ownerUUID = ownerUUID; - this.item = item; - this.player = player; - this.amount = amount; - this.time = time; - } -} diff --git a/src/main/java/fr/openmc/core/features/corporation/shops/Supply.java b/src/main/java/fr/openmc/core/features/corporation/shops/Supply.java deleted file mode 100644 index 7832dfdb1..000000000 --- a/src/main/java/fr/openmc/core/features/corporation/shops/Supply.java +++ /dev/null @@ -1,30 +0,0 @@ -package fr.openmc.core.features.corporation.shops; - -import lombok.Getter; -import lombok.Setter; - -import java.util.UUID; - -@Getter -public class Supply { - - private final UUID supplier; - private final UUID itemId; - private final UUID supplierUUID; - @Setter - private int amount; - - public Supply(UUID supplier, UUID itemId, int amount) { - this.supplier = supplier; - this.itemId = itemId; - this.amount = amount; - this.supplierUUID = UUID.randomUUID(); - } - - public Supply(UUID supplier, UUID itemId, int amount, UUID supplierUUID) { - this.supplier = supplier; - this.itemId = itemId; - this.amount = amount; - this.supplierUUID = supplierUUID; - } -} diff --git a/src/main/java/fr/openmc/core/utils/database/DatabaseManager.java b/src/main/java/fr/openmc/core/utils/database/DatabaseManager.java index f77f4a0ce..71e2b5e25 100644 --- a/src/main/java/fr/openmc/core/utils/database/DatabaseManager.java +++ b/src/main/java/fr/openmc/core/utils/database/DatabaseManager.java @@ -13,7 +13,7 @@ import fr.openmc.core.features.city.sub.statistics.CityStatisticsManager; import fr.openmc.core.features.city.sub.war.WarManager; import fr.openmc.core.features.contest.managers.ContestManager; -import fr.openmc.core.features.corporation.manager.ShopManager; +import fr.openmc.core.features.corporation.manager.ShopDatabaseManager; import fr.openmc.core.features.economy.BankManager; import fr.openmc.core.features.economy.EconomyManager; import fr.openmc.core.features.economy.TransactionsManager; @@ -71,7 +71,7 @@ public static void init() { MascotsManager.initDB(connectionSource); PlayerSettingsManager.initDB(connectionSource); CityStatisticsManager.initDB(connectionSource); - ShopManager.initDB(connectionSource); + ShopDatabaseManager.initDB(connectionSource); HalloweenManager.initDB(connectionSource); } catch (SQLException e) { OMCPlugin.getInstance().getSLF4JLogger().error("Failed to initialize the database connection.", e); From a7c19448391e4413913ca1f424481790152a5a3a Mon Sep 17 00:00:00 2001 From: gab4000 Date: Sat, 13 Dec 2025 15:59:00 +0100 Subject: [PATCH 9/9] feat: add admin shop management and enhance ShopManager functionality --- .../java/fr/openmc/core/CommandsManager.java | 4 +- src/main/java/fr/openmc/core/OMCPlugin.java | 3 + .../commands/ShopAdminCommand.java | 99 +++++++++++++++++++ .../corporation/commands/ShopCommand.java | 7 +- .../ShopAdminCommandPlayerAutocomplete.java | 24 +++++ .../corporation/listener/ShopListener.java | 14 ++- .../manager/PlayerShopManager.java | 53 +++++----- .../manager/ShopDatabaseManager.java | 33 ++++++- .../corporation/manager/ShopManager.java | 98 ++++++++++++++++-- 9 files changed, 286 insertions(+), 49 deletions(-) create mode 100644 src/main/java/fr/openmc/core/features/corporation/commands/ShopAdminCommand.java create mode 100644 src/main/java/fr/openmc/core/features/corporation/commands/autocomplete/ShopAdminCommandPlayerAutocomplete.java diff --git a/src/main/java/fr/openmc/core/CommandsManager.java b/src/main/java/fr/openmc/core/CommandsManager.java index b7dbc1814..92d83c900 100644 --- a/src/main/java/fr/openmc/core/CommandsManager.java +++ b/src/main/java/fr/openmc/core/CommandsManager.java @@ -8,6 +8,7 @@ import fr.openmc.core.commands.fun.Playtime; import fr.openmc.core.commands.utils.*; import fr.openmc.core.features.adminshop.AdminShopCommand; +import fr.openmc.core.features.corporation.commands.ShopAdminCommand; import fr.openmc.core.features.corporation.commands.ShopCommand; import fr.openmc.core.features.credits.CreditsCommand; import fr.openmc.core.features.cube.CubeCommands; @@ -60,7 +61,8 @@ private static void registerCommands() { new Cooldowns(), new CreditsCommand(), new CubeCommands(), - new ShopCommand(), + new ShopCommand(), + new ShopAdminCommand(), new HalloweenCommands() ); } diff --git a/src/main/java/fr/openmc/core/OMCPlugin.java b/src/main/java/fr/openmc/core/OMCPlugin.java index f7190c9f4..03cf5f3e0 100644 --- a/src/main/java/fr/openmc/core/OMCPlugin.java +++ b/src/main/java/fr/openmc/core/OMCPlugin.java @@ -218,6 +218,9 @@ public void onDisable() { // - Cooldowns DynamicCooldownManager.saveCooldowns(); + + // - Shops + ShopManager.shutdown(); if (!OMCPlugin.isUnitTestVersion()) { diff --git a/src/main/java/fr/openmc/core/features/corporation/commands/ShopAdminCommand.java b/src/main/java/fr/openmc/core/features/corporation/commands/ShopAdminCommand.java new file mode 100644 index 000000000..47154d558 --- /dev/null +++ b/src/main/java/fr/openmc/core/features/corporation/commands/ShopAdminCommand.java @@ -0,0 +1,99 @@ +package fr.openmc.core.features.corporation.commands; + +import fr.openmc.core.features.corporation.commands.autocomplete.ShopAdminCommandPlayerAutocomplete; +import fr.openmc.core.features.corporation.manager.PlayerShopManager; +import fr.openmc.core.features.corporation.manager.ShopManager; +import fr.openmc.core.features.corporation.models.Shop; +import fr.openmc.core.utils.messages.MessageType; +import fr.openmc.core.utils.messages.MessagesManager; +import fr.openmc.core.utils.messages.Prefix; +import net.kyori.adventure.text.Component; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import revxrsal.commands.annotation.*; +import revxrsal.commands.bukkit.annotation.CommandPermission; + +@Command("shopadmin") +@CommandPermission("omc.admins.commands.shop") +public class ShopAdminCommand { + + @Subcommand("database query shops") + public void databaseQueryShops(Player player, @Optional @Named("playerShop") @SuggestWith(ShopAdminCommandPlayerAutocomplete.class) OfflinePlayer playerShop) { + if (playerShop == null) { + if (ShopManager.loadShops()) { + MessagesManager.sendMessage(player, Component.text("§aChargement des shops depuis la base de données réussi"), Prefix.SHOP, MessageType.SUCCESS, false); + } else { + MessagesManager.sendMessage(player, Component.text("§cÉchec du chargement des shops depuis la base de données (Error in console)"), Prefix.SHOP, MessageType.ERROR, false); + } + } else { + if (ShopManager.loadShopFor(playerShop)) { + MessagesManager.sendMessage(player, Component.text("§aChargement du shop du joueur §6" + playerShop.getName() + "§a depuis la base de données réussi"), Prefix.SHOP, MessageType.SUCCESS, false); + } else { + MessagesManager.sendMessage(player, Component.text("§cÉchec du chargement du shop du joueur §6" + playerShop.getName() + "§c depuis la base de données (Error in console)"), Prefix.SHOP, MessageType.ERROR, false); + } + } + } + + @Subcommand("database query shop_sales") + public void databaseQueryShopSales(Player player, @Optional @Named("playerShop") @SuggestWith(ShopAdminCommandPlayerAutocomplete.class) OfflinePlayer playerShop) { + + } + + @Subcommand("database query shop_items") + public void databaseQueryShopItems(Player player, @Optional @Named("playerShop") @SuggestWith(ShopAdminCommandPlayerAutocomplete.class) OfflinePlayer playerShop) { + + } + + @Subcommand("database save shops") + public void databaseSaveShops(Player player, @Optional @Named("playerShop") @SuggestWith(ShopAdminCommandPlayerAutocomplete.class) OfflinePlayer playerShop) { + if (playerShop == null) { + if (ShopManager.saveShops()) { + MessagesManager.sendMessage(player, Component.text("§aSauvegarde des shops dans la base de données réussi"), Prefix.SHOP, MessageType.SUCCESS, false); + } else { + MessagesManager.sendMessage(player, Component.text("§cÉchec de la sauvegarde des shops dans la base de données (Error in console)"), Prefix.SHOP, MessageType.ERROR, false); + } + } else { + if (ShopManager.saveShopFor(playerShop)) { + MessagesManager.sendMessage(player, Component.text("§aSauvegarde du shop du joueur §6" + playerShop.getName() + "§a dans la base de données réussi"), Prefix.SHOP, MessageType.SUCCESS, false); + } else { + MessagesManager.sendMessage(player, Component.text("§cÉchec de la sauvegarde du shop du joueur §6" + playerShop.getName() + "§c dans la base de données (Error in console)"), Prefix.SHOP, MessageType.ERROR, false); + } + } + } + + @Subcommand("database save shop_sales") + public void databaseSaveShopSales(Player player, @Optional @Named("playerShop") @SuggestWith(ShopAdminCommandPlayerAutocomplete.class) OfflinePlayer playerShop) { + + } + + @Subcommand("database save shop_items") + public void databaseSaveShopItems(Player player, @Optional @Named("playerShop") @SuggestWith(ShopAdminCommandPlayerAutocomplete.class) OfflinePlayer playerShop) { + + } + + @Subcommand("removeshop") + public void removeShop(Player player, @Named("playerShop") @SuggestWith(ShopAdminCommandPlayerAutocomplete.class) OfflinePlayer target) { + if (target == null) { + MessagesManager.sendMessage(player, Component.text("§cLe joueur spécifié est introuvable"), Prefix.SHOP, MessageType.ERROR, false); + return; + } + + if (!ShopManager.hasShop(target.getUniqueId())) { + MessagesManager.sendMessage(player, Component.text("§cLe joueur spécifié n'a pas de shop"), Prefix.SHOP, MessageType.ERROR, false); + return; + } + + Shop shop = ShopManager.getPlayerShop(target.getUniqueId()); + if (shop == null) { + MessagesManager.sendMessage(player, Component.text("§cLe shop du joueur spécifié est introuvable"), Prefix.SHOP, MessageType.ERROR, false); + return; + } + + if (!shop.getItems().isEmpty()) { + MessagesManager.sendMessage(player, Component.text("§cLe shop du joueur spécifié n'est pas vide"), Prefix.SHOP, MessageType.ERROR, false); + return; + } + + PlayerShopManager.adminDeleteShop(target, player); + } +} diff --git a/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java b/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java index aa4725f0e..5729dff79 100644 --- a/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java +++ b/src/main/java/fr/openmc/core/features/corporation/commands/ShopCommand.java @@ -1,6 +1,7 @@ package fr.openmc.core.features.corporation.commands; import fr.openmc.core.features.corporation.manager.PlayerShopManager; +import fr.openmc.core.features.corporation.manager.ShopManager; import fr.openmc.core.features.corporation.menu.ShopMenu; import fr.openmc.core.features.corporation.menu.ShopSearchMenu; import fr.openmc.core.features.economy.EconomyManager; @@ -19,7 +20,7 @@ public class ShopCommand { @CommandPlaceholder public void onCommand(Player player) { - if (!PlayerShopManager.hasShop(player.getUniqueId())) { + if (!ShopManager.hasShop(player.getUniqueId())) { MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.INFO, false); return; } @@ -51,7 +52,7 @@ public void sellItem(Player player, @Named("price") double price) { @Subcommand("create") @Description("Create a shop") public void createShop(Player player) { - if (PlayerShopManager.hasShop(player.getUniqueId())) { + if (ShopManager.hasShop(player.getUniqueId())) { MessagesManager.sendMessage(player, Component.text("§cVous avez déjà un shop"), Prefix.SHOP, MessageType.INFO, false); return; } @@ -72,7 +73,7 @@ public void unsellItem(Player player, @Named("item number") int itemIndex) { @Subcommand("delete") @Description("Delete a shop") public void deleteShop(Player player) { - if (!PlayerShopManager.hasShop(player.getUniqueId())) { + if (!ShopManager.hasShop(player.getUniqueId())) { MessagesManager.sendMessage(player, Component.text("§cVous n'avez pas de shop"), Prefix.SHOP, MessageType.WARNING, false); return; } diff --git a/src/main/java/fr/openmc/core/features/corporation/commands/autocomplete/ShopAdminCommandPlayerAutocomplete.java b/src/main/java/fr/openmc/core/features/corporation/commands/autocomplete/ShopAdminCommandPlayerAutocomplete.java new file mode 100644 index 000000000..f1b20d4c2 --- /dev/null +++ b/src/main/java/fr/openmc/core/features/corporation/commands/autocomplete/ShopAdminCommandPlayerAutocomplete.java @@ -0,0 +1,24 @@ +package fr.openmc.core.features.corporation.commands.autocomplete; + +import fr.openmc.core.features.corporation.manager.ShopManager; +import fr.openmc.core.features.corporation.models.Shop; +import fr.openmc.core.utils.cache.CacheOfflinePlayer; +import org.jetbrains.annotations.NotNull; +import revxrsal.commands.autocomplete.SuggestionProvider; +import revxrsal.commands.bukkit.actor.BukkitCommandActor; +import revxrsal.commands.node.ExecutionContext; + +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +public class ShopAdminCommandPlayerAutocomplete implements SuggestionProvider { + @Override + public @NotNull Set getSuggestions(@NotNull ExecutionContext context) { + Set shops = ShopManager.getAllShops(); + return shops.stream() + .map(shop -> CacheOfflinePlayer.getOfflinePlayer(shop.getOwnerUUID()).getName()) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + } +} diff --git a/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java b/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java index 2a652e5f3..f56eb2780 100644 --- a/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java +++ b/src/main/java/fr/openmc/core/features/corporation/listener/ShopListener.java @@ -98,20 +98,18 @@ public void onFurnitureBreak(FurnitureBreakEvent event) { @EventHandler public void onFurnitureInteract(FurnitureInteractEvent e) { - if (e.getFurniture() == null) return; + CustomFurniture furniture = e.getFurniture(); + + if (furniture == null) return; - if (!e.getFurniture().getNamespacedID().equals("omc_company:caisse")) return; + if (!furniture.getNamespacedID().equals("omc_company:caisse")) return; - if (e.getFurniture().getEntity() == null) { + if (furniture.getEntity() == null) { MessagesManager.sendMessage(e.getPlayer(), Component.text("§cErreur lors de l'ouverture du shop, veuillez contacter le staff. (Entity is null)"), Prefix.SHOP, MessageType.ERROR, true); return; } - int x = e.getFurniture().getEntity().getLocation().getBlockX(); - int y = e.getFurniture().getEntity().getLocation().getBlockY(); - int z = e.getFurniture().getEntity().getLocation().getBlockZ(); - - Shop shop = ShopManager.getShopAt(x, y, z); + Shop shop = ShopManager.getShopAt(furniture.getEntity().getLocation().subtract(0, 1, 0).toBlockLocation()); if (shop == null) { MessagesManager.sendMessage(e.getPlayer(), Component.text("§cErreur lors de l'ouverture du shop, veuillez contacter le staff. (Shop is null)"), Prefix.SHOP, MessageType.ERROR, true); return; diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java index 9fa0baa4e..9f4c5807c 100644 --- a/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/PlayerShopManager.java @@ -10,25 +10,19 @@ import fr.openmc.core.utils.messages.MessagesManager; import fr.openmc.core.utils.messages.Prefix; import fr.openmc.core.utils.world.WorldUtils; -import lombok.Getter; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.OfflinePlayer; import org.bukkit.block.Block; import org.bukkit.block.data.BlockData; import org.bukkit.block.data.Directional; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - public class PlayerShopManager { - @Getter - private static final Map playerShops = new HashMap<>(); /** * Create a shop if the player has enough money and does not already have one @@ -83,7 +77,7 @@ private static boolean createShop(Player player, Location location) { barrel.setBlockData(barrelData); } - playerShops.put(player.getUniqueId(), shop); + ShopManager.getPlayerShops().put(player.getUniqueId(), shop); Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { if (!ShopDatabaseManager.saveShop(shop)) { @@ -113,7 +107,7 @@ private static boolean createShop(Player player, Location location) { * @param player The player who deletes the shop */ public static void deleteShop(Player player, boolean fromError) { - Shop shop = getPlayerShop(player.getUniqueId()); + Shop shop = ShopManager.getPlayerShop(player.getUniqueId()); if (!fromError && !shop.getItems().isEmpty()) { MessagesManager.sendMessage(player, Component.text("§cVotre shop n'est pas vide"), Prefix.SHOP, MessageType.WARNING, false); return; @@ -124,7 +118,7 @@ public static void deleteShop(Player player, boolean fromError) { return; } - playerShops.remove(player.getUniqueId()); + ShopManager.getPlayerShops().remove(player.getUniqueId()); if (!fromError) { Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { @@ -139,24 +133,25 @@ public static void deleteShop(Player player, boolean fromError) { EconomyManager.addBalance(player.getUniqueId(), 400); MessagesManager.sendMessage(player, Component.text("§a400" + EconomyManager.getEconomyIcon() + " remboursés sur votre compte personnel"), Prefix.SHOP, MessageType.SUCCESS, true); } - - /** - * Get a shop from the UUID of a player - * - * @param playerUUID the UUID of the player to check - * @return the Shop if found - */ - public static Shop getPlayerShop(UUID playerUUID) { - return playerShops.get(playerUUID); - } - - /** - * Check if a player has a shop - * - * @param playerUUID the UUID of the player to check - * @return true if a shop is found - */ - public static boolean hasShop(UUID playerUUID) { - return getPlayerShop(playerUUID) != null; + + public static void adminDeleteShop(OfflinePlayer player, Player admin) { + Shop shop = ShopManager.getPlayerShop(player.getUniqueId()); + if (shop == null) return; + + if (!ShopManager.removeShop(shop)) { + MessagesManager.sendMessage(admin, Component.text("§cShop introuvable"), Prefix.SHOP, MessageType.ERROR, false); + return; + } + ShopManager.getPlayerShops().remove(player.getUniqueId()); + + Bukkit.getScheduler().runTaskAsynchronously(OMCPlugin.getInstance(), () -> { + if (!ShopDatabaseManager.deleteShop(shop)) { + MessagesManager.sendMessage(admin, Component.text("§cErreur lors de la suppression du shop"), Prefix.SHOP, MessageType.ERROR, false); + } + }); + + MessagesManager.sendMessage(admin, Component.text("§6Le shop a bien été supprimé !"), Prefix.SHOP, MessageType.SUCCESS, false); + EconomyManager.addBalance(player.getUniqueId(), 400); + MessagesManager.sendMessage(player, Component.text("§a400" + EconomyManager.getEconomyIcon() + " remboursés sur votre compte personnel"), Prefix.SHOP, MessageType.SUCCESS, true); } } diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/ShopDatabaseManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/ShopDatabaseManager.java index 3749abf69..17e2cef8d 100644 --- a/src/main/java/fr/openmc/core/features/corporation/manager/ShopDatabaseManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/ShopDatabaseManager.java @@ -6,12 +6,19 @@ import com.j256.ormlite.table.TableUtils; import fr.openmc.core.OMCPlugin; import fr.openmc.core.features.corporation.models.Shop; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.jetbrains.annotations.Nullable; import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; public class ShopDatabaseManager { - private static Dao shopDao; + private static Dao shopDao; public static void initDB(ConnectionSource connectionSource) throws SQLException { try { @@ -21,6 +28,30 @@ public static void initDB(ConnectionSource connectionSource) throws SQLException throw new SQLException(e); } } + + public static @Nullable Map loadShops() { + Map shopsByLocation = new HashMap<>(); + try { + List shops = shopDao.queryForAll(); + for (Shop shop : shops) { + Location loc = new Location(Bukkit.getWorld("world"), shop.getX(), shop.getY(), shop.getZ()); + shopsByLocation.put(loc, shop); + } + } catch (SQLException e) { + OMCPlugin.getInstance().getSLF4JLogger().error("Failed to load shops from database", e); + return null; + } + return shopsByLocation; + } + + public static @Nullable Shop loadShopFor(UUID ownerUUID) { + try { + return shopDao.queryForId(ownerUUID); + } catch (SQLException e) { + OMCPlugin.getInstance().getSLF4JLogger().error("Failed to load shop for owner UUID: {}", ownerUUID, e); + return null; + } + } public static boolean saveShop(Shop shop) { try { diff --git a/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java b/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java index b7e3d9c45..f65db5b69 100644 --- a/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java +++ b/src/main/java/fr/openmc/core/features/corporation/manager/ShopManager.java @@ -5,22 +5,84 @@ import fr.openmc.core.features.corporation.ShopFurniture; import fr.openmc.core.features.corporation.models.Shop; import fr.openmc.core.utils.world.WorldUtils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; +import lombok.Getter; +import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.entity.Player; import java.util.HashMap; import java.util.Map; +import java.util.Set; +import java.util.UUID; public class ShopManager { - - private static final Map shopsByLocation = new HashMap<>(); + + @Getter + private static final Map playerShops = new HashMap<>(); + private static Map shopsByLocation; public static void init() { + loadShops(); } + + public static void shutdown() { + saveShops(); + } + + public static boolean loadShops() { + if (shopsByLocation != null) shopsByLocation.clear(); + OMCPlugin.getInstance().getSLF4JLogger().info("Loading shops from database..."); + shopsByLocation = ShopDatabaseManager.loadShops(); + if (shopsByLocation == null) { + OMCPlugin.getInstance().getSLF4JLogger().error("Failed to initialize ShopManager due to database load failure. No shops loaded."); + shopsByLocation = new HashMap<>(); + return false; + } + shopsByLocation.values().forEach(shop -> setPlayerShop(shop.getOwnerUUID(), shop)); + OMCPlugin.getInstance().getSLF4JLogger().info("Loaded {} shops from database.", shopsByLocation.size()); + return true; + } + + public static boolean loadShopFor(OfflinePlayer player) { + OMCPlugin.getInstance().getSLF4JLogger().info("Loading shop for player {} from database...", player.getName()); + Shop shop = ShopDatabaseManager.loadShopFor(player.getUniqueId()); + if (shop == null) { + OMCPlugin.getInstance().getSLF4JLogger().info("No shop found for player {}.", player.getName()); + return false; + } + Location loc = new Location(Bukkit.getWorld("world"), shop.getX(), shop.getY(), shop.getZ()); + shopsByLocation.put(loc, shop); + setPlayerShop(player.getUniqueId(), shop); + OMCPlugin.getInstance().getSLF4JLogger().info("Loaded shop for player {}.", player.getName()); + return true; + } + + public static boolean saveShops() { + OMCPlugin.getInstance().getSLF4JLogger().info("Saving all shops to database..."); + for (Shop shop : playerShops.values()) { + if (!ShopDatabaseManager.saveShop(shop)) { + OMCPlugin.getInstance().getSLF4JLogger().error("Failed to save all shops to database."); + return false; + } + } + OMCPlugin.getInstance().getSLF4JLogger().info("All shops saved to database successfully. {} shops saved.", playerShops.size()); + return true; + } + + public static boolean saveShopFor(OfflinePlayer player) { + OMCPlugin.getInstance().getSLF4JLogger().info("Saving shop for player {} to database...", player.getName()); + Shop shop = getPlayerShop(player.getUniqueId()); + if (shop == null) { + OMCPlugin.getInstance().getSLF4JLogger().info("No shop found for player {} to save.", player.getName()); + return false; + } + if (!ShopDatabaseManager.saveShop(shop)) { + OMCPlugin.getInstance().getSLF4JLogger().error("Failed to save shop for player {} to database.", player.getName()); + return false; + } + OMCPlugin.getInstance().getSLF4JLogger().info("Shop for player {} saved to database successfully.", player.getName()); + return true; + } /** * Retrieves a shop located at a given location. @@ -41,7 +103,7 @@ public static Shop getShopAt(Location location) { * @return The shop found at that location, or null if none exists. */ public static Shop getShopAt(int x, int y, int z) { - return shopsByLocation.get(new Location(Bukkit.getWorld("world"), x, y, z, 0, 0)); + return shopsByLocation.get(new Location(Bukkit.getWorld("world"), x, y, z)); } /** @@ -100,4 +162,26 @@ public static boolean removeShop(Shop shop) { shopsByLocation.entrySet().removeIf(entry -> entry.getValue().getOwnerUUID().equals(shop.getOwnerUUID()))); return true; } + + public static Set getAllShops() { + return Set.copyOf(shopsByLocation.values()); + } + + public static Shop getPlayerShop(UUID playerUUID) { + return playerShops.get(playerUUID); + } + + public static void setPlayerShop(UUID playerUUID, Shop shop) { + playerShops.put(playerUUID, shop); + } + + /** + * Check if a player has a shop + * + * @param playerUUID the UUID of the player to check + * @return true if a shop is found + */ + public static boolean hasShop(UUID playerUUID) { + return getPlayerShop(playerUUID) != null; + } }