public string FixDemoSource(string startdate)
        {
            int cnt = 0;

            SkillCowRequestSubmissionClient rsc = new SkillCowRequestSubmissionClient();

            DateTime cursordate = DateTime.ParseExact(startdate, "yyyyMMdd", CultureInfo.InvariantCulture);

            List <SkillCowRequestSubmission> submissions = new List <SkillCowRequestSubmission>();

            while (cursordate < DateTime.UtcNow.AddDays(1))
            {
                CloudTableQuery <SkillCowRequestSubmission> query = rsc.GetAll(cursordate.ToString("yyyyMMdd"));

                foreach (SkillCowRequestSubmission s in query.Execute().Where(x => x.UtmSource == "demo"))
                {
                    submissions.Add(s);
                }

                cursordate = cursordate.AddDays(1);
            }

            foreach (SkillCowRequestSubmission x in submissions)
            {
                x.UtmSource   = "Kiosks";
                x.UtmCampaign = "JerseyGardens";
                x.UtmTerm     = "Station1";
                rsc.Update(x);
            }

            return(cnt.ToString() + " leads fixed");
        }
        public ActionResult _resultmapping(FormCollection collection)
        {
            SkillCowRequestSubmissionClient rsc = new SkillCowRequestSubmissionClient();

            ViewBag.StartDate = DateTime.ParseExact(collection["startdate"], "yyyyMMdd", CultureInfo.InvariantCulture);
            ViewBag.EndDate   = DateTime.ParseExact(collection["enddate"], "yyyyMMdd", CultureInfo.InvariantCulture);

            return(View(rsc));
        }
        public ActionResult ExportProfiles1()
        {
            SkillCowRequestSubmissionClient rsc = new SkillCowRequestSubmissionClient();

            ViewBag.StartDate = EasternTimeConverter.Convert(DateTime.UtcNow);
            ViewBag.EndDate   = EasternTimeConverter.Convert(DateTime.UtcNow);


            return(View(rsc));
        }
        public ActionResult _nobodyknows(FormCollection collection)
        {
            SkillCowRequestSubmissionClient rsc = new SkillCowRequestSubmissionClient();

            ViewBag.StartDate = DateTime.ParseExact(collection["startdate"], "yyyyMMdd", CultureInfo.InvariantCulture);
            ViewBag.EndDate   = DateTime.ParseExact(collection["enddate"], "yyyyMMdd", CultureInfo.InvariantCulture);

            ViewBag.SearchName = collection["searchname"];

            return(View(rsc));
        }
        public ActionResult GetAgentPerformance(string startdate, string enddate)
        {
            //try
            //{
            Response.ContentType = "application/json";



            string datestamp = EasternTimeConverter.Convert(DateTime.UtcNow).ToString("yyyyMMdd");
            string cached    = BlobJsonResourceManager.Instance.GetJsonResource("skillcowagentdashboard", datestamp, "range" + startdate + enddate);

            if (cached != null && cached.Trim() != "")
            {
                Response.Write(cached);
                Response.End();
                return(null);
            }


            SkillCowRequestSubmissionClient rsc = new SkillCowRequestSubmissionClient();

            DateTime dstartdate = DateTime.ParseExact(startdate, "yyyyMMdd", CultureInfo.InvariantCulture);
            DateTime denddate   = DateTime.ParseExact(enddate, "yyyyMMdd", CultureInfo.InvariantCulture);


            AgentClient  ac             = new AgentClient();
            List <Agent> agentsprofiles = new List <Agent>(ac.GetAll().Execute());

            //Get agent hours
            List <AgentDailyActivity> tempactivity = AgentDailyActivity.Create(agentsprofiles, dstartdate, denddate, null);
            Dictionary <string, IGrouping <string, AgentDailyActivity> > agenthours = new Dictionary <string, IGrouping <string, AgentDailyActivity> >();

            foreach (IGrouping <string, AgentDailyActivity> ag in tempactivity.GroupBy(x => x.Agent))
            {
                agenthours.Add(ag.Key, ag);
            }

            List <SkillCowRequestSubmission> allrecords = rsc.GetKioskLeads(dstartdate, denddate);


            List <object> agents = new List <object>();

            foreach (KeyValuePair <string, IGrouping <string, AgentDailyActivity> > kv in agenthours)
            {
                Agent agentprofile = agentsprofiles.SingleOrDefault(x => x.LoginName == kv.Key.Replace("cindy", "sydneyc"));

                List <object> dates = new List <object>();

                double totalhours = 0;

                Dictionary <string, List <double> > aggregate = new Dictionary <string, List <double> >();

                aggregate.Add("hours", new List <double>());
                aggregate.Add("billablehours", new List <double>());
                aggregate.Add("hourlyearnings", new List <double>());
                aggregate.Add("validschoolleadsnetwork", new List <double>());
                aggregate.Add("companyvalidschoolleadsnetwork", new List <double>());
                aggregate.Add("invalidschoolleadsnetwork", new List <double>());
                aggregate.Add("companyinvalidschoolleadsnetwork", new List <double>());
                aggregate.Add("commissionsschoolleadsnetwork", new List <double>());
                aggregate.Add("AvgRetentionSchoolLeads", new List <double>());
                aggregate.Add("CompanyAvgRetentionSchoolLeads", new List <double>());
                aggregate.Add("AvgLPH", new List <double>());
                aggregate.Add("Stochastic", new List <double>());
                aggregate.Add("CompanyAverageLPHMean", new List <double>());

                List <object> ProductionChartData = new List <object>();

                ProductionChartData.Add(new string[] { "Date", "Best", "Worst", "Average", kv.Key });

                DateTime cursordate = dstartdate;
                while (cursordate <= denddate)
                {
                    IEnumerable <SkillCowRequestSubmission> companyvalidnetworkschoolleads = allrecords.Where(x =>
                                                                                                              x.PartitionKey == cursordate.ToString("yyyyMMdd") &&
                                                                                                              x.GradYear != "GET THIS" &&
                                                                                                              x.GradYear != "undefined" &&
                                                                                                              (int.Parse(x.GradYear) < DateTime.UtcNow.Year || (int.Parse(x.GradYear) == DateTime.UtcNow.Year && DateTime.UtcNow.Month > 5)) &&
                                                                                                              x.SourceForm == "schoolform");

                    IEnumerable <SkillCowRequestSubmission> companyinvalidnetworkschoolleads = allrecords.Where(x =>
                                                                                                                x.PartitionKey == cursordate.ToString("yyyyMMdd") &&
                                                                                                                !(x.GradYear != "GET THIS" && x.GradYear != "undefined" && (int.Parse(x.GradYear) < DateTime.UtcNow.Year || (int.Parse(x.GradYear) == DateTime.UtcNow.Year && DateTime.UtcNow.Month > 5))) &&
                                                                                                                x.SourceForm == "schoolform");

                    IEnumerable <SkillCowRequestSubmission> validnetworkschoolleads = allrecords.Where(x =>
                                                                                                       x.PartitionKey == cursordate.ToString("yyyyMMdd") &&
                                                                                                       x.GradYear != "GET THIS" &&
                                                                                                       x.GradYear != "undefined" &&
                                                                                                       (int.Parse(x.GradYear) < DateTime.UtcNow.Year || (int.Parse(x.GradYear) == DateTime.UtcNow.Year && DateTime.UtcNow.Month > 5)) &&
                                                                                                       x.SourceForm == "schoolform" &&
                                                                                                       x.UtmContent == kv.Key);

                    IEnumerable <SkillCowRequestSubmission> invalidnetworkschoolleads = allrecords.Where(x =>
                                                                                                         x.PartitionKey == cursordate.ToString("yyyyMMdd") &&
                                                                                                         !(x.GradYear != "GET THIS" && x.GradYear != "undefined" && (int.Parse(x.GradYear) < DateTime.UtcNow.Year || (int.Parse(x.GradYear) == DateTime.UtcNow.Year && DateTime.UtcNow.Month > 5))) &&
                                                                                                         x.SourceForm == "schoolform" &&
                                                                                                         x.UtmContent == kv.Key);

                    AgentDailyActivity locationday = null;
                    if (agenthours.ContainsKey(kv.Key))
                    {
                        locationday = agenthours[kv.Key].SingleOrDefault(x => x.FormattedDate == cursordate.ToString("yyyyMMdd"));
                    }

                    int validnetworkschoolleadcount = validnetworkschoolleads.Count();

#warning TO DO: Replace with hourly pay rate from admin
                    double hoursworked = (locationday != null ? locationday.Hours : 0);

                    double lunch = 0;
                    if (hoursworked > 7)
                    {
                        lunch = 1;
                    }
                    else if (hoursworked > 4)
                    {
                        lunch = 0.5;
                    }

                    double billablehours = hoursworked - lunch;

                    double hourlyrate     = agentprofile.PayPerHour;
                    double hourlyearnings = billablehours * hourlyrate;
                    double CommissionRatePerSchoolLeadNetwork = agentprofile.PayPerLead; //TO DO: Replace with hourly pay rate from admin
                    double CommissionRatePerSchoolLeadDirect  = agentprofile.PayPerLead; //TO DO: Replace with hourly pay rate from admin
                    double CommissionRatePerJobLeadNetwork    = 0.25;                    //TO DO: Replace with hourly pay rate from admin
                    double CommissionRatePerJobLeadDirect     = 0.25;                    //TO DO: Replace with hourly pay rate from admin
                    double CommissionsSchoolLeadsNetwork      = validnetworkschoolleadcount * CommissionRatePerSchoolLeadNetwork;

                    int    uniquestudents          = validnetworkschoolleads.GroupBy(x => x.Email).Count();
                    double AvgRetentionSchoolLeads = uniquestudents > 0 ? (double)validnetworkschoolleadcount / uniquestudents : 0;

                    int    companyuniquestudents          = companyvalidnetworkschoolleads.GroupBy(x => x.Email).Count();
                    double CompanyAvgRetentionSchoolLeads = companyuniquestudents > 0 ? (double)companyvalidnetworkschoolleads.Count() / companyvalidnetworkschoolleads.GroupBy(x => x.Email).Count() : 0;



                    double AvgLPH = locationday != null && locationday.Hours > 0 ? CalculateLPH(validnetworkschoolleadcount, locationday.Hours) : 0;
                    double CompanyAverageLPHMean = GetAvgLPHMean(cursordate, companyvalidnetworkschoolleads, agenthours);
                    double CompanyAverageLPHMax  = GetAvgLPHMax(cursordate, companyvalidnetworkschoolleads, agenthours);
                    double CompanyAverageLPHMin  = GetAvgLPHMin(cursordate, companyvalidnetworkschoolleads, agenthours);

                    double Stochastic = 0;
                    if (CompanyAverageLPHMax - CompanyAverageLPHMin > 0 && AvgLPH > 0)
                    {
                        Stochastic = (AvgLPH - CompanyAverageLPHMin) / (CompanyAverageLPHMax - CompanyAverageLPHMin);
                    }



                    dates.Add(new
                    {
                        Agent = kv.Key,
                        Date  = cursordate.ToString("MMM-d"),

                        ValidSchoolLeadsNetwork        = validnetworkschoolleadcount,
                        CompanyValidSchoolLeadsNetwork = companyvalidnetworkschoolleads.Count(),
                        //ValidSchoolLeadsDirect = GetValidSchoolLeads(allrecords),
                        //ValidJobLeadsNetwork = GetValidSchoolLeads(allrecords),
                        //ValidJobLeadsDirect = GetValidSchoolLeads(allrecords),
                        InvalidSchoolLeadsNetwork        = invalidnetworkschoolleads.Count(),
                        CompanyInvalidSchoolLeadsNetwork = companyinvalidnetworkschoolleads.Count(),
                        //InvalidSchoolLeadsDirect = GetValidSchoolLeads(allrecords),
                        //InvalidJobLeadsNetwork = GetValidSchoolLeads(allrecords),
                        //InvalidJobLeadsDirect = GetValidSchoolLeads(allrecords),
                        //IndeedJobs = GetValidSchoolLeads(allrecords),
                        //UdemyCourses = GetValidSchoolLeads(allrecords),
                        UniqueStudents                 = validnetworkschoolleads.GroupBy(x => x.Email).Count(),
                        AvgRetentionSchoolLeads        = AvgRetentionSchoolLeads,
                        CompanyAvgRetentionSchoolLeads = CompanyAvgRetentionSchoolLeads,

                        CompanyAvgLPHMax  = CompanyAverageLPHMax,
                        CompanyAvgLPHMean = CompanyAverageLPHMean,
                        CompanyAvgLPHMin  = CompanyAverageLPHMin,
                        AvgLPH            = AvgLPH,

                        Hours         = hoursworked,
                        BillableHours = billablehours,
                        Lunch         = lunch,
                        Logon         = locationday != null ? locationday.LogonTime : "",
                        Logoff        = locationday != null ? locationday.LogoffTime : "",

                        HourlyRate     = hourlyrate,
                        HourlyEarnings = hourlyearnings,

                        CommissionRatePerSchoolLeadNetwork = CommissionRatePerSchoolLeadNetwork,
                        CommissionRatePerSchoolLeadDirect  = CommissionRatePerSchoolLeadDirect,
                        CommissionRatePerJobLeadNetwork    = CommissionRatePerJobLeadNetwork,
                        CommissionRatePerJobLeadDirect     = CommissionRatePerJobLeadDirect,

                        CommissionsSchoolLeadsNetwork = CommissionsSchoolLeadsNetwork,

                        TotalEarnings = hourlyearnings + CommissionsSchoolLeadsNetwork,

                        Stochastic = Stochastic,

                        Payments    = 0,
                        Adjustments = 0

                                      //,CumulativeEarnings
                    });


                    //Build production chart data arrays
                    if (hoursworked > 0)
                    {
                        try
                        {
                            ProductionChartData.Add(new object[] {
                                cursordate.ToString("MMM-d"),
                                float.Parse(String.Format("{0:0.0}", CompanyAverageLPHMax)),
                                float.Parse(String.Format("{0:0.0}", CompanyAverageLPHMin)),
                                float.Parse(String.Format("{0:0.0}", CompanyAverageLPHMean)),
                                float.Parse(String.Format("{0:0.0}", AvgLPH))
                            });
                        }
                        catch (Exception ex)
                        {
                            Console.Write(ex.Message);
                        }

                        //running totals
                        totalhours += hoursworked;
                        if (locationday != null)
                        {
                            aggregate["hours"].Add(hoursworked);
                            aggregate["billablehours"].Add(billablehours);
                        }
                        aggregate["hourlyearnings"].Add(hourlyearnings);

                        aggregate["validschoolleadsnetwork"].Add(validnetworkschoolleadcount);
                        aggregate["companyvalidschoolleadsnetwork"].Add(companyvalidnetworkschoolleads.Count());

                        aggregate["invalidschoolleadsnetwork"].Add(invalidnetworkschoolleads.Count());
                        aggregate["companyinvalidschoolleadsnetwork"].Add(companyinvalidnetworkschoolleads.Count());

                        aggregate["commissionsschoolleadsnetwork"].Add(CommissionsSchoolLeadsNetwork);

                        aggregate["AvgRetentionSchoolLeads"].Add(AvgRetentionSchoolLeads);
                        aggregate["CompanyAvgRetentionSchoolLeads"].Add(CompanyAvgRetentionSchoolLeads);
                        aggregate["AvgLPH"].Add(AvgLPH);
                        aggregate["CompanyAverageLPHMean"].Add(CompanyAverageLPHMean);
                        aggregate["Stochastic"].Add(Stochastic);
                    }



                    cursordate = cursordate.AddDays(1);
                }

                double aggregatelph = aggregate["AvgLPH"].Average();


                agents.Add(new
                {
                    Id    = kv.Key,
                    Dates = dates.ToArray(),

                    TotalHours          = totalhours,
                    TotalBillableHours  = aggregate["billablehours"].Sum(),
                    AvgHoursPerDay      = aggregate.ContainsKey("hours") ? aggregate["hours"].Average() : 0,
                    TotalHourlyEarnings = aggregate["hourlyearnings"].Sum(),

                    TotalValidSchoolLeadsNetwork        = aggregate["validschoolleadsnetwork"].Sum(),
                    AvgValidSchoolLeadsNetwork          = aggregate["validschoolleadsnetwork"].Average(),
                    CompanyTotalValidSchoolLeadsNetwork = aggregate["companyvalidschoolleadsnetwork"].Sum(),

                    TotalInvalidSchoolLeadsNetwork        = aggregate["invalidschoolleadsnetwork"].Sum(),
                    AvgInvalidSchoolLeadsNetwork          = aggregate["invalidschoolleadsnetwork"].Average(),
                    CompanyTotalInvalidSchoolLeadsNetwork = aggregate["companyinvalidschoolleadsnetwork"].Sum(),

                    //totalvalidschoolleadsdirect = 0;
                    //totalvalidjobleadsnetwork = 0;
                    //totalvalidjobleadsdirect = 0;

                    TotalCommissionCchoolLeadsNetwork = aggregate["commissionsschoolleadsnetwork"].Sum(),

                    TotalEarnings = aggregate["hourlyearnings"].Sum() + aggregate["commissionsschoolleadsnetwork"].Sum(),

                    //totalcommissionschoolleadsdirect = 0;
                    //totalcommissionjobleadsnetwork = 0;
                    //totalcommissionjobleadsdirect = 0;

                    AvgRetentionSchoolLeads        = aggregate["AvgRetentionSchoolLeads"].Average(),
                    CompanyAvgRetentionSchoolLeads = aggregate["CompanyAvgRetentionSchoolLeads"].Average(),

                    AvgLPH = aggregatelph,
                    CompanyAverageLPHMean = aggregate["CompanyAverageLPHMean"].Average(),

                    Stochastic = aggregate["Stochastic"].Average(),

                    ProductionChartData = ProductionChartData.ToArray()
                });
            }


            string retvalue = (new { result = "ok", agents = agents.ToArray() }).ToJSON();

            //Save cached version
            BlobJsonResourceManager.Instance.SaveJsonResource(retvalue, "range" + startdate + enddate, "skillcowagentdashboard", datestamp);

            Response.Write(retvalue);
            Response.End();
            //}
            //catch (Exception ex)
            //{
            //    Response.ContentType = "application/json";
            //    Response.Write(DefaultErrorResponse(ex.Message));
            //    Response.End();
            //}

            return(null);
        }
Exemple #6
0
        public ActionResult Index(FormCollection collection)
        {
            if (Request.Cookies["recordsubmitted"] != null)
            {
                return(View());
            }

#if DEBUG
            string randomip = RandomHelper.Instance.Next(1, 256) + "." + RandomHelper.Instance.Next(0, 256) + "." + RandomHelper.Instance.Next(0, 256) + "." + RandomHelper.Instance.Next(1, 256);
#endif

            string ipaddress = "";
#if DEBUG
            ipaddress = randomip;
#else
            ipaddress = Request.UserHostAddress;
#endif
            string salutation = FormValue(collection, "salutation", "").Trim().ToProperCase();
            string gender     = salutation.ToLower() == "mr" ? "M" : "F";

            string firstname = FormValue(collection, "firstname", "GET THIS");
            string lastname  = FormValue(collection, "lastname", "GET THIS");
            string email     = FormValue(collection, "email", "GET THIS");
            string zip       = FormValue(collection, "zip", "GET THIS");
            string phone     = FormValue(collection, "phone", "GET THIS").Replace(".", "").Replace(" ", "").Replace("-", "").Replace("(", "").Replace(")", "");
            string address   = FormValue(collection, "address1", "GET THIS");
            string city      = FormValue(collection, "city", "GET THIS");
            string state     = FormValue(collection, "state", "GET THIS");
            string edulevel  = FormValue(collection, "education_level", "GET THIS");
            string campaign  = FormValue(collection, "cbncampaign", "13564694"); //(collection["campaign_id"] == null || collection["campaign_id"] == "" ? "GET THIS" : collection["campaign_id"]);

            string gradyear  = FormValue(collection, "gradyear", "GET THIS");    //(collection["gradyear"] == null || collection["gradyear"] == "" ? "GET THIS" : collection["gradyear"]);
            string eduintent = FormValue(collection, "edu_intent", "GET THIS");  //(collection["edu_intent"] == null || collection["edu_intent"] == "" ? "GET THIS" : collection["edu_intent"]);
            string dobyear   = FormValue(collection, "dobyear", "");

            Random rnd      = new Random(DateTime.Now.Millisecond);
            string dobmonth = rnd.Next(1, 13).ToString();
            string dobday   = rnd.Next(1, 29).ToString();


            string utmsource = "", utmcampaign = "", utmcontent = "", utmterm = "";
            if (Request.Cookies["utm_source"] != null)
            {
                utmsource = HttpUtility.UrlDecode(Request.Cookies["utm_source"].Value);
            }
            if (Request.Cookies["utm_campaign"] != null)
            {
                utmcampaign = HttpUtility.UrlDecode(Request.Cookies["utm_campaign"].Value);
            }
            if (Request.Cookies["utm_content"] != null)
            {
                utmcontent = HttpUtility.UrlDecode(Request.Cookies["utm_content"].Value);
            }
            if (Request.Cookies["utm_term"] != null)
            {
                utmterm = HttpUtility.UrlDecode(Request.Cookies["utm_term"].Value);
            }

            int igradyear;
            int.TryParse(gradyear, out igradyear);

            String result  = "";
            String strPost = "campaign_id=" + campaign +
                             "&id=1727" +
                             "&ip=" + ipaddress +
                             "&client=20" +
                             "&salutation=" + salutation +
                             "&gender=" + gender +
                             "&firstname=" + firstname.Trim() +
                             "&lastname=" + lastname.Trim() +
                             "&email=" + email +
                             "&address1=" + address +
                             "&city=" + city +
                             "&state=" + state +
                             "&zip=" + zip +
                             "&phone=" + phone +
                             "&educationlevel=" + edulevel +
                             "&education_level=" + edulevel +
                             "&edu_intent=" + eduintent +
                             "&gradyear=" + gradyear +
                             "&dobyear=" + dobyear +
                             "&dobmonth=" + dobmonth +
                             "&dobday=" + dobday;

            if (igradyear <= DateTime.Now.Year)
            {
                //Create delayed record
                DelayedRecordClient drc = new DelayedRecordClient();
                //First check if delayed record already exists for this email
                DelayedRecord dr = drc.GetByRowKey(email.FormatEmailAsProgrammaticId());
                if (dr == null)
                {
                    drc.AddNewItem(new DelayedRecord
                    {
                        RowKey         = email.FormatEmailAsProgrammaticId(),
                        CampaignId     = campaign,
                        ClientId       = "20",
                        IP             = ipaddress,
                        Salutation     = salutation,
                        Gender         = gender,
                        FirstName      = firstname,
                        LastName       = lastname,
                        Email          = email,
                        Address1       = address,
                        City           = city,
                        State          = state,
                        Zip            = zip,
                        Phone          = phone,
                        EducationLevel = edulevel,
                        EduIntent      = eduintent,
                        GradYear       = gradyear,
                        DobYear        = dobyear,
                        DobMonth       = dobmonth,
                        DobDay         = dobday
                    });
                }
            }


            SkillCowRequestSubmissionClient rsc = new SkillCowRequestSubmissionClient();

            string mode = "external";
            if (Request.Cookies["mode"] != null)
            {
                mode = Request.Cookies["mode"].Value;
            }

            string testresults = "";
            if (Request.Cookies["testresults"] != null)
            {
                testresults = DecodeCookieCharacters(Request.Cookies["testresults"].Value);
            }

            string recommendations = "";
            if (Request.Cookies["recommendations"] != null)
            {
                recommendations = DecodeCookieCharacters(Request.Cookies["recommendations"].Value);
            }

            string careerChoicesJson = GetCareerChoicesJson();
            string data = "{\"careerchoices\":" + careerChoicesJson + "}";

            //Advertise.com variables
            string advertise_affsub        = FromCookie("AFFSUB"),
                   advertise_affiliate     = FromCookie("AFFILIATE"),
                   advertise_country       = FromCookie("COUNTRY"),
                   advertise_countrycode   = FromCookie("COUNTRYCODE"),
                   advertise_geo           = FromCookie("GEO"),
                   advertise_subid         = FromCookie("SUBID"),
                   advertise_terms_html_kw = FromCookie("TERMS_HTML_KW"),
                   advertise_terms         = FromCookie("TERMS");

            rsc.AddNewItem(new SkillCowRequestSubmission {
                Gender = gender, Salutation = salutation, State = state, City = city, Name = firstname, Zip = zip, Email = email, Phone = phone, IP = ipaddress, Mode = mode, CampaignId = campaign, TestResults = testresults, SourceForm = collection["sourceform"], GradYear = gradyear, EduIntent = eduintent, Data = data, Recommendations = recommendations, UtmSource = utmsource, UtmCampaign = utmcampaign, UtmContent = utmcontent, UtmTerm = utmterm

                , SubmissionResult = result

                , advertise_affsub        = advertise_affsub
                , advertise_affiliate     = advertise_affiliate
                , advertise_country       = advertise_country
                , advertise_countrycode   = advertise_countrycode
                , advertise_geo           = advertise_geo
                , advertise_subid         = advertise_subid
                , advertise_terms         = advertise_terms
                , advertise_terms_html_kw = advertise_terms_html_kw
            });


            AddresseeClient adc            = new AddresseeClient();
            string          emailpartition = AddresseeClient.GetPartitionKeyForEmail(email);
            Addressee       a = adc.GetByPartitionAndRowKey(emailpartition, email);
            if (a == null)
            {
                adc.AddNewItem(new Addressee(email.ToLower())
                {
                    Name = firstname, Email = email.ToLower(),
                });

                UserProfileClient upc     = new UserProfileClient();
                UserProfile       profile = new UserProfile(email.ToLower())
                {
                    Gender       = gender,
                    Salutation   = salutation,
                    FirstName    = firstname,
                    LastName     = lastname,
                    Email        = email,
                    Unsubscribed = false,
                    Zip          = zip,
                    Address1     = address,
                    City         = city,
                    State        = state,
                    Phone        = phone,
                    CampaignId   = campaign,

                    GradYear  = gradyear,
                    EduIntent = eduintent
                };
                profile.PopulateCityAndState();
                profile.SetTestResults(Request);
                profile.SetImportantThings(Request);
                profile.SetRecommendations(recommendations);
                profile.SetCareerChoices(data);
                upc.AddNewItem(profile);
            }

            WelcomeEmail.Send(Request, firstname, email, mode == "external");

            Response.Cookies["recordsubmitted"].Value   = "1";
            Response.Cookies["recordsubmitted"].Expires = DateTime.UtcNow.AddDays(90);

            Response.Cookies["ascv"].Value   = "0.20";
            Response.Cookies["ascv"].Expires = DateTime.UtcNow.AddDays(90);

            ViewBag.ThanksFlag = false;

            return(View());
        }
        public ActionResult Index(FormCollection collection)
        {
            if (Request.Cookies["extendedrecordcomplete"] != null)
            {
                return(RedirectToAction("Index", "SkillTest"));
            }

            #region IP ADDRESS
#if DEBUG
            string randomip = RandomHelper.Instance.Next(1, 256) + "." + RandomHelper.Instance.Next(0, 256) + "." + RandomHelper.Instance.Next(0, 256) + "." + RandomHelper.Instance.Next(1, 256);
#endif
            string ipaddress = "";
#if DEBUG
            ipaddress = randomip;
#else
            ipaddress = Request.UserHostAddress;
#endif
            #endregion

            double LEAD_CONVERSION_VALUE   = 1;
            double RECORD_CONVERSION_VALUE = 0.2;

            double conversionValue = 0;

            string schoolsearchresultid = FromCookie("schoolsearchresultid");

            string campaignid = FormValue(collection, "cbncampaign", "13564694");

            string salutation = FormValue(collection, "salutation", "").Trim().ToProperCase();
            string gender     = salutation.ToLower() == "mr" ? "M" : "F";
            string firstname  = FormValue(collection, "firstname", "GET THIS");
            string lastname   = FormValue(collection, "lastname", "GET THIS");

            string email    = FormValue(collection, "email", "GET THIS").Trim().ToLower();
            string zip      = FormValue(collection, "zip", "GET THIS");
            string phone    = FormValue(collection, "phone", "GET THIS").Replace(".", "").Replace(" ", "").Replace("-", "").Replace("(", "").Replace(")", "");
            string address1 = FormValue(collection, "address1", "GET THIS");
            string city     = FormValue(collection, "city", "");
            string state    = FormValue(collection, "state", "");

            string educationlevel = FormValue(collection, "education_level", "SC");
            string eduintent      = FormValue(collection, "edu_intent", "YES");
            string military       = FormValue(collection, "military", "None");
            string gradyear       = FormValue(collection, "gradyear", "GET THIS");
            string sourceform     = FormValue(collection, "sourceform", "");

            string dobyear = FormValue(collection, "dobyear", "");

            Random rnd      = new Random(DateTime.Now.Millisecond);
            int    dobmonth = rnd.Next(1, 13);
            int    dobday   = rnd.Next(1, 29);

            string schoolvariables = "";
            if (Request.Cookies["schoolvariables"] != null)
            {
                schoolvariables = HttpUtility.UrlDecode(Request.Cookies["schoolvariables"].Value);
            }

            //GA variable
            string utmsource   = FromCookie("utm_source"),
                   utmcampaign = FromCookie("utm_campaign"),
                   utmcontent  = FromCookie("utm_content"),
                   utmterm     = FromCookie("utm_term");

            //Advertise.com variables
            string advertise_affsub        = FromCookie("AFFSUB"),
                   advertise_affiliate     = FromCookie("AFFILIATE"),
                   advertise_country       = FromCookie("COUNTRY"),
                   advertise_countrycode   = FromCookie("COUNTRYCODE"),
                   advertise_geo           = FromCookie("GEO"),
                   advertise_subid         = FromCookie("SUBID"),
                   advertise_terms_html_kw = FromCookie("TERMS_HTML_KW"),
                   advertise_terms         = FromCookie("TERMS");

            string[] distinctSubmissions = schoolvariables.Split('^');
            foreach (string submission in distinctSubmissions)
            {
                if (submission != "")
                {
                    string[] submissionTokens = submission.Split('!');

                    string campuskey  = submissionTokens[3];
                    string programkey = submissionTokens.Length > 4 ? submissionTokens[4] : "";



                    String strPost = "campaign_id=" + campaignid +
                                     "&id=1727" +
                                     "&ip=" + ipaddress +
                                     "&client_id=" + submissionTokens[1] +
                                     "&salutation=" + salutation +
                                     "&gender=" + gender +
                                     "&firstname=" + firstname.Trim() +
                                     "&lastname=" + lastname.Trim() +
                                     "&email=" + email +
                                     "&zip=" + zip +
                                     "&phone=" + phone +
                                     "&address1=" + address1 +
                                     "&city=" + city +
                                     "&state=" + state +
                                     "&education_level=" + educationlevel +
                                     "&educationlevel=" + educationlevel +
                                     "&edu_intent=YES" +
                                     "&military=" + military +
                                     "&campus_key=" + submissionTokens[3] +
                                     "&program_key=" + programkey +
                                     "&gradyear=" + gradyear +
                                     "&dobyear=" + dobyear +
                                     "&dobmonth=" + dobmonth.ToString() +
                                     "&dobday=" + dobday.ToString() +
                                     "&form_id=" + submissionTokens[2] +
                                     "&program=" + submissionTokens[0];

                    int igradyear;
                    int.TryParse(gradyear, out igradyear);

                    //Do not submit young leads to CBN
                    if (igradyear <= DateTime.Now.Year)
                    {
                        //Update the record with address
                        DelayedRecordClient drc = new DelayedRecordClient();
                        //First check if delayed record already exists for this email
                        DelayedRecord dr = drc.GetByRowKey(email.FormatEmailAsProgrammaticId());
                        if (dr != null)
                        {
                            if (dr.Address1 != address1)
                            {
                                dr.Address1  = address1;
                                dr.EduIntent = "YES";
                                drc.Update(dr);
                            }
                        }
                    }

                    string submissionResult = "";

                    try
                    {
                        if (igradyear <= DateTime.Now.Year)
                        {
                            submissionResult = SubmitLead(strPost);
                            conversionValue += LEAD_CONVERSION_VALUE;
                        }

                        SkillCowRequestSubmissionClient rsc = new SkillCowRequestSubmissionClient();

                        string mode = "external";
                        if (Request.Cookies["mode"] != null)
                        {
                            mode = Request.Cookies["mode"].Value;
                        }

                        string testresults = "";
                        if (Request.Cookies["testresults"] != null)
                        {
                            testresults = DecodeCookieCharacters(Request.Cookies["testresults"].Value);
                        }

                        string recommendations = "";
                        if (Request.Cookies["recommendations"] != null)
                        {
                            recommendations = DecodeCookieCharacters(Request.Cookies["recommendations"].Value);
                        }

                        string careerChoicesJson = GetCareerChoicesJson();
                        string data = "{\"careerchoices\":" + careerChoicesJson + "}";

                        rsc.AddNewItem(new SkillCowRequestSubmission
                        {
                            Salutation       = salutation,
                            Name             = (firstname + " " + lastname).Trim(),
                            Zip              = zip,
                            Email            = email,
                            Address1         = address1,
                            Phone            = phone,
                            IP               = ipaddress,
                            Mode             = mode,
                            CampaignId       = campaignid,
                            TestResults      = testresults,
                            SourceForm       = collection["sourceform"],
                            GradYear         = gradyear,
                            EduIntent        = eduintent,
                            Recommendations  = recommendations,
                            ClientId         = submissionTokens[1],
                            FormId           = submissionTokens[2],
                            Gender           = gender,
                            CareerId         = submissionTokens[0],
                            SubmissionResult = submissionResult,
                            Data             = data,
                            UtmSource        = utmsource,
                            UtmCampaign      = utmcampaign,
                            UtmContent       = utmcontent,
                            UtmTerm          = utmterm

                            ,
                            City = city
                            ,
                            State = state
                            ,
                            CampusKey = campuskey
                            ,
                            ProgramKey = programkey

                            ,
                            advertise_affsub = advertise_affsub
                            ,
                            advertise_affiliate = advertise_affiliate
                            ,
                            advertise_country = advertise_country
                            ,
                            advertise_countrycode = advertise_countrycode
                            ,
                            advertise_geo = advertise_geo
                            ,
                            advertise_subid = advertise_subid
                            ,
                            advertise_terms = advertise_terms
                            ,
                            advertise_terms_html_kw = advertise_terms_html_kw,

                            PostedString         = strPost,
                            SchoolSearchResultId = schoolsearchresultid
                        });


                        if (campaignid == "13564694")
                        {
                            //Telephony t = new Telephony();
                            //t.SendSMS("+19174340659", "Web lead: " + firstname + " " + lastname);
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }

            AddresseeClient adc            = new AddresseeClient();
            string          emailpartition = AddresseeClient.GetPartitionKeyForEmail(email);
            Addressee       a = adc.GetByPartitionAndRowKey(emailpartition, email);
            if (a == null)
            {
                adc.AddNewItem(new Addressee(email.ToLower())
                {
                    Name = firstname, Email = email.ToLower(),
                });

                UserProfileClient upc     = new UserProfileClient();
                UserProfile       profile = new UserProfile(email.ToLower())
                {
                    Gender       = gender,
                    Salutation   = salutation,
                    FirstName    = firstname,
                    LastName     = lastname,
                    Email        = email,
                    Unsubscribed = false,
                    Zip          = zip,
                    Address1     = address1,
                    City         = city,
                    State        = state,
                    Phone        = phone,
                    CampaignId   = campaignid,
                    GradYear     = gradyear,
                    EduIntent    = eduintent
                };
                profile.PopulateCityAndState();
                profile.SetTestResults(Request);
                profile.SetImportantThings(Request);
                upc.AddNewItem(profile);
            }

            ABTestClient abtc = null;
            abtc = new ABTestClient("Home", Request, Response);
            abtc.CreateGoalConversion("schoolleads", distinctSubmissions.Length);

            Response.Cookies["extendedrecordcomplete"].Value   = "1";
            Response.Cookies["extendedrecordcomplete"].Expires = DateTime.UtcNow.AddDays(90);

            //Only set this cookie for internal
            if (campaignid != "13564694")
            {
                Response.Cookies["ascv"].Value   = conversionValue.ToString();
                Response.Cookies["ascv"].Expires = DateTime.UtcNow.AddDays(90);
            }

            return(RedirectToAction("Index", "SkillTest", new { f = "thanks" }));
        }
        private string SubmitForm(FormCollection collection, string target)
        {
            string submissionResult;
            string campaignid;
            string url;
            string ipaddress = RandomHelper.Instance.Next(1, 256) + "." + RandomHelper.Instance.Next(0, 256) + "." + RandomHelper.Instance.Next(0, 256) + "." + RandomHelper.Instance.Next(1, 256);

            if (target == "school")
            {
                campaignid = "13601764";
                url        = "http://explore-schools.com/affiliate/submit/";
            }
            else
            {
                campaignid = "13601765";
                url        = "http://explore-schools.com/affiliate/submit/";
            }
            string        submit = collection["submit"] != "true" ? "false" : "true";
            List <string> output = new List <string>();

            foreach (var key in collection.AllKeys)
            {
                if (key.ToLower() == "educationlevel")
                {
                    output.Add(new StringBuilder("education_level" + "=" + HttpUtility.UrlEncode(collection[key])).ToString());
                }
                else if (key.ToLower() == "client")
                {
                    output.Add(new StringBuilder("client_id" + "=" + HttpUtility.UrlEncode(collection[key])).ToString());
                }
                else if (key.ToLower() == "submit")
                {
                    continue;
                }
                output.Add(new StringBuilder(key + "=" + HttpUtility.UrlEncode(collection[key])).ToString());
            }
            string result = new StringBuilder("campaign_id=" + campaignid + "&id=1727" + "&ip=" + ipaddress + "&" + string.Join("&", output)).ToString();

            if (submit == "true")
            {
                //submissionResult = "test";
                submissionResult = SubmitLead(result, url);
            }
            else
            {
                submissionResult = "Filtered";
            }
            //return submissionResult;
            //=================================================================================================================================================================================

            String strPost = result;

            string clientid   = FormValue(collection, "client", "");
            string formid     = FormValue(collection, "form_id", "");
            string clienttype = clientid.StartsWith("SC") ? "Direct" : "Network";
            string campuskey  = FormValue(collection, "campus_key", "");
            string programkey = FormValue(collection, "program_key", "");

            string salutation = FormValue(collection, "salutation", "").Trim().ToProperCase();
            string gender     = salutation.ToLower() == "mr" ? "M" : "F";
            string firstname  = FormValue(collection, "firstname", "GET THIS");
            string lastname   = FormValue(collection, "lastname", "GET THIS");

            string email    = FormValue(collection, "email", "GET THIS").Trim().ToLower();
            string zip      = FormValue(collection, "zip", "GET THIS");
            string phone    = FormValue(collection, "phone", "GET THIS").Replace(".", "").Replace(" ", "").Replace("-", "").Replace("(", "").Replace(")", "");
            string address1 = FormValue(collection, "address1", "GET THIS");
            string city     = FormValue(collection, "city", "");
            string state    = FormValue(collection, "state", "");

            string educationlevel = FormValue(collection, "education_level", "SC");
            string eduintent      = FormValue(collection, "edu_intent", "YES");
            string military       = FormValue(collection, "military", "None");
            string gradyear       = FormValue(collection, "gradyear", "GET THIS");
            string sourceform     = FormValue(collection, "sourceform", "");

            string dobyear = FormValue(collection, "dobyear", "");

            Random rnd      = new Random(DateTime.Now.Millisecond);
            int    dobmonth = rnd.Next(1, 13);
            int    dobday   = rnd.Next(1, 29);

            string schoolvariables = "";

            if (Request.Cookies["schoolvariables"] != null)
            {
                schoolvariables = HttpUtility.UrlDecode(Request.Cookies["schoolvariables"].Value);
            }

            //GA variable
            string utmsource   = FromCookie("utm_source"),
                   utmcampaign = FromCookie("utm_campaign"),
                   utmcontent  = FromCookie("utm_content"),
                   utmterm     = FromCookie("utm_term");

            //Advertise.com variables
            string advertise_affsub        = FromCookie("AFFSUB"),
                   advertise_affiliate     = FromCookie("AFFILIATE"),
                   advertise_country       = FromCookie("COUNTRY"),
                   advertise_countrycode   = FromCookie("COUNTRYCODE"),
                   advertise_geo           = FromCookie("GEO"),
                   advertise_subid         = FromCookie("SUBID"),
                   advertise_terms_html_kw = FromCookie("TERMS_HTML_KW"),
                   advertise_terms         = FromCookie("TERMS");
            StringBuilder sbtestresults    = new StringBuilder();
            string        testresults      = "";

            if (Request.Cookies["testresults"] != null)
            {
                testresults = CookieDecoder.DecodeCookieCharacters(Request.Cookies["testresults"].Value);
            }

            string recommendations = "";

            if (Request.Cookies["recommendations"] != null)
            {
                recommendations = CookieDecoder.DecodeCookieCharacters(Request.Cookies["recommendations"].Value);
            }

            string careerChoicesJson = GetCareerChoicesJson();
            string data = "{\"careerchoices\":" + careerChoicesJson + "}";

            //Update the record with address
            DelayedRecordClient drc = new DelayedRecordClient();
            //First check if delayed record already exists for this email
            DelayedRecord dr = drc.GetByRowKey(email.FormatEmailAsProgrammaticId());

            if (dr != null)
            {
                if (dr.Address1 != address1)
                {
                    dr.Address1  = address1;
                    dr.EduIntent = "YES";
                    drc.Update(dr);
                }
            }
            SkillCowRequestSubmissionClient rsc = new SkillCowRequestSubmissionClient();

            rsc.AddNewItem(new SkillCowRequestSubmission
            {
                Salutation       = salutation,
                Name             = (firstname + " " + lastname).Trim(),
                Zip              = zip,
                Email            = email,
                Address1         = address1,
                City             = city,
                State            = state,
                Phone            = phone,
                IP               = ipaddress,
                Mode             = "CareerThesaurus",
                CampaignId       = campaignid,
                TestResults      = testresults,
                SourceForm       = target,
                GradYear         = gradyear,
                EduIntent        = "YES",
                Recommendations  = recommendations,
                ClientId         = clientid,
                FormId           = formid,
                CampusKey        = campuskey,
                ProgramKey       = programkey,
                Gender           = gender,
                SubmissionResult = submissionResult,
                Data             = data,
                UtmSource        = utmsource,
                UtmCampaign      = utmcampaign,
                UtmContent       = utmcontent,
                UtmTerm          = utmterm,
                PostedString     = strPost,
                ClientType       = clienttype
            });

            AddresseeClient adc            = new AddresseeClient();
            string          emailpartition = AddresseeClient.GetPartitionKeyForEmail(email);
            Addressee       a = adc.GetByPartitionAndRowKey(emailpartition, email);

            if (a == null)
            {
                adc.AddNewItem(new Addressee(email.ToLower())
                {
                    Name = firstname, Email = email.ToLower()
                });

                UserProfileClient upc     = new UserProfileClient();
                UserProfile       profile = new UserProfile(email.ToLower())
                {
                    Gender       = gender,
                    Salutation   = salutation,
                    FirstName    = firstname,
                    LastName     = lastname,
                    Email        = email,
                    Unsubscribed = false,
                    Zip          = zip,
                    Address1     = address1,
                    City         = city,
                    State        = state,
                    Phone        = phone,
                    CampaignId   = campaignid,
                    GradYear     = gradyear,
                    EduIntent    = "YES"
                };
                profile.PopulateCityAndState();
                profile.SetTestResults(Request);
                profile.SetImportantThings(Request);
                upc.AddNewItem(profile);
            }

            //============================================================================================================================================================================================
            return(submissionResult);
        }
Exemple #9
0
        public HttpResponse logoff(string location, string agent, string code)
        {
            try
            {
                Response.ContentType = "application/json";

                AgentClient ac = new AgentClient();
                Agent       a  = ac.GetAll().Execute().Where(x => x.LoginName == agent).SingleOrDefault();

                if (a == null)
                {
                    throw new Exception("Invalid agent ID or code");
                }

                if (a.LoginCode == code)
                {
                    DateTime nowTime = EasternTimeConverter.Convert(DateTime.UtcNow);


                    AgentEventClient aec       = new AgentEventClient();
                    AgentEvent       lastEvent = aec.GetAll().Execute().Where(x => x.Agent == agent).OrderByDescending(x => x.EventTime).FirstOrDefault();

                    string hoursworked = "No prior logon.";
                    string production  = "No results.";
                    if (lastEvent.EventType == "logon")
                    {
                        long     elapsedTicks = nowTime.Ticks - lastEvent.EventTime.Ticks;
                        TimeSpan ts           = new TimeSpan(elapsedTicks);
                        hoursworked = ts.Hours.ToString() + "h : " + ts.Minutes + "m logged.";

                        //Count how many leads
                        List <SkillCowRequestSubmission> allrecords = new List <SkillCowRequestSubmission>();

                        DateTime cursordate = lastEvent.EventTime;

                        SkillCowRequestSubmissionClient rsc = new SkillCowRequestSubmissionClient();
                        while (cursordate <= nowTime)
                        {
                            CloudTableQuery <SkillCowRequestSubmission> query = rsc.GetAll(cursordate.ToString("yyyyMMdd"));
                            allrecords.AddRange(query.Execute().Where(x => x.UtmCampaign == location && x.UtmContent == agent).OrderBy(x => x.Timestamp));
                            cursordate = cursordate.AddDays(1);
                        }

                        //tally up
                        int totalschoolleads = 0;
                        int totalindeedjobs  = 0;
                        int totalcourses     = 0;
                        foreach (SkillCowRequestSubmission x in allrecords)
                        {
                            switch (x.SourceForm)
                            {
                            case "schoolform":
                                totalschoolleads++;
                                break;

                            case "indeedjob":
                                totalindeedjobs++;
                                break;

                            case "udemycourse":
                                totalcourses++;
                                break;
                            }
                        }
                        if (totalschoolleads + totalindeedjobs + totalcourses > 0)
                        {
                            production  = "\n";
                            production += totalschoolleads + " school leads\n";
                            production += totalindeedjobs + " indeed jobs\n";
                            production += totalcourses + " udemy courses";
                        }
                    }

                    //Log event
                    aec.AddNewItem(new AgentEvent(agent, "logoff", location));

                    a.CurrentLocation = "";
                    a.CurrentStatus   = "loggedoff";
                    ac.Update(a);

#if DEBUG
#else
                    Telephony t = new Telephony();

                    string message = agent + " logged OFF at " + location + "\n" + hoursworked + "\n" + production;
                    //Send to Rick
                    //t.SendSMS("+19174340659", message);

                    t.SendSMS("+19179578770", message);
#endif

                    Response.Write("{\"result\": \"ok\", \"logonname\": \"" + a.LoginName + "\"}");
                    Response.End();
                }
                else
                {
                    throw new Exception("Invalid agent ID or code");
                }
            }
            catch (Exception ex)
            {
                Response.ContentType = "application/json";
                Response.Write(DefaultErrorResponse(ex.Message));
                Response.End();
            }

            return(null);
        }