コード例 #1
0
 public void EditOrder(Domain.Order order)
 {
     if (_db.Order.Find(order.Orderid) != null)
     {
         _db.Order.Update(Mapper.Map(order));
     }
 }
コード例 #2
0
        public void Handle(StartNewOrder message)
        {
            ValidateProduct(message.ProductId);
            var order = new Domain.Order(message.Id, message.ProductId, message.Quantity);

            repository.Save(order);
        }
コード例 #3
0
        public async Task CompleteOrder(Domain.Order completedOrder)
        {
            var potentialOrders = _context.Orders
                                  .Where(x =>
                                         !x.ActualCostPerShare.HasValue &&
                                         !x.ActualSharesBought.HasValue &&
                                         x.Position.StockSymbol == completedOrder.StockSymbol)
                                  .Select(x => new { ShareDiff = Math.Abs(x.AttemptedSharesBought - completedOrder.SharesBought), Value = x })
                                  .OrderBy(x => x.ShareDiff)
                                  .ToList();

            if (potentialOrders.Any())
            {
                // If there are more than one portential orders, we just want to pick one closet to the attempted shares bought and assign it.
                var order = potentialOrders.Select(x => x.Value).First();

                order.ActualCostPerShare = completedOrder.MarketPrice;
                order.ActualSharesBought = completedOrder.SharesBought;

                await _context.SaveChangesAsync();
            }
            else if (potentialOrders.Count > 1)
            {
                Console.WriteLine("Failed to find potential order that matched. Ignoring for now");
            }
        }
コード例 #4
0
        // CRUD Orders

        /// <summary>
        /// Returns the list of all Orders in the database.
        /// </summary>
        /// <returns> List<Order> toReturn </returns>
        public List <Domain.Order> GetAllOrders()
        {
            var dbOrders = _context.Set <Order>().ToList();
            List <Domain.Order> toReturn = new List <Domain.Order>();

            foreach (var o in dbOrders)
            {
                var n = new Domain.Order(o.Id, o.CustomerId, o.LocationId)
                {
                    Time = (DateTimeOffset)o.Time
                };

                var lines = _context.Set <OrderLine>().Where(i => i.OrderId == o.Id).ToList();
                foreach (var i in lines)
                {
                    var dbProduct  = _context.Set <Product>().Where(p => p.Id == i.ProductId).FirstOrDefault();
                    var domProduct = new Domain.Product(dbProduct.Id, dbProduct.Name, (decimal)dbProduct.Price);

                    n.SetItemAmount(domProduct, i.Amount);
                }
                toReturn.Add(n);
            }

            return(toReturn);
        }
コード例 #5
0
        public async Task <bool> CreateInvoiceAsync(Domain.Order order)
        {
            var customer = await getOrCreateCustomer(order);

            var service = new StripeInvoiceItemService();

            foreach (var line in order.OrderLines)
            {
                var createInvoiceLineOptions = new StripeInvoiceItemCreateOptions
                {
                    Amount      = (int)(line.LineTotal * 100m), // inclusive of quantity & tax
                    Currency    = "nok",                        // TODO: read this from config
                    CustomerId  = customer.Id,
                    Description = !string.IsNullOrWhiteSpace(line.ProductVariantName) ? $"{line.ProductName} ({line.ProductVariantName})" : line.ProductName,
                };
                var invoiceLineItem = await service.CreateAsync(createInvoiceLineOptions);
            }

            var eventInfo            = order.Registration.EventInfo;
            var createInvoiceOptions = new StripeInvoiceCreateOptions
            {
                Billing      = StripeBilling.SendInvoice,
                DaysUntilDue = eventInfo.DateStart.HasValue ? ((eventInfo.LastCancellationDate ?? eventInfo.LastRegistrationDate ?? eventInfo.DateStart) - DateTime.UtcNow).Value.Days : 30,
                Description  = $"Deltakelse for {order.Registration.ParticipantName} på {order.Registration.EventInfo.Title} "
            };
            var createInvoiceService = new StripeInvoiceService();
            await createInvoiceService.CreateAsync(customer.Id, createInvoiceOptions);

            return(true);
        }
コード例 #6
0
        private void SendNotification(Domain.Order stocks, OrderUpdateCommand notification)
        {
            MailMessage mailMessage = new MailMessage();

            mailMessage.From = new MailAddress("*****@*****.**");
            mailMessage.To.Add("*****@*****.**");
            StringBuilder sb = new StringBuilder();

            sb.Append($"\nItems:");

            foreach (var item in notification.Items)
            {
                sb.Append($"\n ProductId - {item.ProductId}");
                sb.Append($"\t Quantity - {item.Quantity}");
                sb.Append($"\t Price - ${item.Price}");
            }

            mailMessage.Body       = $"Your order {stocks.OrderId} has been {stocks.Status}. {sb}";
            mailMessage.Subject    = "subject";
            mailMessage.IsBodyHtml = false;

            SmtpClient client = new SmtpClient("smtp.gmail.com");

            client.UseDefaultCredentials = true;
            client.Credentials           = new NetworkCredential("*****@*****.**", "AES123456@");
            client.Port      = 587;
            client.EnableSsl = true;

            client.Send(mailMessage);
        }
コード例 #7
0
        public async Task <PlaceOrderResponse> PlaceOrder(PlaceOrderRequest request)
        {
            //Perform domain validation
            if (CanPlaceOrder(request))
            {
                var domainOrder = new Domain.Order()
                {
                    DatePlaced       = DateTime.Now,
                    CustomerId       = request.Order.CustomerId,
                    PromotionCode    = request.Order.PromotionCode,
                    BillingAddress   = request.Order.BillingAddress,
                    OrderLines       = request.Order.OrderLines,
                    ShippingAddress  = request.Order.ShippingAddress,
                    ShippingCost     = request.Order.ShippingCost,
                    TotalCost        = request.Order.TotalCost,
                    TransitLocations = request.Order.TransitLocations
                };
                //store the order in the repository
                await _unitOfWork.OrderRepos.AddAsync(domainOrder);

                _unitOfWork.Complete();
                var response = PlaceOrderResponse.Create(true, string.Empty, domainOrder.Id);
                //publish
                //_publisher.Publish(MapToContract(domainOrder, orderId));
                return(response);
            }
            else
            {
                var response = PlaceOrderResponse.Create(false, "Order validation failed", null);
                return(response);
            }
        }
コード例 #8
0
 private Order MapToContract(Domain.Order order, int?orderId = null)
 {
     return(Order.Create(
                orderId: orderId ?? order.OrderId,
                orderLines: order.OrderLines.Select(line => OrderLine.Create(
                                                        product: Product.Create(
                                                            stockcode: line.Product.Stockcode,
                                                            productImageUrl: line.Product.ProductImageUrl,
                                                            volumetricWeight: line.Product.VolumetricWeight
                                                            ),
                                                        quantity: line.Quantity,
                                                        unitPrice: line.UnitPrice
                                                        )).ToList(),
                customerId: order.CustomerId,
                totalCost: order.TotalCost,
                shippingCost: order.ShippingCost,
                billingAddress: Address.Create(order.BillingAddress.AddressLine1,
                                               order.BillingAddress.AddressLine2,
                                               order.BillingAddress.Country),
                shippingAddress: Address.Create(order.ShippingAddress.AddressLine1,
                                                order.ShippingAddress.AddressLine2,
                                                order.ShippingAddress.Country),
                promotionCode: order.PromotionCode,
                datePlaced: order.DatePlaced));
 }
コード例 #9
0
        public async Task <Result <Guid> > Handle(CreateConsumerOrderCommand request, CancellationToken token)
        {
            var cartProductsResult = await _orderService.GetCartProductsAsync(request.Products, token);

            if (!cartProductsResult.Succeeded)
            {
                return(Failure <Guid>(cartProductsResult));
            }

            var cartDeliveriesResult = await _orderService.GetCartDeliveriesAsync(request.ProducersExpectedDeliveries,
                                                                                  cartProductsResult.Data, token);

            if (!cartDeliveriesResult.Succeeded)
            {
                return(Failure <Guid>(cartDeliveriesResult));
            }

            Domain.User user = request.UserId.HasValue && request.UserId != Guid.Empty
                ? await _context.Users.SingleAsync(e => e.Id == request.UserId.Value, token)
                : null;

            var order = new Domain.Order(Guid.NewGuid(), request.Donation, cartProductsResult.Data,
                                         _pspOptions.FixedAmount,
                                         _pspOptions.Percent, _pspOptions.VatPercent, user);

            order.SetDeliveries(cartDeliveriesResult.Data);

            await _context.AddAsync(order, token);

            await _context.SaveChangesAsync(token);

            return(Success(order.Id));
        }
コード例 #10
0
        public async Task Handle(CreateOrder command)
        {
            Domain.Order order = new Domain.Order
            {
                Id     = Guid.NewGuid(),
                BookId = command.BookId
            };
            try
            {
                await _repository.Add(order);

                OrderCreated orderCreated = new OrderCreated
                {
                    OrderId       = order.Id,
                    TransactionId = command.TransactionId
                };

                await _bus.PublishAsync(orderCreated);
            }
            catch (Exception exception)
            {
                CreateOrderFailed failed = new CreateOrderFailed
                {
                    OrderId = order.Id,
                    Message = exception.Message
                };

                await _bus.PublishAsync(failed);
            }
        }
コード例 #11
0
 public void SaveWithUser(Domain.Order order)
 {
     Data.Order Dorder = Mapper.DomOrder2DataOrder(order);
     context.Attach(Dorder.Customer);
     context.Order.Add(Dorder);
     context.SaveChanges();
 }
コード例 #12
0
        /// <summary>
        /// Adds the given Order to the database.
        /// </summary>
        /// <param name="o"></param>
        public void AddOrder(Domain.Order o)
        {
            using var logStream = new StreamWriter("bkdb-logs.txt", append: false)
                  {
                      AutoFlush = true
                  };
            using var _context = GenerateDBContext(logStream);

            Order entity = new Order()
            {
                CustomerId = o.CustomerID, LocationId = o.LocationID, Time = o.Time.UtcDateTime, TotalPrice = (decimal)o.Total
            };

            _context.Set <Order>().Add(entity);
            _context.SaveChanges();
            foreach (var kv in o.Items)
            {
                OrderLine ol = new OrderLine()
                {
                    OrderId = entity.Id, ProductId = kv.Key.ID, Amount = kv.Value
                };
                _context.Set <OrderLine>().Add(ol);
            }
            _context.SaveChanges();
        }
コード例 #13
0
        /// <summary>
        /// Returns the list of Orders placed at the Location with the given ID.
        /// </summary>
        /// <param name="locationID"></param>
        /// <returns> List<Order> toReturn </returns>
        public List <Domain.Order> GetOrdersByLocationID(int locationID)
        {
            using var logStream = new StreamWriter("bkdb-logs.txt", append: false)
                  {
                      AutoFlush = true
                  };
            using var _context = GenerateDBContext(logStream);

            var dbOrders = _context.Set <Order>().Where(i => i.LocationId == locationID).ToList();
            List <Domain.Order> toReturn = new List <Domain.Order>();

            foreach (var o in dbOrders)
            {
                var n = new Domain.Order(o.Id, o.CustomerId, o.LocationId)
                {
                    Time = (DateTimeOffset)o.Time
                };
                var lines = _context.Set <OrderLine>().Where(i => i.OrderId == o.Id).ToList();
                foreach (var i in lines)
                {
                    var dbProduct  = _context.Set <Product>().Where(p => p.Id == i.ProductId).FirstOrDefault();
                    var domProduct = new Domain.Product(dbProduct.Name, (decimal)dbProduct.Price);
                    n.SetItemAmount(domProduct, i.Amount);
                }
                toReturn.Add(n);
            }

            return(toReturn);
        }
コード例 #14
0
        /// <summary>
        /// Returns the specific Order matching the given ID.
        /// </summary>
        /// <param name="id"></param>
        /// <returns> Order ord </returns>
        public Domain.Order GetOrderByID(int id)
        {
            using var logStream = new StreamWriter("bkdb-logs.txt", append: false)
                  {
                      AutoFlush = true
                  };
            using var _context = GenerateDBContext(logStream);

            var o   = _context.Set <Order>().Find(id);
            var ord = new Domain.Order(o.Id, o.CustomerId, o.LocationId)
            {
                Time = (DateTimeOffset)o.Time
            };

            var items = _context.Set <OrderLine>().Where(i => i.OrderId == id).ToList();

            foreach (var i in items)
            {
                var dbProduct  = _context.Set <Product>().Where(p => p.Id == i.ProductId).FirstOrDefault();
                var domProduct = new Domain.Product(dbProduct.Name, (decimal)dbProduct.Price);
                ord.SetItemAmount(domProduct, i.Amount);
            }

            return(ord);
        }
コード例 #15
0
        public async Task <PaymentServiceResponseDTO> CreateInvoice(Domain.Order order)
        {
            var environment = new SandboxEnvironment("AZTu0aTctY3TsQRanLBGIjRYVhzo7rc25etnkVduypxV38zDdRja0Z6_adpN7nakww62w667wNh4_OKT", "EPT6TcCPEuAbNrCatN0_FyrWFTGtO6-1c77lhSj_pMrIx3o2V09BnpZnhLe3CfGO0wtW0IULHGI4yrGc");
            var client      = new PayPalHttpClient(environment);

            int totalPrice = 0;

            foreach (var product in order.ProductsInOrder)
            {
                totalPrice += product.Product.Price;
            }

            var payment = new Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        ItemList = new ItemList(),
                        Amount   = new Amount()
                        {
                            Total    = totalPrice.ToString(),
                            Currency = "USD"
                        }
                    }
                },
                RedirectUrls = new RedirectUrls()
                {
                    CancelUrl = "https://example.com/cancel",
                    ReturnUrl = "https://example.com/return"
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);

            try
            {
                HttpResponse response = await client.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();
                return(new PaymentServiceResponseDTO {
                    PaymentUrl = result.Links.FirstOrDefault(link => link.Rel == APPROVAL_URL).Href
                });
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                return(null);
            }
        }
コード例 #16
0
ファイル: OrderNotifier.cs プロジェクト: 842549829/Pool
 public OrderNotifier(Domain.Order order)
 {
     if (order == null)
     {
         throw new InvalidOperationException("order");
     }
     Order = order;
 }
コード例 #17
0
ファイル: OrderApiDto.cs プロジェクト: aburok/NorthwindStore
 public static OrderApiDto FromDomain(Domain.Order order)
 {
     return(new OrderApiDto()
     {
         Id = order.Id,
         OrderedAt = order.OrderedAt
     });
 }
        private void PrepareHeader(Domain.Order entry, OrderCreateCommand command)
        {
            entry.Status      = Common.Enums.OrderStatus.Pending;
            entry.PaymentType = command.PaymentType;
            entry.ClientId    = command.ClientId;
            entry.CreateAt    = DateTime.UtcNow;

            entry.Total = entry.Items.Sum(x => x.Total);
        }
コード例 #19
0
        public async Task <CompleteOrderResponse> CompleteOrder(CompleteOrderRequest request)
        {
            Domain.Order order = await repo.GetOrder(request.OrderId);

            order.Confirm();
            order = await repo.SaveAsync(order);

            return(new CompleteOrderResponse(true, ResponseAction.Updated));
        }
コード例 #20
0
        public async Task <CancelOrderResponse> CancelOrder(CancelOrderRequest request)
        {
            Domain.Order order = await repo.GetOrder(request.OrderId);

            order.Cancel();
            order = await repo.SaveAsync(order);

            return(new CancelOrderResponse(true, ResponseAction.Updated));
        }
コード例 #21
0
        public Task CreateAsync(Domain.Order order)
        {
            var id = _orders.Keys.Max() + 1;

            order.Id = id;
            _orders.Add(order.Id, order);

            return(Task.CompletedTask);
        }
コード例 #22
0
        public static Data.Entities.Order Map(Domain.Order dmOrder)
        {
            Data.Entities.Order deOrder = new Entities.Order();
            deOrder.Orderid     = dmOrder.Orderid;
            deOrder.Ocustomerid = dmOrder.Ocustomerid;
            deOrder.Datetime    = dmOrder.Datetime;

            return(deOrder);
        }
コード例 #23
0
 private void PrepareDetail(Domain.Order order, OrderCreateCommand command)
 {
     order.Items = command.Items.Select(x => new OrderDetail
     {
         ProductId = x.ProductId,
         Quantity  = x.Quantity,
         UnitPrice = x.Price,
         Total     = x.Price * x.Quantity
     }).ToList();
 }
コード例 #24
0
 private void PrepareDetail(Domain.Order entry, OrderCreateCommand notification)
 {
     entry.Items = notification.Items.Select(x => new OrderDetail
     {
         ProductId = x.ProductId,
         Quantity  = x.Quantity,
         UnitPrice = x.Price,
         Total     = x.Price * x.Quantity
     }).ToList();
 }
コード例 #25
0
        private void PrepareHeader(Domain.Order order, OrderCreateCommand command)
        {
            order.Status      = OrderStatus.Pending;
            order.PaymentType = command.PaymentType;
            order.ClientId    = command.ClientId;
            order.CreatedAt   = DateTime.UtcNow;

            // Sum
            order.Total = order.Items.Sum(x => x.Total);
        }
コード例 #26
0
        private void PrepareHeader(Domain.Order entry, OrderCreateCommand notification)
        {
            // Header information
            entry.Status      = Common.Enums.OrderStatus.Pending;
            entry.PaymentType = notification.PaymentType;
            entry.ClientId    = notification.ClientId;
            entry.CreatedAt   = DateTime.UtcNow;

            // Sum
            entry.Total = entry.Items.Sum(x => x.Total);
        }
コード例 #27
0
        public async Task <PaymentServiceResponseDTO> CreateInvoice(Domain.Order order)
        {
            var environment = new SandboxEnvironment("AVKtkv3o13BU3eqJMpxTDJepdIsPUy1wwZNItREABfTzfc5pVhunjudf5LhzctAPw_WTC6Vvgaap5HSu", "EFCsGNXXcPrxCGkyuJM5d4Ge-fKzBeBtvE6tcDk4LOAGAFghMXDIPai8hMWKah5LLmz2ZaIPzG69fyzY");
            var client      = new PayPalHttpClient(environment);

            var payment = new Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total    = "10",
                            Currency = "USD"
                        }
                    }
                },
                RedirectUrls = new RedirectUrls()
                {
                    CancelUrl = "https://example.com/cancel",
                    ReturnUrl = "https://example.com/return"
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                }
            };

            PaymentCreateRequest request = new PaymentCreateRequest();

            request.RequestBody(payment);

            try
            {
                HttpResponse response = await client.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();

                return(new PaymentServiceResponseDTO
                {
                    PaymentUrl = result.Links.FirstOrDefault(link => link.Rel == APPROVAL_URL).Href
                });
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                return(null);
            }
        }
コード例 #28
0
ファイル: DataAccess.cs プロジェクト: vitrv/Revature-P0
        public void SaveOrder(Domain.Order order, Domain.Location loc, Domain.User u)
        {
            try
            {
                List <Data.Entities.Location> location = db.Location
                                                         .Where(l => l.Name.ToLower().Equals(loc.Name.ToLower()))
                                                         .ToList();
                Data.Entities.Location locEntity = location.First();

                List <Data.Entities.User> user = db.User
                                                 .Where(us => us.Username.ToLower().Equals(u.Username.ToLower()))
                                                 .ToList();
                Data.Entities.User userEntity = user.First();

                Data.Entities.Order result = new Data.Entities.Order();
                result.User = userEntity;
                result.Loc  = locEntity;

                foreach (var p in order._pizzas)
                {
                    Data.Entities.Pizza pizzaEntity = new Data.Entities.Pizza();

                    Data.Entities.PizzaComponent cheeseEntity = new Data.Entities.PizzaComponent();
                    cheeseEntity.C = GetComponentEntity(p.Cheese);

                    Data.Entities.PizzaComponent crustEntity = new Data.Entities.PizzaComponent();
                    crustEntity.C = GetComponentEntity(p.Crust);

                    Data.Entities.PizzaComponent sizeEntity = new Data.Entities.PizzaComponent();
                    sizeEntity.C = GetComponentEntity(p.Size);

                    pizzaEntity.PizzaComponent.Add(cheeseEntity);
                    pizzaEntity.PizzaComponent.Add(crustEntity);
                    pizzaEntity.PizzaComponent.Add(sizeEntity);

                    foreach (var t in p._toppings)
                    {
                        Data.Entities.PizzaComponent toppingEntity = new Data.Entities.PizzaComponent();
                        toppingEntity.C = GetComponentEntity(t);

                        pizzaEntity.PizzaComponent.Add(toppingEntity);
                    }

                    result.Pizza.Add(pizzaEntity);
                }

                db.Add(result);
                db.SaveChanges();
            }
            catch (System.InvalidOperationException)
            {
            }
        }
コード例 #29
0
 public static object GetOrderNotifModel(this Domain.Order order, string purchaseOrderId)
 {
     return(new
     {
         PurchaseOrderId = purchaseOrderId,
         Status = order.Status,
         CreatedOn = order.CreatedOn,
         TotalPrice = order.TotalPrice,
         TotalOnSalePrice = order.TotalOnSalePrice,
         TotalWholeSalePrice = order.TotalWholeSalePrice
     });
 }
コード例 #30
0
ファイル: OrderDto.cs プロジェクト: aburok/NorthwindStore
 public static OrderDto FromModel(Domain.Order order)
 {
     return(new OrderDto()
     {
         Id = order.Id,
         Company = order.Company,
         Country = order.ShipTo.Country,
         ShipToLine1 = order.ShipTo.Line1,
         ShipToLine2 = order.ShipTo.Line2,
         OrderedAt = order.OrderedAt
     });
 }
コード例 #31
0
        public void Check_Customer_Modified_Since()
        {
            IEntity order = new Domain.Order() {
                Id = 1,
                PaymentStatus = PaymentStatus.PartiallyRefunded
            };

            string json = JsonConvert.SerializeObject(order, Formatting.Indented);

            //var client = new Client(this.ApiConfig);
            //var response1 = client.Utilities.GetTime();
            //var date = response1.Data.Item.CurrentTime;

            //var filter = new FilterCustomers();
            //filter.IfModifiedSince = ((DateTime)date).AddMinutes(-10);
            //var response2 = client.Customers.Get(filter);
            //var response3 = client.Customers.Count(filter);
        }