/// <summary> /// A Lambda function that removes an order post from Customer in Orders table. /// </summary> /// <param name="request"></param> public async Task <APIGatewayProxyResponse> RemoveOrderAsync(APIGatewayProxyRequest request, ILambdaContext context) { string customerId = null; string orderId = null; if (request.PathParameters != null && request.PathParameters.ContainsKey(ID_QUERY_STRING_NAME)) { customerId = request.PathParameters[ID_QUERY_STRING_NAME]; } if (request.QueryStringParameters != null && request.QueryStringParameters.ContainsKey("orderId")) { orderId = request.QueryStringParameters["orderId"]; } if (string.IsNullOrEmpty(orderId) || string.IsNullOrEmpty(customerId)) { return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.BadRequest, Body = $"Missing required parameter {ID_QUERY_STRING_NAME}" }); } var cust = await DDBContext.LoadAsync <CustomerOrders>(customerId); if (cust != null) { foreach (var order in cust.Orders.ToList()) { if (order.Id == orderId) { cust.removeList(order); } } //Update Dynamodb await DDBContext.SaveAsync <CustomerOrders>(cust); } else { context.Logger.LogLine("There is an error please call the server master"); } return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = JsonConvert.SerializeObject(new Dictionary <string, string> { { "message", $"Sucessfully deleted the item: {orderId}" } }), Headers = new Dictionary <string, string> { { "Content-Type", "application/json; charset=utf-8" } } }); }
public async Task <VerificationStatus> RetrieveVerificationStatus(string username) { try { var verificationStatus = await DDBContext.LoadAsync <VerificationStatus>(username); return(verificationStatus); } catch (Exception ex) { throw ex; } }
public async Task <UserSetting> RetrieveUserSetting(string username) { try { var userSetting = await DDBContext.LoadAsync <UserSetting>(username); return(userSetting); } catch (Exception ex) { throw ex; } }
public async Task <UserProfile> RetrieveUser(string username) { try { var user = await DDBContext.LoadAsync <UserProfile>(username); user.UserTypeDescription = EnumHelper.GetDescription <UserType>(user.UserType); return(user); } catch (Exception ex) { throw ex; } }
/// <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); }
/// <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); }
///Function that sends an email with receipt attached public async Task <APIGatewayProxyResponse> SendEmailAsync(APIGatewayProxyRequest request, ILambdaContext context) { //Email Data Properties string htmlHeader; string customerId = null; string orderId = null; string year = DateTime.Now.ToString("yyyy"); string totalPrice = null; string subTotal; string signee = null; string signatureUrl = null; string quantity; string price; string description; string customer_name; List <OrderProduct> orderBody = new List <OrderProduct>(); CultureInfo culture = CultureInfo.CreateSpecificCulture("en-NZ"); culture.NumberFormat.CurrencyNegativePattern = 1; //Get HTTP URL PARAMETERS if (request.PathParameters != null && request.PathParameters.ContainsKey("CustomerId")) { customerId = request.PathParameters["CustomerId"]; } if (request.QueryStringParameters != null && request.QueryStringParameters.ContainsKey("orderId")) { orderId = request.QueryStringParameters["orderId"]; } //Null-check Get PARAMS ((RULE: customer ID cannot be null; if order id is null create new order else edit current order with orderId param)) if (!string.IsNullOrEmpty(customerId) && string.IsNullOrEmpty(orderId)) { //Create new instance of orderFunctions -> call add order var create = new OrderFunctions(this.DDBClient, "MaoProduce-Stack-OrderTable-1DCW9ZSV63ZU7"); await create.AddOrderAsync(request, context); } else if (!string.IsNullOrEmpty(customerId) && !string.IsNullOrEmpty(orderId)) { //update existing var update = new OrderFunctions(this.DDBClient, "MaoProduce-Stack-OrderTable-1DCW9ZSV63ZU7"); await update.UpdateOrderAsync(request, context); } else { //return 404 error return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.NotFound, Body = JsonConvert.SerializeObject(new Dictionary <string, string> { { "error", "CUSTOMER_NOT_FOUND" } }), Headers = new Dictionary <string, string> { { "Content-Type", "application/json; charset=utf-8" } } }); } try { //First get the customer details LoadDatabase(); var cust = await DDBContext2.LoadAsync <Customers>(customerId); //Assign customer details to the right property customer_name = cust.Name; //Secondly get the order details var order = await DDBContext.LoadAsync <CustomerOrders>(customerId); if (string.IsNullOrEmpty(orderId)) { orderId = order.LastOrderId; } //Assign orderdetails to the right property foreach (var item in order.Orders) { if (item.Id == orderId) { orderId = item.Id; signee = item.Signature.Signee; signatureUrl = item.Signature.Signature; totalPrice = item.TotalPrice; orderBody = item.Products; } } //Assign the products in order if (string.IsNullOrEmpty(signatureUrl)) { htmlHeader = $"<center> <table width=\"100%\" style=\"max-width:620px;margin:0 auto;border:1px solid black; background-color:#ffffff\" bgcolor=\"#ffffff\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"> <tbody><tr> <td width=\"100%\" style=\"text-align:left\"> <table width=\"100%\" cellspacing=\"0\" border=\"0\" cellpadding=\"20\" bgcolor=\"#ffffff\" style=\"background-color:#ffffff\"> <tbody><tr> <td width=\"30\"> <center> <img width=\"170px\" height=\"auto\" style=\"width:170px;height:auto\" alt=\"Mao Produce\" src=\"https://shop.maoproduce.co.nz/image/catalog/logo.png\" data-image-whitelisted=\"\"> <h2 style=\"color:#3a9821; font-family: Arial, Helvetica, sans-serif; font-size:34px; font-weight: normal; line-height: 1.3;\">Dispatch Slip</h2> </center> </td> </tr> </tbody></table> </td> </tr> <tr> <td width=\"100%\" style=\"text-align:left\"> <table width=\"100%\" cellspacing=\"20\" border=\"0\" cellpadding=\"20\" bgcolor=\"#3a9821\" style=\"background-color:#ffffff\"> <tbody><tr> <td bgcolor=\"#ffffff\" style=\"background-color:#ffffff\"> <h2 style=\"font-family:Arial, Helvetica, sans-serif; line-height: 1.3; font-weight: normal; font-size:20px\">Hi, {customer_name}</h2> <p style=\"font-family:Arial, Helvetica, sans-serif; line-height: 1.3; font-weight: normal; font-size: 15px; color:#474747\">You will find the order details in this email. <br> If you have any questions according to your order or about, please let us know.<br> Thanks for choosing Mao Produce. <br> </p><table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\"> <tbody><tr> <td valign=\"top\" width=\"50%\"> <table border=\"0\" cellspacing=\"0\" cellpadding=\"3\"> <tbody><tr> <td valign=\"top\">Order #:</td> <td valign=\"top\"><strong>{orderId}</strong></td> </tr> <tr> <td valign=\"top\">Signee:</td> <td valign=\"top\"> <strong>{signee}</strong> </td> <td> </td> </tr> <tr> <td> </td> </tr> </tbody></table> </td> <td valign=\"top\" width=\"50%\"> </td> </tr></tbody></table><hr> <div style=\"font-size:11px\"> <table style=\"width:100%\" cellspacing=\"0\" cellpadding=\"3\"> <thead> <tr> <th valign=\"top\" align=\"left\" style=\"background:#e3e3e3\">Description</th> <th valign=\"top\" align=\"right\" width=\"30\" style=\"background:#e3e3e3\">Qty</th> <th valign=\"top\" align=\"right\" width=\"100\" style=\"background:#e3e3e3\">Price</th> <th colspan=\"2\" valign=\"top\" align=\"right\" width=\"100\" style=\"background:#e3e3e3\">Sub-Total</th> </tr> </thead> <tbody>"; } else { htmlHeader = $"<center> <table width=\"100%\" style=\"max-width:620px;margin:0 auto;border:1px solid black; background-color:#ffffff\" bgcolor=\"#ffffff\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"> <tbody><tr> <td width=\"100%\" style=\"text-align:left\"> <table width=\"100%\" cellspacing=\"0\" border=\"0\" cellpadding=\"20\" bgcolor=\"#ffffff\" style=\"background-color:#ffffff\"> <tbody><tr> <td width=\"30\"> <center> <img width=\"170px\" height=\"auto\" style=\"width:170px;height:auto\" alt=\"Mao Produce\" src=\"https://shop.maoproduce.co.nz/image/catalog/logo.png\" data-image-whitelisted=\"\"> <h2 style=\"color:#3a9821; font-family: Arial, Helvetica, sans-serif; font-size:34px; font-weight: normal; line-height: 1.3;\">Dispatch Slip</h2> </center> </td> </tr> </tbody></table> </td> </tr> <tr> <td width=\"100%\" style=\"text-align:left\"> <table width=\"100%\" cellspacing=\"20\" border=\"0\" cellpadding=\"20\" bgcolor=\"#3a9821\" style=\"background-color:#ffffff\"> <tbody><tr> <td bgcolor=\"#ffffff\" style=\"background-color:#ffffff\"> <h2 style=\"font-family:Arial, Helvetica, sans-serif; line-height: 1.3; font-weight: normal; font-size:20px\">Hi, {customer_name}</h2> <p style=\"font-family:Arial, Helvetica, sans-serif; line-height: 1.3; font-weight: normal; font-size: 15px; color:#474747\">You will find the order details in this email. <br> If you have any questions according to your order or about, please let us know.<br> Thanks for choosing Mao Produce. <br> </p><table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\"> <tbody><tr> <td valign=\"top\" width=\"50%\"> <table border=\"0\" cellspacing=\"0\" cellpadding=\"3\"> <tbody><tr> <td valign=\"top\">Order #:</td> <td valign=\"top\"><strong>{orderId}</strong></td> </tr> <tr> <td valign=\"top\">Signee:</td> <td valign=\"top\"> <strong>{signee}</strong> </td> <td> <img width=\"100px\" height=\"auto\" src=\"{signatureUrl}\" valign=\"bottom\" alt=\"signature\" align=\"center\" class=\"text-center\"></td> </tr> <tr> <td> </td> </tr> </tbody></table> </td> <td valign=\"top\" width=\"50%\"> </td> </tr></tbody></table><hr> <div style=\"font-size:11px\"> <table style=\"width:100%\" cellspacing=\"0\" cellpadding=\"3\"> <thead> <tr> <th valign=\"top\" align=\"left\" style=\"background:#e3e3e3\">Description</th> <th valign=\"top\" align=\"right\" width=\"30\" style=\"background:#e3e3e3\">Qty</th> <th valign=\"top\" align=\"right\" width=\"100\" style=\"background:#e3e3e3\">Price</th> <th colspan=\"2\" valign=\"top\" align=\"right\" width=\"100\" style=\"background:#e3e3e3\">Sub-Total</th> </tr> </thead> <tbody>"; } string htmlHeaderNeg = ""; foreach (var products in orderBody) { description = products.Title; quantity = String.Format("{0:0.#}", double.Parse(products.Quantity)); price = String.Format(culture, "{0:C}", double.Parse(products.Price)); subTotal = String.Format(culture, "{0:C}", (double.Parse(products.Quantity) * double.Parse(products.Price))); //check if its a return if (double.Parse(products.Quantity) < 0 || double.Parse(products.Price) < 0) { // Display RED VERSION htmlHeaderNeg += $"<tr style=\"color:red;\"> <td valign=\"top\" align=\"left\">{description}</p></td> <td valign=\"top\" align=\"right\" width=\"30\">{quantity}</td> <td valign=\"top\" align=\"right\" width=\"100\">{price}</td> <td colspan=\"2\" valign=\"top\" align=\"right\" width=\"100\">{subTotal}</td></tr> "; } else { // The HTML body of the email. htmlHeader += $"<tr> <td valign=\"top\" align=\"left\">{description}</td> <td valign=\"top\" align=\"right\" width=\"30\">{quantity}</td> <td valign=\"top\" align=\"right\" width=\"100\">{price}</td> <td colspan=\"2\" valign=\"top\" align=\"right\" width=\"100\">{subTotal}</td> </tr> "; } } htmlHeader += htmlHeaderNeg; if (double.Parse(totalPrice) < 0) { htmlHeader += $"<tr> <td align=\"left\" colspan=\"5\" style=\"border-bottom:solid 1px #e3e3e3\"></td> </tr> </tbody> <tfoot> <tr> <td align=\"right\" colspan=\"4\" style=\"background:#e3e3e3\"><strong>Total:</strong></td> <td align=\"right\" style=\"background:#e3e3e3\"><strong style=\"color:red;\">{String.Format(culture, "{0:C}", double.Parse(totalPrice))}</strong></td> </tr> </tfoot> </table> </div><p><em style=\"font-family: Arial, Helvetica, sans-serif; font-size: 12px; color:#777777\"> <br> <center> \u00A9 Copyright © {year} <a style=\"text-decoration:none; color:#3a9821;\" href=\"https://www.maoproduce.co.nz\">Mao Produce</a> All Rights Reserved. <br> Powered by <a style=\"text-decoration:none; color:darkred;\" href=\"https://canit.co.nz\">CanIT Ltd.</a></p> </center></em></p> </td> </tr> </tbody></table> </td> </tr> </tbody></table> </center>"; } else { htmlHeader += $"<tr> <td align=\"left\" colspan=\"5\" style=\"border-bottom:solid 1px #e3e3e3\"></td> </tr> </tbody> <tfoot> <tr> <td align=\"right\" colspan=\"4\" style=\"background:#e3e3e3\"><strong>Total:</strong></td> <td align=\"right\" style=\"background:#e3e3e3\"><strong>{String.Format(culture, "{0:C}", double.Parse(totalPrice))}</strong></td> </tr> </tfoot> </table> </div><p><em style=\"font-family: Arial, Helvetica, sans-serif; font-size: 12px; color:#777777\"> <br> <center> \u00A9 Copyright © {year} <a style=\"text-decoration:none; color:#3a9821;\" href=\"https://www.maoproduce.co.nz\">Mao Produce</a> All Rights Reserved. <br> Powered by <a style=\"text-decoration:none; color:darkred;\" href=\"https://canit.co.nz\">CanIT Ltd.</a></p> </center></em></p> </td> </tr> </tbody></table> </td> </tr> </tbody></table> </center>"; } //First setup email/template string senderAddress = "Mao Produce <*****@*****.**>"; string receiverAddress = cust.Email; string configSet = "ConfigSet"; // The subject line for the email. string subject = $"Mao Produce Delivery Confirmation."; // The email body for recipients with non-HTML email clients. string textBody = @$ "Hi, {customer_name}, Thank you for your order with Mao Produce. We have recoreded your order: {orderId}. Please view this email in a updated browser to see more details. Thank You! Mao Produce"; // Set-up to SES client using var client = new AmazonSimpleEmailServiceV2Client(RegionEndpoint.APSoutheast2); var sendRequest = new SendEmailRequest() { ConfigurationSetName = configSet, FromEmailAddress = senderAddress, ReplyToAddresses = new List <string> { "*****@*****.**" }, Destination = new Destination { ToAddresses = new List <string> { receiverAddress } }, Content = new EmailContent { Simple = new Message { Subject = new Content { Data = subject }, Body = new Body { Html = new Content { Data = htmlHeader }, Text = new Content { Data = textBody } } } }, }; //Run email client var response = await client.SendEmailAsync(sendRequest); if (response.HttpStatusCode == HttpStatusCode.OK) { context.Logger.LogLine("The email was sent successfully."); } var res = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = JsonConvert.SerializeObject(new Dictionary <string, string> { { "message", "EMAIL_SENT" }, { "orderId", orderId } }), Headers = new Dictionary <string, string> { { "Content-Type", "application/json; charset=utf-8" } } }; orderId = null; return(res); }