diff --git a/docs/CNPC_1.11_MARKET_UPDATE_PLAN.md b/docs/CNPC_1.11_MARKET_UPDATE_PLAN.md index fb1c33158..4d62a7772 100644 --- a/docs/CNPC_1.11_MARKET_UPDATE_PLAN.md +++ b/docs/CNPC_1.11_MARKET_UPDATE_PLAN.md @@ -1,1871 +1,324 @@ -# CustomNPC+ 1.11 Market Update - Implementation Plan +# CustomNPC+ 1.11 Market Update - Implementation Status ## Overview -This document outlines the implementation plan for the CustomNPC+ 1.11 update, focusing on three major features: +This document tracks the implementation status of the CustomNPC+ 1.11 Market Update, which includes: -1. **Auction House** - A new NPC role allowing players to access a global auction system -2. **Currency System** - Built-in currency integration with VaultAPI for Bukkit hybrid servers -3. **Trader Enhancements** - Stock/Inventory system with per-player/per-server options and reset timers +1. **Auction House** - Global auction system with bidding, buyout, and claims +2. **Currency System** - Built-in currency with VaultAPI integration for Bukkit hybrid servers +3. **Trader Enhancements** - Stock/inventory system with reset timers --- -## Table of Contents +## Implementation Status Summary -1. [Architecture Overview](#architecture-overview) -2. [Feature 1: Currency System](#feature-1-currency-system) -3. [Feature 2: Trader Enhancements](#feature-2-trader-enhancements) -4. [Feature 3: Auction House](#feature-3-auction-house) -5. [Implementation Order](#implementation-order) -6. [File Summary](#file-summary) -7. [Testing Strategy](#testing-strategy) +| Phase | Feature | Status | +|-------|---------|--------| +| Phase 1 | Currency System Foundation | **NOT STARTED** | +| Phase 2 | Trader Enhancements | **COMPLETED** | +| Phase 3 | Item Attributes & Restrictions | **COMPLETED** | +| Phase 4 | Auction House Core | **COMPLETED** | +| Phase 5 | Network Packets & Permissions | **COMPLETED** | +| Phase 6 | Auction GUI & Notifications | **COMPLETED** | +| Phase 7 | Admin Management | **NOT STARTED** | --- -## Architecture Overview +## Completed Features -### Current Codebase Patterns +### Phase 2: Trader Enhancements (COMPLETED) +- `EnumStockReset.java` - Stock reset timing options +- `TraderStock.java` - Stock tracking with per-player and per-server modes +- Modified `RoleTrader.java` with stock and currency support +- Modified `ContainerNPCTrader.java` for stock/currency transactions +- Stock persistence via NBT -The implementation will follow existing patterns found in the codebase: +### Phase 3: Item Attributes & Restrictions (COMPLETED) +- `ItemTradeAttribute.java` - Untradeable, ProfileSlot Bound, Soulbound checks +- `AuctionBlacklist.java` - Item/mod/NBT blacklist system +- Integration with AuctionListing validation -| Pattern | Used By | Will Be Applied To | -|---------|---------|-------------------| -| Singleton Controller | `BankController`, `QuestController` | `AuctionController`, `CurrencyController` | -| Role Interface | `RoleTrader`, `RoleBank` | `RoleAuctioneer` | -| Player Data Extension | `PlayerBankData`, `PlayerQuestData` | `PlayerAuctionData`, `PlayerCurrencyData` | -| Cooldown System | `Quest.repeat`, `JobItemGiver` | Trader Stock Reset | -| Optional Addon | `PixelmonHelper`, `DBCAddon` | `VaultHelper` | -| NBT Serialization | All data classes | All new data classes | -| Cache System | `Market.java`, `CacheHashMap` | Auction listings cache | +### Phase 4: Auction House Core (COMPLETED) +- `EnumAuctionDuration.java` - Configurable durations with lang keys +- `EnumAuctionStatus.java` - Auction state management +- `EnumAuctionSort.java` - Sort options with lang keys +- `AuctionListing.java` - Complete listing data structure with bidding logic +- `AuctionFilter.java` - Search/filter criteria (categories removed) +- `AuctionController.java` - Consolidated controller with: + - Listing creation/management + - Bidding and buyout logic + - Claim system for items and currency refunds + - Inline logging (via LogWriter) + - Inline player notifications (via chat messages) + - Pending notification queue for offline players + - Snipe protection + - Sales tax and listing fees +- `AuctionClaim.java` - Claim data for items/money +- `RoleAuctioneer.java` - Auctioneer NPC role +- `ContainerAuction.java` - Auction container +- `ConfigMarket.java` - All market configuration options -### Package Structure for New Features +### Phase 5: Network Packets & Permissions (COMPLETED) +- `AuctionActionPacket.java` - Client-to-server auction actions +- `AuctionDataPacket.java` - Server-to-client data sync +- Packet registration in `PacketHandler.java` +- Permission nodes added to `CustomNpcsPermissions.java` +- API methods added to `ICustomNpc.java` -``` -noppes/npcs/ -├── controllers/ -│ ├── AuctionController.java # Manages global auction house -│ ├── CurrencyController.java # Manages currency settings -│ └── data/ -│ ├── AuctionListing.java # Single auction listing -│ ├── AuctionData.java # World auction data -│ ├── PlayerAuctionData.java # Per-player auction history -│ ├── PlayerCurrencyData.java # Per-player currency balance -│ └── TraderStock.java # Trader stock configuration -├── roles/ -│ └── RoleAuctioneer.java # Auctioneer NPC role -├── containers/ -│ ├── ContainerAuction*.java # Auction GUI containers -│ └── ContainerNPCTraderStock.java # Stock management container -├── client/gui/ -│ ├── player/ -│ │ └── GuiAuction*.java # Player-facing auction GUIs -│ └── roles/ -│ └── GuiNpcAuctioneerSetup.java # Auctioneer configuration GUI +### Phase 6: Auction GUI & Notifications (COMPLETED) +- `GuiAuction.java` - Main auction browser with tabs +- `SubGuiAuctionCreate.java` - Create listing sub-GUI +- `SubGuiAuctionBid.java` - Place bid sub-GUI +- `SubGuiAuctionDetails.java` - View listing details sub-GUI +- All GUI strings use lang keys via `StatCollector.translateToLocal()` +- Localization keys added to `en_US.lang` -kamkeel/npcs/ -├── controllers/ -│ └── CurrencyController.java # Currency management -├── network/packets/ -│ ├── data/ -│ │ ├── AuctionSyncPacket.java # Sync auction data -│ │ └── CurrencySyncPacket.java # Sync currency data -│ └── player/ -│ ├── AuctionActionPacket.java # Auction actions (bid, buy, sell) -│ └── CurrencyActionPacket.java # Currency transactions -└── compat/ - └── VaultHelper.java # VaultAPI integration +--- + +## Removed/Changed Features + +### Removed: Category System +Originally planned to have item categories (Weapons, Armor, Tools, etc.) for filtering. This was **removed** to simplify the initial implementation: +- Deleted `EnumAuctionCategory.java` +- Removed category field from `AuctionListing.java` +- Removed category filtering from `AuctionFilter.java` +- Removed category buttons from `GuiAuction.java` + +**Rationale:** Categories can be added in a future update. Current implementation uses search-based filtering. + +### Consolidated: Controller Architecture +Originally planned separate controllers: +- ~~`AuctionLogger.java`~~ - **CONSOLIDATED** into `AuctionController.logEvent()` +- ~~`AuctionNotificationController.java`~~ - **CONSOLIDATED** into `AuctionController.notifyPlayer()` + +**Rationale:** Reduces complexity, all auction logic in one place. + +### Changed: Localization Approach +- All client GUI strings now use `StatCollector.translateToLocal()` with lang keys +- `EnumAuctionSort` uses lang keys for display names +- `EnumAuctionDuration` uses lang keys for display names + +--- + +## Not Yet Implemented + +### Phase 1: Currency System (NOT STARTED) +Requires implementation: +- [ ] `VaultHelper.java` - VaultAPI integration via reflection +- [ ] `CurrencyController.java` - Currency management +- [ ] `PlayerCurrencyData.java` - Per-player currency (shared across profile slots) +- [ ] Vault dependency in build files +- [ ] Currency configuration GUI + +**Note:** Currently auctions use `long` for prices but the actual currency deduction/deposit is not connected to any economy system. + +### Phase 7: Admin Management (NOT STARTED) +Requires implementation: +- [ ] `GuiAuctionAdmin.java` - Admin auction management GUI +- [ ] `GuiAuctionBlacklist.java` - Blacklist management GUI +- [ ] Admin methods in `AuctionController.java` (adminCancelListing, adminEditListing, etc.) +- [ ] Audit logging for admin actions +- [ ] `/cnpc auction admin` command + +### Additional Missing Features +- [ ] Auctioneer NPC setup GUI (`GuiNpcAuctioneerSetup.java`) +- [ ] Trader stock reset timer banner display +- [ ] Comprehensive testing +- [ ] Player balance display (requires Currency System) + +--- + +## Configuration Reference + +All settings are in `ConfigMarket.java`: + +```java +// Currency +public static String CurrencyName = "Gold"; + +// Auction Durations (in hours) +public static int AuctionDurationShort = 12; +public static int AuctionDurationMedium = 24; +public static int AuctionDurationLong = 48; +public static int AuctionDurationVeryLong = 72; + +// Auction Fees (per duration) +public static long AuctionFeeShort = 10; +public static long AuctionFeeMedium = 25; +public static long AuctionFeeLong = 50; +public static long AuctionFeeVeryLong = 100; + +// Listing Configuration +public static int DefaultMaxListings = 5; +public static double ListingFeePercent = 0.0; +public static double SalesTaxPercent = 0.05; +public static double MinBidIncrementPercent = 0.05; +public static int ClaimExpirationDays = 30; +public static boolean RequireAuctioneerNPC = true; + +// Snipe Protection +public static int SnipeProtectionMinutes = 5; +public static int SnipeProtectionThreshold = 5; ``` --- -## Feature 1: Currency System - -### 1.1 Overview - -The currency system provides a unified economy layer that can: -- Use VaultAPI when available on Bukkit hybrid servers (Cauldron, Thermos, Mohist) -- Fall back to an internal item-based currency when VaultAPI is unavailable -- Be configured per-world or globally - -### 1.2 VaultAPI Integration - -#### 1.2.1 Dependency Setup - -**File: `dependencies.gradle`** -```gradle -// VaultAPI - compile-only for optional integration -compileOnly("net.milkbowl.vault:VaultAPI:1.4") { - transitive = false -} -``` - -**File: `repositories.gradle`** -```gradle -maven { - name = "vault-repo" - url = "https://nexus.hc.to/content/repositories/pub_releases/" -} -``` - -> **Note:** VaultAPI 1.4.1 works with 1.7.10 Bukkit hybrid servers. The dependency is compile-only so the mod works without Vault present. - -#### 1.2.2 VaultHelper Class - -**File: `src/main/java/kamkeel/npcs/compat/VaultHelper.java`** - -```java -package kamkeel.npcs.compat; - -import cpw.mods.fml.common.Loader; -import net.minecraft.entity.player.EntityPlayer; -import noppes.npcs.LogWriter; -import org.bukkit.Bukkit; -import org.bukkit.plugin.RegisteredServiceProvider; - -public class VaultHelper { - public static boolean Enabled = false; - public static boolean Available = false; - - // Cached via reflection - private static Object economy = null; - private static Class economyClass = null; - private static java.lang.reflect.Method getBalance; - private static java.lang.reflect.Method withdrawPlayer; - private static java.lang.reflect.Method depositPlayer; - private static java.lang.reflect.Method hasMethod; - private static java.lang.reflect.Method format; - - public static void load() { - // Check if we're on a Bukkit hybrid server - try { - Class.forName("org.bukkit.Bukkit"); - Available = true; - } catch (ClassNotFoundException e) { - Available = false; - return; - } - - // Try to hook into Vault - try { - Class vaultClass = Class.forName("net.milkbowl.vault.economy.Economy"); - economyClass = vaultClass; - - RegisteredServiceProvider rsp = Bukkit.getServicesManager() - .getRegistration(vaultClass); - - if (rsp != null) { - economy = rsp.getProvider(); - - // Cache reflection methods - getBalance = economyClass.getMethod("getBalance", String.class); - withdrawPlayer = economyClass.getMethod("withdrawPlayer", - String.class, double.class); - depositPlayer = economyClass.getMethod("depositPlayer", - String.class, double.class); - hasMethod = economyClass.getMethod("has", String.class, double.class); - format = economyClass.getMethod("format", double.class); - - Enabled = true; - LogWriter.info("VaultAPI Economy hooked successfully!"); - } - } catch (Exception e) { - LogWriter.info("VaultAPI not available: " + e.getMessage()); - Enabled = false; - } - } - - // Economy Methods - public static double getBalance(EntityPlayer player) { - if (!Enabled) return 0.0; - try { - return (Double) getBalance.invoke(economy, player.getCommandSenderName()); - } catch (Exception e) { - LogWriter.except(e); - return 0.0; - } - } - - public static boolean withdraw(EntityPlayer player, double amount) { - if (!Enabled) return false; - try { - Object response = withdrawPlayer.invoke(economy, - player.getCommandSenderName(), amount); - return (Boolean) response.getClass() - .getMethod("transactionSuccess").invoke(response); - } catch (Exception e) { - LogWriter.except(e); - return false; - } - } - - public static boolean deposit(EntityPlayer player, double amount) { - if (!Enabled) return false; - try { - Object response = depositPlayer.invoke(economy, - player.getCommandSenderName(), amount); - return (Boolean) response.getClass() - .getMethod("transactionSuccess").invoke(response); - } catch (Exception e) { - LogWriter.except(e); - return false; - } - } - - public static boolean has(EntityPlayer player, double amount) { - if (!Enabled) return false; - try { - return (Boolean) hasMethod.invoke(economy, - player.getCommandSenderName(), amount); - } catch (Exception e) { - LogWriter.except(e); - return false; - } - } - - public static String formatCurrency(double amount) { - if (!Enabled) return String.format("%.2f", amount); - try { - return (String) format.invoke(economy, amount); - } catch (Exception e) { - return String.format("%.2f", amount); - } - } -} -``` - -#### 1.2.3 Initialization Hook - -**File: `src/main/java/noppes/npcs/CustomNpcs.java`** - -Add to `load()` method after AddonManager: -```java -// Initialize VaultAPI integration (for Bukkit hybrid servers) -VaultHelper.load(); -``` - -### 1.3 Currency Controller - -**File: `src/main/java/kamkeel/npcs/controllers/CurrencyController.java`** - -```java -package kamkeel.npcs.controllers; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import kamkeel.npcs.compat.VaultHelper; -import noppes.npcs.NoppesUtilPlayer; - -public class CurrencyController { - private static CurrencyController instance; - - // Configuration - public boolean useVaultIfAvailable = true; - public ItemStack fallbackCurrency = null; // Item to use when Vault unavailable - public double itemToVaultRatio = 1.0; // 1 item = X vault currency - - public static CurrencyController getInstance() { - if (instance == null) { - instance = new CurrencyController(); - } - return instance; - } - - /** - * Check if Vault economy is being used - */ - public boolean isUsingVault() { - return useVaultIfAvailable && VaultHelper.Enabled; - } - - /** - * Get player's balance (Vault or item count) - */ - public double getBalance(EntityPlayer player) { - if (isUsingVault()) { - return VaultHelper.getBalance(player); - } - // Fall back to counting items - if (fallbackCurrency != null) { - return NoppesUtilPlayer.countItems(player, fallbackCurrency, false, false); - } - return 0.0; - } - - /** - * Check if player can afford amount - */ - public boolean canAfford(EntityPlayer player, double amount) { - if (isUsingVault()) { - return VaultHelper.has(player, amount); - } - return getBalance(player) >= amount; - } - - /** - * Withdraw currency from player - */ - public boolean withdraw(EntityPlayer player, double amount) { - if (isUsingVault()) { - return VaultHelper.withdraw(player, amount); - } - // Remove items - if (fallbackCurrency != null) { - ItemStack toRemove = fallbackCurrency.copy(); - toRemove.stackSize = (int) Math.ceil(amount / itemToVaultRatio); - return NoppesUtilPlayer.consumeItem(player, toRemove, false, false); - } - return false; - } - - /** - * Deposit currency to player - */ - public boolean deposit(EntityPlayer player, double amount) { - if (isUsingVault()) { - return VaultHelper.deposit(player, amount); - } - // Give items - if (fallbackCurrency != null) { - ItemStack toGive = fallbackCurrency.copy(); - toGive.stackSize = (int) Math.floor(amount / itemToVaultRatio); - return player.inventory.addItemStackToInventory(toGive); - } - return false; - } - - /** - * Format currency for display - */ - public String format(double amount) { - if (isUsingVault()) { - return VaultHelper.formatCurrency(amount); - } - return String.format("%.0f", amount); - } - - // NBT Persistence - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setBoolean("UseVault", useVaultIfAvailable); - compound.setDouble("ItemRatio", itemToVaultRatio); - if (fallbackCurrency != null) { - compound.setTag("FallbackItem", fallbackCurrency.writeToNBT(new NBTTagCompound())); - } - return compound; - } - - public void readFromNBT(NBTTagCompound compound) { - useVaultIfAvailable = compound.getBoolean("UseVault"); - itemToVaultRatio = compound.getDouble("ItemRatio"); - if (compound.hasKey("FallbackItem")) { - fallbackCurrency = ItemStack.loadItemStackFromNBT( - compound.getCompoundTag("FallbackItem")); - } - } -} -``` - -### 1.4 Player Currency Data - -**File: `src/main/java/noppes/npcs/controllers/data/PlayerCurrencyData.java`** - -```java -package noppes.npcs.controllers.data; - -import net.minecraft.nbt.NBTTagCompound; -import java.util.HashMap; - -public class PlayerCurrencyData { - private final PlayerData parent; - - // Transaction history (for auditing/display) - public HashMap transactionHistory = new HashMap<>(); - public double totalEarned = 0.0; - public double totalSpent = 0.0; - - public PlayerCurrencyData(PlayerData parent) { - this.parent = parent; - } - - public void recordTransaction(double amount, boolean isEarning) { - long timestamp = System.currentTimeMillis(); - transactionHistory.put(timestamp, isEarning ? amount : -amount); - if (isEarning) { - totalEarned += amount; - } else { - totalSpent += amount; - } - // Limit history size - if (transactionHistory.size() > 100) { - // Remove oldest entries - Long oldest = transactionHistory.keySet().stream() - .min(Long::compare).orElse(null); - if (oldest != null) { - transactionHistory.remove(oldest); - } - } - } - - public void loadNBTData(NBTTagCompound compound) { - if (compound.hasKey("CurrencyData")) { - NBTTagCompound data = compound.getCompoundTag("CurrencyData"); - totalEarned = data.getDouble("TotalEarned"); - totalSpent = data.getDouble("TotalSpent"); - } - } - - public void saveNBTData(NBTTagCompound compound) { - NBTTagCompound data = new NBTTagCompound(); - data.setDouble("TotalEarned", totalEarned); - data.setDouble("TotalSpent", totalSpent); - compound.setTag("CurrencyData", data); - } -} -``` - -### 1.5 Configuration UI - -Add currency configuration to the global settings GUI: - -**File: `src/main/java/noppes/npcs/client/gui/global/GuiNPCManageCurrency.java`** - -This GUI will allow server operators to: -- Enable/disable Vault integration -- Set fallback currency item -- Configure item-to-Vault ratio -- View server economy statistics - ---- - -## Feature 2: Trader Enhancements - -### 2.1 Overview - -Enhance the existing `RoleTrader` with: -- **Stock System**: Limited inventory that depletes when players buy -- **Per-Player vs Per-Server Stock**: Configure whether stock is shared or individual -- **Stock Reset Timer**: Automatic restocking based on configurable cooldown (like quest cooldowns) -- **Currency Integration**: Use Vault currency alongside or instead of item-based trading - -### 2.2 Trader Stock Configuration - -#### 2.2.1 Stock Data Class - -**File: `src/main/java/noppes/npcs/controllers/data/TraderStock.java`** - -```java -package noppes.npcs.controllers.data; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import java.util.HashMap; - -public class TraderStock { - // Stock configuration - public boolean enableStock = false; - public boolean perPlayer = false; // false = per-server, true = per-player - - // Reset configuration (mirrors Quest cooldown system) - public EnumStockReset resetType = EnumStockReset.NONE; - public long customResetTime = 0; // For MCCUSTOM/RLCUSTOM types - - // Stock quantities per slot (max stock) - public int[] maxStock = new int[18]; - - // Current stock (per-server mode) - public int[] currentStock = new int[18]; - public long lastResetTime = 0; - - // Per-player stock tracking - public HashMap playerStock = new HashMap<>(); - - public TraderStock() { - for (int i = 0; i < 18; i++) { - maxStock[i] = -1; // -1 = unlimited - currentStock[i] = -1; - } - } - - /** - * Get available stock for a slot - */ - public int getAvailableStock(int slot, String playerName) { - if (!enableStock || maxStock[slot] < 0) { - return Integer.MAX_VALUE; // Unlimited - } - - if (perPlayer) { - PlayerTraderStock pStock = playerStock.get(playerName); - if (pStock == null) { - return maxStock[slot]; // Not purchased yet - } - return pStock.getStock(slot, maxStock[slot]); - } - - return currentStock[slot]; - } - - /** - * Consume stock when purchase is made - */ - public boolean consumeStock(int slot, String playerName, int amount) { - if (!enableStock || maxStock[slot] < 0) { - return true; // Unlimited - } - - if (perPlayer) { - PlayerTraderStock pStock = playerStock.computeIfAbsent( - playerName, k -> new PlayerTraderStock()); - return pStock.consumeStock(slot, maxStock[slot], amount); - } - - if (currentStock[slot] >= amount) { - currentStock[slot] -= amount; - return true; - } - return false; - } - - /** - * Check if stock should reset - */ - public boolean shouldReset(long currentTime) { - if (resetType == EnumStockReset.NONE) { - return false; - } - - long elapsed = currentTime - lastResetTime; - long resetInterval = getResetInterval(); - - return elapsed >= resetInterval; - } - - /** - * Reset all stock to max values - */ - public void resetStock(long currentTime) { - lastResetTime = currentTime; - - for (int i = 0; i < 18; i++) { - currentStock[i] = maxStock[i]; - } - - // Clear per-player stock - playerStock.clear(); - } - - /** - * Get reset interval in milliseconds - */ - public long getResetInterval() { - switch (resetType) { - case MCDAILY: - return 24000 * 50; // 24000 ticks * 50ms - case MCWEEKLY: - return 168000 * 50; - case MCCUSTOM: - return customResetTime * 50; - case RLDAILY: - return 86400000L; // 24 hours in ms - case RLWEEKLY: - return 604800000L; // 7 days in ms - case RLCUSTOM: - return customResetTime; - default: - return Long.MAX_VALUE; - } - } - - /** - * Get time until next reset (for display) - */ - public long getTimeUntilReset(long currentTime) { - if (resetType == EnumStockReset.NONE) { - return -1; - } - long elapsed = currentTime - lastResetTime; - long interval = getResetInterval(); - return Math.max(0, interval - elapsed); - } - - // NBT Serialization - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setBoolean("EnableStock", enableStock); - compound.setBoolean("PerPlayer", perPlayer); - compound.setInteger("ResetType", resetType.ordinal()); - compound.setLong("CustomResetTime", customResetTime); - compound.setIntArray("MaxStock", maxStock); - compound.setIntArray("CurrentStock", currentStock); - compound.setLong("LastResetTime", lastResetTime); - - // Save per-player stock - NBTTagList playerList = new NBTTagList(); - for (Map.Entry entry : playerStock.entrySet()) { - NBTTagCompound playerTag = new NBTTagCompound(); - playerTag.setString("Player", entry.getKey()); - entry.getValue().writeToNBT(playerTag); - playerList.appendTag(playerTag); - } - compound.setTag("PlayerStock", playerList); - - return compound; - } - - public void readFromNBT(NBTTagCompound compound) { - enableStock = compound.getBoolean("EnableStock"); - perPlayer = compound.getBoolean("PerPlayer"); - resetType = EnumStockReset.values()[compound.getInteger("ResetType")]; - customResetTime = compound.getLong("CustomResetTime"); - maxStock = compound.getIntArray("MaxStock"); - currentStock = compound.getIntArray("CurrentStock"); - lastResetTime = compound.getLong("LastResetTime"); - - // Load per-player stock - NBTTagList playerList = compound.getTagList("PlayerStock", 10); - for (int i = 0; i < playerList.tagCount(); i++) { - NBTTagCompound playerTag = playerList.getCompoundTagAt(i); - String playerName = playerTag.getString("Player"); - PlayerTraderStock pStock = new PlayerTraderStock(); - pStock.readFromNBT(playerTag); - playerStock.put(playerName, pStock); - } - } -} - -// Inner class for per-player stock tracking -class PlayerTraderStock { - public int[] purchasedAmounts = new int[18]; - public long lastPurchaseTime = 0; - - public int getStock(int slot, int maxStock) { - return Math.max(0, maxStock - purchasedAmounts[slot]); - } - - public boolean consumeStock(int slot, int maxStock, int amount) { - if (getStock(slot, maxStock) >= amount) { - purchasedAmounts[slot] += amount; - lastPurchaseTime = System.currentTimeMillis(); - return true; - } - return false; - } - - public void writeToNBT(NBTTagCompound compound) { - compound.setIntArray("Purchased", purchasedAmounts); - compound.setLong("LastPurchase", lastPurchaseTime); - } - - public void readFromNBT(NBTTagCompound compound) { - purchasedAmounts = compound.getIntArray("Purchased"); - lastPurchaseTime = compound.getLong("LastPurchase"); - } -} -``` - -#### 2.2.2 Stock Reset Enum - -**File: `src/main/java/noppes/npcs/constants/EnumStockReset.java`** - -```java -package noppes.npcs.constants; - -public enum EnumStockReset { - NONE, // Never resets - MCDAILY, // Every 24000 MC ticks (1 MC day) - MCWEEKLY, // Every 168000 MC ticks (7 MC days) - MCCUSTOM, // Custom MC tick interval - RLDAILY, // Every 24 real hours - RLWEEKLY, // Every 7 real days - RLCUSTOM // Custom real-time interval -} -``` - -### 2.3 RoleTrader Modifications - -**File: `src/main/java/noppes/npcs/roles/RoleTrader.java`** - -Add the following to `RoleTrader`: - -```java -// Add new fields -public TraderStock stock = new TraderStock(); -public boolean useCurrency = false; // Use Vault/Currency system -public double[] slotPrices = new double[18]; // Currency prices per slot - -// Modify interact() to check stock reset -@Override -public void interact(EntityPlayer player) { - // Check for stock reset before opening GUI - if (stock.enableStock) { - long currentTime = stock.resetType.name().startsWith("RL") - ? System.currentTimeMillis() - : player.worldObj.getTotalWorldTime(); - - if (stock.shouldReset(currentTime)) { - stock.resetStock(currentTime); - // Save to market if using shared market - if (!marketName.isEmpty()) { - Market.save(this, marketName); - } - } - } - - npc.say(player, npc.advanced.getInteractLine()); - NoppesUtilServer.sendOpenGui(player, EnumGuiType.PlayerTrader, npc); -} - -// Modify writeToNBT -@Override -public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { - // ... existing code ... - - // Add stock data - nbttagcompound.setTag("Stock", stock.writeToNBT(new NBTTagCompound())); - nbttagcompound.setBoolean("UseCurrency", useCurrency); - - // Save currency prices - NBTTagList priceList = new NBTTagList(); - for (double price : slotPrices) { - NBTTagCompound priceTag = new NBTTagCompound(); - priceTag.setDouble("Price", price); - priceList.appendTag(priceTag); - } - nbttagcompound.setTag("SlotPrices", priceList); - - return nbttagcompound; -} - -// Modify readFromNBT -@Override -public void readFromNBT(NBTTagCompound nbttagcompound) { - // ... existing code ... - - // Load stock data - if (nbttagcompound.hasKey("Stock")) { - stock.readFromNBT(nbttagcompound.getCompoundTag("Stock")); - } - useCurrency = nbttagcompound.getBoolean("UseCurrency"); - - // Load currency prices - if (nbttagcompound.hasKey("SlotPrices")) { - NBTTagList priceList = nbttagcompound.getTagList("SlotPrices", 10); - for (int i = 0; i < priceList.tagCount() && i < 18; i++) { - slotPrices[i] = priceList.getCompoundTagAt(i).getDouble("Price"); - } - } -} -``` - -### 2.4 ContainerNPCTrader Modifications - -**File: `src/main/java/noppes/npcs/containers/ContainerNPCTrader.java`** - -Modify `slotClick()` to handle stock and currency: - -```java -public ItemStack slotClick(int slotIndex, EntityPlayer player) { - RoleTrader role = (RoleTrader) npc.roleInterface; - String playerName = player.getCommandSenderName(); - - // ... existing validation ... - - // Check stock availability - if (role.stock.enableStock) { - int available = role.stock.getAvailableStock(slotIndex, playerName); - if (available <= 0) { - // Out of stock - send message to player - return null; - } - } - - // Handle currency-based purchase - if (role.useCurrency && role.slotPrices[slotIndex] > 0) { - double price = role.slotPrices[slotIndex]; - CurrencyController currency = CurrencyController.getInstance(); - - if (!currency.canAfford(player, price)) { - // Can't afford - send message - return null; - } - - // Withdraw currency - if (!currency.withdraw(player, price)) { - return null; - } - } else { - // ... existing item-based currency logic ... - } - - // Consume stock - if (role.stock.enableStock) { - role.stock.consumeStock(slotIndex, playerName, 1); - } - - // ... existing item delivery logic ... - - // Save if using market - if (!role.marketName.isEmpty()) { - Market.save(role, role.marketName); - } - - return soldItem; -} -``` - -### 2.5 Trader Setup GUI Additions - -**File: `src/main/java/noppes/npcs/client/gui/roles/GuiNpcTraderSetup.java`** - -Add new configuration options: - -```java -// Add buttons/fields for: -// - "Enable Stock" toggle -// - "Per Player" / "Per Server" radio buttons -// - "Reset Type" dropdown (None, MC Daily, MC Weekly, etc.) -// - "Custom Reset Time" field -// - "Use Currency" toggle -// - Per-slot stock quantity inputs -// - Per-slot currency price inputs - -private void initStockGui() { - addButton(new GuiNpcButton(20, x, y, 80, 20, - "Enable Stock: " + (role.stock.enableStock ? "Yes" : "No"))); - - addButton(new GuiNpcButton(21, x, y + 22, 80, 20, - role.stock.perPlayer ? "Per Player" : "Per Server")); - - String[] resetTypes = {"None", "MC Daily", "MC Weekly", "MC Custom", - "RL Daily", "RL Weekly", "RL Custom"}; - addButton(new GuiNpcButton(22, x, y + 44, 80, 20, resetTypes, - role.stock.resetType.ordinal())); - - addButton(new GuiNpcButton(23, x, y + 66, 80, 20, - "Use Currency: " + (role.useCurrency ? "Yes" : "No"))); -} -``` - ---- - -## Feature 3: Auction House - -### 3.1 Overview - -The Auction House is a global trading system where players can: -- **List items for sale** at fixed prices or as auctions with bidding -- **Browse listings** by category, search, and filter -- **Bid on auctions** with automatic outbid notifications -- **Buy instantly** for buy-it-now prices -- **Manage their listings** (cancel, modify) -- **Collect proceeds and expired items** via mailbox or direct claim - -### 3.2 Auction Data Structures - -#### 3.2.1 AuctionListing - -**File: `src/main/java/noppes/npcs/controllers/data/AuctionListing.java`** - -```java -package noppes.npcs.controllers.data; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import java.util.UUID; - -public class AuctionListing { - public int id; - public UUID sellerUUID; - public String sellerName; - public ItemStack item; - - // Pricing - public double startingPrice; - public double buyoutPrice; // 0 = no buyout - public double currentBid; - public UUID highBidderUUID; - public String highBidderName; - - // Timing - public long listingTime; - public long expirationTime; - public EnumAuctionDuration duration; - - // Status - public EnumAuctionStatus status = EnumAuctionStatus.ACTIVE; - - // Category - public EnumAuctionCategory category = EnumAuctionCategory.MISC; - - public AuctionListing() {} - - public AuctionListing(UUID seller, String sellerName, ItemStack item, - double startPrice, double buyout, EnumAuctionDuration duration) { - this.sellerUUID = seller; - this.sellerName = sellerName; - this.item = item.copy(); - this.startingPrice = startPrice; - this.buyoutPrice = buyout; - this.currentBid = startPrice; - this.duration = duration; - this.listingTime = System.currentTimeMillis(); - this.expirationTime = listingTime + duration.getMillis(); - this.category = categorizeItem(item); - } - - /** - * Check if auction has expired - */ - public boolean isExpired() { - return System.currentTimeMillis() >= expirationTime; - } - - /** - * Get time remaining in milliseconds - */ - public long getTimeRemaining() { - return Math.max(0, expirationTime - System.currentTimeMillis()); - } - - /** - * Place a bid - */ - public boolean placeBid(UUID bidder, String bidderName, double amount) { - if (status != EnumAuctionStatus.ACTIVE) return false; - if (amount <= currentBid) return false; - if (bidder.equals(sellerUUID)) return false; // Can't bid on own item - - // Minimum bid increment (5% or 1, whichever is greater) - double minIncrement = Math.max(1, currentBid * 0.05); - if (amount < currentBid + minIncrement) return false; - - highBidderUUID = bidder; - highBidderName = bidderName; - currentBid = amount; - - return true; - } - - /** - * Execute buyout - */ - public boolean buyout(UUID buyer, String buyerName) { - if (status != EnumAuctionStatus.ACTIVE) return false; - if (buyoutPrice <= 0) return false; // No buyout available - if (buyer.equals(sellerUUID)) return false; - - highBidderUUID = buyer; - highBidderName = buyerName; - currentBid = buyoutPrice; - status = EnumAuctionStatus.SOLD; - - return true; - } - - /** - * Cancel listing (seller only, before any bids) - */ - public boolean cancel(UUID requester) { - if (!requester.equals(sellerUUID)) return false; - if (highBidderUUID != null) return false; // Has bids, can't cancel - - status = EnumAuctionStatus.CANCELLED; - return true; - } - - /** - * Auto-categorize item based on type - */ - private EnumAuctionCategory categorizeItem(ItemStack item) { - // Implement item categorization logic - // Check for weapons, armor, tools, food, blocks, etc. - return EnumAuctionCategory.MISC; - } - - // NBT Serialization - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setInteger("Id", id); - compound.setString("SellerUUID", sellerUUID.toString()); - compound.setString("SellerName", sellerName); - compound.setTag("Item", item.writeToNBT(new NBTTagCompound())); - compound.setDouble("StartPrice", startingPrice); - compound.setDouble("BuyoutPrice", buyoutPrice); - compound.setDouble("CurrentBid", currentBid); - if (highBidderUUID != null) { - compound.setString("BidderUUID", highBidderUUID.toString()); - compound.setString("BidderName", highBidderName); - } - compound.setLong("ListingTime", listingTime); - compound.setLong("ExpirationTime", expirationTime); - compound.setInteger("Duration", duration.ordinal()); - compound.setInteger("Status", status.ordinal()); - compound.setInteger("Category", category.ordinal()); - return compound; - } - - public void readFromNBT(NBTTagCompound compound) { - id = compound.getInteger("Id"); - sellerUUID = UUID.fromString(compound.getString("SellerUUID")); - sellerName = compound.getString("SellerName"); - item = ItemStack.loadItemStackFromNBT(compound.getCompoundTag("Item")); - startingPrice = compound.getDouble("StartPrice"); - buyoutPrice = compound.getDouble("BuyoutPrice"); - currentBid = compound.getDouble("CurrentBid"); - if (compound.hasKey("BidderUUID")) { - highBidderUUID = UUID.fromString(compound.getString("BidderUUID")); - highBidderName = compound.getString("BidderName"); - } - listingTime = compound.getLong("ListingTime"); - expirationTime = compound.getLong("ExpirationTime"); - duration = EnumAuctionDuration.values()[compound.getInteger("Duration")]; - status = EnumAuctionStatus.values()[compound.getInteger("Status")]; - category = EnumAuctionCategory.values()[compound.getInteger("Category")]; - } -} -``` - -#### 3.2.2 Supporting Enums - -**File: `src/main/java/noppes/npcs/constants/EnumAuctionDuration.java`** - -```java -package noppes.npcs.constants; - -public enum EnumAuctionDuration { - SHORT(2 * 60 * 60 * 1000L), // 2 hours - MEDIUM(12 * 60 * 60 * 1000L), // 12 hours - LONG(24 * 60 * 60 * 1000L), // 24 hours - VERY_LONG(48 * 60 * 60 * 1000L); // 48 hours - - private final long millis; - - EnumAuctionDuration(long millis) { - this.millis = millis; - } - - public long getMillis() { - return millis; - } - - public String getDisplayName() { - switch (this) { - case SHORT: return "2 Hours"; - case MEDIUM: return "12 Hours"; - case LONG: return "24 Hours"; - case VERY_LONG: return "48 Hours"; - default: return "Unknown"; - } - } -} -``` - -**File: `src/main/java/noppes/npcs/constants/EnumAuctionStatus.java`** - -```java -package noppes.npcs.constants; - -public enum EnumAuctionStatus { - ACTIVE, // Currently listed - SOLD, // Successfully sold (buyout or auction end with bids) - EXPIRED, // Ended without bids - CANCELLED, // Cancelled by seller - CLAIMED // Item/money has been claimed -} -``` - -**File: `src/main/java/noppes/npcs/constants/EnumAuctionCategory.java`** - -```java -package noppes.npcs.constants; - -public enum EnumAuctionCategory { - WEAPONS, - ARMOR, - TOOLS, - FOOD, - POTIONS, - BLOCKS, - MATERIALS, - ENCHANTED, - MISC -} -``` - -### 3.3 Auction Controller - -**File: `src/main/java/noppes/npcs/controllers/AuctionController.java`** - -```java -package noppes.npcs.controllers; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import noppes.npcs.CustomNpcs; -import noppes.npcs.LogWriter; -import noppes.npcs.controllers.data.AuctionListing; -import noppes.npcs.constants.*; - -import java.io.File; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; - -public class AuctionController { - private static AuctionController instance; - - // All listings (thread-safe for async operations) - public ConcurrentHashMap listings = new ConcurrentHashMap<>(); - - // Index by seller for quick lookup - private Map> sellerIndex = new ConcurrentHashMap<>(); - - // Pending claims (seller -> items/money to claim) - public Map> pendingClaims = new ConcurrentHashMap<>(); - - private int nextId = 1; - private long lastSaveTime = 0; - private static final long SAVE_INTERVAL = 60000; // Save every minute - - // Configuration - public double listingFee = 0.0; // Fee to list item - public double saleTax = 0.05; // 5% tax on sales - public int maxListingsPerPlayer = 20; - public boolean requireAuctioneer = true; // Require Auctioneer NPC to access - - public static AuctionController getInstance() { - if (instance == null) { - instance = new AuctionController(); - instance.load(); - } - return instance; - } - - /** - * Create a new auction listing - */ - public AuctionListing createListing(EntityPlayer seller, ItemStack item, - double startPrice, double buyout, - EnumAuctionDuration duration) { - UUID sellerUUID = seller.getUniqueID(); - - // Check max listings - Set sellerListings = sellerIndex.get(sellerUUID); - if (sellerListings != null && sellerListings.size() >= maxListingsPerPlayer) { - return null; - } - - // Charge listing fee - if (listingFee > 0) { - CurrencyController currency = CurrencyController.getInstance(); - if (!currency.withdraw(seller, listingFee)) { - return null; - } - } - - // Create listing - AuctionListing listing = new AuctionListing( - sellerUUID, seller.getCommandSenderName(), - item, startPrice, buyout, duration - ); - listing.id = nextId++; - - // Add to indexes - listings.put(listing.id, listing); - sellerIndex.computeIfAbsent(sellerUUID, k -> new HashSet<>()).add(listing.id); - - // Remove item from seller inventory - item.stackSize = 0; - - scheduleSave(); - return listing; - } - - /** - * Place a bid on an auction - */ - public boolean placeBid(EntityPlayer bidder, int listingId, double amount) { - AuctionListing listing = listings.get(listingId); - if (listing == null || listing.isExpired()) return false; - - CurrencyController currency = CurrencyController.getInstance(); - - // Check if bidder can afford - if (!currency.canAfford(bidder, amount)) return false; - - // Refund previous bidder - if (listing.highBidderUUID != null) { - addClaim(listing.highBidderUUID, listing.highBidderName, - null, listing.currentBid, "Outbid refund for: " + - listing.item.getDisplayName()); - } - - // Place bid - if (!listing.placeBid(bidder.getUniqueID(), - bidder.getCommandSenderName(), amount)) { - return false; - } - - // Hold currency from bidder - currency.withdraw(bidder, amount); - - scheduleSave(); - return true; - } - - /** - * Buyout an auction - */ - public boolean buyout(EntityPlayer buyer, int listingId) { - AuctionListing listing = listings.get(listingId); - if (listing == null || listing.buyoutPrice <= 0) return false; - - CurrencyController currency = CurrencyController.getInstance(); - - // Check if buyer can afford - if (!currency.canAfford(buyer, listing.buyoutPrice)) return false; - - // Refund previous bidder if any - if (listing.highBidderUUID != null) { - addClaim(listing.highBidderUUID, listing.highBidderName, - null, listing.currentBid, "Buyout refund for: " + - listing.item.getDisplayName()); - } - - // Execute buyout - if (!listing.buyout(buyer.getUniqueID(), buyer.getCommandSenderName())) { - return false; - } - - // Withdraw from buyer - currency.withdraw(buyer, listing.buyoutPrice); - - // Calculate seller proceeds (minus tax) - double proceeds = listing.buyoutPrice * (1 - saleTax); - - // Add claims for both parties - addClaim(listing.sellerUUID, listing.sellerName, null, proceeds, - "Sale of: " + listing.item.getDisplayName()); - addClaim(buyer.getUniqueID(), buyer.getCommandSenderName(), - listing.item, 0, "Purchased: " + listing.item.getDisplayName()); - - scheduleSave(); - return true; - } - - /** - * Cancel a listing (seller only) - */ - public boolean cancelListing(EntityPlayer player, int listingId) { - AuctionListing listing = listings.get(listingId); - if (listing == null) return false; - - if (!listing.cancel(player.getUniqueID())) return false; - - // Return item to seller - addClaim(listing.sellerUUID, listing.sellerName, listing.item, 0, - "Cancelled listing: " + listing.item.getDisplayName()); - - scheduleSave(); - return true; - } - - /** - * Process expired auctions (called periodically) - */ - public void processExpiredAuctions() { - long now = System.currentTimeMillis(); - - for (AuctionListing listing : listings.values()) { - if (listing.status != EnumAuctionStatus.ACTIVE) continue; - if (!listing.isExpired()) continue; - - if (listing.highBidderUUID != null) { - // Auction successful - has bids - listing.status = EnumAuctionStatus.SOLD; - - double proceeds = listing.currentBid * (1 - saleTax); - addClaim(listing.sellerUUID, listing.sellerName, null, proceeds, - "Auction sold: " + listing.item.getDisplayName()); - addClaim(listing.highBidderUUID, listing.highBidderName, - listing.item, 0, "Won auction: " + listing.item.getDisplayName()); - } else { - // No bids - return to seller - listing.status = EnumAuctionStatus.EXPIRED; - addClaim(listing.sellerUUID, listing.sellerName, listing.item, 0, - "Expired listing: " + listing.item.getDisplayName()); - } - } - - scheduleSave(); - } - - /** - * Get active listings with optional filters - */ - public List getActiveListings(EnumAuctionCategory category, - String search, - int page, int pageSize) { - return listings.values().stream() - .filter(l -> l.status == EnumAuctionStatus.ACTIVE) - .filter(l -> !l.isExpired()) - .filter(l -> category == null || l.category == category) - .filter(l -> search == null || search.isEmpty() || - l.item.getDisplayName().toLowerCase() - .contains(search.toLowerCase())) - .sorted(Comparator.comparingLong(l -> l.expirationTime)) - .skip((long) page * pageSize) - .limit(pageSize) - .collect(Collectors.toList()); - } - - /** - * Get player's own listings - */ - public List getPlayerListings(UUID playerUUID) { - Set ids = sellerIndex.get(playerUUID); - if (ids == null) return Collections.emptyList(); - - return ids.stream() - .map(listings::get) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - } - - /** - * Get pending claims for a player - */ - public List getPendingClaims(UUID playerUUID) { - return pendingClaims.getOrDefault(playerUUID, Collections.emptyList()); - } - - /** - * Claim pending items/money - */ - public boolean claim(EntityPlayer player, int claimIndex) { - List claims = pendingClaims.get(player.getUniqueID()); - if (claims == null || claimIndex >= claims.size()) return false; - - AuctionClaim claim = claims.get(claimIndex); - - // Give item or money - if (claim.item != null) { - if (!player.inventory.addItemStackToInventory(claim.item.copy())) { - return false; // Inventory full - } - } - if (claim.money > 0) { - CurrencyController.getInstance().deposit(player, claim.money); - } - - claims.remove(claimIndex); - scheduleSave(); - return true; - } - - private void addClaim(UUID playerUUID, String playerName, - ItemStack item, double money, String description) { - AuctionClaim claim = new AuctionClaim(item, money, description); - pendingClaims.computeIfAbsent(playerUUID, k -> new ArrayList<>()).add(claim); - } - - // Persistence - private void scheduleSave() { - long now = System.currentTimeMillis(); - if (now - lastSaveTime > SAVE_INTERVAL) { - save(); - lastSaveTime = now; - } - } - - public void save() { - try { - NBTTagCompound compound = new NBTTagCompound(); - compound.setInteger("NextId", nextId); - compound.setDouble("ListingFee", listingFee); - compound.setDouble("SaleTax", saleTax); - compound.setInteger("MaxListings", maxListingsPerPlayer); - - // Save listings - NBTTagList listingList = new NBTTagList(); - for (AuctionListing listing : listings.values()) { - listingList.appendTag(listing.writeToNBT(new NBTTagCompound())); - } - compound.setTag("Listings", listingList); - - // Save claims - NBTTagList claimList = new NBTTagList(); - for (Map.Entry> entry : pendingClaims.entrySet()) { - NBTTagCompound playerClaims = new NBTTagCompound(); - playerClaims.setString("UUID", entry.getKey().toString()); - NBTTagList claims = new NBTTagList(); - for (AuctionClaim claim : entry.getValue()) { - claims.appendTag(claim.writeToNBT(new NBTTagCompound())); - } - playerClaims.setTag("Claims", claims); - claimList.appendTag(playerClaims); - } - compound.setTag("PendingClaims", claimList); - - File file = new File(CustomNpcs.getWorldSaveDirectory(), "auction.dat"); - CompressedStreamTools.writeCompressed(compound, - new java.io.FileOutputStream(file)); - - } catch (Exception e) { - LogWriter.except(e); - } - } - - public void load() { - try { - File file = new File(CustomNpcs.getWorldSaveDirectory(), "auction.dat"); - if (!file.exists()) return; - - NBTTagCompound compound = CompressedStreamTools.readCompressed( - new java.io.FileInputStream(file)); - - nextId = compound.getInteger("NextId"); - listingFee = compound.getDouble("ListingFee"); - saleTax = compound.getDouble("SaleTax"); - maxListingsPerPlayer = compound.getInteger("MaxListings"); - - // Load listings - NBTTagList listingList = compound.getTagList("Listings", 10); - for (int i = 0; i < listingList.tagCount(); i++) { - AuctionListing listing = new AuctionListing(); - listing.readFromNBT(listingList.getCompoundTagAt(i)); - listings.put(listing.id, listing); - sellerIndex.computeIfAbsent(listing.sellerUUID, k -> new HashSet<>()) - .add(listing.id); - } - - // Load claims - NBTTagList claimList = compound.getTagList("PendingClaims", 10); - for (int i = 0; i < claimList.tagCount(); i++) { - NBTTagCompound playerClaims = claimList.getCompoundTagAt(i); - UUID playerUUID = UUID.fromString(playerClaims.getString("UUID")); - NBTTagList claims = playerClaims.getTagList("Claims", 10); - List claimsList = new ArrayList<>(); - for (int j = 0; j < claims.tagCount(); j++) { - AuctionClaim claim = new AuctionClaim(); - claim.readFromNBT(claims.getCompoundTagAt(j)); - claimsList.add(claim); - } - pendingClaims.put(playerUUID, claimsList); - } - - } catch (Exception e) { - LogWriter.except(e); - } - } -} - -// Claim data structure -class AuctionClaim { - public ItemStack item; - public double money; - public String description; - public long timestamp; - - public AuctionClaim() {} - - public AuctionClaim(ItemStack item, double money, String description) { - this.item = item != null ? item.copy() : null; - this.money = money; - this.description = description; - this.timestamp = System.currentTimeMillis(); - } - - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - if (item != null) { - compound.setTag("Item", item.writeToNBT(new NBTTagCompound())); - } - compound.setDouble("Money", money); - compound.setString("Description", description); - compound.setLong("Timestamp", timestamp); - return compound; - } - - public void readFromNBT(NBTTagCompound compound) { - if (compound.hasKey("Item")) { - item = ItemStack.loadItemStackFromNBT(compound.getCompoundTag("Item")); - } - money = compound.getDouble("Money"); - description = compound.getString("Description"); - timestamp = compound.getLong("Timestamp"); - } -} -``` - -### 3.4 Auctioneer Role - -**File: `src/main/java/noppes/npcs/roles/RoleAuctioneer.java`** - -```java -package noppes.npcs.roles; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import noppes.npcs.NoppesUtilServer; -import noppes.npcs.constants.EnumGuiType; -import noppes.npcs.entity.EntityNPCInterface; - -public class RoleAuctioneer extends RoleInterface { - - // Configuration - public String auctionHouseName = "Global"; // For future multi-auction support - public boolean allowSelling = true; - public boolean allowBuying = true; - public boolean showExpiredListings = true; - - // Custom messages - public String welcomeMessage = ""; - public String sellDisabledMessage = "This auctioneer does not accept listings."; - public String buyDisabledMessage = "This auctioneer does not sell items."; - - public RoleAuctioneer(EntityNPCInterface npc) { - super(npc); - } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setString("AuctionHouse", auctionHouseName); - compound.setBoolean("AllowSelling", allowSelling); - compound.setBoolean("AllowBuying", allowBuying); - compound.setBoolean("ShowExpired", showExpiredListings); - compound.setString("WelcomeMsg", welcomeMessage); - compound.setString("SellDisabledMsg", sellDisabledMessage); - compound.setString("BuyDisabledMsg", buyDisabledMessage); - return compound; - } - - @Override - public void readFromNBT(NBTTagCompound compound) { - auctionHouseName = compound.getString("AuctionHouse"); - allowSelling = compound.getBoolean("AllowSelling"); - allowBuying = compound.getBoolean("AllowBuying"); - showExpiredListings = compound.getBoolean("ShowExpired"); - welcomeMessage = compound.getString("WelcomeMsg"); - sellDisabledMessage = compound.getString("SellDisabledMsg"); - buyDisabledMessage = compound.getString("BuyDisabledMsg"); - } - - @Override - public void interact(EntityPlayer player) { - // Show welcome message if set - if (!welcomeMessage.isEmpty()) { - npc.say(player, npc.advanced.getInteractLine()); - } - - // Open auction house GUI - NoppesUtilServer.sendOpenGui(player, EnumGuiType.PlayerAuction, npc); - } -} -``` - -### 3.5 Update EnumRoleType - -**File: `src/main/java/noppes/npcs/constants/EnumRoleType.java`** - -```java -public enum EnumRoleType { - None, - Trader, - Follower, - Bank, - Transporter, - Postman, - Companion, - Mount, - Auctioneer // Add this -} -``` - -### 3.6 Update DataAdvanced - -**File: `src/main/java/noppes/npcs/DataAdvanced.java`** - -Add to `setRole()` method: - -```java -else if (role == EnumRoleType.Auctioneer && !(npc.roleInterface instanceof RoleAuctioneer)) - npc.roleInterface = new RoleAuctioneer(npc); -``` - -### 3.7 Update EnumGuiType - -**File: `src/main/java/noppes/npcs/constants/EnumGuiType.java`** - -Add new GUI types: - -```java -// Auction House GUIs -PlayerAuction, // Main auction browse/buy interface -PlayerAuctionSell, // Create new listing -PlayerAuctionMyListings, // View own listings -PlayerAuctionClaims, // Claim items/money -AuctioneerSetup, // NPC configuration -ManageAuctions // Admin management -``` - -### 3.8 Auction GUI System - -The auction GUI system will consist of multiple interconnected screens: - -#### 3.8.1 Main Auction Browser - -**File: `src/main/java/noppes/npcs/client/gui/player/GuiAuctionBrowse.java`** - -Features: -- Category filter tabs (Weapons, Armor, Tools, etc.) -- Search bar for item names -- Sort options (Time remaining, Price, Recently listed) -- Paginated listing display -- Quick buy/bid buttons - -#### 3.8.2 Create Listing GUI - -**File: `src/main/java/noppes/npcs/client/gui/player/GuiAuctionSell.java`** - -Features: -- Item slot for the item to sell -- Starting price input -- Buyout price input (optional) -- Duration selector -- Listing fee display -- Confirm button - -#### 3.8.3 My Listings GUI - -**File: `src/main/java/noppes/npcs/client/gui/player/GuiAuctionMyListings.java`** - -Features: -- List of player's active listings -- Current bid status -- Time remaining -- Cancel button (if no bids) - -#### 3.8.4 Claims GUI - -**File: `src/main/java/noppes/npcs/client/gui/player/GuiAuctionClaims.java`** - -Features: -- List of pending claims (items won, money from sales, refunds) -- Claim button for each item -- Claim all button - -### 3.9 Network Packets - -#### 3.9.1 Auction Action Packet - -**File: `src/main/java/kamkeel/npcs/network/packets/player/AuctionActionPacket.java`** - -```java -package kamkeel.npcs.network.packets.player; - -public class AuctionActionPacket extends AbstractPacket { - - public enum Action { - CREATE_LISTING, - PLACE_BID, - BUYOUT, - CANCEL, - CLAIM, - CLAIM_ALL, - BROWSE, - MY_LISTINGS - } - - private Action action; - private int listingId; - private double amount; - private NBTTagCompound itemData; - private int duration; - private double buyoutPrice; - private int category; - private String search; - private int page; - - // Implement sendData/receiveData... -} -``` - -#### 3.9.2 Auction Sync Packet - -**File: `src/main/java/kamkeel/npcs/network/packets/data/AuctionSyncPacket.java`** - -Used to send auction listing data to clients for GUI display. - -### 3.10 Periodic Tasks - -Add to server tick handler to process expired auctions: - -**File: `src/main/java/noppes/npcs/ServerTickHandler.java`** - -```java -private int auctionCheckCounter = 0; - -@SubscribeEvent -public void onServerTick(TickEvent.ServerTickEvent event) { - // ... existing code ... - - // Check expired auctions every 5 minutes (6000 ticks) - if (++auctionCheckCounter >= 6000) { - auctionCheckCounter = 0; - AuctionController.getInstance().processExpiredAuctions(); - } -} -``` - ---- - -## Implementation Order - -The features should be implemented in this order due to dependencies: - -### Phase 1: Currency System (Foundation) -1. Add VaultAPI dependency to build files -2. Create `VaultHelper.java` with reflection-based integration -3. Create `CurrencyController.java` -4. Add initialization hook in `CustomNpcs.java` -5. Create `PlayerCurrencyData.java` and integrate with `PlayerData` -6. Create currency configuration GUI -7. Test with and without Vault present - -### Phase 2: Trader Enhancements -1. Create `EnumStockReset.java` -2. Create `TraderStock.java` -3. Modify `RoleTrader.java` to add stock and currency fields -4. Modify `ContainerNPCTrader.java` to handle stock/currency -5. Update `GuiNpcTraderSetup.java` with new options -6. Update network packets for stock synchronization -7. Test stock depletion and reset timers - -### Phase 3: Auction House -1. Create auction enums (`EnumAuctionDuration`, `EnumAuctionStatus`, `EnumAuctionCategory`) -2. Create `AuctionListing.java` and `AuctionClaim` classes -3. Create `AuctionController.java` -4. Update `EnumRoleType.java` to add Auctioneer -5. Create `RoleAuctioneer.java` -6. Update `DataAdvanced.java` for role instantiation -7. Update `EnumGuiType.java` with auction GUIs -8. Create auction containers -9. Create auction GUI classes -10. Create network packets -11. Add periodic task for expired auctions -12. Create auctioneer setup GUI -13. Comprehensive testing - ---- - -## File Summary - -### New Files to Create - -| File | Description | -|------|-------------| -| `kamkeel/npcs/compat/VaultHelper.java` | VaultAPI integration | -| `kamkeel/npcs/controllers/CurrencyController.java` | Currency management | -| `noppes/npcs/controllers/data/PlayerCurrencyData.java` | Per-player currency data | -| `noppes/npcs/controllers/data/TraderStock.java` | Trader stock configuration | -| `noppes/npcs/constants/EnumStockReset.java` | Stock reset types | -| `noppes/npcs/controllers/AuctionController.java` | Auction house management | -| `noppes/npcs/controllers/data/AuctionListing.java` | Auction listing data | -| `noppes/npcs/constants/EnumAuctionDuration.java` | Auction duration options | -| `noppes/npcs/constants/EnumAuctionStatus.java` | Auction status states | -| `noppes/npcs/constants/EnumAuctionCategory.java` | Item categories | -| `noppes/npcs/roles/RoleAuctioneer.java` | Auctioneer NPC role | -| `noppes/npcs/containers/ContainerAuction*.java` | Auction containers | -| `noppes/npcs/client/gui/player/GuiAuction*.java` | Auction GUIs | -| `noppes/npcs/client/gui/roles/GuiNpcAuctioneerSetup.java` | Auctioneer config | -| `kamkeel/npcs/network/packets/player/AuctionActionPacket.java` | Auction actions | -| `kamkeel/npcs/network/packets/data/AuctionSyncPacket.java` | Auction data sync | - -### Files to Modify +## File Inventory + +### New Files Created + +| File | Purpose | +|------|---------| +| `constants/EnumAuctionDuration.java` | Auction duration options | +| `constants/EnumAuctionSort.java` | Sort options with lang keys | +| `constants/EnumAuctionStatus.java` | Auction state enum | +| `constants/EnumStockReset.java` | Trader stock reset types | +| `controllers/AuctionController.java` | Main auction controller | +| `controllers/AuctionBlacklist.java` | Item blacklist system | +| `controllers/data/AuctionListing.java` | Auction listing data | +| `controllers/data/AuctionFilter.java` | Search/filter criteria | +| `controllers/data/AuctionClaim.java` | Claim data structure | +| `controllers/data/TraderStock.java` | Trader stock system | +| `controllers/data/attribute/ItemTradeAttribute.java` | Trade restriction attributes | +| `roles/RoleAuctioneer.java` | Auctioneer NPC role | +| `containers/ContainerAuction.java` | Auction GUI container | +| `client/gui/player/GuiAuction.java` | Main auction GUI | +| `client/gui/player/SubGuiAuctionCreate.java` | Create listing GUI | +| `client/gui/player/SubGuiAuctionBid.java` | Place bid GUI | +| `client/gui/player/SubGuiAuctionDetails.java` | Listing details GUI | +| `config/ConfigMarket.java` | Market configuration | +| `network/packets/player/AuctionActionPacket.java` | Auction action packet | +| `network/packets/data/AuctionDataPacket.java` | Auction data sync packet | + +### Files Deleted +| File | Reason | +|------|--------| +| ~~`constants/EnumAuctionCategory.java`~~ | Categories removed | +| ~~`controllers/AuctionLogger.java`~~ | Consolidated into AuctionController | +| ~~`controllers/AuctionNotificationController.java`~~ | Consolidated into AuctionController | + +### Files Modified | File | Changes | |------|---------| -| `dependencies.gradle` | Add VaultAPI dependency | -| `repositories.gradle` | Add Vault repository | -| `CustomNpcs.java` | Initialize VaultHelper, AuctionController | -| `EnumRoleType.java` | Add Auctioneer | -| `EnumGuiType.java` | Add auction GUI types | -| `DataAdvanced.java` | Handle Auctioneer role | -| `RoleTrader.java` | Add stock and currency support | -| `ContainerNPCTrader.java` | Handle stock/currency transactions | -| `GuiNpcTraderSetup.java` | Add stock/currency UI | -| `PlayerData.java` | Add PlayerCurrencyData | -| `CommonProxy.java` | Register auction containers | -| `ServerTickHandler.java` | Add auction expiration check | +| `CustomNpcs.java` | Initialize AuctionController, AuctionBlacklist | +| `ServerTickHandler.java` | Call AuctionController.onPlayerLogin() | +| `constants/EnumRoleType.java` | Added Auctioneer | +| `constants/EnumGuiType.java` | Added auction GUI types | +| `DataAdvanced.java` | Handle Auctioneer role creation | +| `roles/RoleTrader.java` | Added stock system | +| `containers/ContainerNPCTrader.java` | Stock handling | +| `CustomNpcsPermissions.java` | Auction permission nodes | +| `api/ICustomNpc.java` | Auction API methods | | `PacketHandler.java` | Register auction packets | +| `en_US.lang` | All auction lang keys | --- -## Testing Strategy +## Localization Keys Added -### Unit Testing -- Currency operations (deposit, withdraw, balance) -- Stock depletion and reset calculations -- Auction bid validation -- Auction expiration handling +```properties +# Main GUI +auction.title=Auction House +auction.browse=Browse +auction.myListings=My Listings +auction.myBids=My Bids +auction.claims=Claims +auction.sell=Sell +auction.search=Search +auction.refresh=Refresh +auction.viewDetails=View Details +auction.placeBid=Place Bid +auction.buyout=Buyout +auction.cancel=Cancel +auction.prevPage=< Prev +auction.nextPage=Next > +auction.noResults=No results +auction.page=Page %d of %d +auction.balance=Balance: %s +auction.listings=%d listings -### Integration Testing -- VaultAPI integration on hybrid servers -- Fallback to item currency when Vault unavailable -- Stock persistence across server restarts -- Auction persistence and recovery +# Tab Titles +auction.browseTitle=Browse Auctions +auction.myListingsTitle=My Listings +auction.myBidsTitle=My Active Bids +auction.claimsTitle=Claim Items +auction.sellTitle=Create Listing -### User Acceptance Testing -- Complete trading flow with stock limits -- Complete auction flow (list → bid → win → claim) -- Currency display formatting -- GUI usability +# Listing Details +auction.item=Item: +auction.seller=Seller: +auction.startingPrice=Starting Price: +auction.buyoutPrice=Buyout Price: +auction.currentPrice=Current Price: +auction.currentBid=Current Bid: +auction.minimumBid=Minimum Bid: +auction.highBidder=High Bidder: +auction.totalBids=Total Bids: +auction.quantity=Quantity: +auction.timeLeft=Time Left: +auction.yourBid=Your Bid: +auction.yourBalance=Your Balance: +auction.ended=Ended +auction.noBidsYet=No bids yet -### Edge Cases -- Negative currency amounts -- Concurrent bids on same auction -- Server crash during transaction -- Player offline when auction ends -- Maximum listings per player -- Inventory full when claiming +# Create Listing +auction.createListing=Create Listing +auction.placeItemBelow=Place item in slot below: +auction.noItemSelected=(No item selected) +auction.noBuyoutHint=(0 = no buyout) +auction.duration=Duration: +auction.listingFee=Listing Fee: +auction.create=Create ---- +# Bid GUI +auction.minBid=Min Bid +auction.bidPlus10=+10% +auction.bidPlus25=+25% +auction.insufficientFunds=Insufficient funds! +auction.auctionEnded=Auction has ended! +auction.auctionDetails=Auction Details -## API/Scripting Extensions +# Sort Options +auction.sort.newest=Newest First +auction.sort.oldest=Oldest First +auction.sort.priceHigh=Most Expensive +auction.sort.priceLow=Least Expensive +auction.sort.endingSoon=Ending Soon +auction.sort.mostTime=Most Time Left +auction.sort.nameAZ=Name: A to Z +auction.sort.nameZA=Name: Z to A +auction.sort.mostBids=Most Bids +auction.sort.leastBids=Least Bids -Consider adding these scripting hooks: - -```java -// ICurrency interface for scripts -double getBalance(IPlayer player); -boolean withdraw(IPlayer player, double amount); -boolean deposit(IPlayer player, double amount); -String format(double amount); - -// IAuction interface for scripts -IAuctionListing createListing(IPlayer seller, IItemStack item, - double startPrice, double buyout, int durationHours); -boolean cancelListing(int listingId); -List getPlayerListings(IPlayer player); - -// Events -onAuctionCreated(IAuctionListing listing); -onAuctionBid(IAuctionListing listing, IPlayer bidder, double amount); -onAuctionSold(IAuctionListing listing, IPlayer buyer, double price); -onAuctionExpired(IAuctionListing listing); -onTraderPurchase(ITrader trader, IPlayer buyer, int slot, int stockRemaining); -onTraderStockReset(ITrader trader); +# Duration Options +auction.duration.short=Short (12h) +auction.duration.medium=Medium (24h) +auction.duration.long=Long (48h) +auction.duration.veryLong=Very Long (72h) ``` --- -## Conclusion +## Design Decisions (Confirmed) -This implementation plan provides a comprehensive roadmap for the CustomNPC+ 1.11 Market Update. The three features are designed to work together seamlessly: +1. **Outbid Refunds** → Go to claims (not direct to balance) +2. **Currency** → Shared across all profile slots per player (NOT slot-bound) +3. **Permissions** → Uses existing CustomNPC+ permission pattern (default: 5 slots) +4. **Categories** → Removed for initial implementation (can add later) +5. **Controller Architecture** → Single consolidated AuctionController +6. **Localization** → All client strings use StatCollector with lang keys +7. **StatCollector Usage** → Safe - only called from client-side GUI code +8. **Claim Expiration** → 30 days default (configurable) +9. **Snipe Protection** → Extend TO 5 minutes when bid placed near end +10. **Logging** → Inline in AuctionController using LogWriter -1. **Currency System** provides the foundation for monetary transactions -2. **Trader Enhancements** modernize the existing trader with stock and currency support -3. **Auction House** creates a global marketplace leveraging the currency system +--- -The implementation follows existing codebase patterns and can be developed incrementally, with each phase building on the previous one. +## Next Steps + +1. **Currency System** - Implement VaultHelper and CurrencyController to connect actual economy +2. **Admin Management** - Implement admin GUI and commands +3. **Testing** - Comprehensive testing of all auction flows +4. **Auctioneer Setup GUI** - Create NPC configuration interface +5. **Trader Banner** - Add stock reset timer display above trader GUI diff --git a/src/main/java/kamkeel/npcs/controllers/data/attribute/ItemTradeAttribute.java b/src/main/java/kamkeel/npcs/controllers/data/attribute/ItemTradeAttribute.java new file mode 100644 index 000000000..180f41d02 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/attribute/ItemTradeAttribute.java @@ -0,0 +1,308 @@ +package kamkeel.npcs.controllers.data.attribute; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.controllers.data.PlayerData; + +import java.util.UUID; + +/** + * Utility class for managing item trade restrictions. + * Checks and sets attributes that control whether items can be traded/auctioned. + */ +public class ItemTradeAttribute { + + // New untradeable attribute - prevents all trading + public static final String TAG_UNTRADEABLE = "CNPC_Untradeable"; + + // Existing requirement keys (from ProfileSlotRequirement and SoulbindRequirement) + public static final String TAG_PROFILE_SLOT = "cnpc_profile_slot"; + public static final String TAG_SOULBIND = "cnpc_soulbind"; + + // ==================== Trade Check Methods ==================== + + /** + * Check if item can be traded/auctioned by the given player. + * An item cannot be traded if: + * - It has the Untradeable flag + * - It is bound to a specific profile slot (ProfileSlot Bound) + * - It is soulbound to a different player + * + * @param item The item to check + * @param player The player trying to trade (null to check without player context) + * @return true if the item can be traded + */ + public static boolean canTrade(ItemStack item, EntityPlayer player) { + if (item == null) { + return true; + } + if (!item.hasTagCompound()) { + return true; + } + + NBTTagCompound tag = item.getTagCompound(); + + // Check untradeable flag - always blocks trading + if (tag.getBoolean(TAG_UNTRADEABLE)) { + return false; + } + + // Check profile slot bound - blocks trading as it's tied to a slot + if (tag.hasKey(TAG_PROFILE_SLOT)) { + return false; + } + + // Check soulbound - blocks trading as it's tied to a player + if (tag.hasKey(TAG_SOULBIND)) { + // If we have a player context, check if they're the owner + if (player != null) { + String soulbindUUID = tag.getString(TAG_SOULBIND); + if (soulbindUUID != null && !soulbindUUID.isEmpty()) { + // Even if bound to this player, still can't trade + return false; + } + } + return false; + } + + return true; + } + + /** + * Check if item can be traded (without player context) + */ + public static boolean canTrade(ItemStack item) { + return canTrade(item, null); + } + + /** + * Get the reason why an item cannot be traded. + * Returns a translation key for localization. + * + * @param item The item to check + * @return Translation key for the block reason, or null if tradeable + */ + public static String getTradeBlockReason(ItemStack item) { + if (item == null || !item.hasTagCompound()) { + return null; + } + + NBTTagCompound tag = item.getTagCompound(); + + if (tag.getBoolean(TAG_UNTRADEABLE)) { + return "gui.auction.untradeable"; + } + if (tag.hasKey(TAG_PROFILE_SLOT)) { + return "gui.auction.profileslotbound"; + } + if (tag.hasKey(TAG_SOULBIND)) { + return "gui.auction.soulbound"; + } + + return null; + } + + // ==================== Untradeable Methods ==================== + + /** + * Check if item is marked as untradeable + */ + public static boolean isUntradeable(ItemStack item) { + if (item == null || !item.hasTagCompound()) { + return false; + } + return item.getTagCompound().getBoolean(TAG_UNTRADEABLE); + } + + /** + * Set the untradeable flag on an item + */ + public static void setUntradeable(ItemStack item, boolean untradeable) { + if (item == null) { + return; + } + if (!item.hasTagCompound()) { + item.setTagCompound(new NBTTagCompound()); + } + if (untradeable) { + item.getTagCompound().setBoolean(TAG_UNTRADEABLE, true); + } else { + item.getTagCompound().removeTag(TAG_UNTRADEABLE); + } + } + + // ==================== Profile Slot Bound Methods ==================== + + /** + * Check if item is bound to a profile slot + */ + public static boolean isProfileSlotBound(ItemStack item) { + if (item == null || !item.hasTagCompound()) { + return false; + } + return item.getTagCompound().hasKey(TAG_PROFILE_SLOT); + } + + /** + * Get the profile slot an item is bound to + * @return The profile slot ID, or -1 if not bound + */ + public static int getProfileSlot(ItemStack item) { + if (item == null || !item.hasTagCompound()) { + return -1; + } + if (item.getTagCompound().hasKey(TAG_PROFILE_SLOT)) { + return item.getTagCompound().getInteger(TAG_PROFILE_SLOT); + } + return -1; + } + + /** + * Bind an item to a specific profile slot + */ + public static void setProfileSlotBound(ItemStack item, int slot) { + if (item == null) { + return; + } + if (!item.hasTagCompound()) { + item.setTagCompound(new NBTTagCompound()); + } + if (slot >= 0) { + item.getTagCompound().setInteger(TAG_PROFILE_SLOT, slot); + } else { + item.getTagCompound().removeTag(TAG_PROFILE_SLOT); + } + } + + /** + * Bind an item to the player's current profile slot + */ + public static void bindToCurrentSlot(ItemStack item, EntityPlayer player) { + if (item == null || player == null) { + return; + } + PlayerData data = PlayerData.get(player); + if (data != null) { + setProfileSlotBound(item, data.profileSlot); + } + } + + // ==================== Soulbind Methods ==================== + + /** + * Check if item is soulbound to any player + */ + public static boolean isSoulbound(ItemStack item) { + if (item == null || !item.hasTagCompound()) { + return false; + } + return item.getTagCompound().hasKey(TAG_SOULBIND); + } + + /** + * Check if item is soulbound to a specific player + */ + public static boolean isSoulboundTo(ItemStack item, EntityPlayer player) { + if (item == null || player == null || !item.hasTagCompound()) { + return false; + } + if (!item.getTagCompound().hasKey(TAG_SOULBIND)) { + return false; + } + String soulbindUUID = item.getTagCompound().getString(TAG_SOULBIND); + return player.getUniqueID().toString().equals(soulbindUUID); + } + + /** + * Get the UUID of the player the item is soulbound to + * @return The UUID string, or null if not soulbound + */ + public static String getSoulbindOwner(ItemStack item) { + if (item == null || !item.hasTagCompound()) { + return null; + } + if (item.getTagCompound().hasKey(TAG_SOULBIND)) { + return item.getTagCompound().getString(TAG_SOULBIND); + } + return null; + } + + /** + * Soulbind an item to a player + */ + public static void setSoulbound(ItemStack item, EntityPlayer player) { + if (item == null || player == null) { + return; + } + if (!item.hasTagCompound()) { + item.setTagCompound(new NBTTagCompound()); + } + item.getTagCompound().setString(TAG_SOULBIND, player.getUniqueID().toString()); + } + + /** + * Soulbind an item to a player by UUID + */ + public static void setSoulbound(ItemStack item, UUID playerUUID) { + if (item == null || playerUUID == null) { + return; + } + if (!item.hasTagCompound()) { + item.setTagCompound(new NBTTagCompound()); + } + item.getTagCompound().setString(TAG_SOULBIND, playerUUID.toString()); + } + + /** + * Remove soulbind from an item + */ + public static void removeSoulbind(ItemStack item) { + if (item == null || !item.hasTagCompound()) { + return; + } + item.getTagCompound().removeTag(TAG_SOULBIND); + } + + // ==================== Utility Methods ==================== + + /** + * Clear all trade restriction attributes from an item + */ + public static void clearAllRestrictions(ItemStack item) { + if (item == null || !item.hasTagCompound()) { + return; + } + NBTTagCompound tag = item.getTagCompound(); + tag.removeTag(TAG_UNTRADEABLE); + tag.removeTag(TAG_PROFILE_SLOT); + tag.removeTag(TAG_SOULBIND); + } + + /** + * Get a display string describing all trade restrictions on an item + * @return Human-readable string of restrictions, or empty if none + */ + public static String getRestrictionSummary(ItemStack item) { + if (item == null || !item.hasTagCompound()) { + return ""; + } + + StringBuilder summary = new StringBuilder(); + NBTTagCompound tag = item.getTagCompound(); + + if (tag.getBoolean(TAG_UNTRADEABLE)) { + summary.append("Untradeable"); + } + if (tag.hasKey(TAG_PROFILE_SLOT)) { + if (summary.length() > 0) summary.append(", "); + summary.append("Profile Slot Bound (Slot ").append(tag.getInteger(TAG_PROFILE_SLOT)).append(")"); + } + if (tag.hasKey(TAG_SOULBIND)) { + if (summary.length() > 0) summary.append(", "); + summary.append("Soulbound"); + } + + return summary.toString(); + } +} diff --git a/src/main/java/kamkeel/npcs/network/PacketHandler.java b/src/main/java/kamkeel/npcs/network/PacketHandler.java index 2bdf70426..b6d30d62d 100644 --- a/src/main/java/kamkeel/npcs/network/PacketHandler.java +++ b/src/main/java/kamkeel/npcs/network/PacketHandler.java @@ -36,6 +36,7 @@ import kamkeel.npcs.network.packets.data.gui.GuiWaypointPacket; import kamkeel.npcs.network.packets.data.gui.IsGuiOpenPacket; import kamkeel.npcs.network.packets.data.large.GuiDataPacket; import kamkeel.npcs.network.packets.data.large.PartyDataPacket; +import kamkeel.npcs.network.packets.data.large.AuctionDataPacket; import kamkeel.npcs.network.packets.data.large.ScrollDataPacket; import kamkeel.npcs.network.packets.data.large.ScrollListPacket; import kamkeel.npcs.network.packets.data.large.SyncEffectPacket; @@ -51,6 +52,7 @@ import kamkeel.npcs.network.packets.data.script.ScriptOverlayDataPacket; import kamkeel.npcs.network.packets.data.script.ScriptedParticlePacket; import kamkeel.npcs.network.packets.data.ability.TelegraphSpawnPacket; import kamkeel.npcs.network.packets.data.ability.TelegraphRemovePacket; +import kamkeel.npcs.network.packets.player.AuctionActionPacket; import kamkeel.npcs.network.packets.player.BankActionPacket; import kamkeel.npcs.network.packets.player.CheckPlayerValue; import kamkeel.npcs.network.packets.player.CompanionActionPacket; @@ -564,6 +566,9 @@ public class PacketHandler { // Data | Ability Packets DATA_PACKET.registerPacket(new TelegraphSpawnPacket()); DATA_PACKET.registerPacket(new TelegraphRemovePacket()); + + // Auction Data + DATA_PACKET.registerPacket(new AuctionDataPacket()); } public void registerPlayerPackets() { @@ -625,6 +630,9 @@ public class PacketHandler { PLAYER_PACKET.registerPacket(new PartyAcceptInvitePacket()); PLAYER_PACKET.registerPacket(new PartyIgnoreInvitePacket()); PLAYER_PACKET.registerPacket(new PartyLogToServerPacket()); + + // Auction Packets + PLAYER_PACKET.registerPacket(new AuctionActionPacket()); } public void registerChannels() { diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java index ebcbdfc59..ec8eabf41 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java @@ -62,4 +62,7 @@ public enum EnumDataPacket { // Ability System TELEGRAPH_SPAWN, TELEGRAPH_REMOVE, + + // Auction + AUCTION_DATA, } diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java index 0c1db3cd9..15c90fce5 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java @@ -33,4 +33,7 @@ public enum EnumPlayerPacket { ProfileGet, ProfileGetInfo, SyncRevisionInfo, + + // Auction + AuctionAction, } diff --git a/src/main/java/kamkeel/npcs/network/packets/data/large/AuctionDataPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/large/AuctionDataPacket.java new file mode 100644 index 000000000..f7ca16dd7 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/large/AuctionDataPacket.java @@ -0,0 +1,218 @@ +package kamkeel.npcs.network.packets.data.large; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import kamkeel.npcs.network.LargeAbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.controllers.AuctionController; +import noppes.npcs.controllers.data.AuctionFilter; +import noppes.npcs.controllers.data.AuctionListing; + +import java.io.IOException; +import java.util.List; + +/** + * Large packet for sending auction listing data from server to client. + * Used for initial load and search/filter queries. + */ +public final class AuctionDataPacket extends LargeAbstractPacket { + public static final String packetName = "Large|AuctionData"; + + private DataType dataType; + private List listings; + private int totalResults; + private int currentPage; + private int totalPages; + private long playerBalance; + + public AuctionDataPacket() { + } + + private AuctionDataPacket(DataType type, List listings, + int totalResults, int currentPage, int totalPages, + long playerBalance) { + this.dataType = type; + this.listings = listings; + this.totalResults = totalResults; + this.currentPage = currentPage; + this.totalPages = totalPages; + this.playerBalance = playerBalance; + } + + /** + * Send filtered listing results to client + */ + public static void sendFilteredListings(EntityPlayerMP player, AuctionFilter filter) { + if (AuctionController.Instance == null) { + return; + } + + AuctionController.FilterResult result = AuctionController.Instance.getFilteredListings(filter); + long balance = 0; + if (noppes.npcs.controllers.CurrencyController.Instance != null) { + balance = noppes.npcs.controllers.CurrencyController.Instance.getBalance(player); + } + + AuctionDataPacket packet = new AuctionDataPacket( + DataType.FILTERED_LISTINGS, + result.listings, + result.totalResults, + result.currentPage, + result.totalPages, + balance + ); + PacketHandler.Instance.sendToPlayer(packet, player); + } + + /** + * Send player's own listings + */ + public static void sendMyListings(EntityPlayerMP player) { + if (AuctionController.Instance == null) { + return; + } + + List myListings = AuctionController.Instance + .getListingsBySeller(player.getUniqueID()); + + long balance = 0; + if (noppes.npcs.controllers.CurrencyController.Instance != null) { + balance = noppes.npcs.controllers.CurrencyController.Instance.getBalance(player); + } + + AuctionDataPacket packet = new AuctionDataPacket( + DataType.MY_LISTINGS, + myListings, + myListings.size(), + 0, + 1, + balance + ); + PacketHandler.Instance.sendToPlayer(packet, player); + } + + /** + * Send player's active bids + */ + public static void sendMyBids(EntityPlayerMP player) { + if (AuctionController.Instance == null) { + return; + } + + List myBids = AuctionController.Instance + .getListingsAsBidder(player.getUniqueID()); + + long balance = 0; + if (noppes.npcs.controllers.CurrencyController.Instance != null) { + balance = noppes.npcs.controllers.CurrencyController.Instance.getBalance(player); + } + + AuctionDataPacket packet = new AuctionDataPacket( + DataType.MY_BIDS, + myBids, + myBids.size(), + 0, + 1, + balance + ); + PacketHandler.Instance.sendToPlayer(packet, player); + } + + /** + * Send player's claimable items + */ + public static void sendClaimable(EntityPlayerMP player) { + if (AuctionController.Instance == null) { + return; + } + + List claimable = AuctionController.Instance + .getClaimableListings(player.getUniqueID()); + + long balance = 0; + if (noppes.npcs.controllers.CurrencyController.Instance != null) { + balance = noppes.npcs.controllers.CurrencyController.Instance.getBalance(player); + } + + AuctionDataPacket packet = new AuctionDataPacket( + DataType.CLAIMABLE, + claimable, + claimable.size(), + 0, + 1, + balance + ); + PacketHandler.Instance.sendToPlayer(packet, player); + } + + @Override + public Enum getType() { + return EnumDataPacket.AUCTION_DATA; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + protected byte[] getData() throws IOException { + ByteBuf buffer = Unpooled.buffer(); + + buffer.writeInt(dataType.ordinal()); + buffer.writeInt(totalResults); + buffer.writeInt(currentPage); + buffer.writeInt(totalPages); + buffer.writeLong(playerBalance); + + // Write listings as NBT + NBTTagList listingList = new NBTTagList(); + if (listings != null) { + for (AuctionListing listing : listings) { + listingList.appendTag(listing.writeToNBT(new NBTTagCompound())); + } + } + + NBTTagCompound compound = new NBTTagCompound(); + compound.setTag("Listings", listingList); + ByteBufUtils.writeNBT(buffer, compound); + + byte[] bytes = new byte[buffer.readableBytes()]; + buffer.readBytes(bytes); + return bytes; + } + + @Override + protected void handleCompleteData(ByteBuf data, EntityPlayer player) throws IOException { + // Client-side handling will be done in a client util class + // Similar to NoppesUtil.setScrollData() + int typeOrdinal = data.readInt(); + int totalResults = data.readInt(); + int currentPage = data.readInt(); + int totalPages = data.readInt(); + long playerBalance = data.readLong(); + + NBTTagCompound compound = ByteBufUtils.readNBT(data); + + DataType type = DataType.values()[typeOrdinal]; + + // Store data for client GUI to access + // This will be implemented in the client-side GUI handler + noppes.npcs.client.NoppesUtil.setAuctionData(type.ordinal(), compound, + totalResults, currentPage, totalPages, playerBalance); + } + + public enum DataType { + FILTERED_LISTINGS, + MY_LISTINGS, + MY_BIDS, + CLAIMABLE + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/player/AuctionActionPacket.java b/src/main/java/kamkeel/npcs/network/packets/player/AuctionActionPacket.java new file mode 100644 index 000000000..a63312d80 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/player/AuctionActionPacket.java @@ -0,0 +1,579 @@ +package kamkeel.npcs.network.packets.player; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumPlayerPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChatComponentText; +import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.constants.EnumAuctionDuration; +import noppes.npcs.constants.EnumRoleType; +import noppes.npcs.containers.ContainerAuction; +import noppes.npcs.controllers.AuctionController; +import noppes.npcs.controllers.CurrencyController; +import noppes.npcs.controllers.data.AuctionFilter; +import noppes.npcs.controllers.data.AuctionListing; +import noppes.npcs.util.NBTJsonUtil; +import kamkeel.npcs.network.packets.data.large.AuctionDataPacket; + +import java.io.IOException; + +/** + * Packet for all auction-related player actions. + * Client -> Server for actions, Server -> Client for responses. + */ +public class AuctionActionPacket extends AbstractPacket { + public static final String packetName = "Player|Auction"; + + private Action action; + private int listingId; + private long amount; + private long buyoutPrice; + private int durationOrdinal; + private NBTTagCompound itemData; + private NBTTagCompound filterData; // For query operations + private String responseMessage; + private boolean success; + + public AuctionActionPacket() { + } + + private AuctionActionPacket(Action action) { + this.action = action; + } + + @Override + public boolean needsNPC() { + return true; + } + + // ==================== Client -> Server Actions ==================== + + /** + * Create a new auction listing + */ + @SideOnly(Side.CLIENT) + public static void CreateListing(ItemStack item, long startingPrice, long buyoutPrice, EnumAuctionDuration duration) { + AuctionActionPacket packet = new AuctionActionPacket(Action.CreateListing); + packet.amount = startingPrice; + packet.buyoutPrice = buyoutPrice; + packet.durationOrdinal = duration.ordinal(); + packet.itemData = item.writeToNBT(new NBTTagCompound()); + PacketClient.sendClient(packet); + } + + /** + * Place a bid on an auction + */ + @SideOnly(Side.CLIENT) + public static void PlaceBid(int listingId, long bidAmount) { + AuctionActionPacket packet = new AuctionActionPacket(Action.PlaceBid); + packet.listingId = listingId; + packet.amount = bidAmount; + PacketClient.sendClient(packet); + } + + /** + * Execute buyout on an auction + */ + @SideOnly(Side.CLIENT) + public static void Buyout(int listingId) { + AuctionActionPacket packet = new AuctionActionPacket(Action.Buyout); + packet.listingId = listingId; + PacketClient.sendClient(packet); + } + + /** + * Cancel own listing + */ + @SideOnly(Side.CLIENT) + public static void CancelListing(int listingId) { + AuctionActionPacket packet = new AuctionActionPacket(Action.CancelListing); + packet.listingId = listingId; + PacketClient.sendClient(packet); + } + + /** + * Claim item from won/expired/cancelled auction + */ + @SideOnly(Side.CLIENT) + public static void ClaimItem(int listingId) { + AuctionActionPacket packet = new AuctionActionPacket(Action.ClaimItem); + packet.listingId = listingId; + PacketClient.sendClient(packet); + } + + /** + * Claim proceeds from sold auction + */ + @SideOnly(Side.CLIENT) + public static void ClaimProceeds(int listingId) { + AuctionActionPacket packet = new AuctionActionPacket(Action.ClaimProceeds); + packet.listingId = listingId; + PacketClient.sendClient(packet); + } + + /** + * Query filtered listings + */ + @SideOnly(Side.CLIENT) + public static void QueryListings(AuctionFilter filter) { + AuctionActionPacket packet = new AuctionActionPacket(Action.QueryListings); + packet.filterData = filter.writeToNBT(new NBTTagCompound()); + PacketClient.sendClient(packet); + } + + /** + * Request player's own listings + */ + @SideOnly(Side.CLIENT) + public static void QueryMyListings() { + AuctionActionPacket packet = new AuctionActionPacket(Action.QueryMyListings); + PacketClient.sendClient(packet); + } + + /** + * Request player's active bids + */ + @SideOnly(Side.CLIENT) + public static void QueryMyBids() { + AuctionActionPacket packet = new AuctionActionPacket(Action.QueryMyBids); + PacketClient.sendClient(packet); + } + + /** + * Request player's claimable items + */ + @SideOnly(Side.CLIENT) + public static void QueryClaimable() { + AuctionActionPacket packet = new AuctionActionPacket(Action.QueryClaimable); + PacketClient.sendClient(packet); + } + + @Override + public Enum getType() { + return EnumPlayerPacket.AuctionAction; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.PLAYER_PACKET; + } + + @Override + @SideOnly(Side.CLIENT) + public void sendData(ByteBuf out) throws IOException { + out.writeInt(action.ordinal()); + + switch (action) { + case CreateListing: + out.writeLong(amount); + out.writeLong(buyoutPrice); + out.writeInt(durationOrdinal); + String itemJson = NBTJsonUtil.Convert(itemData); + byte[] itemBytes = itemJson.getBytes("UTF-8"); + out.writeInt(itemBytes.length); + out.writeBytes(itemBytes); + break; + + case PlaceBid: + out.writeInt(listingId); + out.writeLong(amount); + break; + + case Buyout: + case CancelListing: + case ClaimItem: + case ClaimProceeds: + out.writeInt(listingId); + break; + + case QueryListings: + String filterJson = NBTJsonUtil.Convert(filterData); + byte[] filterBytes = filterJson.getBytes("UTF-8"); + out.writeInt(filterBytes.length); + out.writeBytes(filterBytes); + break; + + case QueryMyListings: + case QueryMyBids: + case QueryClaimable: + // No additional data needed + break; + } + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + Action requestedAction = Action.values()[in.readInt()]; + + if (!(player instanceof EntityPlayerMP)) { + return; + } + + EntityPlayerMP playerMP = (EntityPlayerMP) player; + + // Verify NPC is an Auctioneer + if (npc == null || npc.advanced.role != EnumRoleType.Auctioneer) { + return; + } + + // Check if auction system is enabled + if (!ConfigMarket.AuctionEnabled) { + sendResponse(playerMP, false, "Auction system is disabled"); + return; + } + + // Check controller exists + if (AuctionController.Instance == null) { + sendResponse(playerMP, false, "Auction controller not initialized"); + return; + } + + switch (requestedAction) { + case CreateListing: + handleCreateListing(in, playerMP); + break; + case PlaceBid: + handlePlaceBid(in, playerMP); + break; + case Buyout: + handleBuyout(in, playerMP); + break; + case CancelListing: + handleCancelListing(in, playerMP); + break; + case ClaimItem: + handleClaimItem(in, playerMP); + break; + case ClaimProceeds: + handleClaimProceeds(in, playerMP); + break; + case QueryListings: + handleQueryListings(in, playerMP); + break; + case QueryMyListings: + handleQueryMyListings(playerMP); + break; + case QueryMyBids: + handleQueryMyBids(playerMP); + break; + case QueryClaimable: + handleQueryClaimable(playerMP); + break; + } + } + + private void handleCreateListing(ByteBuf in, EntityPlayerMP player) throws IOException { + // Check permission + if (!CustomNpcsPermissions.hasPermission(player, CustomNpcsPermissions.AUCTION_LIST)) { + sendResponse(player, false, "You don't have permission to create listings"); + return; + } + + long startingPrice = in.readLong(); + long buyoutPrice = in.readLong(); + int durationOrdinal = in.readInt(); + + int itemBytesLength = in.readInt(); + byte[] itemBytes = new byte[itemBytesLength]; + in.readBytes(itemBytes); + String itemJson = new String(itemBytes, "UTF-8"); + + try { + NBTTagCompound itemNBT = NBTJsonUtil.Convert(itemJson); + ItemStack requestedItem = ItemStack.loadItemStackFromNBT(itemNBT); + + if (!(player.openContainer instanceof ContainerAuction)) { + sendResponse(player, false, "Open the auction listing screen to create a listing"); + return; + } + + ContainerAuction container = (ContainerAuction) player.openContainer; + ItemStack slotItem = container.getListingItem(); + + if (requestedItem == null || slotItem == null) { + sendResponse(player, false, "Place an item in the listing slot"); + return; + } + + if (!ItemStack.areItemStacksEqual(slotItem, requestedItem) || slotItem.stackSize != requestedItem.stackSize) { + sendResponse(player, false, "Listing item mismatch"); + return; + } + + // Validate duration + EnumAuctionDuration duration; + if (durationOrdinal >= 0 && durationOrdinal < EnumAuctionDuration.values().length) { + duration = EnumAuctionDuration.values()[durationOrdinal]; + } else { + duration = EnumAuctionDuration.MEDIUM; + } + + // Validate prices + if (startingPrice < 1) { + sendResponse(player, false, "Starting price must be at least 1"); + return; + } + + if (buyoutPrice > 0 && buyoutPrice < startingPrice) { + sendResponse(player, false, "Buyout price must be higher than starting price"); + return; + } + + // Create the listing + AuctionListing listing = AuctionController.Instance.createListing( + player, slotItem, startingPrice, buyoutPrice, duration); + + if (listing != null) { + container.clearListingSlot(); + sendResponse(player, true, "Listing created successfully"); + } else { + sendResponse(player, false, "Failed to create listing. Check your balance and listing limit."); + } + } catch (Exception e) { + sendResponse(player, false, "Error creating listing: " + e.getMessage()); + } + } + + private void handlePlaceBid(ByteBuf in, EntityPlayerMP player) throws IOException { + // Check permission + if (!CustomNpcsPermissions.hasPermission(player, CustomNpcsPermissions.AUCTION_BID)) { + sendResponse(player, false, "You don't have permission to bid"); + return; + } + + int listingId = in.readInt(); + long bidAmount = in.readLong(); + + AuctionListing listing = AuctionController.Instance.getListing(listingId); + if (listing == null) { + sendResponse(player, false, "Listing not found"); + return; + } + + if (!listing.isActive()) { + sendResponse(player, false, "This auction has ended"); + return; + } + + if (bidAmount < listing.getMinimumBid()) { + sendResponse(player, false, "Bid must be at least " + listing.getMinimumBid()); + return; + } + + if (!CurrencyController.Instance.canAfford(player, bidAmount)) { + sendResponse(player, false, "You cannot afford this bid"); + return; + } + + if (AuctionController.Instance.placeBid(listingId, player, bidAmount)) { + sendResponse(player, true, "Bid placed successfully"); + } else { + sendResponse(player, false, "Failed to place bid"); + } + } + + private void handleBuyout(ByteBuf in, EntityPlayerMP player) throws IOException { + // Check permission + if (!CustomNpcsPermissions.hasPermission(player, CustomNpcsPermissions.AUCTION_BUYOUT)) { + sendResponse(player, false, "You don't have permission to use buyout"); + return; + } + + int listingId = in.readInt(); + + AuctionListing listing = AuctionController.Instance.getListing(listingId); + if (listing == null) { + sendResponse(player, false, "Listing not found"); + return; + } + + if (!listing.isActive()) { + sendResponse(player, false, "This auction has ended"); + return; + } + + if (listing.buyoutPrice <= 0) { + sendResponse(player, false, "This listing has no buyout option"); + return; + } + + if (!CurrencyController.Instance.canAfford(player, listing.buyoutPrice)) { + sendResponse(player, false, "You cannot afford the buyout price"); + return; + } + + if (AuctionController.Instance.buyout(listingId, player)) { + sendResponse(player, true, "Buyout successful! Claim your item."); + } else { + sendResponse(player, false, "Failed to execute buyout"); + } + } + + private void handleCancelListing(ByteBuf in, EntityPlayerMP player) throws IOException { + int listingId = in.readInt(); + + AuctionListing listing = AuctionController.Instance.getListing(listingId); + if (listing == null) { + sendResponse(player, false, "Listing not found"); + return; + } + + // Admin can cancel any listing + boolean isAdmin = CustomNpcsPermissions.hasPermission(player, CustomNpcsPermissions.AUCTION_ADMIN); + + if (!listing.sellerUUID.equals(player.getUniqueID()) && !isAdmin) { + sendResponse(player, false, "You can only cancel your own listings"); + return; + } + + if (listing.hasBids() && !isAdmin) { + sendResponse(player, false, "Cannot cancel listing with active bids"); + return; + } + + if (AuctionController.Instance.cancelListing(listingId, player, isAdmin)) { + sendResponse(player, true, "Listing cancelled. Claim your item."); + } else { + sendResponse(player, false, "Failed to cancel listing"); + } + } + + private void handleClaimItem(ByteBuf in, EntityPlayerMP player) throws IOException { + int listingId = in.readInt(); + + AuctionListing listing = AuctionController.Instance.getListing(listingId); + if (listing == null) { + sendResponse(player, false, "Listing not found"); + return; + } + + ItemStack claimed = null; + + // Try buyer claim first + if (listing.highBidderUUID != null && listing.highBidderUUID.equals(player.getUniqueID())) { + claimed = AuctionController.Instance.claimBuyerItem(listingId, player); + } + // Then try seller reclaim (for expired/cancelled) + else if (listing.sellerUUID.equals(player.getUniqueID())) { + claimed = AuctionController.Instance.claimExpiredItem(listingId, player); + } + + if (claimed != null) { + // Give item to player + if (!player.inventory.addItemStackToInventory(claimed)) { + // Drop if inventory full + player.entityDropItem(claimed, 0.5f); + } + sendResponse(player, true, "Item claimed"); + } else { + sendResponse(player, false, "Cannot claim item"); + } + } + + private void handleClaimProceeds(ByteBuf in, EntityPlayerMP player) throws IOException { + int listingId = in.readInt(); + + AuctionListing listing = AuctionController.Instance.getListing(listingId); + if (listing == null) { + sendResponse(player, false, "Listing not found"); + return; + } + + if (AuctionController.Instance.claimSellerProceeds(listingId, player)) { + long proceeds = listing.getSellerProceeds(); + sendResponse(player, true, "Claimed " + proceeds + " " + ConfigMarket.CurrencyName); + } else { + sendResponse(player, false, "Cannot claim proceeds"); + } + } + + // ==================== Query Handlers ==================== + + private void handleQueryListings(ByteBuf in, EntityPlayerMP player) throws IOException { + // Check permission + if (!CustomNpcsPermissions.hasPermission(player, CustomNpcsPermissions.AUCTION_USE)) { + sendResponse(player, false, "You don't have permission to view auctions"); + return; + } + + int filterBytesLength = in.readInt(); + byte[] filterBytes = new byte[filterBytesLength]; + in.readBytes(filterBytes); + String filterJson = new String(filterBytes, "UTF-8"); + + try { + NBTTagCompound filterNBT = NBTJsonUtil.Convert(filterJson); + AuctionFilter filter = new AuctionFilter(); + filter.readFromNBT(filterNBT); + + // Send filtered listings to client + AuctionDataPacket.sendFilteredListings(player, filter); + } catch (Exception e) { + sendResponse(player, false, "Error parsing filter"); + } + } + + private void handleQueryMyListings(EntityPlayerMP player) { + // Check permission + if (!CustomNpcsPermissions.hasPermission(player, CustomNpcsPermissions.AUCTION_USE)) { + sendResponse(player, false, "You don't have permission to view auctions"); + return; + } + + AuctionDataPacket.sendMyListings(player); + } + + private void handleQueryMyBids(EntityPlayerMP player) { + // Check permission + if (!CustomNpcsPermissions.hasPermission(player, CustomNpcsPermissions.AUCTION_USE)) { + sendResponse(player, false, "You don't have permission to view auctions"); + return; + } + + AuctionDataPacket.sendMyBids(player); + } + + private void handleQueryClaimable(EntityPlayerMP player) { + // Check permission + if (!CustomNpcsPermissions.hasPermission(player, CustomNpcsPermissions.AUCTION_USE)) { + sendResponse(player, false, "You don't have permission to view auctions"); + return; + } + + AuctionDataPacket.sendClaimable(player); + } + + /** + * Send a response message to the player + */ + private void sendResponse(EntityPlayerMP player, boolean success, String message) { + // Use chat message for now; can be extended to use GUI updates + if (message != null && !message.isEmpty()) { + player.addChatMessage(new ChatComponentText("[Auction] " + message)); + } + } + + private enum Action { + CreateListing, + PlaceBid, + Buyout, + CancelListing, + ClaimItem, + ClaimProceeds, + QueryListings, + QueryMyListings, + QueryMyBids, + QueryClaimable + } +} diff --git a/src/main/java/noppes/npcs/CommonProxy.java b/src/main/java/noppes/npcs/CommonProxy.java index 58f931ab8..a73c179e4 100644 --- a/src/main/java/noppes/npcs/CommonProxy.java +++ b/src/main/java/noppes/npcs/CommonProxy.java @@ -15,6 +15,7 @@ import noppes.npcs.api.IWorld; import noppes.npcs.blocks.tiles.TileNpcContainer; import noppes.npcs.constants.EnumGuiType; import noppes.npcs.containers.ContainerAnvilRepair; +import noppes.npcs.containers.ContainerAuction; import noppes.npcs.containers.ContainerCarpentryBench; import noppes.npcs.containers.ContainerCrate; import noppes.npcs.containers.ContainerCustomGui; @@ -131,6 +132,9 @@ public class CommonProxy implements IGuiHandler { if (gui == EnumGuiType.CompanionInv) return new ContainerNPCCompanion(npc, player); + if (gui == EnumGuiType.PlayerAuction) + return new ContainerAuction(npc, player); + return null; } diff --git a/src/main/java/noppes/npcs/CustomNpcs.java b/src/main/java/noppes/npcs/CustomNpcs.java index 41cd8770e..b29a6cd0b 100644 --- a/src/main/java/noppes/npcs/CustomNpcs.java +++ b/src/main/java/noppes/npcs/CustomNpcs.java @@ -59,6 +59,10 @@ import noppes.npcs.controllers.GlobalDataController; import noppes.npcs.controllers.LinkedItemController; import noppes.npcs.controllers.LinkedNpcController; import noppes.npcs.controllers.MagicController; +import noppes.npcs.controllers.VaultHelper; +import noppes.npcs.controllers.CurrencyController; +import noppes.npcs.controllers.AuctionBlacklist; +import noppes.npcs.controllers.AuctionController; import noppes.npcs.controllers.PlayerDataController; import noppes.npcs.controllers.QuestController; import noppes.npcs.controllers.RecipeController; @@ -310,6 +314,10 @@ public class CustomNpcs { //Loading items in the about to start event was corrupting items with a damage value @EventHandler public void started(FMLServerStartedEvent event) { + new VaultHelper(); + new CurrencyController(); + new AuctionBlacklist(); + new AuctionController(); RecipeController.Instance.load(); new BankController(); DialogController.Instance.load(); diff --git a/src/main/java/noppes/npcs/CustomNpcsPermissions.java b/src/main/java/noppes/npcs/CustomNpcsPermissions.java index c83e92c22..34a5fbf50 100644 --- a/src/main/java/noppes/npcs/CustomNpcsPermissions.java +++ b/src/main/java/noppes/npcs/CustomNpcsPermissions.java @@ -92,6 +92,13 @@ public class CustomNpcsPermissions { public static final Permission SOULSTONE_ALL = new Permission("customnpcs.soulstone.all"); + // Auction System + public static final Permission AUCTION_USE = new Permission("customnpcs.auction.use"); + public static final Permission AUCTION_LIST = new Permission("customnpcs.auction.list"); + public static final Permission AUCTION_BID = new Permission("customnpcs.auction.bid"); + public static final Permission AUCTION_BUYOUT = new Permission("customnpcs.auction.buyout"); + public static final Permission AUCTION_ADMIN = new Permission("customnpcs.auction.admin"); + // Modify / Save Scripts public static final Permission SCRIPT = new Permission("customnpcs.script"); public static final Permission SCRIPT_NPC = new Permission("customnpcs.script.npc"); diff --git a/src/main/java/noppes/npcs/DataAdvanced.java b/src/main/java/noppes/npcs/DataAdvanced.java index 45ecfe4a8..f03714506 100644 --- a/src/main/java/noppes/npcs/DataAdvanced.java +++ b/src/main/java/noppes/npcs/DataAdvanced.java @@ -18,6 +18,7 @@ import noppes.npcs.roles.JobGuard; import noppes.npcs.roles.JobHealer; import noppes.npcs.roles.JobItemGiver; import noppes.npcs.roles.JobSpawner; +import noppes.npcs.roles.RoleAuctioneer; import noppes.npcs.roles.RoleBank; import noppes.npcs.roles.RoleCompanion; import noppes.npcs.roles.RoleFollower; @@ -218,6 +219,8 @@ public class DataAdvanced { npc.roleInterface = new RoleCompanion(npc); else if (role == EnumRoleType.Mount && !(npc.roleInterface instanceof RoleMount)) npc.roleInterface = new RoleMount(npc); + else if (role == EnumRoleType.Auctioneer && !(npc.roleInterface instanceof RoleAuctioneer)) + npc.roleInterface = new RoleAuctioneer(npc); } public void setJob(int i) { diff --git a/src/main/java/noppes/npcs/ServerTickHandler.java b/src/main/java/noppes/npcs/ServerTickHandler.java index 3648f00d7..fe846df19 100644 --- a/src/main/java/noppes/npcs/ServerTickHandler.java +++ b/src/main/java/noppes/npcs/ServerTickHandler.java @@ -10,6 +10,7 @@ import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.world.WorldServer; import noppes.npcs.client.AnalyticsTracking; +import noppes.npcs.controllers.AuctionController; import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.controllers.data.action.ActionManager; @@ -65,6 +66,11 @@ public class ServerTickHandler { ProfileController.Instance.login(player); SyncController.beginLogin(player); SyncController.syncEffects(player); + + // Send pending auction notifications + if (AuctionController.Instance != null) { + AuctionController.Instance.onPlayerLogin(player); + } } @SubscribeEvent diff --git a/src/main/java/noppes/npcs/client/ClientProxy.java b/src/main/java/noppes/npcs/client/ClientProxy.java index 4e64f8351..a31b57a7f 100644 --- a/src/main/java/noppes/npcs/client/ClientProxy.java +++ b/src/main/java/noppes/npcs/client/ClientProxy.java @@ -104,6 +104,7 @@ import noppes.npcs.client.gui.player.GuiCrate; import noppes.npcs.client.gui.player.GuiMailbox; import noppes.npcs.client.gui.player.GuiMailmanWrite; import noppes.npcs.client.gui.player.GuiNPCBankChest; +import noppes.npcs.client.gui.player.GuiAuction; import noppes.npcs.client.gui.player.GuiNPCTrader; import noppes.npcs.client.gui.player.GuiNpcAnvil; import noppes.npcs.client.gui.player.GuiNpcCarpentryBench; @@ -179,6 +180,7 @@ import noppes.npcs.config.ConfigMain; import noppes.npcs.config.StringCache; import noppes.npcs.constants.EnumGuiType; import noppes.npcs.containers.ContainerAnvilRepair; +import noppes.npcs.containers.ContainerAuction; import noppes.npcs.containers.ContainerCarpentryBench; import noppes.npcs.containers.ContainerCrate; import noppes.npcs.containers.ContainerCustomGui; @@ -574,6 +576,9 @@ public class ClientProxy extends CommonProxy { else if (gui == EnumGuiType.MagicBook) return new GuiNpcMagicBook(); + else if (gui == EnumGuiType.PlayerAuction) + return new GuiAuction(npc, (ContainerAuction) container); + else if (gui == EnumGuiType.GlobalRemote) return new GuiNPCGlobalMainMenu(null); diff --git a/src/main/java/noppes/npcs/client/NoppesUtil.java b/src/main/java/noppes/npcs/client/NoppesUtil.java index 620142564..64b26fa5d 100644 --- a/src/main/java/noppes/npcs/client/NoppesUtil.java +++ b/src/main/java/noppes/npcs/client/NoppesUtil.java @@ -182,6 +182,67 @@ public class NoppesUtil { data = new HashMap(); } + // ==================== Auction Data ==================== + + // Static storage for auction data that the GUI can access + private static NBTTagCompound auctionListingData; + private static int auctionDataType; + private static int auctionTotalResults; + private static int auctionCurrentPage; + private static int auctionTotalPages; + private static long auctionPlayerBalance; + + public static void setAuctionData(int dataType, NBTTagCompound compound, + int totalResults, int currentPage, int totalPages, + long playerBalance) { + auctionDataType = dataType; + auctionListingData = compound; + auctionTotalResults = totalResults; + auctionCurrentPage = currentPage; + auctionTotalPages = totalPages; + auctionPlayerBalance = playerBalance; + + // Notify the current GUI if it's an auction GUI + GuiScreen gui = Minecraft.getMinecraft().currentScreen; + if (gui instanceof IAuctionData) { + ((IAuctionData) gui).onAuctionDataReceived(dataType, compound, + totalResults, currentPage, totalPages, playerBalance); + } + } + + public static NBTTagCompound getAuctionListingData() { + return auctionListingData; + } + + public static int getAuctionDataType() { + return auctionDataType; + } + + public static int getAuctionTotalResults() { + return auctionTotalResults; + } + + public static int getAuctionCurrentPage() { + return auctionCurrentPage; + } + + public static int getAuctionTotalPages() { + return auctionTotalPages; + } + + public static long getAuctionPlayerBalance() { + return auctionPlayerBalance; + } + + /** + * Interface for GUIs that receive auction data + */ + public interface IAuctionData { + void onAuctionDataReceived(int dataType, NBTTagCompound data, + int totalResults, int currentPage, int totalPages, + long playerBalance); + } + public static void guiQuestCompletion(EntityPlayer player, NBTTagCompound read) { Quest quest = new Quest(); quest.readNBT(read); diff --git a/src/main/java/noppes/npcs/client/gui/mainmenu/GuiNpcAdvanced.java b/src/main/java/noppes/npcs/client/gui/mainmenu/GuiNpcAdvanced.java index 4cd861448..7ee5e8881 100644 --- a/src/main/java/noppes/npcs/client/gui/mainmenu/GuiNpcAdvanced.java +++ b/src/main/java/noppes/npcs/client/gui/mainmenu/GuiNpcAdvanced.java @@ -26,6 +26,7 @@ import noppes.npcs.client.gui.roles.GuiNpcFollowerJob; import noppes.npcs.client.gui.roles.GuiNpcGuard; import noppes.npcs.client.gui.roles.GuiNpcHealer; import noppes.npcs.client.gui.roles.GuiNpcSpawner; +import noppes.npcs.client.gui.roles.GuiNpcAuctioneer; import noppes.npcs.client.gui.roles.GuiNpcMount; import noppes.npcs.client.gui.roles.GuiNpcTransporter; import noppes.npcs.client.gui.util.GuiNPCInterface2; @@ -49,7 +50,7 @@ public class GuiNpcAdvanced extends GuiNPCInterface2 implements IGuiData { super.initGui(); int y = guiTop + 10; this.addButton(new GuiNpcButton(3, guiLeft + 85 + 160, y, 52, 20, "selectServer.edit")); - this.addButton(new GuiNpcButton(8, guiLeft + 85, y, 155, 20, new String[]{"role.none", "role.trader", "role.follower", "role.bank", "role.transporter", "role.mailman", NoppesStringUtils.translate("role.companion", "(WIP)"), "role.mount"}, npc.advanced.role.ordinal())); + this.addButton(new GuiNpcButton(8, guiLeft + 85, y, 155, 20, new String[]{"role.none", "role.trader", "role.follower", "role.bank", "role.transporter", "role.mailman", NoppesStringUtils.translate("role.companion", "(WIP)"), "role.mount", "role.auctioneer"}, npc.advanced.role.ordinal())); getButton(3).setEnabled(npc.advanced.role != EnumRoleType.None && npc.advanced.role != EnumRoleType.Postman); this.addButton(new GuiNpcButton(4, guiLeft + 85 + 160, y += 22, 52, 20, "selectServer.edit")); @@ -157,6 +158,8 @@ public class GuiNpcAdvanced extends GuiNPCInterface2 implements IGuiData { displayGuiScreen(new GuiNpcCompanion(npc)); else if (npc.advanced.role == EnumRoleType.Mount) displayGuiScreen(new GuiNpcMount(npc)); + else if (npc.advanced.role == EnumRoleType.Auctioneer) + displayGuiScreen(new GuiNpcAuctioneer(npc)); } else if (compound.hasKey("JobData")) { if (npc.jobInterface != null) npc.jobInterface.readFromNBT(compound); diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiAuction.java b/src/main/java/noppes/npcs/client/gui/player/GuiAuction.java new file mode 100644 index 000000000..8dcbcfcbe --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuction.java @@ -0,0 +1,841 @@ +package noppes.npcs.client.gui.player; + +import kamkeel.npcs.network.packets.player.AuctionActionPacket; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.inventory.Slot; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.CustomNpcResourceListener; +import noppes.npcs.client.NoppesUtil; +import noppes.npcs.client.gui.util.*; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.containers.ContainerAuction; +import noppes.npcs.constants.EnumAuctionDuration; +import noppes.npcs.constants.EnumAuctionStatus; +import noppes.npcs.controllers.data.AuctionFilter; +import noppes.npcs.controllers.data.AuctionListing; +import noppes.npcs.entity.EntityNPCInterface; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * Main auction house browse GUI. + * Displays listings with search, sort, and pagination. + */ +public class GuiAuction extends GuiContainerNPCInterface implements IGuiData, + ICustomScrollListener, NoppesUtil.IAuctionData { + + private static final ResourceLocation BG_TEXTURE = new ResourceLocation("customnpcs", "textures/gui/standardbg.png"); + private static final int LEFT_PANEL_X = 8; + private static final int LEFT_PANEL_WIDTH = 190; + private static final int RIGHT_PANEL_X = 210; + private static final int ACTION_BUTTON_WIDTH = 98; + private static final int LISTING_SCROLL_HEIGHT = 100; + private static final int LISTING_SCROLL_WIDTH = 190; + private static final int PAGE_BUTTON_WIDTH = 60; + private static final int SEARCH_FIELD_WIDTH = 140; + private static final int SEARCH_BUTTON_WIDTH = 46; + private static final int HIDDEN_SLOT_POSITION = -1000; + private static final int INVENTORY_START_X = 8; + private static final int INVENTORY_START_Y = 166; + private static final int HOTBAR_Y_OFFSET = 58; + + // GUI Components + private GuiNpcTextField searchField; + private GuiNpcTextField startingPriceField; + private GuiNpcTextField buyoutPriceField; + private GuiCustomScroll listingScroll; + + // Current state + private AuctionFilter currentFilter = new AuctionFilter(); + private List listings = new ArrayList<>(); + private int totalResults = 0; + private int currentPage = 0; + private int totalPages = 0; + private long playerBalance = 0; + + // Tab state (0=Browse, 1=My Listings, 2=My Bids, 3=Claims, 4=Create) + private int currentTab = 0; + private int selectedDuration = 1; + + // Selected listing for details + private int selectedListingIndex = -1; + + // Countdown update timer + private long lastCountdownUpdate = 0; + + private enum ActionMode { + BID, + CANCEL, + CLAIM + } + + public GuiAuction(EntityNPCInterface npc, ContainerAuction container) { + super(npc, container); + this.title = ""; + this.xSize = 319; + this.ySize = 238; + this.closeOnEsc = true; + this.drawDefaultBackground = true; + + // Request initial data + AuctionActionPacket.QueryListings(currentFilter); + } + + @Override + public void initGui() { + super.initGui(); + + int leftX = guiLeft + LEFT_PANEL_X; + int rightX = guiLeft + RIGHT_PANEL_X; + int actionY = guiTop + 44; + boolean isCreateTab = currentTab == 4; + boolean isBrowseTab = currentTab == 0; + + updateListingSlotPosition(isCreateTab); + + // Tab buttons at top + GuiMenuTopButton browseButton = new GuiMenuTopButton(0, guiLeft + 4, guiTop - 17, StatCollector.translateToLocal("auction.browse")); + addTopButton(browseButton); + GuiMenuTopButton myListingsButton = new GuiMenuTopButton(1, browseButton, StatCollector.translateToLocal("auction.myListings")); + addTopButton(myListingsButton); + GuiMenuTopButton myBidsButton = new GuiMenuTopButton(2, myListingsButton, StatCollector.translateToLocal("auction.myBids")); + addTopButton(myBidsButton); + GuiMenuTopButton claimsButton = new GuiMenuTopButton(3, myBidsButton, StatCollector.translateToLocal("auction.claims")); + addTopButton(claimsButton); + GuiMenuTopButton sellButton = new GuiMenuTopButton(4, claimsButton, StatCollector.translateToLocal("auction.sell")); + addTopButton(sellButton); + getTopButton(currentTab).setEnabled(false); + + if (isCreateTab) { + addCreateControls(leftX, rightX); + } else { + if (isBrowseTab) { + // Search field + searchField = new GuiNpcTextField(10, this, leftX, guiTop + 6, SEARCH_FIELD_WIDTH, 14, currentFilter.searchText); + searchField.setMaxStringLength(50); + addTextField(searchField); + + // Search button + addButton(new GuiNpcButton(11, leftX + SEARCH_FIELD_WIDTH + 4, guiTop + 5, SEARCH_BUTTON_WIDTH, 16, + StatCollector.translateToLocal("auction.search"))); + + // Sort button + addButton(new GuiNpcButton(30, leftX, guiTop + 24, LEFT_PANEL_WIDTH, 16, currentFilter.sortOrder.getDisplayName())); + } + + // Listing scroll area + listingScroll = new GuiCustomScroll(this, 0); + listingScroll.guiLeft = leftX; + listingScroll.guiTop = guiTop + 44; + listingScroll.setSize(LISTING_SCROLL_WIDTH, LISTING_SCROLL_HEIGHT); + addScroll(listingScroll); + updateListingDisplay(); + + if (isBrowseTab) { + // Pagination buttons + addButton(new GuiNpcButton(40, leftX, guiTop + 148, PAGE_BUTTON_WIDTH, 16, + StatCollector.translateToLocal("auction.prevPage"))); + addLabel(new GuiNpcLabel(41, getPageLabel(), leftX + 70, guiTop + 152, CustomNpcResourceListener.DefaultTextColor)); + addButton(new GuiNpcButton(42, leftX + LEFT_PANEL_WIDTH - PAGE_BUTTON_WIDTH, guiTop + 148, PAGE_BUTTON_WIDTH, 16, + StatCollector.translateToLocal("auction.nextPage"))); + } + + // Action buttons (right side) + addActionButtons(rightX, actionY); + + // Balance display + addLabel(new GuiNpcLabel(60, String.format(StatCollector.translateToLocal("auction.balance"), formatCurrency(playerBalance)), + rightX, guiTop + 170, 0x00AA00)); + } + + updateButtonStates(); + } + + @Override + public void updateScreen() { + super.updateScreen(); + + // Update countdowns every second + long now = System.currentTimeMillis(); + if (now - lastCountdownUpdate >= 1000) { + lastCountdownUpdate = now; + updateListingDisplay(); + } + + if (currentTab == 4 && inventorySlots instanceof ContainerAuction) { + ItemStack item = ((ContainerAuction) inventorySlots).getListingItem(); + GuiNpcLabel itemLabel = getLabel(102); + GuiNpcButton createButton = getButton(71); + if (item != null) { + if (itemLabel != null) { + itemLabel.label = StatCollector.translateToLocal("auction.item") + " " + item.getDisplayName(); + itemLabel.color = 0x008800; + } + if (createButton != null) { + createButton.setEnabled(true); + } + } else { + if (itemLabel != null) { + itemLabel.label = StatCollector.translateToLocal("auction.noItemSelected"); + itemLabel.color = 0x888888; + } + if (createButton != null) { + createButton.setEnabled(false); + } + } + } + } + + @Override + public void actionPerformed(GuiButton button) { + super.actionPerformed(button); + int id = button.id; + + // Tab buttons + if (id >= 0 && id <= 4) { + switchTab(id); + } + // Search button + else if (id == 11) { + if (currentTab == 0) { + performSearch(); + } + } + // Sort button + else if (id == 30) { + if (currentTab == 0) { + cycleSortOrder(); + } + } + // Pagination + else if (id == 40) { + if (currentTab == 0) { + previousPage(); + } + } else if (id == 42) { + if (currentTab == 0) { + nextPage(); + } + } + // Actions + else if (id == 50) { + viewDetails(); + } else if (id == 51) { + ActionMode mode = getActionMode(); + if (mode == ActionMode.BID) { + placeBid(); + } else if (mode == ActionMode.CANCEL) { + cancelListing(); + } else if (mode == ActionMode.CLAIM) { + claimListing(); + } + } else if (id == 52) { + if (getActionMode() == ActionMode.BID) { + buyout(); + } + } else if (id == 53) { + refresh(); + } else if (id == 70) { + selectedDuration = (selectedDuration + 1) % EnumAuctionDuration.values().length; + initGui(); + } else if (id == 71) { + createListing(); + } else if (id == 72) { + switchTab(0); + } + } + + private void switchTab(int tab) { + currentTab = tab; + currentPage = 0; + selectedListingIndex = -1; + + switch (tab) { + case 0: // Browse + AuctionActionPacket.QueryListings(currentFilter); + break; + case 1: // My Listings + AuctionActionPacket.QueryMyListings(); + break; + case 2: // My Bids + AuctionActionPacket.QueryMyBids(); + break; + case 3: // Claims + AuctionActionPacket.QueryClaimable(); + break; + case 4: + break; + } + + initGui(); + } + + private void performSearch() { + currentFilter.searchText = searchField.getText(); + currentFilter.page = 0; + currentPage = 0; + AuctionActionPacket.QueryListings(currentFilter); + } + + private void cycleSortOrder() { + currentFilter.sortOrder = currentFilter.sortOrder.next(); + currentFilter.page = 0; + currentPage = 0; + AuctionActionPacket.QueryListings(currentFilter); + initGui(); + } + + private void previousPage() { + if (currentPage > 0) { + currentPage--; + currentFilter.page = currentPage; + AuctionActionPacket.QueryListings(currentFilter); + } + } + + private void nextPage() { + if (currentPage < totalPages - 1) { + currentPage++; + currentFilter.page = currentPage; + AuctionActionPacket.QueryListings(currentFilter); + } + } + + private void viewDetails() { + if (selectedListingIndex >= 0 && selectedListingIndex < listings.size()) { + AuctionListing listing = listings.get(selectedListingIndex); + if (listing.item == null) { + return; + } + setSubGui(new SubGuiAuctionDetails(this, listing)); + } + } + + private void placeBid() { + if (selectedListingIndex >= 0 && selectedListingIndex < listings.size()) { + AuctionListing listing = listings.get(selectedListingIndex); + if (listing.item == null) { + return; + } + setSubGui(new SubGuiAuctionBid(this, listing, playerBalance)); + } + } + + private void buyout() { + if (selectedListingIndex >= 0 && selectedListingIndex < listings.size()) { + AuctionListing listing = listings.get(selectedListingIndex); + if (listing.buyoutPrice > 0 && playerBalance >= listing.buyoutPrice) { + AuctionActionPacket.Buyout(listing.id); + refresh(); + } + } + } + + private void refresh() { + switch (currentTab) { + case 0: + AuctionActionPacket.QueryListings(currentFilter); + break; + case 1: + AuctionActionPacket.QueryMyListings(); + break; + case 2: + AuctionActionPacket.QueryMyBids(); + break; + case 3: + AuctionActionPacket.QueryClaimable(); + break; + } + } + + private void updateListingDisplay() { + if (listingScroll == null) return; + + List displayList = new ArrayList<>(); + for (AuctionListing listing : listings) { + String line = formatListingLine(listing); + displayList.add(line); + } + listingScroll.setList(displayList, true, false); + + if (selectedListingIndex >= 0 && selectedListingIndex < displayList.size()) { + listingScroll.selected = selectedListingIndex; + } else { + selectedListingIndex = -1; + listingScroll.selected = -1; + } + } + + private String formatListingLine(AuctionListing listing) { + String itemName = listing.item == null + ? "Unknown" + : listing.item.getDisplayName(); + if (itemName.length() > 15) { + itemName = itemName.substring(0, 12) + "..."; + } + + long price = listing.currentBid > 0 ? listing.currentBid : listing.startingPrice; + String priceStr = formatCurrency(price); + + String timeStr = formatTimeRemaining(listing.getTimeRemaining()); + + return String.format("%s - %s (%s)", itemName, priceStr, timeStr); + } + + private String formatTimeRemaining(long millis) { + if (millis <= 0) return StatCollector.translateToLocal("auction.ended"); + + long seconds = millis / 1000; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + + if (days > 0) { + return days + "d " + (hours % 24) + "h"; + } else if (hours > 0) { + return hours + "h " + (minutes % 60) + "m"; + } else if (minutes > 0) { + return minutes + "m " + (seconds % 60) + "s"; + } else { + return seconds + "s"; + } + } + + private String formatCurrency(long amount) { + if (amount >= 1000000) { + return String.format("%.1fM", amount / 1000000.0); + } else if (amount >= 1000) { + return String.format("%.1fK", amount / 1000.0); + } + return String.valueOf(amount); + } + + private String getPageLabel() { + if (totalPages == 0) { + return StatCollector.translateToLocal("auction.noResults"); + } + return String.format(StatCollector.translateToLocal("auction.page"), currentPage + 1, totalPages); + } + + private void updateButtonStates() { + ActionMode mode = getActionMode(); + AuctionListing listing = getSelectedListing(); + boolean hasSelection = listing != null; + + // Pagination buttons + if (getButton(40) != null) getButton(40).setEnabled(currentPage > 0); + if (getButton(42) != null) getButton(42).setEnabled(currentPage < totalPages - 1); + + // Action buttons based on selection + if (getButton(50) != null) getButton(50).setEnabled(hasSelection); + if (getButton(51) != null) { + if (!hasSelection) { + getButton(51).setEnabled(false); + } else if (mode == ActionMode.BID) { + getButton(51).setEnabled(canPlaceBid(listing)); + } else if (mode == ActionMode.CANCEL) { + getButton(51).setEnabled(canCancelListing(listing)); + } else { + getButton(51).setEnabled(getClaimAction(listing) != ClaimAction.NONE); + } + } + + if (getButton(52) != null) { + if (!hasSelection || mode != ActionMode.BID) { + getButton(52).setEnabled(false); + } else { + getButton(52).setEnabled(canBuyout(listing)); + } + } + } + + private void updateListingSlotPosition(boolean showInventory) { + if (!(inventorySlots instanceof ContainerAuction)) { + return; + } + + ContainerAuction container = (ContainerAuction) inventorySlots; + if (showInventory) { + container.listingSlot.xDisplayPosition = RIGHT_PANEL_X + 41; + container.listingSlot.yDisplayPosition = 64; + + for (int row = 0; row < 3; row++) { + for (int col = 0; col < 9; col++) { + int slotIndex = 1 + col + row * 9; + Slot slot = (Slot) container.inventorySlots.get(slotIndex); + slot.xDisplayPosition = INVENTORY_START_X + col * 18; + slot.yDisplayPosition = INVENTORY_START_Y + row * 18; + } + } + + for (int col = 0; col < 9; col++) { + int slotIndex = 28 + col; + Slot slot = (Slot) container.inventorySlots.get(slotIndex); + slot.xDisplayPosition = INVENTORY_START_X + col * 18; + slot.yDisplayPosition = INVENTORY_START_Y + HOTBAR_Y_OFFSET; + } + } else { + container.listingSlot.xDisplayPosition = HIDDEN_SLOT_POSITION; + container.listingSlot.yDisplayPosition = HIDDEN_SLOT_POSITION; + + for (int slotIndex = 1; slotIndex < container.inventorySlots.size(); slotIndex++) { + Slot slot = (Slot) container.inventorySlots.get(slotIndex); + slot.xDisplayPosition = HIDDEN_SLOT_POSITION; + slot.yDisplayPosition = HIDDEN_SLOT_POSITION; + } + } + } + + private void addCreateControls(int leftX, int rightX) { + addLabel(new GuiNpcLabel(100, StatCollector.translateToLocal("auction.createListing"), leftX, guiTop + 8, 0x404040)); + addLabel(new GuiNpcLabel(101, StatCollector.translateToLocal("auction.placeItemBelow"), rightX, guiTop + 32, 0x404040)); + + ItemStack item = ((ContainerAuction) inventorySlots).getListingItem(); + if (item != null) { + addLabel(new GuiNpcLabel(102, StatCollector.translateToLocal("auction.item") + " " + item.getDisplayName(), + rightX, guiTop + 86, 0x008800)); + } else { + addLabel(new GuiNpcLabel(102, StatCollector.translateToLocal("auction.noItemSelected"), rightX, guiTop + 86, 0x888888)); + } + + addLabel(new GuiNpcLabel(110, StatCollector.translateToLocal("auction.startingPrice"), leftX, guiTop + 36, 0x404040)); + startingPriceField = new GuiNpcTextField(111, this, leftX + 120, guiTop + 34, 90, 14, "100"); + startingPriceField.setIntegersOnly(); + startingPriceField.setMinMaxDefault(1, 999999999, 100); + addTextField(startingPriceField); + + addLabel(new GuiNpcLabel(120, StatCollector.translateToLocal("auction.buyoutPrice"), leftX, guiTop + 58, 0x404040)); + buyoutPriceField = new GuiNpcTextField(121, this, leftX + 120, guiTop + 56, 90, 14, "0"); + buyoutPriceField.setIntegersOnly(); + buyoutPriceField.setMinMaxDefault(0, 999999999, 0); + addTextField(buyoutPriceField); + addLabel(new GuiNpcLabel(122, StatCollector.translateToLocal("auction.noBuyoutHint"), leftX + 214, guiTop + 58, 0x888888)); + + addLabel(new GuiNpcLabel(130, StatCollector.translateToLocal("auction.duration"), leftX, guiTop + 80, 0x404040)); + addButton(new GuiNpcButton(70, leftX + 120, guiTop + 76, 110, 20, getDurationDisplay())); + + long fee = getListingFee(); + addLabel(new GuiNpcLabel(140, StatCollector.translateToLocal("auction.listingFee") + " " + fee + " " + ConfigMarket.CurrencyName, + leftX, guiTop + 104, fee > 0 ? 0xAA0000 : 0x008800)); + + addButton(new GuiNpcButton(71, leftX, guiTop + 126, 90, 20, StatCollector.translateToLocal("auction.create"))); + addButton(new GuiNpcButton(72, leftX + 100, guiTop + 126, 90, 20, StatCollector.translateToLocal("gui.cancel"))); + + if (getButton(71) != null) { + getButton(71).setEnabled(item != null); + } + } + + private String getDurationDisplay() { + EnumAuctionDuration duration = EnumAuctionDuration.values()[selectedDuration]; + return duration.getDisplayName(); + } + + private long getListingFee() { + EnumAuctionDuration duration = EnumAuctionDuration.values()[selectedDuration]; + return duration.getListingFee(); + } + + private void createListing() { + ContainerAuction container = (ContainerAuction) inventorySlots; + ItemStack item = container.getListingItem(); + if (item == null) { + return; + } + + long startingPrice = parsePrice(startingPriceField, 1); + long buyoutPrice = parsePrice(buyoutPriceField, 0); + + if (startingPrice < 1) { + startingPrice = 1; + } + + if (buyoutPrice > 0 && buyoutPrice < startingPrice) { + return; + } + + EnumAuctionDuration duration = EnumAuctionDuration.values()[selectedDuration]; + AuctionActionPacket.CreateListing(item, startingPrice, buyoutPrice, duration); + container.clearListingSlot(); + switchTab(0); + } + + private void cancelListing() { + AuctionListing listing = getSelectedListing(); + if (!canCancelListing(listing)) { + return; + } + + AuctionActionPacket.CancelListing(listing.id); + refresh(); + } + + private void claimListing() { + AuctionListing listing = getSelectedListing(); + if (listing == null) { + return; + } + + ClaimAction action = getClaimAction(listing); + if (action == ClaimAction.ITEM) { + AuctionActionPacket.ClaimItem(listing.id); + } else if (action == ClaimAction.PROCEEDS) { + AuctionActionPacket.ClaimProceeds(listing.id); + } else { + return; + } + + refresh(); + } + + private ActionMode getActionMode() { + if (currentTab == 1) { + return ActionMode.CANCEL; + } + if (currentTab == 3) { + return ActionMode.CLAIM; + } + return ActionMode.BID; + } + + private String getPrimaryActionLabel(ActionMode mode) { + if (mode == ActionMode.CANCEL) { + return StatCollector.translateToLocal("auction.cancel"); + } + if (mode == ActionMode.CLAIM) { + return StatCollector.translateToLocal("auction.claim"); + } + return StatCollector.translateToLocal("auction.placeBid"); + } + + private void addActionButtons(int rightX, int actionY) { + ActionMode mode = getActionMode(); + addButton(new GuiNpcButton(50, rightX, actionY, ACTION_BUTTON_WIDTH, 20, + StatCollector.translateToLocal("auction.viewDetails"))); + addButton(new GuiNpcButton(51, rightX, actionY + 24, ACTION_BUTTON_WIDTH, 20, + getPrimaryActionLabel(mode))); + if (mode == ActionMode.BID) { + addButton(new GuiNpcButton(52, rightX, actionY + 48, ACTION_BUTTON_WIDTH, 20, + StatCollector.translateToLocal("auction.buyout"))); + addButton(new GuiNpcButton(53, rightX, actionY + 72, ACTION_BUTTON_WIDTH, 20, + StatCollector.translateToLocal("auction.refresh"))); + } else { + addButton(new GuiNpcButton(53, rightX, actionY + 48, ACTION_BUTTON_WIDTH, 20, + StatCollector.translateToLocal("auction.refresh"))); + } + } + + private AuctionListing getSelectedListing() { + if (selectedListingIndex < 0 || selectedListingIndex >= listings.size()) { + return null; + } + AuctionListing listing = listings.get(selectedListingIndex); + if (listing == null || listing.item == null) { + return null; + } + return listing; + } + + private boolean canPlaceBid(AuctionListing listing) { + if (listing == null || !listing.isActive()) { + return false; + } + if (isPlayerSeller(listing)) { + return false; + } + return playerBalance >= listing.getMinimumBid(); + } + + private boolean canBuyout(AuctionListing listing) { + if (listing == null || !listing.isActive()) { + return false; + } + if (listing.buyoutPrice <= 0) { + return false; + } + if (isPlayerSeller(listing)) { + return false; + } + return playerBalance >= listing.buyoutPrice; + } + + private boolean canCancelListing(AuctionListing listing) { + if (listing == null || listing.item == null) { + return false; + } + return listing.status == EnumAuctionStatus.ACTIVE && !listing.hasBids(); + } + + private boolean isPlayerSeller(AuctionListing listing) { + if (mc == null || mc.thePlayer == null || listing == null || listing.sellerUUID == null) { + return false; + } + UUID playerId = mc.thePlayer.getUniqueID(); + return listing.sellerUUID.equals(playerId); + } + + private enum ClaimAction { + ITEM, + PROCEEDS, + NONE + } + + private ClaimAction getClaimAction(AuctionListing listing) { + if (listing == null || mc == null || mc.thePlayer == null) { + return ClaimAction.NONE; + } + + UUID playerId = mc.thePlayer.getUniqueID(); + if (listing.sellerUUID != null && listing.sellerUUID.equals(playerId) && !listing.sellerClaimed) { + if (listing.status == EnumAuctionStatus.SOLD) { + return ClaimAction.PROCEEDS; + } + if (listing.status == EnumAuctionStatus.CANCELLED || listing.status == EnumAuctionStatus.EXPIRED) { + return ClaimAction.ITEM; + } + } + + if (listing.highBidderUUID != null && listing.highBidderUUID.equals(playerId) + && listing.status == EnumAuctionStatus.SOLD && !listing.buyerClaimed) { + return ClaimAction.ITEM; + } + + return ClaimAction.NONE; + } + + private long parsePrice(GuiNpcTextField field, long defaultValue) { + if (field == null) { + return defaultValue; + } + try { + return Long.parseLong(field.getText()); + } catch (NumberFormatException e) { + return defaultValue; + } + } + + @Override + protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { + drawDefaultBackground(); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + // Draw background + mc.renderEngine.bindTexture(BG_TEXTURE); + drawTexturedModalRect(guiLeft, guiTop, 0, 0, 252, ySize); + drawTexturedModalRect(guiLeft + 252, guiTop, 188, 0, xSize - 252, ySize); + + // Draw selected item preview + if (selectedListingIndex >= 0 && selectedListingIndex < listings.size()) { + AuctionListing listing = listings.get(selectedListingIndex); + drawItemPreview(listing, guiLeft + RIGHT_PANEL_X + 41, guiTop + 192); + } + + super.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY); + } + + private void drawItemPreview(AuctionListing listing, int x, int y) { + if (listing == null || listing.item == null) return; + + RenderHelper.enableGUIStandardItemLighting(); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glEnable(GL11.GL_COLOR_MATERIAL); + GL11.glEnable(GL11.GL_LIGHTING); + + itemRender.renderItemAndEffectIntoGUI(fontRendererObj, mc.renderEngine, listing.item, x, y); + itemRender.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, listing.item, x, y); + + RenderHelper.disableStandardItemLighting(); + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + // Title + String titleText = getTabTitle(); + fontRendererObj.drawString(titleText, (xSize - fontRendererObj.getStringWidth(titleText)) / 2, -8, + CustomNpcResourceListener.DefaultTextColor); + + if (currentTab != 4) { + String listingsLabel = String.format(StatCollector.translateToLocal("auction.listings"), totalResults); + fontRendererObj.drawString(listingsLabel, LEFT_PANEL_X, 36, 0x666666); + } + } + + private String getTabTitle() { + switch (currentTab) { + case 0: return StatCollector.translateToLocal("auction.browseTitle"); + case 1: return StatCollector.translateToLocal("auction.myListingsTitle"); + case 2: return StatCollector.translateToLocal("auction.myBidsTitle"); + case 3: return StatCollector.translateToLocal("auction.claimsTitle"); + case 4: return StatCollector.translateToLocal("auction.sellTitle"); + default: return StatCollector.translateToLocal("auction.title"); + } + } + + // ICustomScrollListener + @Override + public void customScrollClicked(int mouseX, int mouseY, int mouseButton, GuiCustomScroll scroll) { + int index = scroll.selected; + selectedListingIndex = index; + updateButtonStates(); + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { + if (selectedListingIndex >= 0 && selectedListingIndex < listings.size()) { + viewDetails(); + } + } + + // IGuiData + @Override + public void setGuiData(NBTTagCompound compound) { + // This can be used for initial setup data + } + + // IAuctionData + @Override + public void onAuctionDataReceived(int dataType, NBTTagCompound data, + int totalResults, int currentPage, int totalPages, + long playerBalance) { + this.totalResults = totalResults; + this.currentPage = currentPage; + this.totalPages = totalPages; + this.playerBalance = playerBalance; + + // Parse listings from NBT + listings.clear(); + NBTTagList listingList = data.getTagList("Listings", 10); + for (int i = 0; i < listingList.tagCount(); i++) { + NBTTagCompound listingNBT = listingList.getCompoundTagAt(i); + AuctionListing listing = new AuctionListing(); + listing.readFromNBT(listingNBT); + listings.add(listing); + } + + selectedListingIndex = -1; + updateListingDisplay(); + updateButtonStates(); + + // Update labels + if (getLabel(41) != null) { + getLabel(41).label = getPageLabel(); + } + if (getLabel(60) != null) { + getLabel(60).label = String.format(StatCollector.translateToLocal("auction.balance"), formatCurrency(playerBalance)); + } + } + + @Override + public void save() { + // Nothing to save + } +} diff --git a/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBid.java b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBid.java new file mode 100644 index 000000000..99f1e00f1 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBid.java @@ -0,0 +1,221 @@ +package noppes.npcs.client.gui.player; + +import kamkeel.npcs.network.packets.player.AuctionActionPacket; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.controllers.data.AuctionListing; + +/** + * Sub GUI for placing a bid on an auction. + */ +public class SubGuiAuctionBid extends SubGuiInterface { + private AuctionListing listing; + private long playerBalance; + private GuiNpcTextField bidField; + private long lastUpdate = 0; + + public SubGuiAuctionBid(GuiAuction parent, AuctionListing listing, long playerBalance) { + this.listing = listing; + this.playerBalance = playerBalance; + setBackground("menubg.png"); + xSize = 240; + ySize = 165; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 10; + int labelColor = 0x404040; + + if (listing.item == null) { + addLabel(new GuiNpcLabel(0, StatCollector.translateToLocal("auction.noItemSelected"), guiLeft + 60, y, 0xAA0000)); + addButton(new GuiNpcButton(31, guiLeft + 80, guiTop + 125, 80, 20, StatCollector.translateToLocal("gui.cancel"))); + return; + } + + // Title + addLabel(new GuiNpcLabel(0, StatCollector.translateToLocal("auction.placeBid"), guiLeft + 90, y, labelColor)); + y += 18; + + // Item name + addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("auction.item") + " " + listing.item.getDisplayName(), guiLeft + 15, y, 0x000000)); + y += 14; + + // Current price + long currentPrice = listing.currentBid > 0 ? listing.currentBid : listing.startingPrice; + addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("auction.currentPrice"), guiLeft + 15, y, labelColor)); + addLabel(new GuiNpcLabel(3, formatCurrency(currentPrice), guiLeft + 120, y, 0x008800)); + y += 14; + + // Minimum bid + long minBid = listing.getMinimumBid(); + addLabel(new GuiNpcLabel(4, StatCollector.translateToLocal("auction.minimumBid"), guiLeft + 15, y, labelColor)); + addLabel(new GuiNpcLabel(5, formatCurrency(minBid), guiLeft + 120, y, 0x0066AA)); + y += 14; + + // Your balance + addLabel(new GuiNpcLabel(6, StatCollector.translateToLocal("auction.yourBalance"), guiLeft + 15, y, labelColor)); + addLabel(new GuiNpcLabel(7, formatCurrency(playerBalance), guiLeft + 120, y, + playerBalance >= minBid ? 0x008800 : 0xAA0000)); + y += 14; + + // Time remaining + addLabel(new GuiNpcLabel(8, StatCollector.translateToLocal("auction.timeLeft"), guiLeft + 15, y, labelColor)); + addLabel(new GuiNpcLabel(9, formatTimeRemaining(listing.getTimeRemaining()), guiLeft + 120, y, + getTimeColor(listing.getTimeRemaining()))); + y += 18; + + // Bid input + addLabel(new GuiNpcLabel(10, StatCollector.translateToLocal("auction.yourBid"), guiLeft + 15, y + 3, labelColor)); + bidField = new GuiNpcTextField(11, this, guiLeft + 100, y, 110, 16, String.valueOf(minBid)); + bidField.setIntegersOnly(); + int minBidInt = (int) Math.min(Integer.MAX_VALUE, Math.max(1L, minBid)); + bidField.setMinMaxDefault(minBidInt, Integer.MAX_VALUE, minBidInt); + addTextField(bidField); + y += 24; + + // Quick bid buttons + addButton(new GuiNpcButton(20, guiLeft + 15, y, 60, 16, StatCollector.translateToLocal("auction.minBid"))); + addButton(new GuiNpcButton(21, guiLeft + 79, y, 60, 16, StatCollector.translateToLocal("auction.bidPlus10"))); + addButton(new GuiNpcButton(22, guiLeft + 143, y, 60, 16, StatCollector.translateToLocal("auction.bidPlus25"))); + y += 22; + + // Place bid button + GuiNpcButton bidButton = new GuiNpcButton(30, guiLeft + 35, y, 80, 20, StatCollector.translateToLocal("auction.placeBid")); + bidButton.setEnabled(playerBalance >= minBid && listing.isActive()); + addButton(bidButton); + + // Cancel button + addButton(new GuiNpcButton(31, guiLeft + 125, y, 80, 20, StatCollector.translateToLocal("gui.cancel"))); + + // Error message area + if (playerBalance < minBid) { + addLabel(new GuiNpcLabel(40, StatCollector.translateToLocal("auction.insufficientFunds"), guiLeft + 70, guiTop + ySize - 15, 0xAA0000)); + } else if (!listing.isActive()) { + addLabel(new GuiNpcLabel(40, StatCollector.translateToLocal("auction.auctionEnded"), guiLeft + 70, guiTop + ySize - 15, 0xAA0000)); + } + } + + private String formatCurrency(long amount) { + return String.format("%,d %s", amount, ConfigMarket.CurrencyName); + } + + private String formatTimeRemaining(long millis) { + if (millis <= 0) return StatCollector.translateToLocal("auction.ended"); + + long seconds = millis / 1000; + long minutes = seconds / 60; + long hours = minutes / 60; + + if (hours > 0) { + return String.format("%dh %dm", hours, minutes % 60); + } else if (minutes > 0) { + return String.format("%dm %ds", minutes, seconds % 60); + } else { + return String.format("%ds", seconds); + } + } + + private int getTimeColor(long millis) { + if (millis <= 0) return 0xAA0000; + if (millis < 5 * 60 * 1000) return 0xFF0000; + if (millis < 30 * 60 * 1000) return 0xFF6600; + return 0x008800; + } + + @Override + public void updateScreen() { + super.updateScreen(); + + // Update time remaining every second + long now = System.currentTimeMillis(); + if (now - lastUpdate >= 1000) { + lastUpdate = now; + + GuiNpcLabel timeLabel = getLabel(9); + if (timeLabel != null) { + long remaining = listing.getTimeRemaining(); + timeLabel.label = formatTimeRemaining(remaining); + timeLabel.color = getTimeColor(remaining); + } + + // Disable bid button if auction ended + GuiNpcButton bidButton = getButton(30); + if (bidButton != null && !listing.isActive()) { + bidButton.setEnabled(false); + } + } + } + + @Override + public void actionPerformed(GuiButton button) { + int id = button.id; + + long minBid = listing.getMinimumBid(); + + if (id == 20) { + // Min bid + bidField.setText(String.valueOf(minBid)); + } else if (id == 21) { + // +10% + long newBid = (long) (minBid * 1.10); + if (newBid <= playerBalance) { + bidField.setText(String.valueOf(newBid)); + } + } else if (id == 22) { + // +25% + long newBid = (long) (minBid * 1.25); + if (newBid <= playerBalance) { + bidField.setText(String.valueOf(newBid)); + } + } else if (id == 30) { + // Place bid + placeBid(); + } else if (id == 31) { + // Cancel + close(); + } + } + + private void placeBid() { + long bidAmount = parseBid(bidField); + long minBid = listing.getMinimumBid(); + + if (bidAmount < minBid) { + return; + } + + if (bidAmount > playerBalance) { + return; + } + + if (!listing.isActive()) { + return; + } + + // Send bid to server + AuctionActionPacket.PlaceBid(listing.id, bidAmount); + close(); + } + + private long parseBid(GuiNpcTextField field) { + try { + return Long.parseLong(field.getText()); + } catch (NumberFormatException e) { + return 0L; + } + } + + @Override + public void save() { + // Nothing to save + } +} diff --git a/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionCreate.java b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionCreate.java new file mode 100644 index 000000000..6d7f0a756 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionCreate.java @@ -0,0 +1,178 @@ +package noppes.npcs.client.gui.player; + +import kamkeel.npcs.network.packets.player.AuctionActionPacket; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.item.ItemStack; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.constants.EnumAuctionDuration; +import noppes.npcs.containers.ContainerAuction; + +/** + * Sub GUI for creating a new auction listing. + */ +public class SubGuiAuctionCreate extends SubGuiInterface { + private ContainerAuction container; + + private GuiNpcTextField startingPriceField; + private GuiNpcTextField buyoutPriceField; + private int selectedDuration = 1; // Default to MEDIUM + + public SubGuiAuctionCreate(GuiAuction parent, ContainerAuction container) { + this.container = container; + setBackground("menubg.png"); + xSize = 260; + ySize = 190; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + // Title + addLabel(new GuiNpcLabel(0, StatCollector.translateToLocal("auction.createListing"), guiLeft + 80, guiTop + 8, 0x404040)); + + // Item slot instructions + addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("auction.placeItemBelow"), guiLeft + 20, guiTop + 28, 0x404040)); + + // Item info (shows when item is in slot) + ItemStack item = container.getListingItem(); + if (item != null) { + addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("auction.item") + " " + item.getDisplayName(), guiLeft + 20, guiTop + 50, 0x008800)); + } else { + addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("auction.noItemSelected"), guiLeft + 20, guiTop + 50, 0x888888)); + } + + // Starting price + addLabel(new GuiNpcLabel(10, StatCollector.translateToLocal("auction.startingPrice"), guiLeft + 20, guiTop + 74, 0x404040)); + startingPriceField = new GuiNpcTextField(11, this, guiLeft + 120, guiTop + 72, 90, 14, "100"); + startingPriceField.setIntegersOnly(); + startingPriceField.setMinMaxDefault(1, 999999999, 100); + addTextField(startingPriceField); + + // Buyout price (optional) + addLabel(new GuiNpcLabel(20, StatCollector.translateToLocal("auction.buyoutPrice"), guiLeft + 20, guiTop + 96, 0x404040)); + buyoutPriceField = new GuiNpcTextField(21, this, guiLeft + 120, guiTop + 94, 90, 14, "0"); + buyoutPriceField.setIntegersOnly(); + buyoutPriceField.setMinMaxDefault(0, 999999999, 0); + addTextField(buyoutPriceField); + addLabel(new GuiNpcLabel(22, StatCollector.translateToLocal("auction.noBuyoutHint"), guiLeft + 215, guiTop + 96, 0x888888)); + + // Duration selection + addLabel(new GuiNpcLabel(30, StatCollector.translateToLocal("auction.duration"), guiLeft + 20, guiTop + 118, 0x404040)); + addButton(new GuiNpcButton(31, guiLeft + 120, guiTop + 114, 110, 20, getDurationDisplay())); + + // Fee display + long fee = getListingFee(); + addLabel(new GuiNpcLabel(40, StatCollector.translateToLocal("auction.listingFee") + " " + fee + " " + ConfigMarket.CurrencyName, + guiLeft + 20, guiTop + 142, fee > 0 ? 0xAA0000 : 0x008800)); + + // Create button + addButton(new GuiNpcButton(50, guiLeft + 30, guiTop + 162, 90, 20, StatCollector.translateToLocal("auction.create"))); + getButton(50).setEnabled(item != null); + + // Cancel button + addButton(new GuiNpcButton(51, guiLeft + 140, guiTop + 162, 90, 20, StatCollector.translateToLocal("gui.cancel"))); + } + + private String getDurationDisplay() { + EnumAuctionDuration duration = EnumAuctionDuration.values()[selectedDuration]; + return duration.getDisplayName(); + } + + private long getListingFee() { + EnumAuctionDuration duration = EnumAuctionDuration.values()[selectedDuration]; + return duration.getListingFee(); + } + + @Override + public void actionPerformed(GuiButton button) { + int id = button.id; + + if (id == 31) { + // Cycle duration + selectedDuration = (selectedDuration + 1) % EnumAuctionDuration.values().length; + initGui(); + } else if (id == 50) { + // Create listing + createListing(); + } else if (id == 51) { + // Cancel + close(); + } + } + + private void createListing() { + ItemStack item = container.getListingItem(); + if (item == null) { + return; + } + + long startingPrice = parsePrice(startingPriceField, 1); + long buyoutPrice = parsePrice(buyoutPriceField, 0); + + if (startingPrice < 1) { + startingPrice = 1; + } + + if (buyoutPrice > 0 && buyoutPrice < startingPrice) { + // Show error - buyout must be higher than starting + return; + } + + EnumAuctionDuration duration = EnumAuctionDuration.values()[selectedDuration]; + + // Send to server + AuctionActionPacket.CreateListing(item, startingPrice, buyoutPrice, duration); + + // Clear slot and close + container.clearListingSlot(); + close(); + } + + private long parsePrice(GuiNpcTextField field, long defaultValue) { + try { + return Long.parseLong(field.getText()); + } catch (NumberFormatException e) { + return defaultValue; + } + } + + @Override + public void updateScreen() { + super.updateScreen(); + + // Update item display if it changed + ItemStack item = container.getListingItem(); + GuiNpcLabel itemLabel = getLabel(2); + GuiNpcButton createButton = getButton(50); + + if (item != null) { + if (itemLabel != null) { + itemLabel.label = StatCollector.translateToLocal("auction.item") + " " + item.getDisplayName(); + itemLabel.color = 0x008800; + } + if (createButton != null) { + createButton.setEnabled(true); + } + } else { + if (itemLabel != null) { + itemLabel.label = StatCollector.translateToLocal("auction.noItemSelected"); + itemLabel.color = 0x888888; + } + if (createButton != null) { + createButton.setEnabled(false); + } + } + } + + @Override + public void save() { + // Nothing to save + } +} diff --git a/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionDetails.java b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionDetails.java new file mode 100644 index 000000000..e4131fe94 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionDetails.java @@ -0,0 +1,200 @@ +package noppes.npcs.client.gui.player; + +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.controllers.data.AuctionListing; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +/** + * Sub GUI for viewing auction listing details. + */ +public class SubGuiAuctionDetails extends SubGuiInterface { + private AuctionListing listing; + private long lastUpdate = 0; + + public SubGuiAuctionDetails(GuiAuction parent, AuctionListing listing) { + this.listing = listing; + setBackground("menubg.png"); + xSize = 280; + ySize = 210; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 8; + int labelColor = 0x404040; + int valueColor = 0x000000; + + if (listing.item == null) { + addLabel(new GuiNpcLabel(0, StatCollector.translateToLocal("auction.noItemSelected"), guiLeft + 80, y, 0xAA0000)); + addButton(new GuiNpcButton(50, guiLeft + 100, guiTop + 185, 80, 20, StatCollector.translateToLocal("gui.close"))); + return; + } + + // Title + addLabel(new GuiNpcLabel(0, StatCollector.translateToLocal("auction.auctionDetails"), guiLeft + 100, y, labelColor)); + y += 16; + + // Item name + addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("auction.item"), guiLeft + 20, y, labelColor)); + addLabel(new GuiNpcLabel(2, listing.item.getDisplayName(), guiLeft + 100, y, valueColor)); + y += 14; + + // Quantity + addLabel(new GuiNpcLabel(3, StatCollector.translateToLocal("auction.quantity"), guiLeft + 20, y, labelColor)); + addLabel(new GuiNpcLabel(4, String.valueOf(listing.item.stackSize), guiLeft + 100, y, valueColor)); + y += 14; + + // Seller + addLabel(new GuiNpcLabel(5, StatCollector.translateToLocal("auction.seller"), guiLeft + 20, y, labelColor)); + addLabel(new GuiNpcLabel(6, listing.sellerName, guiLeft + 100, y, valueColor)); + y += 14; + + // Starting price + addLabel(new GuiNpcLabel(10, StatCollector.translateToLocal("auction.startingPrice"), guiLeft + 20, y, labelColor)); + addLabel(new GuiNpcLabel(11, formatCurrency(listing.startingPrice), guiLeft + 120, y, valueColor)); + y += 14; + + // Current bid + if (listing.currentBid > 0) { + addLabel(new GuiNpcLabel(12, StatCollector.translateToLocal("auction.currentBid"), guiLeft + 20, y, labelColor)); + addLabel(new GuiNpcLabel(13, formatCurrency(listing.currentBid), guiLeft + 120, y, 0x008800)); + y += 14; + + // High bidder + addLabel(new GuiNpcLabel(14, StatCollector.translateToLocal("auction.highBidder"), guiLeft + 20, y, labelColor)); + addLabel(new GuiNpcLabel(15, listing.highBidderName, guiLeft + 120, y, valueColor)); + y += 14; + + // Bid count + addLabel(new GuiNpcLabel(16, StatCollector.translateToLocal("auction.totalBids"), guiLeft + 20, y, labelColor)); + addLabel(new GuiNpcLabel(17, String.valueOf(listing.bidCount), guiLeft + 120, y, valueColor)); + y += 14; + } else { + addLabel(new GuiNpcLabel(12, StatCollector.translateToLocal("auction.currentBid"), guiLeft + 20, y, labelColor)); + addLabel(new GuiNpcLabel(13, StatCollector.translateToLocal("auction.noBidsYet"), guiLeft + 120, y, 0x888888)); + y += 14; + } + + // Buyout price + if (listing.buyoutPrice > 0) { + addLabel(new GuiNpcLabel(20, StatCollector.translateToLocal("auction.buyoutPrice"), guiLeft + 20, y, labelColor)); + addLabel(new GuiNpcLabel(21, formatCurrency(listing.buyoutPrice), guiLeft + 120, y, 0xAA6600)); + y += 14; + } + + // Minimum bid + addLabel(new GuiNpcLabel(22, StatCollector.translateToLocal("auction.minimumBid"), guiLeft + 20, y, labelColor)); + addLabel(new GuiNpcLabel(23, formatCurrency(listing.getMinimumBid()), guiLeft + 120, y, 0x0066AA)); + y += 14; + + // Time remaining (will be updated) + addLabel(new GuiNpcLabel(30, StatCollector.translateToLocal("auction.timeLeft"), guiLeft + 20, y, labelColor)); + addLabel(new GuiNpcLabel(31, formatTimeRemaining(listing.getTimeRemaining()), guiLeft + 120, y, + getTimeColor(listing.getTimeRemaining()))); + y += 20; + + // Close button + addButton(new GuiNpcButton(50, guiLeft + 100, guiTop + 185, 80, 20, StatCollector.translateToLocal("gui.close"))); + } + + private String formatCurrency(long amount) { + return String.format("%,d %s", amount, ConfigMarket.CurrencyName); + } + + private String formatTimeRemaining(long millis) { + if (millis <= 0) return StatCollector.translateToLocal("auction.ended"); + + long seconds = millis / 1000; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + + if (days > 0) { + return String.format("%dd %dh %dm", days, hours % 24, minutes % 60); + } else if (hours > 0) { + return String.format("%dh %dm %ds", hours, minutes % 60, seconds % 60); + } else if (minutes > 0) { + return String.format("%dm %ds", minutes, seconds % 60); + } else { + return String.format("%ds", seconds); + } + } + + private int getTimeColor(long millis) { + if (millis <= 0) return 0xAA0000; + if (millis < 5 * 60 * 1000) return 0xFF0000; // < 5 minutes - red + if (millis < 30 * 60 * 1000) return 0xFF6600; // < 30 minutes - orange + if (millis < 60 * 60 * 1000) return 0xAAAA00; // < 1 hour - yellow + return 0x008800; // green + } + + @Override + public void updateScreen() { + super.updateScreen(); + + // Update time remaining every second + long now = System.currentTimeMillis(); + if (now - lastUpdate >= 1000) { + lastUpdate = now; + + GuiNpcLabel timeLabel = getLabel(31); + if (timeLabel != null) { + long remaining = listing.getTimeRemaining(); + timeLabel.label = formatTimeRemaining(remaining); + timeLabel.color = getTimeColor(remaining); + } + } + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + super.drawScreen(mouseX, mouseY, partialTicks); + + // Draw item icon + if (listing.item != null) { + int itemX = guiLeft + 230; + int itemY = guiTop + 32; + + RenderHelper.enableGUIStandardItemLighting(); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glEnable(GL11.GL_COLOR_MATERIAL); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glScalef(2.0f, 2.0f, 2.0f); + + itemRender.renderItemAndEffectIntoGUI(fontRendererObj, mc.renderEngine, + listing.item, itemX / 2, itemY / 2); + itemRender.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, + listing.item, itemX / 2, itemY / 2); + + GL11.glScalef(0.5f, 0.5f, 0.5f); + RenderHelper.disableStandardItemLighting(); + + // Tooltip on hover + if (mouseX >= itemX && mouseX < itemX + 32 && mouseY >= itemY && mouseY < itemY + 32) { + renderToolTip(listing.item, mouseX, mouseY); + } + } + } + + @Override + public void actionPerformed(GuiButton button) { + if (button.id == 50) { + close(); + } + } + + @Override + public void save() { + // Nothing to save + } +} diff --git a/src/main/java/noppes/npcs/client/gui/roles/GuiNpcAuctioneer.java b/src/main/java/noppes/npcs/client/gui/roles/GuiNpcAuctioneer.java new file mode 100644 index 000000000..d5fb8e962 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/roles/GuiNpcAuctioneer.java @@ -0,0 +1,144 @@ +package noppes.npcs.client.gui.roles; + +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.role.RoleSavePacket; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.gui.util.GuiNPCInterface2; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.client.gui.util.ITextfieldListener; +import noppes.npcs.entity.EntityNPCInterface; +import noppes.npcs.roles.RoleAuctioneer; + +public class GuiNpcAuctioneer extends GuiNPCInterface2 implements ITextfieldListener { + + private final RoleAuctioneer role; + + public GuiNpcAuctioneer(EntityNPCInterface npc) { + super(npc); + this.role = npc.roleInterface instanceof RoleAuctioneer ? (RoleAuctioneer) npc.roleInterface : null; + } + + @Override + public void initGui() { + super.initGui(); + if (role == null) { + close(); + return; + } + + int y = guiTop + 10; + + // Left column - Tab visibility + addLabel(new GuiNpcLabel(0, "role.auctioneer.tabs", guiLeft + 10, y, 0x404040)); + y += 18; + + addLabel(new GuiNpcLabel(1, "role.auctioneer.showBrowse", guiLeft + 10, y + 5, 0x404040)); + addButton(new GuiNpcButton(1, guiLeft + 140, y, 50, 20, new String[]{"gui.no", "gui.yes"}, role.showActiveListings ? 1 : 0)); + y += 22; + + addLabel(new GuiNpcLabel(2, "role.auctioneer.showMyListings", guiLeft + 10, y + 5, 0x404040)); + addButton(new GuiNpcButton(2, guiLeft + 140, y, 50, 20, new String[]{"gui.no", "gui.yes"}, role.showMyListings ? 1 : 0)); + y += 22; + + addLabel(new GuiNpcLabel(3, "role.auctioneer.showMyBids", guiLeft + 10, y + 5, 0x404040)); + addButton(new GuiNpcButton(3, guiLeft + 140, y, 50, 20, new String[]{"gui.no", "gui.yes"}, role.showMyBids ? 1 : 0)); + y += 22; + + addLabel(new GuiNpcLabel(4, "role.auctioneer.showClaims", guiLeft + 10, y + 5, 0x404040)); + addButton(new GuiNpcButton(4, guiLeft + 140, y, 50, 20, new String[]{"gui.no", "gui.yes"}, role.showClaims ? 1 : 0)); + y += 30; + + // Actions + addLabel(new GuiNpcLabel(10, "role.auctioneer.actions", guiLeft + 10, y, 0x404040)); + y += 18; + + addLabel(new GuiNpcLabel(11, "role.auctioneer.allowCreate", guiLeft + 10, y + 5, 0x404040)); + addButton(new GuiNpcButton(11, guiLeft + 140, y, 50, 20, new String[]{"gui.no", "gui.yes"}, role.allowCreatingListings ? 1 : 0)); + y += 22; + + addLabel(new GuiNpcLabel(12, "role.auctioneer.allowBid", guiLeft + 10, y + 5, 0x404040)); + addButton(new GuiNpcButton(12, guiLeft + 140, y, 50, 20, new String[]{"gui.no", "gui.yes"}, role.allowBidding ? 1 : 0)); + y += 22; + + addLabel(new GuiNpcLabel(13, "role.auctioneer.allowBuyout", guiLeft + 10, y + 5, 0x404040)); + addButton(new GuiNpcButton(13, guiLeft + 140, y, 50, 20, new String[]{"gui.no", "gui.yes"}, role.allowBuyout ? 1 : 0)); + + // Right column - Messages + int rightX = guiLeft + 210; + int rightY = guiTop + 10; + + addLabel(new GuiNpcLabel(20, "role.auctioneer.messages", rightX, rightY, 0x404040)); + rightY += 18; + + addLabel(new GuiNpcLabel(21, "role.auctioneer.welcome", rightX, rightY + 5, 0x404040)); + rightY += 18; + GuiNpcTextField welcomeField = new GuiNpcTextField(21, this, rightX, rightY, 180, 20, role.welcomeMessage); + welcomeField.setMaxStringLength(200); + addTextField(welcomeField); + rightY += 28; + + addLabel(new GuiNpcLabel(22, "role.auctioneer.noAuction", rightX, rightY + 5, 0x404040)); + rightY += 18; + GuiNpcTextField noAuctionField = new GuiNpcTextField(22, this, rightX, rightY, 180, 20, role.noAuctionMessage); + noAuctionField.setMaxStringLength(200); + addTextField(noAuctionField); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + if (role == null) return; + + if (guibutton instanceof GuiNpcButton) { + GuiNpcButton button = (GuiNpcButton) guibutton; + boolean value = button.getValue() == 1; + + switch (button.id) { + case 1: + role.showActiveListings = value; + break; + case 2: + role.showMyListings = value; + break; + case 3: + role.showMyBids = value; + break; + case 4: + role.showClaims = value; + break; + case 11: + role.allowCreatingListings = value; + break; + case 12: + role.allowBidding = value; + break; + case 13: + role.allowBuyout = value; + break; + } + } + } + + @Override + public void unFocused(GuiNpcTextField textfield) { + if (role == null) return; + + switch (textfield.id) { + case 21: + role.welcomeMessage = textfield.getText(); + break; + case 22: + role.noAuctionMessage = textfield.getText(); + break; + } + } + + @Override + public void save() { + if (role != null) { + PacketClient.sendClient(new RoleSavePacket(role.writeToNBT(new NBTTagCompound()))); + } + } +} diff --git a/src/main/java/noppes/npcs/config/ConfigMarket.java b/src/main/java/noppes/npcs/config/ConfigMarket.java new file mode 100644 index 000000000..f0f019290 --- /dev/null +++ b/src/main/java/noppes/npcs/config/ConfigMarket.java @@ -0,0 +1,245 @@ +package noppes.npcs.config; + +import cpw.mods.fml.common.FMLLog; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.common.config.Property; +import org.apache.logging.log4j.Level; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; + +public class ConfigMarket { + public static Configuration config; + + public final static String MARKET = "Market"; + public final static String CURRENCY = "Market.Currency"; + public final static String AUCTION = "Market.Auction"; + public final static String TRADER = "Market.Trader"; + + // ========================================= + // Market General + // ========================================= + public static boolean MarketEnabled = true; + + // ========================================= + // Currency Settings + // ========================================= + public static boolean UseVaultIfAvailable = true; + public static String CurrencyName = "Gold"; + public static String FallbackCurrencyItem = "customnpcs:npcCoinGold"; + public static long FallbackItemRatio = 1; + public static long StartingBalance = 1000; + public static long MaxBalance = 999999999999L; + + // ========================================= + // Auction Settings + // ========================================= + public static boolean AuctionEnabled = true; + public static int DefaultMaxListings = 5; + public static double ListingFeePercent = 0.0; + public static double SalesTaxPercent = 0.05; + public static boolean RequireAuctioneerNPC = true; + public static int ClaimExpirationDays = 30; + public static double MinBidIncrementPercent = 0.05; + public static int SnipeProtectionMinutes = 5; + public static int SnipeProtectionThreshold = 5; + + // Auction Duration Settings (in hours) + public static int AuctionDurationShort = 2; + public static int AuctionDurationMedium = 12; + public static int AuctionDurationLong = 24; + public static int AuctionDurationVeryLong = 48; + + // Auction Duration Fees (flat currency amount) + public static long AuctionFeeShort = 0; + public static long AuctionFeeMedium = 0; + public static long AuctionFeeLong = 0; + public static long AuctionFeeVeryLong = 0; + + // ========================================= + // Trader Settings + // ========================================= + public static boolean EnableStockByDefault = false; + public static String DefaultResetType = "NONE"; + + public static void init(File configFile) { + config = new Configuration(configFile); + + try { + config.load(); + + // ========================================= + // Market General + // ========================================= + MarketEnabled = config.get(MARKET, "Enable Market System", true, + "Enable the market/economy system").getBoolean(true); + + // ========================================= + // Currency Settings + // ========================================= + config.setCategoryComment(CURRENCY, "Currency system settings for the virtual economy"); + + UseVaultIfAvailable = config.get(CURRENCY, "Use Vault If Available", true, + "Use VaultAPI if available on Bukkit hybrid servers").getBoolean(true); + + CurrencyName = config.get(CURRENCY, "Currency Name", "Gold", + "Display name for the currency").getString(); + + FallbackCurrencyItem = config.get(CURRENCY, "Fallback Currency Item", "customnpcs:npcCoinGold", + "Item registry name to use as currency when Vault is unavailable. Leave empty to disable.").getString(); + + FallbackItemRatio = config.get(CURRENCY, "Fallback Item Ratio", 1, + "Conversion ratio: 1 fallback item = X virtual currency").getInt(1); + + StartingBalance = config.get(CURRENCY, "Starting Balance", 1000, + "Starting balance for new players (only used when Vault is not available)").getInt(1000); + + Property maxBalanceProp = config.get(CURRENCY, "Maximum Balance", String.valueOf(MaxBalance), + "Maximum balance a player can have (only used when Vault is not available)"); + try { + MaxBalance = Long.parseLong(maxBalanceProp.getString()); + } catch (NumberFormatException e) { + MaxBalance = 999999999999L; + } + if (MaxBalance < 0) { + MaxBalance = 0; + } + + // ========================================= + // Auction Settings + // ========================================= + config.setCategoryComment(AUCTION, "Auction house settings"); + + AuctionEnabled = config.get(AUCTION, "Enable Auction House", true, + "Enable/disable the auction house system").getBoolean(true); + + DefaultMaxListings = config.get(AUCTION, "Default Max Listings", 5, + "Default maximum auction listings per player (without permission override)").getInt(5); + + ListingFeePercent = config.get(AUCTION, "Listing Fee Percent", 0.0, + "Listing fee as percentage of starting price (0.0 = no fee)").getDouble(0.0); + + SalesTaxPercent = config.get(AUCTION, "Sales Tax Percent", 0.05, + "Sales tax as percentage taken from final sale price (0.05 = 5%)").getDouble(0.05); + + RequireAuctioneerNPC = config.get(AUCTION, "Require Auctioneer NPC", true, + "Require an Auctioneer NPC to access auction house").getBoolean(true); + + ClaimExpirationDays = config.get(AUCTION, "Claim Expiration Days", 30, + "Claim expiration in days (claims auto-expire after this period, 0 = never)").getInt(30); + + MinBidIncrementPercent = config.get(AUCTION, "Min Bid Increment Percent", 0.05, + "Minimum bid increment as percentage (0.05 = 5% minimum increase)").getDouble(0.05); + + SnipeProtectionMinutes = config.get(AUCTION, "Snipe Protection Minutes", 5, + "Extend auction TO this many minutes when bid placed near end. Set to 0 to disable.").getInt(5); + + SnipeProtectionThreshold = config.get(AUCTION, "Snipe Protection Threshold", 5, + "How many minutes before end triggers snipe protection").getInt(5); + + // Duration settings + AuctionDurationShort = config.get(AUCTION, "Duration Short Hours", 2, + "Short auction duration in hours").getInt(2); + + AuctionDurationMedium = config.get(AUCTION, "Duration Medium Hours", 12, + "Medium auction duration in hours").getInt(12); + + AuctionDurationLong = config.get(AUCTION, "Duration Long Hours", 24, + "Long auction duration in hours").getInt(24); + + AuctionDurationVeryLong = config.get(AUCTION, "Duration Very Long Hours", 48, + "Very long auction duration in hours").getInt(48); + + // Duration fees + AuctionFeeShort = config.get(AUCTION, "Fee Short Duration", 0, + "Flat fee for short duration auctions").getInt(0); + + AuctionFeeMedium = config.get(AUCTION, "Fee Medium Duration", 0, + "Flat fee for medium duration auctions").getInt(0); + + AuctionFeeLong = config.get(AUCTION, "Fee Long Duration", 0, + "Flat fee for long duration auctions").getInt(0); + + AuctionFeeVeryLong = config.get(AUCTION, "Fee Very Long Duration", 0, + "Flat fee for very long duration auctions").getInt(0); + + // ========================================= + // Trader Settings + // ========================================= + config.setCategoryComment(TRADER, "Trader stock system settings"); + + EnableStockByDefault = config.get(TRADER, "Enable Stock By Default", false, + "Enable stock system by default for new traders").getBoolean(false); + + DefaultResetType = config.get(TRADER, "Default Reset Type", "NONE", + "Default stock reset type (NONE, MCDAILY, MCWEEKLY, RLDAILY, RLWEEKLY)").getString(); + + // Set category order + config.setCategoryPropertyOrder(MARKET, new ArrayList<>(Arrays.asList( + "Enable Market System" + ))); + + config.setCategoryPropertyOrder(CURRENCY, new ArrayList<>(Arrays.asList( + "Use Vault If Available", + "Currency Name", + "Fallback Currency Item", + "Fallback Item Ratio", + "Starting Balance", + "Maximum Balance" + ))); + + config.setCategoryPropertyOrder(AUCTION, new ArrayList<>(Arrays.asList( + "Enable Auction House", + "Default Max Listings", + "Listing Fee Percent", + "Sales Tax Percent", + "Require Auctioneer NPC", + "Claim Expiration Days", + "Min Bid Increment Percent", + "Snipe Protection Minutes", + "Snipe Protection Threshold", + "Duration Short Hours", + "Duration Medium Hours", + "Duration Long Hours", + "Duration Very Long Hours", + "Fee Short Duration", + "Fee Medium Duration", + "Fee Long Duration", + "Fee Very Long Duration" + ))); + + config.setCategoryPropertyOrder(TRADER, new ArrayList<>(Arrays.asList( + "Enable Stock By Default", + "Default Reset Type" + ))); + + // Validation + if (DefaultMaxListings < 1) { + DefaultMaxListings = 1; + } + if (ClaimExpirationDays < 0) { + ClaimExpirationDays = 0; + } + if (SnipeProtectionMinutes < 0) { + SnipeProtectionMinutes = 0; + } + if (SnipeProtectionThreshold < 0) { + SnipeProtectionThreshold = 0; + } + if (StartingBalance < 0) { + StartingBalance = 0; + } + if (MaxBalance < 1) { + MaxBalance = 1; + } + + } catch (Exception e) { + FMLLog.log(Level.ERROR, e, "CNPC+ has had a problem loading its market configuration"); + } finally { + if (config.hasChanged()) { + config.save(); + } + } + } +} diff --git a/src/main/java/noppes/npcs/config/LoadConfiguration.java b/src/main/java/noppes/npcs/config/LoadConfiguration.java index 19fad65c2..dfac43d90 100644 --- a/src/main/java/noppes/npcs/config/LoadConfiguration.java +++ b/src/main/java/noppes/npcs/config/LoadConfiguration.java @@ -9,6 +9,7 @@ public class LoadConfiguration { public static File debugConfigFile; public static File clientConfigFile; public static File experimentalConfigFile; + public static File marketConfigFile; public static void init(String configpath) { mainConfigFile = new File(configpath + "main.cfg"); @@ -17,6 +18,7 @@ public class LoadConfiguration { scriptConfigFile = new File(configpath + "script.cfg"); debugConfigFile = new File(configpath + "debug.cfg"); experimentalConfigFile = new File(configpath + "experimental.cfg"); + marketConfigFile = new File(configpath + "market.cfg"); ConfigMain.init(mainConfigFile); ConfigItem.init(itemConfigFile); @@ -24,5 +26,6 @@ public class LoadConfiguration { ConfigScript.init(scriptConfigFile); ConfigDebug.init(debugConfigFile); ConfigExperimental.init(experimentalConfigFile); + ConfigMarket.init(marketConfigFile); } } diff --git a/src/main/java/noppes/npcs/constants/EnumAuctionDuration.java b/src/main/java/noppes/npcs/constants/EnumAuctionDuration.java new file mode 100644 index 000000000..c901d21ce --- /dev/null +++ b/src/main/java/noppes/npcs/constants/EnumAuctionDuration.java @@ -0,0 +1,82 @@ +package noppes.npcs.constants; + +import net.minecraft.util.StatCollector; +import noppes.npcs.config.ConfigMarket; + +/** + * Duration options for auction listings. + * Values are configurable via ConfigMarket. + */ +public enum EnumAuctionDuration { + SHORT("auction.duration.short"), + MEDIUM("auction.duration.medium"), + LONG("auction.duration.long"), + VERY_LONG("auction.duration.veryLong"); + + private final String langKey; + + EnumAuctionDuration(String langKey) { + this.langKey = langKey; + } + + /** + * Get duration in milliseconds + */ + public long getMillis() { + switch (this) { + case SHORT: + return ConfigMarket.AuctionDurationShort * 60L * 60L * 1000L; + case MEDIUM: + return ConfigMarket.AuctionDurationMedium * 60L * 60L * 1000L; + case LONG: + return ConfigMarket.AuctionDurationLong * 60L * 60L * 1000L; + case VERY_LONG: + return ConfigMarket.AuctionDurationVeryLong * 60L * 60L * 1000L; + default: + return 24 * 60L * 60L * 1000L; + } + } + + /** + * Get duration in hours + */ + public int getHours() { + switch (this) { + case SHORT: + return ConfigMarket.AuctionDurationShort; + case MEDIUM: + return ConfigMarket.AuctionDurationMedium; + case LONG: + return ConfigMarket.AuctionDurationLong; + case VERY_LONG: + return ConfigMarket.AuctionDurationVeryLong; + default: + return 24; + } + } + + /** + * Get display name for GUI + */ + public String getDisplayName() { + return StatCollector.translateToLocal(langKey); + } + + /** + * Get listing fee for this duration + */ + public long getListingFee() { + switch (this) { + case SHORT: + return ConfigMarket.AuctionFeeShort; + case MEDIUM: + return ConfigMarket.AuctionFeeMedium; + case LONG: + return ConfigMarket.AuctionFeeLong; + case VERY_LONG: + return ConfigMarket.AuctionFeeVeryLong; + default: + return 0; + } + } +} diff --git a/src/main/java/noppes/npcs/constants/EnumAuctionSort.java b/src/main/java/noppes/npcs/constants/EnumAuctionSort.java new file mode 100644 index 000000000..75220861c --- /dev/null +++ b/src/main/java/noppes/npcs/constants/EnumAuctionSort.java @@ -0,0 +1,39 @@ +package noppes.npcs.constants; + +import net.minecraft.util.StatCollector; + +/** + * Sorting options for auction listings. + */ +public enum EnumAuctionSort { + NEWEST_FIRST("auction.sort.newest"), + OLDEST_FIRST("auction.sort.oldest"), + PRICE_HIGH_TO_LOW("auction.sort.priceHigh"), + PRICE_LOW_TO_HIGH("auction.sort.priceLow"), + ENDING_SOON("auction.sort.endingSoon"), + MOST_TIME_LEFT("auction.sort.mostTime"), + NAME_A_TO_Z("auction.sort.nameAZ"), + NAME_Z_TO_A("auction.sort.nameZA"), + MOST_BIDS("auction.sort.mostBids"), + LEAST_BIDS("auction.sort.leastBids"); + + private final String langKey; + + EnumAuctionSort(String langKey) { + this.langKey = langKey; + } + + public String getDisplayName() { + return StatCollector.translateToLocal(langKey); + } + + public EnumAuctionSort next() { + EnumAuctionSort[] values = values(); + return values[(this.ordinal() + 1) % values.length]; + } + + public EnumAuctionSort previous() { + EnumAuctionSort[] values = values(); + return values[(this.ordinal() - 1 + values.length) % values.length]; + } +} diff --git a/src/main/java/noppes/npcs/constants/EnumAuctionStatus.java b/src/main/java/noppes/npcs/constants/EnumAuctionStatus.java new file mode 100644 index 000000000..9e614e496 --- /dev/null +++ b/src/main/java/noppes/npcs/constants/EnumAuctionStatus.java @@ -0,0 +1,54 @@ +package noppes.npcs.constants; + +/** + * Status of an auction listing. + */ +public enum EnumAuctionStatus { + ACTIVE, // Currently listed and accepting bids + SOLD, // Successfully sold (buyout or auction end with bids) + EXPIRED, // Ended without any bids + CANCELLED, // Cancelled by seller (only allowed before first bid) + CLAIMED; // Item/money has been claimed by respective parties + + /** + * Get display name for GUI + */ + public String getDisplayName() { + switch (this) { + case ACTIVE: return "Active"; + case SOLD: return "Sold"; + case EXPIRED: return "Expired"; + case CANCELLED: return "Cancelled"; + case CLAIMED: return "Claimed"; + default: return "Unknown"; + } + } + + /** + * Get display color for GUI (MC color codes) + */ + public char getColorCode() { + switch (this) { + case ACTIVE: return 'a'; // Green + case SOLD: return '6'; // Gold + case EXPIRED: return '7'; // Gray + case CANCELLED: return 'c'; // Red + case CLAIMED: return '8'; // Dark gray + default: return 'f'; // White + } + } + + /** + * Check if listing can still receive bids + */ + public boolean canBid() { + return this == ACTIVE; + } + + /** + * Check if listing needs claiming (item or money) + */ + public boolean needsClaiming() { + return this == SOLD || this == EXPIRED || this == CANCELLED; + } +} diff --git a/src/main/java/noppes/npcs/constants/EnumGuiType.java b/src/main/java/noppes/npcs/constants/EnumGuiType.java index f2d911561..6c85cb4f5 100644 --- a/src/main/java/noppes/npcs/constants/EnumGuiType.java +++ b/src/main/java/noppes/npcs/constants/EnumGuiType.java @@ -64,5 +64,7 @@ public enum EnumGuiType { ScriptBlock, Paintbrush, MagicBook, - ManageAbilities; + ManageAbilities, + PlayerAuction, + SetupAuctioneer; } diff --git a/src/main/java/noppes/npcs/constants/EnumRoleType.java b/src/main/java/noppes/npcs/constants/EnumRoleType.java index 624658fb3..33f36941a 100644 --- a/src/main/java/noppes/npcs/constants/EnumRoleType.java +++ b/src/main/java/noppes/npcs/constants/EnumRoleType.java @@ -2,5 +2,5 @@ package noppes.npcs.constants; public enum EnumRoleType { - None, Trader, Follower, Bank, Transporter, Postman, Companion, Mount + None, Trader, Follower, Bank, Transporter, Postman, Companion, Mount, Auctioneer } diff --git a/src/main/java/noppes/npcs/constants/EnumStockReset.java b/src/main/java/noppes/npcs/constants/EnumStockReset.java new file mode 100644 index 000000000..cdc56cb95 --- /dev/null +++ b/src/main/java/noppes/npcs/constants/EnumStockReset.java @@ -0,0 +1,64 @@ +package noppes.npcs.constants; + +/** + * Stock reset types for Trader NPCs. + * Mirrors EnumQuestRepeat pattern for consistency. + */ +public enum EnumStockReset { + NONE, // Never resets + MCDAILY, // Every 24000 MC ticks (1 MC day) + MCWEEKLY, // Every 168000 MC ticks (7 MC days) + MCCUSTOM, // Custom MC tick interval + RLDAILY, // Every 24 real hours + RLWEEKLY, // Every 7 real days + RLCUSTOM; // Custom real-time interval + + /** + * Get reset interval in milliseconds for real-time types + * or ticks for MC-time types + */ + public long getDefaultInterval() { + switch (this) { + case MCDAILY: + return 24000; // MC ticks + case MCWEEKLY: + return 168000; // MC ticks (7 days) + case RLDAILY: + return 86400000L; // 24 hours in ms + case RLWEEKLY: + return 604800000L; // 7 days in ms + default: + return 0; + } + } + + /** + * Check if this reset type uses real-world time + */ + public boolean isRealTime() { + return this == RLDAILY || this == RLWEEKLY || this == RLCUSTOM; + } + + /** + * Check if this reset type uses Minecraft time + */ + public boolean isMinecraftTime() { + return this == MCDAILY || this == MCWEEKLY || this == MCCUSTOM; + } + + /** + * Get display name for GUI + */ + public String getDisplayName() { + switch (this) { + case NONE: return "Never"; + case MCDAILY: return "MC Daily"; + case MCWEEKLY: return "MC Weekly"; + case MCCUSTOM: return "MC Custom"; + case RLDAILY: return "Real Daily"; + case RLWEEKLY: return "Real Weekly"; + case RLCUSTOM: return "Real Custom"; + default: return "Unknown"; + } + } +} diff --git a/src/main/java/noppes/npcs/containers/ContainerAuction.java b/src/main/java/noppes/npcs/containers/ContainerAuction.java new file mode 100644 index 000000000..2efd2b1b5 --- /dev/null +++ b/src/main/java/noppes/npcs/containers/ContainerAuction.java @@ -0,0 +1,193 @@ +package noppes.npcs.containers; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import noppes.npcs.entity.EntityNPCInterface; + +/** + * Container for auction house GUI. + * Handles player inventory and item slot for creating listings. + */ +public class ContainerAuction extends Container { + public EntityNPCInterface npc; + public EntityPlayer player; + + // Slot for item being listed + public SlotAuctionItem listingSlot; + private IInventory listingInventory; + + public ContainerAuction(EntityNPCInterface npc, EntityPlayer player) { + this.npc = npc; + this.player = player; + + // Create a single-slot inventory for the item being listed + listingInventory = new InventoryAuctionListing(); + listingSlot = new SlotAuctionItem(listingInventory, 0, 251, 146); + addSlotToContainer(listingSlot); + + // Player inventory slots (standard positioning) + for (int row = 0; row < 3; row++) { + for (int col = 0; col < 9; col++) { + addSlotToContainer(new Slot(player.inventory, col + row * 9 + 9, + 8 + col * 18, 166 + row * 18)); + } + } + + // Player hotbar + for (int col = 0; col < 9; col++) { + addSlotToContainer(new Slot(player.inventory, col, 8 + col * 18, 224)); + } + } + + @Override + public boolean canInteractWith(EntityPlayer player) { + return npc != null && npc.isEntityAlive() && + player.getDistanceSqToEntity(npc) < 64.0D; + } + + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { + ItemStack itemstack = null; + Slot slot = (Slot) inventorySlots.get(slotIndex); + + if (slot != null && slot.getHasStack()) { + ItemStack stackInSlot = slot.getStack(); + itemstack = stackInSlot.copy(); + + // If from listing slot, move to player inventory + if (slotIndex == 0) { + if (!mergeItemStack(stackInSlot, 1, 37, true)) { + return null; + } + } + // If from player inventory, move to listing slot + else { + if (!mergeItemStack(stackInSlot, 0, 1, false)) { + return null; + } + } + + if (stackInSlot.stackSize == 0) { + slot.putStack(null); + } else { + slot.onSlotChanged(); + } + } + + return itemstack; + } + + @Override + public void onContainerClosed(EntityPlayer player) { + super.onContainerClosed(player); + + // Return any item in the listing slot to player + ItemStack stack = listingInventory.getStackInSlot(0); + if (stack != null) { + if (!player.inventory.addItemStackToInventory(stack)) { + player.entityDropItem(stack, 0.5f); + } + } + } + + /** + * Get the item currently in the listing slot + */ + public ItemStack getListingItem() { + return listingInventory.getStackInSlot(0); + } + + /** + * Clear the listing slot (after successful listing creation) + */ + public void clearListingSlot() { + listingInventory.setInventorySlotContents(0, null); + } + + /** + * Simple inventory for the listing slot + */ + private class InventoryAuctionListing implements IInventory { + private ItemStack item; + + @Override + public int getSizeInventory() { return 1; } + + @Override + public ItemStack getStackInSlot(int slot) { return item; } + + @Override + public ItemStack decrStackSize(int slot, int amount) { + if (item != null) { + ItemStack result; + if (item.stackSize <= amount) { + result = item; + item = null; + return result; + } else { + result = item.splitStack(amount); + if (item.stackSize == 0) { + item = null; + } + return result; + } + } + return null; + } + + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + ItemStack result = item; + item = null; + return result; + } + + @Override + public void setInventorySlotContents(int slot, ItemStack stack) { + item = stack; + } + + @Override + public String getInventoryName() { return "AuctionListing"; } + + @Override + public boolean hasCustomInventoryName() { return false; } + + @Override + public int getInventoryStackLimit() { return 64; } + + @Override + public void markDirty() {} + + @Override + public boolean isUseableByPlayer(EntityPlayer player) { return true; } + + @Override + public void openInventory() {} + + @Override + public void closeInventory() {} + + @Override + public boolean isItemValidForSlot(int slot, ItemStack stack) { return true; } + } + + /** + * Custom slot for auction listings + */ + public class SlotAuctionItem extends Slot { + public SlotAuctionItem(IInventory inv, int index, int x, int y) { + super(inv, index, x, y); + } + + @Override + public boolean isItemValid(ItemStack stack) { + // Check if item can be traded (not untradeable, soulbound, etc.) + return kamkeel.npcs.controllers.data.attribute.ItemTradeAttribute.canTrade(stack); + } + } +} diff --git a/src/main/java/noppes/npcs/containers/ContainerNPCTrader.java b/src/main/java/noppes/npcs/containers/ContainerNPCTrader.java index 71dcd6fa6..936868152 100644 --- a/src/main/java/noppes/npcs/containers/ContainerNPCTrader.java +++ b/src/main/java/noppes/npcs/containers/ContainerNPCTrader.java @@ -4,6 +4,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import noppes.npcs.NoppesUtilPlayer; +import noppes.npcs.controllers.CurrencyController; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.roles.RoleTrader; @@ -61,17 +62,43 @@ public class ContainerNPCTrader extends ContainerNpcInterface { ItemStack item = slot.getStack(); if (!canGivePlayer(item, entityplayer)) return null; - if (!canBuy(i, entityplayer)) - return null; if (!isSlotEnabled(i, entityplayer)) return null; - NoppesUtilPlayer.consumeItem(entityplayer, role.inventoryCurrency.getStackInSlot(i), role.ignoreDamage, role.ignoreNBT); - NoppesUtilPlayer.consumeItem(entityplayer, role.inventoryCurrency.getStackInSlot(i + 18), role.ignoreDamage, role.ignoreNBT); + + // Check stock availability + String playerName = entityplayer.getCommandSenderName(); + if (!role.hasStock(i, playerName, 1)) { + return null; // Out of stock + } + + // Handle currency-based purchase + if (role.hasSlotPrice(i)) { + long price = role.getSlotPrice(i); + if (CurrencyController.Instance == null) { + return null; // Currency system not available + } + if (!CurrencyController.Instance.canAfford(entityplayer, price)) { + return null; // Can't afford + } + // Withdraw currency + if (!CurrencyController.Instance.withdraw(entityplayer, price)) { + return null; // Withdrawal failed + } + } else { + // Item-based currency - existing logic + if (!canBuy(i, entityplayer)) + return null; + NoppesUtilPlayer.consumeItem(entityplayer, role.inventoryCurrency.getStackInSlot(i), role.ignoreDamage, role.ignoreNBT); + NoppesUtilPlayer.consumeItem(entityplayer, role.inventoryCurrency.getStackInSlot(i + 18), role.ignoreDamage, role.ignoreNBT); + } + + // Consume stock + role.consumeStock(i, playerName, 1); + ItemStack soldItem = item.copy(); givePlayer(soldItem, entityplayer); role.addPurchase(i, entityplayer.getDisplayName()); return soldItem; - } public boolean isSlotEnabled(int slot, EntityPlayer player) { diff --git a/src/main/java/noppes/npcs/controllers/AuctionBlacklist.java b/src/main/java/noppes/npcs/controllers/AuctionBlacklist.java new file mode 100644 index 000000000..020bb0bcb --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/AuctionBlacklist.java @@ -0,0 +1,419 @@ +package noppes.npcs.controllers; + +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.NBTTagString; +import noppes.npcs.CustomNpcs; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.HashSet; +import java.util.Set; + +/** + * Controller for managing auction house item blacklisting. + * Allows administrators to block specific items, entire mods, + * or items with certain NBT tags from being listed. + */ +public class AuctionBlacklist { + private static final Logger logger = LogManager.getLogger(CustomNpcs.class); + + public static AuctionBlacklist Instance; + + // Blacklist by item registry name (e.g., "minecraft:diamond_sword") + private Set blacklistedItems = new HashSet<>(); + + // Blacklist by mod ID (e.g., "minecraft" blocks all vanilla items) + private Set blacklistedMods = new HashSet<>(); + + // Blacklist by NBT tag presence (e.g., items with specific custom data) + private Set blacklistedNBTTags = new HashSet<>(); + + public AuctionBlacklist() { + Instance = this; + load(); + } + + // ==================== Blacklist Checking ==================== + + /** + * Check if an item is blacklisted from the auction house. + * + * @param item The item to check + * @return true if the item is blacklisted + */ + public boolean isBlacklisted(ItemStack item) { + if (item == null || item.getItem() == null) { + return false; + } + + // Check item registry name + String itemName = Item.itemRegistry.getNameForObject(item.getItem()); + if (itemName != null) { + // Direct item blacklist + if (blacklistedItems.contains(itemName)) { + return true; + } + + // Also check with metadata for specific variants + String itemNameWithMeta = itemName + ":" + item.getItemDamage(); + if (blacklistedItems.contains(itemNameWithMeta)) { + return true; + } + + // Check mod ID + String modId = getModIdFromName(itemName); + if (modId != null && blacklistedMods.contains(modId)) { + return true; + } + } + + // Check NBT tags + if (item.hasTagCompound()) { + NBTTagCompound tag = item.getTagCompound(); + for (String nbtTag : blacklistedNBTTags) { + if (hasNestedTag(tag, nbtTag)) { + return true; + } + } + } + + return false; + } + + /** + * Get the reason why an item is blacklisted + * @return Description of why blacklisted, or null if not blacklisted + */ + public String getBlacklistReason(ItemStack item) { + if (item == null || item.getItem() == null) { + return null; + } + + String itemName = Item.itemRegistry.getNameForObject(item.getItem()); + if (itemName != null) { + if (blacklistedItems.contains(itemName)) { + return "Item is blacklisted: " + itemName; + } + + String itemNameWithMeta = itemName + ":" + item.getItemDamage(); + if (blacklistedItems.contains(itemNameWithMeta)) { + return "Item variant is blacklisted: " + itemNameWithMeta; + } + + String modId = getModIdFromName(itemName); + if (modId != null && blacklistedMods.contains(modId)) { + return "Mod is blacklisted: " + modId; + } + } + + if (item.hasTagCompound()) { + NBTTagCompound tag = item.getTagCompound(); + for (String nbtTag : blacklistedNBTTags) { + if (hasNestedTag(tag, nbtTag)) { + return "Item has blacklisted NBT tag: " + nbtTag; + } + } + } + + return null; + } + + /** + * Extract mod ID from registry name (e.g., "minecraft" from "minecraft:stone") + */ + private String getModIdFromName(String registryName) { + if (registryName == null) { + return null; + } + int colonIndex = registryName.indexOf(':'); + if (colonIndex > 0) { + return registryName.substring(0, colonIndex); + } + return null; + } + + /** + * Check for nested NBT tag (supports dot notation like "display.Name") + */ + private boolean hasNestedTag(NBTTagCompound tag, String path) { + if (tag == null || path == null || path.isEmpty()) { + return false; + } + + String[] parts = path.split("\\."); + NBTTagCompound current = tag; + + for (int i = 0; i < parts.length - 1; i++) { + if (!current.hasKey(parts[i])) { + return false; + } + if (current.hasKey(parts[i], 10)) { // 10 = Compound tag + current = current.getCompoundTag(parts[i]); + } else { + return false; + } + } + + return current.hasKey(parts[parts.length - 1]); + } + + // ==================== Item Blacklist Management ==================== + + /** + * Add an item to the blacklist by registry name + * @param itemName Registry name (e.g., "minecraft:diamond_sword" or "minecraft:wool:14") + */ + public void addItem(String itemName) { + if (itemName != null && !itemName.isEmpty()) { + blacklistedItems.add(itemName); + save(); + logger.info("Added item to auction blacklist: " + itemName); + } + } + + /** + * Add an item to the blacklist from an ItemStack + */ + public void addItem(ItemStack item, boolean includeMeta) { + if (item == null || item.getItem() == null) { + return; + } + String itemName = Item.itemRegistry.getNameForObject(item.getItem()); + if (itemName != null) { + if (includeMeta && item.getHasSubtypes()) { + addItem(itemName + ":" + item.getItemDamage()); + } else { + addItem(itemName); + } + } + } + + /** + * Remove an item from the blacklist + */ + public void removeItem(String itemName) { + if (blacklistedItems.remove(itemName)) { + save(); + logger.info("Removed item from auction blacklist: " + itemName); + } + } + + /** + * Check if a specific item is blacklisted + */ + public boolean isItemBlacklisted(String itemName) { + return blacklistedItems.contains(itemName); + } + + /** + * Get all blacklisted items + */ + public Set getBlacklistedItems() { + return new HashSet<>(blacklistedItems); + } + + // ==================== Mod Blacklist Management ==================== + + /** + * Add an entire mod to the blacklist + * @param modId The mod ID (e.g., "minecraft", "customnpcs") + */ + public void addMod(String modId) { + if (modId != null && !modId.isEmpty()) { + blacklistedMods.add(modId); + save(); + logger.info("Added mod to auction blacklist: " + modId); + } + } + + /** + * Remove a mod from the blacklist + */ + public void removeMod(String modId) { + if (blacklistedMods.remove(modId)) { + save(); + logger.info("Removed mod from auction blacklist: " + modId); + } + } + + /** + * Check if a mod is blacklisted + */ + public boolean isModBlacklisted(String modId) { + return blacklistedMods.contains(modId); + } + + /** + * Get all blacklisted mods + */ + public Set getBlacklistedMods() { + return new HashSet<>(blacklistedMods); + } + + // ==================== NBT Tag Blacklist Management ==================== + + /** + * Add an NBT tag to the blacklist + * Items containing this tag will be blocked + * @param tagPath The tag path (e.g., "display.Name" or "CustomData") + */ + public void addNBTTag(String tagPath) { + if (tagPath != null && !tagPath.isEmpty()) { + blacklistedNBTTags.add(tagPath); + save(); + logger.info("Added NBT tag to auction blacklist: " + tagPath); + } + } + + /** + * Remove an NBT tag from the blacklist + */ + public void removeNBTTag(String tagPath) { + if (blacklistedNBTTags.remove(tagPath)) { + save(); + logger.info("Removed NBT tag from auction blacklist: " + tagPath); + } + } + + /** + * Check if an NBT tag is blacklisted + */ + public boolean isNBTTagBlacklisted(String tagPath) { + return blacklistedNBTTags.contains(tagPath); + } + + /** + * Get all blacklisted NBT tags + */ + public Set getBlacklistedNBTTags() { + return new HashSet<>(blacklistedNBTTags); + } + + // ==================== Persistence ==================== + + public void save() { + File saveDir = CustomNpcs.getWorldSaveDirectory(); + if (saveDir == null) { + return; + } + + try { + NBTTagCompound compound = new NBTTagCompound(); + + // Save blacklisted items + NBTTagList itemList = new NBTTagList(); + for (String item : blacklistedItems) { + itemList.appendTag(new NBTTagString(item)); + } + compound.setTag("Items", itemList); + + // Save blacklisted mods + NBTTagList modList = new NBTTagList(); + for (String mod : blacklistedMods) { + modList.appendTag(new NBTTagString(mod)); + } + compound.setTag("Mods", modList); + + // Save blacklisted NBT tags + NBTTagList nbtList = new NBTTagList(); + for (String nbt : blacklistedNBTTags) { + nbtList.appendTag(new NBTTagString(nbt)); + } + compound.setTag("NBTTags", nbtList); + + // Write to file + File file = new File(saveDir, "auction_blacklist.dat"); + File backup = new File(saveDir, "auction_blacklist.dat_old"); + + if (file.exists()) { + if (backup.exists()) { + backup.delete(); + } + file.renameTo(backup); + } + + file = new File(saveDir, "auction_blacklist.dat"); + FileOutputStream fos = new FileOutputStream(file); + CompressedStreamTools.writeCompressed(compound, fos); + fos.close(); + + } catch (Exception e) { + logger.error("Error saving auction blacklist", e); + } + } + + public void load() { + File saveDir = CustomNpcs.getWorldSaveDirectory(); + if (saveDir == null) { + return; + } + + blacklistedItems.clear(); + blacklistedMods.clear(); + blacklistedNBTTags.clear(); + + try { + File file = new File(saveDir, "auction_blacklist.dat"); + if (!file.exists()) { + // Try backup + file = new File(saveDir, "auction_blacklist.dat_old"); + if (!file.exists()) { + return; + } + } + + FileInputStream fis = new FileInputStream(file); + NBTTagCompound compound = CompressedStreamTools.readCompressed(fis); + fis.close(); + + // Load blacklisted items + NBTTagList itemList = compound.getTagList("Items", 8); // 8 = String tag + for (int i = 0; i < itemList.tagCount(); i++) { + blacklistedItems.add(itemList.getStringTagAt(i)); + } + + // Load blacklisted mods + NBTTagList modList = compound.getTagList("Mods", 8); + for (int i = 0; i < modList.tagCount(); i++) { + blacklistedMods.add(modList.getStringTagAt(i)); + } + + // Load blacklisted NBT tags + NBTTagList nbtList = compound.getTagList("NBTTags", 8); + for (int i = 0; i < nbtList.tagCount(); i++) { + blacklistedNBTTags.add(nbtList.getStringTagAt(i)); + } + + logger.info("Loaded auction blacklist: {} items, {} mods, {} NBT tags", + blacklistedItems.size(), blacklistedMods.size(), blacklistedNBTTags.size()); + + } catch (Exception e) { + logger.error("Error loading auction blacklist", e); + } + } + + /** + * Clear all blacklist entries + */ + public void clearAll() { + blacklistedItems.clear(); + blacklistedMods.clear(); + blacklistedNBTTags.clear(); + save(); + logger.info("Cleared all auction blacklist entries"); + } + + /** + * Get total number of blacklist entries + */ + public int getTotalEntries() { + return blacklistedItems.size() + blacklistedMods.size() + blacklistedNBTTags.size(); + } +} diff --git a/src/main/java/noppes/npcs/controllers/AuctionController.java b/src/main/java/noppes/npcs/controllers/AuctionController.java new file mode 100644 index 000000000..8333fd01a --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/AuctionController.java @@ -0,0 +1,834 @@ +package noppes.npcs.controllers; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.EnumChatFormatting; +import noppes.npcs.CustomNpcs; +import noppes.npcs.LogWriter; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.constants.EnumAuctionDuration; +import noppes.npcs.constants.EnumAuctionSort; +import noppes.npcs.constants.EnumAuctionStatus; +import noppes.npcs.controllers.data.AuctionFilter; +import noppes.npcs.controllers.data.AuctionListing; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +/** + * Controller for the global auction house. + * Manages all auction listings, bidding, claims, notifications, and logging. + */ +public class AuctionController { + private static final String LOG_PREFIX = "[Auction] "; + + public static AuctionController Instance; + + // All auction listings by ID + private Map listings = new ConcurrentHashMap<>(); + + // Next available listing ID + private int nextId = 1; + + // Indices for fast lookup + private Map> listingsBySeller = new ConcurrentHashMap<>(); + private Map> listingsByBidder = new ConcurrentHashMap<>(); + + // Pending notifications for offline players + private Map> pendingNotifications = new ConcurrentHashMap<>(); + + public AuctionController() { + Instance = this; + load(); + } + + // ==================== Listing Management ==================== + + /** + * Create a new auction listing + * @return The new listing, or null if creation failed + */ + public AuctionListing createListing(EntityPlayer seller, ItemStack item, + long startingPrice, long buyoutPrice, + EnumAuctionDuration duration) { + // Validate item + String validation = AuctionListing.validateItem(item); + if (validation != null) { + LogWriter.info(LOG_PREFIX + "Listing validation failed: " + validation); + return null; + } + + // Check seller's listing limit + int currentListings = getActiveListingsCount(seller.getUniqueID()); + int maxListings = getMaxListings(seller); + if (currentListings >= maxListings) { + return null; + } + + // Calculate and charge listing fee + AuctionListing listing = new AuctionListing( + seller.getUniqueID(), + seller.getCommandSenderName(), + item, + startingPrice, + buyoutPrice, + duration + ); + + long listingFee = listing.getListingFee(); + if (listingFee > 0) { + if (!CurrencyController.Instance.canAfford(seller, listingFee)) { + return null; + } + CurrencyController.Instance.withdraw(seller, listingFee); + } + + // Assign ID and store + listing.id = nextId++; + listings.put(listing.id, listing); + + // Update indices + addToSellerIndex(seller.getUniqueID(), listing.id); + + save(); + + // Log to CNPC+ + logEvent("LISTING_CREATED", String.format("ID=%d, Seller=%s, Item=%s x%d, StartPrice=%d, Buyout=%s", + listing.id, listing.sellerName, item.getDisplayName(), item.stackSize, + listing.startingPrice, listing.buyoutPrice > 0 ? listing.buyoutPrice : "None")); + + return listing; + } + + /** + * Get a listing by ID + */ + public AuctionListing getListing(int id) { + return listings.get(id); + } + + /** + * Get all active listings + */ + public List getActiveListings() { + processExpiredAuctions(); + return listings.values().stream() + .filter(AuctionListing::isActive) + .collect(Collectors.toList()); + } + + /** + * Search listings by item name + */ + public List searchListings(String query) { + String lowerQuery = query.toLowerCase(); + return getActiveListings().stream() + .filter(l -> l.item != null) + .filter(l -> l.item.getDisplayName().toLowerCase().contains(lowerQuery)) + .collect(Collectors.toList()); + } + + // ==================== Filtering & Sorting ==================== + + /** + * Get filtered and sorted auction listings. + * @param filter The filter criteria + * @return FilterResult containing matching listings and metadata + */ + public FilterResult getFilteredListings(AuctionFilter filter) { + processExpiredAuctions(); + + // Get all active listings + List results = listings.values().stream() + .filter(AuctionListing::isActive) + .filter(filter::matches) + .collect(Collectors.toList()); + + // Sort the results + sortListings(results, filter.sortOrder); + + // Calculate pagination + int totalResults = results.size(); + int totalPages = totalResults == 0 + ? 0 + : Math.max(1, (int) Math.ceil((double) totalResults / filter.pageSize)); + int currentPage = Math.max(0, filter.page); + if (totalPages > 0 && currentPage >= totalPages) { + currentPage = totalPages - 1; + } + int startIndex = currentPage * filter.pageSize; + int endIndex = Math.min(startIndex + filter.pageSize, totalResults); + + // Get the page slice + List pageResults; + if (startIndex >= totalResults) { + pageResults = new ArrayList<>(); + } else { + pageResults = new ArrayList<>(results.subList(startIndex, endIndex)); + } + + return new FilterResult(pageResults, totalResults, currentPage, totalPages); + } + + /** + * Sort listings according to the specified sort order + */ + public void sortListings(List listings, EnumAuctionSort sortOrder) { + if (listings == null || listings.isEmpty()) { + return; + } + + Comparator comparator; + + switch (sortOrder) { + case NEWEST_FIRST: + comparator = Comparator.comparingLong(l -> -l.listingTime); + break; + case OLDEST_FIRST: + comparator = Comparator.comparingLong(l -> l.listingTime); + break; + case PRICE_HIGH_TO_LOW: + comparator = Comparator.comparingLong((AuctionListing l) -> + -(l.currentBid > 0 ? l.currentBid : l.startingPrice)); + break; + case PRICE_LOW_TO_HIGH: + comparator = Comparator.comparingLong(l -> + l.currentBid > 0 ? l.currentBid : l.startingPrice); + break; + case ENDING_SOON: + comparator = Comparator.comparingLong(l -> l.expirationTime); + break; + case MOST_TIME_LEFT: + comparator = Comparator.comparingLong(l -> -l.expirationTime); + break; + case NAME_A_TO_Z: + comparator = Comparator.comparing(l -> getListingName(l).toLowerCase()); + break; + case NAME_Z_TO_A: + comparator = Comparator.comparing((AuctionListing l) -> + getListingName(l).toLowerCase()).reversed(); + break; + case MOST_BIDS: + comparator = Comparator.comparingInt(l -> -l.bidCount); + break; + case LEAST_BIDS: + comparator = Comparator.comparingInt(l -> l.bidCount); + break; + default: + comparator = Comparator.comparingLong(l -> l.expirationTime); + } + + listings.sort(comparator); + } + + /** + * Result container for filtered queries + */ + public static class FilterResult { + public final List listings; + public final int totalResults; + public final int currentPage; + public final int totalPages; + + public FilterResult(List listings, int totalResults, + int currentPage, int totalPages) { + this.listings = listings; + this.totalResults = totalResults; + this.currentPage = currentPage; + this.totalPages = totalPages; + } + + public boolean hasNextPage() { + return currentPage < totalPages - 1; + } + + public boolean hasPreviousPage() { + return currentPage > 0; + } + + public boolean isEmpty() { + return listings == null || listings.isEmpty(); + } + } + + /** + * Get all listings by a seller + */ + public List getListingsBySeller(UUID sellerUUID) { + List ids = listingsBySeller.get(sellerUUID); + if (ids == null) { + return new ArrayList<>(); + } + return ids.stream() + .map(listings::get) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + /** + * Get active listing count for a seller + */ + public int getActiveListingsCount(UUID sellerUUID) { + return (int) getListingsBySeller(sellerUUID).stream() + .filter(l -> l.status == EnumAuctionStatus.ACTIVE) + .count(); + } + + /** + * Get listings where player is the high bidder + */ + public List getListingsAsBidder(UUID bidderUUID) { + List ids = listingsByBidder.get(bidderUUID); + if (ids == null) { + return new ArrayList<>(); + } + return ids.stream() + .map(listings::get) + .filter(Objects::nonNull) + .filter(AuctionListing::isActive) + .filter(l -> bidderUUID.equals(l.highBidderUUID)) + .collect(Collectors.toList()); + } + + /** + * Get listings that need claiming by a player + */ + public List getClaimableListings(UUID playerUUID) { + List claimable = new ArrayList<>(); + + for (AuctionListing listing : listings.values()) { + // Seller can claim proceeds from sold items + if (listing.sellerUUID.equals(playerUUID) && + listing.status == EnumAuctionStatus.SOLD && + !listing.sellerClaimed) { + claimable.add(listing); + } + + // Seller can claim back cancelled/expired items + if (listing.sellerUUID.equals(playerUUID) && + (listing.status == EnumAuctionStatus.CANCELLED || + listing.status == EnumAuctionStatus.EXPIRED) && + !listing.sellerClaimed) { + claimable.add(listing); + } + + // Buyer can claim won items + if (listing.highBidderUUID != null && + listing.highBidderUUID.equals(playerUUID) && + listing.status == EnumAuctionStatus.SOLD && + !listing.buyerClaimed) { + claimable.add(listing); + } + } + + return claimable; + } + + // ==================== Bidding ==================== + + /** + * Place a bid on an auction + */ + public boolean placeBid(int listingId, EntityPlayer bidder, long amount) { + AuctionListing listing = listings.get(listingId); + if (listing == null) { + return false; + } + + if (!CurrencyController.Instance.canAfford(bidder, amount)) { + return false; + } + + // Store previous bidder for refund + UUID previousBidder = listing.highBidderUUID; + String previousBidderName = listing.highBidderName; + long previousBidAmount = listing.currentBid; + + if (!listing.placeBid(bidder.getUniqueID(), bidder.getCommandSenderName(), amount)) { + return false; + } + + CurrencyController.Instance.withdraw(bidder, amount); + + // Refund previous bidder + if (previousBidder != null) { + CurrencyController.Instance.addClaim(previousBidder, previousBidAmount, + "Auction Outbid", String.valueOf(listingId)); + + // Notify outbid player + notifyPlayer(previousBidder, EnumChatFormatting.RED + + "You have been outbid on " + EnumChatFormatting.WHITE + listing.item.getDisplayName() + + EnumChatFormatting.RED + "! New bid: " + formatCurrency(amount)); + + logEvent("OUTBID", String.format("ID=%d, OutbidPlayer=%s, PrevBid=%d, NewBid=%d", + listingId, previousBidderName, previousBidAmount, amount)); + } + + // Notify seller + notifyPlayer(listing.sellerUUID, EnumChatFormatting.AQUA + + bidder.getCommandSenderName() + " placed a bid of " + formatCurrency(amount) + + " on your " + listing.item.getDisplayName() + "!"); + + addToBidderIndex(bidder.getUniqueID(), listingId); + save(); + + logEvent("BID_PLACED", String.format("ID=%d, Bidder=%s, Amount=%d", + listingId, bidder.getCommandSenderName(), amount)); + + return true; + } + + /** + * Execute buyout on an auction + */ + public boolean buyout(int listingId, EntityPlayer buyer) { + AuctionListing listing = listings.get(listingId); + if (listing == null || listing.buyoutPrice <= 0) { + return false; + } + + if (!CurrencyController.Instance.canAfford(buyer, listing.buyoutPrice)) { + return false; + } + + UUID previousBidder = listing.highBidderUUID; + String previousBidderName = listing.highBidderName; + long previousBidAmount = listing.currentBid; + + if (!listing.buyout(buyer.getUniqueID(), buyer.getCommandSenderName())) { + return false; + } + + CurrencyController.Instance.withdraw(buyer, listing.buyoutPrice); + + // Refund previous bidder + if (previousBidder != null) { + CurrencyController.Instance.addClaim(previousBidder, previousBidAmount, + "Auction Outbid (Buyout)", String.valueOf(listingId)); + + notifyPlayer(previousBidder, EnumChatFormatting.RED + + "Your bid on " + EnumChatFormatting.WHITE + listing.item.getDisplayName() + + EnumChatFormatting.RED + " was outbid by a buyout. Your " + + formatCurrency(previousBidAmount) + " has been refunded."); + } + + addToBidderIndex(buyer.getUniqueID(), listingId); + save(); + + // Notify buyer and seller + notifyPlayer(buyer.getUniqueID(), EnumChatFormatting.GREEN + + "Buyout successful! Claim your " + listing.item.getDisplayName() + " from an Auctioneer."); + + notifyPlayer(listing.sellerUUID, EnumChatFormatting.GREEN + + "Your " + listing.item.getDisplayName() + " was bought out for " + + formatCurrency(listing.buyoutPrice) + "! Claim your proceeds."); + + logEvent("BUYOUT", String.format("ID=%d, Buyer=%s, Price=%d, Seller=%s", + listingId, buyer.getCommandSenderName(), listing.buyoutPrice, listing.sellerName)); + + return true; + } + + /** + * Cancel an auction listing + */ + public boolean cancelListing(int listingId, EntityPlayer requester, boolean forceCancel) { + AuctionListing listing = listings.get(listingId); + if (listing == null) { + return false; + } + + boolean byAdmin = !listing.sellerUUID.equals(requester.getUniqueID()); + if (byAdmin && !forceCancel) { + return false; + } + if (!forceCancel && listing.hasBids()) { + return false; + } + if (listing.status != EnumAuctionStatus.ACTIVE) { + return false; + } + + if (forceCancel && listing.hasBids() && listing.highBidderUUID != null) { + CurrencyController.Instance.addClaim(listing.highBidderUUID, listing.currentBid, + "Auction Cancelled", String.valueOf(listingId)); + notifyPlayer(listing.highBidderUUID, EnumChatFormatting.RED + + "Your bid on " + EnumChatFormatting.WHITE + listing.item.getDisplayName() + + EnumChatFormatting.RED + " was cancelled. Your " + + formatCurrency(listing.currentBid) + " has been refunded."); + } + + listing.status = EnumAuctionStatus.CANCELLED; + + save(); + + if (byAdmin) { + notifyPlayer(listing.sellerUUID, EnumChatFormatting.RED + + "Your auction for " + listing.item.getDisplayName() + + " was cancelled by an administrator."); + } + + logEvent("CANCELLED", String.format("ID=%d, CancelledBy=%s, ByAdmin=%b", + listingId, requester.getCommandSenderName(), byAdmin)); + + return true; + } + + // ==================== Claiming ==================== + + /** + * Claim seller proceeds from a sold auction + */ + public boolean claimSellerProceeds(int listingId, EntityPlayer seller) { + AuctionListing listing = listings.get(listingId); + if (listing == null || !listing.sellerUUID.equals(seller.getUniqueID()) || + listing.status != EnumAuctionStatus.SOLD || listing.sellerClaimed) { + return false; + } + + long proceeds = listing.getSellerProceeds(); + CurrencyController.Instance.deposit(seller, proceeds); + + listing.sellerClaimed = true; + checkAndMarkClaimed(listing); + save(); + + logEvent("PROCEEDS_CLAIMED", String.format("ID=%d, Seller=%s, Amount=%d", + listingId, seller.getCommandSenderName(), proceeds)); + + return true; + } + + /** + * Claim item from won auction + */ + public ItemStack claimBuyerItem(int listingId, EntityPlayer buyer) { + AuctionListing listing = listings.get(listingId); + if (listing == null || listing.highBidderUUID == null || + !listing.highBidderUUID.equals(buyer.getUniqueID()) || + listing.status != EnumAuctionStatus.SOLD || listing.buyerClaimed) { + return null; + } + + listing.buyerClaimed = true; + checkAndMarkClaimed(listing); + save(); + + logEvent("ITEM_CLAIMED", String.format("ID=%d, Buyer=%s, Item=%s", + listingId, buyer.getCommandSenderName(), listing.item.getDisplayName())); + + return listing.item.copy(); + } + + /** + * Claim item from cancelled or expired auction + */ + public ItemStack claimExpiredItem(int listingId, EntityPlayer seller) { + AuctionListing listing = listings.get(listingId); + if (listing == null || !listing.sellerUUID.equals(seller.getUniqueID()) || + (listing.status != EnumAuctionStatus.CANCELLED && listing.status != EnumAuctionStatus.EXPIRED) || + listing.sellerClaimed) { + return null; + } + + listing.sellerClaimed = true; + listing.status = EnumAuctionStatus.CLAIMED; + save(); + + logEvent("ITEM_RECLAIMED", String.format("ID=%d, Seller=%s, Item=%s", + listingId, seller.getCommandSenderName(), listing.item.getDisplayName())); + + return listing.item.copy(); + } + + private void checkAndMarkClaimed(AuctionListing listing) { + if (listing.status == EnumAuctionStatus.SOLD && + listing.sellerClaimed && listing.buyerClaimed) { + listing.status = EnumAuctionStatus.CLAIMED; + } + } + + // ==================== Expiration Processing ==================== + + /** + * Process all expired auctions + */ + public void processExpiredAuctions() { + boolean changed = false; + + for (AuctionListing listing : listings.values()) { + if (listing.status == EnumAuctionStatus.ACTIVE && listing.isExpired()) { + listing.finalize(); + changed = true; + + if (listing.status == EnumAuctionStatus.SOLD) { + // Notify winner and seller + notifyPlayer(listing.highBidderUUID, EnumChatFormatting.GREEN + + "You won the auction for " + listing.item.getDisplayName() + + " for " + formatCurrency(listing.currentBid) + "! Claim your item."); + + notifyPlayer(listing.sellerUUID, EnumChatFormatting.GREEN + + "Your " + listing.item.getDisplayName() + " sold for " + + formatCurrency(listing.currentBid) + "! Claim your proceeds."); + + logEvent("AUCTION_SOLD", String.format("ID=%d, Winner=%s, Price=%d, Seller=%s", + listing.id, listing.highBidderName, listing.currentBid, listing.sellerName)); + } else { + notifyPlayer(listing.sellerUUID, EnumChatFormatting.GRAY + + "Your auction for " + listing.item.getDisplayName() + + " has expired with no bids. Claim your item."); + + logEvent("AUCTION_EXPIRED", String.format("ID=%d, Item=%s, Seller=%s", + listing.id, listing.item.getDisplayName(), listing.sellerName)); + } + } + } + + if (changed) { + save(); + } + } + + /** + * Clean up old claimed listings + */ + public void cleanupOldListings() { + long claimExpirationMs = ConfigMarket.ClaimExpirationDays * 24L * 60L * 60L * 1000L; + if (claimExpirationMs <= 0) return; + + long cutoffTime = System.currentTimeMillis() - claimExpirationMs; + List toRemove = new ArrayList<>(); + + for (AuctionListing listing : listings.values()) { + if (listing.status == EnumAuctionStatus.CLAIMED && + listing.expirationTime < cutoffTime) { + toRemove.add(listing.id); + } + } + + for (int id : toRemove) { + AuctionListing removed = listings.remove(id); + if (removed != null) { + removeFromSellerIndex(removed.sellerUUID, id); + if (removed.highBidderUUID != null) { + removeFromBidderIndex(removed.highBidderUUID, id); + } + } + } + + if (!toRemove.isEmpty()) { + save(); + logEvent("CLEANUP", "Removed " + toRemove.size() + " old listings"); + } + } + + // ==================== Notifications ==================== + + /** + * Send notification to player (or queue if offline) + */ + private void notifyPlayer(UUID playerUUID, String message) { + if (playerUUID == null) return; + + EntityPlayerMP player = getOnlinePlayer(playerUUID); + String fullMessage = EnumChatFormatting.YELLOW + "[Auction] " + message; + + if (player != null) { + player.addChatMessage(new ChatComponentText(fullMessage)); + } else { + pendingNotifications.computeIfAbsent(playerUUID, k -> new ArrayList<>()).add(fullMessage); + // Limit queue size + List queue = pendingNotifications.get(playerUUID); + while (queue.size() > 50) { + queue.remove(0); + } + } + } + + /** + * Send pending notifications on player login + */ + public void onPlayerLogin(EntityPlayerMP player) { + UUID uuid = player.getUniqueID(); + + List notifications = pendingNotifications.remove(uuid); + if (notifications != null && !notifications.isEmpty()) { + player.addChatMessage(new ChatComponentText( + EnumChatFormatting.YELLOW + "[Auction] " + EnumChatFormatting.WHITE + + "You have " + notifications.size() + " auction notification(s):")); + + for (String msg : notifications) { + player.addChatMessage(new ChatComponentText(msg)); + } + } + + // Check claimable items + int claimableCount = getClaimableListings(uuid).size(); + if (claimableCount > 0) { + player.addChatMessage(new ChatComponentText( + EnumChatFormatting.YELLOW + "[Auction] " + EnumChatFormatting.GREEN + + "You have " + claimableCount + " item(s) waiting to be claimed!")); + } + } + + private EntityPlayerMP getOnlinePlayer(UUID uuid) { + if (CustomNpcs.getServer() == null) return null; + + for (Object obj : CustomNpcs.getServer().getConfigurationManager().playerEntityList) { + EntityPlayerMP player = (EntityPlayerMP) obj; + if (player.getUniqueID().equals(uuid)) { + return player; + } + } + return null; + } + + // ==================== Index Management ==================== + + private void addToSellerIndex(UUID seller, int listingId) { + listingsBySeller.computeIfAbsent(seller, k -> new ArrayList<>()).add(listingId); + } + + private void removeFromSellerIndex(UUID seller, int listingId) { + List ids = listingsBySeller.get(seller); + if (ids != null) { + ids.remove(Integer.valueOf(listingId)); + } + } + + private void addToBidderIndex(UUID bidder, int listingId) { + listingsByBidder.computeIfAbsent(bidder, k -> new ArrayList<>()).add(listingId); + } + + private void removeFromBidderIndex(UUID bidder, int listingId) { + List ids = listingsByBidder.get(bidder); + if (ids != null) { + ids.remove(Integer.valueOf(listingId)); + } + } + + private void rebuildIndices() { + listingsBySeller.clear(); + listingsByBidder.clear(); + + for (AuctionListing listing : listings.values()) { + addToSellerIndex(listing.sellerUUID, listing.id); + if (listing.highBidderUUID != null) { + addToBidderIndex(listing.highBidderUUID, listing.id); + } + } + } + + // ==================== Helpers ==================== + + public int getMaxListings(EntityPlayer player) { + return ConfigMarket.DefaultMaxListings; + } + + private String formatCurrency(long amount) { + return String.format("%,d %s", amount, ConfigMarket.CurrencyName); + } + + private void logEvent(String event, String details) { + LogWriter.info(LOG_PREFIX + event + ": " + details); + } + + private String getListingName(AuctionListing listing) { + if (listing == null || listing.item == null) { + return ""; + } + return listing.item.getDisplayName(); + } + + // ==================== Persistence ==================== + + public void save() { + File saveDir = CustomNpcs.getWorldSaveDirectory(); + if (saveDir == null) return; + + try { + NBTTagCompound compound = new NBTTagCompound(); + compound.setInteger("NextId", nextId); + + NBTTagList listingList = new NBTTagList(); + for (AuctionListing listing : listings.values()) { + listingList.appendTag(listing.writeToNBT(new NBTTagCompound())); + } + compound.setTag("Listings", listingList); + + File file = new File(saveDir, "auctions.dat"); + File backup = new File(saveDir, "auctions.dat_old"); + + if (file.exists()) { + if (backup.exists()) backup.delete(); + file.renameTo(backup); + } + + file = new File(saveDir, "auctions.dat"); + FileOutputStream fos = new FileOutputStream(file); + CompressedStreamTools.writeCompressed(compound, fos); + fos.close(); + + } catch (Exception e) { + LogWriter.error(LOG_PREFIX + "Error saving auctions", e); + } + } + + public void load() { + File saveDir = CustomNpcs.getWorldSaveDirectory(); + if (saveDir == null) return; + + listings.clear(); + + try { + File file = new File(saveDir, "auctions.dat"); + if (!file.exists()) { + file = new File(saveDir, "auctions.dat_old"); + if (!file.exists()) return; + } + + FileInputStream fis = new FileInputStream(file); + NBTTagCompound compound = CompressedStreamTools.readCompressed(fis); + fis.close(); + + nextId = compound.getInteger("NextId"); + if (nextId < 1) nextId = 1; + + NBTTagList listingList = compound.getTagList("Listings", 10); + for (int i = 0; i < listingList.tagCount(); i++) { + AuctionListing listing = new AuctionListing(); + listing.readFromNBT(listingList.getCompoundTagAt(i)); + listings.put(listing.id, listing); + } + + rebuildIndices(); + + logEvent("SYSTEM_STARTUP", String.format("Loaded %d listings, %d active", + listings.size(), getActiveListingCount())); + + } catch (Exception e) { + LogWriter.error(LOG_PREFIX + "Error loading auctions", e); + } + } + + // ==================== Statistics ==================== + + public int getActiveListingCount() { + return (int) listings.values().stream() + .filter(l -> l.status == EnumAuctionStatus.ACTIVE) + .count(); + } + + public int getTotalListingCount() { + return listings.size(); + } +} diff --git a/src/main/java/noppes/npcs/controllers/CurrencyController.java b/src/main/java/noppes/npcs/controllers/CurrencyController.java new file mode 100644 index 000000000..16d6c99f4 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/CurrencyController.java @@ -0,0 +1,400 @@ +package noppes.npcs.controllers; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.CustomNpcs; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.controllers.data.PlayerData; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.*; + +/** + * Controller for managing currency operations including: + * - Claims system (for auction refunds, NPC payments, etc.) + * - Transaction history + * - Currency administration + * + * Delegates actual balance operations to VaultHelper. + */ +public class CurrencyController { + private static final Logger logger = LogManager.getLogger(CustomNpcs.class); + + public static CurrencyController Instance; + + // Pending claims per player UUID - claims that can be collected + private Map> pendingClaims = new HashMap<>(); + + // File path for persistence + private String filePath = ""; + + public CurrencyController() { + Instance = this; + load(); + } + + /** + * Get player's current balance + */ + public long getBalance(EntityPlayer player) { + return VaultHelper.Instance.getBalance(player); + } + + /** + * Deposit currency directly to player's balance + */ + public boolean deposit(EntityPlayer player, long amount) { + return VaultHelper.Instance.deposit(player, amount); + } + + /** + * Withdraw currency from player's balance + */ + public boolean withdraw(EntityPlayer player, long amount) { + return VaultHelper.Instance.withdraw(player, amount); + } + + /** + * Check if player can afford an amount + */ + public boolean canAfford(EntityPlayer player, long amount) { + return VaultHelper.Instance.canAfford(player, amount); + } + + /** + * Transfer currency between players + */ + public boolean transfer(EntityPlayer from, EntityPlayer to, long amount) { + return VaultHelper.Instance.transfer(from, to, amount); + } + + /** + * Format amount for display + */ + public String formatAmount(long amount) { + return VaultHelper.Instance.formatAmount(amount); + } + + // ==================== CLAIMS SYSTEM ==================== + + /** + * Add a claim for a player (e.g., auction refund, NPC payment) + * Claims can be collected later by the player. + * + * @param playerUUID The player's UUID + * @param amount The amount to claim + * @param source Description of where this claim came from + * @param sourceId Optional ID of the source (e.g., auction ID) + */ + public void addClaim(UUID playerUUID, long amount, String source, String sourceId) { + if (amount <= 0) { + return; + } + + CurrencyClaim claim = new CurrencyClaim(); + claim.amount = amount; + claim.source = source; + claim.sourceId = sourceId; + claim.timestamp = System.currentTimeMillis(); + claim.expiresAt = claim.timestamp + (ConfigMarket.ClaimExpirationDays * 24L * 60L * 60L * 1000L); + + List claims = pendingClaims.computeIfAbsent(playerUUID, k -> new ArrayList<>()); + claims.add(claim); + + save(); + logger.info("Added claim of {} for player {} from {}", amount, playerUUID, source); + } + + /** + * Get all pending claims for a player + */ + public List getPendingClaims(EntityPlayer player) { + return getPendingClaims(player.getUniqueID()); + } + + /** + * Get all pending claims for a player by UUID + */ + public List getPendingClaims(UUID playerUUID) { + List claims = pendingClaims.get(playerUUID); + if (claims == null) { + return new ArrayList<>(); + } + + // Filter out expired claims + long now = System.currentTimeMillis(); + claims.removeIf(claim -> claim.expiresAt > 0 && claim.expiresAt < now); + + return new ArrayList<>(claims); + } + + /** + * Get total pending claim amount for a player + */ + public long getTotalPendingClaims(EntityPlayer player) { + return getTotalPendingClaims(player.getUniqueID()); + } + + /** + * Get total pending claim amount for a player by UUID + */ + public long getTotalPendingClaims(UUID playerUUID) { + List claims = getPendingClaims(playerUUID); + long total = 0; + for (CurrencyClaim claim : claims) { + total += claim.amount; + } + return total; + } + + /** + * Claim all pending claims for a player + * @return Amount successfully claimed + */ + public long claimAll(EntityPlayer player) { + List claims = getPendingClaims(player); + if (claims.isEmpty()) { + return 0; + } + + long totalClaimed = 0; + + for (CurrencyClaim claim : claims) { + if (deposit(player, claim.amount)) { + totalClaimed += claim.amount; + } + } + + // Clear claims after successful deposit + pendingClaims.remove(player.getUniqueID()); + save(); + + return totalClaimed; + } + + /** + * Claim a specific claim by index + * @return true if successful + */ + public boolean claimSingle(EntityPlayer player, int claimIndex) { + List claims = pendingClaims.get(player.getUniqueID()); + if (claims == null || claimIndex < 0 || claimIndex >= claims.size()) { + return false; + } + + CurrencyClaim claim = claims.get(claimIndex); + if (deposit(player, claim.amount)) { + claims.remove(claimIndex); + if (claims.isEmpty()) { + pendingClaims.remove(player.getUniqueID()); + } + save(); + return true; + } + + return false; + } + + /** + * Check if player has any pending claims + */ + public boolean hasPendingClaims(EntityPlayer player) { + return !getPendingClaims(player).isEmpty(); + } + + // ==================== PERSISTENCE ==================== + + public void load() { + File saveDir = CustomNpcs.getWorldSaveDirectory(); + if (saveDir == null) { + return; + } + + filePath = saveDir.getAbsolutePath(); + pendingClaims.clear(); + + try { + File file = new File(saveDir, "currency_claims.dat"); + if (file.exists()) { + loadFromFile(file); + } + } catch (Exception e) { + logger.error("Error loading currency claims", e); + try { + File file = new File(saveDir, "currency_claims.dat_old"); + if (file.exists()) { + loadFromFile(file); + } + } catch (Exception ee) { + logger.error("Error loading backup currency claims", ee); + } + } + + // Clean expired claims + cleanExpiredClaims(); + } + + private void loadFromFile(File file) throws Exception { + FileInputStream fis = new FileInputStream(file); + NBTTagCompound compound = CompressedStreamTools.readCompressed(fis); + fis.close(); + + NBTTagList claimsList = compound.getTagList("Claims", 10); + for (int i = 0; i < claimsList.tagCount(); i++) { + NBTTagCompound playerCompound = claimsList.getCompoundTagAt(i); + UUID playerUUID = UUID.fromString(playerCompound.getString("UUID")); + + List playerClaims = new ArrayList<>(); + NBTTagList playerClaimsList = playerCompound.getTagList("PlayerClaims", 10); + for (int j = 0; j < playerClaimsList.tagCount(); j++) { + NBTTagCompound claimCompound = playerClaimsList.getCompoundTagAt(j); + CurrencyClaim claim = new CurrencyClaim(); + claim.readFromNBT(claimCompound); + playerClaims.add(claim); + } + + if (!playerClaims.isEmpty()) { + pendingClaims.put(playerUUID, playerClaims); + } + } + + logger.info("Loaded {} player claim records", pendingClaims.size()); + } + + public void save() { + File saveDir = CustomNpcs.getWorldSaveDirectory(); + if (saveDir == null) { + return; + } + + try { + File file = new File(saveDir, "currency_claims.dat"); + File backup = new File(saveDir, "currency_claims.dat_old"); + + if (file.exists()) { + if (backup.exists()) { + backup.delete(); + } + file.renameTo(backup); + } + + NBTTagCompound compound = new NBTTagCompound(); + NBTTagList claimsList = new NBTTagList(); + + for (Map.Entry> entry : pendingClaims.entrySet()) { + if (entry.getValue().isEmpty()) { + continue; + } + + NBTTagCompound playerCompound = new NBTTagCompound(); + playerCompound.setString("UUID", entry.getKey().toString()); + + NBTTagList playerClaimsList = new NBTTagList(); + for (CurrencyClaim claim : entry.getValue()) { + NBTTagCompound claimCompound = new NBTTagCompound(); + claim.writeToNBT(claimCompound); + playerClaimsList.appendTag(claimCompound); + } + playerCompound.setTag("PlayerClaims", playerClaimsList); + + claimsList.appendTag(playerCompound); + } + + compound.setTag("Claims", claimsList); + + file = new File(saveDir, "currency_claims.dat"); + FileOutputStream fos = new FileOutputStream(file); + CompressedStreamTools.writeCompressed(compound, fos); + fos.close(); + } catch (Exception e) { + logger.error("Error saving currency claims", e); + } + } + + /** + * Clean up expired claims + */ + public void cleanExpiredClaims() { + long now = System.currentTimeMillis(); + boolean changed = false; + + Iterator>> it = pendingClaims.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry> entry = it.next(); + List claims = entry.getValue(); + + int before = claims.size(); + claims.removeIf(claim -> claim.expiresAt > 0 && claim.expiresAt < now); + + if (claims.size() != before) { + changed = true; + } + + if (claims.isEmpty()) { + it.remove(); + } + } + + if (changed) { + save(); + } + } + + // ==================== CLAIM DATA CLASS ==================== + + public static class CurrencyClaim { + public long amount; + public String source; // e.g., "Auction Refund", "NPC Payment", "Quest Reward" + public String sourceId; // e.g., auction ID + public long timestamp; // When the claim was created + public long expiresAt; // When the claim expires (0 = never) + + public void writeToNBT(NBTTagCompound compound) { + compound.setLong("Amount", amount); + compound.setString("Source", source != null ? source : ""); + compound.setString("SourceId", sourceId != null ? sourceId : ""); + compound.setLong("Timestamp", timestamp); + compound.setLong("ExpiresAt", expiresAt); + } + + public void readFromNBT(NBTTagCompound compound) { + amount = compound.getLong("Amount"); + source = compound.getString("Source"); + sourceId = compound.getString("SourceId"); + timestamp = compound.getLong("Timestamp"); + expiresAt = compound.getLong("ExpiresAt"); + } + + /** + * Get formatted time remaining until expiration + */ + public String getTimeRemaining() { + if (expiresAt <= 0) { + return "Never"; + } + + long remaining = expiresAt - System.currentTimeMillis(); + if (remaining <= 0) { + return "Expired"; + } + + long days = remaining / (24L * 60L * 60L * 1000L); + long hours = (remaining % (24L * 60L * 60L * 1000L)) / (60L * 60L * 1000L); + + if (days > 0) { + return days + " days, " + hours + " hours"; + } else if (hours > 0) { + return hours + " hours"; + } else { + long minutes = remaining / (60L * 1000L); + return minutes + " minutes"; + } + } + } +} diff --git a/src/main/java/noppes/npcs/controllers/VaultHelper.java b/src/main/java/noppes/npcs/controllers/VaultHelper.java new file mode 100644 index 000000000..54b9235ef --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/VaultHelper.java @@ -0,0 +1,272 @@ +package noppes.npcs.controllers; + +import net.minecraft.entity.player.EntityPlayer; +import noppes.npcs.CustomNpcs; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.controllers.PlayerDataController; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.lang.reflect.Method; + +/** + * Helper class for VaultAPI integration on Bukkit hybrid servers. + * Uses reflection to integrate with Vault when available. + * Falls back to internal currency system when Vault is not present. + */ +public class VaultHelper { + private static final Logger logger = LogManager.getLogger(CustomNpcs.class); + + public static VaultHelper Instance; + + // Vault reflection references + private boolean vaultAvailable = false; + private Object economy = null; + private Method getBalance; + private Method depositPlayer; + private Method withdrawPlayer; + private Method hasAccount; + private Method createPlayerAccount; + private Method responseSuccess; + + // Bukkit references for getting offline player + private Class bukkitClass; + private Method getOfflinePlayer; + + public VaultHelper() { + Instance = this; + + if (!ConfigMarket.UseVaultIfAvailable) { + logger.info("Vault integration disabled by config"); + return; + } + + try { + // Check for Bukkit first + bukkitClass = Class.forName("org.bukkit.Bukkit"); + getOfflinePlayer = bukkitClass.getMethod("getOfflinePlayer", String.class); + + // Check for Vault + Class vaultClass = Class.forName("net.milkbowl.vault.economy.Economy"); + + // Get the Economy service from Bukkit's ServicesManager + Method getServicesManager = bukkitClass.getMethod("getServicesManager"); + Object servicesManager = getServicesManager.invoke(null); + + Method getRegistration = servicesManager.getClass().getMethod("getRegistration", Class.class); + Object registration = getRegistration.invoke(servicesManager, vaultClass); + + if (registration != null) { + Method getProvider = registration.getClass().getMethod("getProvider"); + economy = getProvider.invoke(registration); + + if (economy != null) { + // Get Economy methods - using OfflinePlayer versions for broader compatibility + Class offlinePlayerClass = Class.forName("org.bukkit.OfflinePlayer"); + getBalance = economy.getClass().getMethod("getBalance", offlinePlayerClass); + depositPlayer = economy.getClass().getMethod("depositPlayer", offlinePlayerClass, double.class); + withdrawPlayer = economy.getClass().getMethod("withdrawPlayer", offlinePlayerClass, double.class); + hasAccount = economy.getClass().getMethod("hasAccount", offlinePlayerClass); + createPlayerAccount = economy.getClass().getMethod("createPlayerAccount", offlinePlayerClass); + + // EconomyResponse.transactionSuccess() method + Class economyResponseClass = Class.forName("net.milkbowl.vault.economy.EconomyResponse"); + responseSuccess = economyResponseClass.getField("transactionSuccess").getClass().getMethod("booleanValue"); + + vaultAvailable = true; + logger.info("Vault Economy integration enabled - using external economy"); + } + } + + if (!vaultAvailable) { + logger.info("Vault found but no Economy provider registered - using internal currency"); + } + } catch (ClassNotFoundException e) { + // Vault not present - use internal currency + logger.info("Vault not found - using internal currency system"); + } catch (Exception e) { + logger.warn("Error initializing Vault integration - using internal currency: " + e.getMessage()); + } + } + + /** + * Check if Vault economy is available and enabled + */ + public boolean isVaultEnabled() { + return vaultAvailable && ConfigMarket.UseVaultIfAvailable; + } + + /** + * Get player's balance + * Uses Vault if available, otherwise internal currency + */ + public long getBalance(EntityPlayer player) { + if (isVaultEnabled()) { + try { + Object offlinePlayer = getOfflinePlayer.invoke(null, player.getCommandSenderName()); + Double balance = (Double) getBalance.invoke(economy, offlinePlayer); + return balance.longValue(); + } catch (Exception e) { + logger.warn("Vault getBalance failed, falling back to internal: " + e.getMessage()); + } + } + + // Fall back to internal currency + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + return data.currencyData.getBalance(); + } + + /** + * Deposit currency to player's balance + * Uses Vault if available, otherwise internal currency + * @return true if successful + */ + public boolean deposit(EntityPlayer player, long amount) { + if (amount <= 0) { + return false; + } + + if (isVaultEnabled()) { + try { + Object offlinePlayer = getOfflinePlayer.invoke(null, player.getCommandSenderName()); + + // Ensure account exists + Boolean hasAcc = (Boolean) hasAccount.invoke(economy, offlinePlayer); + if (!hasAcc) { + createPlayerAccount.invoke(economy, offlinePlayer); + } + + Object response = depositPlayer.invoke(economy, offlinePlayer, (double) amount); + // Check if transaction succeeded by checking the transactionSuccess field + Boolean success = (Boolean) response.getClass().getField("transactionSuccess").get(response); + + if (success) { + // Also update internal tracking for statistics + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + data.currencyData.setBalance(getBalance(player)); + return true; + } + return false; + } catch (Exception e) { + logger.warn("Vault deposit failed, falling back to internal: " + e.getMessage()); + } + } + + // Fall back to internal currency + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + boolean success = data.currencyData.deposit(amount); + if (success) { + data.save(); + } + return success; + } + + /** + * Withdraw currency from player's balance + * Uses Vault if available, otherwise internal currency + * @return true if successful + */ + public boolean withdraw(EntityPlayer player, long amount) { + if (amount <= 0) { + return false; + } + + if (isVaultEnabled()) { + try { + Object offlinePlayer = getOfflinePlayer.invoke(null, player.getCommandSenderName()); + + // Check if player has enough + Double currentBalance = (Double) getBalance.invoke(economy, offlinePlayer); + if (currentBalance < amount) { + return false; + } + + Object response = withdrawPlayer.invoke(economy, offlinePlayer, (double) amount); + Boolean success = (Boolean) response.getClass().getField("transactionSuccess").get(response); + + if (success) { + // Also update internal tracking for statistics + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + data.currencyData.setBalance(getBalance(player)); + return true; + } + return false; + } catch (Exception e) { + logger.warn("Vault withdraw failed, falling back to internal: " + e.getMessage()); + } + } + + // Fall back to internal currency + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + boolean success = data.currencyData.withdraw(amount); + if (success) { + data.save(); + } + return success; + } + + /** + * Check if player can afford an amount + */ + public boolean canAfford(EntityPlayer player, long amount) { + return getBalance(player) >= amount; + } + + /** + * Transfer currency from one player to another + * @return true if successful + */ + public boolean transfer(EntityPlayer from, EntityPlayer to, long amount) { + if (amount <= 0) { + return false; + } + + if (!canAfford(from, amount)) { + return false; + } + + // Withdraw from sender first + if (!withdraw(from, amount)) { + return false; + } + + // Deposit to receiver + if (!deposit(to, amount)) { + // Rollback - deposit back to sender + deposit(from, amount); + return false; + } + + return true; + } + + /** + * Set player's balance directly (admin operation) + * Only works with internal currency - Vault manages its own balances + */ + public void setBalance(EntityPlayer player, long amount) { + if (isVaultEnabled()) { + logger.warn("Cannot set balance directly when using Vault - use Vault's economy commands"); + return; + } + + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + data.currencyData.setBalance(amount); + data.save(); + } + + /** + * Format an amount for display with currency name + */ + public String formatAmount(long amount) { + return String.format("%,d %s", amount, ConfigMarket.CurrencyName); + } + + /** + * Get the currency name + */ + public String getCurrencyName() { + return ConfigMarket.CurrencyName; + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/AuctionFilter.java b/src/main/java/noppes/npcs/controllers/data/AuctionFilter.java new file mode 100644 index 000000000..176896fae --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/AuctionFilter.java @@ -0,0 +1,226 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.constants.EnumAuctionSort; + +/** + * Filter/search criteria for auction listings. + * Used to query the auction controller with specific criteria. + */ +public class AuctionFilter { + + /** Search text to match against item names */ + public String searchText = ""; + + /** How to sort results */ + public EnumAuctionSort sortOrder = EnumAuctionSort.ENDING_SOON; + + /** Minimum current bid/price filter */ + public long minPrice = 0; + + /** Maximum current bid/price filter (0 = no max) */ + public long maxPrice = 0; + + /** Only show listings with buyout option */ + public boolean buyoutOnly = false; + + /** Only show listings without any bids yet */ + public boolean noBidsOnly = false; + + /** Page number for pagination (0-indexed) */ + public int page = 0; + + /** Items per page */ + public int pageSize = 20; + + /** Filter by specific seller UUID string (empty = all sellers) */ + public String sellerUUID = ""; + + /** Filter by specific seller name (partial match, empty = all) */ + public String sellerName = ""; + + public AuctionFilter() { + } + + /** + * Create a filter with search text + */ + public static AuctionFilter search(String text) { + AuctionFilter filter = new AuctionFilter(); + filter.searchText = text != null ? text : ""; + return filter; + } + + /** + * Create a filter for a specific seller + */ + public static AuctionFilter seller(String sellerUUID) { + AuctionFilter filter = new AuctionFilter(); + filter.sellerUUID = sellerUUID != null ? sellerUUID : ""; + return filter; + } + + // Builder-style methods for chaining + + public AuctionFilter withSearch(String text) { + this.searchText = text != null ? text : ""; + return this; + } + + public AuctionFilter withSort(EnumAuctionSort sort) { + this.sortOrder = sort; + return this; + } + + public AuctionFilter withPriceRange(long min, long max) { + this.minPrice = min; + this.maxPrice = max; + return this; + } + + public AuctionFilter withBuyoutOnly(boolean buyoutOnly) { + this.buyoutOnly = buyoutOnly; + return this; + } + + public AuctionFilter withNoBidsOnly(boolean noBidsOnly) { + this.noBidsOnly = noBidsOnly; + return this; + } + + public AuctionFilter withPage(int page, int pageSize) { + this.page = Math.max(0, page); + this.pageSize = Math.max(1, Math.min(100, pageSize)); + return this; + } + + public AuctionFilter withSeller(String sellerUUID, String sellerName) { + this.sellerUUID = sellerUUID != null ? sellerUUID : ""; + this.sellerName = sellerName != null ? sellerName : ""; + return this; + } + + /** + * Check if a listing matches this filter's criteria + */ + public boolean matches(AuctionListing listing) { + if (listing == null) { + return false; + } + if (listing.item == null) { + return false; + } + + // Search text filter (case-insensitive) + if (!searchText.isEmpty()) { + String lowerSearch = searchText.toLowerCase(); + String itemName = listing.item.getDisplayName().toLowerCase(); + if (!itemName.contains(lowerSearch)) { + return false; + } + } + + // Price range filter (uses current bid or starting price) + long price = listing.currentBid > 0 ? listing.currentBid : listing.startingPrice; + if (minPrice > 0 && price < minPrice) { + return false; + } + if (maxPrice > 0 && price > maxPrice) { + return false; + } + + // Buyout only filter + if (buyoutOnly && listing.buyoutPrice <= 0) { + return false; + } + + // No bids only filter + if (noBidsOnly && listing.hasBids()) { + return false; + } + + // Seller UUID filter + if (!sellerUUID.isEmpty() && !listing.sellerUUID.toString().equals(sellerUUID)) { + return false; + } + + // Seller name filter (partial match) + if (!sellerName.isEmpty()) { + String lowerName = sellerName.toLowerCase(); + if (!listing.sellerName.toLowerCase().contains(lowerName)) { + return false; + } + } + + return true; + } + + /** + * Reset all filters to defaults + */ + public void reset() { + searchText = ""; + sortOrder = EnumAuctionSort.ENDING_SOON; + minPrice = 0; + maxPrice = 0; + buyoutOnly = false; + noBidsOnly = false; + page = 0; + sellerUUID = ""; + sellerName = ""; + } + + /** + * Write filter to NBT for network transmission + */ + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setString("SearchText", searchText); + compound.setInteger("SortOrder", sortOrder.ordinal()); + compound.setLong("MinPrice", minPrice); + compound.setLong("MaxPrice", maxPrice); + compound.setBoolean("BuyoutOnly", buyoutOnly); + compound.setBoolean("NoBidsOnly", noBidsOnly); + compound.setInteger("Page", page); + compound.setInteger("PageSize", pageSize); + compound.setString("SellerUUID", sellerUUID); + compound.setString("SellerName", sellerName); + return compound; + } + + /** + * Read filter from NBT + */ + public void readFromNBT(NBTTagCompound compound) { + searchText = compound.getString("SearchText"); + + int sortOrdinal = compound.getInteger("SortOrder"); + if (sortOrdinal >= 0 && sortOrdinal < EnumAuctionSort.values().length) { + sortOrder = EnumAuctionSort.values()[sortOrdinal]; + } + + minPrice = compound.getLong("MinPrice"); + maxPrice = compound.getLong("MaxPrice"); + buyoutOnly = compound.getBoolean("BuyoutOnly"); + noBidsOnly = compound.getBoolean("NoBidsOnly"); + page = Math.max(0, compound.getInteger("Page")); + pageSize = compound.getInteger("PageSize"); + if (pageSize <= 0) { + pageSize = 20; + } else { + pageSize = Math.min(100, pageSize); + } + sellerUUID = compound.getString("SellerUUID"); + sellerName = compound.getString("SellerName"); + } + + @Override + public String toString() { + return "AuctionFilter{" + + "search='" + searchText + '\'' + + ", sort=" + sortOrder + + ", price=" + minPrice + "-" + maxPrice + + ", buyoutOnly=" + buyoutOnly + + ", page=" + page + + '}'; + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/AuctionListing.java b/src/main/java/noppes/npcs/controllers/data/AuctionListing.java new file mode 100644 index 000000000..5366e367b --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/AuctionListing.java @@ -0,0 +1,397 @@ +package noppes.npcs.controllers.data; + +import kamkeel.npcs.controllers.data.attribute.ItemTradeAttribute; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.constants.EnumAuctionDuration; +import noppes.npcs.constants.EnumAuctionStatus; +import noppes.npcs.controllers.AuctionBlacklist; + +import java.util.UUID; + +/** + * Represents a single auction listing. + * Contains all data about the item, seller, bidding, and timing. + */ +public class AuctionListing { + // Unique identifier + public int id; + + // Seller info + public UUID sellerUUID; + public String sellerName; + + // Item being sold + public ItemStack item; + + // Pricing + public long startingPrice; + public long buyoutPrice; // 0 = no buyout option + public long currentBid; + + // Current high bidder + public UUID highBidderUUID; + public String highBidderName; + + // Previous bidder (for refund notifications) + public UUID previousBidderUUID; + public String previousBidderName; + public long previousBidAmount; + + // Timing + public long listingTime; // When the auction was created + public long expirationTime; // When the auction ends + public EnumAuctionDuration duration; + + // Status + public EnumAuctionStatus status = EnumAuctionStatus.ACTIVE; + + // Claim tracking + public boolean sellerClaimed = false; // Has seller claimed their proceeds? + public boolean buyerClaimed = false; // Has buyer claimed their item? + + // Bid tracking + public int bidCount = 0; // Number of bids placed + + public AuctionListing() { + } + + /** + * Alias for listingTime (when the auction was created) + */ + public long getCreationTime() { + return listingTime; + } + + // For sorting compatibility + public long creationTime() { + return listingTime; + } + + /** + * Create a new auction listing + */ + public AuctionListing(UUID seller, String sellerName, ItemStack item, + long startPrice, long buyout, EnumAuctionDuration duration) { + this.sellerUUID = seller; + this.sellerName = sellerName; + this.item = item.copy(); + this.startingPrice = startPrice; + this.buyoutPrice = buyout; + this.currentBid = 0; // No bids yet + this.duration = duration; + this.listingTime = System.currentTimeMillis(); + this.expirationTime = listingTime + duration.getMillis(); + this.status = EnumAuctionStatus.ACTIVE; + } + + // ==================== Status Checks ==================== + + /** + * Check if auction has expired + */ + public boolean isExpired() { + return System.currentTimeMillis() >= expirationTime; + } + + /** + * Check if auction is still active + */ + public boolean isActive() { + return status == EnumAuctionStatus.ACTIVE && !isExpired(); + } + + /** + * Get time remaining in milliseconds + */ + public long getTimeRemaining() { + return Math.max(0, expirationTime - System.currentTimeMillis()); + } + + /** + * Get formatted time remaining + */ + public String getTimeRemainingFormatted() { + long remaining = getTimeRemaining(); + + if (remaining <= 0) { + return "Ended"; + } + + long hours = remaining / (60L * 60L * 1000L); + long minutes = (remaining % (60L * 60L * 1000L)) / (60L * 1000L); + + if (hours > 24) { + long days = hours / 24; + hours = hours % 24; + return days + "d " + hours + "h"; + } else if (hours > 0) { + return hours + "h " + minutes + "m"; + } else { + long seconds = (remaining % (60L * 1000L)) / 1000L; + return minutes + "m " + seconds + "s"; + } + } + + /** + * Check if auction has any bids + */ + public boolean hasBids() { + return highBidderUUID != null; + } + + // ==================== Bidding Methods ==================== + + /** + * Calculate minimum valid bid amount + */ + public long getMinimumBid() { + if (!hasBids()) { + return startingPrice; + } + // Minimum increment is configured percent or 1, whichever is greater + long minIncrement = Math.max(1, (long) (currentBid * ConfigMarket.MinBidIncrementPercent)); + return currentBid + minIncrement; + } + + /** + * Place a bid + * @return true if bid was successful + */ + public boolean placeBid(UUID bidder, String bidderName, long amount) { + if (status != EnumAuctionStatus.ACTIVE) { + return false; + } + if (isExpired()) { + return false; + } + if (amount < getMinimumBid()) { + return false; + } + if (bidder.equals(sellerUUID)) { + return false; // Can't bid on own item + } + + // Store previous bidder for refund notification + if (highBidderUUID != null) { + previousBidderUUID = highBidderUUID; + previousBidderName = highBidderName; + previousBidAmount = currentBid; + } + + // Update high bidder + highBidderUUID = bidder; + highBidderName = bidderName; + currentBid = amount; + bidCount++; + + // Snipe protection - extend if bid placed in final minutes + if (ConfigMarket.SnipeProtectionMinutes > 0) { + long timeRemaining = getTimeRemaining(); + long thresholdMs = ConfigMarket.SnipeProtectionThreshold * 60L * 1000L; + + if (timeRemaining < thresholdMs) { + // Extend TO snipe protection time, not by it + long newExpiration = System.currentTimeMillis() + + (ConfigMarket.SnipeProtectionMinutes * 60L * 1000L); + // Only extend if it would actually extend the auction + if (newExpiration > expirationTime) { + expirationTime = newExpiration; + } + } + } + + return true; + } + + /** + * Execute buyout (instant purchase at buyout price) + * @return true if buyout was successful + */ + public boolean buyout(UUID buyer, String buyerName) { + if (status != EnumAuctionStatus.ACTIVE) { + return false; + } + if (isExpired()) { + return false; + } + if (buyoutPrice <= 0) { + return false; // No buyout available + } + if (buyer.equals(sellerUUID)) { + return false; // Can't buy own item + } + + // Store previous bidder for refund + if (highBidderUUID != null) { + previousBidderUUID = highBidderUUID; + previousBidderName = highBidderName; + previousBidAmount = currentBid; + } + + highBidderUUID = buyer; + highBidderName = buyerName; + currentBid = buyoutPrice; + status = EnumAuctionStatus.SOLD; + + return true; + } + + /** + * Cancel listing (seller only, before any bids) + * @return true if cancellation was successful + */ + public boolean cancel(UUID requester) { + if (!requester.equals(sellerUUID)) { + return false; // Only seller can cancel + } + if (hasBids()) { + return false; // Can't cancel with active bids + } + if (status != EnumAuctionStatus.ACTIVE) { + return false; + } + + status = EnumAuctionStatus.CANCELLED; + return true; + } + + /** + * Finalize auction when it expires + * Call this when auction timer runs out + */ + public void finalize() { + if (status != EnumAuctionStatus.ACTIVE) { + return; + } + + if (hasBids()) { + status = EnumAuctionStatus.SOLD; + } else { + status = EnumAuctionStatus.EXPIRED; + } + } + + // ==================== Validation ==================== + + /** + * Validate that the item can be listed + * @return null if valid, error message if invalid + */ + public static String validateItem(ItemStack item) { + if (item == null || item.getItem() == null) { + return "Invalid item"; + } + + // Check trade restrictions (Untradeable, ProfileSlot Bound, Soulbound) + if (!ItemTradeAttribute.canTrade(item)) { + String reason = ItemTradeAttribute.getTradeBlockReason(item); + return reason != null ? reason : "Item cannot be traded"; + } + + // Check blacklist + if (AuctionBlacklist.Instance != null && AuctionBlacklist.Instance.isBlacklisted(item)) { + return "Item is blacklisted from auction"; + } + + return null; // Valid + } + + // ==================== Financial Calculations ==================== + + /** + * Get listing fee for this auction + */ + public long getListingFee() { + long flatFee = duration.getListingFee(); + long percentFee = (long) (startingPrice * ConfigMarket.ListingFeePercent); + return flatFee + percentFee; + } + + /** + * Get seller's proceeds after sales tax + */ + public long getSellerProceeds() { + if (status != EnumAuctionStatus.SOLD) { + return 0; + } + long tax = (long) (currentBid * ConfigMarket.SalesTaxPercent); + return currentBid - tax; + } + + // ==================== NBT Serialization ==================== + + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setInteger("Id", id); + compound.setString("SellerUUID", sellerUUID.toString()); + compound.setString("SellerName", sellerName); + compound.setTag("Item", item.writeToNBT(new NBTTagCompound())); + compound.setLong("StartPrice", startingPrice); + compound.setLong("BuyoutPrice", buyoutPrice); + compound.setLong("CurrentBid", currentBid); + + if (highBidderUUID != null) { + compound.setString("BidderUUID", highBidderUUID.toString()); + compound.setString("BidderName", highBidderName); + } + + if (previousBidderUUID != null) { + compound.setString("PrevBidderUUID", previousBidderUUID.toString()); + compound.setString("PrevBidderName", previousBidderName); + compound.setLong("PrevBidAmount", previousBidAmount); + } + + compound.setLong("ListingTime", listingTime); + compound.setLong("ExpirationTime", expirationTime); + compound.setInteger("Duration", duration.ordinal()); + compound.setInteger("Status", status.ordinal()); + compound.setBoolean("SellerClaimed", sellerClaimed); + compound.setBoolean("BuyerClaimed", buyerClaimed); + compound.setInteger("BidCount", bidCount); + + return compound; + } + + public void readFromNBT(NBTTagCompound compound) { + id = compound.getInteger("Id"); + sellerUUID = UUID.fromString(compound.getString("SellerUUID")); + sellerName = compound.getString("SellerName"); + item = ItemStack.loadItemStackFromNBT(compound.getCompoundTag("Item")); + startingPrice = compound.getLong("StartPrice"); + buyoutPrice = compound.getLong("BuyoutPrice"); + currentBid = compound.getLong("CurrentBid"); + + if (compound.hasKey("BidderUUID")) { + highBidderUUID = UUID.fromString(compound.getString("BidderUUID")); + highBidderName = compound.getString("BidderName"); + } + + if (compound.hasKey("PrevBidderUUID")) { + previousBidderUUID = UUID.fromString(compound.getString("PrevBidderUUID")); + previousBidderName = compound.getString("PrevBidderName"); + previousBidAmount = compound.getLong("PrevBidAmount"); + } + + listingTime = compound.getLong("ListingTime"); + expirationTime = compound.getLong("ExpirationTime"); + + int durationOrdinal = compound.getInteger("Duration"); + if (durationOrdinal >= 0 && durationOrdinal < EnumAuctionDuration.values().length) { + duration = EnumAuctionDuration.values()[durationOrdinal]; + } else { + duration = EnumAuctionDuration.LONG; + } + + int statusOrdinal = compound.getInteger("Status"); + if (statusOrdinal >= 0 && statusOrdinal < EnumAuctionStatus.values().length) { + status = EnumAuctionStatus.values()[statusOrdinal]; + } else { + status = EnumAuctionStatus.ACTIVE; + } + + sellerClaimed = compound.getBoolean("SellerClaimed"); + buyerClaimed = compound.getBoolean("BuyerClaimed"); + bidCount = compound.getInteger("BidCount"); + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerCurrencyData.java b/src/main/java/noppes/npcs/controllers/data/PlayerCurrencyData.java new file mode 100644 index 000000000..511321dbb --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/PlayerCurrencyData.java @@ -0,0 +1,131 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.config.ConfigMarket; + +/** + * Stores player currency balance. + * This data is NOT profile slot bound - all profile slots share the same currency pool. + * When Vault API is available, this serves as a cache/fallback. + */ +public class PlayerCurrencyData { + private long balance; + private long lifetimeEarned; + private long lifetimeSpent; + + public PlayerCurrencyData() { + this.balance = ConfigMarket.StartingBalance; + this.lifetimeEarned = 0; + this.lifetimeSpent = 0; + } + + public void readFromNBT(NBTTagCompound compound) { + if (compound.hasKey("CurrencyBalance")) { + this.balance = compound.getLong("CurrencyBalance"); + } else { + this.balance = ConfigMarket.StartingBalance; + } + this.lifetimeEarned = compound.getLong("CurrencyLifetimeEarned"); + this.lifetimeSpent = compound.getLong("CurrencyLifetimeSpent"); + } + + public void writeToNBT(NBTTagCompound compound) { + compound.setLong("CurrencyBalance", this.balance); + compound.setLong("CurrencyLifetimeEarned", this.lifetimeEarned); + compound.setLong("CurrencyLifetimeSpent", this.lifetimeSpent); + } + + /** + * Get the current balance + */ + public long getBalance() { + return balance; + } + + /** + * Set the balance directly (use with caution) + */ + public void setBalance(long balance) { + if (balance < 0) { + balance = 0; + } + if (balance > ConfigMarket.MaxBalance) { + balance = ConfigMarket.MaxBalance; + } + this.balance = balance; + } + + /** + * Add currency to balance (deposit) + * @param amount Amount to add + * @return true if successful, false if would exceed max balance + */ + public boolean deposit(long amount) { + if (amount <= 0) { + return false; + } + long newBalance = this.balance + amount; + if (newBalance > ConfigMarket.MaxBalance) { + return false; + } + if (newBalance < this.balance) { + // Overflow protection + return false; + } + this.balance = newBalance; + this.lifetimeEarned += amount; + return true; + } + + /** + * Remove currency from balance (withdraw) + * @param amount Amount to remove + * @return true if successful, false if insufficient funds + */ + public boolean withdraw(long amount) { + if (amount <= 0) { + return false; + } + if (this.balance < amount) { + return false; + } + this.balance -= amount; + this.lifetimeSpent += amount; + return true; + } + + /** + * Check if player can afford an amount + */ + public boolean canAfford(long amount) { + return this.balance >= amount; + } + + /** + * Get lifetime earned currency + */ + public long getLifetimeEarned() { + return lifetimeEarned; + } + + /** + * Get lifetime spent currency + */ + public long getLifetimeSpent() { + return lifetimeSpent; + } + + /** + * Format the balance for display + */ + public String formatBalance() { + return formatAmount(this.balance); + } + + /** + * Format an amount for display + */ + public static String formatAmount(long amount) { + return String.format("%,d %s", amount, ConfigMarket.CurrencyName); + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerData.java b/src/main/java/noppes/npcs/controllers/data/PlayerData.java index 599f81ff1..08fdebdd0 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerData.java @@ -59,6 +59,9 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { public DataSkinOverlays skinOverlays = new DataSkinOverlays(this); public MagicData magicData = new MagicData(); + // Currency data - NOT slot-bound, shared across all profile slots + public PlayerCurrencyData currencyData = new PlayerCurrencyData(); + public ActionManager actionManager = new ActionManager(); public PlayerDataScript scriptData; @@ -406,6 +409,9 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { } final NBTTagCompound compound = getNBT(); + // Add currency data to main save (NOT slot-bound, preserved across profile changes) + currencyData.writeToNBT(compound); + final String filename; if (ConfigMain.DatFormat) { filename = uuid + ".dat"; @@ -442,6 +448,13 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { if (data.hasNoTags()) { data = getNBT(); } + + // Load currency BEFORE setNBT so we can preserve it + // Currency is stored in main file but NOT in slot data + if (data.hasKey("CurrencyBalance")) { + currencyData.readFromNBT(data); + } + setNBT(data); } diff --git a/src/main/java/noppes/npcs/controllers/data/TraderStock.java b/src/main/java/noppes/npcs/controllers/data/TraderStock.java new file mode 100644 index 000000000..f3c5f4db9 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/TraderStock.java @@ -0,0 +1,319 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.constants.EnumStockReset; + +import java.util.HashMap; +import java.util.Map; + +/** + * Manages trader stock system including: + * - Per-slot stock limits + * - Per-player vs per-server stock tracking + * - Automatic stock reset timers + */ +public class TraderStock { + // Stock configuration + public boolean enableStock = false; + public boolean perPlayer = false; // false = per-server, true = per-player + + // Reset configuration (mirrors Quest cooldown system) + public EnumStockReset resetType = EnumStockReset.NONE; + public long customResetTime = 0; // For MCCUSTOM/RLCUSTOM types (in ticks or ms) + + // Stock quantities per slot (max stock, -1 = unlimited) + public int[] maxStock = new int[18]; + + // Current stock (per-server mode) + public int[] currentStock = new int[18]; + public long lastResetTime = 0; + + // Per-player stock tracking + public HashMap playerStock = new HashMap<>(); + + public TraderStock() { + for (int i = 0; i < 18; i++) { + maxStock[i] = -1; // -1 = unlimited + currentStock[i] = -1; + } + } + + /** + * Get available stock for a slot + * @param slot The slot index + * @param playerName The player name (for per-player mode) + * @return Available stock count, or Integer.MAX_VALUE if unlimited + */ + public int getAvailableStock(int slot, String playerName) { + if (!enableStock || slot < 0 || slot >= 18 || maxStock[slot] < 0) { + return Integer.MAX_VALUE; // Unlimited + } + + if (perPlayer) { + PlayerTraderStock pStock = playerStock.get(playerName); + if (pStock == null) { + return maxStock[slot]; // Not purchased yet + } + return pStock.getStock(slot, maxStock[slot]); + } + + if (currentStock[slot] < 0) { + return maxStock[slot]; + } + return Math.max(0, currentStock[slot]); + } + + /** + * Check if stock is available for purchase + */ + public boolean hasStock(int slot, String playerName, int amount) { + return getAvailableStock(slot, playerName) >= amount; + } + + /** + * Consume stock when purchase is made + * @return true if successful, false if insufficient stock + */ + public boolean consumeStock(int slot, String playerName, int amount) { + if (!enableStock || slot < 0 || slot >= 18 || maxStock[slot] < 0) { + return true; // Unlimited, always succeeds + } + + if (perPlayer) { + PlayerTraderStock pStock = playerStock.computeIfAbsent( + playerName, k -> new PlayerTraderStock()); + return pStock.consumeStock(slot, maxStock[slot], amount); + } + + if (currentStock[slot] < 0) { + currentStock[slot] = maxStock[slot]; + } + if (currentStock[slot] >= amount) { + currentStock[slot] -= amount; + return true; + } + return false; + } + + /** + * Check if stock should reset based on current time + * @param currentTime Current MC world time (ticks) or real time (ms) depending on reset type + */ + public boolean shouldReset(long currentTime) { + if (resetType == EnumStockReset.NONE) { + return false; + } + + long elapsed = currentTime - lastResetTime; + long resetInterval = getResetInterval(); + + return elapsed >= resetInterval; + } + + /** + * Reset all stock to max values + * @param currentTime Current time to record as reset time + */ + public void resetStock(long currentTime) { + lastResetTime = currentTime; + + // Reset per-server stock + for (int i = 0; i < 18; i++) { + currentStock[i] = maxStock[i]; + } + + // Clear per-player stock + playerStock.clear(); + } + + /** + * Get reset interval based on reset type + * @return Interval in ticks (MC time) or milliseconds (real time) + */ + public long getResetInterval() { + switch (resetType) { + case MCDAILY: + return 24000; // 1 MC day in ticks + case MCWEEKLY: + return 168000; // 7 MC days in ticks + case MCCUSTOM: + return customResetTime; // Custom ticks + case RLDAILY: + return 86400000L; // 24 hours in ms + case RLWEEKLY: + return 604800000L; // 7 days in ms + case RLCUSTOM: + return customResetTime; // Custom ms + default: + return Long.MAX_VALUE; + } + } + + /** + * Get time until next reset + * @param currentTime Current time + * @return Time remaining until reset, or -1 if no reset scheduled + */ + public long getTimeUntilReset(long currentTime) { + if (resetType == EnumStockReset.NONE) { + return -1; + } + long elapsed = currentTime - lastResetTime; + long interval = getResetInterval(); + return Math.max(0, interval - elapsed); + } + + /** + * Format time until reset for display + * @param currentTime Current time + * @return Formatted string like "2 hours" or "1 day, 5 hours" + */ + public String getTimeUntilResetFormatted(long currentTime) { + long remaining = getTimeUntilReset(currentTime); + if (remaining < 0) { + return ""; + } + + if (resetType.isRealTime()) { + // Convert ms to readable format + long hours = remaining / 3600000L; + long days = hours / 24; + hours = hours % 24; + + if (days > 0) { + return days + " day" + (days != 1 ? "s" : "") + + (hours > 0 ? ", " + hours + " hour" + (hours != 1 ? "s" : "") : ""); + } else if (hours > 0) { + return hours + " hour" + (hours != 1 ? "s" : ""); + } else { + long minutes = remaining / 60000L; + return minutes + " minute" + (minutes != 1 ? "s" : ""); + } + } else { + // Convert ticks to MC time format + long mcHours = remaining / 1000; // 1000 ticks = 1 MC hour + long mcDays = mcHours / 24; + mcHours = mcHours % 24; + + if (mcDays > 0) { + return mcDays + " MC day" + (mcDays != 1 ? "s" : "") + + (mcHours > 0 ? ", " + mcHours + " MC hour" + (mcHours != 1 ? "s" : "") : ""); + } else { + return mcHours + " MC hour" + (mcHours != 1 ? "s" : ""); + } + } + } + + /** + * Set stock for a specific slot + */ + public void setMaxStock(int slot, int amount) { + if (slot >= 0 && slot < 18) { + maxStock[slot] = amount; + if (currentStock[slot] < 0 || currentStock[slot] > amount) { + currentStock[slot] = amount; + } + } + } + + // ==================== NBT Serialization ==================== + + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setBoolean("EnableStock", enableStock); + compound.setBoolean("PerPlayer", perPlayer); + compound.setInteger("ResetType", resetType.ordinal()); + compound.setLong("CustomResetTime", customResetTime); + compound.setIntArray("MaxStock", maxStock); + compound.setIntArray("CurrentStock", currentStock); + compound.setLong("LastResetTime", lastResetTime); + + // Save per-player stock + NBTTagList playerList = new NBTTagList(); + for (Map.Entry entry : playerStock.entrySet()) { + NBTTagCompound playerTag = new NBTTagCompound(); + playerTag.setString("Player", entry.getKey()); + entry.getValue().writeToNBT(playerTag); + playerList.appendTag(playerTag); + } + compound.setTag("PlayerStock", playerList); + + return compound; + } + + public void readFromNBT(NBTTagCompound compound) { + enableStock = compound.getBoolean("EnableStock"); + perPlayer = compound.getBoolean("PerPlayer"); + + int resetOrdinal = compound.getInteger("ResetType"); + if (resetOrdinal >= 0 && resetOrdinal < EnumStockReset.values().length) { + resetType = EnumStockReset.values()[resetOrdinal]; + } + + customResetTime = compound.getLong("CustomResetTime"); + + int[] loadedMax = compound.getIntArray("MaxStock"); + int[] loadedCurrent = compound.getIntArray("CurrentStock"); + + if (loadedMax != null && loadedMax.length == 18) { + maxStock = loadedMax; + } + if (loadedCurrent != null && loadedCurrent.length == 18) { + currentStock = loadedCurrent; + } + + lastResetTime = compound.getLong("LastResetTime"); + + // Load per-player stock + playerStock.clear(); + NBTTagList playerList = compound.getTagList("PlayerStock", 10); + for (int i = 0; i < playerList.tagCount(); i++) { + NBTTagCompound playerTag = playerList.getCompoundTagAt(i); + String playerName = playerTag.getString("Player"); + PlayerTraderStock pStock = new PlayerTraderStock(); + pStock.readFromNBT(playerTag); + playerStock.put(playerName, pStock); + } + } + + // ==================== Inner Class for Per-Player Stock ==================== + + public static class PlayerTraderStock { + public int[] purchasedAmounts = new int[18]; + public long lastPurchaseTime = 0; + + public PlayerTraderStock() { + for (int i = 0; i < 18; i++) { + purchasedAmounts[i] = 0; + } + } + + public int getStock(int slot, int maxStock) { + if (slot < 0 || slot >= 18) return 0; + return Math.max(0, maxStock - purchasedAmounts[slot]); + } + + public boolean consumeStock(int slot, int maxStock, int amount) { + if (slot < 0 || slot >= 18) return false; + if (getStock(slot, maxStock) >= amount) { + purchasedAmounts[slot] += amount; + lastPurchaseTime = System.currentTimeMillis(); + return true; + } + return false; + } + + public void writeToNBT(NBTTagCompound compound) { + compound.setIntArray("Purchased", purchasedAmounts); + compound.setLong("LastPurchase", lastPurchaseTime); + } + + public void readFromNBT(NBTTagCompound compound) { + int[] loaded = compound.getIntArray("Purchased"); + if (loaded != null && loaded.length == 18) { + purchasedAmounts = loaded; + } + lastPurchaseTime = compound.getLong("LastPurchase"); + } + } +} diff --git a/src/main/java/noppes/npcs/roles/RoleAuctioneer.java b/src/main/java/noppes/npcs/roles/RoleAuctioneer.java new file mode 100644 index 000000000..4d8febaf1 --- /dev/null +++ b/src/main/java/noppes/npcs/roles/RoleAuctioneer.java @@ -0,0 +1,135 @@ +package noppes.npcs.roles; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.NoppesUtilServer; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.constants.EnumGuiType; +import noppes.npcs.controllers.AuctionController; +import noppes.npcs.controllers.data.Line; +import noppes.npcs.entity.EntityNPCInterface; + +/** + * NPC role for Auctioneer - provides access to the global auction house. + */ +public class RoleAuctioneer extends RoleInterface { + + // Configuration + public boolean showActiveListings = true; // Show active listings tab + public boolean showMyListings = true; // Show player's listings tab + public boolean showMyBids = true; // Show player's bids tab + public boolean showClaims = true; // Show claimable items tab + public boolean allowCreatingListings = true; // Allow creating new listings + public boolean allowBidding = true; // Allow bidding on items + public boolean allowBuyout = true; // Allow buyout purchases + + // Custom greeting messages + public String welcomeMessage = ""; + public String noAuctionMessage = ""; + + public RoleAuctioneer(EntityNPCInterface npc) { + super(npc); + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setBoolean("ShowActiveListings", showActiveListings); + compound.setBoolean("ShowMyListings", showMyListings); + compound.setBoolean("ShowMyBids", showMyBids); + compound.setBoolean("ShowClaims", showClaims); + compound.setBoolean("AllowCreatingListings", allowCreatingListings); + compound.setBoolean("AllowBidding", allowBidding); + compound.setBoolean("AllowBuyout", allowBuyout); + compound.setString("WelcomeMessage", welcomeMessage); + compound.setString("NoAuctionMessage", noAuctionMessage); + return compound; + } + + @Override + public void readFromNBT(NBTTagCompound compound) { + showActiveListings = compound.hasKey("ShowActiveListings") ? + compound.getBoolean("ShowActiveListings") : true; + showMyListings = compound.hasKey("ShowMyListings") ? + compound.getBoolean("ShowMyListings") : true; + showMyBids = compound.hasKey("ShowMyBids") ? + compound.getBoolean("ShowMyBids") : true; + showClaims = compound.hasKey("ShowClaims") ? + compound.getBoolean("ShowClaims") : true; + allowCreatingListings = compound.hasKey("AllowCreatingListings") ? + compound.getBoolean("AllowCreatingListings") : true; + allowBidding = compound.hasKey("AllowBidding") ? + compound.getBoolean("AllowBidding") : true; + allowBuyout = compound.hasKey("AllowBuyout") ? + compound.getBoolean("AllowBuyout") : true; + welcomeMessage = compound.getString("WelcomeMessage"); + noAuctionMessage = compound.getString("NoAuctionMessage"); + } + + @Override + public void interact(EntityPlayer player) { + // Check if auction system is enabled + if (!ConfigMarket.AuctionEnabled) { + if (!noAuctionMessage.isEmpty()) { + npc.say(player, new Line(noAuctionMessage)); + } else { + npc.say(player, new Line("The auction house is currently closed.")); + } + return; + } + + // Process expired auctions before opening GUI + if (AuctionController.Instance != null) { + AuctionController.Instance.processExpiredAuctions(); + } + + // Say welcome message + if (!welcomeMessage.isEmpty()) { + npc.say(player, new Line(welcomeMessage)); + } else { + npc.say(player, npc.advanced.getInteractLine()); + } + + // Open auction GUI + NoppesUtilServer.sendOpenGui(player, EnumGuiType.PlayerAuction, npc); + } + + /** + * Check if player has claims waiting + */ + public boolean hasClaimsWaiting(EntityPlayer player) { + if (AuctionController.Instance == null) { + return false; + } + return !AuctionController.Instance.getClaimableListings(player.getUniqueID()).isEmpty(); + } + + /** + * Get number of active listings in the auction house + */ + public int getActiveListingCount() { + if (AuctionController.Instance == null) { + return 0; + } + return AuctionController.Instance.getActiveListingCount(); + } + + /** + * Get player's current listing count + */ + public int getPlayerListingCount(EntityPlayer player) { + if (AuctionController.Instance == null) { + return 0; + } + return AuctionController.Instance.getActiveListingsCount(player.getUniqueID()); + } + + /** + * Get player's maximum allowed listings + */ + public int getPlayerMaxListings(EntityPlayer player) { + if (AuctionController.Instance == null) { + return ConfigMarket.DefaultMaxListings; + } + return AuctionController.Instance.getMaxListings(player); + } +} diff --git a/src/main/java/noppes/npcs/roles/RoleTrader.java b/src/main/java/noppes/npcs/roles/RoleTrader.java index 5275c26c0..6215eef2f 100644 --- a/src/main/java/noppes/npcs/roles/RoleTrader.java +++ b/src/main/java/noppes/npcs/roles/RoleTrader.java @@ -4,11 +4,13 @@ import foxz.utils.Market; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; import noppes.npcs.NBTTags; import noppes.npcs.NoppesUtilPlayer; import noppes.npcs.NoppesUtilServer; import noppes.npcs.NpcMiscInventory; import noppes.npcs.constants.EnumGuiType; +import noppes.npcs.controllers.data.TraderStock; import noppes.npcs.entity.EntityNPCInterface; import java.util.HashMap; @@ -30,6 +32,13 @@ public class RoleTrader extends RoleInterface { public HashMap playerPurchases; public HashMap playerDisableSlot; + // Stock system + public TraderStock stock = new TraderStock(); + + // Currency system + public boolean useCurrency = false; // Use virtual currency instead of items + public long[] slotPrices = new long[18]; // Currency prices per slot + public RoleTrader(EntityNPCInterface npc) { super(npc); inventoryCurrency = new NpcMiscInventory(36); @@ -59,6 +68,20 @@ public class RoleTrader extends RoleInterface { nbttagcompound.setIntArray("Purchases", purchases); nbttagcompound.setTag("PlayerPurchases", NBTTags.nbtStringIntegerArrayMap(playerPurchases)); } + + // Stock system + nbttagcompound.setTag("Stock", stock.writeToNBT(new NBTTagCompound())); + + // Currency system + nbttagcompound.setBoolean("UseCurrency", useCurrency); + NBTTagList priceList = new NBTTagList(); + for (long price : slotPrices) { + NBTTagCompound priceTag = new NBTTagCompound(); + priceTag.setLong("Price", price); + priceList.appendTag(priceTag); + } + nbttagcompound.setTag("SlotPrices", priceList); + return nbttagcompound; } @@ -94,10 +117,39 @@ public class RoleTrader extends RoleInterface { disableSlot = new int[18]; for (int i = 0; i < disableSlot.length; ++i) disableSlot[i] = 0; } + + // Stock system + if (nbttagcompound.hasKey("Stock")) { + stock.readFromNBT(nbttagcompound.getCompoundTag("Stock")); + } + + // Currency system + useCurrency = nbttagcompound.getBoolean("UseCurrency"); + if (nbttagcompound.hasKey("SlotPrices")) { + NBTTagList priceList = nbttagcompound.getTagList("SlotPrices", 10); + for (int i = 0; i < priceList.tagCount() && i < 18; i++) { + slotPrices[i] = priceList.getCompoundTagAt(i).getLong("Price"); + } + } } @Override public void interact(EntityPlayer player) { + // Check for stock reset before opening GUI + if (stock.enableStock) { + long currentTime = stock.resetType.isRealTime() + ? System.currentTimeMillis() + : player.worldObj.getTotalWorldTime(); + + if (stock.shouldReset(currentTime)) { + stock.resetStock(currentTime); + // Save to market if using shared market + if (!marketName.isEmpty()) { + Market.save(this, marketName); + } + } + } + npc.say(player, npc.advanced.getInteractLine()); try { Market.getMarket(this, marketName); @@ -138,4 +190,78 @@ public class RoleTrader extends RoleInterface { return map.get(name); } + // ==================== Stock System Methods ==================== + + /** + * Check if there is stock available for a slot + */ + public boolean hasStock(int slot, String playerName, int amount) { + if (!stock.enableStock) { + return true; // Stock system disabled, always available + } + return stock.hasStock(slot, playerName, amount); + } + + /** + * Get available stock for a slot + */ + public int getAvailableStock(int slot, String playerName) { + if (!stock.enableStock) { + return Integer.MAX_VALUE; // Unlimited + } + return stock.getAvailableStock(slot, playerName); + } + + /** + * Consume stock after purchase + */ + public boolean consumeStock(int slot, String playerName, int amount) { + if (!stock.enableStock) { + return true; // Stock system disabled + } + boolean consumed = stock.consumeStock(slot, playerName, amount); + if (consumed && !marketName.isEmpty()) { + Market.save(this, marketName); + } + return consumed; + } + + /** + * Get time until stock reset formatted for display + */ + public String getTimeUntilResetFormatted() { + if (!stock.enableStock || stock.resetType == noppes.npcs.constants.EnumStockReset.NONE) { + return ""; + } + long currentTime = stock.resetType.isRealTime() + ? System.currentTimeMillis() + : (npc != null && npc.worldObj != null ? npc.worldObj.getTotalWorldTime() : 0); + return stock.getTimeUntilResetFormatted(currentTime); + } + + // ==================== Currency System Methods ==================== + + /** + * Get the currency price for a slot + */ + public long getSlotPrice(int slot) { + if (slot < 0 || slot >= 18) return 0; + return slotPrices[slot]; + } + + /** + * Set the currency price for a slot + */ + public void setSlotPrice(int slot, long price) { + if (slot >= 0 && slot < 18) { + slotPrices[slot] = Math.max(0, price); + } + } + + /** + * Check if a slot has a currency price set + */ + public boolean hasSlotPrice(int slot) { + return useCurrency && slot >= 0 && slot < 18 && slotPrices[slot] > 0; + } } diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptPlayer.java b/src/main/java/noppes/npcs/scripted/entity/ScriptPlayer.java index 6206cfbac..9fc547260 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptPlayer.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptPlayer.java @@ -49,11 +49,14 @@ import noppes.npcs.compat.PixelmonHelper; import noppes.npcs.config.ConfigScript; import noppes.npcs.constants.EnumQuestType; import noppes.npcs.containers.ContainerCustomGui; +import noppes.npcs.controllers.AuctionController; +import noppes.npcs.controllers.CurrencyController; import noppes.npcs.controllers.CustomGuiController; import noppes.npcs.controllers.DialogController; import noppes.npcs.controllers.PartyController; import noppes.npcs.controllers.PlayerQuestController; import noppes.npcs.controllers.QuestController; +import noppes.npcs.controllers.VaultHelper; import noppes.npcs.controllers.data.Dialog; import noppes.npcs.controllers.data.Party; import noppes.npcs.controllers.data.PlayerData; @@ -895,4 +898,186 @@ public class ScriptPlayer extends ScriptLivingBase } return (IPlayer[]) list.toArray(new IPlayer[list.size()]); } + + // ==================== CURRENCY METHODS ==================== + + /** + * Get the player's current currency balance. + * Uses Vault if available, otherwise uses internal currency system. + * @return The player's currency balance + * @since 1.11 + */ + public long getCurrencyBalance() { + if (CurrencyController.Instance == null) { + return 0; + } + return CurrencyController.Instance.getBalance(player); + } + + /** + * Add currency to the player's balance. + * @param amount The amount to add (must be positive) + * @return true if successful, false if failed (e.g., would exceed max balance) + * @since 1.11 + */ + public boolean addCurrency(long amount) { + if (CurrencyController.Instance == null) { + return false; + } + return CurrencyController.Instance.deposit(player, amount); + } + + /** + * Remove currency from the player's balance. + * @param amount The amount to remove (must be positive) + * @return true if successful, false if insufficient funds + * @since 1.11 + */ + public boolean removeCurrency(long amount) { + if (CurrencyController.Instance == null) { + return false; + } + return CurrencyController.Instance.withdraw(player, amount); + } + + /** + * Check if the player can afford a specific amount. + * @param amount The amount to check + * @return true if player has sufficient balance + * @since 1.11 + */ + public boolean canAffordCurrency(long amount) { + if (CurrencyController.Instance == null) { + return false; + } + return CurrencyController.Instance.canAfford(player, amount); + } + + /** + * Get the configured currency name (e.g., "Gold"). + * @return The currency name + * @since 1.11 + */ + public String getCurrencyName() { + if (VaultHelper.Instance == null) { + return "Currency"; + } + return VaultHelper.Instance.getCurrencyName(); + } + + /** + * Format a currency amount for display (e.g., "1,000 Gold"). + * @param amount The amount to format + * @return Formatted string + * @since 1.11 + */ + public String formatCurrency(long amount) { + if (CurrencyController.Instance == null) { + return String.valueOf(amount); + } + return CurrencyController.Instance.formatAmount(amount); + } + + /** + * Check if the player has pending currency claims. + * Claims are created by auction refunds, NPC payments, etc. + * @return true if there are pending claims + * @since 1.11 + */ + public boolean hasPendingClaims() { + if (CurrencyController.Instance == null) { + return false; + } + return CurrencyController.Instance.hasPendingClaims(player); + } + + /** + * Get the total amount of pending currency claims. + * @return Total pending claim amount + * @since 1.11 + */ + public long getPendingClaimsTotal() { + if (CurrencyController.Instance == null) { + return 0; + } + return CurrencyController.Instance.getTotalPendingClaims(player); + } + + /** + * Claim all pending currency claims and add them to balance. + * @return The total amount claimed + * @since 1.11 + */ + public long claimAllCurrency() { + if (CurrencyController.Instance == null) { + return 0; + } + return CurrencyController.Instance.claimAll(player); + } + + // ==================== AUCTION METHODS ==================== + + /** + * Get the number of active auction listings the player has. + * @return Number of active listings + * @since 1.11 + */ + public int getAuctionListingCount() { + if (AuctionController.Instance == null) { + return 0; + } + return AuctionController.Instance.getActiveListingsCount(player.getUniqueID()); + } + + /** + * Get the maximum number of auction listings the player is allowed. + * @return Maximum listing count + * @since 1.11 + */ + public int getMaxAuctionListings() { + if (AuctionController.Instance == null) { + return 0; + } + return AuctionController.Instance.getMaxListings(player); + } + + /** + * Check if the player has auction items waiting to be claimed. + * This includes won items, expired listings, and sale proceeds. + * @return true if there are claimable items + * @since 1.11 + */ + public boolean hasAuctionClaims() { + if (AuctionController.Instance == null) { + return false; + } + return !AuctionController.Instance.getClaimableListings(player.getUniqueID()).isEmpty(); + } + + /** + * Get the number of auction items waiting to be claimed. + * @return Number of claimable items/listings + * @since 1.11 + */ + public int getAuctionClaimCount() { + if (AuctionController.Instance == null) { + return 0; + } + return AuctionController.Instance.getClaimableListings(player.getUniqueID()).size(); + } + + /** + * Get the number of auctions where the player is the current high bidder. + * @return Number of active bids + * @since 1.11 + */ + public int getActiveAuctionBidCount() { + if (AuctionController.Instance == null) { + return 0; + } + return (int) AuctionController.Instance.getListingsAsBidder(player.getUniqueID()) + .stream() + .filter(l -> l.isActive()) + .count(); + } } diff --git a/src/main/java/noppes/npcs/scripted/item/ScriptItemStack.java b/src/main/java/noppes/npcs/scripted/item/ScriptItemStack.java index 6736369b9..a2588059f 100644 --- a/src/main/java/noppes/npcs/scripted/item/ScriptItemStack.java +++ b/src/main/java/noppes/npcs/scripted/item/ScriptItemStack.java @@ -1,6 +1,7 @@ package noppes.npcs.scripted.item; import com.google.common.collect.Multimap; +import kamkeel.npcs.controllers.data.attribute.ItemTradeAttribute; import kamkeel.npcs.controllers.data.attribute.requirement.IRequirementChecker; import kamkeel.npcs.controllers.data.attribute.requirement.RequirementCheckerRegistry; import kamkeel.npcs.util.AttributeItemUtil; @@ -592,4 +593,117 @@ public class ScriptItemStack implements IItemStack { Set keys = reqTag.func_150296_c(); return keys.toArray(new String[keys.size()]); } + + // ==================== Trade Restriction Methods ==================== + + /** + * Check if this item can be traded or auctioned. + * An item cannot be traded if it is: + * - Marked as untradeable + * - Bound to a profile slot + * - Soulbound to a player + * @return true if the item can be traded + * @since 1.11 + */ + public boolean canTrade() { + return ItemTradeAttribute.canTrade(item); + } + + /** + * Get the reason why this item cannot be traded. + * @return Localization key for the block reason, or null if tradeable + * @since 1.11 + */ + public String getTradeBlockReason() { + return ItemTradeAttribute.getTradeBlockReason(item); + } + + /** + * Check if this item is marked as untradeable + * @return true if untradeable + * @since 1.11 + */ + public boolean isUntradeable() { + return ItemTradeAttribute.isUntradeable(item); + } + + /** + * Set whether this item is untradeable + * @param untradeable true to mark as untradeable + * @since 1.11 + */ + public void setUntradeable(boolean untradeable) { + ItemTradeAttribute.setUntradeable(item, untradeable); + } + + /** + * Check if this item is bound to a profile slot + * @return true if profile slot bound + * @since 1.11 + */ + public boolean isProfileSlotBound() { + return ItemTradeAttribute.isProfileSlotBound(item); + } + + /** + * Get the profile slot this item is bound to + * @return Profile slot ID, or -1 if not bound + * @since 1.11 + */ + public int getProfileSlot() { + return ItemTradeAttribute.getProfileSlot(item); + } + + /** + * Bind this item to a specific profile slot + * @param slot The profile slot ID, or -1 to unbind + * @since 1.11 + */ + public void setProfileSlotBound(int slot) { + ItemTradeAttribute.setProfileSlotBound(item, slot); + } + + /** + * Check if this item is soulbound to any player + * @return true if soulbound + * @since 1.11 + */ + public boolean isSoulbound() { + return ItemTradeAttribute.isSoulbound(item); + } + + /** + * Get the UUID of the player this item is soulbound to + * @return UUID string, or null if not soulbound + * @since 1.11 + */ + public String getSoulbindOwner() { + return ItemTradeAttribute.getSoulbindOwner(item); + } + + /** + * Remove the soulbind from this item + * @since 1.11 + */ + public void removeSoulbind() { + ItemTradeAttribute.removeSoulbind(item); + } + + /** + * Clear all trade restrictions from this item + * (untradeable, profile slot bound, soulbound) + * @since 1.11 + */ + public void clearTradeRestrictions() { + ItemTradeAttribute.clearAllRestrictions(item); + } + + /** + * Get a summary of all trade restrictions on this item + * @return Human-readable string of restrictions, or empty if none + * @since 1.11 + */ + public String getRestrictionSummary() { + return ItemTradeAttribute.getRestrictionSummary(item); + } } diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 73124d9bf..66837c543 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -429,6 +429,19 @@ role.mount.hover=Hover role.mount.ascendspeed=Ascend Speed role.mount.descendspeed=Descend Speed role.mount.walkspeed=Walk Speed: %s +role.auctioneer=Auctioneer +role.auctioneer.tabs=Tab Visibility +role.auctioneer.showBrowse=Show Browse +role.auctioneer.showMyListings=Show My Listings +role.auctioneer.showMyBids=Show My Bids +role.auctioneer.showClaims=Show Claims +role.auctioneer.actions=Player Actions +role.auctioneer.allowCreate=Allow Create +role.auctioneer.allowBid=Allow Bid +role.auctioneer.allowBuyout=Allow Buyout +role.auctioneer.messages=Messages +role.auctioneer.welcome=Welcome Message +role.auctioneer.noAuction=Auction Disabled Message trader.insufficient=Insufficient Currency trader.sufficient=Sufficient Currency @@ -1666,3 +1679,73 @@ condition.hit_count=Hit Count condition.percent=Threshold condition.hits=Required Hits condition.within=Within (ticks) + +auction.title=Auction House +auction.browse=Browse +auction.myListings=My Listings +auction.myBids=My Bids +auction.claims=Claims +auction.sell=Sell +auction.search=Search +auction.refresh=Refresh +auction.viewDetails=View Details +auction.placeBid=Place Bid +auction.buyout=Buyout +auction.cancel=Cancel +auction.prevPage=< Prev +auction.nextPage=Next > +auction.noResults=No results +auction.page=Page %d of %d +auction.balance=Balance: %s +auction.listings=%d listings +auction.browseTitle=Browse Auctions +auction.myListingsTitle=My Listings +auction.myBidsTitle=My Active Bids +auction.claimsTitle=Claim Items +auction.sellTitle=Create Listing +auction.currentPrice=Current Price: +auction.minimumBid=Minimum Bid: +auction.yourBalance=Your Balance: +auction.timeLeft=Time Left: +auction.yourBid=Your Bid: +auction.minBid=Min Bid +auction.bidPlus10=+10% +auction.bidPlus25=+25% +auction.insufficientFunds=Insufficient funds! +auction.auctionEnded=Auction has ended! +auction.ended=Ended +auction.item=Item: +auction.seller=Seller: +auction.startingPrice=Starting Price: +auction.buyoutPrice=Buyout Price: +auction.noBuyout=None +auction.bidCount=Bid Count: +auction.highBidder=High Bidder: +auction.noBids=No bids +auction.claim=Claim +auction.createListing=Create Listing +auction.duration=Duration: +auction.listingFee=Listing Fee: +auction.create=Create +auction.sort.newest=Newest First +auction.sort.oldest=Oldest First +auction.sort.priceHigh=Most Expensive +auction.sort.priceLow=Least Expensive +auction.sort.endingSoon=Ending Soon +auction.sort.mostTime=Most Time Left +auction.sort.nameAZ=Name: A to Z +auction.sort.nameZA=Name: Z to A +auction.sort.mostBids=Most Bids +auction.sort.leastBids=Least Bids +auction.duration.short=Short (12h) +auction.duration.medium=Medium (24h) +auction.duration.long=Long (48h) +auction.duration.veryLong=Very Long (72h) +auction.placeItemBelow=Place item in slot below: +auction.noItemSelected=(No item selected) +auction.noBuyoutHint=(0 = no buyout) +auction.quantity=Quantity: +auction.totalBids=Total Bids: +auction.noBidsYet=No bids yet +auction.auctionDetails=Auction Details +auction.currentBid=Current Bid: