public Order executeOrder(OrderDTO orderdto, string UserName, string StripeClientId) { var order = _orderFactory.Create(orderdto, UserName); var invoice = _invoiceFactory.Create(order); if (!_orderRepo.CheckOrder(order)) { return(null); } order = _orderRepo.addOrder(order); invoice = _invoiceRepo.addInvoice(invoice); var succeded = _stripeService.executeCharge(order.OrderId, invoice.TotalSum, StripeClientId); Payment payment; if (succeded.Item2) { payment = _paymentFactory.Create(succeded.Item1, order.OrderId); _orderRepo.SetExecuted(order); _paymentRepo.addPayment(payment); } else { payment = _paymentFactory.Create(succeded.Item1, order.OrderId); _paymentRepo.addPayment(payment); } return(order); //create charge for stripe from order, complete it //create invoice from return of stripe call }
private void orderSaveButton_Click(object sender, EventArgs e) { try { ValidateOrderFormInputs(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Warning"); return; } Product product = (Product)productsComboBox.SelectedItem; Person person = (Person)personsComboBox.SelectedItem; int amount = int.Parse(amountTextBox.Text); if (product.StockAmount >= amount) { Order order = OrderFactory.Create(product, person, amount); _orderRepository.Save(order); AddOrderToListView(order); DecreaseProductStockAmount(order.Product, order.Amount); RefreshProductsListView(_productRepository.FindAll()); } else { MessageBox.Show("Insufficient stock quantity", "Warning"); } ClearOrderInputs(); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jsonToken = JToken.Load(reader); if (jsonToken.Type == JTokenType.Array) { var orders = new List <IOrder>(); var jsonArray = (JArray)jsonToken; foreach (var item in jsonArray) { var order = OrderFactory.Create(item["type"].Value <string>()); serializer.Populate(item.CreateReader(), order); orders.Add(order); } return(orders); } else if (jsonToken.Type == JTokenType.Object) { IOrder order = OrderFactory.Create(jsonToken["type"].Value <string>()); serializer.Populate(jsonToken.CreateReader(), order); return(order); } else { throw new ArgumentException(string.Format("Unexpected JTokenType ({0}) in reader.", jsonToken.Type.ToString())); } }
public void CheckEdit() { OrderManager manager = OrderFactory.Create(); Order order = new Order { OrderNumber = 212, CustomerName = "Duck Duck", State = "New York", TaxRate = 8, ProductType = "Wood", Area = 900, CostPerSquareFoot = 5, LaborCostPerSquareFoot = 10, OrderDate = new DateTime(2018, 05, 25) }; manager.EditOrder(order); OrderLookupResponse response = manager.LookupOrder(order.OrderNumber, order.OrderDate); Assert.IsNotNull(response.Order); Assert.AreEqual(response.Order.CustomerName, order.CustomerName); Assert.AreEqual(response.Order.State, order.State); Assert.AreEqual(response.Order.TaxRate, order.TaxRate); Assert.AreEqual(response.Order.ProductType, order.ProductType); Assert.AreEqual(response.Order.Area, order.Area); Assert.AreEqual(response.Order.CostPerSquareFoot, order.CostPerSquareFoot); Assert.AreEqual(response.Order.LaborCostPerSquareFoot, order.LaborCostPerSquareFoot); Assert.AreEqual(response.Order.OrderDate, order.OrderDate); }
public void CheckOrders() { OrderManager manager = OrderFactory.Create(); Order order = new Order { OrderNumber = 113, CustomerName = "Philip Chang", State = "New York", TaxRate = 8, ProductType = "Wood", Area = 900, CostPerSquareFoot = 5, LaborCostPerSquareFoot = 10, OrderDate = new DateTime(2018, 05, 22) }; OrdersLookupResponse responses = manager.LookupOrders(order.OrderDate); Assert.AreEqual(responses.Orders.Count, 1); Assert.AreEqual(responses.Orders[0].OrderNumber, order.OrderNumber); Assert.AreEqual(responses.Orders[0].CustomerName, order.CustomerName); Assert.AreEqual(responses.Orders[0].State, order.State); Assert.AreEqual(responses.Orders[0].TaxRate, order.TaxRate); Assert.AreEqual(responses.Orders[0].ProductType, order.ProductType); Assert.AreEqual(responses.Orders[0].Area, order.Area); Assert.AreEqual(responses.Orders[0].CostPerSquareFoot, order.CostPerSquareFoot); Assert.AreEqual(responses.Orders[0].LaborCostPerSquareFoot, order.LaborCostPerSquareFoot); Assert.AreEqual(responses.Orders[0].OrderDate, order.OrderDate); }
public async Task <ServiceResponse <CustomerOrderListVM> > GetOrdersByCustomerAsync(string customerId) { var response = new ServiceResponse <CustomerOrderListVM>(); try { if (string.IsNullOrWhiteSpace(customerId)) { response.AddNotification("customerId is required"); return(response); } var customer = await _customerClient.GetCustomerByIdAsync(customerId); var orders = await _orderClient.GetOrdersByCustomerAsync(customerId); if (customer is null) { response.AddNotification($"customer {customerId} not found"); return(response); } response.Data = new CustomerOrderListVM { Orders = orders?.Select(p => OrderFactory.Create(p, customer))?.ToList() }; } catch (Exception ex) { _logger.LogError(ex, ex.Message); response.AddNotification("unexpected error"); } return(response); }
public IActionResult Checkout(UserViewModel u) { var user = _uservm.AddUser(); user.Name = _uservm.Name; var o = new OrderFactory(); var order = o.Create(); order.Pizzas = _uservm.CurrentOrder.Pizzas; order.Name = "Order"; //generic name order.DateOrdered = _uservm.CurrentOrder.DateOrdered; user.UserOrders.Add(order); _store = _storevm.AddStore(); _store.Name = _storevm.Store; _store.StoreOrders = user.UserOrders; _pr.CreateUser(user); _pr.CreateStore(_store); foreach (var p in order.Pizzas) { _pr.CreatePizza(p); } _uservm.CurrentOrder = null; _uservm.CurrentOrder = new OrderViewModel(); return(Redirect("/user/index")); }
public void counter() { OrderManager manager = OrderFactory.Create(); Order order = new Order(); int test = manager.Counter(order); Assert.IsNotNull(test); Assert.AreEqual(test, 1); }
public void TestCreateShouldReturnOrder() { //Arrange var expectedOrderTotal = _shoppingCartItems.Sum(i => i.ShopItem.Price * i.Amount); //Act var result = _sut.Create(_dateTime, _customer, _shoppingCartItems); //Assert Assert.IsType <Order>(result); Assert.Equal(_dateTime, result.OrderPlaced); Assert.Equal(_customer, result.Customer); Assert.Equal(expectedOrderTotal, result.OrderTotal); Assert.Equal(CartItemCount, result.OrderDetails.Count); }
public IOrder ConvertToAnotherCurrency(IOrder order, string currencyCode) { var newOrder = _factory.Create(); foreach (var item in order.GetItems()) { var newItem = new Item(item.Article, item.Count * (int)_exchangeRateService.GetRate("CZK")); newOrder.AddItem(newItem); } return(newOrder); }
public void ConvertSpecial(PizzaViewModel pizzaViewModel, PizzaStoreDBContext _db) { var CR = new CrustRepository(_db); var SR = new SizeRepository(_db); var PR = new PizzaRepository(_db); var TR = new ToppingRepository(_db); var OR = new OrderRepository(_db); var UR = new UserRepository(_db); var STR = new StoreRepository(_db); var PF = new PizzaFactory(); var tempSpecialty = PF.Create(); tempSpecialty = PR.Get(SelectedPizza); var tempPizza = PF.Create(); tempPizza.Name = SelectedPizza; tempPizza.Description = tempSpecialty.Description; tempPizza.Size = SR.Get(pizzaViewModel.Size); tempPizza.Crust = CR.Get(pizzaViewModel.Crust); tempPizza.Toppings = new List <ToppingsModel>(); tempPizza.SpecialPizza = true; foreach (var t in tempSpecialty.Toppings) { var tempTopping = new ToppingsModel() { Name = t.Name, Description = t.Description }; tempPizza.Toppings.Add(tempTopping); TR.Add(tempTopping); } var cart = OR.GetCurrentOrder(); var OF = new OrderFactory(); if (cart != null) { OR.AddPizza(cart.Id, tempPizza); } else { cart = OF.Create(); cart.Pizzas.Add(tempPizza); cart.CurrentOrder = true; OR.UpdateCurrentOrder(cart); var tempUser = UR.Get(User); UR.AddOrder(tempUser.Id, cart); var tempStore = STR.Get(Store); STR.AddOrder(tempStore.Id, cart); } }
public void Order_Create_returns_new_Order() { var mocks = new MockRepository(); using (mocks.Record()) { base.MockRepository<IOrderContext>(mocks); } using (mocks.Playback()) { //create new order IOrderFactory factory = new OrderFactory(); var entity = factory.Create(); Assert.That(entity.IsNew, Is.True); } }
public void Order_Create_returns_new_Order() { var mocks = new MockRepository(); using (mocks.Record()) { base.MockRepository <IOrderContext>(mocks); } using (mocks.Playback()) { //create new order IOrderFactory factory = new OrderFactory(); var entity = factory.Create(); Assert.That(entity.IsNew, Is.True); } }
public void GetCart(PizzaStoreDBContext _db) { var OF = new OrderFactory(); var OR = new OrderRepository(_db); var cart = OR.GetCurrentOrder(); if (cart != null) { Cart = cart; } else { Cart = OF.Create(); OR.Add(Cart); } }
public void Order() { var customer = CustomerFactory.Create("Luke", "Skywalker", "*****@*****.**"); var product = ProductFactory.Create("Millennium Falcon", 500_000_000); var item = OrderItemFactory.Create(product, 1); var order = OrderFactory.Create(customer); order.AddItem(item); var discount = new DiscountService().Calculate(order.Total, DiscountType.Large); order.ApplyDiscount(discount); Assert.AreEqual(250_000_000, order.Total.Value); }
public void CheckRemove() { OrderManager manager = OrderFactory.Create(); Order order = new Order { OrderNumber = 211, CustomerName = "Swan Johnson", State = "New York", TaxRate = 8, ProductType = "Wood", Area = 900, CostPerSquareFoot = 5, LaborCostPerSquareFoot = 10, OrderDate = new DateTime(2018, 05, 24) }; manager.RemoveOrder(order); OrderLookupResponse response = manager.LookupOrder(order.OrderNumber, order.OrderDate); Assert.AreEqual(response.Success, false); }
public void Execute() { OrderManager manager = OrderFactory.Create(); Console.Clear(); Console.WriteLine("Add an Order"); Console.WriteLine("-----------------------"); Order order = new Order(); SetOrderDate(order); SetCustomerName(order); SetState(order); SetProduct(order); SetArea(order); //display the order Console.WriteLine("This is the order you want to add."); OrdersLookupResponse responseO = manager.LookupOrders(order.OrderDate); int orderNumber1 = manager.Counter(order); ConsoleIO.DisplayOrderDetailsOrderNumber(order, orderNumber1); bool change = AskConfirmation(); if (change) { manager.AddOrder(order); } else { Console.WriteLine("Potential order not ordered."); ConsoleIO.PressAnyKey(); Console.Clear(); } }
public void handleStreamText(string message, string user) { Boolean customOrder = false; Order order = OrderFactory.Create(message); if (order == null) { order = Order.convertStringToOrder(message); order.setLabel("Custom Order").setUser(user); customOrder = true; } else { order = Order.convertStringToOrder(message, order); } if (validateOrder(order)) { if (customOrder) { twithComm.SendMsg(string.Format("Sure {0}, I can make a sandwich that has {1}", order.user, order.ToPrettyString())); } else { twithComm.SendMsg(string.Format("You got it {0}, making that {1}", order.user, order.label)); } order.setDescription(message); orders.Enqueue(order); orderNotification.SetOrderNotification(order); Debug.Log(order.ToString()); } else { //Courtesy Message for bad ingredients twithComm.SendMsg(string.Format("Sorry {0}, thats not a real sandwich. Select a sandwich from our menu. To see it type: \"Hey Roach, whats on the menu?\" Or build your own by naming off the ingredients you want. To see our ingredients type \"Hey Roach, what ingredients do you have?\" .", user)); } }
public void Execute( ItemType itemType, string guid, int itemCount, int inventoryCount, int expectedCount, bool fromPreviousAction, bool legacy ) { var avatarState = _initialState.GetAvatarState(_avatarAddress); ITradableItem tradableItem; var itemId = new Guid(guid); var orderId = Guid.NewGuid(); var updateSellOrderId = Guid.NewGuid(); ItemSubType itemSubType; const long requiredBlockIndex = Order.ExpirationInterval; switch (itemType) { case ItemType.Equipment: { var itemUsable = ItemFactory.CreateItemUsable( _tableSheets.EquipmentItemSheet.First, itemId, requiredBlockIndex); tradableItem = itemUsable; itemSubType = itemUsable.ItemSubType; break; } case ItemType.Costume: { var costume = ItemFactory.CreateCostume(_tableSheets.CostumeItemSheet.First, itemId); costume.Update(requiredBlockIndex); tradableItem = costume; itemSubType = costume.ItemSubType; break; } default: { var material = ItemFactory.CreateTradableMaterial( _tableSheets.MaterialItemSheet.OrderedList.First(r => r.ItemSubType == ItemSubType.Hourglass)); itemSubType = material.ItemSubType; material.RequiredBlockIndex = requiredBlockIndex; tradableItem = material; break; } } var shardedShopAddress = ShardedShopStateV2.DeriveAddress(itemSubType, orderId); var shopState = new ShardedShopStateV2(shardedShopAddress); var order = OrderFactory.Create( _agentAddress, _avatarAddress, orderId, new FungibleAssetValue(_goldCurrencyState.Currency, 100, 0), tradableItem.TradableId, requiredBlockIndex, itemSubType, itemCount ); var orderDigestList = new OrderDigestListState(OrderDigestListState.DeriveAddress(_avatarAddress)); var prevState = _initialState; if (inventoryCount > 1) { for (int i = 0; i < inventoryCount; i++) { // Different RequiredBlockIndex for divide inventory slot. if (tradableItem is ITradableFungibleItem tradableFungibleItem) { var tradable = (TradableMaterial)tradableFungibleItem.Clone(); tradable.RequiredBlockIndex = tradableItem.RequiredBlockIndex - i; avatarState.inventory.AddItem2(tradable, 2 - i); } } } else { avatarState.inventory.AddItem2((ItemBase)tradableItem, itemCount); } var sellItem = legacy ? order.Sell2(avatarState) : order.Sell3(avatarState); var orderDigest = legacy ? order.Digest2(avatarState, _tableSheets.CostumeStatSheet) : order.Digest(avatarState, _tableSheets.CostumeStatSheet); shopState.Add(orderDigest, requiredBlockIndex); orderDigestList.Add(orderDigest); if (legacy) { Assert.True(avatarState.inventory.TryGetTradableItems(itemId, requiredBlockIndex * 2, itemCount, out _)); } else { Assert.True(avatarState.inventory.TryGetLockedItem(new OrderLock(orderId), out _)); } Assert.Equal(inventoryCount, avatarState.inventory.Items.Count); Assert.Equal(expectedCount, avatarState.inventory.Items.Sum(i => i.count)); Assert.Single(shopState.OrderDigestList); Assert.Single(orderDigestList.OrderDigestList); Assert.Equal(requiredBlockIndex * 2, sellItem.RequiredBlockIndex); if (fromPreviousAction) { prevState = prevState.SetState(_avatarAddress, avatarState.Serialize()); } else { prevState = prevState .SetState(_avatarAddress.Derive(LegacyInventoryKey), avatarState.inventory.Serialize()) .SetState(_avatarAddress.Derive(LegacyWorldInformationKey), avatarState.worldInformation.Serialize()) .SetState(_avatarAddress.Derive(LegacyQuestListKey), avatarState.questList.Serialize()) .SetState(_avatarAddress, avatarState.SerializeV2()); } prevState = prevState .SetState(Addresses.GetItemAddress(itemId), sellItem.Serialize()) .SetState(Order.DeriveAddress(order.OrderId), order.Serialize()) .SetState(orderDigestList.Address, orderDigestList.Serialize()) .SetState(shardedShopAddress, shopState.Serialize()); var currencyState = prevState.GetGoldCurrency(); var price = new FungibleAssetValue(currencyState, ProductPrice, 0); var action = new UpdateSell0 { orderId = orderId, updateSellOrderId = updateSellOrderId, tradableId = itemId, sellerAvatarAddress = _avatarAddress, itemSubType = itemSubType, price = price, count = itemCount, }; var nextState = action.Execute(new ActionContext { BlockIndex = 101, PreviousStates = prevState, Random = new TestRandom(), Rehearsal = false, Signer = _agentAddress, }); var updateSellShopAddress = ShardedShopStateV2.DeriveAddress(itemSubType, updateSellOrderId); var nextShopState = new ShardedShopStateV2((Dictionary)nextState.GetState(updateSellShopAddress)); Assert.Equal(1, nextShopState.OrderDigestList.Count); Assert.NotEqual(orderId, nextShopState.OrderDigestList.First().OrderId); Assert.Equal(updateSellOrderId, nextShopState.OrderDigestList.First().OrderId); Assert.Equal(itemId, nextShopState.OrderDigestList.First().TradableId); Assert.Equal(requiredBlockIndex + 101, nextShopState.OrderDigestList.First().ExpiredBlockIndex); }
public void ConvertRegular(PizzaViewModel pizzaViewModel, PizzaStoreDBContext _db) { var UR = new UserRepository(_db); var STR = new StoreRepository(_db); var OR = new OrderRepository(_db); var CR = new CrustRepository(_db); var SR = new SizeRepository(_db); var PR = new PizzaRepository(_db); var TR = new ToppingRepository(_db); var PF = new PizzaFactory(); List <ToppingsModel> TM = new List <ToppingsModel>(); SelectedToppings = new List <CheckBoxTopping>(); foreach (var t in Toppings2) { if (t.IsSelected) { SelectedToppings.Add(t); } } foreach (var t in SelectedToppings) { var throwaway = TR.Get(t.Text); var tempTopping = new ToppingsModel() { Name = throwaway.Name, Description = throwaway.Description }; TM.Add(tempTopping); } //TM.Add(TR.Get(Topping)); var tempPizza = PF.Create(); tempPizza.Name = "custom"; tempPizza.Description = "custom"; tempPizza.Size = SR.Get(pizzaViewModel.Size); tempPizza.Crust = CR.Get(pizzaViewModel.Crust); tempPizza.Toppings = new List <ToppingsModel>(); tempPizza.Toppings = TM; tempPizza.SpecialPizza = false; var cart = OR.GetCurrentOrder(); var OF = new OrderFactory(); if (cart != null) { OR.AddPizza(cart.Id, tempPizza); } else { cart = OF.Create(); cart.Pizzas = new List <PizzaModel>(); cart.Pizzas.Add(tempPizza); cart.CurrentOrder = true; OR.UpdateCurrentOrder(cart); var tempUser = UR.Get(User); UR.AddOrder(tempUser.Id, cart); var tempStore = STR.Get(Store); STR.AddOrder(tempStore.Id, cart); } }
public static IOrder ConvertToOrderModel(this OrderViewModel orderViewModel) => OrderFactory.Create(orderViewModel);
public void Order_Save_Insert_calls_expected_repository_methods() { var mocks = new MockRepository(); using (mocks.Record()) { //mock DTO's var insertedOrderDto1 = mocks.StrictMock<IOrderDto>(); insertedOrderDto1.Customer = "Bob"; insertedOrderDto1.Date = DateTime.Parse("1/1/2008"); insertedOrderDto1.ShippingCost = 5.5M; Expect.Call(insertedOrderDto1.Id).Return(100); Expect.Call(insertedOrderDto1.Timestamp).Return(new byte[8]); var insertedLineItemDto1 = mocks.StrictMock<ILineItemDto>(); insertedLineItemDto1.OrderId = 100; insertedLineItemDto1.ProductName = "Widget A"; insertedLineItemDto1.Price = 10M; insertedLineItemDto1.Quantity = 2; Expect.Call(insertedLineItemDto1.Id).Return(200); Expect.Call(insertedLineItemDto1.Timestamp).Return(new byte[8]); var insertedLineItemDto2 = mocks.StrictMock<ILineItemDto>(); insertedLineItemDto2.OrderId = 100; insertedLineItemDto2.ProductName = "Widget B"; insertedLineItemDto2.Price = 20.5M; insertedLineItemDto2.Quantity = 3; Expect.Call(insertedLineItemDto2.Id).Return(201); Expect.Call(insertedLineItemDto2.Timestamp).Return(new byte[8]); //mock transactional context IOrderContext trxContext = mocks.StrictMock<IOrderContext>(); trxContext.InsertOrder(insertedOrderDto1); trxContext.InsertLineItem(insertedLineItemDto1); trxContext.InsertLineItem(insertedLineItemDto2); trxContext.CompleteTransaction(); trxContext.Dispose(); //mock repository var repository = base.MockRepository<IOrderContext>(mocks); Expect.Call(repository.CreateContext(true)).Return(trxContext); Expect.Call(repository.CreateOrderDto()).Return(insertedOrderDto1); Expect.Call(repository.CreateLineItemDto()).Return(insertedLineItemDto1); Expect.Call(repository.CreateLineItemDto()).Return(insertedLineItemDto2); } using (mocks.Playback()) { //create new order IOrderFactory factory = new OrderFactory(); var entity = factory.Create(); //populate order entity.Customer = "Bob"; entity.Date = DateTime.Parse("1/1/2008"); entity.ShippingCost = 5.5M; //add line items ILineItem child; child = entity.LineItems.AddNew(); child.ProductName = "Widget A"; child.Price = 10M; child.Quantity = 2; child = entity.LineItems.AddNew(); child.ProductName = "Widget B"; child.Price = 20.5M; child.Quantity = 3; //test that entity is new and dirty Assert.That(entity.IsNew, Is.True); Assert.That(entity.IsDirty, Is.True); //perform inserts entity = entity.Save(); //test that entity is old and clean Assert.That(entity.IsNew, Is.False); Assert.That(entity.IsDirty, Is.False); } }
public void Execute() { OrderManager manager = OrderFactory.Create(); Console.Clear(); Console.WriteLine("Lookup an Order"); Console.WriteLine("-----------------------"); bool flag1 = true; int orderNum = 0; while (flag1) { Console.Write("Enter an order number: "); string number = Console.ReadLine(); if (number == null || number == "") { Console.WriteLine("Not a valid Order Number"); ConsoleIO.PressAnyKey(); Console.Clear(); Console.WriteLine("Lookup an Order"); Console.WriteLine("-----------------------"); continue; } if (!int.TryParse(number, out orderNum)) { Console.WriteLine("Not a valid Order Number"); ConsoleIO.PressAnyKey(); Console.Clear(); Console.WriteLine("Lookup an Order"); Console.WriteLine("-----------------------"); continue; } else { flag1 = false; } } bool flag2 = true; DateTime time = new DateTime(); while (flag2) { Console.Write("Enter an order date(MM-dd-yyyy): "); string date = Console.ReadLine(); if (date == null || date == "") { Console.WriteLine("Not a Valid Date. Try again"); ConsoleIO.PressAnyKey(); Console.Clear(); continue; } if (!DateTime.TryParse(date, out time)) { Console.WriteLine("Not a valid Date. Try again"); ConsoleIO.PressAnyKey(); Console.Clear(); continue; } else { flag2 = false; } } OrderLookupResponse response = manager.LookupOrder(orderNum, time); if (response.Success) { ConsoleIO.DisplayOrderDetails(response.Order); } else { Console.WriteLine(response.Message); } ConsoleIO.PressAnyKey(); Console.Clear(); }
public static IOrderVisitor Sort(this string source, string direction) { return(OrderFactory.Create(source, direction)); }
public static IOrderVisitor Descending(this string source) { return(OrderFactory.Create(source, "DESC")); }
//For removing an order, the system should ask for the date and order number. If it //exists, the system should display the order information and prompt the user //if they are sure. If yes, the order should be removed from the file. If no, return //the user to the main menu. public void Execute() { OrderManager manager = OrderFactory.Create(); bool flag1 = true; int orderNum = 0; while (flag1) { Console.Clear(); Console.WriteLine("Remove an Order"); Console.WriteLine("-----------------------"); Console.Write("Enter an order number: "); string number = Console.ReadLine(); if (number == null || number == "") { Console.WriteLine("Not a valid Order Number"); ConsoleIO.PressAnyKey(); Console.Clear(); Console.WriteLine("Remove an Order"); Console.WriteLine("-----------------------"); continue; } if (!int.TryParse(number, out orderNum)) { Console.WriteLine("Not a valid Order Number"); ConsoleIO.PressAnyKey(); Console.Clear(); Console.WriteLine("Lookup an Order"); Console.WriteLine("-----------------------"); continue; } else { flag1 = false; } } bool flag2 = true; DateTime time = new DateTime(); while (flag2) { Console.Clear(); Console.Write("Enter an order date(MM-dd-yyyy): "); string date = Console.ReadLine(); if (date == null || date == "") { Console.WriteLine("Not a Valid Date. Try again"); ConsoleIO.PressAnyKey(); Console.Clear(); continue; } if (!DateTime.TryParse(date, out time)) { Console.WriteLine("Not a valid Date. Try again"); ConsoleIO.PressAnyKey(); Console.Clear(); continue; } else { flag2 = false; } } OrderLookupResponse response = manager.LookupOrder(orderNum, time); if (response.Success) { ConsoleIO.DisplayOrderDetails(response.Order); } else { Console.WriteLine(response.Message); ConsoleIO.PressAnyKey(); return; } Console.Write("Would you like to remove this order? Y or N? "); string yesNo = Console.ReadLine(); while (true) { if (yesNo.ToUpper() == "Y") { manager.RemoveOrder(response.Order); Console.WriteLine($"{response.Order.OrderNumber} has been removed"); ConsoleIO.PressAnyKey(); break; } else if (yesNo.ToUpper() == "N") { return; } } }
public override IAccountStateDelta Execute(IActionContext context) { var states = context.PreviousStates; var inventoryAddress = sellerAvatarAddress.Derive(LegacyInventoryKey); var worldInformationAddress = sellerAvatarAddress.Derive(LegacyWorldInformationKey); var questListAddress = sellerAvatarAddress.Derive(LegacyQuestListKey); var shopAddress = ShardedShopStateV2.DeriveAddress(itemSubType, orderId); var updateSellShopAddress = ShardedShopStateV2.DeriveAddress(itemSubType, updateSellOrderId); var updateSellOrderAddress = Order.DeriveAddress(updateSellOrderId); var itemAddress = Addresses.GetItemAddress(tradableId); var digestListAddress = OrderDigestListState.DeriveAddress(sellerAvatarAddress); if (context.Rehearsal) { return(states .SetState(context.Signer, MarkChanged) .SetState(itemAddress, MarkChanged) .SetState(digestListAddress, MarkChanged) .SetState(shopAddress, MarkChanged) .SetState(updateSellShopAddress, MarkChanged) .SetState(updateSellOrderAddress, MarkChanged) .SetState(inventoryAddress, MarkChanged) .SetState(worldInformationAddress, MarkChanged) .SetState(questListAddress, MarkChanged) .SetState(sellerAvatarAddress, MarkChanged)); } // common var addressesHex = GetSignerAndOtherAddressesHex(context, sellerAvatarAddress); var sw = new Stopwatch(); sw.Start(); var started = DateTimeOffset.UtcNow; Log.Verbose("{AddressesHex} updateSell exec started", addressesHex); if (price.Sign < 0) { throw new InvalidPriceException( $"{addressesHex} Aborted as the price is less than zero: {price}."); } if (!states.TryGetAvatarStateV2(context.Signer, sellerAvatarAddress, out var avatarState, out _)) { throw new FailedLoadStateException( $"{addressesHex} Aborted as the avatar state of the signer was failed to load."); } sw.Stop(); Log.Verbose("{AddressesHex} Sell Get AgentAvatarStates: {Elapsed}", addressesHex, sw.Elapsed); sw.Restart(); if (!avatarState.worldInformation.IsStageCleared( GameConfig.RequireClearedStageLevel.ActionsInShop)) { avatarState.worldInformation.TryGetLastClearedStageId(out var current); throw new NotEnoughClearedStageLevelException( addressesHex, GameConfig.RequireClearedStageLevel.ActionsInShop, current); } sw.Stop(); avatarState.updatedAt = context.BlockIndex; avatarState.blockIndex = context.BlockIndex; if (!states.TryGetState(digestListAddress, out Dictionary rawList)) { throw new FailedLoadStateException($"{addressesHex} failed to load {nameof(OrderDigest)}({digestListAddress})."); } var digestList = new OrderDigestListState(rawList); // migration method avatarState.inventory.UnlockInvalidSlot(digestList, context.Signer, sellerAvatarAddress); avatarState.inventory.ReconfigureFungibleItem(digestList, tradableId); avatarState.inventory.LockByReferringToDigestList(digestList, tradableId, context.BlockIndex); // // for sell cancel Log.Verbose("{AddressesHex} UpdateSell IsStageCleared: {Elapsed}", addressesHex, sw.Elapsed); sw.Restart(); if (!states.TryGetState(shopAddress, out BxDictionary shopStateDict)) { throw new FailedLoadStateException($"{addressesHex}failed to load {nameof(ShardedShopStateV2)}({shopAddress})."); } sw.Stop(); Log.Verbose("{AddressesHex} UpdateSell Sell Cancel Get ShopState: {Elapsed}", addressesHex, sw.Elapsed); sw.Restart(); if (!states.TryGetState(Order.DeriveAddress(orderId), out Dictionary orderDict)) { throw new FailedLoadStateException($"{addressesHex} failed to load {nameof(Order)}({Order.DeriveAddress(orderId)})."); } var orderOnSale = OrderFactory.Deserialize(orderDict); orderOnSale.ValidateCancelOrder(avatarState, tradableId); var itemOnSale = orderOnSale.Cancel(avatarState, context.BlockIndex); if (context.BlockIndex < orderOnSale.ExpiredBlockIndex) { var shardedShopState = new ShardedShopStateV2(shopStateDict); shardedShopState.Remove(orderOnSale, context.BlockIndex); states = states.SetState(shopAddress, shardedShopState.Serialize()); } digestList.Remove(orderOnSale.OrderId); states = states.SetState(itemAddress, itemOnSale.Serialize()) .SetState(digestListAddress, digestList.Serialize()); sw.Stop(); var expirationMail = avatarState.mailBox.OfType <OrderExpirationMail>() .FirstOrDefault(m => m.OrderId.Equals(orderId)); if (!(expirationMail is null)) { avatarState.mailBox.Remove(expirationMail); } // for updateSell var updateSellShopState = states.TryGetState(updateSellShopAddress, out Dictionary serializedState) ? new ShardedShopStateV2(serializedState) : new ShardedShopStateV2(updateSellShopAddress); Log.Verbose("{AddressesHex} UpdateSell Get ShardedShopState: {Elapsed}", addressesHex, sw.Elapsed); sw.Restart(); var newOrder = OrderFactory.Create(context.Signer, sellerAvatarAddress, updateSellOrderId, price, tradableId, context.BlockIndex, itemSubType, count); newOrder.Validate(avatarState, count); var tradableItem = newOrder.Sell(avatarState); var costumeStatSheet = states.GetSheet <CostumeStatSheet>(); var orderDigest = newOrder.Digest(avatarState, costumeStatSheet); updateSellShopState.Add(orderDigest, context.BlockIndex); digestList.Add(orderDigest); states = states.SetState(digestListAddress, digestList.Serialize()); states = states.SetState(inventoryAddress, avatarState.inventory.Serialize()) .SetState(worldInformationAddress, avatarState.worldInformation.Serialize()) .SetState(questListAddress, avatarState.questList.Serialize()) .SetState(sellerAvatarAddress, avatarState.SerializeV2()); sw.Stop(); Log.Verbose("{AddressesHex} UpdateSell Set AvatarState: {Elapsed}", addressesHex, sw.Elapsed); sw.Restart(); states = states .SetState(itemAddress, tradableItem.Serialize()) .SetState(updateSellOrderAddress, newOrder.Serialize()) .SetState(updateSellShopAddress, updateSellShopState.Serialize()); sw.Stop(); var ended = DateTimeOffset.UtcNow; Log.Verbose("{AddressesHex} UpdateSell Set ShopState: {Elapsed}", addressesHex, sw.Elapsed); Log.Verbose("{AddressesHex} UpdateSell Total Executed Time: {Elapsed}", addressesHex, ended - started); return(states); }
public void Order_Save_Insert_calls_expected_repository_methods() { var mocks = new MockRepository(); using (mocks.Record()) { //mock DTO's var insertedOrderDto1 = mocks.StrictMock <IOrderDto>(); insertedOrderDto1.Customer = "Bob"; insertedOrderDto1.Date = DateTime.Parse("1/1/2008"); insertedOrderDto1.ShippingCost = 5.5M; Expect.Call(insertedOrderDto1.Id).Return(100); Expect.Call(insertedOrderDto1.Timestamp).Return(new byte[8]); var insertedLineItemDto1 = mocks.StrictMock <ILineItemDto>(); insertedLineItemDto1.OrderId = 100; insertedLineItemDto1.ProductName = "Widget A"; insertedLineItemDto1.Price = 10M; insertedLineItemDto1.Quantity = 2; Expect.Call(insertedLineItemDto1.Id).Return(200); Expect.Call(insertedLineItemDto1.Timestamp).Return(new byte[8]); var insertedLineItemDto2 = mocks.StrictMock <ILineItemDto>(); insertedLineItemDto2.OrderId = 100; insertedLineItemDto2.ProductName = "Widget B"; insertedLineItemDto2.Price = 20.5M; insertedLineItemDto2.Quantity = 3; Expect.Call(insertedLineItemDto2.Id).Return(201); Expect.Call(insertedLineItemDto2.Timestamp).Return(new byte[8]); //mock transactional context IOrderContext trxContext = mocks.StrictMock <IOrderContext>(); trxContext.InsertOrder(insertedOrderDto1); trxContext.InsertLineItem(insertedLineItemDto1); trxContext.InsertLineItem(insertedLineItemDto2); trxContext.CompleteTransaction(); trxContext.Dispose(); //mock repository var repository = base.MockRepository <IOrderContext>(mocks); Expect.Call(repository.CreateContext(true)).Return(trxContext); Expect.Call(repository.CreateOrderDto()).Return(insertedOrderDto1); Expect.Call(repository.CreateLineItemDto()).Return(insertedLineItemDto1); Expect.Call(repository.CreateLineItemDto()).Return(insertedLineItemDto2); } using (mocks.Playback()) { //create new order IOrderFactory factory = new OrderFactory(); var entity = factory.Create(); //populate order entity.Customer = "Bob"; entity.Date = DateTime.Parse("1/1/2008"); entity.ShippingCost = 5.5M; //add line items ILineItem child; child = entity.LineItems.AddNew(); child.ProductName = "Widget A"; child.Price = 10M; child.Quantity = 2; child = entity.LineItems.AddNew(); child.ProductName = "Widget B"; child.Price = 20.5M; child.Quantity = 3; //test that entity is new and dirty Assert.That(entity.IsNew, Is.True); Assert.That(entity.IsDirty, Is.True); //perform inserts entity = entity.Save(); //test that entity is old and clean Assert.That(entity.IsNew, Is.False); Assert.That(entity.IsDirty, Is.False); } }
public void Create(ItemType itemType, long blockIndex, Order.OrderType orderType) { ITradableItem tradableItem; Guid itemId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); switch (itemType) { case ItemType.Consumable: tradableItem = ItemFactory.CreateItemUsable( _tableSheets.ConsumableItemSheet.First, itemId, 0); break; case ItemType.Costume: tradableItem = ItemFactory.CreateCostume( _tableSheets.CostumeItemSheet.First, itemId); break; case ItemType.Equipment: tradableItem = ItemFactory.CreateItemUsable( _tableSheets.EquipmentItemSheet.First, itemId, 0); break; case ItemType.Material: var tradableMaterialRow = _tableSheets.MaterialItemSheet.OrderedList .First(row => row.ItemSubType == ItemSubType.Hourglass); tradableItem = ItemFactory.CreateTradableMaterial(tradableMaterialRow); itemId = tradableItem.TradableId; break; default: throw new ArgumentOutOfRangeException(nameof(itemType), itemType, null); } var currency = new Currency("NCG", 2, minter: null); Guid orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); Order order = OrderFactory.Create( Addresses.Admin, Addresses.Blacksmith, orderId, new FungibleAssetValue(currency, 1, 0), tradableItem.TradableId, blockIndex, tradableItem.ItemSubType, 1 ); Assert.Equal(orderType, order.Type); Assert.Equal(blockIndex, order.StartedBlockIndex); Assert.Equal(currency * 1, order.Price); Assert.Equal(Addresses.Admin, order.SellerAgentAddress); Assert.Equal(Addresses.Blacksmith, order.SellerAvatarAddress); Assert.Equal(orderId, order.OrderId); Assert.Equal(itemId, order.TradableId); if (orderType == Order.OrderType.Fungible) { Assert.Equal(1, ((FungibleOrder)order).ItemCount); } }
public override IAccountStateDelta Execute(IActionContext context) { var data = TestbedHelper.LoadData <TestbedSell>("TestbedSell"); var addedItemInfos = data.Items .Select(item => new TestbedHelper.AddedItemInfo( context.Random.GenerateRandomGuid(), context.Random.GenerateRandomGuid())) .ToList(); var agentAddress = _privateKey.PublicKey.ToAddress(); var states = context.PreviousStates; var avatarAddress = agentAddress.Derive( string.Format( CultureInfo.InvariantCulture, CreateAvatar.DeriveFormat, _slotIndex ) ); var inventoryAddress = avatarAddress.Derive(LegacyInventoryKey); var worldInformationAddress = avatarAddress.Derive(LegacyWorldInformationKey); var questListAddress = avatarAddress.Derive(LegacyQuestListKey); var orderReceiptAddress = OrderDigestListState.DeriveAddress(avatarAddress); if (context.Rehearsal) { states = states.SetState(agentAddress, MarkChanged); for (var i = 0; i < AvatarState.CombinationSlotCapacity; i++) { var slotAddress = avatarAddress.Derive( string.Format(CultureInfo.InvariantCulture, CombinationSlotState.DeriveFormat, i)); states = states.SetState(slotAddress, MarkChanged); } states = states.SetState(avatarAddress, MarkChanged) .SetState(Addresses.Ranking, MarkChanged) .SetState(worldInformationAddress, MarkChanged) .SetState(questListAddress, MarkChanged) .SetState(inventoryAddress, MarkChanged); for (var i = 0; i < data.Items.Length; i++) { var itemAddress = Addresses.GetItemAddress(addedItemInfos[i].TradableId); var orderAddress = Order.DeriveAddress(addedItemInfos[i].OrderId); var shopAddress = ShardedShopStateV2.DeriveAddress( data.Items[i].ItemSubType, addedItemInfos[i].OrderId); states = states.SetState(avatarAddress, MarkChanged) .SetState(inventoryAddress, MarkChanged) .MarkBalanceChanged(GoldCurrencyMock, agentAddress, GoldCurrencyState.Address) .SetState(orderReceiptAddress, MarkChanged) .SetState(itemAddress, MarkChanged) .SetState(orderAddress, MarkChanged) .SetState(shopAddress, MarkChanged); } return(states); } // Create Agent and avatar var existingAgentState = states.GetAgentState(agentAddress); var agentState = existingAgentState ?? new AgentState(agentAddress); var avatarState = states.GetAvatarState(avatarAddress); if (!(avatarState is null)) { throw new InvalidAddressException( $"Aborted as there is already an avatar at {avatarAddress}."); } if (agentState.avatarAddresses.ContainsKey(_slotIndex)) { throw new AvatarIndexAlreadyUsedException( $"borted as the signer already has an avatar at index #{_slotIndex}."); } agentState.avatarAddresses.Add(_slotIndex, avatarAddress); var rankingState = context.PreviousStates.GetRankingState(); var rankingMapAddress = rankingState.UpdateRankingMap(avatarAddress); avatarState = TestbedHelper.CreateAvatarState(data.avatar.Name, agentAddress, avatarAddress, context.BlockIndex, context.PreviousStates.GetAvatarSheets(), context.PreviousStates.GetSheet <WorldSheet>(), context.PreviousStates.GetGameConfigState(), rankingMapAddress); // Add item var costumeItemSheet = context.PreviousStates.GetSheet <CostumeItemSheet>(); var equipmentItemSheet = context.PreviousStates.GetSheet <EquipmentItemSheet>(); var optionSheet = context.PreviousStates.GetSheet <EquipmentItemOptionSheet>(); var skillSheet = context.PreviousStates.GetSheet <SkillSheet>(); var materialItemSheet = context.PreviousStates.GetSheet <MaterialItemSheet>(); var consumableItemSheet = context.PreviousStates.GetSheet <ConsumableItemSheet>(); for (var i = 0; i < data.Items.Length; i++) { TestbedHelper.AddItem(costumeItemSheet, equipmentItemSheet, optionSheet, skillSheet, materialItemSheet, consumableItemSheet, context.Random, data.Items[i], addedItemInfos[i], avatarState); } avatarState.Customize(0, 0, 0, 0); foreach (var address in avatarState.combinationSlotAddresses) { var slotState = new CombinationSlotState(address, GameConfig.RequireClearedStageLevel.CombinationEquipmentAction); states = states.SetState(address, slotState.Serialize()); } avatarState.UpdateQuestRewards(materialItemSheet); states = states.SetState(agentAddress, agentState.Serialize()) .SetState(Addresses.Ranking, rankingState.Serialize()) .SetState(inventoryAddress, avatarState.inventory.Serialize()) .SetState(worldInformationAddress, avatarState.worldInformation.Serialize()) .SetState(questListAddress, avatarState.questList.Serialize()) .SetState(avatarAddress, avatarState.SerializeV2()); // for sell for (var i = 0; i < data.Items.Length; i++) { var itemAddress = Addresses.GetItemAddress(addedItemInfos[i].TradableId); var orderAddress = Order.DeriveAddress(addedItemInfos[i].OrderId); var shopAddress = ShardedShopStateV2.DeriveAddress( data.Items[i].ItemSubType, addedItemInfos[i].OrderId); var balance = context.PreviousStates.GetBalance(agentAddress, states.GetGoldCurrency()); var price = new FungibleAssetValue(balance.Currency, data.Items[i].Price, 0); var order = OrderFactory.Create(agentAddress, avatarAddress, addedItemInfos[i].OrderId, price, addedItemInfos[i].TradableId, context.BlockIndex, data.Items[i].ItemSubType, data.Items[i].Count); Orders.Add(order); order.Validate(avatarState, data.Items[i].Count); var tradableItem = order.Sell(avatarState); var shardedShopState = states.TryGetState(shopAddress, out Dictionary serializedState) ? new ShardedShopStateV2(serializedState) : new ShardedShopStateV2(shopAddress); var costumeStatSheet = states.GetSheet <CostumeStatSheet>(); var orderDigest = order.Digest(avatarState, costumeStatSheet); shardedShopState.Add(orderDigest, context.BlockIndex); var orderReceiptList = states.TryGetState(orderReceiptAddress, out Dictionary receiptDict) ? new OrderDigestListState(receiptDict) : new OrderDigestListState(orderReceiptAddress); orderReceiptList.Add(orderDigest); states = states.SetState(orderReceiptAddress, orderReceiptList.Serialize()) .SetState(inventoryAddress, avatarState.inventory.Serialize()) .SetState(avatarAddress, avatarState.SerializeV2()) .SetState(itemAddress, tradableItem.Serialize()) .SetState(orderAddress, order.Serialize()) .SetState(shopAddress, shardedShopState.Serialize()); } result.SellerAgentAddress = agentAddress; result.SellerAvatarAddress = avatarAddress; result.ItemInfos = new List <ItemInfos>(); for (var i = 0; i < data.Items.Length; i++) { result.ItemInfos.Add(new ItemInfos( addedItemInfos[i].OrderId, addedItemInfos[i].TradableId, data.Items[i].ItemSubType, data.Items[i].Price, data.Items[i].Count)); } return(states); }
public void Execute( ItemType itemType, bool orderExist, int itemCount, bool backward ) { var avatarState = _initialState.GetAvatarState(_avatarAddress); ITradableItem tradableItem; switch (itemType) { case ItemType.Consumable: tradableItem = ItemFactory.CreateItemUsable( _tableSheets.ConsumableItemSheet.First, Guid.NewGuid(), 0); break; case ItemType.Costume: tradableItem = ItemFactory.CreateCostume( _tableSheets.CostumeItemSheet.First, Guid.NewGuid()); break; case ItemType.Equipment: tradableItem = ItemFactory.CreateItemUsable( _tableSheets.EquipmentItemSheet.First, Guid.NewGuid(), 0); break; case ItemType.Material: var tradableMaterialRow = _tableSheets.MaterialItemSheet.OrderedList .First(row => row.ItemSubType == ItemSubType.Hourglass); tradableItem = ItemFactory.CreateTradableMaterial(tradableMaterialRow); break; default: throw new ArgumentOutOfRangeException(nameof(itemType), itemType, null); } Assert.Equal(0, tradableItem.RequiredBlockIndex); avatarState.inventory.AddItem2((ItemBase)tradableItem, itemCount); var previousStates = _initialState; if (backward) { previousStates = previousStates.SetState(_avatarAddress, avatarState.Serialize()); } else { previousStates = previousStates .SetState(_avatarAddress.Derive(LegacyInventoryKey), avatarState.inventory.Serialize()) .SetState(_avatarAddress.Derive(LegacyWorldInformationKey), avatarState.worldInformation.Serialize()) .SetState(_avatarAddress.Derive(LegacyQuestListKey), avatarState.questList.Serialize()) .SetState(_avatarAddress, avatarState.SerializeV2()); } var currencyState = previousStates.GetGoldCurrency(); var price = new FungibleAssetValue(currencyState, ProductPrice, 0); var orderId = new Guid("6f460c1a755d48e4ad6765d5f519dbc8"); var existOrderId = new Guid("229e5f8c-fabe-4c04-bab9-45325cfa69a4"); var orderAddress = Order.DeriveAddress(orderId); var shardedShopAddress = ShardedShopStateV2.DeriveAddress( tradableItem.ItemSubType, orderId); long blockIndex = 1; if (orderExist) { var shardedShopState = new ShardedShopStateV2(shardedShopAddress); var existOrder = OrderFactory.Create( _agentAddress, _avatarAddress, existOrderId, price, tradableItem.TradableId, 0, tradableItem.ItemSubType, 1 ); existOrder.Sell2(avatarState); blockIndex = existOrder.ExpiredBlockIndex; shardedShopState.Add(existOrder.Digest2(avatarState, _tableSheets.CostumeStatSheet), blockIndex); Assert.Single(shardedShopState.OrderDigestList); previousStates = previousStates.SetState( shardedShopAddress, shardedShopState.Serialize()); } else { Assert.Null(previousStates.GetState(shardedShopAddress)); } var sellAction = new Sell7 { sellerAvatarAddress = _avatarAddress, tradableId = tradableItem.TradableId, count = itemCount, price = price, itemSubType = tradableItem.ItemSubType, orderId = orderId, }; var nextState = sellAction.Execute(new ActionContext { BlockIndex = blockIndex, PreviousStates = previousStates, Rehearsal = false, Signer = _agentAddress, Random = new TestRandom(), }); long expiredBlockIndex = Order.ExpirationInterval + blockIndex; // Check AvatarState and Inventory var nextAvatarState = nextState.GetAvatarStateV2(_avatarAddress); Assert.Single(nextAvatarState.inventory.Items); Assert.True(nextAvatarState.inventory.TryGetTradableItems( tradableItem.TradableId, expiredBlockIndex, 1, out var inventoryItems)); Assert.Single(inventoryItems); ITradableItem nextTradableItem = (ITradableItem)inventoryItems.First().item; Assert.Equal(expiredBlockIndex, nextTradableItem.RequiredBlockIndex); // Check ShardedShopState var nextSerializedShardedShopState = nextState.GetState(shardedShopAddress); Assert.NotNull(nextSerializedShardedShopState); var nextShardedShopState = new ShardedShopStateV2((Dictionary)nextSerializedShardedShopState); var expectedCount = orderExist ? 2 : 1; Assert.Equal(expectedCount, nextShardedShopState.OrderDigestList.Count); var orderDigest = nextShardedShopState.OrderDigestList.First(o => o.OrderId.Equals(orderId)); Assert.Equal(price, orderDigest.Price); Assert.Equal(blockIndex, orderDigest.StartedBlockIndex); Assert.Equal(expiredBlockIndex, orderDigest.ExpiredBlockIndex); Assert.Equal(((ItemBase)tradableItem).Id, orderDigest.ItemId); Assert.Equal(tradableItem.TradableId, orderDigest.TradableId); var serializedOrder = nextState.GetState(orderAddress); Assert.NotNull(serializedOrder); var serializedItem = nextState.GetState(Addresses.GetItemAddress(tradableItem.TradableId)); Assert.NotNull(serializedItem); var order = OrderFactory.Deserialize((Dictionary)serializedOrder); ITradableItem orderItem = (ITradableItem)ItemFactory.Deserialize((Dictionary)serializedItem); Assert.Equal(price, order.Price); Assert.Equal(orderId, order.OrderId); Assert.Equal(tradableItem.TradableId, order.TradableId); Assert.Equal(blockIndex, order.StartedBlockIndex); Assert.Equal(expiredBlockIndex, order.ExpiredBlockIndex); Assert.Equal(_agentAddress, order.SellerAgentAddress); Assert.Equal(_avatarAddress, order.SellerAvatarAddress); Assert.Equal(expiredBlockIndex, orderItem.RequiredBlockIndex); var mailList = nextAvatarState.mailBox.OfType <OrderExpirationMail>().ToList(); Assert.Single(mailList); var mail = mailList.First(); Assert.NotNull(mail); Assert.Equal(expiredBlockIndex, mail.requiredBlockIndex); Assert.Equal(orderId, mail.OrderId); var receiptDict = nextState.GetState(OrderDigestListState.DeriveAddress(_avatarAddress)); Assert.NotNull(receiptDict); var orderDigestList = new OrderDigestListState((Dictionary)receiptDict); Assert.Single(orderDigestList.OrderDigestList); OrderDigest orderDigest2 = orderDigestList.OrderDigestList.First(); Assert.Equal(orderDigest, orderDigest2); }
public override IAccountStateDelta Execute(IActionContext context) { var states = context.PreviousStates; var inventoryAddress = sellerAvatarAddress.Derive(LegacyInventoryKey); var worldInformationAddress = sellerAvatarAddress.Derive(LegacyWorldInformationKey); var questListAddress = sellerAvatarAddress.Derive(LegacyQuestListKey); Address shopAddress = ShardedShopStateV2.DeriveAddress(itemSubType, orderId); Address itemAddress = Addresses.GetItemAddress(tradableId); Address orderAddress = Order.DeriveAddress(orderId); Address orderReceiptAddress = OrderDigestListState.DeriveAddress(sellerAvatarAddress); if (context.Rehearsal) { return(states .SetState(context.Signer, MarkChanged) .SetState(shopAddress, MarkChanged) .SetState(itemAddress, MarkChanged) .SetState(orderAddress, MarkChanged) .SetState(orderReceiptAddress, MarkChanged) .SetState(inventoryAddress, MarkChanged) .SetState(worldInformationAddress, MarkChanged) .SetState(questListAddress, MarkChanged) .SetState(sellerAvatarAddress, MarkChanged)); } var addressesHex = GetSignerAndOtherAddressesHex(context, sellerAvatarAddress); var sw = new Stopwatch(); sw.Start(); var started = DateTimeOffset.UtcNow; Log.Verbose("{AddressesHex}Sell exec started", addressesHex); if (price.Sign < 0) { throw new InvalidPriceException( $"{addressesHex}Aborted as the price is less than zero: {price}."); } if (!states.TryGetAgentAvatarStatesV2( context.Signer, sellerAvatarAddress, out _, out var avatarState)) { throw new FailedLoadStateException( $"{addressesHex}Aborted as the avatar state of the signer was failed to load."); } sw.Stop(); Log.Verbose( "{AddressesHex}Sell Get AgentAvatarStates: {Elapsed}", addressesHex, sw.Elapsed); sw.Restart(); if (!avatarState.worldInformation.IsStageCleared( GameConfig.RequireClearedStageLevel.ActionsInShop)) { avatarState.worldInformation.TryGetLastClearedStageId(out var current); throw new NotEnoughClearedStageLevelException( addressesHex, GameConfig.RequireClearedStageLevel.ActionsInShop, current); } sw.Stop(); Log.Verbose("{AddressesHex}Sell IsStageCleared: {Elapsed}", addressesHex, sw.Elapsed); sw.Restart(); Order order = OrderFactory.Create(context.Signer, sellerAvatarAddress, orderId, price, tradableId, context.BlockIndex, itemSubType, count); order.Validate(avatarState, count); ITradableItem tradableItem = order.Sell(avatarState); var shardedShopState = states.TryGetState(shopAddress, out Dictionary serializedState) ? new ShardedShopStateV2(serializedState) : new ShardedShopStateV2(shopAddress); sw.Stop(); Log.Verbose( "{AddressesHex}Sell Get ShardedShopState: {Elapsed}", addressesHex, sw.Elapsed); sw.Restart(); var costumeStatSheet = states.GetSheet <CostumeStatSheet>(); OrderDigest orderDigest = order.Digest(avatarState, costumeStatSheet); shardedShopState.Add(orderDigest, context.BlockIndex); avatarState.updatedAt = context.BlockIndex; avatarState.blockIndex = context.BlockIndex; var orderReceiptList = states.TryGetState(orderReceiptAddress, out Dictionary receiptDict) ? new OrderDigestListState(receiptDict) : new OrderDigestListState(orderReceiptAddress); orderReceiptList.Add(orderDigest); states = states.SetState(orderReceiptAddress, orderReceiptList.Serialize()); states = states .SetState(inventoryAddress, avatarState.inventory.Serialize()) .SetState(worldInformationAddress, avatarState.worldInformation.Serialize()) .SetState(questListAddress, avatarState.questList.Serialize()) .SetState(sellerAvatarAddress, avatarState.SerializeV2()); sw.Stop(); Log.Verbose("{AddressesHex}Sell Set AvatarState: {Elapsed}", addressesHex, sw.Elapsed); sw.Restart(); states = states .SetState(itemAddress, tradableItem.Serialize()) .SetState(orderAddress, order.Serialize()) .SetState(shopAddress, shardedShopState.Serialize()); sw.Stop(); var ended = DateTimeOffset.UtcNow; Log.Verbose("{AddressesHex}Sell Set ShopState: {Elapsed}", addressesHex, sw.Elapsed); Log.Verbose( "{AddressesHex}Sell Total Executed Time: {Elapsed}", addressesHex, ended - started); return(states); }