public IndexModel(ILogger <IndexModel> logger, OrdersApi ordersApi, OrdersBll ordersBll, ProductsApi productsApi)
 {
     _logger      = logger ?? throw new ArgumentNullException(nameof(logger));
     _ordersApi   = ordersApi ?? throw new ArgumentNullException(nameof(ordersApi));
     _ordersBll   = ordersBll ?? throw new ArgumentNullException(nameof(ordersBll));
     _productsApi = productsApi ?? throw new ArgumentNullException(nameof(productsApi));
 }
        public static async Task <List <MarketOrderBook> > GetMarketOrders()
        {
            var apiInstance = new OrdersApi();
            var orders      = await apiInstance.OrdersGetAsync();

            var marketGroups = orders.GroupBy(order => order.Price);

            var orderbooks = new List <MarketOrderBook>();

            foreach (var group in marketGroups)
            {
                var orderbook = new MarketOrderBook
                {
                    Price     = group.Key.GetValueOrDefault(),
                    MyBidQty  = group.Where(order => order.Side == SideEnum.Buy && order.UserId == UserId).Sum(order => order.Quantity).GetValueOrDefault(),
                    MktBidQty = group.Where(order => order.Side == SideEnum.Buy && order.UserId != UserId).Sum(order => order.Quantity).GetValueOrDefault(),
                    MktAskQty = group.Where(order => order.Side == SideEnum.Sell && order.UserId != UserId).Sum(order => order.Quantity).GetValueOrDefault(),
                    MyAskQty  = group.Where(order => order.Side == SideEnum.Sell && order.UserId == UserId).Sum(order => order.Quantity).GetValueOrDefault()
                };
                orderbooks.Add(orderbook);
            }


            return(orderbooks);
        }
Example #3
0
        public static void ShowOrderDetails(CommandReport commandReport)
        {
            var ordersApi = new OrdersApi();
            var command   = ordersApi.GetCommand(commandReport.CommandId);

            ShowOrderDetails(ordersApi.GetOrder(command.OrderId));
        }
        public void Init()
        {
            authorizationApi = new AuthorizationApi("https://merchant-auth-nz.sandbox.zip.co");
            authorizationApi.Configuration.ClientId     = "VxBHMqt9aI4cPHjRBBmLt1Orw6xkk63n";
            authorizationApi.Configuration.ClientSecret = "o7fNo_1vfSDYUyMA_ZD2sVqxAiO-oeEkYo2FDQhiyUdeJ-8-rx91wRrUkUEJmgEe";

            metaData = new Metadata("platform", "nopCommerce v4.2 Payment Plugin");
            instance = new OrdersApi("https://sandbox.zip.co/nz/api");
        }
Example #5
0
        public void Init()
        {
            instance     = new OrdersApi();
            testAccounts = new TestAccounts();
            var testAccount = testAccounts["Sandbox"];

            locationId = testAccount.LocationId;
            Configuration.Default.AccessToken = testAccount.AccessToken;
        }
Example #6
0
        public SquareOrdersService(SquareConfig config, SquareMerchantCredentials credentials, ISquareLocationsService locationsService, ISquareItemsService itemsService) : base(config, credentials)
        {
            Condition.Requires(locationsService, "locationsService").IsNotNull();
            Condition.Requires(itemsService, "itemsService").IsNotNull();

            _locationsService = locationsService;
            _itemsService     = itemsService;
            _ordersApi        = new OrdersApi(base.ApiConfiguration);
        }
Example #7
0
        public OrdersViewModel(int physicalStoreId)
        {
            _ordersApi       = new OrdersApi();
            _physicalStoreId = physicalStoreId;
            Orders           = new ObservableCollection <OrderViewModel>();
            NewOrders        = new ObservableCollection <OrderViewModel>();

            PreviousPageCommand = new RelayCommand(ExecutePreviousPageCommand, m => _pageIndex > 1);
            NextPageCommand     = new RelayCommand(ExecuteNextPageCommand, m => _pageIndex < _totalPages);
            LogoutCommand       = new RelayCommand(ExecuteLogoutCommand);
            BackCommand         = new RelayCommand(ExecuteBackButton);
        }
Example #8
0
        public static async void PlaceOrder(Account account, PlaceOrder.ActionEnum action, int orderQty, string symbol, PlaceOrder.OrderTypeEnum orderType, double?price = null, double?stopPrice = null)
        {
            var ordersApi = new OrdersApi();
            var request   = new PlaceOrder(AccountSpec: account.Name,
                                           Action: action,
                                           Symbol: symbol,
                                           OrderQty: orderQty,
                                           OrderType: orderType,
                                           Price: price,
                                           StopPrice: stopPrice,
                                           TimeInForce: Services.Model.PlaceOrder.TimeInForceEnum.Day, Text: "Sample");
            var response = await ordersApi.PlaceOrderAsync(request);

            Console.WriteLine($"{request} -> {response}");
        }
Example #9
0
        static string GetCommandDescription(Order order, Contract contract, Command command)
        {
            if (command.CommandType == Command.CommandTypeEnum.Cancel)
            {
                return("Cancel");
            }
            var ordersApi   = new OrdersApi();
            var description = GetOrderVersionDescription(order, contract, ordersApi.GetOrderVersion(command.Id));

            if (command.CommandType == Command.CommandTypeEnum.Modify)
            {
                return($"Modify to {description}");
            }
            return(description);
        }
Example #10
0
        public void OrderApi_CreateOrder()
        {
            OrdersApi api = new OrdersApi(BaseUrl, apiToken, apiKey);

            CreateOrdersRequest req = new CreateOrdersRequest();

            req.Amount = new AmountsCreateOrdersRequest()
            {
                Currency  = CurrencyType.BRL,
                Subtotals = new TotaisAmountsCreateOrdersRequest()
                {
                    Shipping = 0
                }
            };
            string idCliente = "CUS-1IO9IR204YI4";

            req.Customer = new ClienteCreateOrdersRequest(idCliente);
            req.Items    = new System.Collections.Generic.List <OrderItemCreateOrdersRequest>();
            req.Items.Add(new OrderItemCreateOrdersRequest()
            {
                Detail   = "Detalhe Produto de teste ",
                Price    = 100,
                Product  = "Produto de teste ",
                Quantity = 1
            });
            req.OwnId     = "231";
            req.Receivers = new System.Collections.Generic.List <ReceiverCreateOrdersRequest>();
            req.Receivers.Add(new ReceiverCreateOrdersRequest()
            {
                Type   = ReceiverType.PRIMARY,
                Amount = new AmountReceiverCreateOrdersRequest()
                {
                    Percentual = 1,
                    ValueFixed = 1
                },
                FeePayor    = false,
                moipAccount = new MoipAccountReceiverCreateOrdersRequest()
                {
                    Id = "MPA-9B34B54E286C"
                }
            });

            var retorno = api.CreateOrder(req);
        }
Example #11
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("press enter to start");
            _ = Console.ReadLine();

            var ordersApi = new OrdersApi(_httpClient, _config, _secrets);

            var orders = await ordersApi.GetInProgressOrdersAsync().ConfigureAwait(false);

            Console.WriteLine($"Fetched {orders.Content.Count} orders that are in progress.");

            Console.WriteLine("Calculation top 5 products sold");

            var orderBll = new OrdersBll();

            var topFiveSold = orderBll
                              .OrderProductsByQuantity(orders)
                              .Take(5)
                              .ToList();

            Console.WriteLine("Getting product names...");

            var productsAPi = new ProductsApi(_httpClient, _config, _secrets);

            foreach (var(MerchantProductNo, Gtin, Sold) in topFiveSold)
            {
                var product = (await productsAPi.GetProductAsync(MerchantProductNo !).ConfigureAwait(false)).Content.First();
                Console.WriteLine($"Sold: {Sold}, No: {MerchantProductNo}, Gtin: {Gtin}, Stock: {product.Stock}, Name: {product.Name}");
            }

            Console.WriteLine("Updating random product stock to 25...");

            var randomProductIndexToUpdate = _random.Next(0, topFiveSold.Count);
            var randomProduct = topFiveSold.ElementAt(randomProductIndexToUpdate);

            var success = await productsAPi.UpdateProductStockQuantityAsync(randomProduct.MerchantProductNo !, 25);

            Console.WriteLine($"Success: {success}");
            Console.WriteLine("Press enter to close");
            _ = Console.ReadLine();
        }
Example #12
0
        public void main()
        {
            // Configure API key authorization, get an Access Token, Create an Order, Get an Order

            try
            {
                // Setup Authorization
                authorizationApi = new AuthorizationApi("https://merchant-auth-nz.sandbox.zip.co");
                authorizationApi.Configuration.ClientId     = "Your Client Id";
                authorizationApi.Configuration.ClientSecret = "Your Client Secret";

                // Create Acces Token
                var authorization = authorizationApi.AuthorizationCreateToken();
                Debug.WriteLine(authorization);
            }
            catch (Exception e)
            {
                Debug.Print("Exception when calling AuthorizationApi: " + e.Message);
            }

            try
            {
                // Create Order
                ordersApi = new OrdersApi("https://sandbox.zip.co/nz/api");
                var createOrderRequest = CreateRequest(CreateOrderRequest.PaymentFlowEnum.Payment);
                var authorization      = authorizationApi.AuthorizationCreateToken();

                // Create Order
                var createOrderResponse = ordersApi.OrderCreate(authorization, "Idempotency-Key", createOrderRequest);
                Debug.WriteLine(createOrderResponse);

                // Get Order
                var id    = createOrderResponse.OrderId;
                var order = ordersApi.OrderGet(id);
                Debug.WriteLine(order);
            }
            catch (Exception e)
            {
                Debug.Print("Exception when calling OrdersApi: " + e.Message);
            }
        }
        public OrderReadyToProccessViewModel(int storeId, Order order)
        {
            _storeId   = storeId;
            _order     = order;
            _ordersApi = new OrdersApi();

            OrderSummary = BuildOrderSummary();
            RejectValues = Enum.GetValues(typeof(Reject.RejectReasonEnum));
            EstimatedMinutesForDeliveryValues = new List <int>
            {
                30,
                45,
                60,
                75
            };

            EstimatedMinutesForDeliveryIndex = 0;
            RejectReason = Reject.RejectReasonEnum.TooBusy;

            AcceptCommand  = new RelayCommand(ExecuteAcceptCommand);
            DeclineCommand = new RelayCommand(ExecuteDeclineCommand);
        }
        /// <summary>
        /// Creates a client to work with VK API methods.
        /// </summary>
        public CitrinaClient()
        {
            AuthHelper = new AuthHelper();
            Execute    = new ExecuteApi();

            Account       = new AccountApi();
            Ads           = new AdsApi();
            Apps          = new AppsApi();
            Auth          = new AuthApi();
            Board         = new BoardApi();
            Database      = new DatabaseApi();
            Docs          = new DocsApi();
            Fave          = new FaveApi();
            Friends       = new FriendsApi();
            Gifts         = new GiftsApi();
            Groups        = new GroupsApi();
            Leads         = new LeadsApi();
            Likes         = new LikesApi();
            Market        = new MarketApi();
            Messages      = new MessagesApi();
            Newsfeed      = new NewsfeedApi();
            Notes         = new NotesApi();
            Notifications = new NotificationsApi();
            Orders        = new OrdersApi();
            Pages         = new PagesApi();
            Photos        = new PhotosApi();
            Places        = new PlacesApi();
            Polls         = new PollsApi();
            Search        = new SearchApi();
            Secure        = new SecureApi();
            Stats         = new StatsApi();
            Status        = new StatusApi();
            Storage       = new StorageApi();
            Users         = new UsersApi();
            Utils         = new UtilsApi();
            Video         = new VideoApi();
            Wall          = new WallApi();
            Widgets       = new WidgetsApi();
        }
Example #15
0
        public static void ShowAccountActivities(Account account)
        {
            Log.Write($"ShowAccountActivities for {account.Name} account");
            var accountingApi = new AccountingApi();

            foreach (var cashBalance in accountingApi.GetOwnedCashBalances(account.Id))
            {
                Log.Write(cashBalance);
            }
            var marginSnapshot = accountingApi.GetMarginSnapshot(account.Id);

            Log.Write(marginSnapshot);
            var balanceSnapshot = accountingApi.GetCashBalanceSnapshot(new GetCashBalanceSnapshot(account.Id));

            Log.Write(balanceSnapshot);
            var ordersApi = new OrdersApi();
            var orders    = ordersApi.GetOwnedOrders(account.Id);

            foreach (var order in orders)
            {
                Log.Write(order);
            }
            var accountOrders = orders.ToDictionary(x => x.Id);
            var fills         = ordersApi.GetAllFills().Where(fill => accountOrders.ContainsKey(fill.OrderId));

            foreach (var fill in fills)
            {
                Log.Write(fill);
            }
            var positionsApi = new PositionsApi();

            foreach (var position in positionsApi.GetOwnedPositions(account.Id))
            {
                Log.Write(position);
            }
        }
Example #16
0
        public DataTable GetData(int period, string report_guid, string tomcat, string login, string passw, DateTime from,
                                 DateTime to)
        {
            DataTable tableRes = GetTable();
            //1 неделя
            var res = OrdersApi.Olap(tomcat, login, passw, new string[] { "Department" },
                                     new string[] { "GuestNum" }, from.AddDays(-34), to.AddDays(-28));
            var table = new List <Dictionary <string, object> >();

            foreach (var line in res.data)
            {
                for (int i = 0; i < line.Count; ++i)
                {
                    line[line.Keys.ToList()[i]] = line[line.Keys.ToList()[i]].Replace(".", Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator).ToString());
                }
            }
            foreach (var a in res.data)
            {
                try
                {
                    var t = new Dictionary <string, object>();
                    t.Add("Week", "1");
                    t.Add("Department", a["Department"]);
                    t.Add("Guests", decimal.Parse(a["GuestNum"]));
                    t.Add("GuestsAnalysis", 0);
                    table.Add(t);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            //2 неделя
            res = OrdersApi.Olap(tomcat, login, passw, new string[] { "Department" },
                                 new string[] { "GuestNum" }, from.AddDays(-27), to.AddDays(-21));
            foreach (var line in res.data)
            {
                for (int i = 0; i < line.Count; ++i)
                {
                    line[line.Keys.ToList()[i]] = line[line.Keys.ToList()[i]].Replace(".", ",");
                }
            }
            foreach (var a in res.data)
            {
                try
                {
                    var t = new Dictionary <string, object>();
                    t.Add("Week", "2");
                    t.Add("Department", a["Department"]);
                    t.Add("Guests", decimal.Parse(a["GuestNum"]));
                    var GuestsLastWeek = table.FirstOrDefault(b => b["Week"].ToString() == "1" && b["Department"].ToString() == a["Department"])["Guests"];
                    t.Add("GuestsAnalysis", ((decimal)GuestsLastWeek > 0 ? (decimal.Parse(a["GuestNum"]) * 100 / (decimal)GuestsLastWeek - 100) : 0));
                    table.Add(t);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            //3 неделя
            res = OrdersApi.Olap(tomcat, login, passw, new string[] { "Department" },
                                 new string[] { "GuestNum" }, from.AddDays(-20), to.AddDays(-14));
            foreach (var line in res.data)
            {
                for (int i = 0; i < line.Count; ++i)
                {
                    line[line.Keys.ToList()[i]] = line[line.Keys.ToList()[i]].Replace(".", ",");
                }
            }
            foreach (var a in res.data)
            {
                try
                {
                    var t = new Dictionary <string, object>();
                    t.Add("Week", "3");
                    t.Add("Department", a["Department"]);
                    t.Add("Guests", decimal.Parse(a["GuestNum"]));
                    var GuestsLastWeek = table.FirstOrDefault(b => b["Week"].ToString() == "2" && b["Department"].ToString() == a["Department"])["Guests"];
                    t.Add("GuestsAnalysis", ((decimal)GuestsLastWeek > 0 ? (decimal.Parse(a["GuestNum"]) * 100 / (decimal)GuestsLastWeek - 100) : 0));
                    table.Add(t);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            //4 неделя
            res = OrdersApi.Olap(tomcat, login, passw, new string[] { "Department" },
                                 new string[] { "GuestNum" }, from.AddDays(-13), to.AddDays(-7));
            foreach (var line in res.data)
            {
                for (int i = 0; i < line.Count; ++i)
                {
                    line[line.Keys.ToList()[i]] = line[line.Keys.ToList()[i]].Replace(".", ",");
                }
            }

            foreach (var a in res.data)
            {
                try
                {
                    var t = new Dictionary <string, object>();
                    t.Add("Week", "4");
                    t.Add("Department", a["Department"]);
                    t.Add("Guests", decimal.Parse(a["GuestNum"]));
                    var GuestsLastWeek = table.FirstOrDefault(b => b["Week"].ToString() == "3" && b["Department"].ToString() == a["Department"])["Guests"];
                    t.Add("GuestsAnalysis", ((decimal)GuestsLastWeek > 0 ? (decimal.Parse(a["GuestNum"]) * 100 / (decimal)GuestsLastWeek - 100) : 0));
                    table.Add(t);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            //5 неделя
            res = OrdersApi.Olap(tomcat, login, passw, new string[] { "Department" },
                                 new string[] { "GuestNum" }, from.AddDays(-6), to);
            foreach (var line in res.data)
            {
                for (int i = 0; i < line.Count; ++i)
                {
                    line[line.Keys.ToList()[i]] = line[line.Keys.ToList()[i]].Replace(".", ",");
                }
            }

            foreach (var a in res.data)
            {
                try
                {
                    var t = new Dictionary <string, object>();
                    t.Add("Week", "5");
                    t.Add("Department", a["Department"]);
                    t.Add("Guests", decimal.Parse(a["GuestNum"]));
                    var GuestsLastWeek = table.FirstOrDefault(b => b["Week"].ToString() == "4" && b["Department"].ToString() == a["Department"])["Guests"];
                    t.Add("GuestsAnalysis", ((decimal)GuestsLastWeek > 0 ? (decimal.Parse(a["GuestNum"]) * 100 / (decimal)GuestsLastWeek - 100) : 0));
                    table.Add(t);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            try
            {
                foreach (var line in table)
                {
                    var data = line.Select(a => a.Value).Select(a => (object)a).ToArray();
                    tableRes.Rows.Add(data);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(tableRes);
        }
Example #17
0
        public DataTable GetData(int period, string report_guid, string tomcat, string login, string passw, DateTime from,
                                 DateTime to)
        {
            DataTable tableRes = GetTable();
            //1 неделя
            var res = OrdersApi.Olap(tomcat, login, passw, new string[] { "Department" },
                                     new string[] { "DishDiscountSumInt", "UniqOrderId" }, from.AddDays(-34), to.AddDays(-28));
            var table = new List <Dictionary <string, object> >();

            foreach (var line in res.data)
            {
                for (int i = 0; i < line.Count; ++i)
                {
                    line[line.Keys.ToList()[i]] = line[line.Keys.ToList()[i]].Replace(".", Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator).ToString());
                }
            }
            foreach (var a in res.data)
            {
                try
                {
                    var t = new Dictionary <string, object>();
                    t.Add("Week", "1");
                    t.Add("List", a["Department"]);
                    t.Add("AvgCheck", (decimal.Parse(a["DishDiscountSumInt"]) / decimal.Parse(a["UniqOrderId"])));
                    table.Add(t);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            //2 неделя
            res = OrdersApi.Olap(tomcat, login, passw, new string[] { "Department" },
                                 new string[] { "DishDiscountSumInt", "UniqOrderId" }, from.AddDays(-27), to.AddDays(-21));
            foreach (var line in res.data)
            {
                for (int i = 0; i < line.Count; ++i)
                {
                    line[line.Keys.ToList()[i]] = line[line.Keys.ToList()[i]].Replace(".", ",");
                }
            }
            foreach (var a in res.data)
            {
                try
                {
                    var t = new Dictionary <string, object>();
                    t.Add("Week", "2");
                    t.Add("List", a["Department"]);
                    t.Add("AvgCheck", (decimal.Parse(a["DishDiscountSumInt"]) / decimal.Parse(a["UniqOrderId"])));
                    table.Add(t);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            //3 неделя
            res = OrdersApi.Olap(tomcat, login, passw, new string[] { "Department" },
                                 new string[] { "DishDiscountSumInt", "UniqOrderId" }, from.AddDays(-20), to.AddDays(-14));
            foreach (var line in res.data)
            {
                for (int i = 0; i < line.Count; ++i)
                {
                    line[line.Keys.ToList()[i]] = line[line.Keys.ToList()[i]].Replace(".", ",");
                }
            }
            foreach (var a in res.data)
            {
                try
                {
                    var t = new Dictionary <string, object>();
                    t.Add("Week", "3");
                    t.Add("List", a["Department"]);
                    t.Add("AvgCheck", (decimal.Parse(a["DishDiscountSumInt"]) / decimal.Parse(a["UniqOrderId"])));
                    table.Add(t);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            //4 неделя
            res = OrdersApi.Olap(tomcat, login, passw, new string[] { "Department" },
                                 new string[] { "DishDiscountSumInt", "UniqOrderId" }, from.AddDays(-13), to.AddDays(-7));
            foreach (var line in res.data)
            {
                for (int i = 0; i < line.Count; ++i)
                {
                    line[line.Keys.ToList()[i]] = line[line.Keys.ToList()[i]].Replace(".", ",");
                }
            }

            foreach (var a in res.data)
            {
                try
                {
                    var t = new Dictionary <string, object>();
                    t.Add("Week", "4");
                    t.Add("List", a["Department"]);
                    t.Add("AvgCheck", (decimal.Parse(a["DishDiscountSumInt"]) / decimal.Parse(a["UniqOrderId"])));
                    table.Add(t);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            //5 неделя
            res = OrdersApi.Olap(tomcat, login, passw, new string[] { "Department" },
                                 new string[] { "DishDiscountSumInt", "UniqOrderId" }, from.AddDays(-6), to);
            foreach (var line in res.data)
            {
                for (int i = 0; i < line.Count; ++i)
                {
                    line[line.Keys.ToList()[i]] = line[line.Keys.ToList()[i]].Replace(".", ",");
                }
            }

            foreach (var a in res.data)
            {
                try
                {
                    var t = new Dictionary <string, object>();
                    t.Add("Week", "5");
                    t.Add("List", a["Department"]);
                    t.Add("AvgCheck", (decimal.Parse(a["DishDiscountSumInt"]) / decimal.Parse(a["UniqOrderId"])));
                    table.Add(t);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            try
            {
                foreach (var line in table)
                {
                    var data = line.Select(a => a.Value).Select(a => (object)a).ToArray();
                    tableRes.Rows.Add(data);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(tableRes);
        }
Example #18
0
 public OrdersApiTests()
 {
     instance = new OrdersApi();
 }
        public static async Task <List <Trade> > GetHistory()
        {
            var apiInstance = new OrdersApi();

            return(await apiInstance.OrdersGetHistoryAsync());
        }
        public ActionResult ChargeNonce()
        {
            string accessToken = "sandbox-sq0atb-D4TFGj4GmAew2U1yDuxe3Q";

            // Set the location ID
            string locId = "CBASECShk_d_mWkyYVT6bgiV52AgAQ";


            //Create configuration object for apiClient
            Square.Connect.Client.Configuration apiConfiguration = new Square.Connect.Client.Configuration();
            apiConfiguration.AccessToken = accessToken;

            //Create instance of api client
            Square.Connect.Client.ApiClient apiClient = new Square.Connect.Client.ApiClient(apiConfiguration);


            //Create instance of Orders api
            OrdersApi orderApi = new OrdersApi(apiConfiguration);

            //Create instance of Orders api
            CheckoutApi checkoutApi = new CheckoutApi(apiConfiguration);


            //Grab items from session and put them in a list
            List <Item> cartSession = (List <Item>)Session["cart"] != null ? (List <Item>)Session["cart"] : new List <Item>();


            //Create Line Item Request instance
            List <CreateOrderRequestLineItem> lineItems = new List <CreateOrderRequestLineItem>();

            //Create line item for each item stored in the cart session
            foreach (var item in cartSession)
            {
                int lineItemPrice = (int)(item.Product.ProductPrice * 100);

                Money price = new Money(lineItemPrice, Money.CurrencyEnum.USD);
                CreateOrderRequestLineItem lineItem = new CreateOrderRequestLineItem(item.Product.ProductTitle, item.Quantity.ToString(), price);

                lineItems.Add(lineItem);
            }

            string idempotencyKey = Guid.NewGuid().ToString();

            //Create new order request instance with cart items
            CreateOrderRequest orderRequest = new CreateOrderRequest(idempotencyKey, null, lineItems);

            //Get return URL
            //var urlBuilder =
            //new System.UriBuilder(Request.Url.AbsoluteUri)
            //{
            //    Path = Url.Action("PaymentConfirmation", "Products"),
            //    Query = null,
            //};

            //Uri uri = urlBuilder.Uri;
            //string url = urlBuilder.ToString();
            //UNCOMMENT AND CHANGE LAST NULL PARAMETER TO url


            CreateCheckoutRequest checkoutRequest = new CreateCheckoutRequest(idempotencyKey, orderRequest, true, null, null, null);

            try
            {
                var checkoutResponse = checkoutApi.CreateCheckout(locId, checkoutRequest);

                return(Redirect(checkoutResponse.Checkout.CheckoutPageUrl));
            }
            catch (Exception)
            {
                throw;
            }
        }
        public static async Task <List <Order> > GetOrders()
        {
            var apiInstance = new OrdersApi();

            return(await apiInstance.OrdersGetAsync());
        }
        public static async Task <Order> PostOrder(Order order)
        {
            var apiInstance = new OrdersApi();

            return(await apiInstance.OrdersPostAsync(order));
        }
Example #23
0
 public void Init()
 {
     instance = new OrdersApi();
 }
Example #24
0
        public static void ShowOrderDetails(ExecutionReport executionReport)
        {
            var ordersApi = new OrdersApi();

            ShowOrderDetails(ordersApi.GetOrder(executionReport.OrderId));
        }
Example #25
0
        public DataTable GetData(int period, string report_guid, string tomcat, string login, string passw, DateTime from,
                                 DateTime to)
        {
            DataTable tableRes = GetTable();
            //текущая неделя
            var res = OrdersApi.Olap(tomcat, login, passw, new string[] { "Department" },
                                     new string[] { "GuestNum", "DishDiscountSumInt", "UniqOrderId" }, from.AddDays(-6), to);
            var table = new List <Dictionary <string, object> >();

            foreach (var line in res.data)
            {
                for (int i = 0; i < line.Count; ++i)
                {
                    line[line.Keys.ToList()[i]] = line[line.Keys.ToList()[i]].Replace(".", Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator).ToString());
                }
            }
            if (res.data.Count == 0)
            {
                try
                {
                    var t = table.FirstOrDefault();
                    if (t != null)
                    {
                        t.Add("Guests", 0);
                        t.Add("Средний чек", 0);
                    }
                }
                catch (Exception ex)
                {
                    //Логгируем ошибку и идем дальше!
                    Console.WriteLine(ex.Message);
                }
            }
            foreach (var a in res.data)
            {
                try
                {
                    var t = new Dictionary <string, object>();
                    t.Add("Ресторан", a["Department"]);
                    t.Add("Guests", decimal.Parse(a["GuestNum"]));
                    t.Add("Средний чек",
                          (decimal.Parse(a["DishDiscountSumInt"]) / decimal.Parse(a["UniqOrderId"])));

                    table.Add(t);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            //текущие 4 недели
            res = OrdersApi.Olap(tomcat, login, passw, new string[] { "Department" },
                                 new string[] { "GuestNum", "DishDiscountSumInt", "UniqOrderId" }, from.AddDays(-27), to);
            foreach (var line in res.data)
            {
                for (int i = 0; i < line.Count; ++i)
                {
                    line[line.Keys.ToList()[i]] = line[line.Keys.ToList()[i]].Replace(".", ",");
                }
            }
            if (res.data.Count == 0)
            {
                try
                {
                    var t = table.FirstOrDefault();
                    if (t != null)
                    {
                        t.Add("GuestsFourWeeks", 0);
                        t.Add("Средний чек за 4 недели", 0);
                    }
                }
                catch (Exception ex)
                {
                    //Логгируем ошибку и идем дальше!
                    Console.WriteLine(ex.Message);
                }
            }

            foreach (var a in res.data)
            {
                try
                {
                    var t = table.FirstOrDefault(b => b["Ресторан"].ToString() == a["Department"]);
                    if (t != null)
                    {
                        t.Add("GuestsFourWeeks", decimal.Parse(a["GuestNum"]));
                        t.Add("Средний чек за 4 недели",
                              (decimal.Parse(a["DishDiscountSumInt"]) / decimal.Parse(a["UniqOrderId"])));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            //предыдущая неделя

            res = OrdersApi.Olap(tomcat, login, passw, new string[] { "Department" },
                                 new string[] { "GuestNum", "DishDiscountSumInt", "UniqOrderId" }, from.AddDays(-13), to.AddDays(-7));
            foreach (var line in res.data)
            {
                for (int i = 0; i < line.Count; ++i)
                {
                    line[line.Keys.ToList()[i]] = line[line.Keys.ToList()[i]].Replace(".", ",");
                }
            }

            if (res.data.Count == 0)
            {
                try
                {
                    var t = table.FirstOrDefault();
                    if (t != null)
                    {
                        t.Add("GuestsLastWeek", 0);
                        t.Add("Средний чек к прошлой неделе", 0);
                        t.Add("Отношение гостей. Одна неделя", 0);
                        t.Add("Отношение чеков. Одна неделя", 0);
                    }
                }
                catch (Exception ex)
                {
                    //Логгируем ошибку и идем дальше!
                    Console.WriteLine(ex.Message);
                }
            }
            foreach (var a in res.data)
            {
                try
                {
                    var t = table.FirstOrDefault(b => b["Ресторан"].ToString() == a["Department"]);
                    if (t != null)
                    {
                        t.Add("GuestsLastWeek", decimal.Parse(a["GuestNum"]));
                        t.Add("Средний чек к прошлой неделе",
                              (decimal.Parse(a["DishDiscountSumInt"]) / decimal.Parse(a["UniqOrderId"])));
                        t.Add("Отношение гостей. Одна неделя", (decimal)t["GuestsLastWeek"] > 0 ? ((decimal)t["Guests"] * 100 / (decimal)t["GuestsLastWeek"] - 100) : 0);
                        t.Add("Отношение чеков. Одна неделя", (decimal)t["Средний чек к прошлой неделе"] > 0 ?
                              ((decimal)t["Средний чек"] * 100 / (decimal)t["Средний чек к прошлой неделе"] - 100) : 0);
                    }
                }
                catch (Exception ex)
                {
                    //Логгируем ошибку и идем дальше!
                    Console.WriteLine(ex.Message);
                }
            }

            //предыдущие 4 недели
            res = OrdersApi.Olap(tomcat, login, passw, new string[] { "Department" },
                                 new string[] { "GuestNum", "DishDiscountSumInt", "UniqOrderId" }, from.AddDays(-55), to.AddDays(-28));
            foreach (var line in res.data)
            {
                for (int i = 0; i < line.Count; ++i)
                {
                    line[line.Keys.ToList()[i]] = line[line.Keys.ToList()[i]].Replace(".", ",");
                }
            }
            if (res.data.Count == 0)
            {
                try
                {
                    var t = table.FirstOrDefault();
                    if (t != null)
                    {
                        t.Add("GuestsLastFourWeeks", 0);
                        t.Add("Средний чек к прошлым 4 неделям", 0);
                        t.Add("Отношение гостей. Четыре недели", 0);
                        t.Add("Отношение чеков. Четыре недели", 0);
                    }
                }
                catch (Exception ex)
                {
                    //Логгируем ошибку и идем дальше!
                    Console.WriteLine(ex.Message);
                }
            }

            foreach (var a in res.data)
            {
                try
                {
                    var t = table.FirstOrDefault(b => b["Ресторан"].ToString() == a["Department"]);
                    if (t != null)
                    {
                        t.Add("GuestsLastFourWeek", decimal.Parse(a["GuestNum"]));
                        t.Add("Средний чек к прошлым 4 неделям",
                              (decimal.Parse(a["DishDiscountSumInt"]) / decimal.Parse(a["UniqOrderId"])));
                        t.Add("Отношение гостей. Четыре недели", (decimal)t["GuestsLastFourWeek"] > 0 ? ((decimal)t["GuestsFourWeeks"] * 100 / (decimal)t["GuestsLastFourWeek"] - 100) : 0);
                        t.Add("Отношение чеков. Четыре недели", (decimal)t["Средний чек к прошлым 4 неделям"] > 0 ?
                              ((decimal)t["Средний чек за 4 недели"] * 100 / (decimal)t["Средний чек к прошлым 4 неделям"] - 100) : 0);
                    }
                }
                catch (Exception ex)
                {
                    //Логгируем ошибку и идем дальше!
                    Console.WriteLine(ex.Message);
                }
            }
            try
            {
                foreach (var line in table)
                {
                    var data = line.Select(a => a.Value).Select(a => (object)a).ToArray();
                    tableRes.Rows.Add(data);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(tableRes);
        }
Example #26
0
        public static async void ShowOrderDetails(Order order)
        {
            Log.Write($"SHOW ORDER DETAILS FOR {order.Id}");
            var ordersApi      = new OrdersApi();
            var orderCommands  = ordersApi.GetOwnedCommands(order.Id);
            var currentCommand = orderCommands.LastOrDefault(command => command.CommandType == Command.CommandTypeEnum.New || command.CommandType == Command.CommandTypeEnum.Modify && (command.CommandStatus == Command.CommandStatusEnum.AtExecution || command.CommandStatus == Command.CommandStatusEnum.OnHold || command.CommandStatus == Command.CommandStatusEnum.ExecutionSuspended));

            if (currentCommand != null)
            {
                var currentOrderVersion = ordersApi.GetOrderVersion(currentCommand.Id);
                var fills            = ordersApi.GetOwnedFills(order.Id);
                var commandIds       = orderCommands.Select(command => command.Id).ToList();
                var executionReports = ordersApi.GetOwnedExecutionReportsBatch(commandIds);
                var commandReports   = ordersApi.GetOwnedCommandReportsBatch(commandIds);

                var contractLibraryApi = new ContractLibraryApi();
                var contract           = await contractLibraryApi.GetContractAsync(order.ContractId);

                var contractMaturity = await contractLibraryApi.GetContractMaturityAsync(contract.ContractMaturityId);

                var product = await contractLibraryApi.GetProductAsync(contractMaturity.ProductId);

                var lines = orderCommands.Select(command => new
                {
                    Id        = command.Id,
                    Timestamp = command.Timestamp,
                    Text      = GetCommandDescription(order, contract, command)
                })
                            .Concat(
                    fills.Select(fill => new
                {
                    Id        = fill.Id,
                    Timestamp = fill.Timestamp,
                    Text      = GetFillDescription(fill)
                }))
                            .Concat(
                    commandReports.Select(commandReport => new
                {
                    Id        = commandReport.Id,
                    Timestamp = commandReport.Timestamp,
                    Text      = GetCommandReportDescription(commandReport)
                }))
                            .Concat(
                    executionReports.Select(executionReport => new
                {
                    Id        = executionReport.Id,
                    Timestamp = executionReport.Timestamp,
                    Text      = GetExecutionReportDescription(executionReport)
                }));

                string orderStatus;

                switch (order.OrdStatus)
                {
                case Order.OrdStatusEnum.Working:
                    var totalFilled = fills.Where(fill => fill.Active == true).Sum(fill => fill.Qty);
                    if (totalFilled > 0)
                    {
                        orderStatus = "Partially Filled";
                    }
                    else
                    {
                        orderStatus = order.OrdStatus.ToString();
                    }
                    break;

                default:
                    orderStatus = order.OrdStatus.ToString();
                    break;
                }

                string accountHolderEmail;
                var    accountingApi = new AccountingApi();
                var    account       = await accountingApi.GetAccountAsync(order.AccountId);

                try
                {
                    // CTA should look through trading permissions
                    var allTradingPermissions = await accountingApi.GetAllTradingPermissionsAsync();

                    var tradingPermission = allTradingPermissions.First(x => x.AccountId == account.Id && x.Status == TradingPermission.StatusEnum.Approved);
                    accountHolderEmail = tradingPermission.AccountHolderEmail;
                }
                catch
                {
                    // Organization Admin or actual owner of the account has access to User entity
                    var userApi = new UsersApi();
                    var user    = await userApi.GetUserAsync(account.UserId);

                    accountHolderEmail = user.Email;
                }

                Log.Write($"Order #{order.Id} {GetOrderVersionDescription(order, contract, currentOrderVersion)} - {orderStatus}, Acc: #{account.Name}, Email: #{accountHolderEmail}");
                foreach (var line in lines.OrderBy(x => x.Id).ThenBy(x => x.Timestamp))
                {
                    Console.WriteLine($"{line.Timestamp} #{line.Id}: {line.Text}");
                }
                Console.WriteLine();
            }
        }