コード例 #1
0
        public string Process(MerchantTribeApplication app, Dictionary<string, ITagHandler> handlers, ParsedTag tag, string contents)
        {
            string result = string.Empty;

            Orders.Order o = new Orders.Order();
            if (app.CurrentRequestContext.CurrentReceiptOrder != null)
            {
                o = app.CurrentRequestContext.CurrentReceiptOrder;

                // Adwords Tracker at bottom if needed
                if (app.CurrentStore.Settings.Analytics.UseGoogleAdWords)
                {
                    result = MerchantTribe.Commerce.Metrics.GoogleAnalytics.RenderGoogleAdwordTracker(
                                                            o.TotalGrand,
                                                            app.CurrentStore.Settings.Analytics.GoogleAdWordsId,
                                                            app.CurrentStore.Settings.Analytics.GoogleAdWordsLabel,
                                                            app.CurrentStore.Settings.Analytics.GoogleAdWordsBgColor,
                                                            app.CurrentRequestContext.RoutingContext.HttpContext.Request.IsSecureConnection);
                }

                // Add Yahoo Tracker to Bottom if Needed
                if (app.CurrentStore.Settings.Analytics.UseYahooTracker)
                {
                    result += MerchantTribe.Commerce.Metrics.YahooAnalytics.RenderYahooTracker(
                        o, app.CurrentStore.Settings.Analytics.YahooAccountId);
                }
            }

            return result;
        }
コード例 #2
0
        public static Orders.Order CurrentShoppingCart(Orders.OrderService svc, Store currentStore)
        {
            Orders.Order result = null;

            if (CurrentUserHasCart(currentStore))
            {
                Orders.Order cachedCart = SessionManager.CachedShoppingCart;
                if (cachedCart != null)
                {
                    return(cachedCart);
                }
                else
                {
                    result = svc.Orders.FindForCurrentStore(GetCurrentCartID(currentStore));
                    if (result != null)
                    {
                        if (!result.IsPlaced)
                        {
                            if (result.bvin != string.Empty)
                            {
                                SessionManager.CachedShoppingCart = result;
                                return(result);
                            }
                        }
                    }
                }
            }

            result = new Orders.Order();
            svc.Orders.Upsert(result);
            SetCurrentCartId(currentStore, result.bvin);
            SessionManager.CachedShoppingCart = result;
            return(result);
        }
コード例 #3
0
        public Collection <ShippingRateDisplay> GetRates(Orders.Order o, Accounts.Store currentStore)
        {
            Collection <ShippingRateDisplay> result = new Collection <ShippingRateDisplay>();
            List <ShippingGroup>             groups = o.GetShippingGroups();

            return(GetRates(groups, currentStore));
        }
コード例 #4
0
        public string Process(MerchantTribeApplication app, Dictionary <string, ITagHandler> handlers, ParsedTag tag, string contents)
        {
            string result = string.Empty;

            Orders.Order o = new Orders.Order();
            if (app.CurrentRequestContext.CurrentReceiptOrder != null)
            {
                o = app.CurrentRequestContext.CurrentReceiptOrder;

                // Adwords Tracker at bottom if needed
                if (app.CurrentStore.Settings.Analytics.UseGoogleAdWords)
                {
                    result = MerchantTribe.Commerce.Metrics.GoogleAnalytics.RenderGoogleAdwordTracker(
                        o.TotalGrand,
                        app.CurrentStore.Settings.Analytics.GoogleAdWordsId,
                        app.CurrentStore.Settings.Analytics.GoogleAdWordsLabel,
                        app.CurrentStore.Settings.Analytics.GoogleAdWordsBgColor,
                        app.CurrentRequestContext.RoutingContext.HttpContext.Request.IsSecureConnection);
                }

                // Add Yahoo Tracker to Bottom if Needed
                if (app.CurrentStore.Settings.Analytics.UseYahooTracker)
                {
                    result += MerchantTribe.Commerce.Metrics.YahooAnalytics.RenderYahooTracker(
                        o, app.CurrentStore.Settings.Analytics.YahooAccountId);
                }
            }

            return(result);
        }
コード例 #5
0
 public void OrderReceived(Orders.Order order, MerchantTribeApplication app)
 {
     if (OnOrderReceived != null)
     {
         OnOrderReceived(this, order, app);
     }
 }
コード例 #6
0
        public bool RecordPaymentTransaction(MerchantTribe.Payment.Transaction t, Orders.Order o)
        {
            OrderTransaction ot = new OrderTransaction(t);

            ot.OrderId = o.bvin;
            ot.StoreId = o.StoreId;
            return(Create(ot));
        }
コード例 #7
0
        private void OrderMatch(string data)
        {
            var message = JsonConvert.DeserializeObject <Messages.Matched>(data, JsonSettings);
            var cached  = CachedOrderIDs.Where(o => o.Value.BrokerId.Contains(message.MakerOrderId) || o.Value.BrokerId.Contains(message.TakerOrderId));

            var symbol = ConvertProductId(message.ProductId);

            if (!cached.Any())
            {
                return;
            }

            Log.Trace($"GDAXBrokerage.OrderMatch(): Match: {message.ProductId} {data}");
            var orderId  = cached.First().Key;
            var orderObj = cached.First().Value;

            if (!FillSplit.ContainsKey(orderId))
            {
                FillSplit[orderId] = new GDAXFill(orderObj);
            }

            var split = FillSplit[orderId];

            split.Add(message);

            //is this the total order at once? Is this the last split fill?
            var status = Math.Abs(message.Size) == Math.Abs(cached.Single().Value.Quantity) || Math.Abs(split.OrderQuantity) == Math.Abs(split.TotalQuantity())
                ? OrderStatus.Filled : OrderStatus.PartiallyFilled;

            OrderDirection direction;

            // Messages are always from the perspective of the market maker. Flip it in cases of a market order.
            if (orderObj.Type == OrderType.Market)
            {
                direction = message.Side == "sell" ? OrderDirection.Buy : OrderDirection.Sell;
            }
            else
            {
                direction = message.Side == "sell" ? OrderDirection.Sell : OrderDirection.Buy;
            }

            var orderEvent = new OrderEvent
                             (
                cached.First().Key, symbol, message.Time, status,
                direction,
                message.Price, direction == OrderDirection.Sell ? -message.Size : message.Size,
                GetFee(cached.First().Value), $"GDAX Match Event {direction}"
                             );

            //if we're filled we won't wait for done event
            if (orderEvent.Status == OrderStatus.Filled)
            {
                Orders.Order outOrder = null;
                CachedOrderIDs.TryRemove(cached.First().Key, out outOrder);
            }

            OnOrderEvent(orderEvent);
        }
コード例 #8
0
        public ActionResult CreateOrder()
        {
            // uncomment for postman customerIdParseResult = 1
            int customerIdParseResult;

            int.TryParse(_userContext.CustomerId(), out customerIdParseResult);
            var orderItems = new List <OrderItem> {
                new OrderItem()
                {
                    Quantity = 2, ProductId = 38
                }, new OrderItem()
                {
                    Quantity = 1, ProductId = 2
                }
            };
            var shippingAddress = new Address
            {
                Address1      = "21 West 52nd Street",
                Email         = "*****@*****.**",
                FirstName     = "John",
                LastName      = "Smith",
                City          = "New York",
                PhoneNumber   = "12345678",
                ZipPostalCode = "10021",
                CountryId     = 1,
                CreatedOnUtc  = DateTime.UtcNow,
            };
            var billingAddress = new Address
            {
                Address1      = "21 West 52nd Street",
                Email         = "*****@*****.**",
                FirstName     = "John",
                LastName      = "Smith",
                City          = "New York",
                PhoneNumber   = "12345678",
                ZipPostalCode = "10021",
                CountryId     = 1,
                CreatedOnUtc  = DateTime.UtcNow,
            };


            var stubOrder = new Orders.Order
            {
                CustomerId     = customerIdParseResult,
                OrderItems     = orderItems,
                ShippingMethod = "Shipping.FixedRate",
                ShippingRateComputationMethodSystemName = " Shipping Rate Computation Method System Name",
                ShippingAddress         = shippingAddress,
                BillingAddress          = billingAddress,
                CreatedOnUtc            = DateTime.UtcNow,
                PaidDateUtc             = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture),
                PaymentMethodSystemName = "Payments.Manual"
            };

            var order = _nopService.CreateOrder(stubOrder);

            return(new EmptyResult());
        }
コード例 #9
0
ファイル: OrderDto.cs プロジェクト: luqizheng/OrderBaseSystem
 public OrderDto(Orders.Order order)
 {
     Id         = order.Id;
     ClosePrice = order.CloseInfo.Price.Bid;
     CloseTime  = order.CloseTime;
     OpenPrice  = order.OpenInfo.Price.Bid;
     OpenTime   = order.OpenInfo.Price.ArrivedTime.ToString("yyyy-MM-dd HH:mm:ss");
     Status     = order.Status.ToString();
 }
コード例 #10
0
ファイル: SqlEtlTests.cs プロジェクト: morhilai/ravendb
        public void Should_stop_batch_if_size_limit_exceeded_RavenDB_12800()
        {
            using (var store = GetDocumentStore(new Options
            {
                ModifyDatabaseRecord = x => x.Settings[RavenConfiguration.GetKey(c => c.Etl.MaxBatchSize)] = "5"
            }))
            {
                CreateRdbmsSchema(store, @"
CREATE TABLE [dbo].[Orders]
(
    [Id] [nvarchar](50) NOT NULL,
    [Pic] [varbinary](max) NULL
)
");
                using (var session = store.OpenSession())
                {
                    for (int i = 0; i < 10; i++)
                    {
                        var order = new Orders.Order();
                        session.Store(order);

                        var r = new Random(i);

                        var bytes = new byte[1024 * 1024 * 1];

                        r.NextBytes(bytes);

                        session.Advanced.Attachments.Store(order, "my-attachment", new MemoryStream(bytes));
                    }

                    session.SaveChanges();
                }

                var etlDone = WaitForEtl(store, (n, statistics) => statistics.LoadSuccesses > 0);

                SetupSqlEtl(store, @"

var orderData = {
    Id: id(this),
    Pic: loadAttachment('my-attachment') 
};

loadToOrders(orderData);
");

                etlDone.Wait(TimeSpan.FromMinutes(5));

                var database = GetDatabase(store.Database).Result;

                var etlProcess = (SqlEtl)database.EtlLoader.Processes.First();

                var stats = etlProcess.GetPerformanceStats();

                Assert.Contains("Stopping the batch because maximum batch size limit was reached (5 MBytes)", stats.Select(x => x.BatchCompleteReason).ToList());
            }
        }
コード例 #11
0
        public Orders.Order CreateOrder(Orders.Order order)
        {
            string jsonUrl = "api/orders";

            string jsonOrder = JsonConvert.SerializeObject(new
            {
                order = order
            });
            object orderData = _nopApiClient.Post(jsonUrl, jsonOrder);
            var    newOrder  = JsonConvert.DeserializeObject <OrdersRootObject>(orderData.ToString());

            return(newOrder.Orders.FirstOrDefault());
        }
コード例 #12
0
 //Конструктор создания новой строки
 public RouteListItem(RouteList routeList, Order order)
 {
     this.routeList = routeList;
     if(order.OrderStatus == OrderStatus.Accepted)
     {
         this.order = order;
         order.OrderStatus = OrderStatus.InTravelList;
     }
     if (routeList.Status == RouteListStatus.EnRoute)
     {
         this.Order = order;
     }
 }
コード例 #13
0
 public PromotionContext(MerchantTribeApplication app,
                         Orders.Order o,
                         Membership.CustomerAccount currentUser,
                         DateTime currentTimeUtc)
 {
     this.CustomerDescription = string.Empty;
     this.Mode                  = PromotionType.Offer;
     this.MTApp                 = app;
     this.Order                 = o;
     this.Product               = null;
     this.UserPrice             = null;
     this.CurrentDateAndTimeUtc = DateTime.UtcNow;
     this.CurrentCustomer       = currentUser;
 }
コード例 #14
0
        public bool ApplyToOrder(MerchantTribeApplication app,
                                 Orders.Order o,
                                 Membership.CustomerAccount currentCustomer,
                                 DateTime currentDateTimeUtc,
                                 PromotionActionMode mode)
        {
            if (app == null)
            {
                return(false);
            }
            if (o == null)
            {
                return(false);
            }
            if (currentDateTimeUtc == null)
            {
                return(false);
            }

            PromotionContext context = new PromotionContext(app, o, currentCustomer, currentDateTimeUtc);

            context.CustomerDescription = this.CustomerDescription;

            // Make sure we have an active promotion before applying
            if (GetStatus(context.CurrentDateAndTimeUtc) != PromotionStatus.Active)
            {
                return(false);
            }

            // Make sure we meet all requirements
            // NOTE: we order by processing cost which should allow us to check
            // the fastest items first. For example, checking userID is faster
            // than checking user group because ID is in the context and group
            // requires a database call.
            foreach (IPromotionQualification q in this._Qualifications.OrderBy(y => y.ProcessingCost))
            {
                if (!q.MeetsQualification(context))
                {
                    return(false);
                }
            }

            // We're qualified, do actions
            foreach (IPromotionAction a in this._Actions)
            {
                a.ApplyAction(context, mode);
            }

            return(true);
        }
コード例 #15
0
ファイル: GDAXBrokerage.cs プロジェクト: farshidgit/Lean
        /// <summary>
        /// Cancels an order
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public override bool CancelOrder(Orders.Order order)
        {
            var success = new List <bool>();

            foreach (var id in order.BrokerId)
            {
                var req = new RestRequest("/orders/" + id, Method.DELETE);
                GetAuthenticationToken(req);
                var response = RestClient.Execute(req);
                success.Add(response.StatusCode == System.Net.HttpStatusCode.OK);
            }

            return(success.All(a => a));
        }
コード例 #16
0
        public static string RenderLatestTrackerAndTransaction(string googleId, Orders.Order o, string storeName, string categoryName)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("<script type=\"text/javascript\">\n");
            sb.Append("var _gaq = _gaq || [];\n");
            sb.Append("_gaq.push(['_setAccount', '" + googleId + "']);\n");
            sb.Append("_gaq.push(['_trackPageview']);\n");

            if (o != null)
            {
                sb.Append("_gaq.push(['_addTrans',\n");
                sb.Append("'" + GoogleSafeString(o.OrderNumber) + "',\n");                // order ID - required
                sb.Append("'" + GoogleSafeString(storeName) + "',\n");                    // affiliation or store name
                sb.Append("'" + o.TotalGrand + "',\n");                                   // total - required
                sb.Append("'" + o.TotalTax + "',\n");                                     // tax
                sb.Append("'" + o.TotalShippingAfterDiscounts + "',\n");                  // shipping
                sb.Append("'" + GoogleSafeString(o.ShippingAddress.City) + "',\n");       // city
                sb.Append("'" + GoogleSafeString(o.ShippingAddress.RegionName) + "',\n"); // state or province
                sb.Append("'" + GoogleSafeString(o.ShippingAddress.CountyName) + "'\n");  // country
                sb.Append("]);\n");

                foreach (Orders.LineItem li in o.Items)
                {
                    // add item might be called for every item in the shopping cart
                    // where your ecommerce engine loops through each item in the cart and
                    // prints out _addItem for each
                    sb.Append("_gaq.push(['_addItem',\n");
                    sb.Append("'" + GoogleSafeString(o.OrderNumber) + "',\n");  // order ID - required
                    sb.Append("'" + GoogleSafeString(li.ProductSku) + "',\n");  // SKU/code - required
                    sb.Append("'" + GoogleSafeString(li.ProductName) + "',\n"); // product name
                    sb.Append("'" + GoogleSafeString(categoryName) + "',\n");   // category or variation
                    sb.Append("'" + li.AdjustedPricePerItem + "',\n");          // unit price - required
                    sb.Append("'" + li.Quantity + "'\n");                       // quantity - required
                    sb.Append("]);\n");
                }

                sb.Append("_gaq.push(['_trackTrans']);\n"); //submits transaction to the Analytics servers
            }

            sb.Append("(function() {\n");
            sb.Append("var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n");
            sb.Append("ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n");
            sb.Append("var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n");
            sb.Append("})();\n");
            sb.Append("</script>\n");

            return(sb.ToString());
        }
コード例 #17
0
ファイル: GDAXBrokerage.cs プロジェクト: farshidgit/Lean
        /// <summary>
        /// Retreives the fee for a given order
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public decimal GetFee(Orders.Order order)
        {
            var totalFee = 0m;

            foreach (var item in order.BrokerId)
            {
                var req = new RestRequest("/orders/" + item, Method.GET);
                GetAuthenticationToken(req);
                var response = RestClient.Execute(req);
                var fill     = JsonConvert.DeserializeObject <dynamic>(response.Content);

                totalFee += (decimal)fill.fill_fees;
            }

            return(totalFee);
        }
コード例 #18
0
        private void addOrder(object sender, System.Windows.RoutedEventArgs e)
        {
            // Add a new Order.

            if (dataGrid1.SelectedItem == null)
            {
                // The user must select an Order to create a new one.
                MessageBox.Show("Must be positioned on an order to be able to create a new one");
                return;
            }
            var order    = ((OrderInfo)dataGrid1.SelectedItem).Order;
            var newOrder = new Orders.Order();

            // Assign the new Order to the Customer of the currently selected Order.
            newOrder.Customer = order.Customer;
            newOrder.OrderID  = 99999;
        }
コード例 #19
0
 public static void SaveOrderCookies(Orders.Order o, Store currentStore)
 {
     if (o.IsPlaced)
     {
         // Clear Cookies
         SetCookieString(WebAppSettings.CookieNameCartId(currentStore.Id), string.Empty, currentStore);
         SetCookieString(WebAppSettings.CookieNameCartItemCount(currentStore.Id), "0", currentStore);
         SetCookieString(WebAppSettings.CookieNameCartSubTotal(currentStore.Id), "0", currentStore);
     }
     else
     {
         // Save Cart Cookie
         SetCookieString(WebAppSettings.CookieNameCartId(currentStore.Id), o.bvin, currentStore);
         SetCookieString(WebAppSettings.CookieNameCartItemCount(currentStore.Id), Math.Round(o.TotalQuantity, 0).ToString(), currentStore);
         SetCookieString(WebAppSettings.CookieNameCartSubTotal(currentStore.Id), o.TotalOrderAfterDiscounts.ToString("c"), currentStore);
     }
 }
コード例 #20
0
        public Orders.Order UpdateOrder(Orders.Order order)
        {
            string jsonOrder = JsonConvert.SerializeObject(new
            {
                order = order
            });

            var id = order.Id;

            string jsonUrl = $"/api/orders/{id}";

            var orderData = _nopApiClient.Put(jsonUrl, jsonOrder);

            var newOrder = JsonConvert.DeserializeObject <OrdersRootObject>(orderData.ToString());

            return(newOrder.Orders.FirstOrDefault());
        }
コード例 #21
0
        public void Populate(Orders.Order o, OrderService svc)
        {
            Clear();

            foreach (Orders.OrderTransaction t in svc.Transactions.FindForOrder(o.bvin))
            {
                _TotalCredit += t.AmountAppliedToOrder;
                switch (t.Action)
                {
                case MerchantTribe.Payment.ActionType.CashReceived:
                case MerchantTribe.Payment.ActionType.CheckReceived:
                case MerchantTribe.Payment.ActionType.CreditCardCapture:
                case MerchantTribe.Payment.ActionType.CreditCardCharge:
                case MerchantTribe.Payment.ActionType.GiftCardCapture:
                case MerchantTribe.Payment.ActionType.GiftCardDecrease:
                case MerchantTribe.Payment.ActionType.PayPalCapture:
                case MerchantTribe.Payment.ActionType.PayPalCharge:
                case MerchantTribe.Payment.ActionType.PurchaseOrderAccepted:
                case MerchantTribe.Payment.ActionType.CompanyAccountAccepted:
                case MerchantTribe.Payment.ActionType.RewardPointsCapture:
                case MerchantTribe.Payment.ActionType.RewardPointsDecrease:
                    _AmountCharged += t.AmountAppliedToOrder;
                    break;

                case MerchantTribe.Payment.ActionType.CreditCardHold:
                case MerchantTribe.Payment.ActionType.GiftCardHold:
                case MerchantTribe.Payment.ActionType.PayPalHold:
                case MerchantTribe.Payment.ActionType.RewardPointsHold:
                    _AmountAuthorized += t.AmountHeldForOrder;
                    break;

                case MerchantTribe.Payment.ActionType.CashReturned:
                case MerchantTribe.Payment.ActionType.CheckReturned:
                case MerchantTribe.Payment.ActionType.CreditCardRefund:
                case MerchantTribe.Payment.ActionType.GiftCardIncrease:
                case MerchantTribe.Payment.ActionType.PayPalRefund:
                case MerchantTribe.Payment.ActionType.RewardPointsIncrease:
                    _AmountRefunded += -1 * t.AmountAppliedToOrder;
                    break;
                }
            }

            _PaymentsSummary = svc.OrdersListPaymentMethods(o);
            _AmountDue       = o.TotalGrand - _TotalCredit;
        }
コード例 #22
0
ファイル: Check.cs プロジェクト: olegp306/ToyCorp2017
        public override string ProcessJavascriptButton(Orders.Order order)
        {
            string[] companyAccount =
            {
                order.PaymentDetails != null ? order.PaymentDetails.CompanyName : string.Empty,
                order.PaymentDetails != null ? order.PaymentDetails.INN : string.Empty
            };

            string companyName = string.Empty;
            string inn         = string.Empty;

            if (companyAccount.Length > 0)
            {
                companyName = "&bill_CompanyName=" + companyAccount[0];
            }
            if (companyAccount.Length > 1)
            {
                inn = "&bill_INN=" + companyAccount[1];
            }
            return(String.Format("javascript:open_printable_version('Check_{0}.aspx?ordernumber={1}&methodid={2}{3}{4}');", Type.ToString(), order.Number, PaymentMethodId, companyName, inn));
        }
コード例 #23
0
        private void OrderDone(string data)
        {
            Log.Trace($"GDAXBrokerage.Messaging.OrderDone(): Order completed with data {data}");
            var message = JsonConvert.DeserializeObject <Messages.Done>(data, JsonSettings);

            //if we don't exit now, will result in fill message
            if (message.Reason == "canceled" || message.RemainingSize > 0)
            {
                Log.Trace($"GDAXBrokerage.Messaging.OrderDone(): Order cancelled. Remaining {message.RemainingSize}");
                return;
            }

            //is this our order?
            var cached = CachedOrderIDs.Where(o => o.Value.BrokerId.Contains(message.OrderId));

            if (!cached.Any() || cached.Single().Value.Status == OrderStatus.Filled)
            {
                Log.Trace($"GDAXBrokerage.Messaging.OrderDone(): Order could not locate order in cache with order id {message.OrderId}");
                return;
            }

            OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Information, -1,
                                                $"GDAXWebsocketsBrokerage.OrderDone: Encountered done message prior to match filling order brokerId: {message.OrderId} orderId: {cached.FirstOrDefault().Key}"));

            var split = this.FillSplit[cached.First().Key];

            //should have already been filled but match message may have been missed. Let's say we've filled now
            var orderEvent = new OrderEvent
                             (
                cached.First().Key, ConvertProductId(message.ProductId), message.Time, OrderStatus.Filled,
                message.Side == "sell" ? OrderDirection.Sell : OrderDirection.Buy,
                message.Price, message.Side == "sell" ? -split.TotalQuantity() : split.TotalQuantity(),
                GetFee(cached.First().Value), "GDAX Fill Event"
                             );

            Orders.Order outOrder = null;
            CachedOrderIDs.TryRemove(cached.First().Key, out outOrder);

            OnOrderEvent(orderEvent);
        }
コード例 #24
0
        public static Repository.Model.Orders.Order ToRepository(this DtoOrder dto)
        {
            if (dto == null)
            {
                return(null);
            }

            var model = new Orders.Order()
            {
                Id = dto.Id,
                AgreesReference  = dto.AgreesReference,
                AgreesSimilar    = dto.AgreesSimilar,
                AgressGeneric    = dto.AgressGeneric,
                DeliveredOn      = dto.DeliveredOn,
                RequestedOn      = dto.RequestedOn,
                ScheduledTo      = dto.ScheduledTo,
                Client_Id        = dto.Client?.Id,
                AddressToShip_Id = dto.AddressToShip?.Id
            };

            return(model);
        }
コード例 #25
0
        public bool CanMarkOrderAsPaid(Orders.Order order)
        {
            if (order == null)
            {
                throw new ArgumentNullException("order");
            }

            // OrderStatus.Cancelled
            if (order.OrderStatus == "40")
            {
                return(false);
            }

            if (order.PaymentStatus == PaymentStatus.Paid.ToString() ||
                order.PaymentStatus == PaymentStatus.Refunded.ToString() ||
                order.PaymentStatus == PaymentStatus.Voided.ToString())
            {
                return(false);
            }

            return(true);
        }
コード例 #26
0
        private void OrderMatch(string data)
        {
            var message = JsonConvert.DeserializeObject <Messages.Matched>(data, JsonSettings);
            var cached  = CachedOrderIDs.Where(o => o.Value.BrokerId.Contains(message.MakerOrderId) || o.Value.BrokerId.Contains(message.TakerOrderId));

            var symbol = ConvertProductId(message.ProductId);

            if (!cached.Any())
            {
                return;
            }

            var split = this.FillSplit[cached.First().Key];

            split.Add(message);

            //is this the total order at once? Is this the last split fill?
            var status = Math.Abs(message.Size) == Math.Abs(cached.Single().Value.Quantity) || Math.Abs(split.OrderQuantity) == Math.Abs(split.TotalQuantity())
                ? OrderStatus.Filled : OrderStatus.PartiallyFilled;

            var orderEvent = new OrderEvent
                             (
                cached.First().Key, symbol, message.Time, status,
                message.Side == "sell" ? OrderDirection.Sell : OrderDirection.Buy,
                message.Price, message.Side == "sell" ? -message.Size : message.Size,
                GetFee(cached.First().Value), "GDAX Match Event"
                             );

            //if we're filled we won't wait for done event
            if (orderEvent.Status == OrderStatus.Filled)
            {
                Orders.Order outOrder = null;
                CachedOrderIDs.TryRemove(cached.First().Key, out outOrder);
            }

            OnOrderEvent(orderEvent);
        }
コード例 #27
0
        // working with local dates and times
        public static void GenerateInvoiceForStore(Store s, DateTime invoiceDateLocal, MerchantTribeApplication app)
        {
            // Create an Order
            Orders.Order o = new Orders.Order();
            o.StoreId = WebAppSettings.BillingStoreId;
            app.OrderServices.Orders.Create(o);

            o.Notes.Add(new Orders.OrderNote() { IsPublic = false, Note = "Auto Generated By Invoicing System" });

            // Base Rate
            Orders.LineItem li = new Orders.LineItem();
            li.BasePricePerItem = s.CurrentPlanRate;
            li.ProductName = "BV Commerce Hosted: " + s.PlanName;
            li.ProductSku = "BVH" + s.PlanId;
            li.Quantity = 1;
            li.QuantityShipped = 1;
            li.ShippingSchedule = -1;
            o.Items.Add(li);

            // need to add Percent of sales
            decimal lastMonthSales = 0;
            // End date should be immediately before bill not, not on the bill date
            DateTime localEnd = Dates.MaxOutTime(invoiceDateLocal);
            localEnd = localEnd.AddDays(-1);
            DateTime localStart = Dates.ZeroOutTime(invoiceDateLocal).AddMonths(-1);
            lastMonthSales = app.OrderServices.Transactions.FindBillableTransactionTotal(localStart.ToUniversalTime(),
                                                                        localEnd.ToUniversalTime(),
                                                                        s.Id);
            Orders.LineItem li2 = new Orders.LineItem();
            Decimal multiplier = s.CurrentPlanPercent / 100;
            Decimal transFees = Math.Round(multiplier * lastMonthSales, 2, MidpointRounding.AwayFromZero);
            li2.BasePricePerItem = transFees;
            li2.ProductName = "Transaction Fees:";
            li2.ProductShortDescription = s.CurrentPlanPercent + "% of " + lastMonthSales.ToString("c");
            li2.ProductShortDescription += " " + localStart.ToShortDateString() + " to " + localEnd.ToShortDateString();
            li2.ProductSku = "BVHTF";
            li2.Quantity = 1;
            li2.QuantityShipped = 1;
            li2.ShippingSchedule = -1;
            o.Items.Add(li2);

            List<UserAccount> users = app.AccountServices.FindAdminUsersByStoreId(s.Id);
            if (users != null)
            {
                if (users.Count > 0)
                {
                    UserAccount u = users[0];
                    o.UserEmail = u.Email;

                    Service svc = new Service(WebAppSettings.ApplicationConnectionString);
                    BillingAccount act = svc.Accounts.FindOrCreate(u.Email);
                    if (act != null)
                    {
                        o.BillingAddress.RegionData.Abbreviation = string.Empty;
                        o.BillingAddress.RegionName = string.Empty;
                        o.BillingAddress.PostalCode = act.BillingZipCode;
                        o.BillingAddress.FirstName = act.CreditCard.CardHolderName;
                        o.BillingAddress.Company = s.StoreName;

                        app.CalculateOrder(o);

                        Orders.OrderPaymentManager payManager = new Orders.OrderPaymentManager(o, app);
                        payManager.CreditCardAddInfo(act.CreditCard, o.TotalGrand);

                        o.OrderNumber = app.OrderServices.GenerateNewOrderNumber(WebAppSettings.BillingStoreId).ToString();
                        o.StatusCode = Orders.OrderStatusCode.Received;
                        o.IsPlaced = true;
                        o.TimeOfOrderUtc = DateTime.UtcNow;
                        o.EvaluateCurrentShippingStatus();

                        app.OrderServices.Orders.Update(o);
                    }
                }
            }
        }
コード例 #28
0
ファイル: GDAXBrokerage.cs プロジェクト: yuzhucu/Lean
        /// <summary>
        /// Creates a new order
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public override bool PlaceOrder(Orders.Order order)
        {
            LockStream();

            var req = new RestRequest("/orders", Method.POST);

            dynamic payload = new ExpandoObject();

            payload.size       = Math.Abs(order.Quantity);
            payload.side       = order.Direction.ToString().ToLower();
            payload.type       = ConvertOrderType(order.Type);
            payload.price      = order is LimitOrder ? ((LimitOrder)order).LimitPrice : order is StopMarketOrder ? ((StopMarketOrder)order).StopPrice : 0;
            payload.product_id = ConvertSymbol(order.Symbol);

            if (_algorithm.BrokerageModel.AccountType == AccountType.Margin)
            {
                payload.overdraft_enabled = true;
            }

            req.AddJsonBody(payload);

            GetAuthenticationToken(req);
            var response = RestClient.Execute(req);

            if (response.StatusCode == System.Net.HttpStatusCode.OK && response.Content != null)
            {
                var raw = JsonConvert.DeserializeObject <Messages.Order>(response.Content);

                if (raw == null || raw.Id == null)
                {
                    OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, (int)response.StatusCode, "GDAXBrokerage.PlaceOrder: Error parsing response from place order: " + response.Content));
                    UnlockStream();
                    return(false);
                }

                var brokerId = raw.Id;
                if (CachedOrderIDs.ContainsKey(order.Id))
                {
                    CachedOrderIDs[order.Id].BrokerId.Add(brokerId);
                }
                else
                {
                    order.BrokerId.Add(brokerId);
                    CachedOrderIDs.TryAdd(order.Id, order);
                }

                // Add fill splits in all cases; we'll need to handle market fills too.
                FillSplit.TryAdd(order.Id, new GDAXFill(order));

                // Generate submitted event
                OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, 0, "GDAX Order Event")
                {
                    Status = OrderStatus.Submitted
                });

                OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Information, -1, "GDAXBrokerage.PlaceOrder: Order completed successfully orderid:" + order.Id.ToString()));
                UnlockStream();
                return(true);
            }

            OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, 0, "GDAX Order Event")
            {
                Status = OrderStatus.Invalid
            });

            var message = $"GDAXBrokerage.PlaceOrder: Order failed Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: {response.Content}";

            OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, message));
            UnlockStream();
            return(false);
        }
コード例 #29
0
        public Orders.Order PreparePlaceOrderDetails(int userId)
        {
            var orderItems = new List <OrderItem>();/* { new OrderItem() { Quantity = 2, ProductId = 38 }, new OrderItem() { Quantity = 1, ProductId = 2 } };*/
            var cart       = _shoppingCartService.GetShoppingCart(userId.ToString());
            var products   = cart.Products;

            // TODO make it with mapper
            foreach (var product in products)
            {
                OrderItem item = new OrderItem
                {
                    Quantity  = product.Quantity,
                    ProductId = product.ProductId,
                    Product   = product.Product
                };

                orderItems.Add(item);
            }

            // TODO correct address
            #region Adresses
            var shippingAddress = new Address
            {
                Address1      = "21 West 52nd Street",
                Email         = "*****@*****.**",
                FirstName     = "John",
                LastName      = "Smith",
                City          = "New York",
                PhoneNumber   = "12345678",
                ZipPostalCode = "10021",
                CountryId     = 1,
                CreatedOnUtc  = DateTime.UtcNow
            };

            var billingAddress = new Address
            {
                Address1      = "21 West 52nd Street",
                Email         = "*****@*****.**",
                FirstName     = "John",
                LastName      = "Smith",
                City          = "New York",
                PhoneNumber   = "12345678",
                ZipPostalCode = "10021",
                CountryId     = 1,
                CreatedOnUtc  = DateTime.UtcNow,
            };
            #endregion

            var order = new Orders.Order
            {
                CustomerId     = userId,
                OrderItems     = orderItems,
                ShippingMethod = "Shipping.FixedRate",
                ShippingRateComputationMethodSystemName = "Shipping Rate Computation Method System Name",
                ShippingAddress         = shippingAddress,
                BillingAddress          = billingAddress,
                CreatedOnUtc            = DateTime.UtcNow,
                PaymentMethodSystemName = "Payments.Manual"
            };
            return(order);
        }
コード例 #30
0
 public override string ProcessJavascriptButton(Orders.Order order)
 {
     return(String.Format("javascript:open_printable_version('Check_{0}.aspx?ordernumber={1}&methodid={2}');", Type.ToString(), order.Number, PaymentMethodId));
 }
コード例 #31
0
 /// <summary>
 /// Creates instance of GDAXFill
 /// </summary>
 /// <param name="order"></param>
 public GDAXFill(Orders.Order order)
 {
     Order = order;
 }
コード例 #32
0
ファイル: GDAXBrokerage.cs プロジェクト: farshidgit/Lean
 /// <summary>
 /// This operation is not supported
 /// </summary>
 /// <param name="order"></param>
 /// <returns></returns>
 public override bool UpdateOrder(Orders.Order order)
 {
     throw new NotSupportedException("GDAXBrokerage.UpdateOrder: Order update not supported. Please cancel and re-create.");
 }
コード例 #33
0
 public Orders.Order UpdateOrder(Orders.Order order)
 {
     return(_nopService.UpdateOrder(order));
 }