Search in sources :

Example 6 with TEAccount

use of com.erigitic.config.TEAccount in project TotalEconomy by Erigitic.

the class ViewBalanceCommand method execute.

@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    User recipient = args.<User>getOne("player").get();
    Optional<String> optCurrencyName = args.getOne("currencyName");
    TEAccount recipientAccount = (TEAccount) accountManager.getOrCreateAccount(recipient.getUniqueId()).get();
    TransactionResult transactionResult = getTransactionResult(recipientAccount, optCurrencyName);
    if (transactionResult.getResult() == ResultType.SUCCESS) {
        TECurrency currency = (TECurrency) transactionResult.getCurrency();
        Text balanceText = currency.format(recipientAccount.getBalance(currency));
        Map<String, String> messageValues = new HashMap<>();
        messageValues.put("recipient", recipient.getName());
        messageValues.put("amount", balanceText.toPlain());
        sender.sendMessage(messageManager.getMessage("command.viewbalance", messageValues));
        return CommandResult.success();
    } else {
        throw new CommandException(Text.of("[TE] An error occurred setting a player's balance!"));
    }
}
Also used : TransactionResult(org.spongepowered.api.service.economy.transaction.TransactionResult) User(org.spongepowered.api.entity.living.player.User) TECurrency(com.erigitic.config.TECurrency) HashMap(java.util.HashMap) Text(org.spongepowered.api.text.Text) CommandException(org.spongepowered.api.command.CommandException) TEAccount(com.erigitic.config.TEAccount)

Example 7 with TEAccount

use of com.erigitic.config.TEAccount in project TotalEconomy by Erigitic.

the class JobManager method startSalaryTask.

/**
 * Start the timer that pays out the salary to each player after a specified time in seconds
 */
private void startSalaryTask() {
    Scheduler scheduler = totalEconomy.getGame().getScheduler();
    Task.Builder payTask = scheduler.createTaskBuilder();
    payTask.execute(() -> {
        for (Player player : totalEconomy.getServer().getOnlinePlayers()) {
            Optional<TEJob> optJob = getJob(getPlayerJob(player), true);
            if (!optJob.isPresent()) {
                player.sendMessage(Text.of(TextColors.RED, "[TE] Cannot pay your salary! Contact your administrator!"));
                return;
            }
            if (optJob.get().salaryEnabled()) {
                BigDecimal salary = optJob.get().getSalary();
                TEAccount playerAccount = (TEAccount) accountManager.getOrCreateAccount(player.getUniqueId()).get();
                EventContext eventContext = EventContext.builder().add(EventContextKeys.PLAYER, player).build();
                Cause cause = Cause.builder().append(totalEconomy.getPluginContainer()).build(eventContext);
                TransactionResult result = playerAccount.deposit(totalEconomy.getDefaultCurrency(), salary, cause);
                if (result.getResult() == ResultType.SUCCESS) {
                    Map<String, String> messageValues = new HashMap<>();
                    messageValues.put("amount", totalEconomy.getDefaultCurrency().format(salary).toPlain());
                    player.sendMessage(messageManager.getMessage("jobs.salary", messageValues));
                } else {
                    player.sendMessage(Text.of(TextColors.RED, "[TE] Failed to pay your salary! You may want to contact your admin - TransactionResult: ", result.getResult().toString()));
                }
            }
        }
    }).delay(jobsConfig.getNode("salarydelay").getInt(), TimeUnit.SECONDS).interval(jobsConfig.getNode("salarydelay").getInt(), TimeUnit.SECONDS).name("Pay Day").submit(totalEconomy);
}
Also used : Task(org.spongepowered.api.scheduler.Task) Player(org.spongepowered.api.entity.living.player.Player) TransactionResult(org.spongepowered.api.service.economy.transaction.TransactionResult) Scheduler(org.spongepowered.api.scheduler.Scheduler) TEAccount(com.erigitic.config.TEAccount) BigDecimal(java.math.BigDecimal) EventContext(org.spongepowered.api.event.cause.EventContext) Cause(org.spongepowered.api.event.cause.Cause)

Example 8 with TEAccount

use of com.erigitic.config.TEAccount in project TotalEconomy by Erigitic.

the class JobManager method onPlayerPlaceBlock.

/**
 * Used for the place option in jobs. Will check if the job has the place node and if it does it will check if the
 * block that was placed is present in the config of the player's job. If it is, it will grab the job exp reward as
 * well as the pay.
 *
 * @param event ChangeBlockEvent.Place
 */
@Listener
public void onPlayerPlaceBlock(ChangeBlockEvent.Place event) {
    if (event.getCause().first(Player.class).isPresent()) {
        Player player = event.getCause().first(Player.class).get();
        UUID playerUUID = player.getUniqueId();
        String playerJob = getPlayerJob(player);
        Optional<TEJob> optPlayerJob = getJob(playerJob, true);
        BlockState state = event.getTransactions().get(0).getFinal().getState();
        String blockName = state.getType().getName();
        // Enable admins to determine block information by displaying it to them - WHEN they have the flag enabled
        if (accountManager.getUserOption("totaleconomy:block-place-info", player).orElse("0").equals("1")) {
            List<BlockTrait<?>> traits = new ArrayList<>(state.getTraits());
            int count = traits.size();
            List<Text> traitTexts = new ArrayList<>(count);
            for (int i = 0; i < count; i++) {
                Object traitValue = state.getTraitValue(traits.get(i)).orElse(null);
                traitTexts.add(i, Text.of(traits.get(i).getName(), '=', traitValue != null ? traitValue.toString() : "null"));
            }
            Text t = Text.of(TextColors.GRAY, "TRAITS:\n    ", Text.joinWith(Text.of(",\n    "), traitTexts.toArray(new Text[traits.size()])));
            player.sendMessage(Text.of("Block-Name: ", blockName));
            player.sendMessage(t);
        }
        if (optPlayerJob.isPresent()) {
            Optional<TEActionReward> reward = Optional.empty();
            List<String> sets = optPlayerJob.get().getSets();
            for (String s : sets) {
                Optional<TEJobSet> optSet = getJobSet(s);
                if (!optSet.isPresent()) {
                    logger.warn("Job " + playerJob + " has the nonexistent set \"" + s + "\"");
                    continue;
                }
                Optional<TEAction> action = optSet.get().getActionFor("place", blockName);
                if (!action.isPresent()) {
                    continue;
                }
                Optional<TEActionReward> currentReward = action.get().evaluatePlace(logger, state);
                if (!reward.isPresent()) {
                    reward = currentReward;
                    continue;
                }
                if (!currentReward.isPresent()) {
                    continue;
                }
                // Use the one giving higher exp in case of duplicates
                if (currentReward.get().getExpReward() > reward.get().getExpReward()) {
                    reward = currentReward;
                }
            }
            if (reward.isPresent()) {
                TEAccount playerAccount = (TEAccount) accountManager.getOrCreateAccount(player.getUniqueId()).get();
                boolean notify = getNotificationState(playerUUID);
                int expAmount = reward.get().getExpReward();
                BigDecimal payAmount = new BigDecimal(reward.get().getMoneyReward());
                Currency currency = totalEconomy.getDefaultCurrency();
                if (reward.get().getCurrencyId() != null) {
                    Optional<Currency> currencyOpt = totalEconomy.getTECurrencyRegistryModule().getById("totaleconomy:" + reward.get().getCurrencyId());
                    if (currencyOpt.isPresent()) {
                        currency = currencyOpt.get();
                    }
                }
                if (notify) {
                    notifyPlayer(player, payAmount, currency);
                }
                addExp(player, expAmount);
                playerAccount.deposit(currency, payAmount, event.getCause());
                checkForLevel(player);
            }
        }
    }
}
Also used : BlockTrait(org.spongepowered.api.block.trait.BlockTrait) TEAccount(com.erigitic.config.TEAccount) Currency(org.spongepowered.api.service.economy.Currency) Player(org.spongepowered.api.entity.living.player.Player) Text(org.spongepowered.api.text.Text) BigDecimal(java.math.BigDecimal) BlockState(org.spongepowered.api.block.BlockState) Listener(org.spongepowered.api.event.Listener)

Example 9 with TEAccount

use of com.erigitic.config.TEAccount in project TotalEconomy by Erigitic.

the class ShopManager method onItemPurchase.

/**
 * Handles a user purchasing an item from a shop.
 *
 * @param event Primary (Left mouse) click inventory
 * @param player The player clicking within an inventory
 * @param inventory The inventory being interacted with
 */
@Listener
@Exclude(ClickInventoryEvent.Shift.class)
public void onItemPurchase(ClickInventoryEvent.Primary event, @First Player player, @Getter("getTargetInventory") Inventory inventory) {
    Optional<PlayerShopInfo> playerShopInfoOpt = player.get(ShopKeys.PLAYER_SHOP_INFO);
    if (playerShopInfoOpt.isPresent()) {
        Location location = playerShopInfoOpt.get().getOpenShopLocation();
        Optional<TileEntity> tileEntityOpt = location.getTileEntity();
        if (tileEntityOpt.isPresent()) {
            Optional<Shop> shopOpt = tileEntityOpt.get().get(ShopKeys.SINGLE_SHOP);
            if (shopOpt.isPresent()) {
                Shop shop = shopOpt.get();
                ItemStack clickedItem = ItemStack.builder().fromSnapshot(event.getCursorTransaction().getDefault().copy()).build();
                Optional<ShopItem> shopItemOpt = clickedItem.get(ShopKeys.SHOP_ITEM);
                if (shopItemOpt.isPresent()) {
                    event.getCursorTransaction().setValid(false);
                    ShopItem shopItem = shopItemOpt.get();
                    TEAccount ownerAccount = (TEAccount) accountManager.getOrCreateAccount(shop.getOwner()).get();
                    TEAccount customerAccount = (TEAccount) accountManager.getOrCreateAccount(player.getUniqueId()).get();
                    if (customerAccount.getBalance(totalEconomy.getDefaultCurrency()).doubleValue() >= shopItem.getPrice()) {
                        ItemStack purchasedItem = removeShopItemData(clickedItem.copy());
                        Collection<ItemStackSnapshot> rejectedItems = player.getInventory().query(GridInventory.class, Hotbar.class).offer(purchasedItem).getRejectedItems();
                        if (rejectedItems.size() == 0) {
                            customerAccount.transfer(ownerAccount, totalEconomy.getDefaultCurrency(), BigDecimal.valueOf(shopItem.getPrice()), event.getCause());
                            Slot clickedSlot = event.getTransactions().get(0).getSlot();
                            updateItemInSlot(clickedSlot, clickedItem, clickedItem.getQuantity() - 1);
                        } else {
                            event.getTransactions().get(0).setValid(false);
                            player.sendMessage(messageManager.getMessage("shops.purchase.noroom"));
                        }
                    } else {
                        event.getTransactions().get(0).setValid(false);
                        player.sendMessage(messageManager.getMessage("shops.purchase.insufficientfunds"));
                    }
                } else {
                    event.getCursorTransaction().setValid(false);
                    invalidateTransactions(event.getTransactions());
                }
            }
        }
    }
}
Also used : TEAccount(com.erigitic.config.TEAccount) Location(org.spongepowered.api.world.Location) Listener(org.spongepowered.api.event.Listener) Exclude(org.spongepowered.api.event.filter.type.Exclude)

Example 10 with TEAccount

use of com.erigitic.config.TEAccount in project TotalEconomy by Erigitic.

the class TEJobManager method onPlayerBlockBreak.

/**
     * Used for the break option in jobs. Will check if the job has the break node and if it does it will check if the
     * block that was broken is present in the config of the player's job. If it is, it will grab the job exp reward as
     * well as the pay.
     *
     * @param event ChangeBlockEvent.Break
     */
@Listener
public void onPlayerBlockBreak(ChangeBlockEvent.Break event) {
    if (event.getCause().first(Player.class).isPresent()) {
        Player player = event.getCause().first(Player.class).get();
        UUID playerUUID = player.getUniqueId();
        String playerJob = getPlayerJob(player);
        Optional<TEJob> optPlayerJob = getJob(playerJob, true);
        String blockName = event.getTransactions().get(0).getOriginal().getState().getType().getName();
        Optional<UUID> blockCreator = event.getTransactions().get(0).getOriginal().getCreator();
        if (optPlayerJob.isPresent()) {
            // Prevent blocks placed by other players from counting towards a job
            if (!blockCreator.isPresent()) {
                Optional<TEActionReward> reward = Optional.empty();
                List<String> sets = optPlayerJob.get().getSets();
                for (String s : sets) {
                    Optional<TEJobSet> optSet = getJobSet(s);
                    if (!optSet.isPresent()) {
                        logger.warn("[TE] Job " + getPlayerJob(player) + " has the nonexistent set \"" + s + "\"");
                        continue;
                    }
                    reward = optSet.get().getRewardFor("break", blockName);
                }
                if (reward.isPresent()) {
                    int expAmount = reward.get().getExpReward();
                    BigDecimal payAmount = reward.get().getMoneyReward();
                    boolean notify = accountManager.getJobNotificationState(player);
                    TEAccount playerAccount = (TEAccount) accountManager.getOrCreateAccount(player.getUniqueId()).get();
                    if (notify) {
                        notifyPlayer(player, payAmount);
                    }
                    addExp(player, expAmount);
                    playerAccount.deposit(totalEconomy.getDefaultCurrency(), payAmount, Cause.of(NamedCause.of("TotalEconomy", totalEconomy.getPluginContainer())));
                    checkForLevel(player);
                }
            }
        }
    }
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) TEAccount(com.erigitic.config.TEAccount) BigDecimal(java.math.BigDecimal) Listener(org.spongepowered.api.event.Listener)

Aggregations

TEAccount (com.erigitic.config.TEAccount)18 BigDecimal (java.math.BigDecimal)14 Player (org.spongepowered.api.entity.living.player.Player)12 Listener (org.spongepowered.api.event.Listener)10 Text (org.spongepowered.api.text.Text)7 Currency (org.spongepowered.api.service.economy.Currency)6 HashMap (java.util.HashMap)5 CommandException (org.spongepowered.api.command.CommandException)5 TransactionResult (org.spongepowered.api.service.economy.transaction.TransactionResult)5 TECurrency (com.erigitic.config.TECurrency)3 Matcher (java.util.regex.Matcher)3 Pattern (java.util.regex.Pattern)3 User (org.spongepowered.api.entity.living.player.User)3 BlockState (org.spongepowered.api.block.BlockState)2 TileEntity (org.spongepowered.api.block.tileentity.TileEntity)2 BlockTrait (org.spongepowered.api.block.trait.BlockTrait)2 FishData (org.spongepowered.api.data.manipulator.mutable.item.FishData)2 Entity (org.spongepowered.api.entity.Entity)2 EntityDamageSource (org.spongepowered.api.event.cause.entity.damage.source.EntityDamageSource)2 ItemStack (org.spongepowered.api.item.inventory.ItemStack)2