diff --git a/.github/workflows/retired-booking-writes.yml b/.github/workflows/retired-booking-writes.yml new file mode 100644 index 00000000..6fcc2f1d --- /dev/null +++ b/.github/workflows/retired-booking-writes.yml @@ -0,0 +1,20 @@ +# MBA-3824: the .NET booking/capacity slice and booking-api write SQL are retired (docs/adr/0004). +name: retired booking writes guard + +on: + pull_request: + paths: + - 'AssessmentDelivery.*/**' + - 'services/booking-api/**' + - 'scripts/check-retired-booking-writes.sh' + - '.github/workflows/retired-booking-writes.yml' + push: + branches: [estate/legacy-baseline] + +jobs: + grep: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: no booking writes, SeatsAvailable updates or retired procs + run: bash scripts/check-retired-booking-writes.sh diff --git a/AssessmentDelivery.Business/AssessmentDelivery.Business.csproj b/AssessmentDelivery.Business/AssessmentDelivery.Business.csproj index 4c6bd718..28c23e4f 100644 --- a/AssessmentDelivery.Business/AssessmentDelivery.Business.csproj +++ b/AssessmentDelivery.Business/AssessmentDelivery.Business.csproj @@ -61,7 +61,7 @@ - + diff --git a/AssessmentDelivery.Business/Roster/RosterCsv.cs b/AssessmentDelivery.Business/Roster/RosterCsv.cs index 42d765bc..0121f03f 100644 --- a/AssessmentDelivery.Business/Roster/RosterCsv.cs +++ b/AssessmentDelivery.Business/Roster/RosterCsv.cs @@ -29,7 +29,7 @@ public static class RosterCsv public static bool IsOnRoster(string bookingStatus) { - return SeatCounter.HoldsSeat(bookingStatus) || bookingStatus == BookingStatus.Waitlisted; + return bookingStatus == BookingStatus.Booked || bookingStatus == BookingStatus.Attended || bookingStatus == BookingStatus.Waitlisted; } public static IList Order(IEnumerable lines) diff --git a/AssessmentDelivery.Business/Rules/BookingStatus.cs b/AssessmentDelivery.Business/Rules/BookingStatus.cs new file mode 100644 index 00000000..d9993a29 --- /dev/null +++ b/AssessmentDelivery.Business/Rules/BookingStatus.cs @@ -0,0 +1,10 @@ +namespace AssessmentDelivery.Business.Rules +{ + public static class BookingStatus + { + public const string Booked = "BOOKED"; + public const string Cancelled = "CANCELLED"; + public const string Waitlisted = "WAITLISTED"; + public const string Attended = "ATTENDED"; + } +} diff --git a/AssessmentDelivery.Business/Rules/CapacityAuditDetail.cs b/AssessmentDelivery.Business/Rules/CapacityAuditDetail.cs index 4c4506bc..2b086c7b 100644 --- a/AssessmentDelivery.Business/Rules/CapacityAuditDetail.cs +++ b/AssessmentDelivery.Business/Rules/CapacityAuditDetail.cs @@ -5,7 +5,7 @@ namespace AssessmentDelivery.Business.Rules { /// - /// Parses the AuditLog.Detail written by usp_ChangeCapacity ('<old> -> <new>'). + /// Parses the AuditLog.Detail of a capacity change ('<old> -> <new>', legacy capacity proc format). /// Same format rule as db/procs/030_usp_GetCapacityAudit.sql - keep the two in step. /// public sealed class CapacityAuditDetail diff --git a/AssessmentDelivery.Business/Rules/SeatCounter.cs b/AssessmentDelivery.Business/Rules/SeatCounter.cs deleted file mode 100644 index 7b05d857..00000000 --- a/AssessmentDelivery.Business/Rules/SeatCounter.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace AssessmentDelivery.Business.Rules -{ - public static class BookingStatus - { - public const string Booked = "BOOKED"; - public const string Cancelled = "CANCELLED"; - public const string Waitlisted = "WAITLISTED"; - public const string Attended = "ATTENDED"; - } - - /// - /// Seat counting for the admin screens. BOOKED and ATTENDED hold a seat. - /// (same rule as usp_BookSeat - keep the two in step) - /// - public static class SeatCounter - { - public static bool HoldsSeat(string bookingStatus) - { - return bookingStatus == BookingStatus.Booked || bookingStatus == BookingStatus.Attended; - } - - public static int CountBooked(IEnumerable bookingStatuses) - { - return bookingStatuses == null ? 0 : bookingStatuses.Count(HoldsSeat); - } - - public static bool CanCancel(string bookingStatus) - { - return bookingStatus == BookingStatus.Booked || bookingStatus == BookingStatus.Waitlisted; - } - } -} diff --git a/AssessmentDelivery.Data/DataClasses/Entities/ExamSession.cs b/AssessmentDelivery.Data/DataClasses/Entities/ExamSession.cs index 219a6dde..1794af8d 100644 --- a/AssessmentDelivery.Data/DataClasses/Entities/ExamSession.cs +++ b/AssessmentDelivery.Data/DataClasses/Entities/ExamSession.cs @@ -22,8 +22,8 @@ public class ExamSession public int AccommodationCapacity { get; set; } /// - /// Denormalised counter kept up to date by usp_BookSeat / usp_CancelBooking. - /// Do not update this from the portal directly. + /// Denormalised counter, written only by the scheduling-service relay (docs/adr/0003, 0004). + /// Read-only in the portal. /// public int SeatsAvailable { get; set; } diff --git a/AssessmentDelivery.Services/Admin/AdminService.cs b/AssessmentDelivery.Services/Admin/AdminService.cs index 6b311dd9..8fbc5ba4 100644 --- a/AssessmentDelivery.Services/Admin/AdminService.cs +++ b/AssessmentDelivery.Services/Admin/AdminService.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Data; -using System.Data.Entity; using System.Data.SqlClient; using System.Linq; using AssessmentDelivery.Business.Roster; @@ -65,31 +64,6 @@ public IList ListSessions(int centerId) return Load(_db.ExamSessions.Where(s => s.TestCenterId == centerId)); } - public AdminSessionRow GetSessionRow(int sessionId) - { - return Load(_db.ExamSessions.Where(s => s.SessionId == sessionId)).SingleOrDefault(); - } - - public void ChangeCapacity(int sessionId, int newCapacity, string actor) - { - if (newCapacity < 0) - throw new PortalException("Capacity cannot be negative."); - try - { - _db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, - "EXEC dbo.usp_ChangeCapacity @SessionId, @NewCapacity, @Actor", - new SqlParameter("@SessionId", sessionId), - new SqlParameter("@NewCapacity", newCapacity), - new SqlParameter("@Actor", SqlDbType.VarChar, 60) { Value = string.IsNullOrEmpty(actor) ? "portal-admin" : actor }); - } - catch (Exception ex) - { - var pe = SqlErrorHelper.TryTranslate(ex); - if (pe != null) throw pe; - throw; - } - } - public CapacityAuditResult GetCapacityAudit(int centerId, DateTime from, DateTime toExclusive, int? sessionId, int pageNumber, int pageSize) { var rows = QueryCapacityAudit(centerId, from, toExclusive, sessionId, pageNumber, pageSize); @@ -210,7 +184,7 @@ private IList Load(IQueryable q) s.AccommodationCapacity, s.SeatsAvailable, s.Status, - Statuses = s.Bookings.Select(b => b.Status), + Booked = s.Bookings.Count(b => b.Status == BookingStatus.Booked || b.Status == BookingStatus.Attended), WaitlistCount = s.Waitlist.Count() }).ToList(); @@ -227,7 +201,7 @@ private IList Load(IQueryable q) Capacity = r.Capacity, AccommodationCapacity = r.AccommodationCapacity, SeatsAvailable = r.SeatsAvailable, - Booked = SeatCounter.CountBooked(r.Statuses), + Booked = r.Booked, WaitlistCount = r.WaitlistCount, Status = r.Status }).ToList(); diff --git a/AssessmentDelivery.Services/Admin/IAdminService.cs b/AssessmentDelivery.Services/Admin/IAdminService.cs index 5f77f167..8b7fca33 100644 --- a/AssessmentDelivery.Services/Admin/IAdminService.cs +++ b/AssessmentDelivery.Services/Admin/IAdminService.cs @@ -10,8 +10,6 @@ public interface IAdminService TestCenter GetCenter(int centerId); void UpdateCenter(int centerId, string name, bool isActive); IList ListSessions(int centerId); - AdminSessionRow GetSessionRow(int sessionId); - void ChangeCapacity(int sessionId, int newCapacity, string actor); /// Capacity changes for sessions at a centre via usp_GetCapacityAudit, newest first. Reads only. CapacityAuditResult GetCapacityAudit(int centerId, DateTime from, DateTime toExclusive, int? sessionId, int pageNumber, int pageSize); diff --git a/AssessmentDelivery.Services/AssessmentDelivery.Services.csproj b/AssessmentDelivery.Services/AssessmentDelivery.Services.csproj index f7b55ea5..e534799a 100644 --- a/AssessmentDelivery.Services/AssessmentDelivery.Services.csproj +++ b/AssessmentDelivery.Services/AssessmentDelivery.Services.csproj @@ -67,14 +67,7 @@ - - - - - - - diff --git a/AssessmentDelivery.Services/Booking/BookingListItem.cs b/AssessmentDelivery.Services/Booking/BookingListItem.cs deleted file mode 100644 index d49b5047..00000000 --- a/AssessmentDelivery.Services/Booking/BookingListItem.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; - -namespace AssessmentDelivery.Services.Booking -{ - public class BookingListItem - { - public int BookingId { get; set; } - public int SessionId { get; set; } - public string ExamCode { get; set; } - public string ExamTitle { get; set; } - public string CenterName { get; set; } - public DateTime StartsAt { get; set; } - public string Status { get; set; } - public string AccommodationCode { get; set; } - public string Channel { get; set; } - public string ExternalRef { get; set; } - public DateTime BookedAt { get; set; } - public DateTime? CancelledAt { get; set; } - public string CancelReason { get; set; } - public bool CanChange { get; set; } - } -} diff --git a/AssessmentDelivery.Services/Booking/BookingOutcome.cs b/AssessmentDelivery.Services/Booking/BookingOutcome.cs deleted file mode 100644 index 08174fca..00000000 --- a/AssessmentDelivery.Services/Booking/BookingOutcome.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace AssessmentDelivery.Services.Booking -{ - public class BookingOutcome - { - public int BookingId { get; set; } - /// BOOKED or WAITLISTED - public string Status { get; set; } - } -} diff --git a/AssessmentDelivery.Services/Booking/BookingService.cs b/AssessmentDelivery.Services/Booking/BookingService.cs deleted file mode 100644 index bac8330f..00000000 --- a/AssessmentDelivery.Services/Booking/BookingService.cs +++ /dev/null @@ -1,235 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Entity; -using System.Data.SqlClient; -using System.Linq; -using AssessmentDelivery.Business.Rules; -using AssessmentDelivery.Data.DataClasses; -using AssessmentDelivery.Data.DataClasses.Entities; -using AssessmentDelivery.Services.Common; -using AssessmentDelivery.Services.Eligibility; - -namespace AssessmentDelivery.Services.Booking -{ - public class BookingService : IBookingService - { - private readonly AssessmentDeliveryDb _db; - private readonly IEligibilityService _eligibility; - - public BookingService(AssessmentDeliveryDb db, IEligibilityService eligibility) - { - _db = db; - _eligibility = eligibility; - } - - public IList FindOpenSessions(SessionSearchCriteria criteria) - { - var q = _db.ExamSessions.Where(s => s.Status == "OPEN"); - if (criteria != null) - { - if (!string.IsNullOrWhiteSpace(criteria.ExamCode)) - q = q.Where(s => s.Exam.ExamCode == criteria.ExamCode); - if (!string.IsNullOrWhiteSpace(criteria.CenterCode)) - q = q.Where(s => s.TestCenter.CenterCode == criteria.CenterCode); - if (criteria.From.HasValue) - { - var from = criteria.From.Value.Date; - q = q.Where(s => s.StartsAt >= from); - } - if (criteria.To.HasValue) - { - var to = criteria.To.Value.Date.AddDays(1); - q = q.Where(s => s.StartsAt < to); - } - } - return Project(q).OrderBy(s => s.StartsAt).ThenBy(s => s.CenterCode).ToList(); - } - - public SessionListItem GetSession(int sessionId) - { - return Project(_db.ExamSessions.Where(s => s.SessionId == sessionId)).SingleOrDefault(); - } - - public IList ListExams() - { - return _db.Exams.AsNoTracking().Where(e => e.IsPublished).OrderBy(e => e.ExamCode).ToList(); - } - - public IList ListActiveCenters() - { - return _db.TestCenters.AsNoTracking().Where(c => c.IsActive).OrderBy(c => c.CenterCode).ToList(); - } - - public Candidate FindCandidate(string candidateNumber) - { - if (string.IsNullOrWhiteSpace(candidateNumber)) return null; - var number = candidateNumber.Trim().ToUpper(); - return _db.Candidates.AsNoTracking().SingleOrDefault(c => c.CandidateNumber == number); - } - - public IList GetBookingsForCandidate(string candidateNumber) - { - var candidate = FindCandidate(candidateNumber); - if (candidate == null) return new List(); - - var list = ProjectBookings(_db.Bookings.Where(b => b.CandidateId == candidate.CandidateId)) - .OrderByDescending(b => b.StartsAt).ThenByDescending(b => b.BookingId).ToList(); - foreach (var item in list) - item.CanChange = SeatCounter.CanCancel(item.Status); - return list; - } - - public BookingListItem GetBooking(int bookingId) - { - var item = ProjectBookings(_db.Bookings.Where(b => b.BookingId == bookingId)).SingleOrDefault(); - if (item != null) item.CanChange = SeatCounter.CanCancel(item.Status); - return item; - } - - public BookingOutcome Book(int sessionId, string candidateNumber, string accommodationCode) - { - var candidate = FindCandidate(candidateNumber); - if (candidate == null) - throw new PortalException("Candidate number " + candidateNumber + " was not found."); - - var session = _db.ExamSessions.Include(s => s.Exam).AsNoTracking().SingleOrDefault(s => s.SessionId == sessionId); - if (session == null) - throw new PortalException("Session " + sessionId + " was not found."); - - //blank on the form = use the candidate's default from their profile - var requested = string.IsNullOrWhiteSpace(accommodationCode) ? candidate.DefaultAccommodationCode : accommodationCode; - string code; - if (!AccommodationCodes.TryParse(requested, out code)) - throw new PortalException("Unknown accommodation code '" + requested + "'."); - - //retake check has to happen here, usp_BookSeat does not know about results - var decision = _eligibility.Check(candidate.CandidateNumber, session.Exam.ExamCode, session.StartsAt); - if (!decision.Eligible) - throw new PortalException("Not eligible to book " + session.Exam.ExamCode + ": " + decision.Reason); - - var pBookingId = new SqlParameter("@BookingId", SqlDbType.Int) { Direction = ParameterDirection.Output }; - var pStatus = new SqlParameter("@ResultStatus", SqlDbType.VarChar, 12) { Direction = ParameterDirection.Output }; - try - { - _db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, - "EXEC dbo.usp_BookSeat @SessionId, @CandidateId, @AccommodationCode, @BookingId OUTPUT, @ResultStatus OUTPUT", - new SqlParameter("@SessionId", sessionId), - new SqlParameter("@CandidateId", candidate.CandidateId), - new SqlParameter("@AccommodationCode", SqlDbType.VarChar, 10) { Value = (object)code ?? DBNull.Value }, - pBookingId, pStatus); - } - catch (Exception ex) - { - var pe = SqlErrorHelper.TryTranslate(ex); - if (pe != null) throw pe; - throw; - } - return new BookingOutcome { BookingId = (int)pBookingId.Value, Status = (string)pStatus.Value }; - } - - public void Cancel(int bookingId, string reason) - { - try - { - _db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, - "EXEC dbo.usp_CancelBooking @BookingId, @Reason, @Actor", - new SqlParameter("@BookingId", bookingId), - new SqlParameter("@Reason", SqlDbType.NVarChar, 200) { Value = string.IsNullOrWhiteSpace(reason) ? (object)DBNull.Value : reason }, - new SqlParameter("@Actor", SqlDbType.VarChar, 60) { Value = "portal" }); - } - catch (Exception ex) - { - var pe = SqlErrorHelper.TryTranslate(ex); - if (pe != null) throw pe; - throw; - } - } - - public IList FindRescheduleTargets(int bookingId) - { - var booking = _db.Bookings.AsNoTracking().Include(b => b.Session).SingleOrDefault(b => b.BookingId == bookingId); - if (booking == null) return new List(); - var examId = booking.Session.ExamId; - var today = DateTime.Today; - var q = _db.ExamSessions.Where(s => s.ExamId == examId && s.Status == "OPEN" - && s.SessionId != booking.SessionId && s.StartsAt >= today); - return Project(q).OrderBy(s => s.StartsAt).ToList(); - } - - public BookingOutcome Reschedule(int bookingId, int newSessionId) - { - var booking = _db.Bookings.AsNoTracking().Include(b => b.Candidate).SingleOrDefault(b => b.BookingId == bookingId); - var target = _db.ExamSessions.Include(s => s.Exam).AsNoTracking().SingleOrDefault(s => s.SessionId == newSessionId); - if (booking != null && target != null) - { - //same retake check as Book - the proc only checks the exam matches - var decision = _eligibility.Check(booking.Candidate.CandidateNumber, target.Exam.ExamCode, target.StartsAt); - if (!decision.Eligible) - throw new PortalException("Not eligible to book " + target.Exam.ExamCode + ": " + decision.Reason); - } - - var pNewId = new SqlParameter("@NewBookingId", SqlDbType.Int) { Direction = ParameterDirection.Output }; - var pStatus = new SqlParameter("@ResultStatus", SqlDbType.VarChar, 12) { Direction = ParameterDirection.Output }; - try - { - _db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, - "EXEC dbo.usp_RescheduleBooking @BookingId, @NewSessionId, @NewBookingId OUTPUT, @ResultStatus OUTPUT", - new SqlParameter("@BookingId", bookingId), - new SqlParameter("@NewSessionId", newSessionId), - pNewId, pStatus); - } - catch (Exception ex) - { - var pe = SqlErrorHelper.TryTranslate(ex); - if (pe != null) throw pe; - throw; - } - if (pNewId.Value == DBNull.Value) - throw new PortalException("Booking " + bookingId + " could not be rescheduled."); - return new BookingOutcome { BookingId = (int)pNewId.Value, Status = (string)pStatus.Value }; - } - - //------------------------------------------------- - - internal static IQueryable Project(IQueryable q) - { - return q.Select(s => new SessionListItem - { - SessionId = s.SessionId, - ExamCode = s.Exam.ExamCode, - ExamTitle = s.Exam.Title, - CenterCode = s.TestCenter.CenterCode, - CenterName = s.TestCenter.Name, - City = s.TestCenter.City, - RoomName = s.Room.RoomName, - StartsAt = s.StartsAt, - DurationMinutes = s.Exam.DurationMinutes, - Capacity = s.Capacity, - AccommodationCapacity = s.AccommodationCapacity, - SeatsAvailable = s.SeatsAvailable, - Status = s.Status - }); - } - - private static IQueryable ProjectBookings(IQueryable q) - { - return q.Select(b => new BookingListItem - { - BookingId = b.BookingId, - SessionId = b.SessionId, - ExamCode = b.Session.Exam.ExamCode, - ExamTitle = b.Session.Exam.Title, - CenterName = b.Session.TestCenter.Name, - StartsAt = b.Session.StartsAt, - Status = b.Status, - AccommodationCode = b.AccommodationCode, - Channel = b.Channel, - ExternalRef = b.ExternalRef, - BookedAt = b.BookedAt, - CancelledAt = b.CancelledAt, - CancelReason = b.CancelReason - }); - } - } -} diff --git a/AssessmentDelivery.Services/Booking/IBookingService.cs b/AssessmentDelivery.Services/Booking/IBookingService.cs deleted file mode 100644 index bc8337b4..00000000 --- a/AssessmentDelivery.Services/Booking/IBookingService.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Collections.Generic; -using AssessmentDelivery.Data.DataClasses.Entities; - -namespace AssessmentDelivery.Services.Booking -{ - public interface IBookingService - { - IList FindOpenSessions(SessionSearchCriteria criteria); - SessionListItem GetSession(int sessionId); - IList ListExams(); - IList ListActiveCenters(); - - Candidate FindCandidate(string candidateNumber); - IList GetBookingsForCandidate(string candidateNumber); - BookingListItem GetBooking(int bookingId); - - BookingOutcome Book(int sessionId, string candidateNumber, string accommodationCode); - void Cancel(int bookingId, string reason); - IList FindRescheduleTargets(int bookingId); - BookingOutcome Reschedule(int bookingId, int newSessionId); - } -} diff --git a/AssessmentDelivery.Services/Booking/SessionListItem.cs b/AssessmentDelivery.Services/Booking/SessionListItem.cs deleted file mode 100644 index 1e89fb6f..00000000 --- a/AssessmentDelivery.Services/Booking/SessionListItem.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; - -namespace AssessmentDelivery.Services.Booking -{ - public class SessionListItem - { - public int SessionId { get; set; } - public string ExamCode { get; set; } - public string ExamTitle { get; set; } - public string CenterCode { get; set; } - public string CenterName { get; set; } - public string City { get; set; } - public string RoomName { get; set; } - public DateTime StartsAt { get; set; } - public int DurationMinutes { get; set; } - public int Capacity { get; set; } - public int AccommodationCapacity { get; set; } - public int SeatsAvailable { get; set; } - public string Status { get; set; } - } -} diff --git a/AssessmentDelivery.Services/Booking/SessionSearchCriteria.cs b/AssessmentDelivery.Services/Booking/SessionSearchCriteria.cs deleted file mode 100644 index ecc0632b..00000000 --- a/AssessmentDelivery.Services/Booking/SessionSearchCriteria.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace AssessmentDelivery.Services.Booking -{ - public class SessionSearchCriteria - { - public string ExamCode { get; set; } - public string CenterCode { get; set; } - public DateTime? From { get; set; } - public DateTime? To { get; set; } - } -} diff --git a/AssessmentDelivery.Services/Common/SqlErrorHelper.cs b/AssessmentDelivery.Services/Common/SqlErrorHelper.cs deleted file mode 100644 index f2580a5f..00000000 --- a/AssessmentDelivery.Services/Common/SqlErrorHelper.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Data.SqlClient; - -namespace AssessmentDelivery.Services.Common -{ - internal static class SqlErrorHelper - { - //user errors raised by our procs come back as msg 50000, severity 16 - private const int UserDefinedMessage = 50000; - - /// - /// Walks the exception chain looking for a RAISERROR from one of the procs and - /// turns it into a PortalException. Anything else is rethrown by the caller. - /// - public static PortalException TryTranslate(Exception ex) - { - var e = ex; - while (e != null) - { - var sqlEx = e as SqlException; - if (sqlEx != null) - { - foreach (SqlError err in sqlEx.Errors) - { - if (err.Number == UserDefinedMessage && err.Class == 16) - return new PortalException(err.Message, sqlEx); - } - return null; - } - e = e.InnerException; - } - return null; - } - } -} diff --git a/AssessmentDelivery.Services/Eligibility/EligibilityService.cs b/AssessmentDelivery.Services/Eligibility/EligibilityService.cs index 084e447c..bdf2c2bf 100644 --- a/AssessmentDelivery.Services/Eligibility/EligibilityService.cs +++ b/AssessmentDelivery.Services/Eligibility/EligibilityService.cs @@ -1,7 +1,10 @@ using System; +using System.Collections.Generic; +using System.Data.Entity; using System.Linq; using AssessmentDelivery.Business.Rules; using AssessmentDelivery.Data.DataClasses; +using AssessmentDelivery.Data.DataClasses.Entities; using AssessmentDelivery.Services.Common; namespace AssessmentDelivery.Services.Eligibility @@ -17,6 +20,11 @@ public EligibilityService(AssessmentDeliveryDb db, IRetakeRules rules) _rules = rules; } + public IList ListExams() + { + return _db.Exams.AsNoTracking().Where(e => e.IsPublished).OrderBy(e => e.ExamCode).ToList(); + } + public RetakeDecision Check(string candidateNumber, string examCode, DateTime date) { var number = (candidateNumber ?? "").Trim().ToUpper(); diff --git a/AssessmentDelivery.Services/Eligibility/IEligibilityService.cs b/AssessmentDelivery.Services/Eligibility/IEligibilityService.cs index f6eb0c9c..43462949 100644 --- a/AssessmentDelivery.Services/Eligibility/IEligibilityService.cs +++ b/AssessmentDelivery.Services/Eligibility/IEligibilityService.cs @@ -1,10 +1,13 @@ using System; +using System.Collections.Generic; using AssessmentDelivery.Business.Rules; +using AssessmentDelivery.Data.DataClasses.Entities; namespace AssessmentDelivery.Services.Eligibility { public interface IEligibilityService { RetakeDecision Check(string candidateNumber, string examCode, DateTime date); + IList ListExams(); } } diff --git a/AssessmentDelivery.Services/Results/IResultsService.cs b/AssessmentDelivery.Services/Results/IResultsService.cs index 61ebb86c..10f79bf8 100644 --- a/AssessmentDelivery.Services/Results/IResultsService.cs +++ b/AssessmentDelivery.Services/Results/IResultsService.cs @@ -1,9 +1,11 @@ using System.Collections.Generic; +using AssessmentDelivery.Data.DataClasses.Entities; namespace AssessmentDelivery.Services.Results { public interface IResultsService { + Candidate FindCandidate(string candidateNumber); IList GetResultsForCandidate(string candidateNumber); } } diff --git a/AssessmentDelivery.Services/Results/ResultsService.cs b/AssessmentDelivery.Services/Results/ResultsService.cs index 84e606f1..06e3b4c7 100644 --- a/AssessmentDelivery.Services/Results/ResultsService.cs +++ b/AssessmentDelivery.Services/Results/ResultsService.cs @@ -1,6 +1,8 @@ using System.Collections.Generic; +using System.Data.Entity; using System.Linq; using AssessmentDelivery.Data.DataClasses; +using AssessmentDelivery.Data.DataClasses.Entities; namespace AssessmentDelivery.Services.Results { @@ -13,6 +15,13 @@ public ResultsService(AssessmentDeliveryDb db) _db = db; } + public Candidate FindCandidate(string candidateNumber) + { + if (string.IsNullOrWhiteSpace(candidateNumber)) return null; + var number = candidateNumber.Trim().ToUpper(); + return _db.Candidates.AsNoTracking().SingleOrDefault(c => c.CandidateNumber == number); + } + public IList GetResultsForCandidate(string candidateNumber) { var number = (candidateNumber ?? "").Trim().ToUpper(); diff --git a/AssessmentDelivery.Tests/AssessmentDelivery.Tests.csproj b/AssessmentDelivery.Tests/AssessmentDelivery.Tests.csproj index 5e78450a..17873da0 100644 --- a/AssessmentDelivery.Tests/AssessmentDelivery.Tests.csproj +++ b/AssessmentDelivery.Tests/AssessmentDelivery.Tests.csproj @@ -71,7 +71,6 @@ - diff --git a/AssessmentDelivery.Tests/UnitTests/SeatCounterTests.cs b/AssessmentDelivery.Tests/UnitTests/SeatCounterTests.cs deleted file mode 100644 index 8e3abcc7..00000000 --- a/AssessmentDelivery.Tests/UnitTests/SeatCounterTests.cs +++ /dev/null @@ -1,17 +0,0 @@ -using AssessmentDelivery.Business.Rules; -using NUnit.Framework; - -namespace AssessmentDelivery.Tests.UnitTests -{ - [TestFixture] - public class SeatCounterTests - { - [Test] - public void BookedFigureCountsBookedAndAttendedOnly() - { - var statuses = new[] { "BOOKED", "ATTENDED", "CANCELLED", "WAITLISTED", "BOOKED" }; - - Assert.AreEqual(3, SeatCounter.CountBooked(statuses)); - } - } -} diff --git a/AssessmentDelivery.Web/App_Start/RouteConfig.cs b/AssessmentDelivery.Web/App_Start/RouteConfig.cs index 380ae125..e5b1bfec 100644 --- a/AssessmentDelivery.Web/App_Start/RouteConfig.cs +++ b/AssessmentDelivery.Web/App_Start/RouteConfig.cs @@ -9,13 +9,6 @@ public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); - //centre admin capacity panel - URL agreed with ops (see docs/SYSTEM_OVERVIEW.md) - routes.MapRoute( - name: "AdminCapacity", - url: "Admin/Sessions/Capacity/{id}", - defaults: new { controller = "Admin", action = "Capacity" } - ); - //capacity change history for a centre (MBA-3828) routes.MapRoute( name: "AdminCapacityAudit", diff --git a/AssessmentDelivery.Web/AssessmentDelivery.Web.csproj b/AssessmentDelivery.Web/AssessmentDelivery.Web.csproj index 987812ab..37c7a5f5 100644 --- a/AssessmentDelivery.Web/AssessmentDelivery.Web.csproj +++ b/AssessmentDelivery.Web/AssessmentDelivery.Web.csproj @@ -127,7 +127,6 @@ - @@ -136,7 +135,6 @@ - @@ -148,16 +146,10 @@ - - - - - - diff --git a/AssessmentDelivery.Web/Controllers/AdminController.cs b/AssessmentDelivery.Web/Controllers/AdminController.cs index a66b1ef6..3215f89f 100644 --- a/AssessmentDelivery.Web/Controllers/AdminController.cs +++ b/AssessmentDelivery.Web/Controllers/AdminController.cs @@ -61,41 +61,6 @@ public ActionResult Sessions(int? centerId) return View(new SessionsViewModel { Center = center, Sessions = _admin.ListSessions(center.TestCenterId) }); } - public ActionResult Capacity(int id) - { - var model = BuildCapacityModel(id); - if (model == null) return HttpNotFound(); - model.NewCapacity = model.Session.Capacity; - return View(model); - } - - [HttpPost] - [ValidateAntiForgeryToken] - public ActionResult Capacity(int id, int? newCapacity) - { - var model = BuildCapacityModel(id); - if (model == null) return HttpNotFound(); - - if (!newCapacity.HasValue) - { - ModelState.AddModelError("NewCapacity", "Enter the new capacity"); - return View(model); - } - try - { - _admin.ChangeCapacity(id, newCapacity.Value, "portal-admin"); - } - catch (PortalException ex) - { - model.NewCapacity = newCapacity.Value; - ModelState.AddModelError("", ex.Message); - return View(model); - } - - TempData["message"] = "Capacity updated"; - return RedirectToAction("Capacity", new { id }); - } - public ActionResult CapacityAudit(int id, DateTime? from, DateTime? to, int? sessionId, int? page) { var center = _admin.GetCenter(id); @@ -137,17 +102,5 @@ public ActionResult Roster(int id, string format) return File(RosterCsv.ToBytes(csv), RosterCsv.ContentType + "; charset=utf-8", RosterCsv.FileName(roster.CenterCode, roster.ExamCode, DateTime.Now)); } - - private CapacityViewModel BuildCapacityModel(int sessionId) - { - var row = _admin.GetSessionRow(sessionId); - if (row == null) return null; - return new CapacityViewModel - { - Session = row, - CenterId = row.TestCenterId, - CenterName = row.CenterName - }; - } } } diff --git a/AssessmentDelivery.Web/Controllers/BookingController.cs b/AssessmentDelivery.Web/Controllers/BookingController.cs deleted file mode 100644 index 91c81b60..00000000 --- a/AssessmentDelivery.Web/Controllers/BookingController.cs +++ /dev/null @@ -1,138 +0,0 @@ -using System.Web.Mvc; -using AssessmentDelivery.Services.Booking; -using AssessmentDelivery.Services.Common; -using AssessmentDelivery.Web.Models; - -namespace AssessmentDelivery.Web.Controllers -{ - public class BookingController : Controller - { - private readonly IBookingService _booking; - - public BookingController(IBookingService booking) - { - _booking = booking; - } - - // GET /Booking - find open sessions - public ActionResult Index(FindSessionsViewModel model) - { - model = model ?? new FindSessionsViewModel(); - model.Exams = _booking.ListExams(); - model.Centers = _booking.ListActiveCenters(); - model.Searched = Request.QueryString.Count > 0; - if (model.Searched) - { - model.Results = _booking.FindOpenSessions(new SessionSearchCriteria - { - ExamCode = model.ExamCode, - CenterCode = model.CenterCode, - From = model.From, - To = model.To - }); - } - return View(model); - } - - public ActionResult Book(int? sessionId, string candidateNumber) - { - if (!sessionId.HasValue) return RedirectToAction("Index"); - var session = _booking.GetSession(sessionId.Value); - if (session == null) return HttpNotFound(); - return View(new BookViewModel { SessionId = session.SessionId, Session = session, CandidateNumber = candidateNumber }); - } - - [HttpPost] - [ValidateAntiForgeryToken] - public ActionResult Book(BookViewModel model) - { - model.Session = _booking.GetSession(model.SessionId); - if (model.Session == null) return HttpNotFound(); - if (!ModelState.IsValid) return View(model); - - try - { - var outcome = _booking.Book(model.SessionId, model.CandidateNumber, model.AccommodationCode); - TempData["message"] = outcome.Status == "WAITLISTED" - ? "Session is full - booking " + outcome.BookingId + " has been placed on the waitlist." - : "Booking " + outcome.BookingId + " confirmed."; - } - catch (PortalException ex) - { - ModelState.AddModelError("", ex.Message); - return View(model); - } - return RedirectToAction("MyBookings", new { candidateNumber = model.CandidateNumber.Trim().ToUpper() }); - } - - public ActionResult MyBookings(string candidateNumber) - { - var model = new MyBookingsViewModel { CandidateNumber = candidateNumber }; - if (!string.IsNullOrWhiteSpace(candidateNumber)) - { - model.Candidate = _booking.FindCandidate(candidateNumber); - if (model.Candidate == null) - ModelState.AddModelError("", "Candidate number " + candidateNumber + " was not found."); - else - model.Bookings = _booking.GetBookingsForCandidate(candidateNumber); - } - return View(model); - } - - public ActionResult Cancel(int id, string candidateNumber) - { - var booking = _booking.GetBooking(id); - if (booking == null) return HttpNotFound(); - return View(new CancelViewModel { Booking = booking, CandidateNumber = candidateNumber }); - } - - [HttpPost] - [ValidateAntiForgeryToken] - public ActionResult Cancel(int id, CancelViewModel model) - { - try - { - _booking.Cancel(id, model.Reason); - } - catch (PortalException ex) - { - model.Booking = _booking.GetBooking(id); - ModelState.AddModelError("", ex.Message); - return View(model); - } - TempData["message"] = "Booking " + id + " cancelled."; - return RedirectToAction("MyBookings", new { candidateNumber = model.CandidateNumber }); - } - - public ActionResult Reschedule(int id, string candidateNumber) - { - var booking = _booking.GetBooking(id); - if (booking == null) return HttpNotFound(); - return View(new RescheduleViewModel { Booking = booking, CandidateNumber = candidateNumber, Targets = _booking.FindRescheduleTargets(id) }); - } - - [HttpPost] - [ValidateAntiForgeryToken] - public ActionResult Reschedule(int id, RescheduleViewModel model) - { - if (!model.NewSessionId.HasValue) - ModelState.AddModelError("NewSessionId", "Choose the new session"); - else - { - try - { - var outcome = _booking.Reschedule(id, model.NewSessionId.Value); - TempData["message"] = "Booking moved. New booking " + outcome.BookingId + " (" + outcome.Status + ")."; - return RedirectToAction("MyBookings", new { candidateNumber = model.CandidateNumber }); - } - catch (PortalException ex) - { - ModelState.AddModelError("", ex.Message); - } - } - model.Booking = _booking.GetBooking(id); - model.Targets = _booking.FindRescheduleTargets(id); - return View(model); - } - } -} diff --git a/AssessmentDelivery.Web/Controllers/EligibilityController.cs b/AssessmentDelivery.Web/Controllers/EligibilityController.cs index 23f8970c..424a0a7a 100644 --- a/AssessmentDelivery.Web/Controllers/EligibilityController.cs +++ b/AssessmentDelivery.Web/Controllers/EligibilityController.cs @@ -1,6 +1,5 @@ using System; using System.Web.Mvc; -using AssessmentDelivery.Services.Booking; using AssessmentDelivery.Services.Common; using AssessmentDelivery.Services.Eligibility; using AssessmentDelivery.Web.Models; @@ -10,12 +9,10 @@ namespace AssessmentDelivery.Web.Controllers public class EligibilityController : Controller { private readonly IEligibilityService _eligibility; - private readonly IBookingService _booking; - public EligibilityController(IEligibilityService eligibility, IBookingService booking) + public EligibilityController(IEligibilityService eligibility) { _eligibility = eligibility; - _booking = booking; } // GET /Eligibility?candidateNumber=&examCode=&date= @@ -26,7 +23,7 @@ public ActionResult Index(string candidateNumber, string examCode, DateTime? dat CandidateNumber = candidateNumber, ExamCode = examCode, Date = date ?? DateTime.Today, - Exams = _booking.ListExams() + Exams = _eligibility.ListExams() }; if (!string.IsNullOrWhiteSpace(candidateNumber) && !string.IsNullOrWhiteSpace(examCode)) diff --git a/AssessmentDelivery.Web/Controllers/ResultsController.cs b/AssessmentDelivery.Web/Controllers/ResultsController.cs index 4b8d3df7..6edd4f23 100644 --- a/AssessmentDelivery.Web/Controllers/ResultsController.cs +++ b/AssessmentDelivery.Web/Controllers/ResultsController.cs @@ -1,5 +1,4 @@ using System.Web.Mvc; -using AssessmentDelivery.Services.Booking; using AssessmentDelivery.Services.Results; using AssessmentDelivery.Web.Models; @@ -8,12 +7,10 @@ namespace AssessmentDelivery.Web.Controllers public class ResultsController : Controller { private readonly IResultsService _results; - private readonly IBookingService _booking; - public ResultsController(IResultsService results, IBookingService booking) + public ResultsController(IResultsService results) { _results = results; - _booking = booking; } // GET /Results?candidateNumber= @@ -22,7 +19,7 @@ public ActionResult Index(string candidateNumber) var model = new ResultsViewModel { CandidateNumber = candidateNumber }; if (!string.IsNullOrWhiteSpace(candidateNumber)) { - model.Candidate = _booking.FindCandidate(candidateNumber); + model.Candidate = _results.FindCandidate(candidateNumber); if (model.Candidate == null) ModelState.AddModelError("", "Candidate number " + candidateNumber + " was not found."); else diff --git a/AssessmentDelivery.Web/Models/AdminModels.cs b/AssessmentDelivery.Web/Models/AdminModels.cs index a3a7e375..f2e965ae 100644 --- a/AssessmentDelivery.Web/Models/AdminModels.cs +++ b/AssessmentDelivery.Web/Models/AdminModels.cs @@ -12,17 +12,6 @@ public class SessionsViewModel public IList Sessions { get; set; } } - public class CapacityViewModel - { - public AdminSessionRow Session { get; set; } - public int CenterId { get; set; } - public string CenterName { get; set; } - - [Required, Range(0, 500)] - [Display(Name = "New capacity")] - public int NewCapacity { get; set; } - } - public class CapacityAuditViewModel { public TestCenter Center { get; set; } diff --git a/AssessmentDelivery.Web/Models/BookingModels.cs b/AssessmentDelivery.Web/Models/BookingModels.cs deleted file mode 100644 index 81a02c04..00000000 --- a/AssessmentDelivery.Web/Models/BookingModels.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using AssessmentDelivery.Data.DataClasses.Entities; -using AssessmentDelivery.Services.Booking; - -namespace AssessmentDelivery.Web.Models -{ - public class FindSessionsViewModel - { - public string ExamCode { get; set; } - public string CenterCode { get; set; } - [DataType(DataType.Date)] - public DateTime? From { get; set; } - [DataType(DataType.Date)] - public DateTime? To { get; set; } - public string CandidateNumber { get; set; } - - public IList Exams { get; set; } - public IList Centers { get; set; } - public IList Results { get; set; } - public bool Searched { get; set; } - } - - public class BookViewModel - { - public int SessionId { get; set; } - public SessionListItem Session { get; set; } - - [Required] - [Display(Name = "Candidate number")] - public string CandidateNumber { get; set; } - - [Display(Name = "Accommodation code")] - public string AccommodationCode { get; set; } - } - - public class MyBookingsViewModel - { - public string CandidateNumber { get; set; } - public Candidate Candidate { get; set; } - public IList Bookings { get; set; } - } - - public class CancelViewModel - { - public BookingListItem Booking { get; set; } - public string CandidateNumber { get; set; } - [StringLength(200)] - public string Reason { get; set; } - } - - public class RescheduleViewModel - { - public BookingListItem Booking { get; set; } - public string CandidateNumber { get; set; } - public IList Targets { get; set; } - public int? NewSessionId { get; set; } - } -} diff --git a/AssessmentDelivery.Web/README.md b/AssessmentDelivery.Web/README.md index d7d3ca02..0823ef36 100644 --- a/AssessmentDelivery.Web/README.md +++ b/AssessmentDelivery.Web/README.md @@ -7,8 +7,8 @@ Bootstrap 3 / jQuery. Hosted on **http://localhost:8080** (IIS Express). | Project | What lives there | |---|---| | `AssessmentDelivery.Data` | `AssessmentDeliveryDb` (EF6 DbContext) and entities mapped onto the shared tables | -| `AssessmentDelivery.Business` | rules: retake eligibility, accommodation codes, seat counting | -| `AssessmentDelivery.Services` | booking / admin / eligibility / results services; calls the `usp_*` procs | +| `AssessmentDelivery.Business` | rules: retake eligibility, accommodation codes, roster CSV, capacity audit | +| `AssessmentDelivery.Services` | admin / eligibility / results services (reads, plus the centre edit) | | `AssessmentDelivery.Web` | MVC 5 controllers, views, theme (`Content/Site.css`) | | `AssessmentDelivery.Tests` | NUnit 3 unit tests | @@ -53,11 +53,10 @@ packages\NUnit.ConsoleRunner.3.16.3\tools\nunit3-console.exe AssessmentDelivery. ## Notes -- Writes that touch seats go through the stored procedures (`usp_BookSeat`, `usp_CancelBooking`, - `usp_RescheduleBooking`, `usp_ChangeCapacity`); messages raised by the procs are shown on screen. - Editing a centre's name/active flag is a plain EF update. -- Bookings made by partners through booking-api (channel `PARTNER`) and imported bookings show up in - *My bookings* next to portal bookings. +- MBA-3824 retired the booking and capacity pages (`/Booking/**`, `/Admin/Sessions/Capacity/{id}`): they are served + by the scheduling-service UI under `/app`, and the routing gateway (:8000) redirects the old URLs + ([ADR 0004](../docs/adr/0004-retire-portal-booking-slice.md)). The portal no longer writes seats; editing a + centre's name/active flag is a plain EF update. - The "Booked" column in centre admin is counted from the Booking rows (BOOKED + ATTENDED); the "Seats avail." column is the stored `ExamSession.SeatsAvailable` figure. - "Roster (CSV)" on each centre-admin session row (`/Admin/Sessions/Roster/{id}?format=csv`) downloads the diff --git a/AssessmentDelivery.Web/Views/Admin/Capacity.cshtml b/AssessmentDelivery.Web/Views/Admin/Capacity.cshtml deleted file mode 100644 index ee8c90b0..00000000 --- a/AssessmentDelivery.Web/Views/Admin/Capacity.cshtml +++ /dev/null @@ -1,52 +0,0 @@ -@model AssessmentDelivery.Web.Models.CapacityViewModel -@{ - ViewBag.Title = "Change Capacity"; - ViewBag.Breadcrumb = "Test Centres » " + Html.Encode(Model.CenterName) + " » Session #" + Model.Session.SessionId + " » Capacity"; -} -

Capacity administration Session #@Model.Session.SessionId

-
-
-
-
Session details
- - - - - - -
Centre@Model.CenterName
Exam@Model.Session.ExamCode – @Model.Session.ExamTitle
Room@Model.Session.RoomName
Start@Model.Session.StartsAt.ToString("dddd dd MMM yyyy HH:mm")
Status@Html.StatusPill(Model.Session.Status)
-
-
-
-
-
Seat position
- - - - - - - - - -
CapacityAcc. capacitySeats availableBookedWaitlist
@Model.Session.Capacity@Model.Session.AccommodationCapacity@Model.Session.SeatsAvailable@Model.Session.Booked@Model.Session.WaitlistCount
-
-
-
Change capacity
-
- @using (Html.BeginRouteForm("AdminCapacity", new { id = Model.Session.SessionId }, FormMethod.Post, new { @class = "form-inline nw-form" })) - { - @Html.AntiForgeryToken() - @Html.ValidationSummary(false, "", new { @class = "alert alert-danger nw-alert" }) -
- @Html.LabelFor(m => m.NewCapacity) - @Html.TextBoxFor(m => m.NewCapacity, new { @class = "form-control input-sm", type = "number", min = "0", style = "width:90px" }) -
- -

Seats available moves by the same amount. Capacity cannot be lower than the accommodation capacity.

-

Capacity change history for this session

- } -
-
-
-
diff --git a/AssessmentDelivery.Web/Views/Admin/CapacityAudit.cshtml b/AssessmentDelivery.Web/Views/Admin/CapacityAudit.cshtml index 0134c352..9f3cf479 100644 --- a/AssessmentDelivery.Web/Views/Admin/CapacityAudit.cshtml +++ b/AssessmentDelivery.Web/Views/Admin/CapacityAudit.cshtml @@ -61,7 +61,7 @@ { @r.LoggedAt.ToString("dd MMM yyyy HH:mm:ss") - #@r.SessionId @r.ExamCode @r.SessionStartsAt.ToString("dd MMM yyyy HH:mm") + #@r.SessionId @r.ExamCode @r.SessionStartsAt.ToString("dd MMM yyyy HH:mm") @r.RoomName @if (r.OldCapacity.HasValue && r.NewCapacity.HasValue) { diff --git a/AssessmentDelivery.Web/Views/Admin/Sessions.cshtml b/AssessmentDelivery.Web/Views/Admin/Sessions.cshtml index 93cec5ac..6a309432 100644 --- a/AssessmentDelivery.Web/Views/Admin/Sessions.cshtml +++ b/AssessmentDelivery.Web/Views/Admin/Sessions.cshtml @@ -41,7 +41,7 @@ @s.Booked @s.WaitlistCount @Html.StatusPill(s.Status) - Capacity | Audit | Roster (CSV) + Capacity | Audit | Roster (CSV) } @if (Model.Sessions.Count == 0) diff --git a/AssessmentDelivery.Web/Views/Booking/Book.cshtml b/AssessmentDelivery.Web/Views/Booking/Book.cshtml deleted file mode 100644 index 753013d3..00000000 --- a/AssessmentDelivery.Web/Views/Booking/Book.cshtml +++ /dev/null @@ -1,58 +0,0 @@ -@model AssessmentDelivery.Web.Models.BookViewModel -@{ - ViewBag.Title = "Book Session"; - ViewBag.Breadcrumb = "Find sessions » Book session #" + Model.SessionId; -} -

Book a seat Session #@Model.SessionId

-
-
-
-
Session
- - - - - - - - -
Exam@Model.Session.ExamCode – @Model.Session.ExamTitle
Centre@Model.Session.CenterName (@Model.Session.CenterCode)
Room@Model.Session.RoomName
Start@Model.Session.StartsAt.ToString("dddd dd MMM yyyy HH:mm")
Duration@Model.Session.DurationMinutes minutes
Seats available@Model.Session.SeatsAvailable of @Model.Session.Capacity (accommodation capacity @Model.Session.AccommodationCapacity)
Status@Html.StatusPill(Model.Session.Status)
-
-
-
-
-
Booking details
-
- @using (Html.BeginForm("Book", "Booking", FormMethod.Post, new { @class = "form-horizontal nw-form" })) - { - @Html.AntiForgeryToken() - @Html.ValidationSummary(false, "", new { @class = "alert alert-danger nw-alert" }) - @Html.HiddenFor(m => m.SessionId) -
- @Html.LabelFor(m => m.CandidateNumber, new { @class = "col-sm-4 control-label" }) -
@Html.TextBoxFor(m => m.CandidateNumber, new { @class = "form-control input-sm", placeholder = "NW00000000" })
-
-
- @Html.LabelFor(m => m.AccommodationCode, new { @class = "col-sm-4 control-label" }) -
- -
-
-
-
- - @Html.ActionLink("Back", "Index", null, new { @class = "btn btn-default btn-sm" }) -

Leave the accommodation blank to use the code on the candidate profile. If the session is full the candidate is added to the waitlist.

-
-
- } -
-
-
-
diff --git a/AssessmentDelivery.Web/Views/Booking/Cancel.cshtml b/AssessmentDelivery.Web/Views/Booking/Cancel.cshtml deleted file mode 100644 index 75b248ec..00000000 --- a/AssessmentDelivery.Web/Views/Booking/Cancel.cshtml +++ /dev/null @@ -1,34 +0,0 @@ -@model AssessmentDelivery.Web.Models.CancelViewModel -@{ - ViewBag.Title = "Cancel Booking"; - ViewBag.Breadcrumb = "My bookings » Cancel booking " + Model.Booking.BookingId; -} -

Cancel booking #@Model.Booking.BookingId

-
-
-
-
Booking
- - - - - - -
Exam@Model.Booking.ExamCode – @Model.Booking.ExamTitle
Centre@Model.Booking.CenterName
Start@Model.Booking.StartsAt.ToString("dddd dd MMM yyyy HH:mm")
Status@Html.StatusPill(Model.Booking.Status)
Channel@Model.Booking.Channel
-
- @using (Html.BeginForm("Cancel", "Booking", new { id = Model.Booking.BookingId }, FormMethod.Post, new { @class = "nw-form" })) - { - @Html.AntiForgeryToken() - @Html.ValidationSummary(false, "", new { @class = "alert alert-danger nw-alert" }) - @Html.HiddenFor(m => m.CandidateNumber) -
- - @Html.TextBoxFor(m => m.Reason, new { @class = "form-control input-sm", maxlength = "200" }) -
- - @Html.ActionLink("Keep booking", "MyBookings", new { candidateNumber = Model.CandidateNumber }, new { @class = "btn btn-default btn-sm" }) - } -
-
-
-
diff --git a/AssessmentDelivery.Web/Views/Booking/Index.cshtml b/AssessmentDelivery.Web/Views/Booking/Index.cshtml deleted file mode 100644 index 4da5b9e6..00000000 --- a/AssessmentDelivery.Web/Views/Booking/Index.cshtml +++ /dev/null @@ -1,88 +0,0 @@ -@model AssessmentDelivery.Web.Models.FindSessionsViewModel -@{ - ViewBag.Title = "Find Sessions"; -} -
-

Candidate booking Find an open session

- Sessions with status OPEN only. Seats available is the live counter. -
-
-
Search criteria
-
- -
-
-@if (Model.Searched) -{ -
-
Open sessions @Model.Results.Count
- - - - - - - - - @foreach (var s in Model.Results) - { - - - - - - - - - - - - - - - } - @if (Model.Results.Count == 0) - { - - } - -
SessionExamTitleCentreCityRoomStartMinsCapacitySeats avail.Status
#@s.SessionId@s.ExamCode@s.ExamTitle@s.CenterCode@s.City@s.RoomName@s.StartsAt.ToString("dd MMM yyyy HH:mm")@s.DurationMinutes@s.Capacity@s.SeatsAvailable@Html.StatusPill(s.Status) - @Html.ActionLink(s.SeatsAvailable > 0 ? "Book" : "Join waitlist", "Book", new { sessionId = s.SessionId, candidateNumber = Model.CandidateNumber }, new { @class = "btn btn-xs btn-primary" }) -
No open sessions match the criteria.
-
-} diff --git a/AssessmentDelivery.Web/Views/Booking/MyBookings.cshtml b/AssessmentDelivery.Web/Views/Booking/MyBookings.cshtml deleted file mode 100644 index 59072475..00000000 --- a/AssessmentDelivery.Web/Views/Booking/MyBookings.cshtml +++ /dev/null @@ -1,78 +0,0 @@ -@model AssessmentDelivery.Web.Models.MyBookingsViewModel -@{ - ViewBag.Title = "My Bookings"; -} -
-

My bookings

- All bookings for the candidate across portal, partner and import channels. -
-
-
Candidate
-
-
-
- - -
- -
- @Html.ValidationSummary(false, "", new { @class = "alert alert-danger nw-alert" }) - @if (Model.Candidate != null) - { - - - - - - - -
Name@Model.Candidate.FullNameCandidate no.@Model.Candidate.CandidateNumberEmail@Model.Candidate.EmailDefault accommodation@(Model.Candidate.DefaultAccommodationCode ?? "none")
- } -
-
-@if (Model.Bookings != null) -{ -
-
Bookings @Model.Bookings.Count - @Html.ActionLink("Book another session", "Index", new { candidateNumber = Model.Candidate.CandidateNumber }) -
- - - - - - - - - @foreach (var b in Model.Bookings) - { - - - - - - - - - - - - - - - } - @if (Model.Bookings.Count == 0) - { - - } - -
BookingExamTitleCentreSession startStatusAcc.ChannelPartner refBookedCancelled
@b.BookingId@b.ExamCode@b.ExamTitle@b.CenterName@b.StartsAt.ToString("dd MMM yyyy HH:mm")@Html.StatusPill(b.Status)@b.AccommodationCode@b.Channel@b.ExternalRef@b.BookedAt.ToString("dd/MM/yyyy HH:mm")@(b.CancelledAt.HasValue ? b.CancelledAt.Value.ToString("dd/MM/yyyy HH:mm") : "") - @if (b.CanChange) - { - @Html.ActionLink("Reschedule", "Reschedule", new { id = b.BookingId, candidateNumber = Model.Candidate.CandidateNumber }, new { @class = "btn btn-xs btn-default" }) - @Html.Raw(" ") - @Html.ActionLink("Cancel", "Cancel", new { id = b.BookingId, candidateNumber = Model.Candidate.CandidateNumber }, new { @class = "btn btn-xs btn-danger" }) - } -
No bookings on file.
-
-} diff --git a/AssessmentDelivery.Web/Views/Booking/Reschedule.cshtml b/AssessmentDelivery.Web/Views/Booking/Reschedule.cshtml deleted file mode 100644 index cd9a8ec0..00000000 --- a/AssessmentDelivery.Web/Views/Booking/Reschedule.cshtml +++ /dev/null @@ -1,47 +0,0 @@ -@model AssessmentDelivery.Web.Models.RescheduleViewModel -@{ - ViewBag.Title = "Reschedule Booking"; - ViewBag.Breadcrumb = "My bookings » Reschedule booking " + Model.Booking.BookingId; -} -
-

Reschedule booking #@Model.Booking.BookingId

- Currently @Model.Booking.ExamCode at @Model.Booking.CenterName on @Model.Booking.StartsAt.ToString("dd MMM yyyy HH:mm") (@Model.Booking.Status) -
-@using (Html.BeginForm("Reschedule", "Booking", new { id = Model.Booking.BookingId }, FormMethod.Post, new { @class = "nw-form" })) -{ - @Html.AntiForgeryToken() - @Html.HiddenFor(m => m.CandidateNumber) - @Html.ValidationSummary(false, "", new { @class = "alert alert-danger nw-alert" }) -
-
Other open sessions for @Model.Booking.ExamCode
- - - - - - @foreach (var s in Model.Targets) - { - - - - - - - - - - - - } - @if (Model.Targets.Count == 0) - { - - } - -
SessionCentreCityRoomStartCapacitySeats avail.Status
@s.CenterName@s.City@s.RoomName@s.StartsAt.ToString("dd MMM yyyy HH:mm")@s.Capacity@s.SeatsAvailable@Html.StatusPill(s.Status)
No other open sessions for this exam.
-
- - @Html.ActionLink("Back", "MyBookings", new { candidateNumber = Model.CandidateNumber }, new { @class = "btn btn-default btn-sm" }) -
-
-} diff --git a/AssessmentDelivery.Web/Views/Shared/_Layout.cshtml b/AssessmentDelivery.Web/Views/Shared/_Layout.cshtml index deb5f4e8..c3371876 100644 --- a/AssessmentDelivery.Web/Views/Shared/_Layout.cshtml +++ b/AssessmentDelivery.Web/Views/Shared/_Layout.cshtml @@ -32,7 +32,7 @@ Assessment Delivery Portal -
+ @@ -43,7 +43,7 @@
diff --git a/README.md b/README.md index fcd18b15..7b1467d1 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ The portal is Windows-only (.NET Framework 4.8). | What | URL | |---|---| -| Portal | http://localhost:8080/ - `/Admin/Centers`, `/Booking`, `/Booking/MyBookings?candidateNumber=`, `/Eligibility`, `/Results` | +| Portal | http://localhost:8080/ - `/Admin/Centers`, `/Eligibility`, `/Results` (booking pages retired in M5: via :8000 `/Booking/**` redirects to `/app`, [ADR 0004](docs/adr/0004-retire-portal-booking-slice.md)) | | booking-api | http://localhost:8081/api/v1/sessions | | results-service | http://localhost:8082/api/v1/results/candidate/NW00000001 | | capacity-sync | http://localhost:8083/sync/last (`POST /sync/run` to run now) | diff --git a/db/checks/test_usp_GetCapacityAudit.sql b/db/checks/test_usp_GetCapacityAudit.sql index 30c89d49..4e74c05c 100644 --- a/db/checks/test_usp_GetCapacityAudit.sql +++ b/db/checks/test_usp_GetCapacityAudit.sql @@ -1,6 +1,7 @@ /* test_usp_GetCapacityAudit.sql - SQL test for dbo.usp_GetCapacityAudit (MBA-3828) on seed data. - Makes capacity changes through usp_ChangeCapacity plus hand-written AuditLog rows inside one + Makes capacity changes (written the way the retired usp_ChangeCapacity did, MBA-3824) plus + hand-written AuditLog rows inside one transaction, checks the proc output, then ROLLS BACK (leaves the database unchanged). Test rows are moved to 2030 so they never mix with real/seed audit rows. Prints PASS/FAIL per check and raises error 50000 at the end if any check failed. @@ -37,14 +38,18 @@ DECLARE @before INT, @after INT, @n INT; BEGIN TRANSACTION; --- three portal-style changes at C1, one at C2 (raises only, so trigger 033 demotes nothing) -EXEC dbo.usp_ChangeCapacity @SessionId = @s1, @NewCapacity = @new1, @Actor = 'portal-admin'; +-- three portal-style changes at C1, one at C2 (raises only, so trigger 033 demotes nothing), +-- same capacity update and ' -> ' AuditLog row as the retired usp_ChangeCapacity (legacy-baseline) +UPDATE dbo.ExamSession SET Capacity = CASE SessionId WHEN @s1 THEN @new1 WHEN @s2 THEN @new2 WHEN @s3 THEN @new3 ELSE @newx END, + SeatsAvailable = SeatsAvailable + (CASE SessionId WHEN @s1 THEN @new1 WHEN @s2 THEN @new2 WHEN @s3 THEN @new3 ELSE @newx END - Capacity) + WHERE SessionId IN (@s1, @s2, @s3, @x1); +INSERT INTO dbo.AuditLog (EntityName, EntityId, Action, Detail, Actor) VALUES ('ExamSession', @s1, 'CAPACITY', CONCAT(@cap1, ' -> ', @new1), 'portal-admin'); SELECT @a1 = MAX(AuditId) FROM dbo.AuditLog WHERE EntityId = @s1 AND Action = 'CAPACITY'; -EXEC dbo.usp_ChangeCapacity @SessionId = @s2, @NewCapacity = @new2, @Actor = 'portal-admin'; +INSERT INTO dbo.AuditLog (EntityName, EntityId, Action, Detail, Actor) VALUES ('ExamSession', @s2, 'CAPACITY', CONCAT(@cap2, ' -> ', @new2), 'portal-admin'); SELECT @a2 = MAX(AuditId) FROM dbo.AuditLog WHERE EntityId = @s2 AND Action = 'CAPACITY'; -EXEC dbo.usp_ChangeCapacity @SessionId = @s3, @NewCapacity = @new3, @Actor = 'test-admin'; +INSERT INTO dbo.AuditLog (EntityName, EntityId, Action, Detail, Actor) VALUES ('ExamSession', @s3, 'CAPACITY', CONCAT(@cap3, ' -> ', @new3), 'test-admin'); SELECT @a3 = MAX(AuditId) FROM dbo.AuditLog WHERE EntityId = @s3 AND Action = 'CAPACITY'; -EXEC dbo.usp_ChangeCapacity @SessionId = @x1, @NewCapacity = @newx, @Actor = 'portal-admin'; +INSERT INTO dbo.AuditLog (EntityName, EntityId, Action, Detail, Actor) VALUES ('ExamSession', @x1, 'CAPACITY', CONCAT(@capx, ' -> ', @newx), 'portal-admin'); SELECT @ax = MAX(AuditId) FROM dbo.AuditLog WHERE EntityId = @x1 AND Action = 'CAPACITY'; -- malformed CAPACITY detail and a capacity-sync run row (EntityId 0) diff --git a/db/procs/020_usp_BookSeat.sql b/db/procs/020_usp_BookSeat.sql deleted file mode 100644 index 0ce32e1b..00000000 --- a/db/procs/020_usp_BookSeat.sql +++ /dev/null @@ -1,92 +0,0 @@ -/* - usp_BookSeat - book a seat on an exam session (portal channel) - - Returns @ResultStatus = 'BOOKED' or 'WAITLISTED' (session full). - Errors (RAISERROR, severity 16): - 50001 session not found / not open - 50002 candidate already holds an active booking on this session - 50003 no accommodation seat left for an extra-time booking - Retake eligibility is validated by the calling application before this is called. - 2012-03 initial version (portal v2) - 2014-08 accommodation seats (ET25/ET50) -*/ -USE AssessmentDelivery; -GO -IF OBJECT_ID('dbo.usp_BookSeat') IS NOT NULL DROP PROCEDURE dbo.usp_BookSeat; -GO -CREATE PROCEDURE dbo.usp_BookSeat - @SessionId INT, - @CandidateId INT, - @AccommodationCode VARCHAR(10) = NULL, - @BookingId INT OUTPUT, - @ResultStatus VARCHAR(12) OUTPUT -AS -BEGIN - SET NOCOUNT ON; - SET XACT_ABORT ON; - - DECLARE @Seats INT, @AccCap INT, @SessStatus VARCHAR(12), @AccUsed INT, @Pos INT; - - BEGIN TRY - BEGIN TRANSACTION; - - SELECT @Seats = SeatsAvailable, @AccCap = AccommodationCapacity, @SessStatus = Status - FROM dbo.ExamSession WITH (UPDLOCK, HOLDLOCK) - WHERE SessionId = @SessionId; - - IF @SessStatus IS NULL OR @SessStatus <> 'OPEN' - RAISERROR('Session %d is not open for booking.', 16, 1, @SessionId); - - IF EXISTS (SELECT 1 FROM dbo.Booking - WHERE SessionId = @SessionId AND CandidateId = @CandidateId - AND Status IN ('BOOKED','WAITLISTED')) - RAISERROR('Candidate %d already has an active booking on session %d.', 16, 2, @CandidateId, @SessionId); - - IF @AccommodationCode IN ('ET25','ET50') - BEGIN - SELECT @AccUsed = COUNT(*) FROM dbo.Booking - WHERE SessionId = @SessionId AND Status IN ('BOOKED','ATTENDED') - AND AccommodationCode IN ('ET25','ET50'); - IF @AccUsed >= @AccCap - RAISERROR('No accommodation seat available on session %d.', 16, 3, @SessionId); - END - - IF @Seats > 0 - BEGIN - INSERT INTO dbo.Booking (SessionId, CandidateId, Status, AccommodationCode, Channel) - VALUES (@SessionId, @CandidateId, 'BOOKED', @AccommodationCode, 'PORTAL'); - SET @BookingId = SCOPE_IDENTITY(); - - UPDATE dbo.ExamSession - SET SeatsAvailable = SeatsAvailable - 1, LastModified = GETDATE() - WHERE SessionId = @SessionId; - - SET @ResultStatus = 'BOOKED'; - END - ELSE - BEGIN - INSERT INTO dbo.Booking (SessionId, CandidateId, Status, AccommodationCode, Channel) - VALUES (@SessionId, @CandidateId, 'WAITLISTED', @AccommodationCode, 'PORTAL'); - SET @BookingId = SCOPE_IDENTITY(); - - SELECT @Pos = ISNULL(MAX(Position), 0) + 1 FROM dbo.Waitlist WHERE SessionId = @SessionId; - INSERT INTO dbo.Waitlist (SessionId, CandidateId, BookingId, Position) - VALUES (@SessionId, @CandidateId, @BookingId, @Pos); - - SET @ResultStatus = 'WAITLISTED'; - END - - INSERT INTO dbo.AuditLog (EntityName, EntityId, Action, Detail) - VALUES ('Booking', @BookingId, 'BOOK', 'session=' + CAST(@SessionId AS VARCHAR(12)) + ' status=' + @ResultStatus); - - COMMIT TRANSACTION; - END TRY - BEGIN CATCH - IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION; - DECLARE @msg NVARCHAR(2048) = ERROR_MESSAGE(), @state INT = ERROR_STATE(); - RAISERROR(@msg, 16, @state); - RETURN 1; - END CATCH - RETURN 0; -END -GO diff --git a/db/procs/021_usp_CancelBooking.sql b/db/procs/021_usp_CancelBooking.sql deleted file mode 100644 index 8bb7137f..00000000 --- a/db/procs/021_usp_CancelBooking.sql +++ /dev/null @@ -1,56 +0,0 @@ -/* - usp_CancelBooking - cancel a BOOKED or WAITLISTED booking and release the seat. - Waitlisted candidates are NOT promoted automatically; centre staff promote - them from the admin screen (manual process since 2013). - Errors: 50004 booking not found or not cancellable. -*/ -USE AssessmentDelivery; -GO -IF OBJECT_ID('dbo.usp_CancelBooking') IS NOT NULL DROP PROCEDURE dbo.usp_CancelBooking; -GO -CREATE PROCEDURE dbo.usp_CancelBooking - @BookingId INT, - @Reason NVARCHAR(200) = NULL, - @Actor VARCHAR(60) = NULL -AS -BEGIN - SET NOCOUNT ON; - SET XACT_ABORT ON; - - DECLARE @Status VARCHAR(12), @SessionId INT; - - BEGIN TRY - BEGIN TRANSACTION; - - SELECT @Status = Status, @SessionId = SessionId - FROM dbo.Booking WITH (UPDLOCK, HOLDLOCK) - WHERE BookingId = @BookingId; - - IF @Status IS NULL OR @Status NOT IN ('BOOKED','WAITLISTED') - RAISERROR('Booking %d cannot be cancelled.', 16, 4, @BookingId); - - UPDATE dbo.Booking - SET Status = 'CANCELLED', CancelledAt = GETDATE(), CancelReason = @Reason, LastModified = GETDATE() - WHERE BookingId = @BookingId; - - IF @Status = 'BOOKED' - UPDATE dbo.ExamSession - SET SeatsAvailable = SeatsAvailable + 1, LastModified = GETDATE() - WHERE SessionId = @SessionId; - ELSE - DELETE FROM dbo.Waitlist WHERE BookingId = @BookingId; - - INSERT INTO dbo.AuditLog (EntityName, EntityId, Action, Detail, Actor) - VALUES ('Booking', @BookingId, 'CANCEL', @Reason, ISNULL(@Actor, SUSER_SNAME())); - - COMMIT TRANSACTION; - END TRY - BEGIN CATCH - IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION; - DECLARE @msg NVARCHAR(2048) = ERROR_MESSAGE(), @state INT = ERROR_STATE(); - RAISERROR(@msg, 16, @state); - RETURN 1; - END CATCH - RETURN 0; -END -GO diff --git a/db/procs/022_usp_ChangeCapacity.sql b/db/procs/022_usp_ChangeCapacity.sql deleted file mode 100644 index a28b9a3f..00000000 --- a/db/procs/022_usp_ChangeCapacity.sql +++ /dev/null @@ -1,53 +0,0 @@ -/* - usp_ChangeCapacity - change the seat capacity of a session (centre admin). - SeatsAvailable is adjusted by the same delta and never goes below zero. - Errors: 50005 session not found / invalid capacity. -*/ -USE AssessmentDelivery; -GO -IF OBJECT_ID('dbo.usp_ChangeCapacity') IS NOT NULL DROP PROCEDURE dbo.usp_ChangeCapacity; -GO -CREATE PROCEDURE dbo.usp_ChangeCapacity - @SessionId INT, - @NewCapacity INT, - @Actor VARCHAR(60) = NULL -AS -BEGIN - SET NOCOUNT ON; - SET XACT_ABORT ON; - - DECLARE @OldCapacity INT, @AccCap INT; - - BEGIN TRY - BEGIN TRANSACTION; - - SELECT @OldCapacity = Capacity, @AccCap = AccommodationCapacity - FROM dbo.ExamSession WITH (UPDLOCK, HOLDLOCK) - WHERE SessionId = @SessionId; - - IF @OldCapacity IS NULL OR @NewCapacity < 0 OR @NewCapacity < @AccCap - RAISERROR('Invalid capacity %d for session %d.', 16, 5, @NewCapacity, @SessionId); - - UPDATE dbo.ExamSession - SET Capacity = @NewCapacity, - SeatsAvailable = CASE WHEN SeatsAvailable + (@NewCapacity - Capacity) < 0 THEN 0 - ELSE SeatsAvailable + (@NewCapacity - Capacity) END, - LastModified = GETDATE() - WHERE SessionId = @SessionId; - - INSERT INTO dbo.AuditLog (EntityName, EntityId, Action, Detail, Actor) - VALUES ('ExamSession', @SessionId, 'CAPACITY', - CAST(@OldCapacity AS VARCHAR(12)) + ' -> ' + CAST(@NewCapacity AS VARCHAR(12)), - ISNULL(@Actor, SUSER_SNAME())); - - COMMIT TRANSACTION; - END TRY - BEGIN CATCH - IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION; - DECLARE @msg NVARCHAR(2048) = ERROR_MESSAGE(), @state INT = ERROR_STATE(); - RAISERROR(@msg, 16, @state); - RETURN 1; - END CATCH - RETURN 0; -END -GO diff --git a/db/procs/023_usp_RescheduleBooking.sql b/db/procs/023_usp_RescheduleBooking.sql deleted file mode 100644 index e5b84306..00000000 --- a/db/procs/023_usp_RescheduleBooking.sql +++ /dev/null @@ -1,51 +0,0 @@ -/* - usp_RescheduleBooking - move a booking to another session of the same exam. - Implemented as cancel + new booking so seat counters stay in step. - Returns the new booking id and its status (BOOKED / WAITLISTED). - Errors: 50006 target session is for a different exam. -*/ -USE AssessmentDelivery; -GO -IF OBJECT_ID('dbo.usp_RescheduleBooking') IS NOT NULL DROP PROCEDURE dbo.usp_RescheduleBooking; -GO -CREATE PROCEDURE dbo.usp_RescheduleBooking - @BookingId INT, - @NewSessionId INT, - @NewBookingId INT OUTPUT, - @ResultStatus VARCHAR(12) OUTPUT -AS -BEGIN - SET NOCOUNT ON; - SET XACT_ABORT ON; - - DECLARE @CandidateId INT, @Acc VARCHAR(10), @OldExam INT, @NewExam INT; - - SELECT @CandidateId = b.CandidateId, @Acc = b.AccommodationCode, @OldExam = s.ExamId - FROM dbo.Booking b JOIN dbo.ExamSession s ON s.SessionId = b.SessionId - WHERE b.BookingId = @BookingId; - - SELECT @NewExam = ExamId FROM dbo.ExamSession WHERE SessionId = @NewSessionId; - - IF @OldExam IS NULL OR @NewExam IS NULL OR @OldExam <> @NewExam - BEGIN - RAISERROR('Booking %d cannot be moved to session %d.', 16, 6, @BookingId, @NewSessionId); - RETURN 1; - END - - BEGIN TRY - BEGIN TRANSACTION; - EXEC dbo.usp_CancelBooking @BookingId = @BookingId, @Reason = N'Rescheduled'; - EXEC dbo.usp_BookSeat @SessionId = @NewSessionId, @CandidateId = @CandidateId, - @AccommodationCode = @Acc, - @BookingId = @NewBookingId OUTPUT, @ResultStatus = @ResultStatus OUTPUT; - COMMIT TRANSACTION; - END TRY - BEGIN CATCH - IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION; - DECLARE @msg NVARCHAR(2048) = ERROR_MESSAGE(), @state INT = ERROR_STATE(); - RAISERROR(@msg, 16, @state); - RETURN 1; - END CATCH - RETURN 0; -END -GO diff --git a/db/procs/030_usp_GetCapacityAudit.sql b/db/procs/030_usp_GetCapacityAudit.sql index dbb4545d..dc8ba942 100644 --- a/db/procs/030_usp_GetCapacityAudit.sql +++ b/db/procs/030_usp_GetCapacityAudit.sql @@ -1,7 +1,7 @@ /* usp_GetCapacityAudit - read-only capacity change history for one test centre (portal /Admin/Centers/{id}/CapacityAudit, MBA-3828). - Lists the AuditLog rows written by usp_ChangeCapacity (EntityName 'ExamSession', + Lists the AuditLog rows written by usp_ChangeCapacity until MBA-3824 retired it (EntityName 'ExamSession', Action 'CAPACITY', Detail ' -> ') for sessions at @TestCenterId, newest first. capacity-sync run rows (Action 'CAPACITY_SYNC', EntityId 0) are excluded by the Action filter. @From inclusive, @To exclusive. Detail that is not exactly ' -> ' comes back with diff --git a/db/procs/090_retire_booking_procs.sql b/db/procs/090_retire_booking_procs.sql new file mode 100644 index 00000000..f3fd712e --- /dev/null +++ b/db/procs/090_retire_booking_procs.sql @@ -0,0 +1,13 @@ +-- 090_retire_booking_procs.sql +-- MBA-3824 (M5): scheduling-service is the only booking/capacity writer (docs/adr/0003-single-writer-outbox-relay.md), +-- the portal booking pages and booking-api write SQL are deleted, so the four legacy write procs go too. +-- Their source stays in git history (020_usp_BookSeat.sql .. 023_usp_RescheduleBooking.sql at tag legacy-baseline); +-- their behaviour is documented in docs/SYSTEM_OVERVIEW.md and docs/as-is/deep-dives/sql.md. +-- Idempotent: safe on a fresh apply (procs never created) and on an existing M4 database. +USE AssessmentDelivery; +GO +DROP PROCEDURE IF EXISTS dbo.usp_BookSeat; +DROP PROCEDURE IF EXISTS dbo.usp_CancelBooking; +DROP PROCEDURE IF EXISTS dbo.usp_ChangeCapacity; +DROP PROCEDURE IF EXISTS dbo.usp_RescheduleBooking; +GO diff --git a/db/security/040_single_writer.sql b/db/security/040_single_writer.sql index b8789b6f..a696b273 100644 --- a/db/security/040_single_writer.sql +++ b/db/security/040_single_writer.sql @@ -5,42 +5,27 @@ -- gateway (:8000) to scheduling-service; its outbox relay (ad_sched_relay) projects them back here. -- Legacy read pages keep rendering from these tables. ad_sched_import stays read-only (035). -- DENY beats the db_datawriter / GRANT EXECUTE membership from 036, so writes fail with error 229/230. +-- MBA-3824: the four booking procs are dropped by db/procs/090_retire_booking_procs.sql, so no EXECUTE denies. USE AssessmentDelivery; GO DENY INSERT, UPDATE, DELETE ON dbo.Booking TO ad_portal; DENY INSERT, UPDATE, DELETE ON dbo.Waitlist TO ad_portal; DENY UPDATE ON dbo.ExamSession (Capacity, SeatsAvailable, AccommodationCapacity) TO ad_portal; -DENY EXECUTE ON dbo.usp_BookSeat TO ad_portal; -DENY EXECUTE ON dbo.usp_CancelBooking TO ad_portal; -DENY EXECUTE ON dbo.usp_ChangeCapacity TO ad_portal; -DENY EXECUTE ON dbo.usp_RescheduleBooking TO ad_portal; DENY INSERT, UPDATE, DELETE ON dbo.RelayCheckpoint TO ad_portal; GO DENY INSERT, UPDATE, DELETE ON dbo.Booking TO ad_booking_api; DENY INSERT, UPDATE, DELETE ON dbo.Waitlist TO ad_booking_api; DENY UPDATE ON dbo.ExamSession (Capacity, SeatsAvailable, AccommodationCapacity) TO ad_booking_api; -DENY EXECUTE ON dbo.usp_BookSeat TO ad_booking_api; -DENY EXECUTE ON dbo.usp_CancelBooking TO ad_booking_api; -DENY EXECUTE ON dbo.usp_ChangeCapacity TO ad_booking_api; -DENY EXECUTE ON dbo.usp_RescheduleBooking TO ad_booking_api; DENY INSERT, UPDATE, DELETE ON dbo.RelayCheckpoint TO ad_booking_api; GO DENY INSERT, UPDATE, DELETE ON dbo.Booking TO ad_results; DENY INSERT, UPDATE, DELETE ON dbo.Waitlist TO ad_results; DENY UPDATE ON dbo.ExamSession (Capacity, SeatsAvailable, AccommodationCapacity) TO ad_results; -DENY EXECUTE ON dbo.usp_BookSeat TO ad_results; -DENY EXECUTE ON dbo.usp_CancelBooking TO ad_results; -DENY EXECUTE ON dbo.usp_ChangeCapacity TO ad_results; -DENY EXECUTE ON dbo.usp_RescheduleBooking TO ad_results; DENY INSERT, UPDATE, DELETE ON dbo.RelayCheckpoint TO ad_results; GO DENY INSERT, UPDATE, DELETE ON dbo.Booking TO ad_capacity_sync; DENY INSERT, UPDATE, DELETE ON dbo.Waitlist TO ad_capacity_sync; DENY UPDATE ON dbo.ExamSession (Capacity, SeatsAvailable, AccommodationCapacity) TO ad_capacity_sync; -DENY EXECUTE ON dbo.usp_BookSeat TO ad_capacity_sync; -DENY EXECUTE ON dbo.usp_CancelBooking TO ad_capacity_sync; -DENY EXECUTE ON dbo.usp_ChangeCapacity TO ad_capacity_sync; -DENY EXECUTE ON dbo.usp_RescheduleBooking TO ad_capacity_sync; DENY INSERT, UPDATE, DELETE ON dbo.RelayCheckpoint TO ad_capacity_sync; GO -- a leftover shared login from an older apply must not keep a side door open diff --git a/docs/adr/0004-retire-portal-booking-slice.md b/docs/adr/0004-retire-portal-booking-slice.md new file mode 100644 index 00000000..ade00e2b --- /dev/null +++ b/docs/adr/0004-retire-portal-booking-slice.md @@ -0,0 +1,74 @@ +# ADR 0004: retire the .NET booking/capacity slice; legacy booking URLs redirect to /app (MBA-3824, M5) + +Status: accepted. Builds on [ADR 0003](0003-single-writer-outbox-relay.md) (M4 single writer) and the M3 routing +gateway ([services/routing-gateway/README.md](../../services/routing-gateway/README.md)). + +## Context + +Since M4 scheduling-service is the only writer of bookings, waitlist, attendance and capacity for every centre +(`routing.modern-centers=*`, `routing.coexistence-mode=relay`), and every legacy login is denied those writes +(`db/security/040_single_writer.sql`). The portal booking pages, the capacity page, the four booking procs and +booking-api's write SQL were therefore dead code. Their legacy behaviour stays documented in +[README.md](../../README.md), [docs/SYSTEM_OVERVIEW.md](../SYSTEM_OVERVIEW.md) (portal routes, stored procedures) +and [docs/as-is/](../as-is/) (HB-01..HB-31, MR-01..MR-21, deep dives); it is not re-derived here. + +## Decisions + +1. **Portal slice deleted.** `BookingController` and `Views/Booking/*`, `AdminController.Capacity` (GET/POST), + `Views/Admin/Capacity.cshtml` and the `AdminCapacity` route, `AssessmentDelivery.Services/Booking/*`, + `AdminService.ChangeCapacity`/`GetSessionRow`, `SqlErrorHelper` (only translated proc errors), `Models/BookingModels.cs`, + `Business/Rules/SeatCounter.cs` and `SeatCounterTests`. The two reads that `/Eligibility` and `/Results` borrowed + from `IBookingService` moved to `IEligibilityService.ListExams` and `IResultsService.FindCandidate` (same queries). + `BookingStatus` constants moved to `Business/Rules/BookingStatus.cs`; the admin "Booked" column is counted in the + EF query (BOOKED + ATTENDED, same rule). `/Admin/Centers`, `/Admin/Centers/{id}/Edit`, the `/Admin/Sessions` list, + roster CSV, capacity audit, `/Eligibility` and `/Results` are unchanged. The "Bookings" tab, the candidate + quick-find and the per-session "Capacity" links now point at the legacy URLs, which the gateway redirects. +2. **Every centre redirects.** The gateway no longer consults the allow-list for the retired portal pages: they + redirect to `/app` for every centre, including centres never allow-listed in M3, unresolvable ids and requests + without a centre key. GET/HEAD answer `302`, POST `303`; `X-Route: modern`, log reason `legacy page retired`. + + | Legacy URL | Redirect | + |---|---| + | `/Booking[?CenterCode=&ExamCode=&From=&To=]` | `/app/[?center=&exam=&from=&to=]` | + | `/Booking/Book?sessionId=`, `POST /Booking/Book` (form `SessionId`) | `/app/book?sessionId=` (`/app/` without one) | + | `/Booking/MyBookings[?candidateNumber=]` | `/app/my-bookings[?candidateNumber=]` (the UI loads that candidate) | + | `/Booking/Cancel/{id}` | `/app/my-bookings` | + | `/Booking/Reschedule/{id}` | `/app/reschedule/{id}` | + | `/Admin/Sessions?centerId=` | `/app/admin/centers/{centerCode}` (`/app/` if the id does not resolve) | + | `/Admin/Sessions/Capacity/{id}` | `/app/admin/sessions/{id}` | + + Directly on :8080 these URLs are now `404`. `routing.coexistence-mode` stays `relay`. +3. **booking-api writes are routed entirely by the gateway.** `POST /api/v1/bookings`, `DELETE /api/v1/bookings/{id}` + and `POST /api/v1/bookings/{id}/reschedule` are served from scheduling-service by the gateway (M3/M4, unchanged). + booking-api's own write path (`BookingService`, the write DAO methods, request/response models) is deleted; a write + that reaches :8081 directly gets `410 {"error":"LEGACY_WRITE_RETIRED"}` (was `403 LEGACY_WRITE_DENIED` in M4). + Reads (`GET /api/v1/sessions`, `/bookings/{id}`, `/candidates/**`) are unchanged. +4. **Procs dropped.** `db/procs/090_retire_booking_procs.sql` drops `usp_BookSeat`, `usp_CancelBooking`, + `usp_ChangeCapacity` and `usp_RescheduleBooking` (idempotent). Their create scripts `020`..`023` are deleted and kept + in git history (tag `legacy-baseline`). The `DENY EXECUTE` lines on them leave `040_single_writer.sql`. + `db/checks/test_usp_GetCapacityAudit.sql` now writes its capacity changes the way `usp_ChangeCapacity` did. +5. **Guard.** `scripts/check-retired-booking-writes.sh` (CI: `.github/workflows/retired-booking-writes.yml`) fails if + portal C# or booking-api main code references the four procs, updates `SeatsAvailable` or writes `Booking`/`Waitlist`. + +## Expected characterization differences (for M6 parity) + +The M1 transcripts in `characterization/transcripts/` are not edited. Replayed after M5 they differ as follows; +classify these as **intended (MBA-3824)**, not regressions. + +| Class | Transcripts | Through :8000 | Directly against legacy | +|---|---|---|---| +| M5-PORTAL-REDIRECT: a step calls a retired portal page (`POST /Booking/Book`, `/Booking/Cancel/{id}`, `/Booking/Reschedule/{id}`, `/Admin/Sessions/Capacity/{id}`) | AC-01, AC-03, AC-05, AC-07, BK-01, BK-03, BK-05, BK-07 (setup), BK-08, BK-10, CN-01, CN-03, CN-05, CN-07, CP-01, CP-02, CP-03, CP-04, CP-05, CP-07, CP-08, MX-03, RS-01, RS-03, RS-05, RS-07 (setup), RS-08, RS-10, RT-14 (29) | `303 See Other` (`302` for GET) to the `/app` route above, `X-Route: modern`; that step writes nothing, so later `after` snapshots differ | `404` | +| M5-PROC-DROPPED: a db step executes a retired proc | BK-07, CP-06, CP-09, RS-07 | SQL error 2812 `Could not find stored procedure` instead of the proc's error 50000 | same | +| M5-API-WRITE-410: an api step writes on booking-api | AC-02, AC-04, AC-06, AC-08, BK-02, BK-04, BK-06, BK-09, BK-11, CN-02, CN-04, CN-06, CN-08, CP-07, MX-03, RS-02, RS-04, RS-06, RS-08, RS-09, RT-15 | unchanged from M4 (served by scheduling-service in the v1 shape) | `410 LEGACY_WRITE_RETIRED` (M4: `403 LEGACY_WRITE_DENIED`) | +| M5-MIXED: `scripts/mixed-traffic.ps1` workload | MX-01 | as M4 when `PORTAL_URL`/`BOOKING_API_URL` point at :8000 | portal `404`, partner `410` | +| unchanged | RT-01..RT-13 (eligibility pages and API reads), MX-02 | same as M4 | same as M4 | + +## Consequences + +- The slice has one implementation. Removing a centre from `routing.modern-centers` no longer brings back portal + booking pages (they do not exist); it only moves API traffic, and since M4 legacy writes are denied anyway. Narrowing + the allow-list now freezes writes for the removed centres (v2 `403 CENTER_NOT_MODERN`, v1 forwarded to booking-api `410`). +- Through :8000, `/Admin/Sessions?centerId=` opens the modern admin grid (as it already did for allow-listed centres since + M3), so the legacy session list and its roster CSV link are reached directly on :8080 or by URL + (`/Admin/Sessions/Roster/{id}?format=csv` and `/Admin/Centers/{id}/CapacityAudit` still proxy to legacy). +- `SeatsAvailable` is still read by the admin pages; it is written only by the relay (ADR 0003). diff --git a/docs/runbooks/scheduling-service.md b/docs/runbooks/scheduling-service.md index a96f96b7..39a48e28 100644 --- a/docs/runbooks/scheduling-service.md +++ b/docs/runbooks/scheduling-service.md @@ -169,6 +169,10 @@ With the relay live and the legacy write denial in place (`db/security/040_singl > **Single writer (MBA-3823).** Once `db/security/040_single_writer.sql` is applied, routing a centre back to legacy > only moves its *reads*: legacy booking/capacity writes stay denied for every centre, so the steps below do not restore > legacy writes on their own. To hand writes back to legacy use ยง6 (it is all-or-nothing, not per centre). +> +> **M5 (MBA-3824).** The portal booking/capacity pages, the four booking procs and booking-api's write SQL are deleted +> ([ADR 0004](../adr/0004-retire-portal-booking-slice.md)); the gateway redirects the old portal URLs to `/app` for every +> centre. There is no legacy write path left to roll back to; restoring one means reverting the MBA-3824 change. Which backend serves a centre is decided by the routing allow-list `scheduling.routing.modern-centers` (env `SCHEDULING_ROUTING_MODERN_CENTERS`, comma-separated centre codes, `*` = all; everything else goes to diff --git a/scripts/check-retired-booking-writes.sh b/scripts/check-retired-booking-writes.sh new file mode 100644 index 00000000..4e5be090 --- /dev/null +++ b/scripts/check-retired-booking-writes.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# MBA-3824 guard: fails if the retired booking/capacity write paths reappear in the portal (C#) or booking-api. +# docs/adr/0004-retire-portal-booking-slice.md +set -uo pipefail +cd "$(dirname "$0")/.." + +PORTAL=(AssessmentDelivery.Web AssessmentDelivery.Services AssessmentDelivery.Business AssessmentDelivery.Data) +BOOKING_API=services/booking-api/src/main +fail=0 + +check() { + local what=$1 pattern=$2 + shift 2 + local hits + hits=$(grep -rnEI --include='*.cs' --include='*.cshtml' --include='*.java' "$pattern" "$@") + if [ -n "$hits" ]; then + echo "FAIL: $what" + echo "$hits" + fail=1 + fi +} + +check "retired booking procs referenced" 'usp_(BookSeat|CancelBooking|ChangeCapacity|RescheduleBooking)' \ + "${PORTAL[@]}" AssessmentDelivery.Tests "$BOOKING_API" +check "SeatsAvailable updated" '\.SeatsAvailable[[:space:]]*(\+\+|--|[-+]?=[^=>])|SET[[:space:]]+SeatsAvailable' \ + "${PORTAL[@]}" "$BOOKING_API" +check "Booking/Waitlist written" '\.(Bookings|Waitlist)\.(Add|AddRange|Remove|RemoveRange|Attach)\(|(INSERT[[:space:]]+INTO|UPDATE|DELETE[[:space:]]+FROM)[[:space:]]+(dbo\.)?(Booking|Waitlist)([^A-Za-z]|$)' \ + "${PORTAL[@]}" "$BOOKING_API" + +if [ "$fail" -eq 0 ]; then + echo "OK: no retired booking/capacity writes" +fi +exit "$fail" diff --git a/services/README.md b/services/README.md index 613d2c90..b44cd53a 100644 --- a/services/README.md +++ b/services/README.md @@ -43,8 +43,10 @@ java -jar services/results-service/target/results-service.jar java -jar services/capacity-sync/target/capacity-sync.jar ``` -`scripts/mixed-traffic.sh` books a batch of seats through both channels (portal via `usp_BookSeat`, -partner via booking-api) on a freshly seeded database and prints a short summary. +`scripts/mixed-traffic.sh` books a batch of seats through both channels (portal and partner) on a freshly seeded +database and prints a short summary. Since MBA-3824 booking-api no longer writes (direct writes on :8081 get +`410 LEGACY_WRITE_RETIRED`) and the portal booking pages are gone: point `PORTAL_URL` and `BOOKING_API_URL` at the +routing gateway (:8000), which serves both from scheduling-service ([ADR 0004](../docs/adr/0004-retire-portal-booking-slice.md)). ## Profiles / configuration diff --git a/services/booking-api/src/main/java/com/northwind/assessment/booking/dao/BookingDao.java b/services/booking-api/src/main/java/com/northwind/assessment/booking/dao/BookingDao.java index d2529c58..6d29eea8 100644 --- a/services/booking-api/src/main/java/com/northwind/assessment/booking/dao/BookingDao.java +++ b/services/booking-api/src/main/java/com/northwind/assessment/booking/dao/BookingDao.java @@ -13,11 +13,8 @@ import com.northwind.assessment.booking.util.DateUtils; /** - * Booking table access for the partner channel. - * - * NB partner bookings are inserted directly (not through usp_BookSeat) - the proc - * did not take Channel/ExternalRef when the partner API was written (2014) and - * nobody has gone back to it. + * Booking table reads for the partner channel. MBA-3824 deleted the write SQL + * (scheduling-service is the single writer, docs/adr/0003-single-writer-outbox-relay.md). */ @Repository public class BookingDao { @@ -49,53 +46,6 @@ public int findCandidateId(int bookingId) { Integer.class, bookingId); } - public boolean hasActiveBooking(int sessionId, int candidateId) { - Integer n = jdbcTemplate.queryForObject( - "SELECT COUNT(*) FROM dbo.Booking WHERE SessionId = ? AND CandidateId = ? " - + "AND Status IN ('BOOKED','WAITLISTED')", Integer.class, sessionId, candidateId); - return n != null && n.intValue() > 0; - } - - /** Extra-time bookings currently holding an accommodation seat. Same rule as usp_BookSeat. */ - public int countAccommodationSeatsUsed(int sessionId) { - return jdbcTemplate.queryForObject( - "SELECT COUNT(*) FROM dbo.Booking WHERE SessionId = ? AND Status IN ('BOOKED','ATTENDED') " - + "AND AccommodationCode IN ('ET25','ET50')", Integer.class, sessionId); - } - - public int findAccommodationCapacity(int sessionId) { - return jdbcTemplate.queryForObject( - "SELECT AccommodationCapacity FROM dbo.ExamSession WHERE SessionId = ?", Integer.class, sessionId); - } - - public int insertBooking(int sessionId, int candidateId, String status, String accommodationCode, - String channel, String externalRef) { - // SCOPE_IDENTITY rather than getGeneratedKeys, kept from the sqljdbc4 days - return jdbcTemplate.queryForObject( - "SET NOCOUNT ON; " - + "INSERT INTO dbo.Booking (SessionId, CandidateId, Status, AccommodationCode, Channel, ExternalRef) " - + "VALUES (?, ?, ?, ?, ?, ?); " - + "SELECT CAST(SCOPE_IDENTITY() AS INT);", - Integer.class, sessionId, candidateId, status, accommodationCode, channel, externalRef); - } - - public int insertWaitlist(int sessionId, int candidateId, int bookingId) { - int pos = jdbcTemplate.queryForObject( - "SELECT ISNULL(MAX(Position), 0) + 1 FROM dbo.Waitlist WHERE SessionId = ?", Integer.class, sessionId); - jdbcTemplate.update("INSERT INTO dbo.Waitlist (SessionId, CandidateId, BookingId, Position) VALUES (?, ?, ?, ?)", - sessionId, candidateId, bookingId, pos); - return pos; - } - - public void cancel(int bookingId, String reason, String actor) { - jdbcTemplate.update("EXEC dbo.usp_CancelBooking @BookingId = ?, @Reason = ?, @Actor = ?", - bookingId, reason, actor); - } - - public void audit(String entity, int entityId, String action, String detail, String actor) { - jdbcTemplate.update("INSERT INTO dbo.AuditLog (EntityName, EntityId, Action, Detail, Actor) VALUES (?, ?, ?, ?, ?)", - entity, entityId, action, detail, actor); - } private static final RowMapper BOOKING_MAPPER = new RowMapper() { public BookingInfo mapRow(ResultSet rs, int rowNum) throws SQLException { diff --git a/services/booking-api/src/main/java/com/northwind/assessment/booking/dao/SessionDao.java b/services/booking-api/src/main/java/com/northwind/assessment/booking/dao/SessionDao.java index 18ab5b98..210c40a2 100644 --- a/services/booking-api/src/main/java/com/northwind/assessment/booking/dao/SessionDao.java +++ b/services/booking-api/src/main/java/com/northwind/assessment/booking/dao/SessionDao.java @@ -61,28 +61,6 @@ public SessionInfo findById(int sessionId) { return list.isEmpty() ? null : list.get(0); } - /** Exam id of a session, or null. */ - public Integer findExamId(int sessionId) { - List ids = jdbcTemplate.queryForList( - "SELECT ExamId FROM dbo.ExamSession WHERE SessionId = ?", Integer.class, sessionId); - return ids.isEmpty() ? null : ids.get(0); - } - - public Date findStartsAt(int sessionId) { - List d = jdbcTemplate.queryForList( - "SELECT StartsAt FROM dbo.ExamSession WHERE SessionId = ?", Date.class, sessionId); - return d.isEmpty() ? null : d.get(0); - } - - public int readSeatsAvailable(int sessionId) { - return jdbcTemplate.queryForObject( - "SELECT SeatsAvailable FROM dbo.ExamSession WHERE SessionId = ?", Integer.class, sessionId); - } - - public void decrementSeatsAvailable(int sessionId) { - jdbcTemplate.update("UPDATE dbo.ExamSession SET SeatsAvailable = SeatsAvailable - 1, LastModified = GETDATE() " - + "WHERE SessionId = ?", sessionId); - } private static final RowMapper SESSION_MAPPER = new RowMapper() { public SessionInfo mapRow(ResultSet rs, int rowNum) throws SQLException { diff --git a/services/booking-api/src/main/java/com/northwind/assessment/booking/model/BookingRequest.java b/services/booking-api/src/main/java/com/northwind/assessment/booking/model/BookingRequest.java deleted file mode 100644 index e1e9eac7..00000000 --- a/services/booking-api/src/main/java/com/northwind/assessment/booking/model/BookingRequest.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.northwind.assessment.booking.model; - -/** - * POST /api/v1/bookings body. - */ -public class BookingRequest { - - private Integer sessionId; - private String candidateNumber; - private String accommodationCode; - private String externalRef; - - public Integer getSessionId() { - return sessionId; - } - - public void setSessionId(Integer sessionId) { - this.sessionId = sessionId; - } - - public String getCandidateNumber() { - return candidateNumber; - } - - public void setCandidateNumber(String candidateNumber) { - this.candidateNumber = candidateNumber; - } - - public String getAccommodationCode() { - return accommodationCode; - } - - public void setAccommodationCode(String accommodationCode) { - this.accommodationCode = accommodationCode; - } - - public String getExternalRef() { - return externalRef; - } - - public void setExternalRef(String externalRef) { - this.externalRef = externalRef; - } -} diff --git a/services/booking-api/src/main/java/com/northwind/assessment/booking/model/BookingResponse.java b/services/booking-api/src/main/java/com/northwind/assessment/booking/model/BookingResponse.java deleted file mode 100644 index 3dd66025..00000000 --- a/services/booking-api/src/main/java/com/northwind/assessment/booking/model/BookingResponse.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.northwind.assessment.booking.model; - -public class BookingResponse { - - private int bookingId; - private String status; - - public BookingResponse() { - } - - public BookingResponse(int bookingId, String status) { - this.bookingId = bookingId; - this.status = status; - } - - public int getBookingId() { - return bookingId; - } - - public void setBookingId(int bookingId) { - this.bookingId = bookingId; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } -} diff --git a/services/booking-api/src/main/java/com/northwind/assessment/booking/model/RescheduleRequest.java b/services/booking-api/src/main/java/com/northwind/assessment/booking/model/RescheduleRequest.java deleted file mode 100644 index e26adbec..00000000 --- a/services/booking-api/src/main/java/com/northwind/assessment/booking/model/RescheduleRequest.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.northwind.assessment.booking.model; - -public class RescheduleRequest { - - private Integer newSessionId; - - public Integer getNewSessionId() { - return newSessionId; - } - - public void setNewSessionId(Integer newSessionId) { - this.newSessionId = newSessionId; - } -} diff --git a/services/booking-api/src/main/java/com/northwind/assessment/booking/service/BookingService.java b/services/booking-api/src/main/java/com/northwind/assessment/booking/service/BookingService.java deleted file mode 100644 index 0974018f..00000000 --- a/services/booking-api/src/main/java/com/northwind/assessment/booking/service/BookingService.java +++ /dev/null @@ -1,178 +0,0 @@ -package com.northwind.assessment.booking.service; - -import java.util.Arrays; -import java.util.Date; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.dao.DataAccessException; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import com.northwind.assessment.booking.dao.BookingDao; -import com.northwind.assessment.booking.dao.CandidateDao; -import com.northwind.assessment.booking.dao.SessionDao; -import com.northwind.assessment.booking.model.BookingInfo; -import com.northwind.assessment.booking.model.BookingRequest; -import com.northwind.assessment.booking.model.BookingResponse; -import com.northwind.assessment.booking.model.Candidate; -import com.northwind.assessment.booking.model.EligibilityResult; -import com.northwind.assessment.booking.model.SessionInfo; -import com.northwind.assessment.booking.web.ApiException; - -/** - * Partner bookings. Mirrors the checks in usp_BookSeat (portal) so both channels - * reject the same requests. - */ -@Service -public class BookingService { - - private static final Logger log = LoggerFactory.getLogger(BookingService.class); - - static final List ACCOMMODATION_CODES = Arrays.asList("ET25", "ET50", "SR", "RB"); - static final List EXTRA_TIME_CODES = Arrays.asList("ET25", "ET50"); - - @Autowired - private BookingDao bookingDao; - - @Autowired - private SessionDao sessionDao; - - @Autowired - private CandidateDao candidateDao; - - @Autowired - private RetakeEligibilityService retakeEligibilityService; - - @Value("${booking.channel:PARTNER}") - private String channel; - - @Value("${booking.audit-actor:booking-api}") - private String auditActor; - - @Transactional - public BookingResponse book(BookingRequest req) { - if (req == null || req.getSessionId() == null || StringUtils.isBlank(req.getCandidateNumber())) { - throw ApiException.badRequest("VALIDATION", "sessionId and candidateNumber are required"); - } - String acc = StringUtils.trimToNull(req.getAccommodationCode()); - if (acc != null) { - acc = acc.toUpperCase(); - if (!ACCOMMODATION_CODES.contains(acc)) { - throw ApiException.badRequest("VALIDATION", "Unknown accommodationCode " + acc); - } - } - if (req.getExternalRef() != null && req.getExternalRef().length() > 40) { - throw ApiException.badRequest("VALIDATION", "externalRef is limited to 40 characters"); - } - - Candidate cand = candidateDao.findByNumber(req.getCandidateNumber().trim()); - if (cand == null) { - throw ApiException.notFound("CANDIDATE_NOT_FOUND", "Candidate " + req.getCandidateNumber() + " not found"); - } - int sessionId = req.getSessionId().intValue(); - SessionInfo session = sessionDao.findById(sessionId); - if (session == null) { - throw ApiException.notFound("SESSION_NOT_FOUND", "Session " + sessionId + " not found"); - } - if (!"OPEN".equals(session.getStatus())) { - throw ApiException.conflict("SESSION_NOT_OPEN", "Session " + sessionId + " is not open for booking"); - } - if (bookingDao.hasActiveBooking(sessionId, cand.getCandidateId())) { - throw ApiException.conflict("DUPLICATE_BOOKING", - "Candidate " + cand.getCandidateNumber() + " already has an active booking on session " + sessionId); - } - if (acc != null && EXTRA_TIME_CODES.contains(acc)) { - int used = bookingDao.countAccommodationSeatsUsed(sessionId); - if (used >= session.getAccommodationCapacity()) { - throw ApiException.conflict("NO_ACCOMMODATION_SEAT", - "No accommodation seat available on session " + sessionId); - } - } - - // retake rules are checked against the date the candidate would sit the exam - Integer examId = sessionDao.findExamId(sessionId); - Date sitting = sessionDao.findStartsAt(sessionId); - EligibilityResult elig = retakeEligibilityService.check(cand.getCandidateId(), examId.intValue(), sitting); - if (!elig.isEligible()) { - String msg = "Candidate " + cand.getCandidateNumber() + " is not eligible to book " + session.getExamCode() - + " (" + elig.getReason() + ")"; - if (elig.getEarliestRetakeDate() != null) { - msg += ", earliest retake date " + elig.getEarliestRetakeDate(); - } - throw ApiException.conflict("NOT_ELIGIBLE", msg); - } - - int seats = sessionDao.readSeatsAvailable(sessionId); - int bookingId; - String status; - if (seats > 0) { - bookingId = bookingDao.insertBooking(sessionId, cand.getCandidateId(), "BOOKED", acc, channel, - req.getExternalRef()); - sessionDao.decrementSeatsAvailable(sessionId); - status = "BOOKED"; - } else { - bookingId = bookingDao.insertBooking(sessionId, cand.getCandidateId(), "WAITLISTED", acc, channel, - req.getExternalRef()); - bookingDao.insertWaitlist(sessionId, cand.getCandidateId(), bookingId); - status = "WAITLISTED"; - } - bookingDao.audit("Booking", bookingId, "BOOK", - "session=" + sessionId + " status=" + status + " channel=" + channel - + (req.getExternalRef() != null ? " ref=" + req.getExternalRef() : ""), auditActor); - log.info("Partner booking {} for {} on session {} -> {}", bookingId, cand.getCandidateNumber(), sessionId, status); - return new BookingResponse(bookingId, status); - } - - @Transactional - public void cancel(int bookingId, String reason) { - BookingInfo b = bookingDao.findById(bookingId); - if (b == null) { - throw ApiException.notFound("BOOKING_NOT_FOUND", "Booking " + bookingId + " not found"); - } - if (!"BOOKED".equals(b.getStatus()) && !"WAITLISTED".equals(b.getStatus())) { - throw ApiException.conflict("NOT_CANCELLABLE", "Booking " + bookingId + " is " + b.getStatus()); - } - try { - bookingDao.cancel(bookingId, StringUtils.defaultIfBlank(reason, "Cancelled by partner"), auditActor); - } catch (DataAccessException e) { - throw ApiException.conflict("NOT_CANCELLABLE", e.getMostSpecificCause().getMessage()); - } - } - - /** Cancel through the proc, then book the new session through the normal partner path. */ - @Transactional - public BookingResponse reschedule(int bookingId, Integer newSessionId) { - if (newSessionId == null) { - throw ApiException.badRequest("VALIDATION", "newSessionId is required"); - } - BookingInfo old = bookingDao.findById(bookingId); - if (old == null) { - throw ApiException.notFound("BOOKING_NOT_FOUND", "Booking " + bookingId + " not found"); - } - Integer oldExam = sessionDao.findExamId(old.getSessionId()); - Integer newExam = sessionDao.findExamId(newSessionId.intValue()); - if (newExam == null) { - throw ApiException.notFound("SESSION_NOT_FOUND", "Session " + newSessionId + " not found"); - } - if (!newExam.equals(oldExam)) { - throw ApiException.conflict("DIFFERENT_EXAM", "Booking " + bookingId + " cannot be moved to session " - + newSessionId + " (different exam)"); - } - if (newSessionId.intValue() == old.getSessionId()) { - throw ApiException.conflict("SAME_SESSION", "Booking " + bookingId + " is already on session " + newSessionId); - } - cancel(bookingId, "Rescheduled"); - - BookingRequest req = new BookingRequest(); - req.setSessionId(newSessionId); - req.setCandidateNumber(old.getCandidateNumber()); - req.setAccommodationCode(old.getAccommodationCode()); - req.setExternalRef(old.getExternalRef()); - return book(req); - } -} diff --git a/services/booking-api/src/main/java/com/northwind/assessment/booking/web/BookingController.java b/services/booking-api/src/main/java/com/northwind/assessment/booking/web/BookingController.java index b7b59bb7..eb5b2ba7 100644 --- a/services/booking-api/src/main/java/com/northwind/assessment/booking/web/BookingController.java +++ b/services/booking-api/src/main/java/com/northwind/assessment/booking/web/BookingController.java @@ -2,34 +2,31 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.northwind.assessment.booking.dao.BookingDao; import com.northwind.assessment.booking.model.BookingInfo; -import com.northwind.assessment.booking.model.BookingRequest; -import com.northwind.assessment.booking.model.BookingResponse; -import com.northwind.assessment.booking.model.RescheduleRequest; -import com.northwind.assessment.booking.service.BookingService; +/** + * Partner booking reads. MBA-3824 retired the write SQL: book, cancel and reschedule are served by + * scheduling-service through the routing gateway (:8000), which answers /api/v1/bookings writes itself + * (docs/adr/0004-retire-portal-booking-slice.md). A write that reaches :8081 directly gets 410. + */ @RestController @RequestMapping("/api/v1/bookings") public class BookingController { - @Autowired - private BookingService bookingService; + static final String LEGACY_WRITE_RETIRED = "LEGACY_WRITE_RETIRED"; @Autowired private BookingDao bookingDao; @RequestMapping(method = RequestMethod.POST) - public ResponseEntity book(@RequestBody BookingRequest req) { - return new ResponseEntity(bookingService.book(req), HttpStatus.CREATED); + public void book() { + throw retired(); } @RequestMapping(value = "/{bookingId}", method = RequestMethod.GET) @@ -42,15 +39,17 @@ public BookingInfo get(@PathVariable("bookingId") int bookingId) { } @RequestMapping(value = "/{bookingId}", method = RequestMethod.DELETE) - public BookingInfo cancel(@PathVariable("bookingId") int bookingId, - @RequestParam(value = "reason", required = false) String reason) { - bookingService.cancel(bookingId, reason); - return bookingDao.findById(bookingId); + public void cancel(@PathVariable("bookingId") int bookingId) { + throw retired(); } @RequestMapping(value = "/{bookingId}/reschedule", method = RequestMethod.POST) - public BookingResponse reschedule(@PathVariable("bookingId") int bookingId, - @RequestBody RescheduleRequest req) { - return bookingService.reschedule(bookingId, req == null ? null : req.getNewSessionId()); + public void reschedule(@PathVariable("bookingId") int bookingId) { + throw retired(); + } + + static ApiException retired() { + return new ApiException(HttpStatus.GONE, LEGACY_WRITE_RETIRED, "booking-api no longer writes bookings; " + + "send book/cancel/reschedule through the routing gateway (:8000) to scheduling-service"); } } diff --git a/services/booking-api/src/main/resources/application.properties b/services/booking-api/src/main/resources/application.properties index faa6f708..ac0053c7 100644 --- a/services/booking-api/src/main/resources/application.properties +++ b/services/booking-api/src/main/resources/application.properties @@ -12,8 +12,5 @@ spring.datasource.tomcat.validation-query=SELECT 1 spring.jackson.serialization.write-dates-as-timestamps=false spring.jackson.serialization.indent-output=true -# partner channel identity written to Booking.Channel / AuditLog.Actor -booking.channel=PARTNER -booking.audit-actor=booking-api logging.level.com.northwind=INFO diff --git a/services/booking-api/src/test/java/com/northwind/assessment/booking/web/BookingControllerTest.java b/services/booking-api/src/test/java/com/northwind/assessment/booking/web/BookingControllerTest.java new file mode 100644 index 00000000..2e63f653 --- /dev/null +++ b/services/booking-api/src/test/java/com/northwind/assessment/booking/web/BookingControllerTest.java @@ -0,0 +1,43 @@ +package com.northwind.assessment.booking.web; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.springframework.http.HttpStatus; + +/** MBA-3824: booking-api no longer writes; direct writes on :8081 are answered 410 LEGACY_WRITE_RETIRED. */ +public class BookingControllerTest { + + private final BookingController controller = new BookingController(); + + @Test + public void bookIsRetired() { + assertRetired(new Runnable() { public void run() { controller.book(); } }); + } + + @Test + public void cancelIsRetired() { + assertRetired(new Runnable() { public void run() { controller.cancel(42); } }); + } + + @Test + public void rescheduleIsRetired() { + assertRetired(new Runnable() { public void run() { controller.reschedule(42); } }); + } + + @Test + public void retiredWriteRendersAs410() { + assertEquals(HttpStatus.GONE, new ApiExceptionHandler().handleApi(BookingController.retired()).getStatusCode()); + } + + private static void assertRetired(Runnable call) { + try { + call.run(); + fail("expected ApiException"); + } catch (ApiException e) { + assertEquals(HttpStatus.GONE, e.getStatus()); + assertEquals("LEGACY_WRITE_RETIRED", e.getError()); + } + } +} diff --git a/services/routing-gateway/README.md b/services/routing-gateway/README.md index c5c97a23..fe50799b 100644 --- a/services/routing-gateway/README.md +++ b/services/routing-gateway/README.md @@ -48,15 +48,20 @@ unless `routing.coexistence-mode=relay` is set; M4 sets it once the relay is liv ## What is routed where +**Retired portal pages (MBA-3824, M5).** The portal no longer has booking or capacity pages, so the seven portal rows +below redirect for **every** centre, whatever the allow-list says, and also without a centre key or when the key does +not resolve (`/app/`, or `/app/my-bookings?candidateNumber=` for `/Booking/MyBookings?candidateNumber=`). The +allow-list still applies to the API rows. See [ADR 0004](../../docs/adr/0004-retire-portal-booking-slice.md). + | Request | Centre from | Allow-listed centre | Otherwise | |---|---|---|---| -| `GET /Booking?CenterCode=` | CenterCode | 302 `/app/?center=..&exam=..&from=..&to=` | portal | -| `GET /Booking/Book?sessionId=`, `POST /Booking/Book` (form `SessionId`) | sessionId | 302/303 `/app/book?sessionId=` | portal | -| `/Booking/Reschedule/{id}` | bookingId | `/app/reschedule/{id}` | portal | -| `/Booking/Cancel/{id}` | bookingId | `/app/my-bookings` | portal | -| `GET /Booking/MyBookings?centerCode=` | centerCode | `/app/my-bookings` | portal | -| `GET /Admin/Sessions?centerId=` | centerId | `/app/admin/centers/{centerCode}` | portal | -| `/Admin/Sessions/Capacity/{id}` | sessionId | `/app/admin/sessions/{id}` | portal | +| `GET /Booking?CenterCode=` | CenterCode | 302 `/app/?center=..&exam=..&from=..&to=` | same (M5) | +| `GET /Booking/Book?sessionId=`, `POST /Booking/Book` (form `SessionId`) | sessionId | 302/303 `/app/book?sessionId=` | same (M5) | +| `/Booking/Reschedule/{id}` | bookingId | `/app/reschedule/{id}` | same (M5) | +| `/Booking/Cancel/{id}` | bookingId | `/app/my-bookings` | same (M5) | +| `GET /Booking/MyBookings[?candidateNumber=]` | - | `/app/my-bookings[?candidateNumber=]` | same (M5) | +| `GET /Admin/Sessions?centerId=` | centerId | `/app/admin/centers/{centerCode}` | same (M5) | +| `/Admin/Sessions/Capacity/{id}` | sessionId | `/app/admin/sessions/{id}` | same (M5) | | `GET /api/v1/sessions?centerCode=` | centerCode | `/api/v2/centers/{c}/sessions` in v1 shape | booking-api | | `GET /api/v1/sessions/{id}` | sessionId | `/api/v2/sessions/{id}` in v1 shape | booking-api | | `POST /api/v1/bookings` | body `sessionId` | `POST /api/v2/bookings` (channel PARTNER), v1 `{bookingId,status}` 201 | booking-api | @@ -64,8 +69,7 @@ unless `routing.coexistence-mode=relay` is set; M4 sets it once the relay is liv | `/app/**`, `/api/v2/**` | - | scheduling-service | scheduling-service | | `/api/v1/results/**`, `/sync/**`, every other portal page | - | results-service / capacity-sync / portal | same | -Requests without a centre key (e.g. `/Booking/MyBookings?candidateNumber=`, `/api/v1/sessions` without -`centerCode`) stay on legacy. Portal pages without a modern equivalent (`/Admin/Centers`, `/Eligibility`, +API requests without a centre key (e.g. `/api/v1/sessions` without `centerCode`) stay on legacy. Portal pages without a modern equivalent (`/Admin/Centers`, `/Eligibility`, `/Results`, roster CSV, capacity audit) always stay on legacy. The centre is resolved through scheduling-service `GET /api/v2/internal/routing/resolve?centerCode=|centerId=|sessionId=|bookingId=` diff --git a/services/routing-gateway/src/main/java/com/northwind/routing/route/PortalRoutes.java b/services/routing-gateway/src/main/java/com/northwind/routing/route/PortalRoutes.java index 247535a4..ccc332ce 100644 --- a/services/routing-gateway/src/main/java/com/northwind/routing/route/PortalRoutes.java +++ b/services/routing-gateway/src/main/java/com/northwind/routing/route/PortalRoutes.java @@ -8,10 +8,12 @@ import org.springframework.web.util.UriComponentsBuilder; /** - * The legacy MVC 5 booking/admin pages that the strangler can move (routes from - * AssessmentDelivery.Web/App_Start/RouteConfig.cs, flows in docs/SYSTEM_OVERVIEW.md) and their modern UI deep - * links under {@code /app} (services/scheduling-service/frontend/src/App.tsx). MVC routing and model binding - * are case-insensitive, so paths and parameter names are matched case-insensitively here too. + * The legacy MVC 5 booking/admin pages (routes from AssessmentDelivery.Web/App_Start/RouteConfig.cs at + * {@code legacy-baseline}, flows in docs/SYSTEM_OVERVIEW.md) and their modern UI deep links under {@code /app} + * (services/scheduling-service/frontend/src/App.tsx). Since MBA-3824 (M5) the portal no longer serves these pages, + * so every match is redirected whatever the centre, and a missing centre key still matches (see + * docs/adr/0004-retire-portal-booking-slice.md). MVC routing and model binding are case-insensitive, so paths and + * parameter names are matched case-insensitively here too. */ public final class PortalRoutes { @@ -40,20 +42,20 @@ public static Optional match(String method, String rawPath, MultiValueMap String action = seg.length >= 2 ? seg[1] : "index"; String id = seg.length == 3 ? seg[2] : null; if (seg.length <= 2 && action.equals("index") && get) { - return withKey(Page.FIND, Kind.CENTER_CODE, param(query, "CenterCode"), null); + return retired(Page.FIND, Kind.CENTER_CODE, param(query, "CenterCode"), null); } if (seg.length == 2 && action.equals("book")) { - return get ? withKey(Page.BOOK, Kind.SESSION_ID, param(query, "sessionId"), null) + return get ? retired(Page.BOOK, Kind.SESSION_ID, param(query, "sessionId"), null) : Optional.of(new Match(Page.BOOK, Lookup.of(Kind.SESSION_ID, null), null, true)); } if (seg.length == 2 && action.equals("mybookings") && get) { - return withKey(Page.MY_BOOKINGS, Kind.CENTER_CODE, param(query, "centerCode"), null); + return retired(Page.MY_BOOKINGS, Kind.CENTER_CODE, param(query, "centerCode"), null); } if (id != null && isId(id) && action.equals("cancel")) { - return withKey(Page.CANCEL, Kind.BOOKING_ID, id, id); + return retired(Page.CANCEL, Kind.BOOKING_ID, id, id); } if (id != null && isId(id) && action.equals("reschedule")) { - return withKey(Page.RESCHEDULE, Kind.BOOKING_ID, id, id); + return retired(Page.RESCHEDULE, Kind.BOOKING_ID, id, id); } return Optional.empty(); } @@ -66,20 +68,37 @@ public static Optional match(String method, String rawPath, MultiValueMap return Optional.empty(); } - /** Modern UI location (proxied by this gateway) for an allow-listed match. */ + /** Modern UI location (proxied by this gateway); {@code center} is the resolved centre code or null. */ public static String redirect(Match m, String center, MultiValueMap query) { UriComponentsBuilder b = UriComponentsBuilder.newInstance(); switch (m.page()) { case FIND -> { - b.path("/app/").queryParam("center", center); + b.path("/app/"); + addIfPresent(b, "center", center); addIfPresent(b, "exam", param(query, "ExamCode")); addIfPresent(b, "from", param(query, "From")); addIfPresent(b, "to", param(query, "To")); } - case BOOK -> b.path("/app/book").queryParam("sessionId", m.lookup().value()); - case CANCEL, MY_BOOKINGS -> b.path("/app/my-bookings"); + case BOOK -> { + if (m.lookup().present()) { + b.path("/app/book").queryParam("sessionId", m.lookup().value()); + } else { + b.path("/app/"); + } + } + case CANCEL -> b.path("/app/my-bookings"); + case MY_BOOKINGS -> { + b.path("/app/my-bookings"); + addIfPresent(b, "candidateNumber", param(query, "candidateNumber")); + } case RESCHEDULE -> b.path("/app/reschedule/").path(m.id()); - case ADMIN_SESSIONS -> b.path("/app/admin/centers/").path(center); + case ADMIN_SESSIONS -> { + if (center != null && !center.isBlank()) { + b.path("/app/admin/centers/").path(center); + } else { + b.path("/app/"); + } + } case ADMIN_CAPACITY -> b.path("/app/admin/sessions/").path(m.id()); default -> throw new IllegalArgumentException(m.page().name()); } @@ -115,6 +134,10 @@ static boolean isId(String s) { return !s.isEmpty() && s.length() <= 10 && s.chars().allMatch(Character::isDigit); } + private static Optional retired(Page page, Kind kind, String value, String id) { + return Optional.of(new Match(page, Lookup.of(kind, value), id, false)); + } + private static Optional withKey(Page page, Kind kind, String value, String id) { if (value == null || value.isBlank()) { return Optional.empty(); diff --git a/services/routing-gateway/src/main/java/com/northwind/routing/web/StranglerFilter.java b/services/routing-gateway/src/main/java/com/northwind/routing/web/StranglerFilter.java index 3747dd34..abffae5c 100644 --- a/services/routing-gateway/src/main/java/com/northwind/routing/web/StranglerFilter.java +++ b/services/routing-gateway/src/main/java/com/northwind/routing/web/StranglerFilter.java @@ -39,13 +39,15 @@ * migration can move, decides legacy vs modern ({@link RouteDecider}), then either forwards to the legacy * upstream unchanged, redirects a portal page to the modern UI ({@link PortalRoutes}), or serves a v1 partner * call from scheduling-service in the v1 shape ({@link ModernV1Client}). With an empty allow-list no lookups are - * made and no bodies are read, so the gateway is a transparent proxy. Every request is logged + * made and no bodies are read, so the gateway is a transparent proxy. The retired portal booking pages are the + * exception (MBA-3824): they always redirect to {@code /app}, for every centre. Every request is logged * {@code route=legacy|modern center=} and answered with an {@code X-Route} header. */ @Component public class StranglerFilter implements GlobalFilter, Ordered { static final String CENTER_IS_MODERN = "CENTER_IS_MODERN"; + static final String RETIRED = "legacy page retired"; public static final String X_ROUTE = "X-Route"; private static final Logger log = LoggerFactory.getLogger(StranglerFilter.class); @@ -94,19 +96,25 @@ private Mono portal(ServerWebExchange ex, GatewayFilterChain chain) { } PortalRoutes.Match m = found.get(); if (!m.needsForm()) { - return decide(m.lookup()).flatMap(d -> d.modern() - ? redirect(ex, PortalRoutes.redirect(m, d.center(), req.getQueryParams()), d) - : forward(ex, chain, d)); + return retired(ex, m); } - if (allowList.isEmpty()) { - return forward(ex, chain, RouteDecision.legacy(null, "allow-list empty")); - } - return BodyCache.cache(ex).flatMap(cached -> { - PortalRoutes.Match withKey = m.withLookup(Lookup.of(Lookup.Kind.SESSION_ID, - BodyCache.formField(BodyCache.bytes(cached), "SessionId"))); - return decide(withKey.lookup()).flatMap(d -> d.modern() - ? redirect(cached, PortalRoutes.redirect(withKey, d.center(), req.getQueryParams()), d) - : forward(cached, chain, d)); + return BodyCache.cache(ex).flatMap(cached -> retired(cached, m.withLookup(Lookup.of(Lookup.Kind.SESSION_ID, + BodyCache.formField(BodyCache.bytes(cached), "SessionId"))))); + } + + /** + * MBA-3824: the portal no longer has these pages, so they redirect to the modern UI for every centre, allow-listed + * or not. Only {@code /Admin/Sessions?centerId=} needs a lookup (centre id to code for the deep link). + */ + private Mono retired(ServerWebExchange ex, PortalRoutes.Match m) { + Mono> center = switch (m.page()) { + case FIND -> Mono.just(Optional.ofNullable(m.lookup().value()).map(c -> c.trim().toUpperCase(Locale.ROOT))); + case ADMIN_SESSIONS -> resolver.resolve(m.lookup()).onErrorReturn(Optional.empty()); + default -> Mono.just(Optional.empty()); + }; + return center.flatMap(c -> { + RouteDecision d = RouteDecision.modern(c.orElse(null), RETIRED); + return redirect(ex, PortalRoutes.redirect(m, c.orElse(null), ex.getRequest().getQueryParams()), d); }); } diff --git a/services/routing-gateway/src/test/java/com/northwind/routing/GatewayIntegrationTest.java b/services/routing-gateway/src/test/java/com/northwind/routing/GatewayIntegrationTest.java index b092422d..c86f2b26 100644 --- a/services/routing-gateway/src/test/java/com/northwind/routing/GatewayIntegrationTest.java +++ b/services/routing-gateway/src/test/java/com/northwind/routing/GatewayIntegrationTest.java @@ -109,7 +109,44 @@ void nonBookingTrafficIsProxiedToLegacyUnchanged() { web.get().uri("/Results?candidateNumber=NW00000001").exchange() .expectStatus().isOk().expectHeader().valueEquals("X-Route", "legacy") .expectBody(String.class).isEqualTo("

legacy /Results?candidateNumber=NW00000001

"); - web.get().uri("/Booking?CenterCode=CHI01").exchange() + web.get().uri("/Admin/Centers").exchange() + .expectStatus().isOk().expectHeader().valueEquals("X-Route", "legacy"); + web.get().uri("/Eligibility?candidateNumber=NW00000001&examCode=AZ-104").exchange() + .expectStatus().isOk().expectHeader().valueEquals("X-Route", "legacy"); + } + + /** MBA-3824: the portal pages are gone, so their URLs redirect for every centre, not only allow-listed ones. */ + @Test + void retiredPortalPagesRedirectForEveryCentre() { + writeConfig(""); + web.post().uri("/actuator/refresh").exchange().expectStatus().isOk(); + int portalCalls = PORTAL.calls("GET", "/Booking").size(); + web.get().uri("/Booking?CenterCode=chi01&ExamCode=AZ-104").exchange() + .expectStatus().isFound().expectHeader().valueEquals("X-Route", "modern") + .expectHeader().valueEquals("Location", "/app/?center=CHI01&exam=AZ-104"); + web.get().uri("/Booking").exchange().expectStatus().isFound().expectHeader().valueEquals("Location", "/app/"); + web.get().uri("/Booking/Book?sessionId=200").exchange() + .expectStatus().isFound().expectHeader().valueEquals("Location", "/app/book?sessionId=200"); + web.post().uri("/Booking/Book").contentType(MediaType.APPLICATION_FORM_URLENCODED) + .bodyValue("SessionId=200&CandidateNumber=NW00000901").exchange() + .expectStatus().isSeeOther().expectHeader().valueEquals("Location", "/app/book?sessionId=200"); + web.get().uri("/Booking/MyBookings?candidateNumber=NW00000042").exchange() + .expectStatus().isFound().expectHeader().valueEquals("Location", "/app/my-bookings?candidateNumber=NW00000042"); + web.get().uri("/Booking/Cancel/1200").exchange() + .expectStatus().isFound().expectHeader().valueEquals("Location", "/app/my-bookings"); + web.post().uri("/Booking/Cancel/1200").contentType(MediaType.APPLICATION_FORM_URLENCODED).bodyValue("x=1").exchange() + .expectStatus().isSeeOther().expectHeader().valueEquals("Location", "/app/my-bookings"); + web.get().uri("/Booking/Reschedule/1200").exchange() + .expectStatus().isFound().expectHeader().valueEquals("Location", "/app/reschedule/1200"); + web.get().uri("/Admin/Sessions?centerId=1").exchange() + .expectStatus().isFound().expectHeader().valueEquals("Location", "/app/admin/centers/BOS01"); + web.get().uri("/Admin/Sessions?centerId=99").exchange() + .expectStatus().isFound().expectHeader().valueEquals("Location", "/app/"); + web.get().uri("/Admin/Sessions/Capacity/200").exchange() + .expectStatus().isFound().expectHeader().valueEquals("Location", "/app/admin/sessions/200"); + assertThat(PORTAL.calls("GET", "/Booking")).hasSize(portalCalls); + assertThat(PORTAL.calls("POST", "/Booking/Book")).isEmpty(); + web.get().uri("/Results?candidateNumber=NW00000042").exchange() .expectStatus().isOk().expectHeader().valueEquals("X-Route", "legacy"); } @@ -143,11 +180,6 @@ void portalPagesForAllowListedCentreRedirectToModernUi() { web.post().uri("/Booking/Book").contentType(MediaType.APPLICATION_FORM_URLENCODED) .bodyValue("__RequestVerificationToken=t&SessionId=154&CandidateNumber=NW00000901").exchange() .expectStatus().isSeeOther().expectHeader().valueEquals("Location", "/app/book?sessionId=154"); - web.post().uri("/Booking/Book").contentType(MediaType.APPLICATION_FORM_URLENCODED) - .bodyValue("SessionId=200&CandidateNumber=NW00000901").exchange() - .expectStatus().isOk().expectHeader().valueEquals("X-Route", "legacy"); - assertThat(PORTAL.calls("POST", "/Booking/Book").get(PORTAL.calls("POST", "/Booking/Book").size() - 1).body()) - .isEqualTo("SessionId=200&CandidateNumber=NW00000901"); web.get().uri("/Admin/Sessions?centerId=1").exchange() .expectStatus().isFound().expectHeader().valueEquals("Location", "/app/admin/centers/BOS01"); web.get().uri("/Admin/Sessions/Capacity/154").exchange() @@ -171,7 +203,7 @@ void rollbackByEditingTheFileRoutesToLegacyWithinFiveSecondsAndModernBookingsSta long deadline = System.currentTimeMillis() + 5000; String route = "modern"; while (System.currentTimeMillis() < deadline) { - route = web.get().uri("/Booking?CenterCode=BOS01").exchange().returnResult(String.class) + route = web.get().uri("/api/v1/sessions?centerCode=BOS01").exchange().returnResult(String.class) .getResponseHeaders().getFirst("X-Route"); if ("legacy".equals(route)) { break; @@ -190,10 +222,10 @@ void rollbackByEditingTheFileRoutesToLegacyWithinFiveSecondsAndModernBookingsSta void refreshEndpointReloadsAndInvalidListIsRejected() { writeConfig("SEA01"); web.post().uri("/actuator/refresh").exchange().expectStatus().isOk(); - web.get().uri("/Booking?CenterCode=BOS01").exchange().expectHeader().valueEquals("X-Route", "legacy"); + web.get().uri("/api/v1/sessions?centerCode=BOS01").exchange().expectHeader().valueEquals("X-Route", "legacy"); writeConfig("BOS01,LON01"); web.post().uri("/actuator/refresh").exchange().expectStatus().isOk(); - web.get().uri("/Booking?CenterCode=SEA01").exchange().expectStatus().isFound(); + web.get().uri("/api/v1/sessions?centerCode=SEA01").exchange().expectHeader().valueEquals("X-Route", "modern"); } @Test @@ -245,7 +277,7 @@ void reschedulesNeverMoveABookingOntoASeatTheOtherSideOwns() { .expectBody().jsonPath("$.error").isEqualTo("CENTER_IS_MODERN"); writeConfig(""); long deadline = System.currentTimeMillis() + 5000; - while (System.currentTimeMillis() < deadline && !"legacy".equals(web.get().uri("/Booking?CenterCode=BOS01") + while (System.currentTimeMillis() < deadline && !"legacy".equals(web.get().uri("/api/v1/sessions?centerCode=BOS01") .exchange().returnResult(String.class).getResponseHeaders().getFirst("X-Route"))) { Thread.yield(); } diff --git a/services/routing-gateway/src/test/java/com/northwind/routing/RouteDeciderTest.java b/services/routing-gateway/src/test/java/com/northwind/routing/RouteDeciderTest.java index 6a9505ad..74be5e3b 100644 --- a/services/routing-gateway/src/test/java/com/northwind/routing/RouteDeciderTest.java +++ b/services/routing-gateway/src/test/java/com/northwind/routing/RouteDeciderTest.java @@ -59,6 +59,9 @@ void portalRoutesMapToModernUiDeepLinks() { assertThat(PortalRoutes.redirect(resched, "BOS01", q())).isEqualTo("/app/reschedule/42"); var mine = PortalRoutes.match("GET", "/Booking/MyBookings", q("centerCode", "BOS01")).orElseThrow(); assertThat(PortalRoutes.redirect(mine, "BOS01", q())).isEqualTo("/app/my-bookings"); + var bookmark = PortalRoutes.match("GET", "/Booking/MyBookings", q("candidateNumber", "NW00000042")).orElseThrow(); + assertThat(PortalRoutes.redirect(bookmark, null, q("candidateNumber", "NW00000042"))) + .isEqualTo("/app/my-bookings?candidateNumber=NW00000042"); var admin = PortalRoutes.match("GET", "/Admin/Sessions", q("centerId", "1")).orElseThrow(); assertThat(admin.lookup()).isEqualTo(Lookup.of(Lookup.Kind.CENTER_ID, "1")); assertThat(PortalRoutes.redirect(admin, "BOS01", q())).isEqualTo("/app/admin/centers/BOS01"); @@ -67,9 +70,11 @@ void portalRoutesMapToModernUiDeepLinks() { } @Test - void routesWithoutACentreKeyAndNonBookingPagesStayLegacy() { - assertThat(PortalRoutes.match("GET", "/Booking", q())).isEmpty(); - assertThat(PortalRoutes.match("GET", "/Booking/MyBookings", q("candidateNumber", "NW00000001"))).isEmpty(); + void retiredPagesMatchWithoutACentreKeyAndNonBookingPagesStayLegacy() { + assertThat(PortalRoutes.redirect(PortalRoutes.match("GET", "/Booking", q()).orElseThrow(), null, q())).isEqualTo("/app/"); + assertThat(PortalRoutes.redirect(PortalRoutes.match("GET", "/Booking/Book", q()).orElseThrow(), null, q())).isEqualTo("/app/"); + assertThat(PortalRoutes.redirect(PortalRoutes.match("GET", "/Admin/Sessions", q("centerId", "99")).orElseThrow(), null, q())) + .isEqualTo("/app/"); assertThat(PortalRoutes.match("GET", "/Admin/Sessions", q())).isEmpty(); assertThat(PortalRoutes.match("GET", "/Admin/Centers", q())).isEmpty(); assertThat(PortalRoutes.match("GET", "/Admin/Sessions/Roster/154", q("format", "csv"))).isEmpty(); diff --git a/services/scheduling-service/frontend/src/candidate.ts b/services/scheduling-service/frontend/src/candidate.ts index 37d39603..c94c5502 100644 --- a/services/scheduling-service/frontend/src/candidate.ts +++ b/services/scheduling-service/frontend/src/candidate.ts @@ -2,9 +2,15 @@ import { useCallback, useState } from 'react'; const KEY = 'scheduling.candidateNumber'; -/** The signed-in candidate is just a remembered candidate number (no auth in this story). */ -export function useCandidateNumber(): [string, (v: string) => void] { - const [value, setValue] = useState(() => localStorage.getItem(KEY) ?? ''); +/** + * The signed-in candidate is just a remembered candidate number (no auth in this story). + * `initial` (e.g. from a deep link) wins over the remembered number and is remembered in its place. + */ +export function useCandidateNumber(initial?: string): [string, (v: string) => void] { + const [value, setValue] = useState(() => { + if (initial) localStorage.setItem(KEY, initial); + return initial || (localStorage.getItem(KEY) ?? ''); + }); const set = useCallback((v: string) => { // persist synchronously: callers often navigate away in the same tick if (v) localStorage.setItem(KEY, v); diff --git a/services/scheduling-service/frontend/src/pages/MyBookings.tsx b/services/scheduling-service/frontend/src/pages/MyBookings.tsx index e8ad4961..070a1122 100644 --- a/services/scheduling-service/frontend/src/pages/MyBookings.tsx +++ b/services/scheduling-service/frontend/src/pages/MyBookings.tsx @@ -1,5 +1,5 @@ import { useCallback, useEffect, useState, type FormEvent } from 'react'; -import { Link } from 'react-router-dom'; +import { Link, useSearchParams } from 'react-router-dom'; import { ApiError, CANDIDATE_RE, api, fmtDateTime, type Booking } from '../api'; import { Empty, Modal, PageHeader, Spinner, StatusBadge } from '../components/ui'; import { useToast } from '../components/Toast'; @@ -8,7 +8,10 @@ import { useCandidateNumber } from '../candidate'; /** Candidate: list bookings, cancel (with confirmation), reschedule. */ export default function MyBookings() { const toast = useToast(); - const [candidate, setCandidate] = useCandidateNumber(); + const [params] = useSearchParams(); + // legacy /Booking/MyBookings?candidateNumber= bookmarks arrive here via the routing gateway (MBA-3824) + const linked = (params.get('candidateNumber') ?? '').trim().toUpperCase(); + const [candidate, setCandidate] = useCandidateNumber(CANDIDATE_RE.test(linked) ? linked : undefined); const [input, setInput] = useState(candidate); const [error, setError] = useState(''); const [bookings, setBookings] = useState(null); diff --git a/services/scheduling-service/src/test/java/com/northwind/scheduling/relay/LegacySingleWriterIT.java b/services/scheduling-service/src/test/java/com/northwind/scheduling/relay/LegacySingleWriterIT.java index e330ec18..eb97ce47 100644 --- a/services/scheduling-service/src/test/java/com/northwind/scheduling/relay/LegacySingleWriterIT.java +++ b/services/scheduling-service/src/test/java/com/northwind/scheduling/relay/LegacySingleWriterIT.java @@ -31,6 +31,7 @@ class LegacySingleWriterIT { static final String RELAY_PASSWORD = "Sch3dRelay!Dev2026"; static final int PERMISSION_DENIED = 229; static final int COLUMN_PERMISSION_DENIED = 230; + static final int PROC_NOT_FOUND = 2812; @BeforeAll static void build() { @@ -50,7 +51,7 @@ void legacyLoginCannotWriteBookingsWaitlistOrSeats(String login) throws SQLExcep assertDenied(st, "UPDATE dbo.ExamSession SET Capacity = Capacity + 1 WHERE SessionId = 154", login.equals("ad_sched_import") ? PERMISSION_DENIED : COLUMN_PERMISSION_DENIED); for (String proc : new String[] {"usp_BookSeat", "usp_CancelBooking", "usp_ChangeCapacity", "usp_RescheduleBooking"}) { - assertDenied(st, "EXEC dbo." + proc, PERMISSION_DENIED); + assertDenied(st, "EXEC dbo." + proc, PROC_NOT_FOUND); // MBA-3824: dropped by db/procs/090 } // reads keep working (legacy pages render from the legacy tables) try (var rs = st.executeQuery("SELECT COUNT(*) FROM dbo.Booking")) {