Exemplo n.º 1
0
        // POST api/calendarapi
        public HttpResponseMessage Post([FromBody] ScheduleDTO scheduleDTO)
        {
            if (ModelState.IsValid)
            {
                var recurringCalendarEvent = MapperFacade.MapperConfiguration.Map <ScheduleDTO, Schedule>(scheduleDTO);
                //recurringCalendarEvent.Id = Guid.NewGuid(); //Assign new ID on save.

                //Ensure unsupported options are not created
                if (scheduleDTO.Frequency != 0 && scheduleDTO.Frequency != 1 && scheduleDTO.Frequency != 2)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Frequency not supported. Must be once off (0), Daily (1) or Weekly(2)"));
                }

                //Lookup Business and attach, so that no updates or inserts are performed on BusinessType lookup table
                recurringCalendarEvent.UserProfile = db.UserProfiles.Single(u => u.Email == User.Identity.Name);
                if (recurringCalendarEvent.UserProfile == null)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Userprofile is null"));
                }
                try
                {
                    db.Schedules.Add(recurringCalendarEvent);
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    var mes = ex.Message;
                }
                return(Request.CreateResponse(HttpStatusCode.Created));
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }
Exemplo n.º 2
0
        // POST api/calendarapi
        public HttpResponseMessage Post([FromBody] CalendarEventDTO calendarEventDTO)
        {
            if (ModelState.IsValid &&
                calendarEventDTO.StartTime >= DateTime.Now.AddHours(-1) &&  //Ensure entry is a valid start date and finish date
                calendarEventDTO.FinishTime > calendarEventDTO.StartTime)
            {
                var calendarEvent = Mapper.Map <CalendarEventDTO, CalendarEvent>(calendarEventDTO);
                calendarEvent.Id = Guid.NewGuid(); //Assign new ID on save.

                //Lookup Business and attach, so that no updates or inserts are performed on BusinessType lookup table
                calendarEvent.UserProfile = db.UserProfiles.Single(u => u.Email == User.Identity.Name);
                if (calendarEvent.UserProfile == null)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Userprofile is null"));
                }


                db.CalendarEvents.Add(calendarEvent);
                db.SaveChanges();

                calendarEventDTO = Mapper.Map <CalendarEvent, CalendarEventDTO>(calendarEvent);
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, calendarEventDTO);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = calendarEventDTO.Id }));
                return(response);
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }
Exemplo n.º 3
0
        // PUT api/BusinessTypeAPI/5
        public HttpResponseMessage PutBusinessType(int id, BusinessType businesstype)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            if (id != businesstype.Id)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            db.Entry(businesstype).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        public HttpResponseMessage CancelShift(Guid Id, ShiftChangeActionDTO shiftCancelDTO)
        {
            var shift = db.Shifts.Find(Id);

            if (shift == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Shift not found"));
            }

            //Only the staff member assigned to the shift can request to cancel the shift
            if (ClaimsAuthorization.CheckAccess("Get", "BusinessId", shift.Roster.BusinessLocation.Business.Id.ToString()) ||
                shift.Employee.UserProfile.Email != User.Identity.Name)
            {
                if (shiftCancelDTO.Reason == String.Empty)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Reason cannot be blank"));
                }

                //Check to see if there is already a pending cancellation request
                var shiftCancelRequest = db.ShiftChangeRequests.Where(sc => sc.Type == ShiftRequestType.Cancel &&
                                                                      sc.Shift.Id == Id &&
                                                                      sc.Status == RequestStatus.Pending);
                if (shiftCancelRequest.Count() > 0)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Existing cancellation request already for shift id:" + Id.ToString()));
                }

                ShiftChangeRequest shiftChangeRequest = new ShiftChangeRequest
                {
                    Id          = Guid.NewGuid(),
                    Reason      = shiftCancelDTO.Reason,
                    Shift       = shift,
                    Type        = ShiftRequestType.Cancel,
                    Status      = RequestStatus.Pending,
                    CreatedDate = WebUI.Common.Common.DateTimeNowLocal(),
                    CreatedBy   = shift.Employee
                };

                //Get all managers for this busiess location
                var managers = db.Employees.Where(m => m.IsAdmin == true && m.BusinessLocation.Id == shift.Roster.BusinessLocation.Id);
                foreach (var mgr in managers)
                {
                    if (mgr.UserProfile != null)
                    {
                        //Send notifications to managers of the affected business location information that the employee has requested to cancel a shift
                        MessagingService.ShiftCancelRequest(mgr.UserProfile.Email, mgr.UserProfile.FirstName, shift.Employee.UserProfile.FirstName + ' ' + shift.Employee.UserProfile.LastName, shift.InternalLocation.BusinessLocation.Name, shift.StartTime, shift.FinishTime);
                    }
                }


                db.ShiftChangeRequests.Add(shiftChangeRequest);
                db.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.Created, shiftChangeRequest.Id));
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
Exemplo n.º 5
0
        public HttpResponseMessage ApproveTimesheetEntry([FromBody] TimesheetEntryDTO timesheetEntryDTO)
        {
            if (Is <TimesheetFeature> .Enabled)
            {
                TimesheetEntry timesheetEntry = db.TimesheetEntries.Find(timesheetEntryDTO.Id);
                if (timesheetEntry == null)
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
                }

                var email = HttpContext.Current.User.Identity.Name;

                UserProfile userProfile = db.UserProfiles.FirstOrDefault(usr => usr.Email == email);
                if (userProfile == null)
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
                }

                //Check business rules
                if (!timesheetEntryDTO.FinishDateTime.HasValue)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Finish time for shift must be specified"));
                }

                if (timesheetEntryDTO.FinishDateTime.Value < timesheetEntryDTO.StartDateTime)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Finish time for shift must be AFTER start time"));
                }

                if (ClaimsAuthorization.CheckAccess("Put", "BusinessId", timesheetEntry.TimeCard.BusinessLocation.Business.Id.ToString()))
                {
                    timesheetEntry.Approved         = true;
                    timesheetEntry.ApprovedDateTime = WebUI.Common.Common.DateTimeNowLocal();
                    timesheetEntry.ApprovedBy       = userProfile;
                    timesheetEntry.StartDateTime    = timesheetEntryDTO.StartDateTime;
                    timesheetEntry.FinishDateTime   = timesheetEntryDTO.FinishDateTime;

                    try
                    {
                        db.Entry(timesheetEntry).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                    catch (DbUpdateConcurrencyException ex)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
                    }

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotImplemented));
            }
        }
        public ExternalBroadcastDTO ExternalJobPosting([FromBody] ExternalBroadcastDTO model)
        {
            var status = 0;


            ExternalShiftBroadcast externalBrodcaseShift = new ExternalShiftBroadcast();

            externalBrodcaseShift.Id          = Guid.NewGuid();
            externalBrodcaseShift.Description = model.Description;
            externalBrodcaseShift.Wage        = model.Wage;
            externalBrodcaseShift.Status      = ExternalShiftStatus.Pending;

            db.ExternalShiftBroadcasts.Add(externalBrodcaseShift);
            status = db.SaveChanges();

            //check if any Qualificatoin is selected.
            if (model.Qualification != null)
            {
                foreach (var item in model.Qualification)
                {
                    ExternalShiftQualification shiftQualification = new ExternalShiftQualification();
                    shiftQualification.Id = Guid.NewGuid();
                    shiftQualification.QualificationslookupQualificationId = item.ValueGuid;
                    shiftQualification.ExternalShiftBroadcastId            = externalBrodcaseShift.Id;
                    db.ExternalShiftQualifications.Add(shiftQualification);
                    db.SaveChanges();
                }
            }


            foreach (var item in model.BroadcastedOpenShiftList)
            {
                var shiftResult = db.Shifts.Where(a => a.Id == item.BroadcastedOpenShiftId).FirstOrDefault();
                shiftResult.ExternalShiftBroadcastId = externalBrodcaseShift.Id;
                db.SaveChanges();
            }

            //Check if any Skill is selected.
            if (model.Skills != null)
            {
                foreach (var item in model.Skills)
                {
                    ExternalShiftSkills skills = new ExternalShiftSkills();
                    skills.Id = Guid.NewGuid();
                    skills.ExternalShiftBroadcastId = externalBrodcaseShift.Id;
                    skills.IndustrySkillsId         = item.ValueGuid;
                    db.ExternalShiftSkills.Add(skills);
                    db.SaveChanges();
                }
            }

            ExternalBroadcastDTO externalBroadCastDTO = MapperFacade.MapperConfiguration.Map <ExternalShiftBroadcast, ExternalBroadcastDTO>(externalBrodcaseShift);

            return(externalBroadCastDTO);
        }
Exemplo n.º 7
0
        // GET api/AccountAPI/5
        //Get method used to ValidateUser upon login/authentication, should only be called on login
        internal LoginModelDTO GetAccount(string email, string passwordHash)
        {
            var userProfile = db.UserProfiles.FirstOrDefault(Usr => Usr.Email == email);

            if (userProfile == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.ExpectationFailed, "Account email/password incorrect"));
            }
            else if (userProfile.Membership.IsConfirmed == false)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Account is not confirmed"));
            }
            else if (userProfile.Membership.IsLockedOut == true)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Account is locked"));
            }

            String hashedPassword        = userProfile.Membership.Password;
            bool   verificationSucceeded = (hashedPassword != null && hashedPassword == passwordHash);

            if (verificationSucceeded)
            {
                userProfile.Membership.PasswordFailuresSinceLastSuccess = 0;
                userProfile.Membership.LastLoginDate = WebUI.Common.Common.DateTimeNowLocal();
            }
            else //failed login attempt
            {
                userProfile.Membership.LastPasswordFailureDate = WebUI.Common.Common.DateTimeNowLocal();

                int failures = userProfile.Membership.PasswordFailuresSinceLastSuccess;
                if (failures < UserCredentials.MaxInvalidPasswordAttempts)
                {
                    ++userProfile.Membership.PasswordFailuresSinceLastSuccess;
                }
                else if (failures >= UserCredentials.MaxInvalidPasswordAttempts)
                {
                    userProfile.Membership.LastLockoutDate = WebUI.Common.Common.DateTimeNowLocal();
                    userProfile.Membership.IsLockedOut     = true;
                }
            }

            db.SaveChanges();

            if (verificationSucceeded)
            {
                return new LoginModelDTO {
                           Email = userProfile.Email
                }
            }
            ;
            else
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Invalid password"));
            }
        }
        public HttpResponseMessage PostShiftTemplate(ShiftTemplateDTO shiftTemplateDTO)
        {
            if (ModelState.IsValid)
            {
                if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", shiftTemplateDTO.BusinessLocationId.ToString()))
                {
                    //Business rules
                    if (shiftTemplateDTO.StartTime > shiftTemplateDTO.FinishTime && !shiftTemplateDTO.FinishNextDay)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Shift start time must be before end time"));
                    }
                    //Role selected must be applicable to the Employee
                    if (shiftTemplateDTO.EmployeeId != null && shiftTemplateDTO.RoleId.HasValue && db.Employees.Find(shiftTemplateDTO.EmployeeId).Roles.FirstOrDefault(r => r.Id == shiftTemplateDTO.RoleId) == null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Employee does not have the role specified"));
                    }

                    var shiftTemplate = MapperFacade.MapperConfiguration.Map <ShiftTemplateDTO, ShiftTemplate>(shiftTemplateDTO);
                    shiftTemplate.Id = Guid.NewGuid(); //Assign new ID on save.

                    shiftTemplate.Enabled = true;      //default to enabled

                    shiftTemplate.BusinessLocation = db.BusinessLocations.Find(shiftTemplateDTO.BusinessLocationId);
                    if (shiftTemplateDTO.InternalLocationId.HasValue)
                    {
                        shiftTemplate.InternalLocation = db.InternalLocations.Find(shiftTemplateDTO.InternalLocationId);
                    }
                    if (shiftTemplateDTO.RoleId.HasValue)
                    {
                        shiftTemplate.Role = db.Roles.Find(shiftTemplateDTO.RoleId);
                    }
                    if (shiftTemplateDTO.EmployeeId.HasValue)
                    {
                        shiftTemplate.Employee = db.Employees.Find(shiftTemplateDTO.EmployeeId);
                    }

                    db.ShiftTemplates.Add(shiftTemplate);
                    db.SaveChanges();

                    shiftTemplateDTO = MapperFacade.MapperConfiguration.Map <ShiftTemplate, ShiftTemplateDTO>(shiftTemplate);
                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, shiftTemplateDTO);
                    response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = shiftTemplateDTO.Id }));
                    return(response);
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
                }
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }
Exemplo n.º 9
0
        public HttpResponseMessage CreateEmployerRequest(string id)
        {
            try
            {
                var busLocIdGd = Guid.Parse(id);
                var email      = HttpContext.Current.User.Identity.Name;

                //Check that employee email address is not already registered to the business
                if (db.Employees.Any(emp => emp.Email == email && emp.BusinessLocation.Id == busLocIdGd))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Email address already registered with business location"));
                }

                //Check that employee is not already linked to the business
                if (db.Employees.Any(emp => emp.UserProfile.Email == email && emp.BusinessLocation.Id == busLocIdGd))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "User is already registered with business location"));
                }

                //Check that a request hasn't already been lodged with the business previously
                if (db.EmployerRequests.Any(er => er.UserProfile.Email == email && er.BusinessLocation.Id == busLocIdGd))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Request has already been registered with business location"));
                }

                var empRequest = new EmployerRequest();

                empRequest.Id               = Guid.NewGuid();
                empRequest.CreatedDate      = WebUI.Common.Common.DateTimeNowLocal();
                empRequest.Status           = RequestStatus.Pending;
                empRequest.BusinessLocation = db.BusinessLocations.SingleOrDefault(b => b.Id == busLocIdGd);
                empRequest.UserProfile      = db.UserProfiles.SingleOrDefault(usr => usr.Email == email);

                db.EmployerRequests.Add(empRequest);

                db.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
        public int InsertCourt(
            BasketballCourt entity)
        {
            using (var dbContext = new DataModelDbContext())
            {
                dbContext.BasketballCourts.Add(entity).Entity.Uid = Guid.NewGuid();

                return(dbContext.SaveChanges());
            }
        }
Exemplo n.º 11
0
        // POST api/shiftapi
        //Create a new shift
        public HttpResponseMessage PostRoster([FromBody] RosterCreateDTO rosterCreateDTO)
        {
            if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", rosterCreateDTO.BusinessLocationId.ToString()))
            {
                if (ModelState.IsValid)
                {
                    Roster existingRoster = db.Rosters.Where(r => r.BusinessLocation.Id == rosterCreateDTO.BusinessLocationId &&
                                                             r.WeekStartDate == rosterCreateDTO.WeekStartDate.Date).FirstOrDefault();
                    //Business rules
                    if (existingRoster != null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "A roster already exists for the week starting " + rosterCreateDTO.WeekStartDate.ToShortDateString()));
                    }
                    //Cannot create a roster for a weeks starting in the past EXCEPT if it is the current week.
                    if (rosterCreateDTO.WeekStartDate.Date < WebUI.Common.Common.GetNextWeekday(WebUI.Common.Common.DateTimeNowLocal(), DayOfWeek.Monday).Date.AddDays(-7))
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "A roster cannot be created for a week starting in the past"));
                    }

                    var rosterList  = new List <Roster>();
                    var businessLoc = db.BusinessLocations.Find(rosterCreateDTO.BusinessLocationId);
                    var rosterWeek1 = CreateRosterForWeekStarting(rosterCreateDTO, businessLoc);
                    db.Rosters.Add(rosterWeek1);

                    //If rosters are being created for a month or fortnight.
                    if (rosterCreateDTO.RostersToCreate == RosterToCreateEnum.Fortnight ||
                        rosterCreateDTO.RostersToCreate == RosterToCreateEnum.Month)
                    {
                        var rosterWeek2 = CreateRosterForWeekStarting(rosterCreateDTO, businessLoc, 1);
                        db.Rosters.Add(rosterWeek2);
                        //For month, add remaining two weeks
                        if (rosterCreateDTO.RostersToCreate == RosterToCreateEnum.Month)
                        {
                            var rosterWeek3 = CreateRosterForWeekStarting(rosterCreateDTO, businessLoc, 2);
                            db.Rosters.Add(rosterWeek3);
                            var rosterWeek4 = CreateRosterForWeekStarting(rosterCreateDTO, businessLoc, 3);
                            db.Rosters.Add(rosterWeek4);
                        }
                    }

                    db.SaveChanges();

                    return(Request.CreateResponse(HttpStatusCode.Created));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have appropriate permission"));
            }
        }
        public HttpResponseMessage Post(BusinessPreferencesDTO businessPrefDTO)
        {
            if (ModelState.IsValid)
            {
                var businessPref = MapperFacade.MapperConfiguration.Map <BusinessPreferencesDTO, BusinessPreferences>(businessPrefDTO);
                businessPref.Id = Guid.NewGuid(); //Assign new ID on save.

                db.BusinessPreferences.Add(businessPref);
                db.SaveChanges();

                businessPrefDTO = MapperFacade.MapperConfiguration.Map <BusinessPreferences, BusinessPreferencesDTO>(businessPref);
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, businessPrefDTO);
                //response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = businessDTO.Id }));
                return(response);
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }
Exemplo n.º 13
0
        // POST api/<controller>
        public void Post([FromBody] ShiftBlockDTO shiftBlockDTO)
        {
            if (Is <ShiftBlockFeature> .Enabled)
            {
                if (ModelState.IsValid)
                {
                    if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", shiftBlockDTO.BusinessLocationId.ToString()))
                    {
                        //Business rules
                        if (shiftBlockDTO.StartTime > shiftBlockDTO.FinishTime && !shiftBlockDTO.FinishNextDay)
                        {
                            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "ShiftBlock start time must be before end time"));
                        }

                        var shiftBlock = MapperFacade.MapperConfiguration.Map <ShiftBlockDTO, ShiftBlock>(shiftBlockDTO);
                        shiftBlock.Id = Guid.NewGuid(); //Assign new ID on save.

                        shiftBlock.BusinessLocation = db.BusinessLocations.Find(shiftBlockDTO.BusinessLocationId);
                        shiftBlock.Role             = db.Roles.Find(shiftBlockDTO.RoleId);

                        db.ShiftBlocks.Add(shiftBlock);
                        db.SaveChanges();
                    }
                    else
                    {
                        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
                    }
                }
                else
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotImplemented));
            }
        }
Exemplo n.º 14
0
        public void AddTokenDetails([FromBody] PaymentDetailsDTO paymentDetailsDTO)
        {
            if (Is <PaymentFeature> .Enabled)
            {
                var employee = db.Employees.Find(paymentDetailsDTO.EmployeeID);
                if (employee != null)
                {
                    if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", employee.BusinessLocation.Id.ToString()))
                    {
                        var paymentdetails = new PaymentDetails
                        {
                            Id = Guid.NewGuid()
                        };

                        if (employee.PaymentDetails != null)
                        {
                            paymentdetails = employee.PaymentDetails;
                        }

                        paymentdetails.TokenCustomerID  = paymentDetailsDTO.TokenCustomerID;
                        paymentdetails.BusinessLocation = employee.BusinessLocation;
                        paymentdetails.CreatedDate      = WebUI.Common.Common.DateTimeNowLocal();

                        //If there is another payment detail from a different employee then delete
                        if (employee.BusinessLocation.PaymentDetails != null &&
                            employee.BusinessLocation.PaymentDetails.Employee.Id != employee.Id)
                        {
                            //employee.BusinessLocation.PaymentDetails.
                            db.Entry(employee.BusinessLocation.PaymentDetails).State = EntityState.Deleted;
                        }

                        employee.PaymentDetails = paymentdetails;

                        db.SaveChanges();
                    }
                    else
                    {
                        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
                    }
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotImplemented));
            }
        }
        // GET: api/CollegeDetails
        public QuestionList savequestiondetails()
        {
            QuestionList ee = new QuestionList();

            ee.Question     = "abcd";
            ee.QuestionType = "3";

            //ee.QuestionType = "2";
            using (DataModelDbContext dbContext = new DataModelDbContext())
            {
                dbContext.QuestionLists.Add(ee);
                dbContext.SaveChanges();
            }
            return(ee);
        }
        public int SaveReview(
            Rating entity)
        {
            using (var dbContext = new DataModelDbContext())
            {
                Rating existing = dbContext.Ratings.AsNoTracking()
                                  .Where(r => r.CourtUid == entity.CourtUid && r.PlayerUid == entity.PlayerUid)
                                  .SingleOrDefault();
                if (existing != null)
                {
                    dbContext.Ratings.Update(entity);
                }
                else
                {
                    dbContext.Ratings.Add(entity);
                }

                return(dbContext.SaveChanges());
            }
        }
        public HttpResponseMessage Put(Guid id, UserPreferencesDTO usrPrefDTO)
        {
            var         email      = HttpContext.Current.User.Identity.Name;
            UserProfile usrProfile = db.UserProfiles.FirstOrDefault(usr => usr.Email == email && usr.Id == id);

            if (usrProfile != null)
            {
                if (!ModelState.IsValid)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }
                try
                {
                    var userPreferences = db.UserPreferences.Find(usrPrefDTO.Id);

                    //If NULL, then retain any existing image data as no overrite is occurring (we don't pass back the whole image each time)
                    //This is a bit of a hack, best solution is to seperate out any uploaded documents as per this page (http://www.codeproject.com/Articles/658522/Storing-Images-in-SQL-Server-using-EF-and-ASP-NET)
                    if (usrPrefDTO.ImageData == null)
                    {
                        usrPrefDTO.ImageData = userPreferences.ImageData;
                        usrPrefDTO.ImageType = userPreferences.ImageType;
                    }

                    userPreferences = MapperFacade.MapperConfiguration.Map <UserPreferencesDTO, UserPreferences>(usrPrefDTO, userPreferences);

                    db.Entry(userPreferences).State = EntityState.Modified;

                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
        public HttpResponseMessage RejectShiftChangeRequest(string id, ShiftChangeActionDTO rejectDTO)
        {
            try
            {
                var requestId = Guid.Parse(id);
                var email     = HttpContext.Current.User.Identity.Name;

                var scRequest = db.ShiftChangeRequests.FirstOrDefault(er => er.Id == requestId && er.Status == RequestStatus.Pending);

                //Ensure user has "Put" manager permissions for the business location which the request corresponds to
                if (!ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", scRequest.Shift.Roster.BusinessLocation.Id.ToString()))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have permissions."));
                }

                if (scRequest == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Unable to find pending shift change request."));
                }

                //Update Request object
                scRequest.Status          = RequestStatus.Denied;
                scRequest.ActionedDate    = WebUI.Common.Common.DateTimeNowLocal();
                scRequest.ActionedComment = rejectDTO.Reason;
                //Attach the Employee record which matches the logged in user profile and business id.
                scRequest.ActionedBy = db.UserProfiles.FirstOrDefault(usr => usr.Email == email).Employees.FirstOrDefault(emp => emp.BusinessLocation.Id == scRequest.Shift.Roster.BusinessLocation.Id);

                db.SaveChanges();

                MessagingService.ShiftChangeRequestRejected(scRequest.CreatedBy.Email, scRequest.CreatedBy.FirstName, scRequest.Shift.StartTime.ToString() + " - " + scRequest.Shift.FinishTime.ToString() + " @ " + scRequest.Shift.InternalLocation.BusinessLocation.Name, scRequest.ActionedBy.FirstName + ' ' + scRequest.ActionedBy.LastName, rejectDTO.Reason);


                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
Exemplo n.º 19
0
        // POST api/RosterBroadcastapi
        //Create a new shift
        public HttpResponseMessage PutRosterBroadcast([FromBody] IEnumerable <RosterBroadcastDTO> rosterBroadcastListDTO)
        {
            //List to store all Employees who have had shifts broadcast
            List <EmployeeDTO> employees          = new List <EmployeeDTO>();
            List <EmployeeDTO> employeesNoProfile = new List <EmployeeDTO>();
            List <ShiftDTO>    openShifts         = new List <ShiftDTO>();

            if (rosterBroadcastListDTO.Count() > 0)
            {
                Guid businessLocationId = db.Rosters.Find(rosterBroadcastListDTO.First().Id).BusinessLocation.Id;

                if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", businessLocationId.ToString()))
                {
                    //TODO: test allbusiness logic
                    foreach (RosterBroadcastDTO rosterBroadcastDTO in rosterBroadcastListDTO)
                    {
                        int dow = (int)rosterBroadcastDTO.Day + 1; // SQL Day of week

                        IQueryable <Shift> shiftsToBroadcast = null;
                        if (rosterBroadcastDTO.LocationId != Guid.Empty)
                        {
                            //Do the updates to broadcast all shifts on each day for each location specified
                            shiftsToBroadcast = db.Shifts.Where(s => s.Roster.Id == rosterBroadcastDTO.Id &&
                                                                s.InternalLocation.Id == rosterBroadcastDTO.LocationId &&
                                                                SqlFunctions.DatePart("weekday", s.StartTime) == dow);
                        }
                        else
                        {
                            shiftsToBroadcast = db.Shifts.Where(s => s.Roster.Id == rosterBroadcastDTO.Id &&
                                                                s.InternalLocation == null &&
                                                                SqlFunctions.DatePart("weekday", s.StartTime) == dow);
                        }

                        foreach (Shift shift in shiftsToBroadcast)
                        {
                            shift.IsPublished = true;
                            //Add to list of employees who have shifts broadcast
                            if (shift.Employee != null)
                            {
                                if (shift.Employee.UserProfile != null)
                                {
                                    //If email not already added to list to send
                                    if (employees.Where(em => em.Id == shift.Employee.Id).Count() == 0)
                                    {
                                        employees.Add(new EmployeeDTO
                                        {
                                            Id        = shift.Employee.Id,
                                            FirstName = shift.Employee.UserProfile.FirstName,
                                            LastName  = shift.Employee.UserProfile.LastName,
                                            Email     = shift.Employee.UserProfile.Email
                                        });
                                    }
                                }
                                else
                                {
                                    //Employee does not have a linked userprofile, therefore try to use email is entered into employee by manager
                                    if (!String.IsNullOrEmpty(shift.Employee.Email) &&
                                        (employeesNoProfile.Where(em => em.Id == shift.Employee.Id).Count() == 0))
                                    {
                                        employeesNoProfile.Add(new EmployeeDTO
                                        {
                                            Id        = shift.Employee.Id,
                                            FirstName = shift.Employee.FirstName,
                                            LastName  = shift.Employee.LastName,
                                            Email     = shift.Employee.Email
                                        });
                                    }
                                }
                            }


                            //If this is an OPEN shift
                            if (shift.Employee == null)
                            {
                                openShifts.Add(MapperFacade.MapperConfiguration.Map <Shift, ShiftDTO>(shift));
                            }
                        }
                    }
                    db.SaveChanges();

                    //Send notifications to any staff who have shifts being published.
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    foreach (var emp in employees)
                    {
                        MessagingService.ShiftBroadcast(emp.Email, emp.FirstName);
                    }
                    foreach (var emp in employeesNoProfile)
                    {
                        MessagingService.ShiftBroadcastNotRegistered(emp.Email, emp.FirstName);
                    }
                    sw.Stop();

                    //Publish notification about open shifts
                    var busLocs = openShifts.Select(s => s.BusinessLocationId.Value).Distinct().ToList();
                    MessagingService.OpenShiftsBroadcast(busLocs);
                }
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Exemplo n.º 20
0
        // POST api/shiftapi
        //Create a new shift
        public HttpResponseMessage PostShift([FromBody] ShiftDTO shiftDTO, [FromUri] Guid businessLocationId)
        {
            if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", businessLocationId.ToString()))
            {
                if (ModelState.IsValid)
                {
                    var    dateMinusWeek = shiftDTO.StartDateTime.AddDays(-7);
                    Roster roster        = db.Rosters.Find(shiftDTO.RosterId);

                    //Business rules
                    if (roster == null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Unable to find corresponding roster"));
                    }
                    if (shiftDTO.StartDateTime > shiftDTO.FinishDateTime)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Shift start time must be before end time"));
                    }
                    if (shiftDTO.StartDateTime < roster.WeekStartDate ||
                        shiftDTO.StartDateTime >= roster.WeekStartDate.AddDays(7))
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Shift start time must be within the roster week starting '" + roster.WeekStartDate.ToShortDateString() + "'"));
                    }
                    if ((shiftDTO.FinishDateTime - shiftDTO.StartDateTime).Days > 1)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Shift can not span more than one day"));
                    }
                    if (shiftDTO.StartDateTime < WebUI.Common.Common.DateTimeNowLocal())
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Shift start time must not be in the past"));
                    }

                    using (ScheduleActionAPIController scheduleAPIController = new ScheduleActionAPIController())
                    {
                        var unavailEmployees = scheduleAPIController.GetUnavailableEmployees(shiftDTO.BusinessLocationId.GetValueOrDefault(), shiftDTO.StartDateTime.Ticks.ToString(), shiftDTO.FinishDateTime.Ticks.ToString(), Guid.Empty);
                        if (unavailEmployees.FirstOrDefault(e => e.Id == shiftDTO.EmployeeId) != null)
                        {
                            return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Employee is not available on this day"));
                        }
                    }

                    var shift = MapperFacade.MapperConfiguration.Map <ShiftDTO, Shift>(shiftDTO);
                    shift.Id               = Guid.NewGuid(); //Assign new ID on save.
                    shift.Roster           = roster;
                    shift.Employee         = db.Employees.Find(shiftDTO.EmployeeId);
                    shift.InternalLocation = db.InternalLocations.Find(shiftDTO.InternalLocationId);
                    shift.Role             = db.Roles.Find(shiftDTO.RoleId);

                    db.Shifts.Add(shift);
                    db.SaveChanges();

                    //If save as shift block also selected, then create new shift block
                    if (shiftDTO.SaveAsShiftBlock)
                    {
                        ShiftBlockDTO shiftBlockDTO = new ShiftBlockDTO
                        {
                            StartTime          = shiftDTO.StartTime,
                            FinishTime         = shiftDTO.FinishTime,
                            BusinessLocationId = businessLocationId,
                            RoleId             = shiftDTO.RoleId,
                            FinishNextDay      = (shiftDTO.FinishDay > shiftDTO.StartDay)
                        };

                        using (ShiftBlockAPIController sb = new ShiftBlockAPIController())
                        {
                            sb.Post(shiftBlockDTO);
                        }
                    }

                    //HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
                    //response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = role.Id }));
                    return(Request.CreateResponse(HttpStatusCode.Created));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
Exemplo n.º 21
0
        private ClockInOutReponseDTO PunchTimeClock(Guid employeeId, Guid businessLocationId, DateTime?timePunchVal = null)
        {
            //NOTE: EMployee Id can be an EMployee QR code, or a UserProfile QR code. Need to check for both to get a match.
            var responseObj = new ClockInOutReponseDTO();

            //First check if this is an employeeif
            Employee emp       = db.Employees.Find(employeeId);
            var      authEmail = HttpContext.Current.User.Identity.Name;

            if (emp == null) //Try and see if it is a UserProfile QR code with a linked employee to the selected business location
            {
                var usrProfile = db.UserProfiles.Find(employeeId);
                if (usrProfile != null)
                {
                    //Find employee linked to userprofile for selected business location
                    emp = usrProfile.Employees.FirstOrDefault(e => e.BusinessLocation.Id == businessLocationId);
                    if (emp == null)
                    {
                        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "No matching employee record to the business location could be found"));
                    }
                }
                else
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "No matching employee or user profile records could be found "));
                }
            }
            //throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));

            if (!emp.IsActive)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Employee is NOT active"));
            }

            if (emp.BusinessLocation.Id != businessLocationId)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Employee does not belong to business location"));
            }

            if (ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", businessLocationId.ToString()))
            {
#if DEBUG
                DateTime timePunch = (timePunchVal.HasValue)? timePunchVal.Value : WebUI.Common.Common.DateTimeNowLocal();
#else
                DateTime timePunch = WebUI.Common.Common.DateTimeNowLocal();
#endif

                //See if there are any timecards not chceked out for the employee
                TimeCard tc     = db.TimeCards.FirstOrDefault(t => t.Employee.Id == emp.Id && !t.ClockOut.HasValue);
                bool     exists = false;
                //If there is no open check in record create a new time card entry
                if (tc == null)
                { //CHECK IN
                    //Get the roster object associated with this time punch
                    var weekStartDate = WebUI.Common.Common.GetStartOfWeek(timePunch, DayOfWeek.Monday);
                    var roster        = db.Rosters.FirstOrDefault(r => r.BusinessLocation.Id == businessLocationId && r.WeekStartDate == weekStartDate);
                    if (roster == null)
                    {
                        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Unable to find matching Roster obejct for week"));
                    }

                    //See if we can locate a shift at the business location which corresponds to this check in event.
                    //Search for a start time which is within 30 mins of timepunch
                    var dtMinTime = timePunch.AddMinutes(-WebUI.Common.Constants.TimeCardShiftVariance);
                    var dtMaxTime = timePunch.AddMinutes(WebUI.Common.Constants.TimeCardShiftVariance);
                    var shift     = db.Shifts.FirstOrDefault(s => s.Roster.BusinessLocation.Id == businessLocationId && s.IsPublished && s.Employee.Id == emp.Id &&
                                                             s.StartTime >= dtMinTime && s.StartTime <= dtMaxTime);

                    tc                     = new TimeCard();
                    tc.Roster              = roster;
                    tc.Id                  = Guid.NewGuid();
                    tc.ClockIn             = timePunch;
                    tc.Employee            = emp;
                    tc.Shift               = shift;
                    responseObj.CheckInOut = CheckInOutEnum.CheckIn;
                    responseObj.Message    = "Check in confirmed. ";
                    if (shift != null)
                    {
                        responseObj.ShiftDetails = shift.StartTime.ToShortTimeString() + " - " + shift.FinishTime.ToShortTimeString();
                    }

                    tc.TimesheetEntry    = new TimesheetEntry();
                    tc.TimesheetEntry.Id = Guid.NewGuid();
                    //If a matched shift has been found then default the timesheet entry to the matched shift
                    //Otherwise set it to the timeclocked entry
                    if (shift != null)
                    {
                        tc.TimesheetEntry.StartDateTime  = shift.StartTime;
                        tc.TimesheetEntry.FinishDateTime = shift.FinishTime;
                    }
                    else
                    {
                        tc.TimesheetEntry.StartDateTime = new DateTime(timePunch.Year, timePunch.Month, timePunch.Day, timePunch.Hour, timePunch.Minute, 0);
                    }
                }
                else //Check out the previous record
                {
                    //CHECK OUT
                    exists                 = true;
                    tc.ClockOut            = timePunch;
                    responseObj.CheckInOut = CheckInOutEnum.CheckOut;
                    responseObj.Message    = "Check out confirmed. ";
                    if (tc.Shift != null)
                    {
                        responseObj.ShiftDetails = tc.Shift.StartTime.ToShortTimeString() + " - " + tc.Shift.FinishTime.ToShortTimeString();
                    }
                    else //Timesheet entry default finished time to the timepunch if it has not been defaulted to any linked shift
                    {
                        tc.TimesheetEntry.FinishDateTime = new DateTime(timePunch.Year, timePunch.Month, timePunch.Day, timePunch.Hour, timePunch.Minute, 0);
                    }
                }

                responseObj.Message += (emp.FirstName + " " + emp.LastName + " " + timePunch.ToString(WebUI.Common.Common.GetLocaleDateTimeDisplayFormat(HttpContext.Current.Request.UserLanguages.FirstOrDefault())) + " @ " + emp.BusinessLocation.Name);
                tc.BusinessLocation  = emp.BusinessLocation;
                tc.LastUpdatedDate   = WebUI.Common.Common.DateTimeNowLocal();
                tc.LastUpdatedBy     = db.UserProfiles.First(Usr => Usr.Email == authEmail).Employees.First(u => u.BusinessLocation.Id == businessLocationId);

                if (!exists)
                {
                    db.TimeCards.Add(tc);
                }

                db.SaveChanges();

                return(responseObj);
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
Exemplo n.º 22
0
        public HttpResponseMessage PutBusiness(Guid id, BusinessDetailsDTO businessDTO)
        {
            if (ClaimsAuthorization.CheckAccess("Put", "BusinessId", id.ToString()))
            {
                if (!ModelState.IsValid)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }

                if (id != businessDTO.Id)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest));
                }

                try
                {
                    var business = MapperFacade.MapperConfiguration.Map <BusinessDetailsDTO, Business>(businessDTO, db.Businesses.Single(b => b.Id == id));

                    //Lookup BusinessType and attach, so that no updates or inserts are performed on BusinessType lookup table
                    business.Type = db.BusinessTypes.Single(t => t.Id == businessDTO.TypeId);

                    ////Apply any role updates or inserts
                    //foreach (RoleDTO roleDTO in businessDTO.Roles)
                    //{
                    //    Role role = business.Roles.FirstOrDefault(r => r.Id == roleDTO.Id);
                    //    //If there is a role, then need to update
                    //    if (role != null)
                    //        role.Name = roleDTO.Name;
                    //    else //This is a new role being added
                    //    {
                    //        var newRole = MapperFacade.MapperConfiguration.Map<RoleDTO, Role>(roleDTO);
                    //        newRole.Id = Guid.NewGuid();
                    //        business.Roles.Add(newRole);
                    //    } //Note: deletion of roles is not supported here
                    //}

                    db.Entry(business).State = EntityState.Modified;

                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
Exemplo n.º 23
0
        // PUT api/EmployeeAPI/5
        public HttpResponseMessage PutEmployee(Guid id, EmployeeDTO employeeDTO)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            if (id != employeeDTO.Id)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            if (employeeDTO.Roles != null && employeeDTO.Roles.Count > 5)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.ExpectationFailed, "Maximimum of 5 roles only can be added"));
            }

            try
            {
                bool sendEmailNotification = false;

                var employee = db.Employees.Find(id);

                if (!ClaimsAuthorization.CheckAccess("Put", "BusinessLocationId", employee.BusinessLocation.Id.ToString()))
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have appropriate permission"));
                }

                //Do not allow modification of email addresses which are linked to userprofiles already
                if (employee.UserProfile != null && employeeDTO.Email != employee.Email)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "You can not modify email address for an employee which is linked to a registered user"));
                }

                //If the email address is being updated then send notification to new address
                if (employee.Email != employeeDTO.Email && !String.IsNullOrEmpty(employeeDTO.Email))
                {
                    sendEmailNotification = true;
                }

                //Map the updates across to original object
                employee = MapperFacade.MapperConfiguration.Map <EmployeeDTO, Employee>(employeeDTO, employee);

                //Check to see if there is already an employee with this same email address registered for the business location.
                var employeeExistingEmail = db.Employees.FirstOrDefault(emp => !String.IsNullOrEmpty(employeeDTO.Email) && emp.Email == employee.Email && emp.Id != employee.Id && emp.BusinessLocation.Id == employee.BusinessLocation.Id);
                if (employeeExistingEmail != null)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "An employee with this email address already exists for this business"));
                }


                //Lookup BusinessLocation and attach, so that no updates or inserts are performed on BusinessType lookup table
                var busLoc = db.BusinessLocations.Single(b => b.Id == employeeDTO.BusinessLocationId);
                employee.BusinessLocation = busLoc;

                if (employee.IsAdmin)
                {
                    employee.ManagerBusinessLocations.Add(busLoc);
                }
                else
                {
                    //if not admin but currently linked
                    if (employee.ManagerBusinessLocations.Contains(busLoc))
                    {
                        employee.ManagerBusinessLocations.Remove(busLoc);
                    }
                }
                //Hook up any roles selected
                employee.Roles.Clear(); //Clear first so we can hook up correct DB items
                if (employeeDTO.Roles != null)
                {
                    foreach (RoleDTO roleDTO in employeeDTO.Roles)
                    {
                        Role role = db.Roles.FirstOrDefault(r => r.Id == roleDTO.Id);
                        if (role == null)
                        {
                            return(Request.CreateResponse(HttpStatusCode.NotFound));
                        }
                        employee.Roles.Add(role);
                    }
                }

                //If user email has been updated then send notification and request
                if (sendEmailNotification)
                {
                    //Remove any old employee requests
                    if (employee.EmployeeRequest != null)
                    {
                        db.Entry(employee.EmployeeRequest).State = EntityState.Deleted;
                    }

                    //Create an entry in the EMployeeRequest table
                    EmployeeRequest empRequest = new EmployeeRequest()
                    {
                        Id               = Guid.NewGuid(),
                        CreatedDate      = WebUI.Common.Common.DateTimeNowLocal(),
                        Status           = RequestStatus.Pending,
                        BusinessLocation = employee.BusinessLocation
                    };
                    employee.EmployeeRequest = empRequest;

                    //If an existing user profile exists with matching email address
                    if (db.UserProfiles.Any(usr => usr.Email == employee.Email))
                    {
                        //Send user email notifying them that a business has registered their email and they need to approve to link
                        MessagingService.BusinessRegisteredEmployee(employee.FirstName, employee.BusinessLocation.Business.Name, true, employee.Email, employee.MobilePhone);
                    }
                    else //Send email notifying them that they have been registered with a business and invite to register an account
                    {
                        MessagingService.BusinessRegisteredEmployee(employee.FirstName, employee.BusinessLocation.Business.Name, false, employee.Email, employee.MobilePhone);
                    }
                }

                db.Entry(employee).State = EntityState.Modified;

                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Exemplo n.º 24
0
        public bool PostViewedWizard()
        {
            var email = HttpContext.Current.User.Identity.Name;

            UserProfile userProfile = db.UserProfiles.FirstOrDefault(usr => usr.Email == email);

            if (userProfile == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            userProfile.HasViewedWizard = true;

            db.SaveChanges();

            return(userProfile.HasViewedWizard);
        }