public static int Insert(Shift shiftToInsert) { VolunteerDatabaseDataContext db = new VolunteerDatabaseDataContext(); db.Shifts.InsertOnSubmit(shiftToInsert); db.SubmitChanges(); return shiftToInsert.Shift_ID; }
public void GenerateSchedulePriorityTest() { //arrange ShiftTable shifts = new ShiftTable(); Shift shift1 = new Shift("", "", "Sunday", "7", "15", "Sion", "", ""); Shift shift2 = new Shift("", "", "Sunday", "15", "23", "Sion", "", ""); Shift shift3 = new Shift("", "", "Sunday", "23", "7", "Sion", "", ""); shifts.AddShift(shift1); shifts.AddShift(shift2); shifts.AddShift(shift3); ShiftTable options = new ShiftTable(); Shift option1 = new Shift("123456789", "Polishuk", "Sunday", "7", "15", "Sion", "Low", ""); Shift option2 = new Shift("123456789", "Polishuk", "Sunday", "15", "23", "Sion", "High", ""); Shift option3 = new Shift("123456789", "Polishuk", "Sunday", "23", "7", "Sion", "Low", ""); options.AddShift(option1); options.AddShift(option2); options.AddShift(option3); //act GenerateTable generator = new GenerateTable(options, shifts); ShiftTable schedule = generator.GenerateSchedule(); //assert Assert.AreEqual(schedule.GetAllShifts().Count, 1, "GenerateSchedulePriorityTest error: the number of shift do not mach expectation"); Assert.AreEqual(schedule.optionExists(option2), true, "GenerateSchedulePriorityTest error: the option do not exists"); }
public SymbolEvent(Common.SafeBitArray bitset, int samplesPerSymbol, bool decision, Shift shift) { mBitset = bitset; mSamplesPerSymbol = samplesPerSymbol; mDecision = decision; mShift = shift; }
public void Select_Finds_FirstToSatisfyAllConstraints() { var mockery = new MockRepository(); var constraint1 = mockery.StrictMock<IResidentConstraint>(); var constraint2 = mockery.StrictMock<IResidentConstraint>(); var selector = new ResidentSelector(); selector.Constraints.Clear(); selector.Constraints.Add(constraint1); selector.Constraints.Add(constraint2); var residents = new List<Resident> { new Resident(), new Resident(), new Resident() }; var shift = new Shift(DateTime.Today, DateTime.Today, DateTime.Today); using (mockery.Record()) { SetupResult.For(constraint1.Assignable(residents.First(), shift)).Return(false); SetupResult.For(constraint2.Assignable(residents.First(), shift)).Return(true); SetupResult.For(constraint1.Assignable(residents.Skip(1).First(), shift)).Return(true); SetupResult.For(constraint2.Assignable(residents.Skip(1).First(), shift)).Return(false); SetupResult.For(constraint1.Assignable(residents.Skip(2).First(), shift)).Return(true); SetupResult.For(constraint2.Assignable(residents.Skip(2).First(), shift)).Return(true); } using (mockery.Playback()) { Assert.AreEqual(residents.Skip(2).First(), selector.Select(residents, shift)); } }
public IEnumerable<Shift> CreateShiftsForDay(DateTime day, IEnumerable<RotationShift> rotationShifts) { return rotationShifts.Where(rs => rs.IsAssingingRequired).Select(rs => { var shift = new Shift(day, rs.StartTime, rs.EndTime, rs.MultipleDayDecorator); rs.Shifts.Add(shift); return shift; }); }
public static List<Vector> Shift(this List<Vector> vectorList, Shift toApply) { List<Vector> toReturn = new List<Vector>(); foreach(Vector vector in vectorList) { toReturn.Add(vector.Shift(toApply)); } return toReturn; }
protected void ODS_Shift_Inserting(object sender, ObjectDataSourceMethodEventArgs e) { shift = (Shift)e.InputParameters[0]; Shift checkShift = TheShiftMgr.LoadShift(shift.Code); if (checkShift != null) { ShowErrorMessage("Common.Business.Error.EntityExist", shift.Code); e.Cancel = true; } }
//THIS METHOD RETURNS COPYIES OF ALL SHIFTS IN THE LIST public List<Shift> GetAllShifts() { List<Shift> result = new List<Shift>(); foreach (Shift sh in shiftTable) { Shift newShift = new Shift(sh.getWroker_ID(), sh.getName(), sh.getDay(), sh.getBegin_Time(), sh.getEnd_Time(), sh.getOrganization(), sh.getPriority(), sh.getNumOfWorkers()); result.Add(newShift); } return result; }
public void Select_Finds_Resident_With_Least_Number_Of_Shifts() { var residents = new List<Resident> { new Resident(), new Resident() }; var shift = new Shift(DateTime.Today, DateTime.Today, DateTime.Today); residents.First().Shifts.Add(shift); var selector = new ResidentSelector(); selector.Constraints.Clear(); Assert.AreEqual(residents.Skip(1).First(), selector.Select(residents, shift)); }
public bool Assignable(Resident resident, Shift shift) { var shiftHours = shift.DateRange.Hours; var startConstraint = shift.EndTime.AddDays(-28).AddMinutes(1); var endConstraint = shift.StartTime.AddMinutes(-1); var assignedHours = resident.Shifts.Where(s => s.DateRange.Equals(new DateRange(startConstraint, endConstraint))) .Select(s => new DateRange(DateExtensions.Max(s.StartTime, startConstraint), DateExtensions.Min(s.EndTime, endConstraint))) .Sum(dr => dr.Hours); var resultingAverage = ((assignedHours + shiftHours) / 4m); return resultingAverage <= 80; }
public void Assignable_AlreadyAssigned24_NotPGY1(ResidentYears residentYears) { //24HRShift var assignedShift = new Shift(DateTime.Today, TimeConstants.StartOfDay, TimeConstants.EndOfDay); var resident = new Resident { ResidentYear = residentYears }; resident.Shifts.Add(assignedShift); Assert.AreEqual(24, assignedShift.DateRange.Hours); var unAssingableShift = new Shift(DateTime.Today.AddDays(1), TimeConstants.StartOfDay, TimeConstants.StartOfDay); //1 minute shift Assert.IsFalse(new ContinuousDutyHourConstraint().Assignable(resident, unAssingableShift)); var assingableShift = new Shift(DateTime.Today.AddDays(1), TimeConstants.StartOfDay.AddMinutes(1), TimeConstants.StartOfDay.AddMinutes(1)); //1 minute shift non conitinous Assert.IsTrue(new ContinuousDutyHourConstraint().Assignable(resident, assingableShift)); }
public void Assignable_AlreadyAssigned16_PGY1() { //16HRShift var assignedShift = new Shift(DateTime.Today, TimeConstants.StartOfDay, TimeConstants.StartOfDay.AddHours(16).AddMinutes(-1)); var resident = new Resident { ResidentYear = ResidentYears.PGY_1 }; resident.Shifts.Add(assignedShift); Assert.AreEqual(16, assignedShift.DateRange.Hours); var unAssingableShift = new Shift(DateTime.Today, TimeConstants.StartOfDay.AddHours(16), TimeConstants.StartOfDay.AddHours(16)); //1 minute shift Assert.IsFalse(new ContinuousDutyHourConstraint().Assignable(resident, unAssingableShift)); var assingableShift = new Shift(DateTime.Today, TimeConstants.StartOfDay.AddHours(16).AddMinutes(1), TimeConstants.StartOfDay.AddHours(16).AddMinutes(1)); //1 minute shift non conitinous Assert.IsTrue(new ContinuousDutyHourConstraint().Assignable(resident, assingableShift)); }
public bool Assignable(Resident resident, Shift shift) { var maxHours = resident.MaxContinuousShiftHours; var shiftHours = shift.DateRange.Hours; if (shiftHours > maxHours) return false; var startConstraint = shift.EndTime.AddHours(-maxHours); // Period of 'maxHours' hours and 1 minute from end of shift var endConstraint = shift.StartTime.AddMinutes(-1); var assignedHours = resident.Shifts.Where(s => s.DateRange.Equals(new DateRange(startConstraint, endConstraint)))//shifts in 'maxHours' hour period .Select(s => new DateRange(DateExtensions.Max(s.StartTime, startConstraint), DateExtensions.Min(s.EndTime, endConstraint))) .Sum(dr => dr.Hours); return assignedHours + shiftHours <= maxHours; }
public void Assignable_ShiftWouldResultInMoreThan16_PGY1() { //15.5HRShift var assignedShift = new Shift(DateTime.Today, TimeConstants.StartOfDay.AddMinutes(30), TimeConstants.StartOfDay.AddHours(16).AddMinutes(-1)); var resident = new Resident { ResidentYear = ResidentYears.PGY_1 }; resident.Shifts.Add(assignedShift); //31 minute shift var unAssingableShift = new Shift(DateTime.Today, TimeConstants.StartOfDay.AddHours(16), TimeConstants.StartOfDay.AddHours(16).AddMinutes(30)); Assert.IsFalse(new ContinuousDutyHourConstraint().Assignable(resident, unAssingableShift)); //30 minute shift var assingableShift = new Shift(DateTime.Today, TimeConstants.StartOfDay.AddHours(16), TimeConstants.StartOfDay.AddHours(16).AddMinutes(29)); Assert.IsTrue(new ContinuousDutyHourConstraint().Assignable(resident, assingableShift)); }
public void Assignable_ShiftWouldResultInMoreThan24_NotPGY1(ResidentYears residentYears) { //23.5HRShift var assignedShift = new Shift(DateTime.Today, TimeConstants.StartOfDay.AddMinutes(30), TimeConstants.EndOfDay); var resident = new Resident { ResidentYear = residentYears }; resident.Shifts.Add(assignedShift); //31 minute shift var unAssingableShift = new Shift(DateTime.Today.AddDays(1), TimeConstants.StartOfDay, TimeConstants.StartOfDay.AddMinutes(30)); Assert.IsFalse(new ContinuousDutyHourConstraint().Assignable(resident, unAssingableShift)); //30 minute shift var assingableShift = new Shift(DateTime.Today.AddDays(1), TimeConstants.StartOfDay, TimeConstants.StartOfDay.AddMinutes(29)); Assert.IsTrue(new ContinuousDutyHourConstraint().Assignable(resident, assingableShift)); }
public void divideLowOrHighTest() { //arrange Shift s1 = new Shift("", "", "Sunday", "7", "15", "", "High", ""); Shift s2 = new Shift("", "", "Thursday", "23", "3", "", "Low", ""); ShiftTable t1 = new ShiftTable(); t1.AddShift(s1); t1.AddShift(s2); GenerateTable gen = new GenerateTable(t1, null); ShiftTable high = gen.getHighPriorityOptions(); ShiftTable low = gen.getLowPriorityOptions(); //act bool result_low = low.shiftExists("Thursday", "23", "3"); bool result_high = high.shiftExists("Sunday", "7", "15"); //assert Assert.AreEqual(result_low, false, "divideLowOrHighTest error: the shift is high priotity, expected low"); Assert.AreEqual(result_high, true, "divideLowOrHighTest error: the shift is low priotity, expected high"); }
public static void Create(string shift) { if (shift.Length == 0) { throw new Exception("Invalid shift."); } JobBoardDataContext db = new JobBoardDataContext(); // Make sure we don't already have a education entry for this int existing = db.Shifts.Where(x => x.shift1 == shift).Count(); if (existing > 0) { throw new Exception("Existing entry."); } // Create new education level Shift sh = new Shift { id = Guid.NewGuid(), shift1 = shift, date_added = DateTime.Now }; // Save education db.Shifts.InsertOnSubmit(sh); db.SubmitChanges(); }
//Insert new shifts public void FormView1_InsertItem() { var shift = new Shift(); TryUpdateModel(shift); if (ModelState.IsValid) { try { Service.InsertShift(shift); //Success message saved in Session varible "Message" Page.SetTempData("Message", String.Format("Uppgifterna har sparats")); //Flush cache HttpContext.Current.Cache.Remove("Shifts"); Response.RedirectToRoute("Default"); } catch (Exception) { ModelState.AddModelError(String.Empty, "Passet kunde inte sparas."); } } }
public async Task <Unit> Handle(Command request, CancellationToken cancellationToken) { dynamic errors = new ExpandoObject(); var location = await _context.Locations.FindAsync(request.LocationId); if (location == null) { errors.location = "Invalid Location"; } var license = await _context.Licenses.FindAsync(request.LicenseId); if (license == null) { errors.license = "Invalid License"; } var room = await _context.Rooms.FindAsync(request.RoomId); if (room == null || room.LocationId != location.Id) { errors.room = "Invalid Room"; } var modality = await _context.Modalities.FindAsync(request.ModalityId); if (modality == null) { errors.modality = "Invalid Modality"; } var technologist = await _context.Technologists.FindAsync(request.TechnologistId); if (technologist == null || technologist.ModalityId != modality.Id) { errors.technologist = "Invalid Technologist"; } int errorCount = ((ICollection <KeyValuePair <string, Object> >)errors).Count; if (errorCount > 0) { throw new RestException(HttpStatusCode.NotFound, errors); } var shift = new Shift { Id = request.Id, Start = request.Start, End = request.End, License = license, Location = location, Room = room, Technologist = technologist, Modality = modality }; _context.Shifts.Add(shift); var success = await _context.SaveChangesAsync() > 0; if (success) { return(Unit.Value); } throw new Exception("Problem saving changes"); }
private void CalculateOpenShiftTimes(AttData attendanceRecord, Shift shift) { try { //Calculate WorkMin //Calculate WorkMin attendanceRecord.Remarks.Replace("[LI]", ""); attendanceRecord.Remarks.Replace("[EI]", ""); attendanceRecord.Remarks.Replace("[EO]", ""); attendanceRecord.Remarks.Replace("[LO]", ""); attendanceRecord.Remarks.Replace("[G-OT]", ""); attendanceRecord.Remarks.Replace("[R-OT]", ""); attendanceRecord.Remarks.Replace("[N-OT]", ""); attendanceRecord.Remarks.Replace("[Manual]", ""); attendanceRecord.Remarks = attendanceRecord.Remarks + "[Manual]"; if (attendanceRecord != null) { if (attendanceRecord.TimeOut != null && attendanceRecord.TimeIn != null) { attendanceRecord.Remarks = ""; TimeSpan mins = (TimeSpan)(attendanceRecord.TimeOut - attendanceRecord.TimeIn); attendanceRecord.WorkMin = (short)mins.TotalMinutes; //Check if GZ holiday then place all WorkMin in GZOTMin if (attendanceRecord.StatusGZ == true) { attendanceRecord.GZOTMin = (short)mins.TotalMinutes; attendanceRecord.WorkMin = (short)mins.TotalMinutes; attendanceRecord.StatusGZOT = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[GZ-OT]"; } else if (attendanceRecord.StatusDO == true) { attendanceRecord.OTMin = (short)mins.TotalMinutes; attendanceRecord.WorkMin = (short)mins.TotalMinutes; attendanceRecord.StatusOT = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[R-OT]"; } else { if (shift.HasBreak == true) { attendanceRecord.WorkMin = (short)(attendanceRecord.WorkMin - shift.BreakMin); attendanceRecord.ShifMin = (short)(ProcessSupportFunc.CalculateShiftMinutes(shift, attendanceRecord.AttDate.Value.DayOfWeek) - (short)attendanceRecord.BreakMin); } else { attendanceRecord.Remarks.Replace("[Absent]", ""); attendanceRecord.StatusAB = false; attendanceRecord.StatusP = true; // CalculateShiftEndTime = ShiftStart + DutyHours //Calculate OverTIme, if ((mins.TotalMinutes > (attendanceRecord.ShifMin + shift.OverTimeMin)) && attendanceRecord.Emp.HasOT == true) { attendanceRecord.OTMin = (Int16)(Convert.ToInt16(mins.TotalMinutes) - attendanceRecord.ShifMin); attendanceRecord.WorkMin = (short)((mins.TotalMinutes) - attendanceRecord.OTMin); attendanceRecord.StatusOT = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[N-OT]"; } //Calculate Early Out if (mins.TotalMinutes < (attendanceRecord.ShifMin - shift.EarlyOut)) { Int16 EarlyoutMin = (Int16)(attendanceRecord.ShifMin - Convert.ToInt16(mins.TotalMinutes)); if (EarlyoutMin > shift.EarlyOut) { attendanceRecord.EarlyOut = EarlyoutMin; attendanceRecord.StatusEO = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[EO]"; } else { attendanceRecord.StatusEO = null; attendanceRecord.EarlyOut = null; attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[EO]", ""); } } else { attendanceRecord.StatusEO = null; attendanceRecord.EarlyOut = null; attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[EO]", ""); } if ((attendanceRecord.StatusGZ != true || attendanceRecord.StatusDO != true) && attendanceRecord.Emp.HasOT == true) { if (attendanceRecord.LateOut != null) { attendanceRecord.OTMin = attendanceRecord.LateOut; attendanceRecord.StatusOT = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[N-OT]"; } } if (shift.SubtractOTFromWork == true) { if (attendanceRecord.LateOut != null && attendanceRecord.LateOut > shift.LateOut) { attendanceRecord.WorkMin = (short)(attendanceRecord.WorkMin - attendanceRecord.LateOut); } } if (shift.RoundOffWorkMin == true) { if (attendanceRecord.LateOut != null || attendanceRecord.EarlyIn != null) { // round off work mins if overtime less than shift.OverTimeMin > if (attendanceRecord.WorkMin > attendanceRecord.ShifMin && (attendanceRecord.WorkMin <= (attendanceRecord.ShifMin + shift.OverTimeMin))) { attendanceRecord.WorkMin = attendanceRecord.ShifMin; } } } //Mark Absent if less than 4 hours if (attendanceRecord.AttDate.Value.DayOfWeek != DayOfWeek.Friday && attendanceRecord.StatusDO != true && attendanceRecord.StatusGZ != true) { short MinShiftMin = (short)shift.MinHrs; if (attendanceRecord.WorkMin < MinShiftMin) { attendanceRecord.StatusAB = true; attendanceRecord.StatusP = false; attendanceRecord.Remarks = attendanceRecord.Remarks + "[Absent]"; } else { attendanceRecord.StatusAB = false; attendanceRecord.StatusP = true; attendanceRecord.Remarks.Replace("[Absent]", ""); } } } } } } } catch (Exception ex) { } }
/// <summary> /// Calling this method will convert from the passed value to the LatLon /// </summary> /// <param name="pHorizontal">The point on the horizontal axis (easting or latitude)</param> /// <param name="pVertical">The point on the vertical axis (northing or longtitude)</param> /// <param name="pHeight">The height to be converted</param> /// <returns>The location as a LatLon coordinate</returns> private ICoordinate InternalCalculate(double pHorizontal, double pVertical, double pHeight) { double eS = 0, nS = 0; double ht_dif = 0; double E = 0, N = 0; Shift s = (Shift)mShifts.CalculateShift(pHorizontal, pVertical); eS = s.Easting; nS = s.Northing; ht_dif = Math.Round(s.Height, 3); double diff = 0, diffn = 0, NeweS = 0, NewnS = 0; int iterations = 0; do { E = pHorizontal - eS; // use shifts to calculate OSGRS80 Grid coordinates N = pVertical - nS; s = (Shift)mShifts.CalculateShift(pHorizontal, pVertical); NeweS = s.Easting; NewnS = s.Northing; ht_dif = s.Height; diff = NeweS - eS; diffn = NewnS - nS; eS = NeweS; nS = NewnS; iterations = iterations + 1; } while ((iterations < 30) && ((Math.Abs(diff) > 0.00001)) || (Math.Abs(diffn) > 0.00001)); double a = OSGB35Constants.a; a *= OSGB35Constants.f0; double b = OSGB35Constants.b; b *= OSGB35Constants.f0; double n = (a - b) / (a + b); double e2 = ((a * a) - (b * b)) / (a * a); double latEst = ((N - OSGB35Constants.n0) / a) + OSGB35Constants.lat0; double latNew, dLat, sLat, M; iterations = 0; do { dLat = latEst - OSGB35Constants.lat0; // difference in latitude sLat = latEst + OSGB35Constants.lat0; // sum of latitude M = MeridianArc.ComputeMeridanArc(dLat, sLat, n, b); latNew = ((N - OSGB35Constants.n0 - M) / a) + latEst; latEst = latNew; diff = N - OSGB35Constants.n0 - M; } while ((iterations++ < 30) && (diff > 0.000001)); double nu = (a / Math.Pow(1 - e2 * Math.Pow(Math.Sin(latEst), 2.0), 0.5)); double rho = ((a * (1 - e2)) / Math.Pow(1 - e2 * Math.Pow(Math.Sin(latEst), 2.0), 1.5)); double n2 = (nu / rho) - 1; double VII = Math.Tan(latEst) / (2 * nu * rho); double VIII = (Math.Tan(latEst) / (24 * rho * Math.Pow(nu, 3.0))) * (5 + (3 * Math.Pow(Math.Tan(latEst), 2.0)) + n2 - (9 * Math.Pow(Math.Tan(latEst), 2.0) * n2)); double IX = (Math.Tan(latEst) / (720 * rho * Math.Pow(nu, 5.0))) * (61 + (90 * Math.Pow(Math.Tan(latEst), 2.0)) + (45 * Math.Pow(Math.Tan(latEst), 4.0))); double X = 1 / (Math.Cos(latEst) * nu); double XI = (1 / (6 * (Math.Cos(latEst) * Math.Pow(nu, 3.0))) * ((nu / rho) + (2 * Math.Pow(Math.Tan(latEst), 2.0)))); double XII = (1 / (120 * (Math.Cos(latEst) * Math.Pow(nu, 5.0))) * (5 + (28 * Math.Pow(Math.Tan(latEst), 2.0)) + (24 * Math.Pow(Math.Tan(latEst), 4.0)))); double XIIA = (1 / (5040 * (Math.Cos(latEst) * Math.Pow(nu, 7.0))) * (61 + (662 * Math.Pow(Math.Tan(latEst), 2.0)) + (1320 * Math.Pow(Math.Tan(latEst), 4.0)) + (720 * Math.Pow(Math.Tan(latEst), 6.0)))); double y = E - OSGB35Constants.e0; double k1 = latEst - (y * y * VII) + (Math.Pow(y, 4.0) * VIII) - (Math.Pow(y, 6.0) * IX); double k2 = OSGB35Constants.lon0 + (y * X) - (Math.Pow(y, 3.0) * XI) + (Math.Pow(y, 5.0) * XII) - (Math.Pow(y, 7.0) * XIIA); double k3 = pHeight + ht_dif; // [TestCase(49.92226393730, -6.29977752014, 100.000, 91492.146, 11318.804, 46.519)] double xr1 = mCoordinateSupport.RadiansToDegrees(k1); double xr2 = mCoordinateSupport.RadiansToDegrees(k2); return(new LatLon(xr1, xr2, k3)); }
private void CalculateShiftTimes(AttData attendanceRecord, Shift shift) { try { //Calculate WorkMin attendanceRecord.Remarks = ""; TimeSpan mins = (TimeSpan)(attendanceRecord.TimeOut - attendanceRecord.TimeIn); //Check if GZ holiday then place all WorkMin in GZOTMin if (attendanceRecord.StatusGZ == true) { attendanceRecord.GZOTMin = (short)mins.TotalMinutes; attendanceRecord.WorkMin = (short)mins.TotalMinutes; attendanceRecord.StatusGZOT = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[G-OT]"; } //if Rest day then place all WorkMin in OTMin else if (attendanceRecord.StatusDO == true) { attendanceRecord.OTMin = (short)mins.TotalMinutes; attendanceRecord.WorkMin = (short)mins.TotalMinutes; attendanceRecord.StatusOT = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[R-OT]"; } else { /////////// to-do -----calculate Margins for those shifts which has break mins if (shift.HasBreak == true) { attendanceRecord.WorkMin = (short)(mins.TotalMinutes - shift.BreakMin); attendanceRecord.ShifMin = (short)(CalculateShiftMinutes(shift, attendanceRecord.AttDate.Value.DayOfWeek) - (short)shift.BreakMin); } else { //Calculate Late IN, Compare margin with Shift Late In if (attendanceRecord.TimeIn.Value.TimeOfDay > attendanceRecord.DutyTime) { TimeSpan lateMinsSpan = (TimeSpan)(attendanceRecord.TimeIn.Value.TimeOfDay - attendanceRecord.DutyTime); if (lateMinsSpan.TotalMinutes > shift.LateIn) { attendanceRecord.LateIn = (short)lateMinsSpan.TotalMinutes; attendanceRecord.StatusLI = true; attendanceRecord.EarlyIn = null; attendanceRecord.Remarks = attendanceRecord.Remarks + "[LI]"; } else { attendanceRecord.StatusLI = null; attendanceRecord.LateIn = null; attendanceRecord.Remarks.Replace("[LI]", ""); } } else { attendanceRecord.StatusLI = null; attendanceRecord.LateIn = null; attendanceRecord.Remarks.Replace("[LI]", ""); } //Calculate Early In, Compare margin with Shift Early In if (attendanceRecord.TimeIn.Value.TimeOfDay < attendanceRecord.DutyTime) { TimeSpan EarlyInMinsSpan = (TimeSpan)(attendanceRecord.DutyTime - attendanceRecord.TimeIn.Value.TimeOfDay); if (EarlyInMinsSpan.TotalMinutes > shift.EarlyIn) { attendanceRecord.EarlyIn = (short)EarlyInMinsSpan.TotalMinutes; attendanceRecord.StatusEI = true; attendanceRecord.LateIn = null; attendanceRecord.Remarks = attendanceRecord.Remarks + "[EI]"; } else { attendanceRecord.StatusEI = null; attendanceRecord.EarlyIn = null; attendanceRecord.Remarks.Replace("[EI]", ""); } } else { attendanceRecord.StatusEI = null; attendanceRecord.EarlyIn = null; attendanceRecord.Remarks.Replace("[EI]", ""); } // CalculateShiftEndTime = ShiftStart + DutyHours DateTime shiftEnd = CalculateShiftEndTime(shift, attendanceRecord.AttDate.Value, attendanceRecord.DutyTime.Value); //Calculate Early Out, Compare margin with Shift Early Out if (attendanceRecord.TimeOut < shiftEnd) { TimeSpan EarlyOutMinsSpan = (TimeSpan)(shiftEnd - attendanceRecord.TimeOut); if (EarlyOutMinsSpan.TotalMinutes > shift.EarlyOut) { attendanceRecord.EarlyOut = (short)EarlyOutMinsSpan.TotalMinutes; attendanceRecord.StatusEO = true; attendanceRecord.LateOut = null; attendanceRecord.Remarks = attendanceRecord.Remarks + "[EO]"; } else { attendanceRecord.StatusEO = null; attendanceRecord.EarlyOut = null; attendanceRecord.Remarks.Replace("[EO]", ""); } } else { attendanceRecord.StatusEO = null; attendanceRecord.EarlyOut = null; attendanceRecord.Remarks.Replace("[EO]", ""); } //Calculate Late Out, Compare margin with Shift Late Out if (attendanceRecord.TimeOut > shiftEnd) { TimeSpan LateOutMinsSpan = (TimeSpan)(attendanceRecord.TimeOut - shiftEnd); if (LateOutMinsSpan.TotalMinutes > shift.LateOut) { attendanceRecord.LateOut = (short)LateOutMinsSpan.TotalMinutes; // Late Out cannot have an early out, In case of poll at multiple times before and after shiftend attendanceRecord.EarlyOut = null; attendanceRecord.StatusLO = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[LO]"; } else { attendanceRecord.StatusLO = null; attendanceRecord.LateOut = null; attendanceRecord.Remarks.Replace("[LO]", ""); } } else { attendanceRecord.StatusLO = null; attendanceRecord.LateOut = null; attendanceRecord.Remarks.Replace("[LO]", ""); } //Subtract EarlyIn and LateOut from Work Minutes //////-------to-do--------- Automate earlyin,lateout from shift setup attendanceRecord.WorkMin = (short)(mins.TotalMinutes); if (attendanceRecord.EarlyIn != null && attendanceRecord.EarlyIn > shift.EarlyIn) { attendanceRecord.WorkMin = (short)(attendanceRecord.WorkMin - attendanceRecord.EarlyIn); } if (attendanceRecord.LateOut != null && attendanceRecord.LateOut > shift.LateOut) { attendanceRecord.WorkMin = (short)(attendanceRecord.WorkMin - attendanceRecord.LateOut); } if (attendanceRecord.LateOut != null || attendanceRecord.EarlyIn != null) { // round off work mins if overtime less than shift.OverTimeMin > if (attendanceRecord.WorkMin > CalculateShiftMinutes(shift, attendanceRecord.AttDate.Value.DayOfWeek) && (attendanceRecord.WorkMin <= (CalculateShiftMinutes(shift, attendanceRecord.AttDate.Value.DayOfWeek) + shift.OverTimeMin))) { attendanceRecord.WorkMin = CalculateShiftMinutes(shift, attendanceRecord.AttDate.Value.DayOfWeek); } } //Calculate OverTime = OT, Compare margin with Shift OverTime //----to-do----- Handle from shift //if (attendanceRecord.EarlyIn > shift.EarlyIn || attendanceRecord.LateOut > shift.LateOut) //{ // if (attendanceRecord.StatusGZ != true || attendanceRecord.StatusDO != true) // { // short _EarlyIn; // short _LateOut; // if (attendanceRecord.EarlyIn == null) // _EarlyIn = 0; // else // _EarlyIn = 0; // if (attendanceRecord.LateOut == null) // _LateOut = 0; // else // _LateOut = (short)attendanceRecord.LateOut; // attendanceRecord.OTMin = (short)(_EarlyIn + _LateOut); // attendanceRecord.StatusOT = true; // attendanceRecord.Remarks = attendanceRecord.Remarks + "[N-OT]"; // } //} if (attendanceRecord.StatusGZ != true || attendanceRecord.StatusDO != true) { if (attendanceRecord.LateOut != null) { attendanceRecord.OTMin = attendanceRecord.LateOut; attendanceRecord.StatusOT = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[N-OT]"; } else { attendanceRecord.OTMin = null; attendanceRecord.StatusOT = null; attendanceRecord.Remarks.Replace("[OT]", ""); attendanceRecord.Remarks.Replace("[N-OT]", ""); } } else { attendanceRecord.OTMin = null; attendanceRecord.StatusOT = null; attendanceRecord.Remarks.Replace("[OT]", ""); attendanceRecord.Remarks.Replace("[N-OT]", ""); } } } } catch (Exception ex) { } }
/// <summary> /// 登录事件 /// </summary> private void picLogin_Click(object sender, EventArgs e) { if (this.TxtUser.Text == "请输入用户名" || this.TxtKey.Text == "请输入密码" || this.TxtUser.Text == "" || this.TxtKey.Text == "")//判断是否为空 { PassValue.MessageInfor = "用户名和密码不能为空"; Messagebox mb = new Messagebox(); mb.ShowDialog(); this.TxtKey.Text = "请输入密码"; this.TxtUser.Text = ""; this.TxtUser.Focus(); } else { PassValue.username = this.TxtUser.Text;//用户名 PassValue.password = this.TxtKey.Text;//密码 string passvalue = PassValue.username + ":" + PassValue.password; WebHeaderCollection headers = new WebHeaderCollection(); headers.Add("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(passvalue))); headers.Add("Authed", "true"); LoginID li = null; HttpResult httpResult = httpReq.HttpPost("auth/tokens", null, headers); if ((int)httpResult.StatusCode == 0) { MessageBox.Show(string.Format("{0}{1}", httpResult.StatusDescription, httpResult.OtherDescription), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return; } //else if ((int)httpResult.StatusCode == 403) //{ // if (MessageBox.Show("用户已在其他地方登陆 是否强制登陆?", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK) // { // headers.Add("Authed", "true"); // httpResult = httpReq.HttpPost("auth/tokens", null, headers); // } // else // { // return; // } //} if ((int)httpResult.StatusCode >= 200 && (int)httpResult.StatusCode < 300) { li = httpReq.ScriptDeserialize<LoginID>(httpResult.Html); PassValue.token = "Token " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(li.id));//ID加密 PassValue.tokenid = li.id; PassValue.Code = li.principal.code; if (needRemPassword) { Global.GetConfig().SetConfigString("system", "LoginUserName", this.TxtUser.Text.Trim()); Global.GetConfig().SetConfigString("system", "LoginUserPSW", this.TxtKey.Text.Trim()); } //获取楼层信息 Layout floorLayout = httpReq.HttpGet<Layout>("layout"); if (floorLayout != null) { foreach (Floor floor in floorLayout.floors) { PassValue.tablesstatuslist.Add(floor.number); } PassValue.tablesstatuslist.Sort(); } //获取桌子信息 PassValue.Tables = httpReq.HttpGet<List<Table>>("tables"); //获取交接班需要的信息 Shift shift = new Shift(); shift.cashier = new Employee(); if (li != null) { shift.cashier.id = li.principal.id; } httpResult = httpReq.HttpPost("shifts", shift); if ((int)httpResult.StatusCode >= 200 && (int)httpResult.StatusCode < 300) { shift = httpReq.ScriptDeserialize<Shift>(httpResult.Html); PassValue.shiftId = shift.id; needHandOver = shift.isWarn; } else if ((int)httpResult.StatusCode == 0) { MessageBox.Show(string.Format("{0}{1}", httpResult.StatusDescription, httpResult.OtherDescription), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return; } Main frmMain = new Main(this); frmMain.Show(); } else { MessageBox.Show("请输入正确的工号和密码!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); this.TxtKey.Text = ""; this.TxtUser.Text = ""; this.TxtUser.Focus(); } } }
private static string FindProblemDescription(int typeSizeInBits, int shiftBy, Shift shiftDirection, out bool isLiteralZero) { if (shiftBy == 0) { isLiteralZero = true; return(string.Format(MessageFormat_UselessShift, 0)); } isLiteralZero = false; if (shiftBy < typeSizeInBits) { return(null); } if (shiftDirection == Shift.Right) { return(string.Format(MessageFormat_RightShiftTooLarge, shiftBy)); } var shiftSuggestion = shiftBy % typeSizeInBits; if (typeSizeInBits == 64) { return(shiftSuggestion == 0 ? string.Format(MessageFormat_UselessShift, shiftBy) : string.Format(MessageFormat_ShiftTooLarge, shiftSuggestion)); } if (shiftSuggestion == 0) { return(string.Format(MessageFormat_UseLargerTypeOrPromote, "less than " + typeSizeInBits)); } return(string.Format(MessageFormat_UseLargerTypeOrPromote, shiftSuggestion)); }
partial void UpdateShift(Shift instance);
public void setShift(Shift turno) { this.shift = turno; }
public NDbResult <List <Shift> > GetShifts() { var results = Shift.GetShifts(); return(results); }
partial void InsertShift(Shift instance);
public StandardDoorActor(byte[] record) : base(record) { flag = Shift.AsByte(Variable, 0x003F); locked = Shift.AsBool(Variable, 0x80); }
public LiftingDoorActor(byte[] record) : base(record) { flags = Shift.AsByte(Variable, 0x003F); type = Shift.AsByte(Variable, 0x0FC0); }
//Insert new shift public void InsertShift(Shift shift) { try { using (var conn = CreateConnection()) { var cmd = new SqlCommand("IA.uspInsertShift", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@Date", SqlDbType.DateTime, 8).Value = shift.Date; cmd.Parameters.Add("@EmpID", SqlDbType.Int, 4).Value = shift.EmpID; cmd.Parameters.Add("@TOSID", SqlDbType.Int, 4).Value = shift.TOSID; cmd.Parameters.Add("@ShiftID", SqlDbType.Int, 4).Direction = ParameterDirection.Output; conn.Open(); cmd.ExecuteNonQuery(); shift.EmpID = (int) cmd.Parameters["@ShiftID"].Value; } } catch { throw new ApplicationException("An error occured in the data layer while inserting shift"); } }
public TransitionPlaneActor(byte[] record) : base(record) { flag = Shift.AsByte(Variable, 0x003F); type = Shift.AsUInt16(Variable, 0xFFC0); }
public void AddShift(Shift shift) { iContext.AddShift(shift); }
public async Task SheriffOverrideConflictRemove() { var sheriffObject = await CreateSheriffUsingDbContext(); var newLocation = new Location { Name = "New PLace", AgencyId = "zfddf2342" }; await Db.Location.AddAsync(newLocation); await Db.SaveChangesAsync(); var startDate = DateTimeOffset.UtcNow.Date.AddHours(1); var endDate = startDate.AddHours(8); var shift = new Shift { Id = 9000665, StartDate = startDate, EndDate = endDate, LocationId = newLocation.Id, Timezone = "America/Vancouver", SheriffId = sheriffObject.Id }; Db.Shift.Add(shift); var duty = new Duty { LocationId = newLocation.Id, }; Db.Duty.Add(duty); await Db.SaveChangesAsync(); var dutySlot = new DutySlot { SheriffId = sheriffObject.Id, LocationId = newLocation.Id, StartDate = startDate, EndDate = endDate, DutyId = duty.Id }; Db.DutySlot.Add(dutySlot); var lookupCode = new LookupCode { Code = "zz4", Description = "gg", LocationId = newLocation.Id }; await Db.LookupCode.AddAsync(lookupCode); await Db.SaveChangesAsync(); var entity = new SheriffLeaveDto { LeaveTypeId = lookupCode.Id, SheriffId = sheriffObject.Id, StartDate = startDate, EndDate = endDate }; Assert.True(Db.Shift.Any(s => s.ExpiryDate == null && s.Id == shift.Id)); Assert.True(Db.DutySlot.Any(ds => ds.ExpiryDate == null && ds.Id == dutySlot.Id)); await _controller.AddSheriffLeave(entity, true); Assert.False(Db.Shift.Any(s => s.ExpiryDate == null && s.Id == shift.Id)); Assert.False(Db.DutySlot.Any(ds => ds.ExpiryDate == null && ds.Id == dutySlot.Id)); }
public RegShiftReg(Reg Reg = default, Shift Shift = default, Reg RegCount = default) { this.Reg = Reg; this.Shift = Shift; this.RegCount = RegCount; }
protected void AddEmailReport(string[] toEmailAddressesForHourly, string[] toEmailAddressesForShiftly, Shift shift, string department = null) { if (department is null) { department = _defaultDepartment; } EmailReportConfigs.Add(new EmailReportConfig(department, shift, toEmailAddressesForHourly, toEmailAddressesForShiftly)); }
private bool Equals(LogNormalDistribution other) { return(Mean.Equals(other.Mean) && StandardDeviation.Equals(other.StandardDeviation) && Shift.Equals(other.Shift)); }
ISurface ISurface.Shift(Shift shift) { return this.Shift(shift); }
public string GetShiftName(DataTable segmentsTable) { return(DataTable_Functions.GetTableValue(segmentsTable, "SHIFT_ID", Shift.ToString(), "SHIFT")); }
private void fillWeeklyShiftTable(string org_name) { SqlConnection conn = new SqlConnection(getConnectionString()); string sql = "SELECT [Day], [Begin Time], [End Time], [Shift Info] FROM [Shift Schedule] WHERE [Organization Name] = '" + org_name + "'"; try { conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataReader myReader = cmd.ExecuteReader(); while (myReader.Read()) { for(int i = 0; i < Convert.ToInt32(myReader[3]); i++) { Shift shiftInWeek = new Shift(null, null, null, null, null, null, null, null); shiftInWeek.setDay(myReader[0].ToString().Trim()); shiftInWeek.setBegin_Time(myReader[1].ToString().Trim()); shiftInWeek.setEnd_Time(myReader[2].ToString().Trim()); weeklyShiftTable.AddShift(shiftInWeek); } } } catch (System.Data.SqlClient.SqlException ex) { string msg = "Insert Error:"; msg += ex.Message; throw new Exception(msg); } finally { conn.Close(); } }
private void CalculateOpenShiftTimes(AttData attendanceRecord, Shift shift) { try { //Calculate WorkMin if (attendanceRecord != null) { if (attendanceRecord.TimeOut != null && attendanceRecord.TimeIn != null) { attendanceRecord.Remarks = ""; TimeSpan mins = (TimeSpan)(attendanceRecord.TimeOut - attendanceRecord.TimeIn); //Check if GZ holiday then place all WorkMin in GZOTMin if (attendanceRecord.StatusGZ == true) { attendanceRecord.GZOTMin = (short)mins.TotalMinutes; attendanceRecord.WorkMin = (short)mins.TotalMinutes; attendanceRecord.StatusGZOT = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[GZ-OT]"; } else if (attendanceRecord.StatusDO == true) { attendanceRecord.OTMin = (short)mins.TotalMinutes; attendanceRecord.WorkMin = (short)mins.TotalMinutes; attendanceRecord.StatusOT = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[R-OT]"; } else { if (shift.HasBreak == true) { attendanceRecord.WorkMin = (short)(mins.TotalMinutes - shift.BreakMin); attendanceRecord.ShifMin = (short)(CalculateShiftMinutes(shift, attendanceRecord.AttDate.Value.DayOfWeek) - (short)shift.BreakMin); } else { // CalculateShiftEndTime = ShiftStart + DutyHours TimeSpan shiftEnd = CalculateShiftEndTime(shift, attendanceRecord.AttDate.Value.DayOfWeek); attendanceRecord.WorkMin = (short)(mins.TotalMinutes); //Calculate OverTIme, if (mins.TotalMinutes > (CalculateShiftMinutes(shift, attendanceRecord.AttDate.Value.DayOfWeek) + shift.OverTimeMin)) { attendanceRecord.OTMin = (Int16)(Convert.ToInt16(mins.TotalMinutes) - CalculateShiftMinutes(shift, attendanceRecord.AttDate.Value.DayOfWeek)); attendanceRecord.WorkMin = (short)((mins.TotalMinutes) - attendanceRecord.OTMin); attendanceRecord.StatusOT = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[N-OT]"; } //Calculate Early Out if (mins.TotalMinutes < (CalculateShiftMinutes(shift, attendanceRecord.AttDate.Value.DayOfWeek) - shift.EarlyOut)) { Int16 EarlyoutMin = (Int16)(CalculateShiftMinutes(shift, attendanceRecord.AttDate.Value.DayOfWeek) - Convert.ToInt16(mins.TotalMinutes)); if (EarlyoutMin > shift.EarlyOut) { attendanceRecord.EarlyOut = EarlyoutMin; attendanceRecord.StatusEO = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[EO]"; } else { attendanceRecord.StatusEO = null; attendanceRecord.EarlyOut = null; attendanceRecord.Remarks.Replace("[EO]", ""); } } else { attendanceRecord.StatusEO = null; attendanceRecord.EarlyOut = null; attendanceRecord.Remarks.Replace("[EO]", ""); } // round off work mins if overtime less than shift.OverTimeMin > if (attendanceRecord.WorkMin > CalculateShiftMinutes(shift, attendanceRecord.AttDate.Value.DayOfWeek) && (attendanceRecord.WorkMin <= (CalculateShiftMinutes(shift, attendanceRecord.AttDate.Value.DayOfWeek) + shift.OverTimeMin))) { attendanceRecord.WorkMin = CalculateShiftMinutes(shift, attendanceRecord.AttDate.Value.DayOfWeek); } } } } } } catch (Exception ex) { string _error = ""; if (ex.InnerException.Message != null) { _error = ex.InnerException.Message; } else { _error = ex.Message; } _myHelperClass.WriteToLogFile("Attendance Processing at Calculating Times; " + _error); } }
/// <summary> /// 确认交接 /// </summary> private void Btn_Transfer_Click(object sender, EventArgs e) { if (PassValue.IsPrintshifts == false) { MessageBox.Show("请先打印交接班单!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return; } Shift shift = new Shift(); shift.end = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace(' ', 'T'); Employee cashier = new Employee(); cashier.id = PassValue.shiftId; shift.cashier = cashier; HttpResult httpResult = httpReq.HttpPatch(string.Format("shifts/{0}", PassValue.shiftId), shift); if ((int)httpResult.StatusCode == 0) { MessageBox.Show(string.Format("{0}{1}", httpResult.StatusDescription, httpResult.OtherDescription), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return; } if ((int)httpResult.StatusCode >= 200 && (int)httpResult.StatusCode < 300) { MessageBox.Show("交接成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); httpResult = httpReq.HttpDelete(string.Format("auth/tokens/{0}", PassValue.tokenid)); if ((int)httpResult.StatusCode == 0) { MessageBox.Show(string.Format("{0}{1}", httpResult.StatusDescription, httpResult.OtherDescription), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return; } string path = Application.StartupPath + @"/点菜100.exe"; System.Diagnostics.Process.Start(path); Application.Exit(); } else if ((int)httpResult.StatusCode == 401) { LoginBusiness lg = new LoginBusiness(); lg.LoginAgain(); return; } else { if ((int)httpResult.StatusCode == 403) { MessageBox.Show("有反结算账单未结算,请结算!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else { MessageBox.Show("未知错误!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } }
private void CalculateShiftTimes(AttData attendanceRecord, Shift shift) { try { //Calculate WorkMin attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[LI]", ""); attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[EI]", ""); attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[EO]", ""); attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[LO]", ""); attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[G-OT]", ""); attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[R-OT]", ""); attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[N-OT]", ""); attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[Manual]", ""); TimeSpan mins = (TimeSpan)(attendanceRecord.TimeOut - attendanceRecord.TimeIn); attendanceRecord.WorkMin = (short)(mins.TotalMinutes); //Check if GZ holiday then place all WorkMin in GZOTMin if (attendanceRecord.StatusGZ == true) { attendanceRecord.PDays = 0; attendanceRecord.ABDays = 0; attendanceRecord.LeaveDays = 0; attendanceRecord.GZOTMin = (short)mins.TotalMinutes; attendanceRecord.WorkMin = (short)mins.TotalMinutes; attendanceRecord.StatusGZOT = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[G-OT]"; attendanceRecord.ABDays = 0; attendanceRecord.PDays = 0; attendanceRecord.LeaveDays = 0; } //if Rest day then place all WorkMin in OTMin else if (attendanceRecord.StatusDO == true) { if (attendanceRecord.Emp.HasOT != false) { attendanceRecord.PDays = 0; attendanceRecord.ABDays = 0; attendanceRecord.LeaveDays = 0; attendanceRecord.OTMin = (short)mins.TotalMinutes; attendanceRecord.WorkMin = (short)mins.TotalMinutes; attendanceRecord.StatusOT = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[R-OT]"; attendanceRecord.ABDays = 0; attendanceRecord.PDays = 0; attendanceRecord.LeaveDays = 0; } } else { /////////// to-do -----calculate Margins for those shifts which has break mins if (attendanceRecord.StatusBreak == true) { attendanceRecord.WorkMin = (short)(attendanceRecord.WorkMin - attendanceRecord.BreakMin); attendanceRecord.ShifMin = (short)(ProcessSupportFunc.CalculateShiftMinutes(shift, attendanceRecord.AttDate.Value.DayOfWeek) - (short)attendanceRecord.BreakMin); } else { if (attendanceRecord.StatusHL == true && attendanceRecord.StatusLeave != true) { attendanceRecord.ABDays = 0; attendanceRecord.PDays = 0.5; attendanceRecord.LeaveDays = 0.5; } else { attendanceRecord.ABDays = 0; attendanceRecord.PDays = 1; attendanceRecord.LeaveDays = 0; } attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[Absent]", ""); attendanceRecord.StatusAB = false; attendanceRecord.StatusP = true; #region -- Margins-- //Calculate Late IN, Compare margin with Shift Late In if (attendanceRecord.TimeIn.Value.TimeOfDay > attendanceRecord.DutyTime) { TimeSpan lateMinsSpan = (TimeSpan)(attendanceRecord.TimeIn.Value.TimeOfDay - attendanceRecord.DutyTime); if (lateMinsSpan.TotalMinutes > shift.LateIn) { attendanceRecord.LateIn = (short)lateMinsSpan.TotalMinutes; attendanceRecord.StatusLI = true; attendanceRecord.EarlyIn = null; attendanceRecord.Remarks = attendanceRecord.Remarks + "[LI]"; } else { attendanceRecord.StatusLI = null; attendanceRecord.LateIn = null; attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[LI]", ""); } } else { attendanceRecord.StatusLI = null; attendanceRecord.LateIn = null; attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[LI]", ""); } //Calculate Early In, Compare margin with Shift Early In if (attendanceRecord.TimeIn.Value.TimeOfDay < attendanceRecord.DutyTime) { TimeSpan EarlyInMinsSpan = (TimeSpan)(attendanceRecord.DutyTime - attendanceRecord.TimeIn.Value.TimeOfDay); if (EarlyInMinsSpan.TotalMinutes > shift.EarlyIn) { attendanceRecord.EarlyIn = (short)EarlyInMinsSpan.TotalMinutes; attendanceRecord.StatusEI = true; attendanceRecord.LateIn = null; attendanceRecord.Remarks = attendanceRecord.Remarks + "[EI]"; } else { attendanceRecord.StatusEI = null; attendanceRecord.EarlyIn = null; attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[EI]", ""); } } else { attendanceRecord.StatusEI = null; attendanceRecord.EarlyIn = null; attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[EI]", ""); } // CalculateShiftEndTime = ShiftStart + DutyHours DateTime shiftEnd = ProcessSupportFunc.CalculateShiftEndTimeWithAttData(attendanceRecord.AttDate.Value, attendanceRecord.DutyTime.Value, (short)(attendanceRecord.ShifMin + attendanceRecord.BreakMin)); //Calculate Early Out, Compare margin with Shift Early Out if (attendanceRecord.TimeOut < shiftEnd) { TimeSpan EarlyOutMinsSpan = (TimeSpan)(shiftEnd - attendanceRecord.TimeOut); if (EarlyOutMinsSpan.TotalMinutes > shift.EarlyOut) { attendanceRecord.EarlyOut = (short)EarlyOutMinsSpan.TotalMinutes; attendanceRecord.StatusEO = true; attendanceRecord.LateOut = null; attendanceRecord.Remarks = attendanceRecord.Remarks + "[EO]"; } else { attendanceRecord.StatusEO = null; attendanceRecord.EarlyOut = null; attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[EO]", ""); } } else { attendanceRecord.StatusEO = null; attendanceRecord.EarlyOut = null; attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[EO]", ""); } //Calculate Late Out, Compare margin with Shift Late Out if (attendanceRecord.TimeOut > shiftEnd) { TimeSpan LateOutMinsSpan = (TimeSpan)(attendanceRecord.TimeOut - shiftEnd); if (LateOutMinsSpan.TotalMinutes > shift.LateOut) { attendanceRecord.LateOut = (short)LateOutMinsSpan.TotalMinutes; // Late Out cannot have an early out, In case of poll at multiple times before and after shiftend attendanceRecord.EarlyOut = null; attendanceRecord.StatusLO = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[LO]"; } else { attendanceRecord.StatusLO = null; attendanceRecord.LateOut = null; attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[LO]", ""); } } else { attendanceRecord.StatusLO = null; attendanceRecord.LateOut = null; attendanceRecord.Remarks = attendanceRecord.Remarks.Replace("[LO]", ""); } #endregion if ((attendanceRecord.StatusGZ != true || attendanceRecord.StatusDO != true) && attendanceRecord.Emp.HasOT == true) { if (attendanceRecord.LateOut != null) { if ((attendanceRecord.WorkMin - attendanceRecord.ShifMin) > shift.OverTimeMin) { attendanceRecord.OTMin = (short)(attendanceRecord.WorkMin - attendanceRecord.ShifMin); attendanceRecord.StatusOT = true; attendanceRecord.Remarks = attendanceRecord.Remarks + "[N-OT]"; } } } //Subtract EarlyIn and LateOut from Work Minutes if (shift.SubtractEIFromWork == true) { if (attendanceRecord.EarlyIn != null && attendanceRecord.EarlyIn > shift.EarlyIn) { attendanceRecord.WorkMin = (short)(attendanceRecord.WorkMin - attendanceRecord.EarlyIn); } } if (shift.SubtractOTFromWork == true) { if (attendanceRecord.LateOut != null && attendanceRecord.LateOut > shift.LateOut) { attendanceRecord.WorkMin = (short)(attendanceRecord.WorkMin - attendanceRecord.LateOut); } } if (shift.AddEIInOT == true && attendanceRecord.Emp.HasOT == true) { if (attendanceRecord.EarlyIn != null) { if (attendanceRecord.OTMin != null) { attendanceRecord.OTMin = (short)(attendanceRecord.OTMin + attendanceRecord.EarlyIn); } else { attendanceRecord.OTMin = (short)attendanceRecord.EarlyIn; } } } if (shift.RoundOffWorkMin == true) { if (attendanceRecord.LateOut != null || attendanceRecord.EarlyIn != null) { if (attendanceRecord.WorkMin > attendanceRecord.ShifMin && (attendanceRecord.WorkMin <= (attendanceRecord.ShifMin + shift.OverTimeMin))) { attendanceRecord.WorkMin = attendanceRecord.ShifMin; } } } if (attendanceRecord.StatusHL == true) { attendanceRecord.PDays = 0.5; attendanceRecord.ABDays = 0; attendanceRecord.LeaveDays = 0.5; } else { attendanceRecord.PDays = 1; attendanceRecord.ABDays = 0; attendanceRecord.LeaveDays = 0; } //Mark Absent if less than 4 hours if (attendanceRecord.AttDate.Value.DayOfWeek != DayOfWeek.Friday && attendanceRecord.StatusDO != true && attendanceRecord.StatusGZ != true) { short MinShiftMin = (short)shift.MinHrs; if (attendanceRecord.WorkMin < MinShiftMin) { attendanceRecord.StatusAB = true; attendanceRecord.StatusP = false; attendanceRecord.Remarks = "[Absent]"; } else { attendanceRecord.StatusAB = false; attendanceRecord.StatusP = true; attendanceRecord.Remarks.Replace("[Absent]", ""); } } } } } catch (Exception ex) { } }
/// <summary> /// 新增排班 /// </summary> /// <param name="shift">排班</param> /// <returns></returns> public void Add(Shift shift) { shift.Id = _idGenerator.CreateId(); _context.Shift.Add(shift); }
private TimeSpan CalculateShiftEndTime(Shift shift, short ShiftMins) { return(shift.StartTime + (new TimeSpan(0, ShiftMins, 0))); }
private Shift GetShiftsByWaiterRestaurantDateAndTime(IRepository repository, Shift shift) { return(repository.FindBy <Shift>(s => s.Restaurant.Id == shift.Restaurant.Id && s.Staff.Id == shift.Staff.Id && s.IsCancelled == false && s.StartTime == shift.StartTime).FirstOrDefault()); }
public ActionResult Edit(int id) { Shift shift = _shiftRepository.Get(id); return(View(shift)); }
//Calculate Shift of a Group in Period public Shift GetShift(DateTime dtDateTimeArg, Int16 intGroupArg) { Shift shiShiftLoc = 0; int intShiftTemp = 0; //Calculation of Basic Duration TimeSpan tsBasicDuration = dtDateTimeArg - this.dtShiftOrginPty; tsBasicDuration = tsBasicDuration.Add(new TimeSpan(1, 0, 0, 0)); //Calculation of Durations int tsEfectiveDuration = tsBasicDuration.Days % this.intPeriodLengethPty; int intRemaining = tsEfectiveDuration % this.intWorkShiftsRepeatCountPty; int intDivided = tsEfectiveDuration / this.intWorkShiftsRepeatCountPty; //Work Shifts if (tsEfectiveDuration >= 1 && tsEfectiveDuration <= this.intWorkShiftsLengethPty) { if (intRemaining != 0) { intShiftTemp = intDivided + 1; } else { intShiftTemp = intDivided; } } //Rest Shifts else { intShiftTemp = this.intShiftsCountInDayPty + 1; } switch (this.stShiftType) { case ShiftType.تعداد۱ـمدت۲۴ـکاری۱ـاستراحت۲: intShiftTemp += intGroupArg - 1; intShiftTemp %= this.intPeriodShiftsCountPty; if (intShiftTemp == 1) { shiShiftLoc = Shift.روز; } if (intShiftTemp == 2) { shiShiftLoc = Shift.استراحت; } if (intShiftTemp == 3) { shiShiftLoc = Shift.استراحت; } break; case ShiftType.تعداد۲ـمدت۱۲ـکاری۲ـاستراحت۲: intShiftTemp += intGroupArg - 1; intShiftTemp %= this.intPeriodShiftsCountPty; if (intShiftTemp == 1) { shiShiftLoc = Shift.روز; } if (intShiftTemp == 2) { shiShiftLoc = Shift.شب; } if (intShiftTemp == 3) { shiShiftLoc = Shift.استراحت; } break; case ShiftType.تعداد3ـمدت8ـکاری۲ـاستراحت۲: intShiftTemp += intGroupArg - 1; intShiftTemp %= this.intPeriodShiftsCountPty; if (intShiftTemp == 1) { shiShiftLoc = Shift.صبح; } if (intShiftTemp == 2) { shiShiftLoc = Shift.عصر; } if (intShiftTemp == 3) { shiShiftLoc = Shift.شب; } if (intShiftTemp == 4) { shiShiftLoc = Shift.استراحت; } break; case ShiftType.تعداد۲ـمدت8ـکاری3ـاستراحت1: intShiftTemp += intGroupArg - 1; intShiftTemp %= this.intPeriodShiftsCountPty; if (intShiftTemp == 1) { shiShiftLoc = Shift.صبح; } if (intShiftTemp == 2) { shiShiftLoc = Shift.عصر; } if (intShiftTemp == 3) { shiShiftLoc = Shift.استراحت; } break; } //Rest Shift return(shiShiftLoc); }
public static void Initialize(WTSContext context) { context.Database.EnsureCreated(); if (context.Employees.Any()) { return; } var shifts = new Shift[] { new Shift { ID = 1, Start = new DateTime(2016, 11, 11, 9, 0, 0), End = new DateTime(2016, 11, 11, 17, 0, 0), Name = "Morning 9-17", }, new Shift { ID = 2, Start = new DateTime(2016, 11, 12, 10, 0, 0), End = new DateTime(2016, 11, 12, 14, 0, 0), Name = "Morning 10-14" }, new Shift { ID = 4, Start = new DateTime(2016, 11, 13, 9, 0, 0), End = new DateTime(2016, 11, 13, 17, 0, 0), Name = "Morning 9-17" }, new Shift { ID = 5, Start = new DateTime(2016, 11, 14, 10, 0, 0), End = new DateTime(2016, 11, 14, 14, 0, 0), Name = "Morning 10-14" }, new Shift { ID = 6, Start = new DateTime(2016, 11, 15, 9, 0, 0), End = new DateTime(2016, 11, 15, 17, 0, 0), Name = "Morning 9-17" }, new Shift { ID = 7, Start = new DateTime(2016, 12, 13, 9, 0, 0), End = new DateTime(2016, 12, 13, 17, 0, 0), Name = "Morning 9-17" }, new Shift { ID = 8, Start = new DateTime(2016, 12, 14, 9, 0, 0), End = new DateTime(2016, 12, 14, 17, 0, 0), Name = "Morning 9-17" }, }; foreach (Shift shift in shifts) { context.Shifts.Add(shift); } context.SaveChanges(); var employees = new Employee[] { new Employee { ID = 1, FirstName = "John", Surname = "Brown" }, new Employee { ID = 2, FirstName = "Harry", Surname = "Potter" }, new Employee { ID = 3, FirstName = "Alice", Surname = "White" }, new Employee { ID = 4, FirstName = "Joe", Surname = "Mellor" }, new Employee { ID = 5, FirstName = "Neil", Surname = "Fearn" }, new Employee { ID = 6, FirstName = "Rob", Surname = "Lang" } }; foreach (Employee employee in employees) { context.Employees.Add(employee); } context.SaveChanges(); var workShifts = new EmployeeWorkShift[] { new EmployeeWorkShift { EmployeeId = 1, ShiftId = 1 }, new EmployeeWorkShift { EmployeeId = 2, ShiftId = 1 }, new EmployeeWorkShift { EmployeeId = 3, ShiftId = 1 }, new EmployeeWorkShift { EmployeeId = 4, ShiftId = 1 }, new EmployeeWorkShift { EmployeeId = 1, ShiftId = 2 }, new EmployeeWorkShift { EmployeeId = 5, ShiftId = 2 }, new EmployeeWorkShift { EmployeeId = 6, ShiftId = 2 }, new EmployeeWorkShift { EmployeeId = 1, ShiftId = 4 }, new EmployeeWorkShift { EmployeeId = 4, ShiftId = 4 }, new EmployeeWorkShift { EmployeeId = 6, ShiftId = 4 }, new EmployeeWorkShift { EmployeeId = 2, ShiftId = 4 }, new EmployeeWorkShift { EmployeeId = 6, ShiftId = 5 }, new EmployeeWorkShift { EmployeeId = 2, ShiftId = 5 }, new EmployeeWorkShift { EmployeeId = 4, ShiftId = 5 }, new EmployeeWorkShift { EmployeeId = 5, ShiftId = 5 }, new EmployeeWorkShift { EmployeeId = 1, ShiftId = 6 }, new EmployeeWorkShift { EmployeeId = 2, ShiftId = 6 }, new EmployeeWorkShift { EmployeeId = 3, ShiftId = 6 }, new EmployeeWorkShift { EmployeeId = 6, ShiftId = 6 }, new EmployeeWorkShift { EmployeeId = 3, ShiftId = 7 }, new EmployeeWorkShift { EmployeeId = 5, ShiftId = 7 }, new EmployeeWorkShift { EmployeeId = 2, ShiftId = 7 }, new EmployeeWorkShift { EmployeeId = 1, ShiftId = 8 }, }; foreach (EmployeeWorkShift workShift in workShifts) { context.EmployeeWorkShifts.Add(workShift); } context.SaveChanges(); }
private Shift GetShiftFromInt(int intShiftArg) { Shift shiShiftLoc = 0; switch (this.stShiftType) { case ShiftType.تعداد۱ـمدت۲۴ـکاری۱ـاستراحت۲: if (intShiftArg == 1) { shiShiftLoc = Shift.شبانه_روز; } if (intShiftArg == 2) { shiShiftLoc = Shift.استراحت; } if (intShiftArg == 3) { shiShiftLoc = Shift.استراحت; } break; case ShiftType.تعداد۲ـمدت۱۲ـکاری۲ـاستراحت۲: if (intShiftArg == 1) { shiShiftLoc = Shift.صبح; } if (intShiftArg == 2) { shiShiftLoc = Shift.شب; } if (intShiftArg == 3) { shiShiftLoc = Shift.استراحت; } break; case ShiftType.تعداد3ـمدت8ـکاری۲ـاستراحت۲: if (intShiftArg == 1) { shiShiftLoc = Shift.صبح; } if (intShiftArg == 2) { shiShiftLoc = Shift.عصر; } if (intShiftArg == 3) { shiShiftLoc = Shift.شب; } if (intShiftArg == 4) { shiShiftLoc = Shift.استراحت; } break; case ShiftType.تعداد۲ـمدت8ـکاری3ـاستراحت1: if (intShiftArg == 1) { shiShiftLoc = Shift.صبح; } if (intShiftArg == 2) { shiShiftLoc = Shift.عصر; } if (intShiftArg == 3) { shiShiftLoc = Shift.شب; } break; } return(shiShiftLoc); }
/// <summary> /// Check if this new shift occurs the next morning after a night shift or night before a morning shift /// </summary> /// <param name="newShift">The new shift</param> /// <returns>true if it is consecutive overnight, false otherwise</returns> public Shift ReturnConsecutiveOpenCloseShifts(Shift newShift) { bool checkYesterday = false; // check if this is even a morning or night shift if (!(newShift.StartTime <= TimeUtilities.ConvertToDateTime("0900") || newShift.EndTime >= TimeUtilities.ConvertToDateTime("2100"))) { // not an opening or closing shift - return false return(null); } // holds the target start and ened times DateTime targetStart = newShift.StartTime; DateTime targetEnd = newShift.EndTime; // get the index of this shifts day int index = TimeUtilities.daysOfWeek.IndexOf(newShift.Day); int target = 0; // get the target index of the day we wish to check if (newShift.StartTime <= TimeUtilities.ConvertToDateTime("0900")) { // this shift is an opening shift // we will need to check previous day checkYesterday = true; // increment target times by 1 day targetStart = targetStart.AddDays(1); targetEnd = targetEnd.AddDays(1); // check if current index is monday if (index == 0) { // set target to sunday target = TimeUtilities.daysOfWeek.Count - 1; } else { // otherwise subtract 1 target = index - 1; } } else if (newShift.EndTime >= TimeUtilities.ConvertToDateTime("2100")) {// this shift is an opening shift // we will check next day's shift checkYesterday = false; // increment target times by 1 day targetStart.AddDays(-1); targetEnd.AddDays(-1); // check if current index is sunday if (index == TimeUtilities.daysOfWeek.Count - 1) { // set target to monday target = 0; } else { // otherwise add 1 target = index + 1; } } else { // should be impossible to reach this point due to first if statement at top of method throw new Exception("WTF?! How'd you get here?!?"); } // do the actual checking foreach (Shift shift in this._shiftsWorking._shifts[TimeUtilities.daysOfWeek[target]]) { // if we're checking yesterday if (checkYesterday) { TimeSpan difference = (targetStart - shift.EndTime); // get time difference and see if it is at least or less than expected amount if (difference <= new TimeSpan(11, 30, 0)) { // these are consecutive shifts, return true return(shift); } } else { // we are checking tomorrow // get time difference and see if it is at least or less than expected amount if ((targetEnd - shift.StartTime) <= new TimeSpan(11, 30, 0)) { // these are consecutive shifts, return true return(shift); } } } // never found a conflicting shift return(null); }
partial void DeleteShift(Shift instance);
/// <summary> /// Method to process the shift entities in a batch manner. /// </summary> /// <param name="accessToken">The MS Graph Access token.</param> /// <param name="lookUpEntriesFoundList">The lookUp entries that have been found.</param> /// <param name="shiftsNotFoundList">The shifts that have not been found.</param> /// <param name="userModelList">The users list.</param> /// <param name="userModelNotFoundList">The list of users that have not been found.</param> /// <param name="lookUpData">The look up data from the Shift Entity Mapping table.</param> /// <param name="processKronosUsersQueueInBatch">The Kronos users in the queue.</param> /// <param name="shiftsResponse">The Shifts Response from MS Graph.</param> /// <param name="monthPartitionKey">The monthwise partition.</param> /// <returns>A unit of execution.</returns> private async Task ProcessShiftEntitiesBatchAsync( string accessToken, List<TeamsShiftMappingEntity> lookUpEntriesFoundList, List<Shift> shiftsNotFoundList, List<UserDetailsModel> userModelList, List<UserDetailsModel> userModelNotFoundList, List<TeamsShiftMappingEntity> lookUpData, IEnumerable<UserDetailsModel> processKronosUsersQueueInBatch, App.KronosWfc.Models.ResponseEntities.Shifts.UpcomingShifts.Response shiftsResponse, string monthPartitionKey) { this.telemetryClient.TrackTrace($"ShiftController - ProcessShiftEntitiesBatchAsync started at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}"); var shiftDisplayName = string.Empty; var shiftNotes = string.Empty; var shiftTheme = this.appSettings.ShiftTheme; // This foreach loop processes each user in the batch. foreach (var user in processKronosUsersQueueInBatch) { // This foreach loop will process the shift(s) that belong to each user. foreach (var kronosShift in shiftsResponse?.Schedule?.ScheduleItems?.ScheduleShift) { if (user.KronosPersonNumber == kronosShift.Employee.FirstOrDefault().PersonNumber) { this.telemetryClient.TrackTrace($"ShiftController - Processing the shifts for user: {user.KronosPersonNumber}"); List<ShiftActivity> shiftActivity = new List<ShiftActivity>(); // This foreach loop will create the necessary Shift Activities // based on the Shift Segments that are retrieved from Kronos. foreach (var activity in kronosShift?.ShiftSegments) { shiftActivity.Add(new ShiftActivity { IsPaid = true, StartDateTime = this.utility.CalculateStartDateTime(activity), EndDateTime = this.utility.CalculateEndDateTime(activity), Code = string.Empty, DisplayName = activity.SegmentTypeName, }); } var shift = new Shift { UserId = user.ShiftUserId, SchedulingGroupId = user.ShiftScheduleGroupId, SharedShift = new SharedShift { DisplayName = shiftDisplayName, Notes = this.utility.GetShiftNotes(kronosShift), StartDateTime = shiftActivity[0].StartDateTime, EndDateTime = shiftActivity[shiftActivity.Count - 1].EndDateTime, Theme = shiftTheme, Activities = shiftActivity, }, }; shift.KronosUniqueId = this.utility.CreateUniqueId(shift); this.telemetryClient.TrackTrace($"ShiftController-KronosHash: {shift.KronosUniqueId}"); userModelList.Add(user); if (lookUpData.Count == 0) { shiftsNotFoundList.Add(shift); userModelNotFoundList.Add(user); } else { var kronosUniqueIdExists = lookUpData.Where(c => c.KronosUniqueId == shift.KronosUniqueId); if (kronosUniqueIdExists.Any() && (kronosUniqueIdExists != default(List<TeamsShiftMappingEntity>))) { lookUpEntriesFoundList.Add(kronosUniqueIdExists.FirstOrDefault()); } else { shiftsNotFoundList.Add(shift); userModelNotFoundList.Add(user); } } } } } if (lookUpData.Except(lookUpEntriesFoundList).Any()) { await this.DeleteOrphanDataShiftsEntityMappingAsync(accessToken, lookUpEntriesFoundList, userModelList, lookUpData).ConfigureAwait(false); } await this.CreateEntryShiftsEntityMappingAsync(accessToken, userModelNotFoundList, shiftsNotFoundList, monthPartitionKey).ConfigureAwait(false); this.telemetryClient.TrackTrace($"ShiftController - ProcessShiftEntitiesBatchAsync ended at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}"); }
public async Task <IActionResult> Swap([FromBody] SwapShiftsRequest request) { #region Error handling - String parsing to Guid // Parse input strings to Guids, if parsing fails abort if (!Guid.TryParse(request.ShiftAId, out Guid ShiftAGuid)) { return(StatusCode(StatusCodes.Status406NotAcceptable, "Shift Id A (" + request.ShiftAId + ") is not a valid Guid! Aborting swap...")); } if (!Guid.TryParse(request.ShiftBId, out Guid ShiftBGuid)) { return(StatusCode(StatusCodes.Status406NotAcceptable, "Shift Id B (" + request.ShiftBId + ") is not a valid Guid! Aborting swap...")); } #endregion Shift a = await _shiftService.GetShiftByIdAsync(ShiftAGuid); Shift b = await _shiftService.GetShiftByIdAsync(ShiftBGuid); #region Error handling // Guids are valid, but check if they actually match valid Shift Ids if (a == null) { return(StatusCode(StatusCodes.Status404NotFound, "Shift A Id:" + ShiftAGuid + " is a valid Guid, but does not match any shift Ids in the database!")); } if (b == null) { return(StatusCode(StatusCodes.Status404NotFound, "Shift B Id:" + ShiftBGuid + " is a valid Guid, but does not match any shift Ids in the database!")); } // Shift Ids are valid, check that the user is not trying to swap shifts that belong to the same employee if (a.ShiftOwnerId == b.ShiftOwnerId) { return(StatusCode(StatusCodes.Status406NotAcceptable, "Trying to swap two shifts that are assigned to the same employee, " + "when two different employees are expected! Aborting swap...")); } // Check if Shift a overlaps with any shifts from Employee B, and likewise for Shift B and Employee A List <Shift> allShiftForEmployeeA = await _shiftService.GetShiftsForSpecificEmployeeByIdAsync(a.ShiftOwnerId); List <Shift> allShiftForEmployeeB = await _shiftService.GetShiftsForSpecificEmployeeByIdAsync(b.ShiftOwnerId); for (int i = 0; i < allShiftForEmployeeA.Count; i++) { if (DoesShiftsOverlap(allShiftForEmployeeA[i], b)) { return(StatusCode(StatusCodes.Status406NotAcceptable, "During swap, shift B overlaps with an existing shift (Id:" + allShiftForEmployeeA[i].Id + ") for Employee A (Id:" + a.ShiftOwnerId + ")! Aborting...")); } } for (int i = 0; i < allShiftForEmployeeB.Count; i++) { if (DoesShiftsOverlap(allShiftForEmployeeB[i], a)) { return(StatusCode(StatusCodes.Status406NotAcceptable, "During swap, shift A overlaps with an existing shift (Id:" + allShiftForEmployeeB[i].Id + ") for Employee B (Id:" + b.ShiftOwnerId + ")! Aborting...")); } } #endregion // Simply swap the shift owners for each shift Guid temp = a.ShiftOwnerId; a.ShiftOwnerId = b.ShiftOwnerId; b.ShiftOwnerId = temp; // Inform the database that the shifts have been updated bool aUpdated = await _shiftService.UpdateShiftAsync(a); bool bUpdated = await _shiftService.UpdateShiftAsync(b); if (aUpdated && bUpdated) { return(Ok("Succesful swap!")); } return(NotFound()); }
private void fillShiftOptionsTable(string org_name) { SqlConnection conn = new SqlConnection(getConnectionString()); string sql = "SELECT [Worker ID], [Day], [Begin Time], [End Time], [Organization Name], [Priority] FROM [Shift Options] WHERE [Organization Name] = '" + org_name + "'"; try { conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataReader myReader = cmd.ExecuteReader(); while (myReader.Read()) { Shift shiftOption = new Shift(null, null, null, null, null, null, null, null); shiftOption.setWorker_ID(myReader[0].ToString().Trim()); shiftOption.setDay(myReader[1].ToString().Trim()); shiftOption.setBegin_Time(myReader[2].ToString().Trim()); shiftOption.setEnd_Time(myReader[3].ToString().Trim()); shiftOption.setOrganization(myReader[4].ToString().Trim()); shiftOption.setPriority(myReader[5].ToString().Trim()); shiftOptionsTable.AddShift(shiftOption); } } catch (System.Data.SqlClient.SqlException ex) { string msg = "Insert Error:"; msg += ex.Message; throw new Exception(msg); } finally { conn.Close(); } }
//• 名称(输入,不可空,唯一) //• 代码(输入,不可空,唯一) //• 开始时间(选择,时间,不可空,如06:00) //• 班次类型(选择,不可空,选项包含:今日/次日,默认今日) //• 截止时间(选择,时间,不可空,如06:00) //• 备注(输入,可空) public ResultMessage DoValidation(Shift model) { ResultMessage msg = new ResultMessage(); if (string.IsNullOrEmpty(model.name)) { msg.Success = false; msg.Content = "名称不能为空"; return(msg); } if (string.IsNullOrEmpty(model.code)) { msg.Success = false; msg.Content = "代码不能为空"; return(msg); } if (model.startAt.ToString() == "00:00:00") { msg.Success = false; msg.Content = "开始时间不能为空"; return(msg); } if (model.endAt.ToString() == "00:00:00") { msg.Success = false; msg.Content = "截止时间不能为空"; return(msg); } if (string.IsNullOrEmpty(model.shiftType.ToString()) || model.shiftType == 0) { msg.Success = false; msg.Content = "班次类型不能为空"; return(msg); } IShiftService cs = new ShiftService(Settings.Default.db); List <Shift> shift = cs.All(); if (model.id <= 0) { bool isRecordExists = shift.Where(p => p.code == model.code && p.name == model.name).ToList().Count() > 0; if (isRecordExists) { msg.Success = false; msg.Content = "数据已经存在!"; return(msg); } } else { bool isRecordExists = shift.Where(p => p.code == model.code && p.name == model.name && p.id != model.id).ToList().Count() > 0; if (isRecordExists) { msg.Success = false; msg.Content = "数据已经存在!"; return(msg); } } return(new ResultMessage() { Success = true, Content = "" }); }
/// <summary> /// 打印交接单 /// </summary> private void Btn_Print_Click(object sender, EventArgs e) { this.lbMessage.Text = "正在打印请稍后。。。"; Application.DoEvents(); Task task = new Task(); task.kind = "shift"; Shift shift = new Shift(); shift.id =PassValue.shiftId; task.shift = shift; HttpResult httpResult = httpReq.HttpPost("printing/tasks", task); if ((int)httpResult.StatusCode == 401) { this.lbMessage.Text = ""; LoginBusiness lg = new LoginBusiness(); lg.LoginAgain(); return; } else if ((int)httpResult.StatusCode == 0) { MessageBox.Show(string.Format("{0}{1}", httpResult.StatusDescription, httpResult.OtherDescription), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return; } if ((int)httpResult.StatusCode >= 200 && (int)httpResult.StatusCode < 300) { MessageBox.Show("打印成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else { if ((int)httpResult.StatusCode == 410) { MessageBox.Show("请检查打印机是否连接!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else { MessageBox.Show("未知错误!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } PassValue.IsPrintshifts = true; this.lbMessage.Text = ""; }
public void Select_UsesConstraints() { var mockery = new MockRepository(); var constraint1 = mockery.StrictMock<IResidentConstraint>(); var constraint2 = mockery.StrictMock<IResidentConstraint>(); var selector = new ResidentSelector(); selector.Constraints.Clear(); selector.Constraints.Add(constraint1); selector.Constraints.Add(constraint2); var residents = new List<Resident> { new Resident() }; var shift = new Shift(DateTime.Today, DateTime.Today, DateTime.Today); using (mockery.Record()) { Expect.Call(constraint1.Assignable(residents.First(), shift)).Return(true); Expect.Call(constraint2.Assignable(residents.First(), shift)).Return(true); } using (mockery.Playback()) { Assert.AreEqual(residents.First(), selector.Select(residents, shift)); } }
//this method fills the list that includes the information about the weekly shift table private void fillWeeklyShiftTable(string org_name) { SqlConnection conn = new SqlConnection(getConnectionString()); string sql = "SELECT [Day], [Begin Time], [End Time], [Shift Info], [Worker ID] FROM [Shift Schedule] WHERE [Organization Name] = '" + org_name + "'"; try { conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataReader myReader = cmd.ExecuteReader(); if (!myReader.HasRows) { return; } while (myReader.Read()) { Shift shiftInWeek = new Shift(null, null, null, null, null, null, null, null); shiftInWeek.setDay(myReader[0].ToString().Trim()); shiftInWeek.setBegin_Time(myReader[1].ToString().Trim()); shiftInWeek.setEnd_Time(myReader[2].ToString().Trim()); shiftInWeek.setWorker_ID(myReader[4].ToString().Trim()); shiftInWeek.setOrganization(org_name); weeklyShiftTable.AddShift(shiftInWeek); } myReader.Close(); if (weeklyShiftTable.getShiftFromTable(0).getWroker_ID() != null && weeklyShiftTable.getShiftFromTable(0).getWroker_ID() != "NULL") { sql = "SELECT [ID], [First Name], [Last Name] FROM [Worker] WHERE [Organization Name] = '" + org_name + "'"; cmd = new SqlCommand(sql, conn); myReader = cmd.ExecuteReader(); while (myReader.Read()) { for (int i = 0; i < weeklyShiftTable.tableSize(); i++) { if (weeklyShiftTable.getShiftFromTable(i).getWroker_ID().Equals(myReader[0].ToString().Trim())) { weeklyShiftTable.getShiftFromTable(i).setName(myReader[1].ToString().Trim() + " " + myReader[2].ToString().Trim()); } } } } } catch (System.Data.SqlClient.SqlException ex) { string msg = "Insert Error:"; msg += ex.Message; throw new Exception(msg); } finally { conn.Close(); } }
public async Task <IActionResult> Edit([FromRoute] Guid shiftId, [FromBody] EditShiftRequest request) { #region Error handling // In case of bad user input, gets Guid as string an parses to Guid - this shouldn't be nessecary with proper front-end setup if (!Guid.TryParse(request.ShiftOwnerId, out Guid requestOwnerId)) { return(StatusCode(StatusCodes.Status406NotAcceptable, "The given Id is not a valid Guid!")); } List <Employee> allEmployees = await _employeeService.GetAllEmployeesAsync(); bool _ownerIdExists = false; for (int i = 0; i < allEmployees.Count; i++) { if (allEmployees[i].Id == requestOwnerId) { _ownerIdExists = true; break; } } if (!_ownerIdExists) { return(StatusCode(StatusCodes.Status406NotAcceptable, "No owner with the given Id exists!")); } if (request.Day < 1 || request.Day > 31 || request.Month < 1 || request.Month > 12 || request.Year < 1 || new DateTime(request.Year, request.Month, request.Day) < DateTime.Now) { return(StatusCode(StatusCodes.Status406NotAcceptable, "The given date for the shift is not valid!" + "\nMake sure the date is not in the past, and that Day is between 1-31, and Month is between 1-12!")); } if (request.StartTime < 0 || request.StartTime > 23) { return(StatusCode(StatusCodes.Status406NotAcceptable, "The time given for the start of the shift is not valid! Must be between 0 and 23!")); } if (request.EndTime <= request.StartTime || request.EndTime > 24) { return(StatusCode(StatusCodes.Status406NotAcceptable, "The time given for the end of the shift is not valid! Must be higher than the start time (" + request.StartTime + "), but no higher than 24!")); } List <Shift> allShiftForEmployee = await _shiftService.GetShiftsForSpecificEmployeeByIdAsync(requestOwnerId); for (int i = 0; i < allShiftForEmployee.Count; i++) { if (shiftId != allShiftForEmployee[i].Id && DoesShiftsOverlap(allShiftForEmployee[i], request)) { return(StatusCode(StatusCodes.Status406NotAcceptable, "The new time for this shift overlaps with a different shift (Id:" + allShiftForEmployee[i].Id + ") for this employee (Id:" + allShiftForEmployee[i].ShiftOwnerId + ")")); } } #endregion // NOTE: Ideally i would simply create a new shift, and update the database with the given shift, // However this causes a tracking error for the given Id, which is only allowed 1 tracker, // So as a patchwerk solution i instead change each individual value for that shift. Shift shift = await _shiftService.GetShiftByIdAsync(shiftId); shift.ShiftOwnerId = Guid.Parse(request.ShiftOwnerId); shift.Day = request.Day; shift.Month = request.Month; shift.Year = request.Year; shift.StartTime = request.StartTime; shift.EndTime = request.EndTime; bool updated = await _shiftService.UpdateShiftAsync(shift); if (updated) { return(Ok(shift)); } return(NotFound()); }