Exemplo n.º 1
0
        public void HandleRequest(IRequest request)
        {
            var character = request.Session.Character;
            var orderId   = request.Data.GetOrDefault <int>(k.ID);
            var newPrice  = request.Data.GetOrDefault <double>(k.price);
            var testMode  = request.Session.AccessLevel.IsAdminOrGm();


            using (var scope = Db.CreateTransaction())
            {
                newPrice.ThrowIfLessOrEqual(0, ErrorCodes.IllegalMarketPrice);

                var order = _marketOrderRepository.Get(orderId).ThrowIfNull(ErrorCodes.ItemNotFound);
                order.submitterEID.ThrowIfNotEqual(character.Eid, ErrorCodes.AccessDenied);

                if (!request.Session.AccessLevel.IsAdminOrGm())
                {
                    if (!order.IsModifyTimeValid())
                    {
                        Message.Builder.FromRequest(request).WithData(order.GetValidModifyInfo()).WrapToResult().Send();
                        return;
                    }
                }


                var newTotalPrice = newPrice * order.quantity;
                var oldPrice      = order.FullPrice;

                order.price = newPrice; // set the new price

                if (!order.isSell)
                {
                    //BUY order
                    var priceDifference = newTotalPrice - oldPrice;

                    if (Math.Abs(priceDifference) < double.Epsilon)
                    {
                        //nothing to do
                        return;
                    }

                    // take the deposit from the character or corp
                    _marketHelper.CashIn(character, order.useCorporationWallet, priceDifference, order.itemDefinition, 1, TransactionType.ModifyMarketOrder);

                    //store the deposit in the central bank
                    var dockingBase = order.GetMarket().GetDockingBase();
                    dockingBase.AddCentralBank(TransactionType.ModifyMarketOrder, priceDifference);
                }

                //update the price in sql
                _marketOrderRepository.UpdatePrice(order);

                var result = _marketHelper.GetMarketOrdersInfo(character);
                Message.Builder.FromRequest(request).WithData(result).WrapToResult().Send();

                scope.Complete();
            }

            Task.Run(() => { BackgroundProcess(testMode); });
        }
        public void HandleRequest(IRequest request)
        {
            using (var scope = Db.CreateTransaction())
            {
                var marketItemID = request.Data.GetOrDefault <int>(k.marketItemID);

                var result = new Dictionary <string, object>();

                var marketOrder = _marketOrderRepository.Get(marketItemID).ThrowIfNull(ErrorCodes.ItemNotFound);

                var character = request.Session.Character;
                marketOrder.submitterEID.ThrowIfNotEqual(character.Eid, ErrorCodes.OwnerMismatch);

                //check minimal duration
                if (!marketOrder.IsModifyTimeValid())
                {
                    Message.Builder.FromRequest(request).WithData(marketOrder.GetValidModifyInfo()).WrapToResult().Send();
                    return;
                }

                var canceledItem = marketOrder.Cancel(_marketOrderRepository);

                if (canceledItem != null)
                {
                    result.Add(k.item, canceledItem.BaseInfoToDictionary());
                }

                result.Add(k.marketItemID, marketOrder.id); //return the item id anyways

                Message.Builder.FromRequest(request).WithData(result).WrapToResult().Send();

                scope.Complete();
            }
        }
Exemplo n.º 3
0
        public void RemoveItemsByCategoryFlags(CategoryFlags categoryFlag, bool withVendor = false)
        {
            var definitions = _entityServices.Defaults.GetAll().GetDefinitionsByCategoryFlag(categoryFlag);

            var defArrayString = definitions.ArrayToString();

            var query = "SELECT marketitemid FROM dbo.marketitems WHERE itemdefinition IN (" + defArrayString + ") and isvendoritem=0";

            var orders = Db.Query().CommandText(query)
                         .Execute()
                         .Select(r => _marketOrderRepository.Get(r.GetValue <int>("marketitemid")))
                         .Where(o => o != null)
                         .ToArray();

            var count = 0;

            Logger.Info("cancelling " + orders.Length + " market items for cf:" + categoryFlag);

            foreach (var order in orders)
            {
                Logger.Info("cancelling " + order.EntityDefault.Name + " quantity:" + order.quantity);
                order.Cancel(_marketOrderRepository);
                count++;
            }

            Logger.Info("cancelled " + count + " market items for cf:" + categoryFlag);

            if (!withVendor)
            {
                return;
            }
            Logger.Info("removing vendor market items for cf:" + categoryFlag);

            query = "delete marketitems WHERE itemdefinition IN (" + defArrayString + ") and isvendoritem=1";
            count = Db.Query().CommandText(query).ExecuteNonQuery();

            Logger.Info("removed " + count + " vendor market items for cf:" + categoryFlag);
        }
        public void HandleRequest(IRequest request)
        {
            using (var scope = Db.CreateTransaction())
            {
                var buyer                = request.Session.Character;
                var marketItemId         = request.Data.GetOrDefault <int>(k.marketItemID);
                var useCorporationWallet = request.Data.GetOrDefault <int>(k.useCorporationWallet) == 1;
                var quantity             = request.Data.GetOrDefault <int>(k.quantity);

                quantity.ThrowIfLessOrEqual(0, ErrorCodes.WTFErrorMedicalAttentionSuggested);
                buyer.IsDocked.ThrowIfFalse(ErrorCodes.CharacterHasToBeDocked);
                buyer.CheckPrivilegedTransactionsAndThrowIfFailed();

                var market = buyer.GetCurrentDockingBase().GetMarketOrThrow();

                var sellOrder = _marketOrderRepository.Get(marketItemId).ThrowIfNull(ErrorCodes.ItemNotFound);

                sellOrder.submitterEID.ThrowIfEqual(buyer.Eid, ErrorCodes.CannotBuyFromYourself);

                var corporationEid = buyer.CorporationEid;

                if (sellOrder.forMembersOf != null)
                {
                    corporationEid.ThrowIfNotEqual((long)sellOrder.forMembersOf, ErrorCodes.AccessDenied);
                }

                var publicContainer = buyer.GetPublicContainerWithItems();

                var sellerEid = sellOrder.submitterEID;
                var seller    = Character.GetByEid(sellerEid);

                if (!sellOrder.isVendorItem)
                {
                    //nem vendor, hanem player az aki eladja a cuccot

                    var forCorporation = sellOrder.forMembersOf != null;

                    var boughtQuantity = quantity;

                    seller.ThrowIfEqual(null, ErrorCodes.CharacterNotFound);

                    // the item as entity
                    var itemOnMarket = market.GetItemByMarketOrder(sellOrder);

                    var resultItem = itemOnMarket;
                    if (sellOrder.quantity == quantity)
                    {
                        //delete the sell order coz it's done
                        _marketOrderRepository.Delete(sellOrder);
                        sellOrder.quantity = 0;
                    }
                    else if (sellOrder.quantity > quantity)
                    {
                        sellOrder.quantity = sellOrder.quantity - quantity;
                        _marketOrderRepository.UpdateQuantity(sellOrder);

                        resultItem = itemOnMarket.Unstack(quantity);
                        itemOnMarket.Save();
                    }
                    else if (sellOrder.quantity < quantity)
                    {
                        //bought quantity => marketitem.quantity
                        boughtQuantity = sellOrder.quantity;

                        //delete the sell order coz it's done
                        _marketOrderRepository.Delete(sellOrder);
                        sellOrder.quantity = 0;
                    }

                    resultItem.Owner = buyer.Eid;

                    // add to public container
                    publicContainer.AddItem(resultItem, false);
                    publicContainer.Save();

                    //take money
                    _marketHelper.CashIn(buyer, useCorporationWallet, sellOrder.price, sellOrder.itemDefinition, boughtQuantity, TransactionType.marketBuy);
                    //pay out
                    market.PayOutToSeller(seller, sellOrder.useCorporationWallet, resultItem.Definition, sellOrder.price, boughtQuantity, TransactionType.marketSell, sellOrder.IsAffectsAverage(), forCorporation);


                    Market.SendMarketItemBoughtMessage(buyer, resultItem);

                    Message.Builder.SetCommand(Commands.MarketSellOrderUpdate)
                    .WithData(new Dictionary <string, object> {
                        { k.sellOrder, sellOrder.ToDictionary() }
                    })
                    .ToCharacters(seller, buyer)
                    .Send();
                }
                else
                {
                    // the item is a vendor sell order
                    if (sellOrder.quantity < 0)
                    {
                        //infinite quantity case
                        _marketHelper.CashIn(buyer, useCorporationWallet, sellOrder.price, sellOrder.itemDefinition, quantity, TransactionType.marketBuy);

                        var boughtItem = publicContainer.CreateAndAddItem(sellOrder.itemDefinition, false, item =>
                        {
                            item.Owner    = buyer.Eid;
                            item.Quantity = quantity;
                        });
                        Market.SendMarketItemBoughtMessage(buyer, boughtItem);

                        //average price
                        _marketHandler.InsertAveragePrice(market, sellOrder.itemDefinition, quantity * sellOrder.price, quantity);
                        market.AddCentralBank(TransactionType.marketBuy, quantity * sellOrder.price); //vendor income
                    }
                    else
                    {
                        // vendor finite
                        var boughtQuantity = quantity;

                        if (sellOrder.quantity == quantity)
                        {
                            sellOrder.quantity = 0; //signal order delete
                            //all sold
                            _marketOrderRepository.Delete(sellOrder);
                        }
                        else if (sellOrder.quantity < quantity)
                        {
                            boughtQuantity     = sellOrder.quantity; //clip the amount
                            sellOrder.quantity = 0;                  //signal order delete
                            //all sold
                            _marketOrderRepository.Delete(sellOrder);
                        }
                        else if (sellOrder.quantity > quantity)
                        {
                            sellOrder.quantity -= quantity;
                            //update entry
                            _marketOrderRepository.UpdateQuantity(sellOrder);
                        }

                        _marketHelper.CashIn(buyer, useCorporationWallet, sellOrder.price, sellOrder.itemDefinition, boughtQuantity, TransactionType.marketBuy);

                        //average price
                        _marketHandler.InsertAveragePrice(market, sellOrder.itemDefinition, boughtQuantity * sellOrder.price, boughtQuantity);
                        market.AddCentralBank(TransactionType.marketBuy, boughtQuantity * sellOrder.price); //vendor income

                        var boughtItem = publicContainer.CreateAndAddItem(sellOrder.itemDefinition, false, item =>
                        {
                            item.Owner    = buyer.Eid;
                            item.Quantity = boughtQuantity;
                        });
                        Market.SendMarketItemBoughtMessage(buyer, boughtItem);

                        Message.Builder.SetCommand(Commands.MarketSellOrderUpdate)
                        .WithData(new Dictionary <string, object> {
                            { k.sellOrder, sellOrder.ToDictionary() }
                        })
                        .ToCharacter(buyer)
                        .Send();
                    }
                }

                publicContainer.Save();

                Message.Builder.SetCommand(Commands.ListContainer)
                .WithData(publicContainer.ToDictionary())
                .ToCharacter(buyer)
                .Send();

                scope.Complete();
            }
        }
Exemplo n.º 5
0
        public void HandleRequest(IRequest request)
        {
            using (var scope = Db.CreateTransaction())
            {
                var seller        = request.Session.Character;
                var itemEid       = request.Data.GetOrDefault <long>(k.itemEID);
                var duration      = request.Data.GetOrDefault <int>(k.duration);
                var pricePerPiece = request.Data.GetOrDefault <double>(k.price);
                var quantity      = request.Data.GetOrDefault <int>(k.quantity);
                var useSellerCorporationWallet = request.Data.GetOrDefault <int>(k.useCorporationWallet) == 1;
                var containerEid     = request.Data.GetOrDefault <long>(k.container);
                var forMyCorporation = request.Data.GetOrDefault <int>(k.forMembersOf) == 1;
                var targetOrderId    = request.Data.GetOrDefault <int>(k.targetOrder);

                seller.IsDocked.ThrowIfFalse(ErrorCodes.CharacterHasToBeDocked);
                seller.CheckPrivilegedTransactionsAndThrowIfFailed();

                quantity.ThrowIfLessOrEqual(0, ErrorCodes.WTFErrorMedicalAttentionSuggested);
                pricePerPiece.ThrowIfLessOrEqual(0, ErrorCodes.IllegalMarketPrice);
                duration.ThrowIfLess(1, ErrorCodes.MinimalDurationNotReached);

                var market = seller.GetCurrentDockingBase().GetMarketOrThrow();

                var corporationEid = seller.CorporationEid;

                var publicContainer = seller.GetPublicContainerWithItems();

                var sourceContainer = (Container)publicContainer.GetItemOrThrow(containerEid, true);

                long?forMembersOf = null;
                if (forMyCorporation)
                {
                    if (!DefaultCorporationDataCache.IsCorporationDefault(corporationEid))
                    {
                        forMembersOf = corporationEid;
                    }
                    else
                    {
                        forMyCorporation = false;
                    }
                }

                //unstack a fraction or take the whole item, check for conditions
                var itemToSell = market.PrepareItemForSale(seller, itemEid, quantity, sourceContainer);

                if (_marketInfoService.CheckAveragePrice)
                {
                    var avgPrice = _marketHandler.GetAveragePriceByMarket(market, itemToSell.Definition);

                    if (avgPrice != null && avgPrice.AveragePrice > 0)
                    {
                        (pricePerPiece <avgPrice.AveragePrice * (1 - _marketInfoService.Margin) ||
                                        pricePerPiece> avgPrice.AveragePrice * (1 + _marketInfoService.Margin)).ThrowIfTrue(ErrorCodes.PriceOutOfAverageRange);
                    }
                }

                MarketOrder highestBuyOrder;

                if (targetOrderId > 0)
                {
                    //target order was defined by user
                    highestBuyOrder = _marketOrderRepository.Get(targetOrderId).ThrowIfNull(ErrorCodes.ItemNotFound);

                    //for my corp?
                    highestBuyOrder.forMembersOf?.ThrowIfNotEqual(corporationEid, ErrorCodes.AccessDenied);

                    //sell to order
                    market.FulfillSellOrderInstantly(seller, useSellerCorporationWallet, highestBuyOrder, itemToSell, sourceContainer);
                }
                else
                {
                    //try to find a buy order for the currently submitted item, it finds the closest buy order
                    highestBuyOrder = _marketOrderRepository.GetHighestBuyOrder(itemToSell.Definition, pricePerPiece, seller.Eid, market, corporationEid);

                    if (!forMyCorporation && highestBuyOrder != null)
                    {
                        //sell to order
                        market.FulfillSellOrderInstantly(seller, useSellerCorporationWallet, highestBuyOrder, itemToSell, sourceContainer);
                    }
                    else
                    {
                        if (!forMyCorporation)
                        {
                            _marketHelper.CheckSellOrderCounts(seller).ThrowIfFalse(ErrorCodes.MarketItemsExceed);
                        }

                        var realMarketFee = Market.GetRealMarketFee(seller, duration);

                        //cash market fee anyways
                        _marketHelper.CashInMarketFee(seller, useSellerCorporationWallet, realMarketFee);
                        market.GetDockingBase().AddCentralBank(TransactionType.marketFee, realMarketFee);

                        market.CreateSellOrder(seller.Eid, itemToSell, duration, pricePerPiece, quantity, useSellerCorporationWallet, forMembersOf);
                    }
                }

                publicContainer.Save();

                var containerData = publicContainer.ToDictionary();

                Message.Builder.SetCommand(Commands.ListContainer)
                .WithData(containerData)
                .ToCharacter(seller)
                .Send();
                scope.Complete();
            }
        }
 public MarketOrder GetMarketOrder(int id) => _marketOrderRepository.Get(id);