protected void btnContinue_Click(object sender, EventArgs e) { //STEP 1 //Insert into pnd_SavedAddressedSelections table (ValMap-DEV)- return ReferenceID via Stored Procedure //STEP 2 //Insert into pnd_CustomerDistribution table (Redesign db) with ReferenceID and return DistributionID //STEP 3 //Insert into pnd_SavedAddressedListFilters table //STEP 4 //Set cookie to store DistributionID string referenceID = CreateDistribution(); int distributionID = 0; //Something went wrong inserting the SavedAddressedSelection if (String.IsNullOrEmpty(referenceID)) { pnlFilterData.Visible = false; pnlError.Visible = true; litErrorMessage.Text = "We're sorry but something went wrong while saving your selection. Our IT Staff has been notified and you will be contacted very shortly about this error."; EmailUtility.SendAdminEmail("Error in CreateDistribution on BuildList page."); pnlSysError.Visible = true; litSysError.Text = "Error - No reference ID was returned."; } //STEP 1 - insert into Map Server went OK else { pnlFilterData.Visible = true; pnlError.Visible = false; //STEP 2 distributionID = SaveCustomerDistribution(referenceID); //STEP 3 SaveCustomerFilterSelections(distributionID); //Something went wrong with saving the customer selection. if (distributionID == 0) { pnlFilterData.Visible = false; pnlError.Visible = true; litErrorMessage.Text = "We're sorry but something went wrong while saving your selection. Our IT Staff has been notified and you will be contacted very shortly about this error."; EmailUtility.SendAdminEmail("Error in SaveCustomerSelection on BuildList page."); pnlSysError.Visible = true; litSysError.Text = "Error - No Distribution ID was returned."; } //All is good. Let's go! else { //Delete any existing cookies. if (Request.Cookies["TaradelDistributionID"] != null) { HttpCookie taradelDistIDCookie = new HttpCookie("TaradelDistributionID"); taradelDistIDCookie.Expires = DateTime.Now.AddDays(-1d); Response.Cookies.Add(taradelDistIDCookie); } //Set NEW cookie. Will expire in 20 minutes. HttpCookie newTaradelDistIDCookie = new HttpCookie("TaradelDistributionID"); newTaradelDistIDCookie.Expires = DateTime.Now.AddMinutes(20); newTaradelDistIDCookie.Value = distributionID.ToString(); Response.Cookies.Add(newTaradelDistIDCookie); //End ================= Response.Redirect("~/Step1-TargetReview.aspx?distid=" + distributionID); } } }
private void CreateCart() { //======================================================================================================================================== // USelectID type 1. // Cart Build Steps: // 1) EDDM Product // a) Build the Xml Document. Load <cart /> parent node. // b) Begin building Product Node components // 1) Build Options SortedList (Int, Int) // 2) Build OptionCategories List (of ProductOptionCategory) // 3) Build PriceMatrix // c) Get PrintMethodID // d) Loop through OptionCategories, add to Options as needed. // e) Get the product options from the Selected Product. Get the OptCatID. // f) Build the Quote object // g) Set variables returned from Quote Object. // h) Finally, insert the Product Node into the Cart // 2) EDDM Attribute Nodes // 3) EDDM OrderCalc Node // 4) EDDM Drops Node // 5) EDDM Indiv Drop Nodes w/ nested Area Nodes // 6) EDDM Design Node // 7) EDDM SHIPMENTS Node and w/ nested Shipment node(s) //======================================================================================================================================== //DEFINE ALL THE VARIABLES TaradelReceiptUtility.OrderCalculator eddmObjCalc = new TaradelReceiptUtility.OrderCalculator(); StringBuilder methodVars = new StringBuilder(); //Customer data. Needed below in multiple nodes. Taradel.Customer oCust = Taradel.CustomerDataSource.GetCustomer(User.Identity.Name); string eddmGUID = System.Guid.NewGuid().ToString(); string jobName = "OLB Campaign for " + RetrieveFromSession(TaradelSession.Location) + "-" + DateTime.Today.ToShortDateString(); string sCustomField1 = appxCMS.Util.CMSSettings.GetSetting("Job", "JobDescription1"); string sCustomField2 = appxCMS.Util.CMSSettings.GetSetting("Job", "JobDescription2"); string sCustomField3 = appxCMS.Util.CMSSettings.GetSetting("Job", "JobDescription3"); string designType = "template"; //'possible choices: 'my', 'template', 'pro' string deliveryAddressID = "0"; //Ship To Address ID string comments = ""; //also comes from JobComments.Text on normal pages string mailAllPiecesAtOnce = "yes"; //Normally comes from ddlDrops.SelectedValue. Yes/No, True/False DateTime startingDate = DateTime.Parse(RetrieveFromSession(TaradelSession.StartDate)); //Normally comes from (txtLaunchWeek.Text). User selected start of 'Launch Week' string zip = "23060"; //Normally ZipCode.Text. User Ship To Zip Code. //Prices decimal price = 0; //Stores calculated total price from Quote Obj. (total mailed x price per piece) decimal taxablePrice = 0; //Currently same as eddmPrice / eddmQuoteObj.Price decimal pricePerPiece = 0; //Stores EDDM Price Per Piece from Quote Obj. //Fees / Rates decimal postageFee = 0; //Fee for postage. (totalMailQty * postageRate) double dropFee = 0; //Fee for extra drop. Ex $99 double dropPrice = 0; //Fee for additional drops. Ex $99 x number of drops. decimal postageRate = 0; //Postage Rate //Product attributes decimal weight = 0; //Comes from Base Product Obj decimal WeightPerPage = 0; //Used for Shipments Node. (Weight * PageCount) / EDDMSelected //various quantities int holdQTY = 0; //Obsolete concept. In place just to be safe. AKA 'iHoldQty' Does not apply to OLB. int extraCopies = 00; //AKA 'iShipQty'. Comes from user. Does not apply to OLB. int printQTY = 0; //AKA 'iPrintQty'. (totalSelected + holdQTY + extraCopies) //Campaign variables int numDrops = 1; //Num of drops. AKA iDrops. Default to 1 for OLB. int sendThisNumberOfDrops = 0; //Adjusted # of Drops to send to oPriceQuote. Work Around. //int iFrequency = 0; //Every X of weeks - selected in DropDownList. Now stored as Page Property //Distribution variables bool useBusinesses = true; //Flag to use Businesses in distribution. bool usePOBoxes = true; //Flag to use PO Boxes in distribution. bool useResidential = true; //Flag to use Residentials in distribution. int daysToAdd = 1; //Used to logically find next drop date. AKA 'weekInterval' int totalDropSelections = 0; //Used as a running total to store total 'matches' in the EDDM DataTable int totalAreaSelections = 0; //Quote params bool isFlatRateShipping = false; //Set by Quote Obj. decimal flatRateFee = 0; //Comes from QuoteObj.ShipPrice. int flatRateShipQTY = 1000; //Hard coded to 1000. //Get Design Type. Set flags bool bProDesign = false; if (designType == "pro") { bProDesign = true; } //In OLB Environment, Template will ALWAYS be the design type. Normally, designType is set by DropDownList on page. bool bTemplateDesign = false; if (designType == "template") { bTemplateDesign = true; } //Postage Rate postageRate = appxCMS.Util.AppSettings.GetDecimal("USPSPostageRate"); if (postageRate <= 0) { postageRate = 0.16M; } //Calculate Stuff / Assign more stuff printQTY = CalculatePrintQTY(totalSelected, holdQTY, extraCopies); //daysToAdd = (7 * frequency); //Multiple Impressions Logic //If is Multiple Impressions, change the number of drops to match the number of impressions if (numImpressions == 1) { eddmObjCalc.IsThisAMultiple = false; eddmObjCalc.NumOfDrops = numDrops; eddmObjCalc.MailPieces = totalSelected; //Should always be Yes for OLB if (mailAllPiecesAtOnce.ToLower() == "yes") { eddmObjCalc.NumOfDrops = 1; numDrops = 1; } } else { eddmObjCalc.IsThisAMultiple = true; eddmObjCalc.NumOfDrops = numImpressions; eddmObjCalc.MailPieces = (totalSelected * numImpressions); } //The PriceQuote Obj ADDS on the drop fees based on the number of drops since we are NOT charging for Multiple //Impressions on SOME sites set the number of drops to 1 for these sites. sendThisNumberOfDrops = eddmObjCalc.NumOfDrops; if (multipleImpressionsNoFee) { sendThisNumberOfDrops = 1; } if (numDrops == 0) { numDrops = 1; } //1) PRODUCT NODE //a) Build the Xml Document. Load <cart /> parent node. XmlDocument oXML = new XmlDocument(); oXML.LoadXml("<cart />"); //Find and define 'the cart'. Doesn't yet exist in Profile. XmlNode oCart = oXML.SelectSingleNode("/cart"); //b) Begin building Product Node components //1) Build Options SortedList (Int, Int) SortedList <int, int> productOptions; productOptions = new SortedList <int, int>(); //2) Build OptionCategories List (of ProductOptionCategory) List <Taradel.ProductOptionCategory> oOptCats = Taradel.ProductDataSource.GetProductOptionCategories(baseProductID); //oPriceMatrix //3) Build PriceMatrix Taradel.PriceMatrix oPriceMatrix = Taradel.ProductDataSource.GetPriceRange(baseProductID, totalSelected); if (oPriceMatrix != null) { //c) Get PrintMethodID printMethodID = oPriceMatrix.PrintMethod.PrintMethodId; //d) Loop through OptionCategories, add to Options as needed. foreach (Taradel.ProductOptionCategory oOptCat in oOptCats) { IEnumerable <Taradel.ProductOption> oOpts = default(IEnumerable <Taradel.ProductOption>); oOpts = oOptCat.Options.Where((Taradel.ProductOption po) => po.ProductPrintMethodOptions.Any((ppmo => ppmo.PrintMethodReference.ForeignKey() == printMethodID))); if (oOpts.Count() > 0) { productOptions.Add(oOptCat.OptCatID, 0); } } } else { pnlNormal.Visible = false; pnlError.Visible = true; litErrorMessage.Text = "Uh Oh! Don't worry but something went wrong. Our IT Staff has been notified and you will be contacted very shortly about this error."; EmailUtility.SendAdminEmail("oPriceMatrix IS Null. (TargetDataMap3.aspx)"); } //e) Get the product options from the Selected Product. Get the OptCatID. ???? Already done?? Taradel.ProductPriceQuote oPriceQuote = new Taradel.ProductPriceQuote(siteID, baseProductID, totalMailed, holdQTY, extraCopies, distributionID, sendThisNumberOfDrops, productOptions, oCust.ZipCode, bProDesign, bTemplateDesign, 0, "percent"); //f) Build the Quote object //For Each oOpt As Taradel.PMOptionInfo In oPriceQuote.SelectedOptions foreach (Taradel.PMOptionInfo oOpt in oPriceQuote.SelectedOptions) { double dOptMarkup = 0; Boolean bPercent = false; if (oOpt.PriceMatrixOptionMarkup != null) { dOptMarkup = oOpt.BasePrice; bPercent = oOpt.BaseMarkupPercent; } } //g) Set variables returned from Quote Object. //Set Proper Weight, Price, Taxable Price, etc. These values and variables are needed/used later in the code. pricePerPiece = oPriceQuote.PricePerPiece; weight = oPriceQuote.Weight; price = oPriceQuote.Price; taxablePrice = CalculateTaxPrice(price, postageRate, totalMailed); isFlatRateShipping = oPriceQuote.IsFlatRateShipping; flatRateFee = oPriceQuote.ShipPrice; postageFee = (totalMailed * postageRate); dropFee = CalculateMultipleImpressionDropFee(eddmObjCalc.NumOfDrops, dropPrice); //Set Design Fee Attribute. Store 0 unless Pro was selected. if (designType.ToLower() != "pro") { designFee = 0; } //h) Finally, insert the Product Node into the Cart //ADD THE EDDM PRODUCT NODE oCart = (CartUtility.AddProduct(oCart, DateTime.Now.ToString(), baseProductID.ToString(), designFee.ToString(), distributionID.ToString(), flatRateFee.ToString(), flatRateShipQTY.ToString(), eddmGUID, isFlatRateShipping.ToString(), comments, jobName, productName, paperHeight.ToString(), paperWidth.ToString(), postageFee.ToString(), price.ToString(), pricePerPiece.ToString(), productID.ToString(), totalMailed.ToString(), siteID.ToString(), productSKU.ToString(), taxablePrice.ToString(), "EDDM", weight.ToString())); //2) EDDM Attribute Nodes foreach (Taradel.PMOptionInfo oOpt in oPriceQuote.SelectedOptions) { double dOptMarkup = 0; Boolean bPercent = false; if (oOpt.PriceMatrixOptionMarkup != null) { dOptMarkup = oOpt.BasePrice; bPercent = oOpt.BaseMarkupPercent; } oCart = (CartUtility.AddAttribute(oCart, "EDDM", oOpt.OptCatName, oOpt.OptCatId.ToString(), oOpt.OptionId.ToString(), oOpt.OptName, dOptMarkup.ToString(), bPercent.ToString(), oOpt.Weight.Value.ToString())); } //Professional Service Attribute if (designType == "pro") { oCart = (CartUtility.AddAttribute(oCart, "EDDM", "Professional Design Services", "0", "1", paperWidth + "x" + paperHeight + " (" + designFee.ToString("C") + ")", designFee.ToString(), "False", "0")); } //Postage Fee Attribute oCart = (CartUtility.AddAttribute(oCart, "EDDM", "Postage Fee", "0", postageFee.ToString(), eddmObjCalc.MailPieces.ToString("N0") + " pieces (" + postageFee.ToString("C") + ")", postageFee.ToString(), "False", "0")); //Number of Drops Attribute string dropLabel = ""; if (numImpressions == 1) { dropLabel = " drop"; } else { dropLabel = " drops"; } oCart = (CartUtility.AddAttribute(oCart, "EDDM", "Number of Drops", "0", eddmObjCalc.NumOfDrops.ToString(), (numImpressions.ToString() + dropLabel + " (" + extraDropFee.ToString("C") + ")"), dropFee.ToString(), "False", "0")); //Drop Schedule Attribute oCart = (CartUtility.AddAttribute(oCart, "EDDM", "Drop Schedule", "0", "every " + frequency.ToString() + " weeks", frequency.ToString() + " weeks", "0", "False", "0")); //3) EDDM ORDER CALC NODE oCart = (CartUtility.AddOrderCalc(oCart, "EDDM", "0", "0", oCust.State, "", "0", "0", "0", "0", "0")); //4) EDDM DROPS NODE //oDist Taradel.CustomerDistribution oDist = Taradel.CustomerDistributions.GetDistribution(distributionID); //oUselect Taradel.USelectProductConfiguration oUSelect = Taradel.Helper.USelect.GetProduct(oDist.USelectMethodReference.ForeignKey(), baseProductID); //oSummary obj Taradel.MapServer.UserData.SelectionSummary oSummary = Taradel.CustomerDistributions.GetSelectionSummary(oDist.ReferenceId); //oSelects List <Taradel.MapServer.UserData.AreaSelection> oSelects = Taradel.CustomerDistributions.GetSelections(oDist.ReferenceId); if (oSummary != null) { useBusinesses = oSummary.UseBusiness; usePOBoxes = oSummary.UsePOBox; } oCart = (CartUtility.AddDrops(oCart, "EDDM", oCust.Company, oCust.Address1, oCust.Address2, oCust.City, oCust.State, oCust.ZipCode, "", "", useResidential.ToString(), useBusinesses.ToString(), usePOBoxes.ToString())); //5) EDDM INDIV DROPS w/ Area Nodes int dropBreak = totalSelected / numImpressions; bool bOnePer = false; DateTime dropDate = startingDate; //Multiple impressions if (numImpressions > 1) { //this is a muliple - so divide back out the tempObjCalc.MailPieces for each drop eddmObjCalc.MailPieces = eddmObjCalc.MailPieces / eddmObjCalc.NumOfDrops; dropBreak = eddmObjCalc.MailPieces; bOnePer = false; //Loop through the drops for (int dropNumber = 1; dropNumber <= numImpressions; dropNumber++) { daysToAdd = ((dropNumber - 1) * (frequency * 7)); dropDate = startingDate.AddDays(daysToAdd); //Find Prev Friday DateTime prevFridayDropDate = dropDate; while (prevFridayDropDate.DayOfWeek != DayOfWeek.Friday) { prevFridayDropDate = prevFridayDropDate.AddDays(-1); } //added 2/19/2016 dropDate = prevFridayDropDate; //end added 2/19/2016 //Add the Drop Nodes oCart = CartUtility.AddIndividualDrop(oCart, "EDDM", dropNumber.ToString(), totalMailed.ToString(), dropDate.ToShortDateString(), true, eddmObjCalc.NumOfDrops.ToString()); Response.Write("totalMailed" + totalMailed.ToString() + "<br />"); Response.Write("totalSelected" + totalSelected.ToString() + "<br />"); //new --> rs 1/14/2016 //CartUtility.AddIndividualDrop(oCart, "EDDM", dropNumber.ToString(), eddmObjCalc.MailPieces.ToString(), dropDate.ToShortDateString(), true, eddmObjCalc.NumOfDrops.ToString()); //end the new //Loop Thru Areas foreach (Taradel.MapServer.UserData.AreaSelection oSelect in oSelects) { try { totalAreaSelections = oSelect.Residential; if (useBusinesses) { totalAreaSelections = totalAreaSelections + oSelect.Business; } if (usePOBoxes) { totalAreaSelections = totalAreaSelections + oSelect.POBoxes; } //Add each Area Node oCart = CartUtility.AddIndividualArea(oCart, "EDDM", dropNumber.ToString(), oSelect.Name, oSelect.FriendlyName, totalAreaSelections.ToString()); totalDropSelections = totalDropSelections + totalAreaSelections; } catch (Exception ex) { } } //Update total attribute with new value oCart = CartUtility.UpdateDropCount(oCart, "EDDM", dropNumber.ToString(), totalDropSelections.ToString()); //reset totalDropSelections = 0; } } //single impression else { dropBreak = totalSelected / numImpressions; //oSelects.Count = # of Routes //If number of drops is the same as number as the number of routes AND is more than one. if (numImpressions == oSelects.Count && numImpressions > 1) { bOnePer = true; } for (int dropNumber = 1; dropNumber == numImpressions; dropNumber++) { DateTime prevFridayDropDate = startingDate; //Find the previous Friday while (prevFridayDropDate.DayOfWeek != DayOfWeek.Friday) { prevFridayDropDate = prevFridayDropDate.AddDays(-1); } //Add the Drop Nodes oCart = CartUtility.AddIndividualDrop(oCart, "EDDM", dropNumber.ToString(), totalMailed.ToString(), dropDate.ToShortDateString(), false, eddmObjCalc.NumOfDrops.ToString()); //Loop Thru Areas foreach (Taradel.MapServer.UserData.AreaSelection oSelect in oSelects) { try { totalAreaSelections = oSelect.Residential; if (useBusinesses) { totalAreaSelections = totalAreaSelections + oSelect.Business; } if (usePOBoxes) { totalAreaSelections = totalAreaSelections + oSelect.POBoxes; } //Add each Area Node oCart = CartUtility.AddIndividualArea(oCart, "EDDM", dropNumber.ToString(), oSelect.Name, oSelect.FriendlyName, totalAreaSelections.ToString()); totalDropSelections = totalDropSelections + totalAreaSelections; } catch (Exception ex) { } } //Update total attribute with new value oCart = CartUtility.UpdateDropCount(oCart, "EDDM", dropNumber.ToString(), totalDropSelections.ToString()); //reset totalDropSelections = 0; } } //6) EDDM DESIGN NODE //Upload and Save the file first and then ...update the cart. string sClientBase = Taradel.WLUtil.GetRelativeSiteImagesPath() + "/UserImages"; string frontAction = ""; string frontFileName = ""; string frontFileExt = ""; long frontFileSize = 0; string frontTmpName = ""; string frontRealFileName = ""; string backAction = ""; string backFileName = ""; string backFileExt = ""; long backFileSize = 0; string backTmpName = ""; string backRealFileName = ""; bool hasBackDesign = false; string artKey = ""; string requiresProof = ""; if (!Directory.Exists(Server.MapPath(sClientBase))) { Directory.CreateDirectory(Server.MapPath(sClientBase)); } string sClientFolder = sClientBase + "/" + Profile.UserName.Replace("@", "_"); string sClientPath = Server.MapPath(sClientFolder); DirectoryInfo oDir = new DirectoryInfo(sClientPath); if (!oDir.Exists) { oDir.Create(); } switch (designType.ToLower()) { case "my": //logic ommitted because OLB always uses a Template break; case "template": artKey = hidSelectedTemplateID.Value; break; } //Add Design Node oCart = (CartUtility.AddDesign(oCart, "EDDM", designType, frontFileExt, frontFileName, frontRealFileName, frontAction, hasBackDesign, backFileExt, backFileName, backRealFileName, backAction, artKey, requiresProof)); //7) EDDM SHIPMENTS NODE WeightPerPage = ((weight * pageCount) / totalSelected); if (extraCopies > 0) { if (deliveryAddressID == "0") { //Create a new address and get the ID string sMsg = ""; int iAddr = Taradel.CustomerAddressDataSource.NewAddress(oCust.CustomerID, "", "", "", "", oCust.Address1.ToString(), oCust.Address2.ToString(), oCust.City.ToString(), oCust.State.ToString(), oCust.ZipCode.ToString(), ref sMsg); if (iAddr > 0) { deliveryAddressID = iAddr.ToString(); } } } oCart = (CartUtility.AddShipments(oCart, "EDDM", deliveryAddressID.ToString(), extraCopies.ToString(), weight.ToString(), pageCount.ToString(), paperWidth.ToString(), paperHeight.ToString(), flatRateFee.ToString("N2"), oCust.ZipCode, totalMailed)); Profile.Cart = oXML; Profile.Save(); }