public async Task<IHttpActionResult> GetCurrentAccountRoles(string companyGUID)
        {
            List<AccountRole> dbRoleCollection = new List<AccountRole>();

            // Get the logged-in user.
            var currentUser = this.User as ServiceUser;

            Services.Log.Info("Find Company  [" + companyGUID + "] Staff Assignments for Current User");

            stranddContext context = new stranddContext();

            //Loading List of Account Roles from DB Context
            dbRoleCollection = await context.AccountRoles.Where(a => a.UserProviderID == currentUser.Id)
                .Where(b => b.CompanyGUID == companyGUID).ToListAsync<AccountRole>();

            if (dbRoleCollection.Count > 0)
            {
                string responseText = "Returned Company  [" + companyGUID + "] Staff Assignments for Account [" + currentUser.Id + "] " + currentUser.Id;
                Services.Log.Info(responseText);
                return Ok(dbRoleCollection);
            }
            else
            {
                string responseText = "No Company  [" + companyGUID + "] Staff Assignments for Account [" + currentUser.Id + "] " + currentUser.Id;
                Services.Log.Info(responseText);
                AccountRole noneRole = new AccountRole { CompanyGUID = companyGUID, RoleAssignment = "NONE", UserProviderID = currentUser.Id };
                dbRoleCollection.Add(noneRole);
                return Ok(dbRoleCollection);
            }

        }
        public static string GetProviderID(string incidentGUID)
        {
            if (string.IsNullOrEmpty(incidentGUID))
            {
                return("NO INCIDENT - NO PROVIDER ID");
            }
            else
            {
                stranddContext context        = new stranddContext();
                Incident       returnIncident = context.Incidents.Find(incidentGUID);


                if (returnIncident == null)
                {
                    return("INCIDENT NOT FOUND - NO PROVIDER ID");
                }
                else
                {
                    if (string.IsNullOrEmpty(returnIncident.ProviderUserID))
                    {
                        return("NO ASSOCIATED USER");
                    }
                    else
                    {
                        return(returnIncident.ProviderUserID);
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public async Task<HttpResponseMessage> NewCompany(CompanyRequest companyRequest)
        {
            Services.Log.Info("New Company Request [API]");

            stranddContext context = new stranddContext();

            //Checks for unique Company Name
            Company company = await context.Companies.Where(a => a.Name == companyRequest.Name).SingleOrDefaultAsync();

            if (company != null)
            {
                //Return Failed Response
                string responseText = "Company Already Exists [" + company.Name + "].";
                Services.Log.Warn(responseText);
                return this.Request.CreateResponse(HttpStatusCode.BadRequest, responseText);
            }
            else
            {
                //Vehicle Creation 
                Company newCompany = new Company
                {
                    Id = Guid.NewGuid().ToString(),
                    Name = companyRequest.Name,
                    Type = companyRequest.Type

                };
                context.Companies.Add(newCompany);
                await context.SaveChangesAsync();

                string responseText = ("New Company Created #" + newCompany.Id);
                Services.Log.Info(responseText);

                return this.Request.CreateResponse(HttpStatusCode.Created, responseText);
            }
        }
        public async Task<HttpResponseMessage> NewCostingSlab(CostingSlabRequest costingSlabRequest)
        {

            Services.Log.Info("New CostingSlab Request [API]");
            string responseText;

            stranddContext context = new stranddContext();

            CostingSlab newCostingSlab = new CostingSlab
            {
                
                Id = Guid.NewGuid().ToString(),
                IdentifierGUID = costingSlabRequest.IdentifierGUID,
                ServiceType = costingSlabRequest.ServiceType,
                Status = costingSlabRequest.Status,
                StartTime = costingSlabRequest.StartTime,
                EndTime = costingSlabRequest.EndTime,
                BaseCharge = costingSlabRequest.BaseCharge,
                BaseKilometersFloor = costingSlabRequest.BaseKilometersFloor,
                ExtraKilometersCharge = costingSlabRequest.ExtraKilometersCharge
              
                // Version = new Byte[125],
                //CreatedAt = costingSlabRequest.StartTime,
                //UpdatedAt=costingSlabRequest.StartTime,
                //Deleted= false

            };

            context.CostingSlabs.Add(newCostingSlab);
            await context.SaveChangesAsync();

            responseText = "CostingSlab Successfully Generated";
            Services.Log.Info(responseText);
            return this.Request.CreateResponse(HttpStatusCode.Created, responseText);
        }
        public static Incident GetIncident(string incidentGUID)
        {
            stranddContext context        = new stranddContext();
            Incident       returnIncident = context.Incidents.Find(incidentGUID);

            return(returnIncident);
        }
        public HttpResponseMessage RoadZenAccountProviderRegistration(ProviderRegistrationRequest registrationRequest)
        {
            Services.Log.Info("New Account Provider Registration Request [API]");

            // Phone Number SS Validation
            if (!Regex.IsMatch(registrationRequest.Phone, "^[0-9]{10}$"))
            {
                Services.Log.Warn("Invalid phone number (must be 10 numeric digits");
                return this.Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid phone number (must be 10 numeric digits");
            }
            if (!RegexUtilities.IsValidEmail(registrationRequest.Email))
            {
                Services.Log.Warn("Invalid e-mail address");
                return this.Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid e-mail address");
            }

            // Get the logged-in user.
            var currentUser = this.User as ServiceUser;

            stranddContext context = new stranddContext();

            Account account = context.Accounts.Where(a => a.Phone == registrationRequest.Phone).SingleOrDefault();
            if (account != null)
            {
                string responseText = "Phone Number Already Registered";
                Services.Log.Warn(responseText);
                return this.Request.CreateResponse(HttpStatusCode.BadRequest, WebConfigurationManager.AppSettings["RZ_MobileClientUserWarningPrefix"] + responseText);

            }

            //Password SS Validation
            if (registrationRequest.Password.Length < 6)
            {
                Services.Log.Warn("Invalid password (at least 6 chars required)");
                return this.Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid password (at least 6 chars required)");
            }

            byte[] salt = RoadZenSecurityUtils.generateSalt();

            Guid guid = Guid.NewGuid();

            Account newUserAccount = new Account
            {
                Id = guid.ToString(),
                Name = registrationRequest.Name,
                Phone = registrationRequest.Phone,
                Email = registrationRequest.Email,
                ProviderUserID = "RoadZen:" + guid.ToString("N").ToUpper(),
                Salt =  salt,
                SaltedAndHashedPassword = RoadZenSecurityUtils.hash(registrationRequest.Password, salt)
            };

            context.Accounts.Add(newUserAccount);
            context.SaveChanges();

            Services.Log.Info("Account for [" + newUserAccount.ProviderUserID + "] has been created");
            return this.Request.CreateResponse(HttpStatusCode.Created, "Account for [" + newUserAccount.ProviderUserID + "] has been created");
        }
        public IncidentExcelData(Incident baseIncident)
        {
            stranddContext context = new stranddContext();

            // Pull Incident data
            this.TimeStamp        = (baseIncident.CreatedAt != null) ? (DateTimeOffset)baseIncident.CreatedAt : DateTimeOffset.MinValue;
            this.IncidentGUID     = baseIncident.Id;
            this.JobCode          = baseIncident.JobCode;
            this.ArrivalTime      = System.Convert.ToString(baseIncident.ProviderArrivalTime);
            this.ConcertoCaseID   = baseIncident.ConcertoCaseID;
            this.StaffNotes       = baseIncident.StaffNotes;
            this.ServiceFee       = System.Convert.ToString(baseIncident.ServiceFee);
            this.CustomerComments = baseIncident.CustomerComments;
            this.CustomerRating   = baseIncident.Rating.ToString();
            this.IncidentStatus   = baseIncident.StatusCode;

            //pull customer Data
            AccountInfo lookupCustomer = new AccountInfo(baseIncident.ProviderUserID);

            this.CustomerName  = lookupCustomer.Name;
            this.CustomerPhone = lookupCustomer.Phone;

            //pull Vehicle data
            VehicleInfo lookupVehicle = new VehicleInfo(baseIncident.VehicleGUID);

            this.VehicleDescription  = lookupVehicle.Year + " " + lookupVehicle.Color + " " + lookupVehicle.Make + " " + lookupVehicle.Model;
            this.VehicleRegistration = lookupVehicle.RegistrationNumber;

            //Pull Payment data

            Payment lookupPayment = context.Payments
                                    .Where(u => u.IncidentGUID == baseIncident.Id)
                                    .FirstOrDefault();

            this.PaymentStatus   = (lookupPayment != null) ? lookupPayment.Status : null;
            this.PaymentAmount   = (lookupPayment != null) ? lookupPayment.Amount : 0;
            this.PaymentPlatform = (lookupPayment != null) ? lookupPayment.PaymentPlatform : null;

            //Pull Admin from History Event

            HistoryEvent lookupAdminEvent = context.HistoryLog
                                            .Where(u => u.ReferenceID == baseIncident.Id)
                                            .Where(v => v.Code == "INCIDENT_STATUS_ADMIN")
                                            .Where(x => x.Attribute == "CONFIRMED")
                                            .FirstOrDefault();

            AccountInfo lookupAdmin;

            if (lookupAdminEvent != null)
            {
                lookupAdmin = new AccountInfo(lookupAdminEvent.AdminID);
            }
            else
            {
                lookupAdmin = new AccountInfo(null);
            }
            this.ConfirmedAdminName = lookupAdmin.Name;
        }
        public HttpResponseMessage CustomerIncidentPaymentView(string incidentGUID)
        {
            HttpResponseMessage response;
            Services.Log.Info("Customer Incident [" + incidentGUID + "] Payment View Requested [API]");

            Uri redirectURI;
            string paymentService;
            IncidentInfo paymentIncident;

            stranddContext context = new stranddContext();
            Incident returnIncident = context.Incidents.Find(incidentGUID);

            if (returnIncident != null)
            {
                paymentService = "Instamojo";  //WILL ADAPT AS NEW PAYMENT SERVICES ADDED
                paymentIncident = new IncidentInfo(incidentGUID);
            }
            else { paymentService = "Not Found"; paymentIncident = new IncidentInfo(); }

            if (paymentService == "Instamojo")
            {

                string instamojoIncidentDataField = WebConfigurationManager.AppSettings["RZ_InstamojoIncidentDataField"]; // "data_Field_25373"

                var redirectQuery = HttpUtility.ParseQueryString(string.Empty);

                redirectQuery["data_readonly"] = "data_amount";
                redirectQuery["embed"] = "form";

                redirectQuery["data_amount"] = (paymentIncident.ServiceFee - paymentIncident.PaymentAmount).ToString();
                redirectQuery["data_email"] = paymentIncident.IncidentUserInfo.Email.ToString();
                redirectQuery["data_name"] = paymentIncident.IncidentUserInfo.Name.ToString();
                redirectQuery["data_phone"] = paymentIncident.IncidentUserInfo.Phone.ToString();

                redirectQuery[("data_" + instamojoIncidentDataField)] = incidentGUID;
                redirectQuery["data_hidden"] = ("data_" + instamojoIncidentDataField);

                string urlFullString = WebConfigurationManager.AppSettings["RZ_InstamojoBaseURL"].ToString() + "?" + redirectQuery.ToString();
                redirectURI = new Uri(urlFullString);

                response = Request.CreateResponse(HttpStatusCode.Moved);
                response.Headers.Location = redirectURI;
                Services.Log.Info("Customer Incident Payment View [" + urlFullString + "] Returned [VIEW]");

            }
            else
            {
                response = Request.CreateResponse("<H1>No Incident Found</H1>");
                Services.Log.Warn("Customer Incident [" + incidentGUID  + "] Not Found [VIEW]");
            }

            //Return Generated Response
            return response;
        }
        public async Task<IHttpActionResult> GetAllStaffAssignments()
        {
            Services.Log.Info("Full Staff Assisgnments Log Requested [API]");
            List<AccountRole> dbAccountRoleCollection = new List<AccountRole>();

            stranddContext context = new stranddContext();

            //Loading List of Incidents from DB Context
            dbAccountRoleCollection = await (context.AccountRoles).ToListAsync<AccountRole>();

            //Return Successful Response
            Services.Log.Info("Full Staff Assisgnments Log Returned [API]");
            return Ok(dbAccountRoleCollection);
        }
Ejemplo n.º 10
0
        public async Task<IHttpActionResult> GetAllVehicleInfos()
        {
            Services.Log.Info("Vehicle Log Requested [API]");
            List<Vehicle> dbVehicleCollection = new List<Vehicle>();

            stranddContext context = new stranddContext();

            //Loading List of Incidents from DB Context
            dbVehicleCollection = await (context.Vehicles).ToListAsync<Vehicle>();

            //Return Successful Response
            Services.Log.Info("Vehicle Log Returned [API]");
            return Ok(dbVehicleCollection);
        }
Ejemplo n.º 11
0
        public async Task<IHttpActionResult> GetAllCompanies()
        {
            Services.Log.Info("Company Log Requested [API]");
            List<Company> dbCompanyCollection = new List<Company>();

            stranddContext context = new stranddContext();

            //Loading List of Incidents from DB Context
            dbCompanyCollection = await (context.Companies).ToListAsync<Company>();

            //Return Successful Response
            Services.Log.Info("Company Log Returned [API]");
            return Ok(dbCompanyCollection);
        }
        public async Task<IHttpActionResult> GetAllCostingSlab()
        {
            Services.Log.Info("Full CostingSlab Log Requested [API]");
            List<CostingSlab> dbCostingSlabCollection = new List<CostingSlab>();

            stranddContext context = new stranddContext();

            //Loading List of CostingSlab from DB Context
            dbCostingSlabCollection = await (context.CostingSlabs.OrderBy(a=>a.Status)).ToListAsync<CostingSlab>();

            //Return Successful Response
            Services.Log.Info("Full CostingSlab Log Returned [API]");
            return Ok(dbCostingSlabCollection);
        }
        public async Task<IHttpActionResult> GetAllExceptions()
        {
            Services.Log.Info("Exception Log Requested [API]");
            List<ExceptionEntry> dbExceptionCollection = new List<ExceptionEntry>();

            stranddContext context = new stranddContext();

            //Loading List of Accounts from DB Context
            dbExceptionCollection = await (context.ExceptionLog).ToListAsync<ExceptionEntry>();

            //Return Successful Response
            Services.Log.Info("Exception Log Returned [API]");
            return Ok(dbExceptionCollection);
        }
        public async Task<IHttpActionResult> GetAllHistoryLog()
        {
            Services.Log.Info("History Log Requested [API]");
            List<HistoryEvent> dbHistoryLog = new List<HistoryEvent>();

            stranddContext context = new stranddContext();

            //Loading Log of History Events from DB Context
            dbHistoryLog = await (context.HistoryLog).ToListAsync<HistoryEvent>();

            //Return Successful Response
            Services.Log.Info("History Log Returned [API]");
            return Ok(dbHistoryLog);
        }
        public IncidentExcelData(Incident baseIncident)
        {
            stranddContext context = new stranddContext();

            // Pull Incident data
            this.TimeStamp = (baseIncident.CreatedAt != null) ? (DateTimeOffset) baseIncident.CreatedAt : DateTimeOffset.MinValue;
            this.IncidentGUID = baseIncident.Id;
            this.JobCode = baseIncident.JobCode;
            this.ArrivalTime = System.Convert.ToString(baseIncident.ProviderArrivalTime);
            this.ConcertoCaseID = baseIncident.ConcertoCaseID;
            this.StaffNotes = baseIncident.StaffNotes;
            this.ServiceFee = System.Convert.ToString(baseIncident.ServiceFee);
            this.CustomerComments = baseIncident.CustomerComments;
            this.CustomerRating = baseIncident.Rating.ToString();
            this.IncidentStatus = baseIncident.StatusCode;

            //pull customer Data
            AccountInfo lookupCustomer = new AccountInfo(baseIncident.ProviderUserID);
            this.CustomerName = lookupCustomer.Name;
            this.CustomerPhone = lookupCustomer.Phone;

            //pull Vehicle data
            VehicleInfo lookupVehicle = new VehicleInfo(baseIncident.VehicleGUID);
            this.VehicleDescription = lookupVehicle.Year + " " + lookupVehicle.Color + " " + lookupVehicle.Make + " " + lookupVehicle.Model;
            this.VehicleRegistration = lookupVehicle.RegistrationNumber;

            //Pull Payment data

            Payment lookupPayment = context.Payments
            .Where(u => u.IncidentGUID == baseIncident.Id)
            .FirstOrDefault();
            this.PaymentStatus = (lookupPayment != null) ? lookupPayment.Status : null;
            this.PaymentAmount = (lookupPayment != null) ? lookupPayment.Amount : 0;
            this.PaymentPlatform = (lookupPayment != null) ? lookupPayment.PaymentPlatform : null;

            //Pull Admin from History Event

            HistoryEvent lookupAdminEvent = context.HistoryLog
              .Where(u => u.ReferenceID == baseIncident.Id)
              .Where(v => v.Code == "INCIDENT_STATUS_ADMIN")
              .Where(x => x.Attribute == "CONFIRMED")
              .FirstOrDefault();

            AccountInfo lookupAdmin;
            if (lookupAdminEvent != null) { lookupAdmin = new AccountInfo(lookupAdminEvent.AdminID); }
            else { lookupAdmin = new AccountInfo(null); }
            this.ConfirmedAdminName = lookupAdmin.Name;
        }
        public async Task<IHttpActionResult> GetIncidentInfos()
        {
            Services.Log.Info("Incident Log Requested [API]");
            List<Incident> dbIncidentCollection = new List<Incident>();
            List<IncidentInfo> fullIncidentCollection = new List<IncidentInfo>();

            stranddContext context = new stranddContext();

            //Loading List of Incidents from DB Context
            dbIncidentCollection = await (context.Incidents).ToListAsync<Incident>();
            foreach (Incident dbIncident in dbIncidentCollection) { fullIncidentCollection.Add(new IncidentInfo(dbIncident)); }

            //Return Successful Response
            Services.Log.Info("Full Incident Log Returned [API]");
            return Ok(fullIncidentCollection);
        }
        public StaffAssignmentInfo(AccountRole accountRole)
        {
            stranddContext context = new stranddContext();

            AccountRole returnAccountRole = accountRole;

            if (returnAccountRole != null)
            {
                this.UserProviderID = returnAccountRole.UserProviderID;
                this.RoleAssignment = returnAccountRole.RoleAssignment;

                Account returnUser = context.Accounts
                                     .Where(u => u.ProviderUserID == returnAccountRole.UserProviderID)
                                     .FirstOrDefault();
                if (returnUser != null)
                {
                    this.AccountGUID = returnUser.Id;
                    this.Name        = returnUser.Name;
                    this.Phone       = returnUser.Phone;
                    this.Email       = returnUser.Email;
                }
                else
                {
                    this.Name  = "NONE";
                    this.Phone = "NONE";
                    this.Email = "NONE";
                }

                Company returnCompany = context.Companies
                                        .Where(u => u.Id == returnAccountRole.CompanyGUID)
                                        .FirstOrDefault();

                if (returnCompany != null)
                {
                    this.CompanyName = returnCompany.Name;
                }
                else
                {
                    this.CompanyName = "NONE";
                }
            }
            else
            {
                this.RoleAssignment = "NONE";
                this.CompanyName    = "NONE";
            }
        }
Ejemplo n.º 18
0
        public static async Task logHistoryEventAsync(string code, string attribute, string referenceID, string adminID, string customerID, string providerID)
        {
            HistoryEvent newEvent = new HistoryEvent()
            {
                Id = Guid.NewGuid().ToString(),
                Code = code,
                Attribute = attribute,
                ReferenceID = referenceID,
                AdminID = adminID,
                CustomerID = customerID,
                ProviderID = providerID
            };

            stranddContext context = new stranddContext();
            context.HistoryLog.Add(newEvent);
            await context.SaveChangesAsync();
        }
        public StaffAssignmentInfo(AccountRole accountRole)
        {
            stranddContext context = new stranddContext();

            AccountRole returnAccountRole = accountRole;

            if (returnAccountRole != null)
            {
                this.UserProviderID = returnAccountRole.UserProviderID;
                this.RoleAssignment = returnAccountRole.RoleAssignment;

                Account returnUser = context.Accounts
                    .Where(u => u.ProviderUserID == returnAccountRole.UserProviderID)
                    .FirstOrDefault();
                if (returnUser != null)
                {
                    this.AccountGUID = returnUser.Id;
                    this.Name = returnUser.Name;
                    this.Phone = returnUser.Phone;
                    this.Email = returnUser.Email;
                }
                else
                {
                    this.Name = "NONE";
                    this.Phone = "NONE";
                    this.Email = "NONE";
                }

                Company returnCompany = context.Companies
                    .Where(u => u.Id == returnAccountRole.CompanyGUID)
                    .FirstOrDefault();

                if (returnCompany != null)
                {
                    this.CompanyName = returnCompany.Name;
                }
                else { this.CompanyName = "NONE"; }

            }
            else
            {
                this.RoleAssignment = "NONE";
                this.CompanyName = "NONE";
            }
        }
Ejemplo n.º 20
0
        public static async Task logHistoryEventAsync(string code, string attribute, string referenceID, string adminID, string customerID, string providerID)
        {
            HistoryEvent newEvent = new HistoryEvent()
            {
                Id          = Guid.NewGuid().ToString(),
                Code        = code,
                Attribute   = attribute,
                ReferenceID = referenceID,
                AdminID     = adminID,
                CustomerID  = customerID,
                ProviderID  = providerID
            };

            stranddContext context = new stranddContext();

            context.HistoryLog.Add(newEvent);
            await context.SaveChangesAsync();
        }
        public HttpResponseMessage RoadZenLogin(LoginRequest loginRequest)
        {
            Services.Log.Info("RoadZen Login Request from Phone# [" + loginRequest.Phone + "]");

            stranddContext context = new stranddContext();
            Account useraccount = context.Accounts.Where(a => a.Phone == loginRequest.Phone).SingleOrDefault();
            if (useraccount != null)
            {
                // Check if Registered Phone Number is through Google-Provider Account
                if (useraccount.ProviderUserID.Substring(0,6)=="Google")
                {
                    string responseText = "Phone Number Registered with Google";
                    Services.Log.Warn(responseText);
                    return this.Request.CreateResponse(HttpStatusCode.Unauthorized, WebConfigurationManager.AppSettings["RZ_MobileClientUserWarningPrefix"] + responseText);
                }

                byte[] incoming = RoadZenSecurityUtils.hash(loginRequest.Password, useraccount.Salt);

                if (RoadZenSecurityUtils.slowEquals(incoming, useraccount.SaltedAndHashedPassword))
                {
                    ClaimsIdentity claimsIdentity = new ClaimsIdentity();
                    claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, loginRequest.Phone));
                    claimsIdentity.AddClaim(new Claim("AccountGUID", useraccount.Id));

                    LoginResult loginResult = new RoadZenLoginProvider(handler).CreateLoginResult(claimsIdentity, Services.Settings.MasterKey);

                    Services.Log.Info("Account [" + useraccount.ProviderUserID + "] has logged-in");
                    return this.Request.CreateResponse(HttpStatusCode.OK, loginResult);
                }
                else
                {
                    string responseText = "Incorrect Password";
                    Services.Log.Warn(responseText);
                    return this.Request.CreateResponse(HttpStatusCode.Unauthorized, WebConfigurationManager.AppSettings["RZ_MobileClientUserWarningPrefix"] + responseText);
                }
            }
            else
            {
                string responseText = "Unregistered Phone Number";
                Services.Log.Warn(responseText);
                return this.Request.CreateResponse(HttpStatusCode.Unauthorized, WebConfigurationManager.AppSettings["RZ_MobileClientUserWarningPrefix"] + responseText);
            }
        }
        public async Task<IHttpActionResult> GetActiveIncidentInfos()
        {
            Services.Log.Info("Active Incident Log Requested [API]");
            List<Incident> dbIncidentQuery = new List<Incident>();
            List<IncidentInfo> activeIncidentCollection = new List<IncidentInfo>();

            stranddContext context = new stranddContext();

            //Loading List of Active Incidents from DB Context
            dbIncidentQuery = await context.Incidents
                .Where(b => b.StatusCode != "CANCELLED" && b.StatusCode != "DECLINED" && b.StatusCode != "COMPLETED" && b.StatusCode != "FAILED")
                .ToListAsync<Incident>();

            foreach (Incident dbIncident in dbIncidentQuery) { activeIncidentCollection.Add(new IncidentInfo(dbIncident)); }

            //Return Successful Response
            Services.Log.Info("Active Incident Log Returned [API]");
            return Ok(activeIncidentCollection);
        }
        public async Task<IHttpActionResult> GetCompanyStaffAssignments(string companyGUID)
        {
            Services.Log.Info("Company  [" + companyGUID + "] Staff Assisgnments Log Requested [API]");
            List<AccountRole> dbAccountRoleCollection = new List<AccountRole>();
            List<StaffAssignmentInfo> fullStaffAssignmentCollection = new List<StaffAssignmentInfo>();

            stranddContext context = new stranddContext();

            //Loading List of Incidents from DB Context
            dbAccountRoleCollection = await context.AccountRoles.Where(a => a.CompanyGUID == companyGUID).ToListAsync<AccountRole>();

            //Expanding Account Role Info
            foreach (AccountRole accountRole in dbAccountRoleCollection) { fullStaffAssignmentCollection.Add(new StaffAssignmentInfo(accountRole)); }


            //Return Successful Response
            Services.Log.Info("Company  [" + companyGUID + "] Staff Assisgnments Log Returned [API]");
            return Ok(fullStaffAssignmentCollection);
        }
        public async Task<IHttpActionResult> GetCostingSlabInfo(string CostingSlabid)
        {

            List<CostingSlab> dbCostingSlab = new List<CostingSlab>();
           
            // Get the logged-in user.
           // var currentUser = this.User as ServiceUser;

            Services.Log.Info("CostingSlabID [" + CostingSlabid + "] CostingSlab Information Requested [API]");

            stranddContext context = new stranddContext();

                dbCostingSlab = await context.CostingSlabs.Where(a => a.Id == CostingSlabid)
             .ToListAsync<CostingSlab>();

                //Return Successful Response
                Services.Log.Info("CostingSlabID [" + CostingSlabid + "] CostingSlab Information Returned");
                return Ok(dbCostingSlab);
         
        }
        public AccountExcelData(Account baseAccount)
        {
            this.Id = baseAccount.Id;
            this.Phone = baseAccount.Phone;
            this.Name = baseAccount.Name;
            this.Email = baseAccount.Email;
            this.ProviderUserID = baseAccount.ProviderUserID;
            this.Salt = System.Convert.ToString( baseAccount.Salt);
            this.SaltedAndHashedPassword = System.Convert.ToString(baseAccount.SaltedAndHashedPassword);
            this.Version = System.Convert.ToString( baseAccount.Version);

            this.RegisterDate = (baseAccount.CreatedAt != null)  ? (DateTimeOffset) baseAccount.CreatedAt : DateTimeOffset.MinValue;
            this.UpdatedAt = (baseAccount.UpdatedAt != null) ? (DateTimeOffset)baseAccount.UpdatedAt : DateTimeOffset.MinValue;
            this.Deleted = System.Convert.ToString( baseAccount.Deleted);

            stranddContext context = new stranddContext();
            int SubmittedCount = context.Incidents.Count(u => u.ProviderUserID == baseAccount.ProviderUserID);

            this.IncidentSubmittedCount = System.Convert.ToString(SubmittedCount);
        }
        public AccountExcelData(Account baseAccount)
        {
            this.Id                      = baseAccount.Id;
            this.Phone                   = baseAccount.Phone;
            this.Name                    = baseAccount.Name;
            this.Email                   = baseAccount.Email;
            this.ProviderUserID          = baseAccount.ProviderUserID;
            this.Salt                    = System.Convert.ToString(baseAccount.Salt);
            this.SaltedAndHashedPassword = System.Convert.ToString(baseAccount.SaltedAndHashedPassword);
            this.Version                 = System.Convert.ToString(baseAccount.Version);

            this.RegisterDate = (baseAccount.CreatedAt != null)  ? (DateTimeOffset)baseAccount.CreatedAt : DateTimeOffset.MinValue;
            this.UpdatedAt    = (baseAccount.UpdatedAt != null) ? (DateTimeOffset)baseAccount.UpdatedAt : DateTimeOffset.MinValue;
            this.Deleted      = System.Convert.ToString(baseAccount.Deleted);

            stranddContext context        = new stranddContext();
            int            SubmittedCount = context.Incidents.Count(u => u.ProviderUserID == baseAccount.ProviderUserID);

            this.IncidentSubmittedCount = System.Convert.ToString(SubmittedCount);
        }
Ejemplo n.º 27
0
        //Constructor built on ProviderUserID LookUp
        public AccountInfo(string providerUserID)
        {
            if (string.IsNullOrEmpty(providerUserID))
            {
                this.AccountGUID    = "NO ASSOCIATED USER";
                this.Name           = "NO USER";
                this.Phone          = "NO PHONE";
                this.Email          = "NO EMAIL";
                this.ProviderUserID = providerUserID;
                this.RegisteredAt   = System.DateTime.Now;
            }
            else
            {
                stranddContext context = new stranddContext();

                //[RECONSIDER] Look up User based upon ProviderUserID
                Account returnUser = context.Accounts
                                     .Where(u => u.ProviderUserID == providerUserID)
                                     .FirstOrDefault();

                if (returnUser == null)
                {
                    this.AccountGUID    = "NO USER ACCOUNT";
                    this.Name           = providerUserID;
                    this.Phone          = "NO PHONE";
                    this.Email          = "NO EMAIL";
                    this.ProviderUserID = providerUserID;
                    this.RegisteredAt   = System.DateTime.Now;
                }
                else
                {
                    this.AccountGUID    = returnUser.Id;
                    this.Name           = returnUser.Name;
                    this.Phone          = returnUser.Phone;
                    this.Email          = returnUser.Email;
                    this.ProviderUserID = returnUser.ProviderUserID;
                    this.RegisteredAt   = returnUser.CreatedAt;
                }
            }
        }
Ejemplo n.º 28
0
        //Constructor built on ProviderUserID LookUp
        public AccountInfo(string providerUserID)
        {
            if (string.IsNullOrEmpty(providerUserID))
            {
                this.AccountGUID = "NO ASSOCIATED USER";
                this.Name = "NO USER";
                this.Phone = "NO PHONE";
                this.Email = "NO EMAIL";
                this.ProviderUserID = providerUserID;
                this.RegisteredAt = System.DateTime.Now;
            }
            else
            {
                stranddContext context = new stranddContext();

                //[RECONSIDER] Look up User based upon ProviderUserID
                Account returnUser = context.Accounts
                    .Where(u => u.ProviderUserID == providerUserID)
                    .FirstOrDefault();

                if (returnUser == null)
                {
                    this.AccountGUID = "NO USER ACCOUNT";
                    this.Name = providerUserID;
                    this.Phone = "NO PHONE";
                    this.Email = "NO EMAIL";
                    this.ProviderUserID = providerUserID;
                    this.RegisteredAt = System.DateTime.Now;
                }
                else
                {
                    this.AccountGUID = returnUser.Id;
                    this.Name = returnUser.Name;
                    this.Phone = returnUser.Phone;
                    this.Email = returnUser.Email;
                    this.ProviderUserID = returnUser.ProviderUserID;
                    this.RegisteredAt = returnUser.CreatedAt;
                }
            }
        }
        public async Task<HttpResponseMessage> ProviderClientExceptionGeneral(ExceptionLogRequest clientException)
        {
            Services.Log.Warn("Mobile Provider Client General Exception [API]");
            Services.Log.Warn(clientException.Exception);

            ExceptionEntry newException = new ExceptionEntry()
            {
                Id = Guid.NewGuid().ToString(),
                ExceptionText = clientException.Exception,
                Source = "MOBILE PROVIDER CLIENT"
            };

            stranddContext context = new stranddContext();
            context.ExceptionLog.Add(newException);

            await context.SaveChangesAsync();

            string responseText;
            responseText = "Exception Logged in Service";

            //Return Successful Response
            return this.Request.CreateResponse(HttpStatusCode.OK, responseText);

        }
        public async Task<IHttpActionResult> GetInactiveIncidentInfos(int historyHours)
        {
            Services.Log.Info("Inactive Incident Log Requested [API]");
            List<Incident> dbIncidentQuery = new List<Incident>();
            List<IncidentInfo> inactiveIncidentCollection = new List<IncidentInfo>();

            stranddContext context = new stranddContext();
            DateTime floorDate;

            if (historyHours == null || historyHours < 0) { floorDate = Convert.ToDateTime("01/01/2001"); }
            else
            {
                TimeSpan spanBuffer = new TimeSpan(historyHours, 0, 0);
                floorDate = (DateTime.Now).Subtract(spanBuffer);
            }

            //Loading List of Active Incidents from DB Context
            dbIncidentQuery = await context.Incidents
                .Where(b => b.StatusCode == "CANCELLED" || b.StatusCode == "DECLINED" || b.StatusCode == "COMPLETED")
                .Where(x => x.CreatedAt >= floorDate)
                .ToListAsync<Incident>();

            foreach (Incident dbIncident in dbIncidentQuery) { inactiveIncidentCollection.Add(new IncidentInfo(dbIncident)); }

            //Return Successful Response
            Services.Log.Info("Inactive Incident Log Returned [API]");
            return Ok(inactiveIncidentCollection);
        }
        public async Task<HttpResponseMessage> UpdateCosting(IncidentCostingRequest costingRequest)
        {

            Services.Log.Info("Update Incident Costing Request [API]");
            string responseText;

            IncidentInfo infoOutput;

            //Get Defaults From Configuration and overrride from Request (To be Modified in Expansions)

            string companyGUID = (costingRequest.ProviderIdentifierGUID == null || costingRequest.ProviderIdentifierGUID == "") ? WebConfigurationManager.AppSettings["RZ_DefaultProviderCompany"] : costingRequest.ProviderIdentifierGUID;
            string policyGUID = (costingRequest.CustomerIdentifierGUID == null || costingRequest.CustomerIdentifierGUID == "") ? WebConfigurationManager.AppSettings["RZ_DefaultCustomerPolicy"] : costingRequest.CustomerIdentifierGUID;

            stranddContext context = new stranddContext();

            CostingSlab providerSlab = new CostingSlab();
            providerSlab = await (from r in context.CostingSlabs where (r.IdentifierGUID == companyGUID && r.ServiceType == costingRequest.ServiceType && r.Status == "CURRENT") select r).FirstOrDefaultAsync();
            if (providerSlab == null) { responseText = "Provider Company Costing Slab Not Found"; Services.Log.Warn(responseText); }
            else { IncidentController.SaveCostingSlabAsync(costingRequest, providerSlab, "PROVIDER", Services); }

            CostingSlab customerSlab = new CostingSlab();
            customerSlab = await (from r in context.CostingSlabs where (r.IdentifierGUID == policyGUID && r.ServiceType == costingRequest.ServiceType && r.Status == "CURRENT") select r).FirstOrDefaultAsync();

            if (customerSlab == null) { responseText = "Customer Policy Costing Slab Not Found"; Services.Log.Warn(responseText); return this.Request.CreateResponse(HttpStatusCode.NotFound, responseText); }
            else
            {
                await IncidentController.SaveCostingSlabAsync(costingRequest, customerSlab, "CUSTOMER", Services);
                responseText = "Incident Costings Request Processed";

                infoOutput = new IncidentInfo(costingRequest.IncidentGUID);

                //Web Client Notifications
                IHubContext hubContext = Services.GetRealtime<IncidentHub>();
                hubContext.Clients.All.updateIncidentCostingAdmin(infoOutput);
                Services.Log.Info("Connected Clients Generated");
            }

            return this.Request.CreateResponse(HttpStatusCode.OK, responseText);
        }
        public HttpResponseMessage GenerateIncidentExcel()
        {
            var queryStrings = Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);

            string timeZoneDisplayString;
            TimeZoneInfo timeZoneRequest;
            DateTimeOffset startTime;
            DateTimeOffset endTime;

            string responseText;
            responseText = "Excel Output Requested -";



            if (queryStrings.ContainsKey("timezone"))
            {
                try
                {
                    timeZoneRequest = TimeZoneInfo.FindSystemTimeZoneById(queryStrings["timezone"]);
                }
                catch (TimeZoneNotFoundException)
                {
                    Services.Log.Warn("Unable to retrieve the requested Time Zone. Reverting to UTC.");
                    timeZoneRequest = TimeZoneInfo.Utc;
                }
                catch (InvalidTimeZoneException)
                {
                    Services.Log.Warn("Unable to retrieve the requested Time Zone. Reverting to UTC.");
                    timeZoneRequest = TimeZoneInfo.Utc;
                }
            }
            else
            {
                Services.Log.Warn("No Time Zone Requested. Reverting to UTC.");
                timeZoneRequest = TimeZoneInfo.Utc;
            }

            if (queryStrings.ContainsKey("starttime"))
            {
                if (!DateTimeOffset.TryParse(queryStrings["starttime"], out startTime))
                {
                    Services.Log.Warn("Unable to parse the requested Start Time [" + queryStrings["starttime"] + "]. Reverting to Min Value.");
                }
            }
            else
            {
                startTime = DateTimeOffset.MinValue;
                Services.Log.Warn("No Start Time Requested. Reverting to Min Value.");
            }

            if (queryStrings.ContainsKey("endtime"))
            {
                if (!DateTimeOffset.TryParse(queryStrings["endtime"], out endTime))
                {
                    endTime = DateTimeOffset.MaxValue;
                    Services.Log.Warn("Unable to parse the requested End Time [" + queryStrings["endtime"] + "]. Reverting to Max Value.");
                }
            }
            else
            {
                endTime = DateTimeOffset.MaxValue;
                Services.Log.Warn("No End Time Requested. Reverting to Max Value.");
            }

            timeZoneDisplayString = "[" + timeZoneRequest.DisplayName.ToString() + "]";
            responseText += " TimeZone " + timeZoneDisplayString;
            responseText += " StartTime [" + startTime.ToString() + "]";
            responseText += " EndTime [" + endTime.ToString() + "]";
            responseText += " [API]";

            Services.Log.Info(responseText);

            List<Incident> dbIncidentCollection = new List<Incident>();
            List<IncidentExcelData> fullIncidentCollection = new List<IncidentExcelData>();


            stranddContext context = new stranddContext();


            //     List<Incident> objincident = context.Incidents.ToList();

            //Loading List of Incidents from DB Context
            dbIncidentCollection = context.Incidents
                .Where(a => a.CreatedAt >= startTime)
               .Where(a => a.CreatedAt <= endTime)
                .ToList();

            foreach (Incident dbIncident in dbIncidentCollection) { fullIncidentCollection.Add(new IncidentExcelData(dbIncident)); }

            string strData = string.Empty;
            strData = "IncidentGUID,TimeStamp,IncidentStatus,ArrivalTime,ConcertoCaseID,JobCode,ConfirmedAdminName,CustomerName,CustomerPhone,VehicleRegistration,VehicleDescription,StaffNotes,ServiceFee,CustomerComments,CustomerRating,PaymentStatus,PaymentAmount,PaymentPlatform";

            DataTable table = ExcelHelper.ConvertListToDataTable(fullIncidentCollection);
            ExcelHelper objexcel = new ExcelHelper();

            return objexcel.GetExcel(table, strData, "IncidentHistoryReport");

        }
        public static async Task SaveCostingSlabAsync(IncidentCostingRequest costingRequest, CostingSlab inputSlab, string slabType, ApiServices Services)
        {

            string responseText;

            //Get Tax Rate
            decimal taxZoneRate = System.Convert.ToDecimal(WebConfigurationManager.AppSettings["RZ_DefaultTaxZoneRate"]);

            //Calulate Provider
            decimal calculatedBaseServiceCost =
                (costingRequest.ServiceKilometers > inputSlab.BaseKilometersFloor) ? (inputSlab.BaseCharge + ((costingRequest.ServiceKilometers - inputSlab.BaseKilometersFloor)) * inputSlab.ExtraKilometersCharge) : inputSlab.BaseCharge;
            decimal calculatedSubtotal = calculatedBaseServiceCost + costingRequest.ParkingCosts + costingRequest.TollCosts + costingRequest.OtherCosts - costingRequest.OffsetDiscount;
            decimal calculatedTaxes = (calculatedSubtotal * taxZoneRate) / 100;
            decimal calculatedTotalCost = calculatedSubtotal + calculatedTaxes;

            stranddContext context = new stranddContext();

            //Check for Provider Incident in IncidentCosting
            IncidentCosting updateIncidentCosting = await (from r in context.IncidentCostings where (r.IncidentGUID == costingRequest.IncidentGUID && r.Type == slabType) 
                                                          select r).FirstOrDefaultAsync();

            if (updateIncidentCosting != null)
            {
                updateIncidentCosting.IdentifierGUID = inputSlab.IdentifierGUID;
                updateIncidentCosting.ServiceType = costingRequest.ServiceType;
                updateIncidentCosting.CostingSlabGUID = inputSlab.Id;
                updateIncidentCosting.TaxZoneRate = taxZoneRate;
                updateIncidentCosting.ServiceKilometers = costingRequest.ServiceKilometers;
                updateIncidentCosting.ParkingCosts = costingRequest.ParkingCosts;
                updateIncidentCosting.TollCosts = costingRequest.TollCosts;
                updateIncidentCosting.OtherCosts = costingRequest.OtherCosts;
                updateIncidentCosting.OffsetDiscount = (slabType=="CUSTOMER") ? costingRequest.OffsetDiscount : 0;
                updateIncidentCosting.CalculatedSubtotal = calculatedSubtotal;
                updateIncidentCosting.CalculatedBaseServiceCost = calculatedBaseServiceCost;
                updateIncidentCosting.CalculatedTaxes = calculatedTaxes;
                updateIncidentCosting.CalculatedTotalCost = calculatedTotalCost;

                await context.SaveChangesAsync();

                responseText = "IncidentCostings (" + slabType + ") Successfully Updated";
            }

            else
            {
                IncidentCosting newIncidentCosting = new IncidentCosting
                {
                    Id = Guid.NewGuid().ToString(),
                    IncidentGUID = costingRequest.IncidentGUID,
                    IdentifierGUID = inputSlab.IdentifierGUID,
                    Type = slabType,
                    ServiceType = costingRequest.ServiceType,
                    CostingSlabGUID = inputSlab.Id,
                    TaxZoneRate = taxZoneRate,
                    ServiceKilometers = costingRequest.ServiceKilometers,
                    ParkingCosts = costingRequest.ParkingCosts,
                    TollCosts = costingRequest.TollCosts,
                    OtherCosts = costingRequest.OtherCosts,
                    OffsetDiscount = (slabType == "CUSTOMER") ? costingRequest.OffsetDiscount : 0,
                    CalculatedSubtotal = calculatedSubtotal,
                    CalculatedBaseServiceCost = calculatedBaseServiceCost,
                    CalculatedTaxes = calculatedTaxes,
                    CalculatedTotalCost = calculatedTotalCost

                };
                context.IncidentCostings.Add(newIncidentCosting);
                await context.SaveChangesAsync();

                responseText = "IncidentCostings (" + slabType + ") Successfully Generated";
            }

        }
Ejemplo n.º 34
0
        public IncidentInfo(Incident baseIncident)
        {
            //Create UserInfo Object based upon Passed in ProviderUserID [Call to DB Made in Constructor]
            AccountInfo lookupUser = new AccountInfo(baseIncident.ProviderUserID);

            //Create VehicleInfo Object based upon Passed in VehicleGUID [Call to DB Made in Constructor]
            VehicleInfo lookupVehicle = new VehicleInfo(baseIncident.VehicleGUID);

            stranddContext context = new stranddContext();

            IncidentCosting lookupIncidentCosting = context.IncidentCostings
                                                    .Where(u => u.IncidentGUID == baseIncident.Id)
                                                    .Where(v => v.Type == "CUSTOMER")
                                                    .FirstOrDefault();

            //Payment Information
            List <Payment> lookupPaymentList = context.Payments
                                               .Where(u => u.IncidentGUID == baseIncident.Id)
                                               .ToList <Payment>();

            string paymentMethodString = null;

            if (lookupPaymentList.Count != 0)
            {
                if (lookupPaymentList.Count > 1)
                {
                    paymentMethodString = "Multiple Payments [" + lookupPaymentList.Count.ToString() + "]";
                }
                else
                {
                    paymentMethodString = lookupPaymentList[0].PaymentPlatform;
                }
            }

            decimal sumPaymentTotal = lookupPaymentList.Sum(a => a.Amount);

            //Confirmed Admin Information
            HistoryEvent lookupAdminEvent = context.HistoryLog
                                            .Where(u => u.ReferenceID == baseIncident.Id)
                                            .OrderByDescending(d => d.CreatedAt)
                                            .Where(v => v.Code == "INCIDENT_STATUS_ADMIN")
                                            .Where(x => x.Attribute == "CONFIRMED" || x.Attribute == "OPERATOR-ASSIGNED")
                                            .FirstOrDefault();

            AccountInfo lookupAdmin;

            if (lookupAdminEvent != null)
            {
                lookupAdmin = new AccountInfo(lookupAdminEvent.AdminID);
            }
            else
            {
                lookupAdmin = new AccountInfo(null);
            }

            this.IncidentGUID          = baseIncident.Id;
            this.IncidentUserInfo      = lookupUser;
            this.IncidentVehicleInfo   = lookupVehicle;
            this.ConfirmedAdminAccount = lookupAdmin;
            this.JobCode             = baseIncident.JobCode;
            this.LocationObj         = (baseIncident.LocationObj != null) ? JsonConvert.DeserializeObject <IncidentLocation>(baseIncident.LocationObj) : null;
            this.ConcertoCaseID      = baseIncident.ConcertoCaseID;
            this.StatusCode          = baseIncident.StatusCode;
            this.Rating              = baseIncident.Rating;
            this.ServiceFee          = baseIncident.ServiceFee;
            this.CoordinateX         = baseIncident.CoordinateX;
            this.CoordinateY         = baseIncident.CoordinateY;
            this.ProviderArrivalTime = baseIncident.ProviderArrivalTime;
            this.CreatedAt           = baseIncident.CreatedAt;
            this.UpdatedAt           = baseIncident.UpdatedAt;
            this.CustomerComments    = baseIncident.CustomerComments;
            this.StaffNotes          = baseIncident.StaffNotes;
            this.PaymentAmount       = sumPaymentTotal;     //(lookupPayment != null) ? lookupPayment.Amount : 0;
            this.PaymentMethod       = paymentMethodString; //(lookupPayment != null) ? lookupPayment.PaymentPlatform : null;
            this.AdditionalDetails   = baseIncident.AdditionalDetails;

            //retrive data IncidentCostings
            this.ServiceType               = (lookupIncidentCosting != null) ? lookupIncidentCosting.ServiceType   : null;
            this.ServiceKilometers         = (lookupIncidentCosting != null) ? lookupIncidentCosting.ServiceKilometers : 0;
            this.CalculatedBaseServiceCost = (lookupIncidentCosting != null) ? lookupIncidentCosting.CalculatedBaseServiceCost : 0;
            this.ParkingCosts              = (lookupIncidentCosting != null) ? lookupIncidentCosting.ParkingCosts : 0;
            this.TollCosts           = (lookupIncidentCosting != null) ? lookupIncidentCosting.TollCosts : 0;
            this.OtherCosts          = (lookupIncidentCosting != null) ? lookupIncidentCosting.OtherCosts : 0;
            this.OffsetDiscount      = (lookupIncidentCosting != null) ? lookupIncidentCosting.OffsetDiscount : 0;
            this.CalculatedSubtotal  = (lookupIncidentCosting != null) ? lookupIncidentCosting.CalculatedSubtotal : 0;
            this.TaxZoneRate         = (lookupIncidentCosting != null) ? lookupIncidentCosting.TaxZoneRate : 0;
            this.CalculatedTaxes     = (lookupIncidentCosting != null) ? lookupIncidentCosting.CalculatedTaxes : 0;
            this.CalculatedTotalCost = (lookupIncidentCosting != null) ? lookupIncidentCosting.CalculatedTotalCost : 0;
        }
        public async Task<HttpResponseMessage> UpdateDetails(IncidentDetailsRequest detailsRequest)
        {
            Services.Log.Info("Incident Details Update Request [API]");
            string responseText;

            stranddContext context = new stranddContext();

            //Retrieve Incident
            Incident updateIncident = await (from r in context.Incidents where (r.Id == detailsRequest.IncidentGUID) select r).FirstOrDefaultAsync();

            //Find the Incident to Edit and return Bad Response if not found
            if (updateIncident != null)
            {
                //Check for Submitted Status and Update
                if (detailsRequest.Notes != null)
                {
                    updateIncident.StaffNotes = detailsRequest.Notes;
                }

                //Check for Submitted Pricing and Update
                if (detailsRequest.ConcertoCaseID != null)
                {
                    updateIncident.ConcertoCaseID = detailsRequest.ConcertoCaseID;
                }
            }
            else
            {
                // Return Failed Response
                responseText = "Incident [" + detailsRequest.IncidentGUID + "] is not found in the system";
                Services.Log.Warn(responseText);
                return this.Request.CreateResponse(HttpStatusCode.BadRequest, responseText);
            }

            //Save record
            await context.SaveChangesAsync();
            responseText = "Incident [" + updateIncident.Id + "] Details Updated";
            Services.Log.Info(responseText);

            //Notifying Connect WebClients with IncidentInfo Package
            IHubContext hubContext = Services.GetRealtime<IncidentHub>();
            hubContext.Clients.All.updateIncidentDetailsAdmin(new IncidentInfo(updateIncident));
            Services.Log.Info("Connected Clients Updated");

            //Return Successful Response
            return this.Request.CreateResponse(HttpStatusCode.OK, responseText);
        }
        public async Task<HttpResponseMessage> UpdatePayment(IncidentPaymentRequest paymentRequest)
        {
            Services.Log.Info("Incident Payment Update Request [API]");
            string responseText;

            stranddContext context = new stranddContext();

            //Retrieve Incident
            Incident updateIncident = await (from r in context.Incidents where (r.Id == paymentRequest.IncidentGUID) select r).FirstOrDefaultAsync();

            //Find the Incident to Edit and return Bad Response if not found
            if (updateIncident != null)
            {
                string guidnew = Guid.NewGuid().ToString();
                //Check for Submitted Payment Amount             
                Payment newPayment = new Payment
                {
                    Id = guidnew,
                    PaymentPlatform = paymentRequest.PaymentMethod,
                    PlatformPaymentID = guidnew,
                    Amount = paymentRequest.PaymentAmount,
                    Fees = -1,
                    ProviderUserID = IncidentInfo.GetProviderID(paymentRequest.IncidentGUID),
                    Status = "Admin-Entered",
                    BuyerName = "NONE",
                    BuyerEmail = "NONE",
                    BuyerPhone = "NONE",
                    Currency = "INR",
                    AuthenticationCode = "NONE",
                    IncidentGUID = paymentRequest.IncidentGUID
                };

                if (paymentRequest.PaymentMethod == "PAYMENT-CASH")
                {
                    newPayment.PaymentPlatform = "Cash Payment (Admin)";
                    newPayment.Status = "Paid";
                }

                if (paymentRequest.PaymentMethod == "PAYMENT-FAIL")
                {
                    newPayment.PaymentPlatform = "Payment Failure (Admin)";
                    newPayment.Status = "FAILED";
                }

                if (paymentRequest.PaymentAmount == 0)
                {
                    newPayment.Amount = -1;
                }

                //Save record
                context.Payments.Add(newPayment);
                await context.SaveChangesAsync();
                responseText = "Incident [" + updateIncident.Id + "] Payment Status Updated";
                Services.Log.Info(responseText);

                //Notify Particular Connected User through SignalR
                IHubContext hubContext = Services.GetRealtime<IncidentHub>();
                hubContext.Clients.Group(updateIncident.ProviderUserID).updateMobileClientStatus(newPayment.GetCustomerPushObject());
                Services.Log.Info("Mobile Client [" + updateIncident.ProviderUserID + "] Status Update Payload Sent");

                //Web Client Notifications
                hubContext.Clients.All.saveNewPayment(newPayment);
                Services.Log.Info("Connected Clients Updated");

                //Return Successful Response
                return this.Request.CreateResponse(HttpStatusCode.OK, responseText);
            }
            else
            {
                // Return Failed Response
                responseText = "Incident [" + paymentRequest.IncidentGUID + "] is not found in the system";
                Services.Log.Warn(responseText);
                return this.Request.CreateResponse(HttpStatusCode.BadRequest, responseText);
            }

        }
        public async Task<HttpResponseMessage> UpdateStatus(IncidentStatusRequest statusRequest)
        {
            Services.Log.Info("Incident Status Update Request [API]");
            string responseText;

            stranddContext context = new stranddContext();

            //Retrieve Incident
            Incident updateIncident = await (from r in context.Incidents where (r.Id == statusRequest.IncidentGUID) select r).FirstOrDefaultAsync();

            //Find the Incident to Edit and return Bad Response if not found
            if (updateIncident != null)
            {
                //Check for Submitted Status and Update
                if (statusRequest.NewStatusCode != null)
                {
                    updateIncident.StatusCode = statusRequest.NewStatusCode;
                    updateIncident.StatusCustomerConfirm = false;
                    updateIncident.StatusProviderConfirm = false;
                }

                //Check for Submitted Pricing and Update
                if (statusRequest.ServiceFee != 0)
                {
                    updateIncident.ServiceFee = statusRequest.ServiceFee;

                }

                //Check if ETA and Save Arrival Time
                if (statusRequest.ETA != 0)
                {
                    if (statusRequest.NewStatusCode == "ARRIVED")
                    {
                        updateIncident.ProviderArrivalTime = System.DateTime.Now;
                    }
                    else
                    {
                        DateTimeOffset? priorETA = updateIncident.ProviderArrivalTime;
                        updateIncident.ProviderArrivalTime = System.DateTime.Now.AddMinutes(statusRequest.ETA);

                        if (priorETA != null)
                        {
                            DateTimeOffset compareETA = (DateTimeOffset)priorETA;

                            compareETA = compareETA.AddMinutes(Convert.ToInt32(WebConfigurationManager.AppSettings["RZ_DelayMinuteBuffer"]));
                            if (DateTimeOffset.Compare(compareETA, (DateTimeOffset)updateIncident.ProviderArrivalTime) < 0) { statusRequest.Delayed = true; }
                        }
                    }
                }
            }
            else
            {
                // Return Failed Response
                responseText = "Incident [" + statusRequest.IncidentGUID + "] is not found in the system";
                Services.Log.Warn(responseText);
                return this.Request.CreateResponse(HttpStatusCode.BadRequest, responseText);
            }

            //Save record
            await context.SaveChangesAsync();
            responseText = "Incident [" + updateIncident.Id + "] Status Updated" + " to Code [" + updateIncident.StatusCode + "]";
            Services.Log.Info(responseText);

            ProcessStatusRequestBehavior(statusRequest, updateIncident, Services);

            //Return Successful Response
            return this.Request.CreateResponse(HttpStatusCode.OK, responseText);
        }
        public async Task<HttpResponseMessage> CustomerCancel(IncidentStatusRequest statusRequest)
        {
            Services.Log.Info("Incident Cancellation Request [API]");
            string responseText;

            // Get the logged-in user.
            var currentUser = this.User as ServiceUser;

            stranddContext context = new stranddContext();

            //Retrieve Incident
            Incident updateIncident = await (from r in context.Incidents where (r.Id == statusRequest.IncidentGUID) select r).FirstOrDefaultAsync();

            //Find the Incident to Cancel and return Bad Response if not found
            if (updateIncident == null)
            {
                // Return Failed Response
                responseText = "Incident [" + statusRequest.IncidentGUID + "] is not found in the system";
                Services.Log.Warn(responseText);
                return this.Request.CreateResponse(HttpStatusCode.BadRequest, responseText);
            }
            else
            {

                updateIncident.StatusCode = "CANCELLED";
                updateIncident.StatusCustomerConfirm = true;
                updateIncident.StatusProviderConfirm = false;

                //Save record
                await context.SaveChangesAsync();
                responseText = "Incident [" + updateIncident.Id + "] Cancelled by Customer";
                Services.Log.Info(responseText);

                //Notifying Connect WebClients with IncidentInfo Package
                IHubContext hubContext = Services.GetRealtime<IncidentHub>();
                hubContext.Clients.All.updateIncidentStatusCustomerCancel(new IncidentInfo(updateIncident));
                Services.Log.Info("Connected Clients Updated");

                await HistoryEvent.logHistoryEventAsync("INCIDENT_CANCEL_CUSTOMER", null, updateIncident.Id, null, currentUser.Id, null);
                //Return Successful Response
                return this.Request.CreateResponse(HttpStatusCode.OK, responseText);
            }

        }