Exemplo n.º 1
0
        public void PaymentFail(String orderStatus = "030")
        {
            NBrightBuyUtils.ProcessEventProvider(EventActions.BeforePaymentFail, PurchaseInfo);

            if (!PurchaseInfo.GetXmlPropertyBool("genxml/stopprocess"))
            {
                // only move back to cart, if we've not processed payment already.
                if (IsNotPaid())
                {
                    // If the client returns to the website before payment is accepted,
                    // then we may get a CART but no ORDER. So once it has moved to ORDER we cannot return to CART.
                    // In theory this should never happen, but in reality, this has happened.
                    //PurchaseTypeCode = "CART";

                    // make a new cart and copy the order data to it.
                    OrderFunctions.CopyToCart(this);

                    PurchaseTypeCode = "ORDER"; // Make sure this order is moved to an order.
                    CreatedDate      = DateTime.Now.ToString("O");
                    ReleaseModelTransQty();
                    if (orderStatus != "030")
                    {
                        OrderStatus = orderStatus;
                        AddAuditStatusChange(orderStatus, UserController.Instance.GetCurrentUserInfo().Username);
                    }
                    AddAuditStatusChange("030", UserController.Instance.GetCurrentUserInfo().Username);
                    OrderStatus = "030";
                    SavePurchaseData();
                }
            }

            NBrightBuyUtils.ProcessEventProvider(EventActions.AfterPaymentFail, PurchaseInfo);
        }
Exemplo n.º 2
0
        public void OnGet()
        {
            List <OrderViewModel> orders = new List <OrderViewModel>();

            var orderdtos = new OrderFunctions(conString, null, null, null, null).GetOrders();

            foreach (var order in orderdtos)
            {
                orders.Add(order);
            }
            foreach (var order in orders)
            {
                order.products = new OrderFunctions(conString, null, null, null, null).GetCartProductsFromOrderRef(order.OrderReference);
            }
            Orders = orders;
        }
Exemplo n.º 3
0
        public void ProcessRequest(HttpContext context)
        {
            #region "Initialize"

            var strOut = "** No Action **";

            var paramCmd       = Utils.RequestQueryStringParam(context, "cmd");
            var itemId         = Utils.RequestQueryStringParam(context, "itemid");
            var ctlType        = Utils.RequestQueryStringParam(context, "ctltype");
            var idXref         = Utils.RequestQueryStringParam(context, "idxref");
            var xpathpdf       = Utils.RequestQueryStringParam(context, "pdf");
            var xpathref       = Utils.RequestQueryStringParam(context, "pdfref");
            var lang           = Utils.RequestQueryStringParam(context, "lang");
            var language       = Utils.RequestQueryStringParam(context, "language");
            var moduleId       = Utils.RequestQueryStringParam(context, "mid");
            var moduleKey      = Utils.RequestQueryStringParam(context, "mkey");
            var parentid       = Utils.RequestQueryStringParam(context, "parentid");
            var entryid        = Utils.RequestQueryStringParam(context, "entryid");
            var entryxid       = Utils.RequestQueryStringParam(context, "entryxid");
            var catid          = Utils.RequestQueryStringParam(context, "catid");
            var catxid         = Utils.RequestQueryStringParam(context, "catxid");
            var templatePrefix = Utils.RequestQueryStringParam(context, "tprefix");
            var value          = Utils.RequestQueryStringParam(context, "value");
            var itemListName   = Utils.RequestQueryStringParam(context, "listname");
            if (itemListName == "")
            {
                itemListName = "ItemList";
            }
            if (itemListName == "*")
            {
                itemListName = "ItemList";
            }

            #region "setup language"

            // because we are using a webservice the system current thread culture might not be set correctly,
            _uilang = NBrightBuyUtils.SetContextLangauge(context);
            var ajaxInfo = NBrightBuyUtils.GetAjaxFields(context);
            _editlang = NBrightBuyUtils.GetEditLang(ajaxInfo, _uilang);

            #endregion

            Logging.Debug($"XmlConnector called with: paramCmd='{paramCmd}', itemId='{itemId}', itemListName='{itemListName}'");

            #endregion

            try
            {
                #region "Do processing of command"

                if (paramCmd.StartsWith("client."))
                {
                    strOut = ClientFunctions.ProcessCommand(paramCmd, context);
                }
                else if (paramCmd.StartsWith("orderadmin_"))
                {
                    strOut = OrderFunctions.ProcessCommand(paramCmd, context);
                }
                else if (paramCmd.StartsWith("payment_"))
                {
                    strOut = PaymentFunctions.ProcessCommand(paramCmd, context);
                }
                else if (paramCmd.StartsWith("product_"))
                {
                    ProductFunctions.EntityTypeCode = "PRD";
                    strOut = ProductFunctions.ProcessCommand(paramCmd, context, _editlang);
                }
                else if (paramCmd.StartsWith("category_"))
                {
                    CategoryFunctions.EntityTypeCode = "CATEGORY";
                    strOut = CategoryFunctions.ProcessCommand(paramCmd, context, _editlang);
                }
                else if (paramCmd.StartsWith("property_"))
                {
                    PropertyFunctions.EntityTypeCode = "CATEGORY";
                    strOut = PropertyFunctions.ProcessCommand(paramCmd, context, _editlang);
                }
                else if (paramCmd.StartsWith("itemlist_"))
                {
                    strOut = ItemListsFunctions.ProcessCommand(paramCmd, context);
                }
                else if (paramCmd.StartsWith("addressadmin_"))
                {
                    strOut = AddressAdminFunctions.ProcessCommand(paramCmd, context);
                }
                else if (paramCmd.StartsWith("plugins_"))
                {
                    strOut = PluginFunctions.ProcessCommand(paramCmd, context);
                }
                else if (paramCmd.StartsWith("cart_"))
                {
                    strOut = CartFunctions.ProcessCommand(paramCmd, context);
                }
                else
                {
                    switch (paramCmd)
                    {
                    case "test":
                        strOut = "<root>" + UserController.Instance.GetCurrentUserInfo().Username + "</root>";
                        break;

                    case "setdata":
                        break;

                    case "deldata":
                        break;

                    case "getdata":
                        strOut = GetReturnData(context);
                        break;

                    case "fileupload":
                        if (NBrightBuyUtils.CheckRights())
                        {
                            strOut = FileUpload(context);
                        }
                        break;

                    case "fileclientupload":
                        if (StoreSettings.Current.GetBool("allowupload"))
                        {
                            strOut = FileUpload(context, itemId);
                        }
                        break;

                    case "docdownload":

                        var fname   = Utils.RequestQueryStringParam(context, "filename");
                        var filekey = Utils.RequestQueryStringParam(context, "key");
                        if (filekey != "")
                        {
                            var uData = new UserData();
                            if (uData.HasPurchasedDocByKey(filekey))
                            {
                                fname = uData.GetPurchasedFileName(filekey);
                            }
                            fname = StoreSettings.Current.FolderDocuments + "/" + fname;
                        }
                        if (fname != "")
                        {
                            strOut = fname;     // return this is error.
                            var downloadname = Utils.RequestQueryStringParam(context, "downloadname");
                            var fpath        = HttpContext.Current.Server.MapPath(fname);
                            if (downloadname == "")
                            {
                                downloadname = Path.GetFileName(fname);
                            }
                            try
                            {
                                Utils.ForceDocDownload(fpath, downloadname, context.Response);
                            }
                            catch (Exception ex)
                            {
                                // ignore, robots can cause error on thread abort.
                                //Exceptions.LogException(ex);
                                Logging.Debug($"XmlConnector.ProcessRequest exception for {paramCmd} which is ignored because bots tend to cause these on thread abort: {ex.Message}.");
                            }
                        }
                        break;

                    case "printproduct":
                        break;

                    case "renderpostdata":
                        strOut = RenderPostData(context);
                        break;

                    case "getsettings":
                        strOut = GetSettings(context);
                        break;

                    case "savesettings":
                        if (NBrightBuyUtils.CheckRights())
                        {
                            strOut = SaveSettings(context);
                        }
                        break;

                    case "updateprofile":
                        strOut = UpdateProfile(context);
                        break;

                    case "dosearch":
                        strOut = DoSearch(context);
                        break;

                    case "resetsearch":
                        strOut = ResetSearch(context);
                        break;

                    case "orderby":
                        strOut = DoOrderBy(context);
                        break;

                    case "renderthemefolders":
                        strOut = RenderThemeFolders(context);
                        break;
                    }
                }

                if (strOut == "** No Action **")
                {
                    var pluginData = new PluginData(PortalSettings.Current.PortalId);
                    var provList   = pluginData.GetAjaxProviders();
                    foreach (var d in provList)
                    {
                        if (paramCmd.ToLower().StartsWith(d.Key.ToLower() + "_") || paramCmd.ToLower().StartsWith("cmd" + d.Key.ToLower() + "_"))
                        {
                            var ajaxprov = AjaxInterface.Instance(d.Key);
                            if (ajaxprov != null)
                            {
                                strOut = ajaxprov.ProcessCommand(paramCmd, context, _editlang);
                            }
                        }
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                strOut = ex.ToString();
                Logging.LogException(ex);
                //Exceptions.LogException(ex);
            }


            #region "return results"

            //send back xml as plain text
            context.Response.Clear();
            context.Response.ContentType = "text/plain";
            context.Response.Write(strOut);
            context.Response.End();

            #endregion
        }
Exemplo n.º 4
0
        public void ProcessRequest(HttpContext context)
        {
            #region "Initialize"

            var strOut = "** No Action **";

            var paramCmd       = Utils.RequestQueryStringParam(context, "cmd");
            var itemId         = Utils.RequestQueryStringParam(context, "itemid");
            var ctlType        = Utils.RequestQueryStringParam(context, "ctltype");
            var idXref         = Utils.RequestQueryStringParam(context, "idxref");
            var xpathpdf       = Utils.RequestQueryStringParam(context, "pdf");
            var xpathref       = Utils.RequestQueryStringParam(context, "pdfref");
            var lang           = Utils.RequestQueryStringParam(context, "lang");
            var language       = Utils.RequestQueryStringParam(context, "language");
            var moduleId       = Utils.RequestQueryStringParam(context, "mid");
            var moduleKey      = Utils.RequestQueryStringParam(context, "mkey");
            var parentid       = Utils.RequestQueryStringParam(context, "parentid");
            var entryid        = Utils.RequestQueryStringParam(context, "entryid");
            var entryxid       = Utils.RequestQueryStringParam(context, "entryxid");
            var catid          = Utils.RequestQueryStringParam(context, "catid");
            var catxid         = Utils.RequestQueryStringParam(context, "catxid");
            var templatePrefix = Utils.RequestQueryStringParam(context, "tprefix");
            var value          = Utils.RequestQueryStringParam(context, "value");
            var itemListName   = Utils.RequestQueryStringParam(context, "listname");
            if (itemListName == "")
            {
                itemListName = "ItemList";
            }
            if (itemListName == "*")
            {
                itemListName = "ItemList";
            }

            #region "setup language"

            // because we are using a webservice the system current thread culture might not be set correctly,
            NBrightBuyUtils.SetContextLangauge(context);
            var ajaxInfo = NBrightBuyUtils.GetAjaxFields(context);
            _editlang = NBrightBuyUtils.GetEditLang(ajaxInfo, Utils.GetCurrentCulture());

            #endregion

            Logging.Debug($"XmlConnector called with: paramCmd='{paramCmd}', itemId='{itemId}', itemListName='{itemListName}'");

            #endregion

            try
            {
                #region "Do processing of command"

                if (paramCmd.StartsWith("client."))
                {
                    strOut = ClientFunctions.ProcessCommand(paramCmd, context);
                }
                else if (paramCmd.StartsWith("orderadmin_"))
                {
                    strOut = OrderFunctions.ProcessCommand(paramCmd, context);
                }
                else if (paramCmd.StartsWith("payment_"))
                {
                    strOut = PaymentFunctions.ProcessCommand(paramCmd, context);
                }
                else if (paramCmd.StartsWith("product_"))
                {
                    var productFunctions = new ProductFunctions();
                    strOut = productFunctions.ProcessCommand(paramCmd, context, _editlang);
                }
                else if (paramCmd.StartsWith("category_"))
                {
                    var categoryFunctions = new CategoryFunctions();
                    strOut = categoryFunctions.ProcessCommand(paramCmd, context, _editlang);
                }
                else if (paramCmd.StartsWith("property_"))
                {
                    var propertyFunctions = new PropertyFunctions();
                    strOut = propertyFunctions.ProcessCommand(paramCmd, context, _editlang);
                }
                else if (paramCmd.StartsWith("itemlist_"))
                {
                    strOut = ItemListsFunctions.ProcessCommand(paramCmd, context);
                }
                else if (paramCmd.StartsWith("addressadmin_"))
                {
                    strOut = AddressAdminFunctions.ProcessCommand(paramCmd, context);
                }
                else if (paramCmd.StartsWith("plugins_"))
                {
                    strOut = PluginFunctions.ProcessCommand(paramCmd, context);
                }
                else if (paramCmd.StartsWith("cart_"))
                {
                    strOut = CartFunctions.ProcessCommand(paramCmd, context);
                }
                else
                {
                    switch (paramCmd)
                    {
                    case "test":
                        strOut = "<root>" + UserController.Instance.GetCurrentUserInfo().Username + "</root>";
                        break;

                    case "setdata":
                        break;

                    case "deldata":
                        break;

                    case "getdata":
                        strOut = GetReturnData(context);
                        break;

                    case "fileupload":
                        if (NBrightBuyUtils.CheckRights())
                        {
                            strOut = FileUpload(context);
                        }
                        break;

                    case "fileclientupload":
                        if (StoreSettings.Current.GetBool("allowupload"))
                        {
                            strOut = FileUpload(context, itemId);
                        }
                        break;

                    case "docdownload":
                        strOut = DownloadSystemFile(paramCmd, context);
                        break;

                    case "printproduct":
                        break;

                    case "renderpostdata":
                        strOut = RenderPostData(context);
                        break;

                    case "getsettings":
                        strOut = GetSettings(context);
                        break;

                    case "savesettings":
                        if (NBrightBuyUtils.CheckRights())
                        {
                            strOut = SaveSettings(context);
                        }
                        break;

                    case "updateprofile":
                        strOut = UpdateProfile(context);
                        break;

                    case "dosearch":
                        strOut = DoSearch(context);
                        break;

                    case "resetsearch":
                        strOut = ResetSearch(context);
                        break;

                    case "orderby":
                        strOut = DoOrderBy(context);
                        break;

                    case "renderthemefolders":
                        strOut = RenderThemeFolders(context);
                        break;
                    }
                }

                if (strOut == "** No Action **")
                {
                    var ajaxprovider = ajaxInfo.GetXmlProperty("genxml/hidden/ajaxprovider");
                    if (ajaxprovider == "")
                    {
                        ajaxprovider = Utils.RequestQueryStringParam(context, "ajaxprovider");
                    }

                    var pluginData = new PluginData(PortalSettings.Current.PortalId);
                    var provList   = pluginData.GetAjaxProviders();
                    if (ajaxprovider != "")
                    {
                        strOut = "Ajax Provider not found: " + ajaxprovider;
                        if (provList.ContainsKey(ajaxprovider))
                        {
                            var ajaxprov = AjaxInterface.Instance(ajaxprovider);
                            if (ajaxprov != null)
                            {
                                strOut = ajaxprov.ProcessCommand(paramCmd, context, _editlang);
                            }
                        }
                    }
                    else
                    {
                        foreach (var d in provList)
                        {
                            if (paramCmd.ToLower().StartsWith(d.Key.ToLower() + "_") || paramCmd.ToLower().StartsWith("cmd" + d.Key.ToLower() + "_"))
                            {
                                var ajaxprov = AjaxInterface.Instance(d.Key);
                                if (ajaxprov != null)
                                {
                                    strOut = ajaxprov.ProcessCommand(paramCmd, context, _editlang);
                                }
                            }
                        }
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                strOut = ex.ToString();
                Logging.LogException(ex);
                //Exceptions.LogException(ex);
            }


            #region "return results"

            //send back xml as plain text
            context.Response.Clear();
            context.Response.ContentType = "text/plain";
            context.Response.Write(strOut);
            context.Response.End();

            #endregion
        }
 public void Init()
 {
     _logger         = new Mock <ILogger <OrderFunctions> >();
     _orderService   = new Mock <IOrderService>();
     _orderFunctions = new OrderFunctions(_orderService.Object, _logger.Object);
 }
Exemplo n.º 6
0
 public OrderTests()
 {
     orderFunctions = new OrderFunctions(null, iOrderFunctions.Object, iProductFunctions.Object, iStockFunctions.Object, iStock.Object);
 }
        ///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>&nbsp;</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>&nbsp;</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);
            }