예제 #1
0
        /// <summary>
        /// A Lambda function that adds an order by customer.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <APIGatewayProxyResponse> AddOrderAsync(APIGatewayProxyRequest request, ILambdaContext context)
        {
            const string url = "https://maoproduce-stack-customer-signatures.s3-ap-southeast-2.amazonaws.com/";

            //instantiate new order object
            Orders newOrder   = new Orders();
            string customerId = null;
            string lastOrderId;

            //check for customerId parameter from url
            if (request.PathParameters != null && request.PathParameters.ContainsKey(ID_QUERY_STRING_NAME))
            {
                customerId = request.PathParameters[ID_QUERY_STRING_NAME];
            }
            else if (request.QueryStringParameters != null && request.QueryStringParameters.ContainsKey(ID_QUERY_STRING_NAME))
            {
                customerId = request.QueryStringParameters[ID_QUERY_STRING_NAME];
            }

            //GET the last order number
            var search = this.DDBContext.ScanAsync <CustomerOrders>(null);
            var page   = await search.GetNextSetAsync();

            List <int> list = new List <int>();


            if (!page.Any())
            {
                lastOrderId = "17050";
            }
            else
            {
                foreach (var customer in page)
                {
                    list.Add(int.Parse(customer.LastOrderId));
                }

                lastOrderId = (list.Max() + 1).ToString();
            }

            //get the request body
            var requestOrder = JsonConvert.DeserializeObject <Order_AllOrders>(request?.Body);

            //Convert sent All Orders to Orders Model
            newOrder.Id       = lastOrderId;
            newOrder.DateTime = DateTime.Now;
            newOrder.IsOpen   = requestOrder.IsOpen;

            //pass signature data to AWSS3BucketSave Function
            string          signatureTitle = newOrder.Id + "-" + String.Format("{0}.png", DateTime.Now.ToString("ddMMyyyyhhmmsstt"));
            AWSS3BucketSave bucket         = new AWSS3BucketSave();
            await bucket.WritingAnObjectAsync(requestOrder.Signature.Signature, signatureTitle);

            //New instance of signatture with url
            SignatureDetails sig = new SignatureDetails();
            var sigExist         = requestOrder.Signature;

            if (string.IsNullOrEmpty(sigExist.Signature))
            {
                sig.Signature = "";
                sig.Signee    = requestOrder.Signature.Signee;
            }
            else
            {
                sig.Signature = url + signatureTitle;
                sig.Signee    = requestOrder.Signature.Signee;
            }

            //Save new signature object
            newOrder.Signature  = sig;
            newOrder.TotalPrice = requestOrder.TotalPrice;
            newOrder.Products   = requestOrder.Products;

            ////load current customer data in dynamodb order table
            var custNewOrder = await DDBContext.LoadAsync <CustomerOrders>(customerId);

            if (custNewOrder != null)
            {
                custNewOrder.LastOrderId = lastOrderId;
                custNewOrder.Orders.Add(newOrder);

                //Save the order in the right customer.
                var saveOrder = DDBContext.SaveAsync <CustomerOrders>(custNewOrder);
            }
            else
            {
                CustomerOrders newCustOrder = new CustomerOrders();
                newCustOrder.CustomerId  = customerId;
                newCustOrder.LastOrderId = lastOrderId;
                newCustOrder.addList(newOrder);

                //Save to Dynamodb
                var saveOrder = DDBContext.SaveAsync <CustomerOrders>(newCustOrder);
            }

            //create success response
            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = JsonConvert.SerializeObject(new Dictionary <string, string> {
                    { "message", "Order sucessfully created" }, { "orderId", lastOrderId }
                }),
                Headers = new Dictionary <string, string> {
                    { "Content-Type", "application/json; charset=utf-8" }
                }
            };

            return(response);
        }
예제 #2
0
        /// <summary>
        /// A Lambda function that returns orders from a single customer. WORST CODE IN THIS PROJECT - DO IT BETTER PLS
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <APIGatewayProxyResponse> GetOrdersByCustAsync(APIGatewayProxyRequest request, ILambdaContext context)
        {
            //Two parameters should be passed. Customer Id is required to load orders from customer
            bool   isOpen       = true;
            string customerId   = null;
            string customerName = null;
            List <Order_AllOrders> orderList = new List <Order_AllOrders>();

            //check for customerId parameter
            if (request.PathParameters != null && request.PathParameters.ContainsKey(ID_QUERY_STRING_NAME))
            {
                customerId = request.PathParameters[ID_QUERY_STRING_NAME];
            }
            else if (request.QueryStringParameters != null && request.QueryStringParameters.ContainsKey(ID_QUERY_STRING_NAME))
            {
                customerId = request.QueryStringParameters[ID_QUERY_STRING_NAME];
            }
            //check for status(isOpen) filter
            if (request.QueryStringParameters != null && request.QueryStringParameters.ContainsKey("isOpen"))
            {
                isOpen = bool.Parse(request.QueryStringParameters["isOpen"]);
            }

            //Check if CustomerId exist; else send bad request response.
            if (string.IsNullOrEmpty(customerId))
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.BadRequest,
                    Body = $"Missing required parameter {ID_QUERY_STRING_NAME}"
                });
            }

            //Function to load from dynamodb
            context.Logger.LogLine($"Getting orders from customer {customerId}");
            var orders = new CustomerOrders();

            try
            {
                orders = await DDBContext.LoadAsync <CustomerOrders>(customerId);

                orders.Orders.Sort((o1, o2) => DateTime.Compare(o2.DateTime, o1.DateTime));
            }
            catch (Exception e)
            {
                //check if customer exist in orders table
                context.Logger.LogLine($"There was an error: {e}");
            }


            //check if orders exist in customer
            if (orders == null)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.NotFound,
                    Body = JsonConvert.SerializeObject(new Dictionary <string, string> {
                        { "message", "ORDER_IS_EMPTY" }
                    }),
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "application/json; charset=utf-8" }
                    }
                });
            }


            //Cycle through users and get the orders
            if (isOpen)
            {
                foreach (var item in orders.Orders)
                {
                    if (item.IsOpen == true)
                    {
                        //call function to get customer from customer table
                        LoadDatabase();
                        //call dynamodb
                        var search = this.DDBContext2.ScanAsync <Customers>(null);
                        var page   = await search.GetNextSetAsync();

                        foreach (var cust in page)
                        {
                            if (cust.Id == customerId)
                            {
                                customerName = cust.Name;
                            }
                        }
                        //assign all fields appropriately
                        //instantiate all order object to convert orders later
                        var allorder = new Order_AllOrders
                        {
                            CustomerId   = orders.CustomerId,
                            CustomerName = customerName,
                            DateTime     = item.DateTime,
                            Id           = item.Id,
                            IsOpen       = item.IsOpen,
                            Products     = item.Products,
                            Signature    = item.Signature,
                            TotalPrice   = item.TotalPrice
                        };
                        orderList.Add(allorder);
                    }
                }
            }
            else
            {
                foreach (var item in orders.Orders)
                {
                    //call function to get customer from customer table
                    LoadDatabase();
                    //call dynamodb
                    var search = this.DDBContext2.ScanAsync <Customers>(null);
                    var page   = await search.GetNextSetAsync();

                    foreach (var cust in page)
                    {
                        if (cust.Id == customerId)
                        {
                            customerName = cust.Name;
                        }
                    }
                    //assign all fields appropriately
                    //instantiate all order object to convert orders later
                    var allorder = new Order_AllOrders
                    {
                        CustomerId   = orders.CustomerId,
                        CustomerName = customerName,
                        DateTime     = item.DateTime,
                        Id           = item.Id,
                        IsOpen       = item.IsOpen,
                        Products     = item.Products,
                        Signature    = item.Signature,
                        TotalPrice   = item.TotalPrice
                    };
                    orderList.Add(allorder);
                }
            }



            //response
            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = LowercaseJsonSerializer.SerializeObject(orderList),
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "application/json; charset=utf-8" }
                }
            };

            return(response);
        }