PageRenderTime 31ms CodeModel.GetById 3ms app.highlight 22ms RepoModel.GetById 2ms app.codeStats 0ms

/FACT.Web/Business/ControllerFunctions.cs

https://bitbucket.org/gsilves/fact
C# | 357 lines | 345 code | 11 blank | 1 comment | 74 complexity | b5ebc65d5150cba349ae218f0e7117f7 MD5 | raw file
  1using AuthorizeNet.Api.Contracts.V1;
  2using FACT.Domain.Models;
  3using FACT.Domain.Models.Controllers;
  4using FACT.Domain.Models.EntityModels;
  5using FACT.Domain.Models.MiscModels;
  6using FACT.Service;
  7using FACT.Web.Models;
  8using FACT.Web.Services;
  9using Newtonsoft.Json;
 10using Newtonsoft.Json.Linq;
 11using System;
 12using System.Collections.Generic;
 13using System.Configuration;
 14using System.Linq;
 15using System.Text;
 16using System.Web;
 17using System.Web.Mvc;
 18using System.Web.UI.WebControls;
 19using System.Xml;
 20using System.Xml.Linq;
 21
 22namespace FACT.Web.Business
 23{
 24    public static class ControllerFunctions
 25    {
 26        private static AuthorizeNetService aNetApi = new AuthorizeNetService();
 27        private static int intCSVLimit = 500;
 28        private static int intContactLimit = 500;
 29
 30        public static List<MyCampaignsModel> GetMyCampaigns(Profiles advisor, IFactMainService _factMainService)
 31        {
 32            List<MyCampaignsModel> listOfMyCampaignModels = new List<MyCampaignsModel>();
 33            AmazonS3Service awsService = new AmazonS3Service();
 34            MamlFunctions mamlController = new MamlFunctions();
 35            List<Campaigns> savedCampaigns = _factMainService.FindAllCampaigns().Where(p => p.UserId == advisor.UserId && p.Status == "Saved").ToList();
 36            foreach (var s in savedCampaigns)
 37            {
 38                AmazonResponse ar = awsService.DownloadMaml(s.CampaignFileURL);
 39                if (ar.Successful)
 40                {
 41                    string mamlXML = ar.Message;
 42                    MyCampaignsModel myCampaignsModel = new MyCampaignsModel();
 43                    myCampaignsModel.Status = "";
 44                    myCampaignsModel.DbStatus = s.Status;
 45                    myCampaignsModel.CampaignName = s.CampaignName;
 46                    myCampaignsModel.DateSubmitted = s.DateSubmitted;
 47                    myCampaignsModel.Maml = mamlXML;
 48                    myCampaignsModel.Program = mamlController.FromMAMLString(mamlXML);
 49                    myCampaignsModel.CreatorName = advisor.FirstName + " " + advisor.LastName;
 50                    myCampaignsModel.Url = s.CampaignFileURL;
 51                    listOfMyCampaignModels.Add(myCampaignsModel);
 52                }
 53            }
 54            byte[] progCallData =
 55                Encoding.UTF8.GetBytes(@"{""Credentials"":{""IsEncrypted"":false,""PartnerPassword"":"""",""PartnerTicket"":""" + advisor.MFMasterPartnerTicket + @""",""Ticket"":""" +
 56                advisor.MFTicket + @""",""UserPassword"":""" + advisor.GetMFPassword(Convert.ToBoolean(ConfigurationManager.AppSettings["MFPasswordMODAct"])) +
 57                @"""},""SearchString"":"""",""MaxRows"":500,""SortExpression"":"""",""StartRowIndex"":0,""State"":255}");
 58            JObject progResultPost = JObject.FromObject(GlobalFunctions.ProcessJSONHTTPRequest("https://studio.mdl.io/REST/programservice/GetProgramList", progCallData,
 59                                                                                             "application/json", "POST", "", ""));
 60            if (progResultPost["Result"]["ErrorMessage"].ToString() != "")
 61            {
 62            }
 63            else
 64            {
 65                for (int i = 0; i <= progResultPost["ProgramList"].Count() - 1; i++)
 66                {
 67                    string creatorId = progResultPost["ProgramList"][i]["CreatorID"].ToString();
 68                    if (creatorId == advisor.MFUserID)
 69                    {
 70                        string pName = progResultPost["ProgramList"][i]["ProgramName"].ToString();
 71                        try
 72                        {
 73                            Campaigns dbCampaign = _factMainService.FindAllCampaigns().Where(x => x.CampaignName == pName && x.UserId == advisor.UserId).First();
 74                            if (dbCampaign != null)
 75                            {
 76                                if (dbCampaign.Status == "Saved")
 77                                {
 78                                    foreach (MyCampaignsModel savedCampaign in listOfMyCampaignModels)
 79                                    {
 80                                        if (savedCampaign.CampaignName == pName)
 81                                        {
 82                                            savedCampaign.CreatorName = progResultPost["ProgramList"][i]["CreatorName"].ToString();
 83                                            savedCampaign.Id = Convert.ToInt32(progResultPost["ProgramList"][i]["ProgramID"].ToString());
 84                                            savedCampaign.CampaignName = progResultPost["ProgramList"][i]["ProgramName"].ToString();
 85                                            savedCampaign.Status = progResultPost["ProgramList"][i]["StateName"].ToString();
 86                                            savedCampaign.State = Convert.ToInt32(progResultPost["ProgramList"][i]["State"]);
 87                                            savedCampaign.DateSubmitted = Convert.ToDateTime(progResultPost["ProgramList"][i]["PublishDate"].ToString());
 88                                            break;
 89                                        }
 90                                    }
 91                                }
 92                                else
 93                                {
 94                                    MyCampaignsModel myCampaignsModel = new MyCampaignsModel();
 95                                    myCampaignsModel.CreatorName = progResultPost["ProgramList"][i]["CreatorName"].ToString();
 96                                    myCampaignsModel.Id = Convert.ToInt32(progResultPost["ProgramList"][i]["ProgramID"].ToString());
 97                                    myCampaignsModel.CampaignName = progResultPost["ProgramList"][i]["ProgramName"].ToString();
 98                                    myCampaignsModel.Status = progResultPost["ProgramList"][i]["StateName"].ToString();
 99                                    myCampaignsModel.State = Convert.ToInt32(progResultPost["ProgramList"][i]["State"].ToString());
100                                    myCampaignsModel.DateSubmitted = Convert.ToDateTime(progResultPost["ProgramList"][i]["PublishDate"].ToString());
101                                    myCampaignsModel.Maml = dbCampaign.CampaignFileURL;
102                                    myCampaignsModel.Token = dbCampaign.ApprovalToken;
103                                    myCampaignsModel.DbStatus = dbCampaign.Status;
104                                    listOfMyCampaignModels.Add(myCampaignsModel);
105                                }
106                            }
107                        }
108                        catch (Exception)
109                        {
110                        }
111                    }
112                }
113            }
114            return listOfMyCampaignModels.OrderByDescending(x => x.DateSubmitted).ToList();
115        }
116
117        public static string generateDisclosure(Profiles profile, IFactMainService _factMainService)
118        {
119            string res = "";
120            Disclosures objDisclosure = _factMainService.FindAllDisclosures().SingleOrDefault(p => p.UserType == profile.UserType && p.IAType == profile.IAType);
121            if (objDisclosure != null)
122            {
123                if (objDisclosure.isVariable)
124                {
125                    objDisclosure.DisclosureText = objDisclosure.DisclosureText.Replace("[INSERT RIA NAME HERE]", profile.ApprovedRIAName).Replace("[FSC/RAA/SPF/WFS]", profile.BDID);
126                }
127                res = objDisclosure.DisclosureText;
128            }
129            else
130            {
131                res = "No disclosure text!";
132            }
133            return res;
134        }
135
136        public static void StopAllCampaigns(long userId, IFactMainService _factMainService)
137        {
138            Profiles Profile = _factMainService.FindProfileById(userId);
139            MindfireFunctions objMF = new MindfireFunctions();
140            objMF.AuthenticateAccount(Profile.Email, Profile.GetMFPassword(Convert.ToBoolean(ConfigurationManager.AppSettings["MFPasswordMODAct"])), ref Profile);
141            byte[] progCallData = Encoding.UTF8.GetBytes(@"{""Credentials"":{""IsEncrypted"":false,""PartnerPassword"":"""",""PartnerTicket"":""" + Profile.MFMasterPartnerTicket +
142                @""",""Ticket"":""" + Profile.MFTicket + @""",""UserPassword"":""" + Profile.GetMFPassword(Convert.ToBoolean(ConfigurationManager.AppSettings["MFPasswordMODAct"])) +
143                @"""},""SearchString"":"""",""MaxRows"":500,""SortExpression"":"""",""StartRowIndex"":0,""State"":255}");
144            JObject progResultPost = JObject.FromObject(GlobalFunctions.ProcessJSONHTTPRequest("https://studio.mdl.io/REST/programservice/GetProgramList", progCallData,
145                "application/json", "POST", "", ""));
146            if (progResultPost["Result"]["ErrorMessage"].ToString() != "")
147            {
148            }
149            else
150            {
151                for (int i = 0; i <= progResultPost["ProgramList"].Count() - 1; i++)
152                {
153                    string creatorId = progResultPost["ProgramList"][i]["CreatorID"].ToString();
154                    if (creatorId == Profile.MFUserID)
155                    {
156                        string pName = progResultPost["ProgramList"][i]["ProgramName"].ToString();
157                        string programID = progResultPost["ProgramList"][i]["ProgramID"].ToString();
158                        byte[] campaignCallData = Encoding.UTF8.GetBytes(@"{""Credentials"":{""IsEncrypted"":false,""PartnerPassword"":"""",""PartnerTicket"":"""",""Ticket"":""" +
159                            Profile.MFTicket + @""",""UserPassword"":""" + Profile.GetMFPassword(Convert.ToBoolean(ConfigurationManager.AppSettings["MFPasswordMODAct"])) +
160                            @"""},""MamlFormat"":0,""ProgramID"":" + programID + "}");
161                        JObject campaignResultPost = JObject.FromObject(GlobalFunctions.ProcessJSONHTTPRequest("https://studio.mdl.io/REST/programservice/CheckoutProgram", campaignCallData,
162                            "application/json", "POST", "", ""));
163                        if (campaignResultPost["Result"]["ErrorMessage"].ToString() != "")
164                        {
165                        }
166                        else
167                        {
168                            string mamlXML = string.Empty;
169                            string byteString = string.Empty;
170                            for (int x = 0; x <= campaignResultPost["Maml"].Count() - 1; x++)
171                            {
172                                mamlXML = mamlXML + (char)(Convert.ToInt32(campaignResultPost["Maml"][x].ToString()));
173                            }
174                            XmlDocument campXML = new XmlDocument();
175                            campXML.LoadXml(mamlXML);
176                            XmlElement rootLoad = campXML.DocumentElement;
177                            Campaigns campaignChangedStatus = _factMainService.FindAllCampaigns().Where(c => c.CampaignName == pName).SingleOrDefault();
178                            if (campaignChangedStatus != null)
179                            {
180                                if (rootLoad.Attributes["State"].Value == "Start")
181                                {
182                                    rootLoad.Attributes["State"].Value = "Stop";
183                                    //*** rootLoad.Item["Campaign"].Attributes["State"].Value = "Stop";
184                                    
185                                }
186                                var encodedData = GlobalFunctions.Convert64(campXML.InnerXml);
187                                for (int x = 0; x <= encodedData.Length - 1; x++)
188                                {
189                                    byteString = byteString + encodedData[x] + ",";
190                                    byteString = byteString + Environment.NewLine;
191                                }
192                                byteString = byteString.Remove(byteString.LastIndexOf(","));
193                                byte[] progCallData2 =
194                                    Encoding.UTF8.GetBytes(@"{""Maml"":[" + byteString +
195                                    @"],""MamlFormat"":0,""CheckoutAfterCheckin"":false,""Comments"":""Edited Campaign"",""Credentials"":{""IsEncrypted"":false,""PartnerPassword"":"""",""PartnerTicket"":"""",""Ticket"":""" +
196                                    Profile.MFTicket + @""",""UserPassword"":""" + Profile.GetMFPassword(Convert.ToBoolean(ConfigurationManager.AppSettings["MFPasswordMODAct"])) + @"""}}");
197                                JObject campaignStopPost = JObject.FromObject(GlobalFunctions.ProcessJSONHTTPRequest("https://studio.mdl.io/REST/programservice/CheckinProgram",
198                                    progCallData2, "application/json", "POST", "", ""));
199                                if (campaignStopPost["Result"]["ErrorMessage"].ToString() != "")
200                                {
201                                }
202                                else
203                                {
204                                    if (campaignChangedStatus != null)
205                                    {
206                                        campaignChangedStatus.Status = "Stop";
207                                        campaignChangedStatus.LaunchDate = DateTime.Now;
208                                        _factMainService.UpdateCampaigns(campaignChangedStatus);
209                                    }
210                                }
211                            }
212                        }
213                    }
214                }
215            }
216        }
217
218        public static bool HasSubscriptions(string authorizeNetId)
219        {
220            if (authorizeNetId == null)
221            {
222                authorizeNetId = "";
223            }
224            getCustomerProfileResponse tmp = aNetApi.GetCustomerProfile(authorizeNetId);
225            List<ARBGetSubscriptionResponse> subscriptions = new List<ARBGetSubscriptionResponse>();
226            if (tmp != null && !(tmp.subscriptionIds == null) && !(tmp.subscriptionIds.Count() == 0))
227            {
228                foreach (var subId in tmp.subscriptionIds)
229                {
230                    subscriptions.Add(aNetApi.GetSubscriptionDetails(subId));
231                }
232            }
233            else
234            {
235                return false;
236            }
237            int countOfActiveSubs = subscriptions.Where(x => x.subscription.status == 0).ToList().Count;
238            return (countOfActiveSubs > 0);
239        }
240
241        public static string decodeBDID(string BDID)
242        {
243            if (BDID.ToUpper().Contains("SAGEPOINT"))
244            {
245                return "SPF";
246            }
247            else if (BDID.ToUpper().Contains("ROYAL"))
248            {
249                return "RAA";
250            }
251            else if (BDID.ToUpper().Contains("FSC SECURITIES"))
252            {
253                return "FSC";
254            }
255            else if (BDID.ToUpper().Contains("WOODBURY"))
256            {
257                return "WFS";
258            }
259            else if (BDID.ToUpper().Contains("ADVISOR GROUP"))
260            {
261                return "AG";
262            }
263            else
264            {
265                return "0";
266            }
267        }
268
269        public static string generatePersonaDisclosure(Personas _persona, Profiles _profile, IFactMainService _factMainService)
270        {
271            string res = "";
272            Disclosures objDisclosure = _factMainService.FindAllDisclosures().SingleOrDefault(p => p.UserType == _profile.UserType && p.IAType == _persona.IAType);
273            if (objDisclosure != null)
274            {
275                if (objDisclosure.isVariable)
276                {
277                    objDisclosure.DisclosureText = objDisclosure.DisclosureText.Replace("[INSERT RIA NAME HERE]", _persona.ApprovedRIAName).Replace("[FSC/RAA/SPF/WFS]", _persona.BDID);
278                }
279                res = objDisclosure.DisclosureText;
280            }
281            else
282            {
283                res = "No disclosure text!";
284            }
285            return res;
286        }
287
288        public static bool IsImage(HttpPostedFileBase file)
289        {
290            return file.ContentType == "image/gif" || file.ContentType == "image/jpeg" || file.ContentType == "image/png";
291        }
292
293        private static SalesForceImportViewModel FillCustomFields(SalesForceImportViewModel sfImports)
294        {
295            sfImports.intCSVLimit = intCSVLimit.ToString();
296            sfImports.intContactLimit = intContactLimit.ToString();
297            var customFields = Enumerable.Empty<CustomFieldAdmin>();
298            try
299            {
300                customFields = ProcessSalesForceServiceRequestAdmin(service => 
301                service.GetCustomFieldsAdmin(SessionManager.SalesForce.Authentication, SoqlDataTable.Contact, SoqlDataTable.Lead));
302            }
303            catch (Exception exception)
304            {
305                Tuple<String, Object[]> extraMessageFormat = MessageHelper.GetCurrentRequestInformationMessageFormat();
306                this.EventLogger.LogError(exception, extraMessageFormat.Item1, extraMessageFormat.Item2);
307            }
308            IEnumerable<ListItem> contactCustomFields = customFields.Where(cf => cf.Table == SoqlDataTable.Contact).Select(cf => new ListItem(cf.Label, cf.Id)).ToArray();
309            IEnumerable<ListItem> leadCustomFields = customFields.Where(cf => cf.Table == SoqlDataTable.Lead).Select(cf => new ListItem(cf.Label, cf.Id).ToArray();
310            var contactOptions = contactCustomFields.Select(purpose => new SelectListItem()
311            {
312                Text = purpose.Text,
313                Value = purpose.Value
314            }).ToList();
315            var leadOptions = leadCustomFields.Select(purpose => new SelectListItem()
316            {
317                Text = purpose.Text,
318                Value = purpose.Value
319            }).ToList();
320            SelectListItem firstCustom = new SelectListItem();
321            firstCustom.Value = "0";
322            firstCustom.Text = "Select Custom Contact";
323            contactOptions.Add(firstCustom);
324            sfImports.CustomFieldsContact = contactOptions;
325            SelectListItem firstLead = new SelectListItem();
326            firstLead.Value = "0";
327            firstLead.Text = "Select Custom Lead";
328            leadOptions.Add(firstLead);
329            sfImports.CustomFieldsLead = leadOptions;
330            sfImports.SelectedContact = "0";
331            sfImports.SelectedLead = "0";
332            return sfImports;
333        }
334
335        private static void ProcessSalesForceServiceRequestAdmin<TResult>(Func<SFServiceAdmin, TResult> request)
336        {
337            SFServiceAdmin _sfServiceAdmin = new SFServiceAdmin();
338            if (SessionManagerAdmin.SalesForceAdmin.AccessTokenAvailableAdmin)
339            {
340                try
341                {
342                    return request[_sfServiceAdmin];
343                }
344                catch (SalesForceSessionExceptionAdmin exception)
345                {
346                    SessionManagerAdmin.SalesForceAdmin.AuthenticationAdmin = _sfServiceAdmin.GetAuthenticationInformationAdmin(SessionManagerAdmin.SalesForceAdmin.AuthenticationAdmin.RefreshToken);
347                    return request(_sfServiceAdmin);
348                }
349            }
350            else
351            {
352                SessionManagerAdmin.SalesForceAdmin.AuthenticationAdmin = _sfServiceAdmin.GetAuthenticationInformationAdmin(SessionManagerAdmin.SalesForceAdmin.AuthenticationAdmin.RefreshToken);
353                return request(_sfServiceAdmin);
354            }
355        }
356    }
357}