use of org.spongepowered.api.service.economy.EconomyService in project Almura by AlmuraDev.
the class MembershipHandler method handleMembershipPurchase.
public void handleMembershipPurchase(Player player, int newMembershipLevel) {
// Typically only thing that fails here is if someone is running a hacked client. This method double checks that.
if (!player.hasPermission("almura.membership.purchase")) {
serverNotificationManager.sendWindowMessage(player, Text.of("Permission Denied"), Text.of("Missing: almura.membership.purchase"));
return;
}
final EconomyService econService = Sponge.getServiceManager().provide(EconomyService.class).orElse(null);
final LuckPerms permService = Sponge.getServiceManager().provide(LuckPerms.class).orElse(null);
if (econService != null && permService != null) {
final Account account = econService.getOrCreateAccount(player.getUniqueId()).orElse(null);
if (account != null) {
BigDecimal balance;
final Currency currency = econService.getDefaultCurrency();
balance = account.getBalance(currency);
double fee = 0;
if (newMembershipLevel == 1) {
fee = 2500000;
if (!(balance.doubleValue() >= fee)) {
serverNotificationManager.sendWindowMessage(player, Text.of("Insufficient Funds"), Text.of("Insufficient Funds to purchase Citizen Membership."));
return;
}
}
if (newMembershipLevel == 2) {
fee = 5000000;
if (!(balance.doubleValue() >= fee)) {
serverNotificationManager.sendWindowMessage(player, Text.of("Insufficient Funds"), Text.of("Insufficient Funds to purchase Explorer Membership."));
return;
}
}
if (newMembershipLevel == 3) {
fee = 10000000;
if (!(balance.doubleValue() >= fee)) {
serverNotificationManager.sendWindowMessage(player, Text.of("Insufficient Funds"), Text.of("Insufficient Funds to purchase Pioneer Membership."));
return;
}
}
String currentGroup = permService.getUserManager().getUser(player.getUniqueId()).getPrimaryGroup();
String newMembership = "";
if (newMembershipLevel == 1)
newMembership = "Citizen";
if (newMembershipLevel == 2)
newMembership = "Explorer";
if (newMembershipLevel == 3)
newMembership = "Pioneer";
BigDecimal deduct = new BigDecimal(fee);
final String command = "lp user " + player.getName() + " promote members";
if (newMembershipLevel == 1 && currentGroup.equalsIgnoreCase("survivor")) {
this.commandManager.process(Sponge.getServer().getConsole(), command);
account.withdraw(currency, deduct, Sponge.getCauseStackManager().getCurrentCause());
this.network.sendTo(player, new ClientboundMembershipSuccessPacket(newMembership));
return;
}
if (newMembershipLevel == 2 && (currentGroup.equalsIgnoreCase("survivor") || currentGroup.equalsIgnoreCase("citizen"))) {
if (currentGroup.equalsIgnoreCase("survivor")) {
this.commandManager.process(Sponge.getServer().getConsole(), command);
}
this.commandManager.process(Sponge.getServer().getConsole(), command);
account.withdraw(currency, deduct, Sponge.getCauseStackManager().getCurrentCause());
this.network.sendTo(player, new ClientboundMembershipSuccessPacket(newMembership));
return;
}
if (newMembershipLevel == 3 && (currentGroup.equalsIgnoreCase("survivor") || currentGroup.equalsIgnoreCase("citizen") || currentGroup.equalsIgnoreCase("explorer"))) {
if (currentGroup.equalsIgnoreCase("survivor")) {
this.commandManager.process(Sponge.getServer().getConsole(), command);
this.commandManager.process(Sponge.getServer().getConsole(), command);
}
if (currentGroup.equalsIgnoreCase("citizen")) {
this.commandManager.process(Sponge.getServer().getConsole(), command);
}
this.commandManager.process(Sponge.getServer().getConsole(), command);
account.withdraw(currency, deduct, Sponge.getCauseStackManager().getCurrentCause());
this.network.sendTo(player, new ClientboundMembershipSuccessPacket(newMembership));
return;
}
// This should be impossible, leaving this debug line.
System.out.println("Current Group: " + currentGroup + " Failed to upgrade, no path found");
}
} else {
serverNotificationManager.sendWindowMessage(player, Text.of("Error"), Text.of("Economy or Permission Service offline!"));
}
}
use of org.spongepowered.api.service.economy.EconomyService in project Almura by AlmuraDev.
the class ServerStoreManager method handleSellingItemTransaction.
public void handleSellingItemTransaction(final Player player, final String id, final int recNo, final int quantity) {
checkNotNull(player);
checkNotNull(id);
checkState(recNo >= 0);
checkState(quantity >= 0);
final Store store = this.getStore(id).orElse(null);
if (store == null) {
this.logger.error("Player '{}' attempted to sell an item to store '{}' but the server has no knowledge of it. Syncing " + "store registry...", player.getName(), id);
this.syncStoreRegistryTo(player);
return;
}
final EconomyService economyService = this.serviceManager.provide(EconomyService.class).orElse(null);
if (economyService == null) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("Critical error encountered, check the " + "server console for more details!"));
this.logger.error("Player '{}' attempted to sell an to from store '{}' but the economy service no longer exists. This is a " + "critical error that should be reported to your economy plugin ASAP.", player.getName(), id);
return;
}
final UniqueAccount account = economyService.getOrCreateAccount(player.getUniqueId()).orElse(null);
if (account == null) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("Critical error encountered, check the " + "server console for more details!"));
this.logger.error("Player '{}' attempted to sell an item to store '{}' but the economy service returned no account for them. " + "This is a critical error that should be reported to your economy plugin ASAP.", player.getName(), id);
return;
}
final List<SellingItem> sellingItems = store.getSellingItems();
if (sellingItems.isEmpty()) {
this.logger.error("Player '{}' attempted to sell an item to store '{}' but the server knows of no " + "selling items for it. This could be a de-sync or an exploit.", player.getName(), store.getId());
this.network.sendTo(player, new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.SELLING, sellingItems));
return;
}
final SellingItem found = sellingItems.stream().filter(v -> v.getRecord() == recNo).findAny().orElse(null);
if (found == null) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("Critical error encountered, check the " + "server console for more details!"));
this.logger.error("Player '{}' attempted to sell item '{}' to store '{}' but the server knows of no knowledge of it. This could be a " + "de-sync or an exploit. Discarding...", player.getName(), recNo, store.getId());
this.network.sendTo(player, new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.SELLING, sellingItems));
return;
}
final boolean infinite = found.getQuantity() == FeatureConstants.UNLIMITED;
if (!infinite && found.getQuantity() < quantity) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("There is not enough quantity left to sell " + "your product!"));
return;
}
final BigDecimal price = found.getPrice();
final double total = price.doubleValue() * quantity;
final EntityPlayerMP serverPlayer = (EntityPlayerMP) player;
final IItemHandler inventory = serverPlayer.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.UP);
final SellingItem copyStack = found.copy();
copyStack.setQuantity(quantity);
int amountLeft = copyStack.getQuantity();
for (int j = 0; j < inventory.getSlots(); j++) {
final ItemStack slotStack = inventory.getStackInSlot(j);
if (ItemHandlerHelper.canItemStacksStack(slotStack, copyStack.asRealStack())) {
amountLeft -= inventory.extractItem(j, amountLeft, false).getCount();
}
if (amountLeft <= 0) {
break;
}
}
if (amountLeft != 0) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("Critical error encountered, check the " + "server console for more details!"));
this.logger.error("Player '{}' attempted to sell item '{}' to store '{}' but they do not have enough inventory quantity. " + "This could be a de-sync or an exploit. Discarding...", player.getName(), recNo, store.getId());
return;
}
this.scheduler.createTaskBuilder().async().execute(() -> {
try (final DSLContext context = this.databaseManager.createContext(true)) {
int result;
if (!infinite) {
result = StoreQueries.createUpdateSellingItem(found.getRecord(), found.getQuantity() - quantity, found.getIndex(), found.getPrice()).build(context).execute();
if (result == 0) {
// TODO It failed, message
return;
}
}
result = StoreQueries.createInsertSellingTransaction(Instant.now(), found.getRecord(), player.getUniqueId(), found.getPrice(), quantity).build(context).execute();
if (result == 0) {
// TODO It failed, message
StoreQueries.createUpdateSellingItem(found.getRecord(), found.getQuantity(), found.getIndex(), found.getPrice()).build(context).execute();
return;
}
final List<SellingItem> finalSellingItems = new ArrayList<>();
if (!infinite) {
final Results results = StoreQueries.createFetchSellingItemsAndDataFor(store.getId(), false).build(context).fetchMany();
results.forEach(r -> finalSellingItems.addAll(this.parseSellingItemsFrom(r)));
}
this.scheduler.createTaskBuilder().execute(() -> {
if (!infinite) {
store.putSellingItems(finalSellingItems);
}
// Pay the seller
try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
frame.pushCause(store);
account.deposit(economyService.getDefaultCurrency(), BigDecimal.valueOf(total), frame.getCurrentCause());
this.notificationManager.sendPopupNotification(player, Text.of(TextColors.GREEN, "Transaction Complete"), Text.of("Sold ", TextColors.AQUA, quantity, TextColors.WHITE, " x ", TextColors.YELLOW, found.asRealStack().getDisplayName(), TextColors.RESET, " for a total of ", TextColors.GOLD, "$", FeatureConstants.CURRENCY_DECIMAL_FORMAT.format(total)), 3);
}
if (!infinite) {
this.network.sendToAll(new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.SELLING, store.getSellingItems()));
}
}).submit(this.container);
} catch (final SQLException e) {
e.printStackTrace();
}
}).submit(this.container);
}
use of org.spongepowered.api.service.economy.EconomyService in project Almura by AlmuraDev.
the class ServerStoreManager method handleBuyingItemTransaction.
/**
* Transaction (Selling/Buying)
*/
public void handleBuyingItemTransaction(final Player player, final String id, final int recNo, final int quantity) {
checkNotNull(player);
checkNotNull(id);
checkState(recNo >= 0);
checkState(quantity >= 0);
final Store store = this.getStore(id).orElse(null);
if (store == null) {
this.logger.error("Player '{}' attempted to buy an item from store '{}' but the server has no knowledge of it. Syncing " + "store registry...", player.getName(), id);
this.syncStoreRegistryTo(player);
return;
}
final EconomyService economyService = this.serviceManager.provide(EconomyService.class).orElse(null);
if (economyService == null) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("Critical error encountered, check the " + "server console for more details!"));
this.logger.error("Player '{}' attempted to buy an item from store '{}' but the economy service no longer exists. This is a " + "critical error that should be reported to your economy plugin ASAP.", player.getName(), id);
return;
}
final UniqueAccount account = economyService.getOrCreateAccount(player.getUniqueId()).orElse(null);
if (account == null) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("Critical error encountered, check the " + "server console for more details!"));
this.logger.error("Player '{}' attempted to buy an item from store '{}' but the economy service returned no account for them. " + "This is a critical error that should be reported to your economy plugin ASAP.", player.getName(), id);
return;
}
final List<BuyingItem> buyingItems = store.getBuyingItems();
if (buyingItems.isEmpty()) {
this.logger.error("Player '{}' attempted to buy an item from store '{}' but the server knows of no " + " buying items for it. This could be a de-sync or an exploit.", player.getName(), store.getId());
this.network.sendTo(player, new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.BUYING, buyingItems));
return;
}
final BuyingItem found = buyingItems.stream().filter(v -> v.getRecord() == recNo).findAny().orElse(null);
if (found == null) {
this.logger.error("Player '{}' attempted to buy item '{}' from store '{}' but the server knows of no knowledge of it. " + "This could be a de-sync or an exploit. Discarding...", player.getName(), recNo, store.getId());
this.network.sendTo(player, new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.BUYING, buyingItems));
return;
}
final boolean infinite = found.getQuantity() == FeatureConstants.UNLIMITED;
if (!infinite && found.getQuantity() < quantity) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("There is not enough quantity left to fulfill your order!"));
return;
}
final BigDecimal balance = account.getBalance(economyService.getDefaultCurrency());
final BigDecimal price = found.getPrice();
final double total = price.doubleValue() * quantity;
if (total > balance.doubleValue()) {
final String formattedTotal = FeatureConstants.CURRENCY_DECIMAL_FORMAT.format(total);
final String formattedBalance = FeatureConstants.CURRENCY_DECIMAL_FORMAT.format(balance.doubleValue());
final String formattedDifference = FeatureConstants.CURRENCY_DECIMAL_FORMAT.format(total - balance.doubleValue());
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("You attempted to purchase items totaling to ", TextColors.RED, formattedTotal, TextColors.RESET, " while you only have ", TextColors.GREEN, formattedBalance, TextColors.RESET, ".", Text.NEW_LINE, Text.NEW_LINE, "You need ", TextColors.LIGHT_PURPLE, formattedDifference, TextColors.RESET, " more!"));
return;
}
EntityPlayerMP serverPlayer = (EntityPlayerMP) player;
final IItemHandler inventory = serverPlayer.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.UP);
final BuyingItem copyStack = found.copy();
copyStack.setQuantity(quantity);
final ItemStack simulatedResultStack = ItemHandlerHelper.insertItemStacked(inventory, copyStack.asRealStack(), true);
if (!simulatedResultStack.isEmpty()) {
this.notificationManager.sendWindowMessage(player, Text.of("Store"), Text.of("You lack sufficient inventory space to " + "purchase these item(s)!"));
return;
}
// Charge the buyer
try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
frame.pushCause(store);
account.withdraw(economyService.getDefaultCurrency(), BigDecimal.valueOf(total), frame.getCurrentCause());
this.notificationManager.sendPopupNotification(player, Text.of(TextColors.GREEN, "Transaction Complete"), Text.of("Purchased ", TextColors.AQUA, quantity, TextColors.WHITE, " x ", TextColors.YELLOW, found.asRealStack().getDisplayName(), TextColors.RESET, " for a total of ", TextColors.GOLD, "$", FeatureConstants.CURRENCY_DECIMAL_FORMAT.format(total)), 3);
}
this.scheduler.createTaskBuilder().async().execute(() -> {
try (final DSLContext context = this.databaseManager.createContext(true)) {
int result;
if (!infinite) {
result = StoreQueries.createUpdateBuyingItem(found.getRecord(), found.getQuantity() - quantity, found.getIndex(), found.getPrice()).build(context).execute();
if (result == 0) {
// TODO It failed, message
return;
}
}
result = StoreQueries.createInsertBuyingTransaction(Instant.now(), found.getRecord(), player.getUniqueId(), found.getPrice(), quantity).build(context).execute();
if (result == 0) {
// TODO It failed, message
StoreQueries.createUpdateBuyingItem(found.getRecord(), found.getQuantity(), found.getIndex(), found.getPrice()).build(context).execute();
return;
}
final List<BuyingItem> finalBuyingItems = new ArrayList<>();
if (!infinite) {
final Results results = StoreQueries.createFetchBuyingItemsAndDataFor(store.getId(), false).build(context).fetchMany();
results.forEach(r -> finalBuyingItems.addAll(this.parseBuyingItemsFor(r)));
}
this.scheduler.createTaskBuilder().execute(() -> {
if (!infinite) {
store.putBuyingItems(finalBuyingItems);
}
final ItemStack resultStack = ItemHandlerHelper.insertItemStacked(inventory, copyStack.asRealStack(), false);
if (!resultStack.isEmpty()) {
// TODO Inventory changed awaiting DB and now we're full...could drop it on the ground? It is an off-case
}
if (!infinite) {
this.network.sendToAll(new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.BUYING, store.getBuyingItems()));
}
}).submit(this.container);
} catch (final SQLException e) {
e.printStackTrace();
}
}).submit(this.container);
}
use of org.spongepowered.api.service.economy.EconomyService in project Almura by AlmuraDev.
the class ServerClaimManager method sendUpdate.
protected void sendUpdate(final Player player, Claim claim) {
if (GriefDefender.getCore() != null) {
boolean isWorldOrilla = false;
boolean isWorldAsgard = false;
if (Sponge.getServer().getWorld("Orilla").isPresent()) {
isWorldOrilla = Sponge.getServer().getWorld("Orilla").get().getUniqueId() == claim.getWorldUniqueId();
}
if (Sponge.getServer().getWorld("Asgard").isPresent()) {
isWorldAsgard = Sponge.getServer().getWorld("Asgard").get().getUniqueId() == claim.getWorldUniqueId();
}
if (GriefDefender.getPermissionManager() != null) {
if (claim == null) {
// This is intended to catch when a delayed task is sent to this method and claim is purposely left null.
claim = GriefDefender.getCore().getClaimManager(player.getWorld().getUniqueId()).getClaimAt(player.getLocation().getPosition().toInt());
}
if (claim != null) {
boolean isClaim = true;
boolean hasWECUI = false;
boolean isForSale = false;
boolean showWarnings = true;
String claimName = "";
String claimGreeting = "";
String claimFarewell = "";
String dateCreated = "";
String claimOwner = "";
String claimType = "";
double claimEconBalance = 0.0;
double claimTaxRate = 0.0;
double claimTaxes = 0.0;
double claimBlockCost = 0.0;
double claimBlockSell = 0.0;
int claimSize = 0;
double claimTaxBalance = 0.0;
double claimSalePrice = 0.0;
final boolean isWilderness = claim.isWilderness();
final boolean isTownClaim = claim.isTown();
final boolean isAdminClaim = claim.isAdminClaim();
final boolean isBasicClaim = claim.isBasicClaim();
final boolean isSubdivision = claim.isSubdivision();
if (claim.getData() != null) {
showWarnings = claim.getData().allowDenyMessages();
}
if (player != null && GriefDefender.getCore().getWorldEditProvider() != null) {
hasWECUI = GriefDefender.getCore().getWorldEditProvider().hasCUISupport(player.getUniqueId());
}
if (claim.getOwnerName() != null) {
claimOwner = claim.getOwnerName();
}
if (claim.getData() != null && claim.getData().getGreeting().isPresent()) {
claimGreeting = ((TextComponent) claim.getData().getGreeting().get()).content();
}
if (claim.getData() != null && claim.getData().getFarewell().isPresent()) {
claimFarewell = ((TextComponent) claim.getData().getFarewell().get()).content();
}
if (claim.getDisplayName() == null) {
claimName = "Name Not Set";
} else {
claimName = claim.getDisplayName();
}
claimType = claim.getType().getName();
dateCreated = claim.getData().getDateCreated().toString();
if (claim.getData() != null) {
final EconomyService service = Sponge.getServiceManager().provide(EconomyService.class).orElse(null);
if (service != null && player != null) {
if (claim.getEconomyData().isForSale()) {
isForSale = true;
claimSalePrice = this.claimSalePrice(claim);
}
// Todo: implement the rest of the econ stuffz.
claimTaxRate = this.claimTaxRate(claim);
claimTaxes = this.claimTaxes(claim);
claimBlockCost = this.claimBlockCost(claim);
claimBlockSell = this.claimBlockSell(claim);
final Currency currency = service.getDefaultCurrency();
if (claim.getEconomyData() != null) {
claimTaxBalance = this.claimTaxBalance(claim);
UUID accountID = claim.getEconomyAccountId();
if (!(accountID == null)) {
final UniqueAccount claimAccount = service.getOrCreateAccount(accountID).orElse(null);
claimEconBalance = claimAccount.getBalance(currency).doubleValue();
}
}
}
}
if (!claim.isWilderness()) {
claimSize = claim.getArea();
}
// Set custom Claim Name for Protected Area's
if (isWorldAsgard || isWorldOrilla) {
claimName = "Server Protected Area";
}
if (player != null) {
if (debug)
System.out.println("Sending Claim packet update to: [" + player.getName() + "] for Claim: [" + claim.getDisplayName() + "] Wilderness: [" + isWilderness + "]");
this.network.sendTo(player, new ClientboundClaimDataPacket(isClaim, claimName, claimOwner, isWilderness, isTownClaim, isAdminClaim, isBasicClaim, isSubdivision, claimEconBalance, claimGreeting, claimFarewell, dateCreated, claimType, claimSize, isForSale, showWarnings, claimTaxRate, claimTaxes, claimBlockCost, claimBlockSell, hasWECUI, claimTaxBalance, claimSalePrice));
}
}
}
}
}
use of org.spongepowered.api.service.economy.EconomyService in project Almura by AlmuraDev.
the class ServerHeadUpDisplayManager method createPlayerCurrencyPacket.
@Nullable
private ClientboundPlayerCurrencyPacket createPlayerCurrencyPacket(final Player player) {
final EconomyService service = Sponge.getServiceManager().provide(EconomyService.class).orElse(null);
if (service != null) {
final Account account = service.getOrCreateAccount(player.getUniqueId()).orElse(null);
BigDecimal balance = BigDecimal.ZERO;
if (account != null) {
final Currency currency = service.getDefaultCurrency();
balance = account.getBalance(currency);
}
return new ClientboundPlayerCurrencyPacket(balance);
}
return null;
}
Aggregations