Search in sources :

Example 6 with BuyingItem

use of com.almuradev.almura.feature.store.listing.BuyingItem in project Almura by AlmuraDev.

the class StoreScreen method listOrModify.

private void listOrModify() {
    final ItemStack selectedItem = this.adminItemList.getSelectedItem();
    if (selectedItem == null) {
        return;
    }
    final Optional<BuyingItem> buyingItem = this.store.getBuyingItems().stream().filter(i -> StoreScreen.isStackEqualIgnoreSize(i.asRealStack(), selectedItem)).findAny();
    final Optional<SellingItem> sellingItem = this.store.getSellingItems().stream().filter(i -> StoreScreen.isStackEqualIgnoreSize(i.asRealStack(), selectedItem)).findAny();
    if (buyingItem.isPresent() || sellingItem.isPresent()) {
        new StoreListScreen(this, this.store, buyingItem.orElse(null), sellingItem.orElse(null), selectedItem).display();
    } else {
        new StoreListScreen(this, this.store, selectedItem).display();
    }
}
Also used : Arrays(java.util.Arrays) UIComponent(net.malisis.core.client.gui.component.UIComponent) BuyingItem(com.almuradev.almura.feature.store.listing.BuyingItem) I18n(net.minecraft.client.resources.I18n) BigDecimal(java.math.BigDecimal) UISaneTooltip(com.almuradev.almura.shared.client.ui.component.UISaneTooltip) MalisisGui(net.malisis.core.client.gui.MalisisGui) BasicTextBox(net.malisis.core.client.gui.component.interaction.BasicTextBox) Side(net.minecraftforge.fml.relauncher.Side) Map(java.util.Map) BasicList(net.malisis.core.client.gui.component.container.BasicList) BasicContainer(net.malisis.core.client.gui.component.container.BasicContainer) NonNullList(net.minecraft.util.NonNullList) FontColors(net.malisis.core.util.FontColors) FeatureConstants(com.almuradev.almura.shared.feature.FeatureConstants) StoreModule(com.almuradev.almura.feature.store.StoreModule) UIButtonBuilder(net.malisis.core.client.gui.component.interaction.button.builder.UIButtonBuilder) ClientStoreManager(com.almuradev.almura.feature.store.client.ClientStoreManager) UITooltip(net.malisis.core.client.gui.component.decoration.UITooltip) Collectors(java.util.stream.Collectors) List(java.util.List) EntityPlayer(net.minecraft.entity.player.EntityPlayer) UIImage(net.malisis.core.client.gui.component.decoration.UIImage) Optional(java.util.Optional) SortType(com.almuradev.almura.feature.SortType) BasicLine(net.malisis.core.client.gui.component.decoration.BasicLine) HashMap(java.util.HashMap) ITooltipFlag(net.minecraft.client.util.ITooltipFlag) FeatureSortTypes(com.almuradev.almura.FeatureSortTypes) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Inject(javax.inject.Inject) ItemStack(net.minecraft.item.ItemStack) Minecraft(net.minecraft.client.Minecraft) Anchor(net.malisis.core.client.gui.Anchor) SellingItem(com.almuradev.almura.feature.store.listing.SellingItem) StoreItem(com.almuradev.almura.feature.store.listing.StoreItem) Subscribe(com.google.common.eventbus.Subscribe) BasicScreen(net.malisis.core.client.gui.BasicScreen) UIExpandingLabel(com.almuradev.almura.shared.client.ui.component.UIExpandingLabel) CreativeTabs(net.minecraft.creativetab.CreativeTabs) SideOnly(net.minecraftforge.fml.relauncher.SideOnly) UISelect(net.malisis.core.client.gui.component.interaction.UISelect) ComponentEvent(net.malisis.core.client.gui.event.ComponentEvent) Nullable(javax.annotation.Nullable) UIButton(net.malisis.core.client.gui.component.interaction.UIButton) UITextField(net.malisis.core.client.gui.component.interaction.UITextField) UILabel(net.malisis.core.client.gui.component.decoration.UILabel) TextFormatting(net.minecraft.util.text.TextFormatting) Store(com.almuradev.almura.feature.store.Store) SideType(com.almuradev.almura.feature.store.SideType) BasicForm(net.malisis.core.client.gui.component.container.BasicForm) FontRenderer(net.minecraft.client.gui.FontRenderer) ForgeRegistries(net.minecraftforge.fml.common.registry.ForgeRegistries) Comparator(java.util.Comparator) FontOptions(net.malisis.core.renderer.font.FontOptions) BuyingItem(com.almuradev.almura.feature.store.listing.BuyingItem) ItemStack(net.minecraft.item.ItemStack) SellingItem(com.almuradev.almura.feature.store.listing.SellingItem)

Example 7 with BuyingItem

use of com.almuradev.almura.feature.store.listing.BuyingItem 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);
}
Also used : IItemHandler(net.minecraftforge.items.IItemHandler) FilterRegistry(com.almuradev.almura.shared.feature.filter.FilterRegistry) Results(org.jooq.Results) Item(net.minecraft.item.Item) Inject(com.google.inject.Inject) StoreQueries(com.almuradev.almura.feature.store.database.StoreQueries) BuyingItem(com.almuradev.almura.feature.store.listing.BuyingItem) EntityPlayerMP(net.minecraft.entity.player.EntityPlayerMP) DatabaseManager(com.almuradev.almura.shared.database.DatabaseManager) BigDecimal(java.math.BigDecimal) Map(java.util.Map) DSLContext(org.jooq.DSLContext) StoreBuyingItem(com.almuradev.generated.store.tables.StoreBuyingItem) BasicBuyingItem(com.almuradev.almura.feature.store.basic.listing.BasicBuyingItem) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) EconomyService(org.spongepowered.api.service.economy.EconomyService) VanillaStack(com.almuradev.almura.shared.item.VanillaStack) Timestamp(java.sql.Timestamp) ClientboundListItemsResponsePacket(com.almuradev.almura.feature.store.network.ClientboundListItemsResponsePacket) FeatureConstants(com.almuradev.almura.shared.feature.FeatureConstants) Sponge(org.spongepowered.api.Sponge) DatabaseQueue(com.almuradev.almura.shared.database.DatabaseQueue) ServiceManager(org.spongepowered.api.service.ServiceManager) NetworkConfig(com.almuradev.almura.shared.network.NetworkConfig) UUID(java.util.UUID) Result(org.jooq.Result) Instant(java.time.Instant) StoreSellingItemDataRecord(com.almuradev.generated.store.tables.records.StoreSellingItemDataRecord) Collectors(java.util.stream.Collectors) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ClientConnectionEvent(org.spongepowered.api.event.network.ClientConnectionEvent) ChannelBinding(org.spongepowered.api.network.ChannelBinding) List(java.util.List) Stream(java.util.stream.Stream) StoreSellingItemData(com.almuradev.generated.store.tables.StoreSellingItemData) ClientboundStoreGuiResponsePacket(com.almuradev.almura.feature.store.network.ClientboundStoreGuiResponsePacket) CapabilityItemHandler(net.minecraftforge.items.CapabilityItemHandler) StoreSellingItemRecord(com.almuradev.generated.store.tables.records.StoreSellingItemRecord) ChannelId(org.spongepowered.api.network.ChannelId) IngameFeature(com.almuradev.almura.shared.feature.IngameFeature) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) Query(org.jooq.Query) Almura(com.almuradev.almura.Almura) Getter(org.spongepowered.api.event.filter.Getter) StoreBuyingItemData(com.almuradev.generated.store.tables.StoreBuyingItemData) BasicSellingItem(com.almuradev.almura.feature.store.basic.listing.BasicSellingItem) GameStartingServerEvent(org.spongepowered.api.event.game.state.GameStartingServerEvent) HashMap(java.util.HashMap) ServerboundListItemsRequestPacket(com.almuradev.almura.feature.store.network.ServerboundListItemsRequestPacket) Singleton(javax.inject.Singleton) ArrayList(java.util.ArrayList) ItemStack(net.minecraft.item.ItemStack) SQLException(java.sql.SQLException) Lists(com.google.common.collect.Lists) ItemHandlerHelper(net.minecraftforge.items.ItemHandlerHelper) Text(org.spongepowered.api.text.Text) StoreBuyingItemRecord(com.almuradev.generated.store.tables.records.StoreBuyingItemRecord) BasicStore(com.almuradev.almura.feature.store.basic.BasicStore) SellingItem(com.almuradev.almura.feature.store.listing.SellingItem) StoreItem(com.almuradev.almura.feature.store.listing.StoreItem) StoreSellingItem(com.almuradev.generated.store.tables.StoreSellingItem) GameState(org.spongepowered.api.GameState) CauseStackManager(org.spongepowered.api.event.CauseStackManager) PluginContainer(org.spongepowered.api.plugin.PluginContainer) TextColors(org.spongepowered.api.text.format.TextColors) Nullable(javax.annotation.Nullable) Record(org.jooq.Record) StoreBuyingItemDataRecord(com.almuradev.generated.store.tables.records.StoreBuyingItemDataRecord) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Scheduler(org.spongepowered.api.scheduler.Scheduler) ServerNotificationManager(com.almuradev.almura.feature.notification.ServerNotificationManager) EnumFacing(net.minecraft.util.EnumFacing) IOException(java.io.IOException) SerializationUtil(com.almuradev.almura.shared.util.SerializationUtil) Witness(com.almuradev.core.event.Witness) ClientboundStoresRegistryPacket(com.almuradev.almura.feature.store.network.ClientboundStoresRegistryPacket) ForgeRegistries(net.minecraftforge.fml.common.registry.ForgeRegistries) ResourceLocation(net.minecraft.util.ResourceLocation) Listener(org.spongepowered.api.event.Listener) UniqueAccount(org.spongepowered.api.service.economy.account.UniqueAccount) Comparator(java.util.Comparator) ServerboundModifyItemsPacket(com.almuradev.almura.feature.store.network.ServerboundModifyItemsPacket) UniqueAccount(org.spongepowered.api.service.economy.account.UniqueAccount) IItemHandler(net.minecraftforge.items.IItemHandler) SQLException(java.sql.SQLException) BasicStore(com.almuradev.almura.feature.store.basic.BasicStore) ClientboundListItemsResponsePacket(com.almuradev.almura.feature.store.network.ClientboundListItemsResponsePacket) DSLContext(org.jooq.DSLContext) BigDecimal(java.math.BigDecimal) EconomyService(org.spongepowered.api.service.economy.EconomyService) Results(org.jooq.Results) CauseStackManager(org.spongepowered.api.event.CauseStackManager) BuyingItem(com.almuradev.almura.feature.store.listing.BuyingItem) StoreBuyingItem(com.almuradev.generated.store.tables.StoreBuyingItem) BasicBuyingItem(com.almuradev.almura.feature.store.basic.listing.BasicBuyingItem) EntityPlayerMP(net.minecraft.entity.player.EntityPlayerMP) List(java.util.List) ArrayList(java.util.ArrayList) ItemStack(net.minecraft.item.ItemStack)

Example 8 with BuyingItem

use of com.almuradev.almura.feature.store.listing.BuyingItem in project Almura by AlmuraDev.

the class ClientboundListItemsResponsePacket method readFrom.

@Override
public void readFrom(final ChannelBuf buf) {
    this.id = buf.readString();
    this.type = StoreItemSegmentType.valueOf(buf.readString());
    final int count = buf.readInteger();
    if (count > 0) {
        if (type == StoreItemSegmentType.SELLING) {
            this.storeItems = new ArrayList<SellingItem>();
        } else {
            this.storeItems = new ArrayList<BuyingItem>();
        }
        for (int i = 0; i < count; i++) {
            final int record = buf.readInteger();
            final Instant created;
            try {
                created = SerializationUtil.bytesToObject(buf.readBytes(buf.readInteger()));
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
                continue;
            }
            final ResourceLocation location = new ResourceLocation(buf.readString(), buf.readString());
            final Item item = ForgeRegistries.ITEMS.getValue(location);
            if (item == null) {
                new IOException("Unknown item id '" + location.toString() + "' when receiving item! . Skipping...").printStackTrace();
                continue;
            }
            final int quantity = buf.readInteger();
            final int metadata = buf.readInteger();
            final BigDecimal price = ByteBufUtil.readBigDecimal((ByteBuf) buf);
            final int index = buf.readInteger();
            final int compoundDataLength = buf.readInteger();
            NBTTagCompound compound = null;
            if (compoundDataLength > 0) {
                try {
                    compound = SerializationUtil.compoundFromBytes(buf.readBytes(compoundDataLength));
                } catch (IOException e) {
                    e.printStackTrace();
                    continue;
                }
            }
            final Constructor<? extends AbstractStoreItem> constructor;
            try {
                constructor = this.type.getItemClass().getConstructor(Integer.TYPE, Instant.class, Item.class, Integer.TYPE, Integer.TYPE, BigDecimal.class, Integer.TYPE, NBTTagCompound.class);
                final AbstractStoreItem storeItem = constructor.newInstance(record, created, item, quantity, metadata, price, index, compound);
                if (this.type == StoreItemSegmentType.SELLING) {
                    ((List<SellingItem>) this.storeItems).add((SellingItem) storeItem);
                } else {
                    ((List<BuyingItem>) this.storeItems).add((BuyingItem) storeItem);
                }
            } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : AbstractStoreItem(com.almuradev.almura.feature.store.basic.listing.AbstractStoreItem) Instant(java.time.Instant) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) IOException(java.io.IOException) BasicSellingItem(com.almuradev.almura.feature.store.basic.listing.BasicSellingItem) SellingItem(com.almuradev.almura.feature.store.listing.SellingItem) BigDecimal(java.math.BigDecimal) InvocationTargetException(java.lang.reflect.InvocationTargetException) AbstractStoreItem(com.almuradev.almura.feature.store.basic.listing.AbstractStoreItem) Item(net.minecraft.item.Item) BasicSellingItem(com.almuradev.almura.feature.store.basic.listing.BasicSellingItem) BuyingItem(com.almuradev.almura.feature.store.listing.BuyingItem) SellingItem(com.almuradev.almura.feature.store.listing.SellingItem) StoreItem(com.almuradev.almura.feature.store.listing.StoreItem) ResourceLocation(net.minecraft.util.ResourceLocation) BuyingItem(com.almuradev.almura.feature.store.listing.BuyingItem) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

BuyingItem (com.almuradev.almura.feature.store.listing.BuyingItem)8 ArrayList (java.util.ArrayList)8 SellingItem (com.almuradev.almura.feature.store.listing.SellingItem)7 StoreItem (com.almuradev.almura.feature.store.listing.StoreItem)7 BigDecimal (java.math.BigDecimal)7 List (java.util.List)6 BasicBuyingItem (com.almuradev.almura.feature.store.basic.listing.BasicBuyingItem)5 BasicSellingItem (com.almuradev.almura.feature.store.basic.listing.BasicSellingItem)5 FeatureConstants (com.almuradev.almura.shared.feature.FeatureConstants)5 StoreBuyingItem (com.almuradev.generated.store.tables.StoreBuyingItem)5 IOException (java.io.IOException)5 Item (net.minecraft.item.Item)5 NBTTagCompound (net.minecraft.nbt.NBTTagCompound)5 ResourceLocation (net.minecraft.util.ResourceLocation)5 StoreSellingItem (com.almuradev.generated.store.tables.StoreSellingItem)4 StoreBuyingItemDataRecord (com.almuradev.generated.store.tables.records.StoreBuyingItemDataRecord)4 StoreBuyingItemRecord (com.almuradev.generated.store.tables.records.StoreBuyingItemRecord)4 StoreSellingItemDataRecord (com.almuradev.generated.store.tables.records.StoreSellingItemDataRecord)4 StoreSellingItemRecord (com.almuradev.generated.store.tables.records.StoreSellingItemRecord)4 Comparator (java.util.Comparator)4