blackopsrepl commited on
Commit
50f82a1
·
verified ·
1 Parent(s): 79deb5f

Upload 30 files

Browse files
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use Python 3.12 base image
2
+ FROM python:3.12
3
+
4
+ # Install JDK 21 (required for solverforge-legacy)
5
+ RUN apt-get update && \
6
+ apt-get install -y wget gnupg2 && \
7
+ wget -O- https://packages.adoptium.net/artifactory/api/gpg/key/public | gpg --dearmor > /usr/share/keyrings/adoptium-archive-keyring.gpg && \
8
+ echo "deb [signed-by=/usr/share/keyrings/adoptium-archive-keyring.gpg] https://packages.adoptium.net/artifactory/deb bookworm main" > /etc/apt/sources.list.d/adoptium.list && \
9
+ apt-get update && \
10
+ apt-get install -y temurin-21-jdk && \
11
+ apt-get clean && \
12
+ rm -rf /var/lib/apt/lists/*
13
+
14
+ # Copy application files
15
+ COPY . .
16
+
17
+ # Install the application
18
+ RUN pip install --no-cache-dir -e .
19
+
20
+ # Expose port 8080
21
+ EXPOSE 8080
22
+
23
+ # Run the application
24
+ CMD ["run-app"]
README.md CHANGED
@@ -1,12 +1,86 @@
1
  ---
2
- title: Maintenance Scheduling Python
3
- emoji: 🐨
4
- colorFrom: green
5
- colorTo: pink
6
  sdk: docker
 
7
  pinned: false
8
  license: apache-2.0
9
- short_description: Generate the optimal schedule for your maintenance staff
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Maintenance Scheduling (Python)
3
+ emoji: 🔧
4
+ colorFrom: gray
5
+ colorTo: green
6
  sdk: docker
7
+ app_port: 8080
8
  pinned: false
9
  license: apache-2.0
10
+ short_description: SolverForge Maintenance Scheduling problem
11
  ---
12
 
13
+ # Maintenance Scheduling (Python)
14
+
15
+ Assign maintenance jobs to crews and schedule them over time, avoiding conflicts and meeting deadlines.
16
+
17
+ - [Prerequisites](#prerequisites)
18
+ - [Run the application](#run-the-application)
19
+ - [Test the application](#test-the-application)
20
+
21
+ ## Prerequisites
22
+
23
+ 1. Install [Python 3.10, 3.11 or 3.12](https://www.python.org/downloads/).
24
+
25
+ 2. Install JDK 17+, for example with [Sdkman](https://sdkman.io):
26
+ ```sh
27
+ $ sdk install java
28
+ ```
29
+
30
+ ## Run the application
31
+
32
+ 1. Git clone the solverforge-quickstarts repo and navigate to this directory:
33
+ ```sh
34
+ $ git clone https://github.com/SolverForge/solverforge-quickstarts.git
35
+ ...
36
+ $ cd solverforge-quickstarts/fast/maintenance-scheduling-fast
37
+ ```
38
+
39
+ 2. Create a virtual environment:
40
+ ```sh
41
+ $ python -m venv .venv
42
+ ```
43
+
44
+ 3. Activate the virtual environment:
45
+ ```sh
46
+ $ . .venv/bin/activate
47
+ ```
48
+
49
+ 4. Install the application:
50
+ ```sh
51
+ $ pip install -e .
52
+ ```
53
+
54
+ 5. Run the application:
55
+ ```sh
56
+ $ run-app
57
+ ```
58
+
59
+ 6. Visit [http://localhost:8080](http://localhost:8080) in your browser.
60
+
61
+ 7. Click on the **Solve** button.
62
+
63
+ ## Problem Description
64
+
65
+ The maintenance scheduling problem assigns maintenance jobs to crews over a planning period while respecting constraints:
66
+
67
+ ### Hard Constraints
68
+ - **Crew conflict**: A crew can only work on one job at a time
69
+ - **Min start date**: Jobs cannot start before their ready date
70
+ - **Max end date**: Jobs must complete before their deadline
71
+
72
+ ### Soft Constraints
73
+ - **Before ideal end date**: Slight penalty for finishing too early (maintenance cycles restart sooner)
74
+ - **After ideal end date**: Heavy penalty for finishing late (risk of missing deadline)
75
+ - **Tag conflict**: Avoid scheduling jobs with the same tag (e.g., same area) at overlapping times
76
+
77
+ ## Test the application
78
+
79
+ 1. Run tests:
80
+ ```sh
81
+ $ pytest
82
+ ```
83
+
84
+ ## More information
85
+
86
+ Visit [solverforge.org](https://www.solverforge.org).
logging.conf ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [loggers]
2
+ keys=root,timefold_solver
3
+
4
+ [handlers]
5
+ keys=consoleHandler
6
+
7
+ [formatters]
8
+ keys=simpleFormatter
9
+
10
+ [logger_root]
11
+ level=INFO
12
+ handlers=consoleHandler
13
+
14
+ [logger_timefold_solver]
15
+ level=INFO
16
+ qualname=timefold.solver
17
+ handlers=consoleHandler
18
+ propagate=0
19
+
20
+ [handler_consoleHandler]
21
+ class=StreamHandler
22
+ level=INFO
23
+ formatter=simpleFormatter
24
+ args=(sys.stdout,)
25
+
26
+ [formatter_simpleFormatter]
27
+ class=uvicorn.logging.ColourizedFormatter
28
+ format={levelprefix:<8} @ {name} : {message}
29
+ style={
30
+ use_colors=True
pyproject.toml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+
6
+ [project]
7
+ name = "maintenance_scheduling"
8
+ version = "1.0.0"
9
+ requires-python = ">=3.10"
10
+ dependencies = [
11
+ 'solverforge-legacy == 1.24.1',
12
+ 'fastapi == 0.111.0',
13
+ 'pydantic == 2.7.3',
14
+ 'uvicorn == 0.30.1',
15
+ 'pytest == 8.2.2',
16
+ ]
17
+
18
+
19
+ [project.scripts]
20
+ run-app = "maintenance_scheduling:main"
src/maintenance_scheduling/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uvicorn
2
+
3
+ from .rest_api import app as app
4
+
5
+
6
+ def main():
7
+ config = uvicorn.Config("maintenance_scheduling:app",
8
+ port=8080,
9
+ log_config="logging.conf",
10
+ use_colors=True)
11
+ server = uvicorn.Server(config)
12
+ server.run()
13
+
14
+
15
+ if __name__ == "__main__":
16
+ main()
src/maintenance_scheduling/constraints.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from solverforge_legacy.solver.score import (
2
+ constraint_provider,
3
+ HardSoftScore,
4
+ Joiners,
5
+ ConstraintFactory,
6
+ Constraint,
7
+ )
8
+
9
+ from .domain import Job
10
+
11
+ # Constraint names
12
+ CREW_CONFLICT = "Crew conflict"
13
+ MIN_START_DATE = "Min start date"
14
+ MAX_END_DATE = "Max end date"
15
+ BEFORE_IDEAL_END_DATE = "Before ideal end date"
16
+ AFTER_IDEAL_END_DATE = "After ideal end date"
17
+ TAG_CONFLICT = "Tag conflict"
18
+
19
+
20
+ @constraint_provider
21
+ def define_constraints(constraint_factory: ConstraintFactory):
22
+ """
23
+ Defines all constraints for the maintenance scheduling problem.
24
+
25
+ Args:
26
+ constraint_factory: The constraint factory.
27
+
28
+ Returns:
29
+ List of all defined constraints.
30
+ """
31
+ return [
32
+ # Hard constraints
33
+ crew_conflict(constraint_factory),
34
+ min_start_date(constraint_factory),
35
+ max_end_date(constraint_factory),
36
+ # Soft constraints
37
+ before_ideal_end_date(constraint_factory),
38
+ after_ideal_end_date(constraint_factory),
39
+ tag_conflict(constraint_factory),
40
+ ]
41
+
42
+
43
+ # ************************************************************************
44
+ # Hard constraints
45
+ # ************************************************************************
46
+
47
+
48
+ def crew_conflict(constraint_factory: ConstraintFactory) -> Constraint:
49
+ """
50
+ A crew can do at most one maintenance job at the same time.
51
+
52
+ Penalizes overlapping jobs assigned to the same crew, proportional to the
53
+ number of overlapping days.
54
+ """
55
+ return (
56
+ constraint_factory.for_each_unique_pair(
57
+ Job,
58
+ Joiners.equal(lambda job: job.crew),
59
+ Joiners.overlapping(
60
+ lambda job: job.start_date,
61
+ lambda job: job.get_end_date(),
62
+ ),
63
+ )
64
+ .filter(lambda job1, job2: job1.crew is not None)
65
+ .penalize(
66
+ HardSoftScore.ONE_HARD,
67
+ lambda job1, job2: _calculate_overlap_days(job1, job2),
68
+ )
69
+ .as_constraint(CREW_CONFLICT)
70
+ )
71
+
72
+
73
+ def min_start_date(constraint_factory: ConstraintFactory) -> Constraint:
74
+ """
75
+ Don't start a maintenance job before it's ready to start.
76
+
77
+ Penalizes jobs that start before their minimum start date, proportional
78
+ to the number of days early.
79
+ """
80
+ return (
81
+ constraint_factory.for_each(Job)
82
+ .filter(
83
+ lambda job: job.start_date is not None
84
+ and job.min_start_date is not None
85
+ and job.start_date < job.min_start_date
86
+ )
87
+ .penalize(
88
+ HardSoftScore.ONE_HARD,
89
+ lambda job: (job.min_start_date - job.start_date).days,
90
+ )
91
+ .as_constraint(MIN_START_DATE)
92
+ )
93
+
94
+
95
+ def max_end_date(constraint_factory: ConstraintFactory) -> Constraint:
96
+ """
97
+ Don't end a maintenance job after it's due.
98
+
99
+ Penalizes jobs that end after their maximum end date, proportional
100
+ to the number of days late.
101
+ """
102
+ return (
103
+ constraint_factory.for_each(Job)
104
+ .filter(
105
+ lambda job: job.get_end_date() is not None
106
+ and job.max_end_date is not None
107
+ and job.get_end_date() > job.max_end_date
108
+ )
109
+ .penalize(
110
+ HardSoftScore.ONE_HARD,
111
+ lambda job: (job.get_end_date() - job.max_end_date).days,
112
+ )
113
+ .as_constraint(MAX_END_DATE)
114
+ )
115
+
116
+
117
+ # ************************************************************************
118
+ # Soft constraints
119
+ # ************************************************************************
120
+
121
+
122
+ def before_ideal_end_date(constraint_factory: ConstraintFactory) -> Constraint:
123
+ """
124
+ Early maintenance is expensive because maintenance cycles restart sooner.
125
+
126
+ Penalizes jobs that finish before their ideal end date.
127
+ Weight: 1 point per day early (lowest priority soft constraint).
128
+ """
129
+ return (
130
+ constraint_factory.for_each(Job)
131
+ .filter(
132
+ lambda job: job.get_end_date() is not None
133
+ and job.ideal_end_date is not None
134
+ and job.get_end_date() < job.ideal_end_date
135
+ )
136
+ .penalize(
137
+ HardSoftScore.ONE_SOFT,
138
+ lambda job: (job.ideal_end_date - job.get_end_date()).days,
139
+ )
140
+ .as_constraint(BEFORE_IDEAL_END_DATE)
141
+ )
142
+
143
+
144
+ def after_ideal_end_date(constraint_factory: ConstraintFactory) -> Constraint:
145
+ """
146
+ Late maintenance is risky because delays can push it over the due date.
147
+
148
+ Penalizes jobs that finish after their ideal end date.
149
+ Weight: 1,000,000 points per day late (high priority soft constraint).
150
+ """
151
+ return (
152
+ constraint_factory.for_each(Job)
153
+ .filter(
154
+ lambda job: job.get_end_date() is not None
155
+ and job.ideal_end_date is not None
156
+ and job.get_end_date() > job.ideal_end_date
157
+ )
158
+ .penalize(
159
+ HardSoftScore.of_soft(1_000_000),
160
+ lambda job: (job.get_end_date() - job.ideal_end_date).days,
161
+ )
162
+ .as_constraint(AFTER_IDEAL_END_DATE)
163
+ )
164
+
165
+
166
+ def tag_conflict(constraint_factory: ConstraintFactory) -> Constraint:
167
+ """
168
+ Avoid overlapping maintenance jobs with the same tag.
169
+
170
+ For example, road maintenance in the same area should not overlap.
171
+ Penalizes overlapping jobs that share tags, proportional to the number
172
+ of shared tags and the overlap duration.
173
+ Weight: 1,000 points per tag per day of overlap.
174
+ """
175
+ return (
176
+ constraint_factory.for_each_unique_pair(
177
+ Job,
178
+ Joiners.overlapping(
179
+ lambda job: job.start_date,
180
+ lambda job: job.get_end_date(),
181
+ ),
182
+ )
183
+ .filter(lambda job1, job2: len(job1.get_common_tags(job2)) > 0)
184
+ .penalize(
185
+ HardSoftScore.of_soft(1_000),
186
+ lambda job1, job2: len(job1.get_common_tags(job2))
187
+ * _calculate_overlap_days(job1, job2),
188
+ )
189
+ .as_constraint(TAG_CONFLICT)
190
+ )
191
+
192
+
193
+ # ************************************************************************
194
+ # Helper functions
195
+ # ************************************************************************
196
+
197
+
198
+ def _calculate_overlap_days(job1: Job, job2: Job) -> int:
199
+ """
200
+ Calculate the number of overlapping calendar days between two jobs.
201
+
202
+ Args:
203
+ job1: First job
204
+ job2: Second job
205
+
206
+ Returns:
207
+ Number of overlapping days (calendar days, not working days)
208
+ """
209
+ if job1.start_date is None or job2.start_date is None:
210
+ return 0
211
+
212
+ end1 = job1.get_end_date()
213
+ end2 = job2.get_end_date()
214
+
215
+ if end1 is None or end2 is None:
216
+ return 0
217
+
218
+ # Calculate overlap range
219
+ overlap_start = max(job1.start_date, job2.start_date)
220
+ overlap_end = min(end1, end2)
221
+
222
+ if overlap_start >= overlap_end:
223
+ return 0
224
+
225
+ return (overlap_end - overlap_start).days
src/maintenance_scheduling/converters.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Converters for bidirectional transformation between domain objects and API models.
3
+ """
4
+
5
+ from datetime import date
6
+ from typing import Dict, List, Optional
7
+
8
+ from solverforge_legacy.solver import SolverStatus
9
+ from solverforge_legacy.solver.score import HardSoftScore
10
+
11
+ from . import domain
12
+
13
+
14
+ # ************************************************************************
15
+ # Helper functions
16
+ # ************************************************************************
17
+
18
+
19
+ def date_to_iso(d: Optional[date]) -> Optional[str]:
20
+ """Convert a date to ISO format string."""
21
+ return d.isoformat() if d else None
22
+
23
+
24
+ def iso_to_date(s: Optional[str]) -> Optional[date]:
25
+ """Convert an ISO format string to a date."""
26
+ return date.fromisoformat(s) if s else None
27
+
28
+
29
+ # ************************************************************************
30
+ # Domain -> Model conversions
31
+ # ************************************************************************
32
+
33
+
34
+ def work_calendar_to_model(wc: domain.WorkCalendar) -> domain.WorkCalendarModel:
35
+ """Convert a WorkCalendar domain object to its API model."""
36
+ return domain.WorkCalendarModel(
37
+ id=wc.id,
38
+ from_date=date_to_iso(wc.from_date),
39
+ to_date=date_to_iso(wc.to_date),
40
+ )
41
+
42
+
43
+ def crew_to_model(crew: domain.Crew) -> domain.CrewModel:
44
+ """Convert a Crew domain object to its API model."""
45
+ return domain.CrewModel(id=crew.id, name=crew.name)
46
+
47
+
48
+ def job_to_model(job: domain.Job) -> domain.JobModel:
49
+ """Convert a Job domain object to its API model."""
50
+ return domain.JobModel(
51
+ id=job.id,
52
+ name=job.name,
53
+ duration_in_days=job.duration_in_days,
54
+ min_start_date=date_to_iso(job.min_start_date),
55
+ max_end_date=date_to_iso(job.max_end_date),
56
+ ideal_end_date=date_to_iso(job.ideal_end_date),
57
+ tags=list(job.tags),
58
+ crew=crew_to_model(job.crew) if job.crew else None,
59
+ start_date=date_to_iso(job.start_date),
60
+ end_date=date_to_iso(job.get_end_date()),
61
+ )
62
+
63
+
64
+ def schedule_to_model(schedule: domain.MaintenanceSchedule) -> domain.MaintenanceScheduleModel:
65
+ """Convert a MaintenanceSchedule domain object to its API model."""
66
+ return domain.MaintenanceScheduleModel(
67
+ work_calendar=work_calendar_to_model(schedule.work_calendar),
68
+ crews=[crew_to_model(c) for c in schedule.crews],
69
+ jobs=[job_to_model(j) for j in schedule.jobs],
70
+ start_date_range=[date_to_iso(d) for d in schedule.start_date_range],
71
+ score=str(schedule.score) if schedule.score else None,
72
+ solver_status=schedule.solver_status.name if schedule.solver_status else None,
73
+ )
74
+
75
+
76
+ # ************************************************************************
77
+ # Model -> Domain conversions
78
+ # ************************************************************************
79
+
80
+
81
+ def model_to_work_calendar(model: domain.WorkCalendarModel) -> domain.WorkCalendar:
82
+ """Convert a WorkCalendarModel to its domain object."""
83
+ return domain.WorkCalendar(
84
+ id=model.id,
85
+ from_date=iso_to_date(model.from_date),
86
+ to_date=iso_to_date(model.to_date),
87
+ )
88
+
89
+
90
+ def model_to_crew(model: domain.CrewModel) -> domain.Crew:
91
+ """Convert a CrewModel to its domain object."""
92
+ return domain.Crew(id=model.id, name=model.name)
93
+
94
+
95
+ def model_to_schedule(model: domain.MaintenanceScheduleModel) -> domain.MaintenanceSchedule:
96
+ """
97
+ Convert a MaintenanceScheduleModel to its domain object.
98
+
99
+ Handles reference resolution for crew assignments.
100
+ """
101
+ # Create work calendar
102
+ work_calendar = model_to_work_calendar(model.work_calendar)
103
+
104
+ # Create crews and lookup
105
+ crews: List[domain.Crew] = [model_to_crew(c) for c in model.crews]
106
+ crew_lookup: Dict[str, domain.Crew] = {c.id: c for c in crews}
107
+
108
+ # Create jobs with crew references resolved
109
+ jobs: List[domain.Job] = []
110
+ for job_model in model.jobs:
111
+ # Resolve crew reference
112
+ crew = None
113
+ if job_model.crew:
114
+ if isinstance(job_model.crew, str):
115
+ crew = crew_lookup.get(job_model.crew)
116
+ elif isinstance(job_model.crew, domain.CrewModel):
117
+ crew = crew_lookup.get(job_model.crew.id)
118
+
119
+ job = domain.Job(
120
+ id=job_model.id,
121
+ name=job_model.name,
122
+ duration_in_days=job_model.duration_in_days,
123
+ min_start_date=iso_to_date(job_model.min_start_date),
124
+ max_end_date=iso_to_date(job_model.max_end_date),
125
+ ideal_end_date=iso_to_date(job_model.ideal_end_date),
126
+ tags=set(job_model.tags) if job_model.tags else set(),
127
+ crew=crew,
128
+ start_date=iso_to_date(job_model.start_date) if job_model.start_date else None,
129
+ )
130
+ jobs.append(job)
131
+
132
+ # Parse start_date_range
133
+ start_date_range = (
134
+ [iso_to_date(d) for d in model.start_date_range]
135
+ if model.start_date_range
136
+ else []
137
+ )
138
+
139
+ # Parse score
140
+ score = None
141
+ if model.score:
142
+ score = HardSoftScore.parse(model.score)
143
+
144
+ # Parse solver status
145
+ solver_status = SolverStatus.NOT_SOLVING
146
+ if model.solver_status:
147
+ solver_status = SolverStatus[model.solver_status]
148
+
149
+ return domain.MaintenanceSchedule(
150
+ work_calendar=work_calendar,
151
+ crews=crews,
152
+ jobs=jobs,
153
+ start_date_range=start_date_range,
154
+ score=score,
155
+ solver_status=solver_status,
156
+ )
src/maintenance_scheduling/demo_data.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import date, timedelta
2
+ from enum import Enum
3
+ from random import Random
4
+ from typing import List
5
+
6
+ from .domain import (
7
+ Crew,
8
+ Job,
9
+ MaintenanceSchedule,
10
+ WorkCalendar,
11
+ calculate_end_date,
12
+ create_start_date_range,
13
+ )
14
+
15
+
16
+ class DemoData(Enum):
17
+ SMALL = "SMALL"
18
+ LARGE = "LARGE"
19
+
20
+
21
+ # Job area names for generating job names
22
+ JOB_AREA_NAMES = [
23
+ "Downtown", "Uptown", "Park", "Airport", "Bay", "Hill", "Forest", "Station",
24
+ "Hospital", "Harbor", "Market", "Fort", "Beach", "Garden", "River", "Springs",
25
+ "Tower", "Mountain"
26
+ ]
27
+
28
+ # Job target names for generating job names
29
+ JOB_TARGET_NAMES = [
30
+ "Street", "Bridge", "Tunnel", "Highway", "Boulevard", "Avenue", "Square", "Plaza"
31
+ ]
32
+
33
+
34
+ def _get_next_monday(from_date: date) -> date:
35
+ """Get the next Monday on or after the given date."""
36
+ days_until_monday = (7 - from_date.weekday()) % 7
37
+ if days_until_monday == 0 and from_date.weekday() != 0:
38
+ days_until_monday = 7
39
+ return from_date + timedelta(days=days_until_monday)
40
+
41
+
42
+ def generate_demo_data(demo_data: DemoData) -> MaintenanceSchedule:
43
+ """
44
+ Generate demo data for the maintenance scheduling problem.
45
+
46
+ Args:
47
+ demo_data: The demo data type (SMALL or LARGE)
48
+
49
+ Returns:
50
+ A MaintenanceSchedule with crews, work calendar, and jobs
51
+ """
52
+ # Create crews
53
+ crews: List[Crew] = [
54
+ Crew(id="1", name="Alpha crew"),
55
+ Crew(id="2", name="Beta crew"),
56
+ Crew(id="3", name="Gamma crew"),
57
+ ]
58
+ if demo_data == DemoData.LARGE:
59
+ crews.append(Crew(id="4", name="Delta crew"))
60
+ crews.append(Crew(id="5", name="Epsilon crew"))
61
+
62
+ # Create work calendar
63
+ from_date = _get_next_monday(date.today())
64
+ week_list_size = 16 if demo_data == DemoData.LARGE else 8
65
+ to_date = from_date + timedelta(weeks=week_list_size)
66
+ work_calendar = WorkCalendar(id="1", from_date=from_date, to_date=to_date)
67
+
68
+ workday_total = week_list_size * 5
69
+
70
+ # Create jobs
71
+ jobs: List[Job] = []
72
+ job_list_size = week_list_size * len(crews) * 3 // 5
73
+ job_area_target_limit = min(len(JOB_TARGET_NAMES), len(crews) * 2)
74
+ random = Random(17) # Same seed as Java
75
+
76
+ for i in range(job_list_size):
77
+ job_area = JOB_AREA_NAMES[i // job_area_target_limit]
78
+ job_target = JOB_TARGET_NAMES[i % job_area_target_limit]
79
+
80
+ # 1 day to 2 workweeks (1 workweek on average)
81
+ duration_in_days = 1 + random.randint(0, 9)
82
+
83
+ # Calculate date constraints with at least 5 days of flexibility
84
+ min_max_between_workdays = (
85
+ duration_in_days + 5
86
+ + random.randint(0, workday_total - (duration_in_days + 5) - 1)
87
+ )
88
+ min_workday_offset = random.randint(0, workday_total - min_max_between_workdays)
89
+ min_ideal_end_between_workdays = min_max_between_workdays - 1 - random.randint(0, 3)
90
+
91
+ # Calculate dates using the weekend-skipping calculation
92
+ min_start_date = calculate_end_date(from_date, min_workday_offset)
93
+ max_end_date = calculate_end_date(min_start_date, min_max_between_workdays)
94
+ ideal_end_date = calculate_end_date(min_start_date, min_ideal_end_between_workdays)
95
+
96
+ # 10% chance of having "Subway" tag
97
+ if random.random() < 0.1:
98
+ tags = {job_area, "Subway"}
99
+ else:
100
+ tags = {job_area}
101
+
102
+ jobs.append(Job(
103
+ id=str(i),
104
+ name=f"{job_area} {job_target}",
105
+ duration_in_days=duration_in_days,
106
+ min_start_date=min_start_date,
107
+ max_end_date=max_end_date,
108
+ ideal_end_date=ideal_end_date,
109
+ tags=tags,
110
+ ))
111
+
112
+ # Create and return the schedule
113
+ schedule = MaintenanceSchedule(
114
+ work_calendar=work_calendar,
115
+ crews=crews,
116
+ jobs=jobs,
117
+ )
118
+
119
+ # The start_date_range will be auto-populated by __post_init__
120
+ # But let's ensure it's populated
121
+ if not schedule.start_date_range:
122
+ schedule.start_date_range = create_start_date_range(from_date, to_date)
123
+
124
+ return schedule
src/maintenance_scheduling/domain.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, field
2
+ from datetime import date, timedelta
3
+ from typing import List, Optional, Annotated, Union, Set
4
+
5
+ from solverforge_legacy.solver import SolverStatus
6
+ from solverforge_legacy.solver.score import HardSoftScore
7
+ from solverforge_legacy.solver.domain import (
8
+ planning_entity,
9
+ planning_solution,
10
+ PlanningId,
11
+ PlanningVariable,
12
+ PlanningEntityCollectionProperty,
13
+ ProblemFactCollectionProperty,
14
+ ProblemFactProperty,
15
+ ValueRangeProvider,
16
+ PlanningScore,
17
+ )
18
+ from .json_serialization import JsonDomainBase
19
+ from pydantic import Field
20
+
21
+
22
+ # ************************************************************************
23
+ # Utility functions for working day calculations
24
+ # ************************************************************************
25
+
26
+
27
+ def calculate_end_date(start_date: Optional[date], duration_in_days: int) -> Optional[date]:
28
+ """
29
+ Calculate the end date by adding working days to the start date, skipping weekends.
30
+
31
+ The end date is exclusive (like Java's implementation).
32
+
33
+ Args:
34
+ start_date: The start date (inclusive)
35
+ duration_in_days: Number of working days the job takes
36
+
37
+ Returns:
38
+ The end date (exclusive), or None if start_date is None
39
+ """
40
+ if start_date is None:
41
+ return None
42
+
43
+ # Skip weekends. Does not work for holidays.
44
+ # Keep in sync with create_start_date_range().
45
+ # Formula: For every 5 working days plus the weekday offset, add 2 weekend days
46
+ # Python weekday(): Monday=0, Tuesday=1, ..., Sunday=6
47
+ weekend_padding = 2 * ((duration_in_days + start_date.weekday()) // 5)
48
+ return start_date + timedelta(days=duration_in_days + weekend_padding)
49
+
50
+
51
+ def count_working_days_between(start: date, end: date) -> int:
52
+ """
53
+ Count the number of working days (Mon-Fri) between two dates.
54
+
55
+ Args:
56
+ start: Start date (inclusive)
57
+ end: End date (exclusive)
58
+
59
+ Returns:
60
+ Number of working days between the dates
61
+ """
62
+ if start >= end:
63
+ return 0
64
+
65
+ count = 0
66
+ current = start
67
+ while current < end:
68
+ if current.weekday() < 5: # Monday=0 to Friday=4
69
+ count += 1
70
+ current += timedelta(days=1)
71
+ return count
72
+
73
+
74
+ def create_start_date_range(from_date: date, to_date: date) -> List[date]:
75
+ """
76
+ Generate a list of working days (Mon-Fri) within the date range.
77
+
78
+ Args:
79
+ from_date: Start of range (inclusive)
80
+ to_date: End of range (exclusive)
81
+
82
+ Returns:
83
+ List of working days in the range
84
+ """
85
+ dates = []
86
+ current = from_date
87
+ while current < to_date:
88
+ if current.weekday() < 5: # Monday=0 to Friday=4
89
+ dates.append(current)
90
+ current += timedelta(days=1)
91
+ return dates
92
+
93
+
94
+ # ************************************************************************
95
+ # Domain classes
96
+ # ************************************************************************
97
+
98
+
99
+ @dataclass
100
+ class WorkCalendar:
101
+ """Defines the planning window for the schedule."""
102
+ id: Annotated[str, PlanningId]
103
+ from_date: date # Inclusive
104
+ to_date: date # Exclusive
105
+
106
+
107
+ @dataclass
108
+ class Crew:
109
+ """A maintenance crew that can be assigned to jobs."""
110
+ id: Annotated[str, PlanningId]
111
+ name: str
112
+
113
+ def __hash__(self):
114
+ return hash(self.id)
115
+
116
+ def __eq__(self, other):
117
+ if isinstance(other, Crew):
118
+ return self.id == other.id
119
+ return False
120
+
121
+ def __str__(self):
122
+ return f"{self.name}({self.id})"
123
+
124
+
125
+ @planning_entity
126
+ @dataclass
127
+ class Job:
128
+ """
129
+ A maintenance job that needs to be scheduled.
130
+
131
+ Planning variables:
132
+ - crew: The crew assigned to this job
133
+ - start_date: When the job starts (inclusive)
134
+
135
+ The end_date is computed from start_date and duration_in_days.
136
+ """
137
+ id: Annotated[str, PlanningId]
138
+ name: str
139
+ duration_in_days: int
140
+ min_start_date: date # Inclusive - earliest the job can start
141
+ max_end_date: date # Exclusive - latest the job can end
142
+ ideal_end_date: date # Exclusive - preferred end date
143
+ tags: Set[str] = field(default_factory=set)
144
+
145
+ # Planning variables
146
+ crew: Annotated[Optional[Crew], PlanningVariable] = None
147
+ start_date: Annotated[Optional[date], PlanningVariable] = None
148
+
149
+ def get_end_date(self) -> Optional[date]:
150
+ """Calculate the end date based on start_date and duration."""
151
+ return calculate_end_date(self.start_date, self.duration_in_days)
152
+
153
+ @property
154
+ def end_date(self) -> Optional[date]:
155
+ """End date property for convenient access."""
156
+ return self.get_end_date()
157
+
158
+ def calculate_overlap(self, other: "Job") -> int:
159
+ """
160
+ Calculate the number of overlapping working days with another job.
161
+
162
+ Args:
163
+ other: The other job to compare with
164
+
165
+ Returns:
166
+ Number of overlapping working days
167
+ """
168
+ if self.start_date is None or other.start_date is None:
169
+ return 0
170
+
171
+ self_end = self.get_end_date()
172
+ other_end = other.get_end_date()
173
+
174
+ if self_end is None or other_end is None:
175
+ return 0
176
+
177
+ # Calculate overlap range
178
+ overlap_start = max(self.start_date, other.start_date)
179
+ overlap_end = min(self_end, other_end)
180
+
181
+ if overlap_start >= overlap_end:
182
+ return 0
183
+
184
+ return count_working_days_between(overlap_start, overlap_end)
185
+
186
+ def get_common_tags(self, other: "Job") -> Set[str]:
187
+ """Get the tags that both jobs share."""
188
+ return self.tags & other.tags
189
+
190
+ def __str__(self):
191
+ return f"{self.name}({self.id})"
192
+
193
+
194
+ @planning_solution
195
+ @dataclass
196
+ class MaintenanceSchedule:
197
+ """
198
+ The planning solution containing the schedule to be optimized.
199
+ """
200
+ work_calendar: Annotated[WorkCalendar, ProblemFactProperty]
201
+ crews: Annotated[List[Crew], ProblemFactCollectionProperty, ValueRangeProvider]
202
+ jobs: Annotated[List[Job], PlanningEntityCollectionProperty]
203
+ start_date_range: Annotated[
204
+ List[date], ProblemFactCollectionProperty, ValueRangeProvider
205
+ ] = field(default_factory=list)
206
+ score: Annotated[Optional[HardSoftScore], PlanningScore] = None
207
+ solver_status: SolverStatus = SolverStatus.NOT_SOLVING
208
+
209
+ def __post_init__(self):
210
+ """Initialize start_date_range if not provided."""
211
+ if not self.start_date_range and self.work_calendar:
212
+ self.start_date_range = create_start_date_range(
213
+ self.work_calendar.from_date,
214
+ self.work_calendar.to_date
215
+ )
216
+
217
+
218
+ # ************************************************************************
219
+ # Pydantic REST models for API
220
+ # ************************************************************************
221
+
222
+
223
+ class WorkCalendarModel(JsonDomainBase):
224
+ id: str
225
+ from_date: str = Field(..., alias="fromDate") # ISO date string
226
+ to_date: str = Field(..., alias="toDate")
227
+
228
+
229
+ class CrewModel(JsonDomainBase):
230
+ id: str
231
+ name: str
232
+
233
+
234
+ class JobModel(JsonDomainBase):
235
+ id: str
236
+ name: str
237
+ duration_in_days: int = Field(..., alias="durationInDays")
238
+ min_start_date: str = Field(..., alias="minStartDate")
239
+ max_end_date: str = Field(..., alias="maxEndDate")
240
+ ideal_end_date: str = Field(..., alias="idealEndDate")
241
+ tags: List[str] = Field(default_factory=list)
242
+ crew: Optional[Union[str, CrewModel]] = None
243
+ start_date: Optional[str] = Field(None, alias="startDate")
244
+ end_date: Optional[str] = Field(None, alias="endDate")
245
+
246
+
247
+ class MaintenanceScheduleModel(JsonDomainBase):
248
+ work_calendar: WorkCalendarModel = Field(..., alias="workCalendar")
249
+ crews: List[CrewModel]
250
+ jobs: List[JobModel]
251
+ start_date_range: List[str] = Field(default_factory=list, alias="startDateRange")
252
+ score: Optional[str] = None
253
+ solver_status: Optional[str] = Field(None, alias="solverStatus")
src/maintenance_scheduling/json_serialization.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from solverforge_legacy.solver.score import HardSoftScore
2
+
3
+ from typing import Any
4
+ from pydantic import (
5
+ BaseModel,
6
+ ConfigDict,
7
+ PlainSerializer,
8
+ BeforeValidator,
9
+ ValidationInfo,
10
+ )
11
+ from pydantic.alias_generators import to_camel
12
+
13
+
14
+ class JsonDomainBase(BaseModel):
15
+ model_config = ConfigDict(
16
+ alias_generator=to_camel,
17
+ populate_by_name=True,
18
+ from_attributes=True,
19
+ )
20
+
21
+
22
+ ScoreSerializer = PlainSerializer(lambda score: str(score), return_type=str)
23
+ IdSerializer = PlainSerializer(
24
+ lambda item: item.id if item is not None else None, return_type=str | None
25
+ )
26
+
27
+
28
+ def validate_score(v: Any, info: ValidationInfo) -> Any:
29
+ if isinstance(v, HardSoftScore) or v is None:
30
+ return v
31
+ if isinstance(v, str):
32
+ return HardSoftScore.parse(v)
33
+ raise ValueError('"score" should be a string')
34
+
35
+
36
+ ScoreValidator = BeforeValidator(validate_score)
src/maintenance_scheduling/rest_api.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI REST endpoints for the maintenance scheduling application.
3
+ """
4
+
5
+ from fastapi import FastAPI, HTTPException
6
+ from fastapi.staticfiles import StaticFiles
7
+ from uuid import uuid4
8
+ from typing import Dict, List
9
+ from dataclasses import asdict
10
+ import logging
11
+
12
+ from .domain import MaintenanceSchedule, MaintenanceScheduleModel
13
+ from .converters import schedule_to_model, model_to_schedule
14
+ from .score_analysis import ConstraintAnalysisDTO, MatchAnalysisDTO
15
+ from .demo_data import generate_demo_data, DemoData
16
+ from .solver import solver_manager, solution_manager
17
+
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ app = FastAPI(docs_url='/q/swagger-ui')
22
+
23
+ data_sets: Dict[str, MaintenanceSchedule] = {}
24
+
25
+
26
+ # ************************************************************************
27
+ # Demo Data Endpoints
28
+ # ************************************************************************
29
+
30
+
31
+ @app.get("/demo-data")
32
+ async def get_demo_data_list() -> List[str]:
33
+ """Get available demo data sets."""
34
+ return [demo.name for demo in DemoData]
35
+
36
+
37
+ @app.get("/demo-data/{demo_name}", response_model=MaintenanceScheduleModel)
38
+ async def get_demo_data_by_name(demo_name: str) -> MaintenanceScheduleModel:
39
+ """Get a specific demo data set."""
40
+ try:
41
+ demo = DemoData[demo_name]
42
+ schedule = generate_demo_data(demo)
43
+ return schedule_to_model(schedule)
44
+ except KeyError:
45
+ raise HTTPException(status_code=404, detail=f"Demo data '{demo_name}' not found")
46
+
47
+
48
+ # ************************************************************************
49
+ # Schedule Endpoints
50
+ # ************************************************************************
51
+
52
+
53
+ @app.get("/schedules")
54
+ async def list_schedules() -> List[str]:
55
+ """List the job IDs of all submitted schedules."""
56
+ return list(data_sets.keys())
57
+
58
+
59
+ @app.post("/schedules")
60
+ async def solve_schedule(model: MaintenanceScheduleModel) -> str:
61
+ """
62
+ Submit a schedule for solving.
63
+
64
+ Returns the job ID that can be used to track progress and retrieve results.
65
+ """
66
+ job_id = str(uuid4())
67
+ schedule = model_to_schedule(model)
68
+ data_sets[job_id] = schedule
69
+ solver_manager.solve_and_listen(
70
+ job_id,
71
+ schedule,
72
+ lambda solution: data_sets.update({job_id: solution})
73
+ )
74
+ return job_id
75
+
76
+
77
+ @app.get("/schedules/{job_id}", response_model=MaintenanceScheduleModel)
78
+ async def get_schedule(job_id: str) -> MaintenanceScheduleModel:
79
+ """Get the current solution for a job."""
80
+ schedule = data_sets.get(job_id)
81
+ if not schedule:
82
+ raise HTTPException(status_code=404, detail="Schedule not found")
83
+ schedule.solver_status = solver_manager.get_solver_status(job_id)
84
+ return schedule_to_model(schedule)
85
+
86
+
87
+ @app.get("/schedules/{job_id}/status")
88
+ async def get_schedule_status(job_id: str) -> dict:
89
+ """Get the status and score for a job (lightweight, without full solution)."""
90
+ schedule = data_sets.get(job_id)
91
+ if not schedule:
92
+ raise HTTPException(status_code=404, detail="Schedule not found")
93
+ solver_status = solver_manager.get_solver_status(job_id)
94
+ return {
95
+ "score": str(schedule.score) if schedule.score else None,
96
+ "solverStatus": solver_status.name if solver_status else None,
97
+ }
98
+
99
+
100
+ @app.delete("/schedules/{job_id}", response_model=MaintenanceScheduleModel)
101
+ async def stop_solving(job_id: str) -> MaintenanceScheduleModel:
102
+ """Terminate solving and return the best solution so far."""
103
+ solver_manager.terminate_early(job_id)
104
+ schedule = data_sets.get(job_id)
105
+ if not schedule:
106
+ raise HTTPException(status_code=404, detail="Schedule not found")
107
+ schedule.solver_status = solver_manager.get_solver_status(job_id)
108
+ return schedule_to_model(schedule)
109
+
110
+
111
+ # ************************************************************************
112
+ # Score Analysis Endpoint
113
+ # ************************************************************************
114
+
115
+
116
+ @app.put("/schedules/analyze")
117
+ async def analyze_schedule(model: MaintenanceScheduleModel) -> dict:
118
+ """
119
+ Analyze the constraints in a schedule.
120
+
121
+ Returns detailed information about which constraints are satisfied or violated.
122
+ """
123
+ schedule = model_to_schedule(model)
124
+ analysis = solution_manager.analyze(schedule)
125
+ constraints = []
126
+ for constraint in getattr(analysis, 'constraint_analyses', []) or []:
127
+ matches = [
128
+ MatchAnalysisDTO(
129
+ name=str(getattr(getattr(match, 'constraint_ref', None), 'constraint_name', "")),
130
+ score=str(getattr(match, 'score', "0hard/0soft")),
131
+ justification=str(getattr(match, 'justification', ""))
132
+ )
133
+ for match in getattr(constraint, 'matches', []) or []
134
+ ]
135
+ constraints.append(ConstraintAnalysisDTO(
136
+ name=str(getattr(constraint, 'constraint_name', "")),
137
+ weight=str(getattr(constraint, 'weight', "0hard/0soft")),
138
+ score=str(getattr(constraint, 'score', "0hard/0soft")),
139
+ matches=matches
140
+ ))
141
+ return {"constraints": [asdict(constraint) for constraint in constraints]}
142
+
143
+
144
+ # ************************************************************************
145
+ # Static Files
146
+ # ************************************************************************
147
+
148
+
149
+ app.mount("/", StaticFiles(directory="static", html=True), name="static")
src/maintenance_scheduling/score_analysis.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Annotated
3
+
4
+ from solverforge_legacy.solver.score import HardSoftScore
5
+ from .json_serialization import ScoreSerializer
6
+
7
+
8
+ @dataclass
9
+ class MatchAnalysisDTO:
10
+ name: str
11
+ score: Annotated[HardSoftScore, ScoreSerializer]
12
+ justification: object
13
+
14
+
15
+ @dataclass
16
+ class ConstraintAnalysisDTO:
17
+ name: str
18
+ weight: Annotated[HardSoftScore, ScoreSerializer]
19
+ matches: list[MatchAnalysisDTO]
20
+ score: Annotated[HardSoftScore, ScoreSerializer]
src/maintenance_scheduling/solver.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from solverforge_legacy.solver import SolverManager, SolutionManager
2
+ from solverforge_legacy.solver.config import (
3
+ SolverConfig,
4
+ ScoreDirectorFactoryConfig,
5
+ TerminationConfig,
6
+ Duration,
7
+ )
8
+
9
+ from .domain import Job, MaintenanceSchedule
10
+ from .constraints import define_constraints
11
+
12
+
13
+ solver_config = SolverConfig(
14
+ solution_class=MaintenanceSchedule,
15
+ entity_class_list=[Job],
16
+ score_director_factory_config=ScoreDirectorFactoryConfig(
17
+ constraint_provider_function=define_constraints
18
+ ),
19
+ termination_config=TerminationConfig(spent_limit=Duration(seconds=30)),
20
+ )
21
+
22
+ solver_manager = SolverManager.create(solver_config)
23
+ solution_manager = SolutionManager.create(solver_manager)
static/app.js ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Maintenance Scheduling Color Palette
2
+ const COLOR_IDEAL = '#8AE234'; // Green - in ideal window
3
+ const COLOR_IDEAL_BG = '#8AE23433'; // Green with transparency
4
+ const COLOR_ACCEPTABLE = '#FCAF3E'; // Orange - after ideal, before due
5
+ const COLOR_ACCEPTABLE_BG = '#FCAF3E33'; // Orange with transparency
6
+ const COLOR_OVERDUE = '#EF2929'; // Red - past due date
7
+ const COLOR_OVERDUE_BG = '#EF292999'; // Red with transparency
8
+ const BRAND_GREEN = '#10b981'; // SolverForge brand green
9
+ const HIGHLIGHT_COLOR = 'rgba(99, 102, 241, 0.15)'; // Indigo highlight
10
+
11
+ var autoRefreshIntervalId = null;
12
+ let highlightedCrewId = null;
13
+
14
+ let demoDataId = null;
15
+ let scheduleId = null;
16
+ let loadedSchedule = null;
17
+
18
+ const byCrewPanel = document.getElementById("byCrewPanel");
19
+ const byCrewTimelineOptions = {
20
+ timeAxis: {scale: "day"},
21
+ orientation: {axis: "top"},
22
+ stack: false,
23
+ xss: {disabled: true}, // Items are XSS safe through JQuery
24
+ zoomMin: 3 * 1000 * 60 * 60 * 24 // Three day in milliseconds
25
+ };
26
+ var byCrewGroupData = new vis.DataSet();
27
+ var byCrewItemData = new vis.DataSet();
28
+ var byCrewTimeline = new vis.Timeline(byCrewPanel, byCrewItemData, byCrewGroupData, byCrewTimelineOptions);
29
+
30
+ const byJobPanel = document.getElementById("byJobPanel");
31
+ const byJobTimelineOptions = {
32
+ timeAxis: {scale: "day"},
33
+ orientation: {axis: "top"},
34
+ xss: {disabled: true}, // Items are XSS safe through JQuery
35
+ zoomMin: 3 * 1000 * 60 * 60 * 24 // Three day in milliseconds
36
+ };
37
+ var byJobGroupData = new vis.DataSet();
38
+ var byJobItemData = new vis.DataSet();
39
+ var byJobTimeline = new vis.Timeline(byJobPanel, byJobItemData, byJobGroupData, byJobTimelineOptions);
40
+
41
+
42
+ $(document).ready(function () {
43
+ replaceQuickstartSolverForgeAutoHeaderFooter();
44
+
45
+ $("#solveButton").click(function () {
46
+ solve();
47
+ });
48
+ $("#stopSolvingButton").click(function () {
49
+ stopSolving();
50
+ });
51
+ $("#analyzeButton").click(function () {
52
+ analyze();
53
+ });
54
+ // HACK to allow vis-timeline to work within Bootstrap tabs
55
+ $("#byCrewTab").on('shown.bs.tab', function (event) {
56
+ byCrewTimeline.redraw();
57
+ })
58
+ $("#byJobTab").on('shown.bs.tab', function (event) {
59
+ byJobTimeline.redraw();
60
+ })
61
+
62
+ // Timeline item click handlers
63
+ byCrewTimeline.on('select', function(properties) {
64
+ if (properties.items.length > 0) {
65
+ const itemId = properties.items[0];
66
+ // Ignore background items (they have underscore in ID like "job1_readyToIdealEnd")
67
+ if (!String(itemId).includes('_')) {
68
+ showJobDetails(itemId);
69
+ }
70
+ byCrewTimeline.setSelection([]); // Clear selection
71
+ }
72
+ });
73
+ byJobTimeline.on('select', function(properties) {
74
+ if (properties.items.length > 0) {
75
+ const itemId = properties.items[0];
76
+ if (!String(itemId).includes('_')) {
77
+ showJobDetails(itemId);
78
+ }
79
+ byJobTimeline.setSelection([]);
80
+ }
81
+ });
82
+
83
+ setupAjax();
84
+ fetchDemoData();
85
+ });
86
+
87
+ function setupAjax() {
88
+ $.ajaxSetup({
89
+ headers: {
90
+ 'Content-Type': 'application/json',
91
+ 'Accept': 'application/json,text/plain', // plain text is required by solve() returning UUID of the solver job
92
+ }
93
+ });
94
+
95
+ // Extend jQuery to support $.put() and $.delete()
96
+ jQuery.each(["put", "delete"], function (i, method) {
97
+ jQuery[method] = function (url, data, callback, type) {
98
+ if (jQuery.isFunction(data)) {
99
+ type = type || callback;
100
+ callback = data;
101
+ data = undefined;
102
+ }
103
+ return jQuery.ajax({
104
+ url: url,
105
+ type: method,
106
+ dataType: type,
107
+ data: data,
108
+ success: callback
109
+ });
110
+ };
111
+ });
112
+ }
113
+
114
+ function fetchDemoData() {
115
+ $.get("/demo-data", function (data) {
116
+ data.forEach(item => {
117
+ $("#testDataButton").append($('<a id="' + item + 'TestData" class="dropdown-item" href="#">' + item + '</a>'));
118
+
119
+ $("#" + item + "TestData").click(function () {
120
+ switchDataDropDownItemActive(item);
121
+ scheduleId = null;
122
+ demoDataId = item;
123
+
124
+ refreshSchedule();
125
+ });
126
+ });
127
+
128
+ // load first data set
129
+ demoDataId = data[0];
130
+ switchDataDropDownItemActive(demoDataId);
131
+ refreshSchedule();
132
+ }).fail(function (xhr, ajaxOptions, thrownError) {
133
+ // disable this page as there is no data
134
+ let $demo = $("#demo");
135
+ $demo.empty();
136
+ $demo.html("<h1><p align=\"center\">No test data available</p></h1>")
137
+ });
138
+ }
139
+
140
+ function switchDataDropDownItemActive(newItem) {
141
+ activeCssClass = "active";
142
+ $("#testDataButton > a." + activeCssClass).removeClass(activeCssClass);
143
+ $("#" + newItem + "TestData").addClass(activeCssClass);
144
+ }
145
+
146
+ function refreshSchedule() {
147
+ let path = "/schedules/" + scheduleId;
148
+ if (scheduleId === null) {
149
+ if (demoDataId === null) {
150
+ alert("Please select a test data set.");
151
+ return;
152
+ }
153
+
154
+ path = "/demo-data/" + demoDataId;
155
+ }
156
+
157
+ $.getJSON(path, function (schedule) {
158
+ loadedSchedule = schedule;
159
+ renderSchedule(schedule);
160
+ })
161
+ .fail(function (xhr, ajaxOptions, thrownError) {
162
+ showError("Getting the schedule has failed.", xhr);
163
+ refreshSolvingButtons(false);
164
+ });
165
+ }
166
+
167
+ function renderSchedule(schedule) {
168
+ refreshSolvingButtons(schedule.solverStatus != null && schedule.solverStatus !== "NOT_SOLVING");
169
+ $("#score").text("Score: " + (schedule.score == null ? "?" : schedule.score));
170
+
171
+ const unassignedJobs = $("#unassignedJobs");
172
+ unassignedJobs.children().remove();
173
+ var unassignedJobsCount = 0;
174
+ byCrewGroupData.clear();
175
+ byJobGroupData.clear();
176
+ byCrewItemData.clear();
177
+ byJobItemData.clear();
178
+
179
+ $.each(schedule.crews, (index, crew) => {
180
+ byCrewGroupData.add({id: crew.id, content: crew.name});
181
+ });
182
+
183
+ $.each(schedule.jobs, (index, job) => {
184
+ const jobGroupElement = $(`<div/>`)
185
+ .append($(`<h5 class="card-title mb-1"/>`).text(job.name))
186
+ .append($(`<p class="card-text ms-2 mb-0"/>`).text(`${job.durationInDays} workdays`));
187
+ byJobGroupData.add({
188
+ id: job.id,
189
+ content: jobGroupElement.html()
190
+ });
191
+ byJobItemData.add({
192
+ id: job.id + "_readyToIdealEnd", group: job.id,
193
+ start: job.minStartDate, end: job.idealEndDate,
194
+ type: "background",
195
+ style: `background-color: ${COLOR_IDEAL_BG}`
196
+ });
197
+ byJobItemData.add({
198
+ id: job.id + "_idealEndToDue", group: job.id,
199
+ start: job.idealEndDate, end: job.maxEndDate,
200
+ type: "background",
201
+ style: `background-color: ${COLOR_ACCEPTABLE_BG}`
202
+ });
203
+
204
+ if (job.crew == null || job.startDate == null) {
205
+ unassignedJobsCount++;
206
+ const unassignedJobElement = $(`<div class="card-body p-2"/>`)
207
+ .append($(`<h5 class="card-title mb-1"/>`).text(job.name))
208
+ .append($(`<p class="card-text ms-2 mb-0"/>`).text(`${job.durationInDays} workdays`))
209
+ .append($(`<p class="card-text ms-2 mb-0"/>`).text(`Start: ${job.minStartDate}`))
210
+ .append($(`<p class="card-text ms-2 mb-0"/>`).text(`End: ${job.maxEndDate}`));
211
+ const byJobJobElement = $(`<div/>`)
212
+ .append($(`<h5 class="card-title mb-1"/>`).text(`Unassigned`));
213
+ $.each(job.tags, (index, tag) => {
214
+ const color = pickColor(tag);
215
+ unassignedJobElement.append($(`<span class="badge me-1" style="background-color: ${color}"/>`).text(tag));
216
+ byJobJobElement.append($(`<span class="badge me-1" style="background-color: ${color}"/>`).text(tag));
217
+ });
218
+ const card = $(`<div class="card" style="cursor: pointer;"/>`).append(unassignedJobElement);
219
+ card.click(() => showJobDetails(job.id));
220
+ unassignedJobs.append($(`<div class="col"/>`).append(card));
221
+ byJobItemData.add({
222
+ id: job.id,
223
+ group: job.id,
224
+ content: byJobJobElement.html(),
225
+ start: job.minStartDate,
226
+ end: JSJoda.LocalDate.parse(job.minStartDate).plusDays(job.durationInDays).toString(),
227
+ style: `background-color: ${COLOR_OVERDUE_BG}`
228
+ });
229
+ } else {
230
+ const beforeReady = JSJoda.LocalDate.parse(job.startDate).isBefore(JSJoda.LocalDate.parse(job.minStartDate));
231
+ const afterDue = JSJoda.LocalDate.parse(job.endDate).isAfter(JSJoda.LocalDate.parse(job.maxEndDate));
232
+ const byCrewJobElement = $(`<div/>`)
233
+ .append($(`<h5 class="card-title mb-1"/>`).text(job.name))
234
+ .append($(`<p class="card-text ms-2 mb-0"/>`).text(`${job.durationInDays} workdays`));
235
+ const byJobJobElement = $(`<div/>`)
236
+ .append($(`<h5 class="card-title mb-1"/>`).text(job.crew.name));
237
+ if (beforeReady) {
238
+ byCrewJobElement.append($(`<p class="badge badge-danger mb-0"/>`).text(`Before ready (too early)`));
239
+ byJobJobElement.append($(`<p class="badge badge-danger mb-0"/>`).text(`Before ready (too early)`));
240
+ }
241
+ if (afterDue) {
242
+ byCrewJobElement.append($(`<p class="badge badge-danger mb-0"/>`).text(`After due (too late)`));
243
+ byJobJobElement.append($(`<p class="badge badge-danger mb-0"/>`).text(`After due (too late)`));
244
+ }
245
+ $.each(job.tags, (index, tag) => {
246
+ const color = pickColor(tag);
247
+ byCrewJobElement.append($(`<span class="badge me-1" style="background-color: ${color}"/>`).text(tag));
248
+ byJobJobElement.append($(`<span class="badge me-1" style="background-color: ${color}"/>`).text(tag));
249
+ });
250
+ byCrewItemData.add({
251
+ id: job.id, group: job.crew.id,
252
+ content: byCrewJobElement.html(),
253
+ start: job.startDate, end: job.endDate
254
+ });
255
+ byJobItemData.add({
256
+ id: job.id, group: job.id,
257
+ content: byJobJobElement.html(),
258
+ start: job.startDate, end: job.endDate,
259
+ crewId: job.crew.id
260
+ });
261
+ }
262
+ });
263
+ if (unassignedJobsCount === 0) {
264
+ unassignedJobs.append($(`<p/>`).text(`There are no unassigned jobs.`));
265
+ }
266
+ byCrewTimeline.setWindow(schedule.workCalendar.fromDate, schedule.workCalendar.toDate);
267
+ byJobTimeline.setWindow(schedule.workCalendar.fromDate, schedule.workCalendar.toDate);
268
+
269
+ // Render crew table and clear any previous highlighting
270
+ renderCrewTable(schedule);
271
+ highlightedCrewId = null;
272
+ }
273
+
274
+ function solve() {
275
+ $.post("/schedules", JSON.stringify(loadedSchedule), function (data) {
276
+ scheduleId = data;
277
+ refreshSolvingButtons(true);
278
+ }).fail(function (xhr, ajaxOptions, thrownError) {
279
+ showError("Start solving failed.", xhr);
280
+ refreshSolvingButtons(false);
281
+ },
282
+ "text");
283
+ }
284
+
285
+ function analyze() {
286
+ analyzeScore(loadedSchedule, "/schedules/analyze");
287
+ }
288
+
289
+ function refreshSolvingButtons(solving) {
290
+ if (solving) {
291
+ $("#solveButton").hide();
292
+ $("#stopSolvingButton").show();
293
+ $("#solvingSpinner").addClass("active");
294
+ if (autoRefreshIntervalId == null) {
295
+ autoRefreshIntervalId = setInterval(refreshSchedule, 2000);
296
+ }
297
+ } else {
298
+ $("#solveButton").show();
299
+ $("#stopSolvingButton").hide();
300
+ $("#solvingSpinner").removeClass("active");
301
+ if (autoRefreshIntervalId != null) {
302
+ clearInterval(autoRefreshIntervalId);
303
+ autoRefreshIntervalId = null;
304
+ }
305
+ }
306
+ }
307
+
308
+ function stopSolving() {
309
+ $.delete("/schedules/" + scheduleId, function () {
310
+ refreshSolvingButtons(false);
311
+ refreshSchedule();
312
+ }).fail(function (xhr, ajaxOptions, thrownError) {
313
+ showError("Stop solving failed.", xhr);
314
+ });
315
+ }
316
+
317
+ function copyTextToClipboard(id) {
318
+ var text = document.getElementById(id).innerText;
319
+ navigator.clipboard.writeText(text);
320
+ }
321
+
322
+ function replaceQuickstartSolverForgeAutoHeaderFooter() {
323
+ const solverforgeHeader = $("header#solverforge-auto-header");
324
+ if (solverforgeHeader != null) {
325
+ solverforgeHeader.css("background-color", "#ffffff");
326
+ solverforgeHeader.append(
327
+ $(`<div class="container-fluid">
328
+ <nav class="navbar sticky-top navbar-expand-lg shadow-sm mb-3" style="background-color: #ffffff;">
329
+ <a class="navbar-brand" href="https://www.solverforge.org">
330
+ <img src="/webjars/solverforge/img/solverforge-horizontal.svg" alt="SolverForge logo" width="400">
331
+ </a>
332
+ <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
333
+ <span class="navbar-toggler-icon"></span>
334
+ </button>
335
+ <div class="collapse navbar-collapse" id="navbarNav">
336
+ <ul class="nav nav-pills">
337
+ <li class="nav-item active" id="navUIItem">
338
+ <button class="nav-link active" id="navUI" data-bs-toggle="pill" data-bs-target="#demo" type="button" style="color: #1f2937;">Demo UI</button>
339
+ </li>
340
+ <li class="nav-item" id="navRestItem">
341
+ <button class="nav-link" id="navRest" data-bs-toggle="pill" data-bs-target="#rest" type="button" style="color: #1f2937;">Guide</button>
342
+ </li>
343
+ <li class="nav-item" id="navOpenApiItem">
344
+ <button class="nav-link" id="navOpenApi" data-bs-toggle="pill" data-bs-target="#openapi" type="button" style="color: #1f2937;">REST API</button>
345
+ </li>
346
+ </ul>
347
+ </div>
348
+ <div class="ms-auto d-flex align-items-center gap-3">
349
+ <div class="dropdown">
350
+ <button class="btn dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="background-color: #10b981; color: #ffffff; border-color: #10b981;">
351
+ Data
352
+ </button>
353
+ <div id="testDataButton" class="dropdown-menu" aria-labelledby="dropdownMenuButton"></div>
354
+ </div>
355
+ </div>
356
+ </nav>
357
+ </div>`),
358
+ );
359
+ }
360
+
361
+ const solverforgeFooter = $("footer#solverforge-auto-footer");
362
+ if (solverforgeFooter != null) {
363
+ solverforgeFooter.append(
364
+ $(`<footer class="bg-black text-white-50">
365
+ <div class="container">
366
+ <div class="hstack gap-3 p-4">
367
+ <div class="ms-auto"><a class="text-white" href="https://www.solverforge.org">SolverForge</a></div>
368
+ <div class="vr"></div>
369
+ <div><a class="text-white" href="https://www.solverforge.org/docs">Documentation</a></div>
370
+ <div class="vr"></div>
371
+ <div><a class="text-white" href="https://github.com/SolverForge/solverforge-legacy">Code</a></div>
372
+ <div class="vr"></div>
373
+ <div class="me-auto"><a class="text-white" href="mailto:info@solverforge.org">Support</a></div>
374
+ </div>
375
+ </div>
376
+ </footer>`),
377
+ );
378
+ }
379
+ }
380
+
381
+ // ****************************************************************************
382
+ // Job Details Modal
383
+ // ****************************************************************************
384
+
385
+ function showJobDetails(jobId) {
386
+ const job = loadedSchedule.jobs.find(j => j.id === jobId);
387
+ if (!job) return;
388
+
389
+ $("#jobDetailsName").text(job.name);
390
+ $("#jobDetailsCrew").html(job.crew ?
391
+ `<i class="fas fa-hard-hat me-1"></i>${job.crew.name}` :
392
+ '<span class="text-danger">Unassigned</span>');
393
+ $("#jobDetailsDuration").text(`${job.durationInDays} workdays`);
394
+ $("#jobDetailsMinStart").text(job.minStartDate);
395
+ $("#jobDetailsMaxEnd").text(job.maxEndDate);
396
+ $("#jobDetailsIdealEnd").text(job.idealEndDate);
397
+
398
+ if (job.startDate && job.endDate) {
399
+ $("#jobDetailsScheduled").text(`${job.startDate} to ${job.endDate}`);
400
+ } else {
401
+ $("#jobDetailsScheduled").html('<span class="text-muted">Not scheduled</span>');
402
+ }
403
+
404
+ // Tags
405
+ const tagsContainer = $("#jobDetailsTags");
406
+ tagsContainer.empty();
407
+ if (job.tags && job.tags.length > 0) {
408
+ job.tags.forEach(tag => {
409
+ const color = pickColor(tag);
410
+ tagsContainer.append($(`<span class="badge me-1" style="background-color: ${color}"/>`).text(tag));
411
+ });
412
+ } else {
413
+ tagsContainer.html('<span class="text-muted">None</span>');
414
+ }
415
+
416
+ // Status alerts
417
+ const statusDiv = $("#jobDetailsStatus");
418
+ statusDiv.hide().removeClass("alert-danger alert-warning alert-success");
419
+
420
+ if (!job.crew || !job.startDate) {
421
+ statusDiv.addClass("alert-danger").text("This job is not assigned to any crew.").show();
422
+ } else {
423
+ const beforeReady = JSJoda.LocalDate.parse(job.startDate).isBefore(JSJoda.LocalDate.parse(job.minStartDate));
424
+ const afterDue = JSJoda.LocalDate.parse(job.endDate).isAfter(JSJoda.LocalDate.parse(job.maxEndDate));
425
+ const afterIdeal = JSJoda.LocalDate.parse(job.endDate).isAfter(JSJoda.LocalDate.parse(job.idealEndDate));
426
+
427
+ if (beforeReady) {
428
+ statusDiv.addClass("alert-warning").text("Scheduled before ready date (too early).").show();
429
+ } else if (afterDue) {
430
+ statusDiv.addClass("alert-danger").text("Scheduled after due date (too late).").show();
431
+ } else if (afterIdeal) {
432
+ statusDiv.addClass("alert-warning").text("Ends after ideal date.").show();
433
+ } else {
434
+ statusDiv.addClass("alert-success").text("Scheduled within ideal window.").show();
435
+ }
436
+ }
437
+
438
+ new bootstrap.Modal("#jobDetailsModal").show();
439
+ }
440
+
441
+ // ****************************************************************************
442
+ // Crew Details Modal
443
+ // ****************************************************************************
444
+
445
+ function showCrewDetails(crewId) {
446
+ const crew = loadedSchedule.crews.find(c => c.id === crewId);
447
+ if (!crew) return;
448
+
449
+ const crewJobs = loadedSchedule.jobs.filter(j => j.crew && j.crew.id === crewId);
450
+ const totalWorkdays = crewJobs.reduce((sum, j) => sum + j.durationInDays, 0);
451
+
452
+ $("#crewDetailsName").text(crew.name);
453
+ $("#crewDetailsJobCount").text(crewJobs.length);
454
+ $("#crewDetailsWorkdays").text(totalWorkdays);
455
+
456
+ // Job list
457
+ const jobList = $("#crewDetailsJobList");
458
+ jobList.empty();
459
+
460
+ if (crewJobs.length === 0) {
461
+ jobList.append('<div class="list-group-item text-muted">No jobs assigned</div>');
462
+ } else {
463
+ crewJobs.forEach(job => {
464
+ const afterDue = job.endDate && JSJoda.LocalDate.parse(job.endDate).isAfter(JSJoda.LocalDate.parse(job.maxEndDate));
465
+ const statusIcon = afterDue ?
466
+ '<i class="fas fa-exclamation-triangle text-danger me-2"></i>' :
467
+ '<i class="fas fa-check-circle text-success me-2"></i>';
468
+
469
+ const item = $(`
470
+ <a href="#" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
471
+ <div>
472
+ ${statusIcon}
473
+ <strong>${job.name}</strong>
474
+ <small class="text-muted ms-2">${job.durationInDays} days</small>
475
+ </div>
476
+ <small class="text-muted">${job.startDate || 'Not scheduled'}</small>
477
+ </a>
478
+ `);
479
+ item.click((e) => {
480
+ e.preventDefault();
481
+ bootstrap.Modal.getInstance(document.getElementById('crewDetailsModal')).hide();
482
+ setTimeout(() => showJobDetails(job.id), 300);
483
+ });
484
+ jobList.append(item);
485
+ });
486
+ }
487
+
488
+ new bootstrap.Modal("#crewDetailsModal").show();
489
+ }
490
+
491
+ // ****************************************************************************
492
+ // Crew Highlighting
493
+ // ****************************************************************************
494
+
495
+ function renderCrewTable(schedule) {
496
+ const crewTableBody = $("#crewTableBody");
497
+ crewTableBody.empty();
498
+
499
+ schedule.crews.forEach(crew => {
500
+ const crewJobs = schedule.jobs.filter(j => j.crew && j.crew.id === crew.id);
501
+ const totalWorkdays = crewJobs.reduce((sum, j) => sum + j.durationInDays, 0);
502
+ const color = pickColor("crew" + crew.id);
503
+
504
+ const row = $(`
505
+ <tr class="crew-row" data-crew-id="${crew.id}">
506
+ <td>
507
+ <div class="crew-color-indicator" style="background-color: ${color};">
508
+ <i class="fas fa-hard-hat"></i>
509
+ </div>
510
+ </td>
511
+ <td><strong>${crew.name}</strong></td>
512
+ <td>${crewJobs.length}</td>
513
+ <td>${totalWorkdays}</td>
514
+ <td>
515
+ <button class="btn btn-sm btn-outline-secondary crew-info-btn" title="View details">
516
+ <i class="fas fa-info-circle"></i>
517
+ </button>
518
+ </td>
519
+ </tr>
520
+ `);
521
+
522
+ // Click row to highlight
523
+ row.click((e) => {
524
+ if (!$(e.target).closest('.crew-info-btn').length) {
525
+ toggleCrewHighlight(crew.id);
526
+ }
527
+ });
528
+
529
+ // Click info button to show details
530
+ row.find('.crew-info-btn').click((e) => {
531
+ e.stopPropagation();
532
+ showCrewDetails(crew.id);
533
+ });
534
+
535
+ crewTableBody.append(row);
536
+ });
537
+ }
538
+
539
+ function toggleCrewHighlight(crewId) {
540
+ if (highlightedCrewId === crewId) {
541
+ clearCrewHighlight();
542
+ } else {
543
+ highlightCrew(crewId);
544
+ }
545
+ }
546
+
547
+ function clearCrewHighlight() {
548
+ highlightedCrewId = null;
549
+ $(".crew-row").removeClass("table-active");
550
+
551
+ // Reset timeline item opacity in both views
552
+ byCrewItemData.forEach(item => {
553
+ if (item.originalStyle !== undefined) {
554
+ byCrewItemData.update({ id: item.id, style: item.originalStyle });
555
+ }
556
+ });
557
+ byJobItemData.forEach(item => {
558
+ if (item.originalStyle !== undefined) {
559
+ byJobItemData.update({ id: item.id, style: item.originalStyle });
560
+ }
561
+ });
562
+ }
563
+
564
+ function highlightCrew(crewId) {
565
+ highlightedCrewId = crewId;
566
+
567
+ // Highlight table row
568
+ $(".crew-row").removeClass("table-active");
569
+ $(`[data-crew-id="${crewId}"]`).addClass("table-active");
570
+
571
+ // Dim non-highlighted timeline items in "By crew" view
572
+ byCrewItemData.forEach(item => {
573
+ if (item.originalStyle === undefined) {
574
+ item.originalStyle = item.style || "";
575
+ }
576
+ if (item.group !== crewId) {
577
+ byCrewItemData.update({
578
+ id: item.id,
579
+ style: item.originalStyle + "; opacity: 0.25;"
580
+ });
581
+ } else {
582
+ byCrewItemData.update({
583
+ id: item.id,
584
+ style: item.originalStyle
585
+ });
586
+ }
587
+ });
588
+
589
+ // Dim non-highlighted timeline items in "By job" view
590
+ byJobItemData.forEach(item => {
591
+ if (item.originalStyle === undefined) {
592
+ item.originalStyle = item.style || "";
593
+ }
594
+ // Check if this job belongs to the highlighted crew
595
+ if (item.crewId !== crewId && item.type !== "background") {
596
+ byJobItemData.update({
597
+ id: item.id,
598
+ style: item.originalStyle + "; opacity: 0.25;"
599
+ });
600
+ } else if (item.type !== "background") {
601
+ byJobItemData.update({
602
+ id: item.id,
603
+ style: item.originalStyle
604
+ });
605
+ }
606
+ });
607
+ }
static/index.html ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta http-equiv="content-type" content="text/html; charset=UTF-8">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
7
+ <title>Maintenance Scheduling - SolverForge for Python</title>
8
+
9
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css">
10
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
11
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vis-timeline@7.7.2/styles/vis-timeline-graph2d.min.css"
12
+ integrity="sha256-svzNasPg1yR5gvEaRei2jg+n4Pc3sVyMUWeS6xRAh6U=" crossorigin="anonymous">
13
+ <link rel="stylesheet" href="/webjars/solverforge/css/solverforge-webui.css"/>
14
+ <link rel="icon" href="/webjars/solverforge/img/solverforge-favicon.svg" type="image/svg+xml">
15
+ <style>
16
+ /* Weekend highlighting */
17
+ .vis-time-axis .vis-grid.vis-saturday,
18
+ .vis-time-axis .vis-grid.vis-sunday {
19
+ background: #D3D7CFFF;
20
+ }
21
+
22
+ /* Solving spinner animation */
23
+ #solvingSpinner {
24
+ display: none;
25
+ width: 1.25rem;
26
+ height: 1.25rem;
27
+ border: 2px solid #10b981;
28
+ border-top-color: transparent;
29
+ border-radius: 50%;
30
+ animation: spin 0.75s linear infinite;
31
+ vertical-align: middle;
32
+ }
33
+ #solvingSpinner.active {
34
+ display: inline-block;
35
+ }
36
+ @keyframes spin {
37
+ to { transform: rotate(360deg); }
38
+ }
39
+
40
+ /* Button hover effects */
41
+ .btn {
42
+ transition: all 0.2s ease;
43
+ }
44
+ #solveButton:hover {
45
+ transform: translateY(-1px);
46
+ box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
47
+ }
48
+ #stopSolvingButton:hover {
49
+ transform: translateY(-1px);
50
+ box-shadow: 0 2px 8px rgba(220, 53, 69, 0.3);
51
+ }
52
+
53
+ /* Unassigned job cards */
54
+ #unassignedJobs .card {
55
+ transition: transform 0.2s ease, box-shadow 0.2s ease;
56
+ border-left: 4px solid #ef4444;
57
+ }
58
+ #unassignedJobs .card:hover {
59
+ transform: translateY(-2px);
60
+ box-shadow: 0 4px 12px rgba(239, 68, 68, 0.2);
61
+ }
62
+
63
+ /* Crew table styling */
64
+ #crewTable tbody tr.crew-row {
65
+ cursor: pointer;
66
+ transition: background-color 0.2s ease;
67
+ }
68
+ #crewTable tbody tr.crew-row:hover {
69
+ background-color: rgba(99, 102, 241, 0.1);
70
+ }
71
+ #crewTable tbody tr.crew-row.table-active {
72
+ background-color: rgba(99, 102, 241, 0.15) !important;
73
+ }
74
+ .crew-color-indicator {
75
+ width: 1.5rem;
76
+ height: 1.5rem;
77
+ border-radius: 50%;
78
+ display: flex;
79
+ align-items: center;
80
+ justify-content: center;
81
+ }
82
+ .crew-color-indicator i {
83
+ color: white;
84
+ font-size: 0.65rem;
85
+ }
86
+
87
+ /* Timeline styling */
88
+ .vis-item .vis-item-content {
89
+ font-size: 0.85rem;
90
+ padding: 2px 4px;
91
+ }
92
+ .vis-labelset .vis-label {
93
+ padding: 4px 8px;
94
+ }
95
+ .vis-item:not(.vis-background) {
96
+ cursor: pointer;
97
+ }
98
+ .vis-item:not(.vis-background):hover {
99
+ filter: brightness(1.05);
100
+ }
101
+
102
+ /* Score analysis table hover */
103
+ #scoreAnalysisModalContent .table tbody tr {
104
+ transition: background-color 0.15s ease;
105
+ }
106
+ #scoreAnalysisModalContent .table tbody tr:hover {
107
+ background-color: rgba(99, 102, 241, 0.08);
108
+ }
109
+
110
+ /* Score display styling */
111
+ .score {
112
+ color: #1f2937;
113
+ }
114
+ </style>
115
+ </head>
116
+
117
+ <body>
118
+ <header id="solverforge-auto-header">
119
+ <!-- Filled in by app.js -->
120
+ </header>
121
+ <div class="tab-content">
122
+
123
+ <div id="demo" class="tab-pane fade show active container-fluid">
124
+ <div class="sticky-top d-flex justify-content-center align-items-center" aria-live="polite" aria-atomic="true">
125
+ <div id="notificationPanel" style="position: absolute; top: .5rem;"></div>
126
+ </div>
127
+ <h1>Road maintenance schedule solver</h1>
128
+ <p>Generate the optimal schedule for your maintenance staff.</p>
129
+
130
+ <div class="mb-2">
131
+ <button id="solveButton" type="button" class="btn btn-success">
132
+ <span class="fas fa-play"></span> Solve
133
+ </button>
134
+ <button id="stopSolvingButton" type="button" class="btn btn-danger">
135
+ <span class="fas fa-stop"></span> Stop solving
136
+ </button>
137
+ <span id="solvingSpinner" class="ms-2"></span>
138
+ <span id="score" class="score ms-2 align-middle fw-bold">Score: ?</span>
139
+ <button id="analyzeButton" type="button" class="ms-2 btn btn-secondary">
140
+ <span class="fas fa-question"></span>
141
+ </button>
142
+
143
+ <div class="float-end">
144
+ <ul class="nav nav-pills" role="tablist">
145
+ <li class="nav-item" role="presentation">
146
+ <button class="nav-link active" id="byCrewTab" data-bs-toggle="tab" data-bs-target="#byCrewPanel" type="button" role="tab" aria-controls="byCrewPanel" aria-selected="true">By crew</button>
147
+ </li>
148
+ <li class="nav-item" role="presentation">
149
+ <button class="nav-link" id="byJobTab" data-bs-toggle="tab" data-bs-target="#byJobPanel" type="button" role="tab" aria-controls="byJobPanel" aria-selected="false">By job</button>
150
+ </li>
151
+ </ul>
152
+ </div>
153
+ </div>
154
+ <div class="row mb-4">
155
+ <div class="col-md-3">
156
+ <h5>Crews <small class="text-muted"><i class="fas fa-hand-pointer"></i> Click to highlight</small></h5>
157
+ <table class="table table-sm" id="crewTable">
158
+ <thead>
159
+ <tr>
160
+ <th style="width: 2rem;"></th>
161
+ <th>Crew</th>
162
+ <th>Jobs</th>
163
+ <th>Days</th>
164
+ <th style="width: 2.5rem;"></th>
165
+ </tr>
166
+ </thead>
167
+ <tbody id="crewTableBody"></tbody>
168
+ </table>
169
+ </div>
170
+ <div class="col-md-9">
171
+ <div class="tab-content">
172
+ <div class="tab-pane fade show active" id="byCrewPanel" role="tabpanel" aria-labelledby="byCrewTab">
173
+ </div>
174
+ <div class="tab-pane fade" id="byJobPanel" role="tabpanel" aria-labelledby="byJobTab">
175
+ </div>
176
+ </div>
177
+ </div>
178
+ </div>
179
+
180
+ <h2>Unassigned jobs</h2>
181
+ <div id="unassignedJobs" class="row row-cols-3 g-3 mb-4"></div>
182
+ </div>
183
+
184
+ <div id="rest" class="tab-pane fade container-fluid">
185
+ <h1>REST API Guide</h1>
186
+
187
+ <h2>Maintenance Scheduling solver integration via cURL</h2>
188
+
189
+ <h3>1. Download demo data</h3>
190
+ <pre>
191
+ <button class="btn btn-outline-dark btn-sm float-end"
192
+ onclick="copyTextToClipboard('curl1')">Copy</button>
193
+ <code id="curl1">curl -X GET -H 'Accept:application/json' http://localhost:8080/demo-data/SMALL -o sample.json</code>
194
+ </pre>
195
+
196
+ <h3>2. Post the sample data for solving</h3>
197
+ <p>The POST operation returns a <code>jobId</code> that should be used in subsequent commands.</p>
198
+ <pre>
199
+ <button class="btn btn-outline-dark btn-sm float-end"
200
+ onclick="copyTextToClipboard('curl2')">Copy</button>
201
+ <code id="curl2">curl -X POST -H 'Content-Type:application/json' http://localhost:8080/schedules -d@sample.json</code>
202
+ </pre>
203
+
204
+ <h3>3. Get the current status and score</h3>
205
+ <pre>
206
+ <button class="btn btn-outline-dark btn-sm float-end"
207
+ onclick="copyTextToClipboard('curl3')">Copy</button>
208
+ <code id="curl3">curl -X GET -H 'Accept:application/json' http://localhost:8080/schedules/{jobId}/status</code>
209
+ </pre>
210
+
211
+ <h3>4. Get the complete solution</h3>
212
+ <pre>
213
+ <button class="btn btn-outline-dark btn-sm float-end"
214
+ onclick="copyTextToClipboard('curl4')">Copy</button>
215
+ <code id="curl4">curl -X GET -H 'Accept:application/json' http://localhost:8080/schedules/{jobId}</code>
216
+ </pre>
217
+
218
+ <h3>5. Fetch the analysis of the solution</h3>
219
+ <pre>
220
+ <button class="btn btn-outline-dark btn-sm float-end"
221
+ onclick="copyTextToClipboard('curl5')">Copy</button>
222
+ <code id="curl5">curl -X PUT -H 'Content-Type:application/json' http://localhost:8080/schedules/analyze -d@solution.json</code>
223
+ </pre>
224
+
225
+ <h3>6. Terminate solving early</h3>
226
+ <pre>
227
+ <button class="btn btn-outline-dark btn-sm float-end"
228
+ onclick="copyTextToClipboard('curl6')">Copy</button>
229
+ <code id="curl6">curl -X DELETE -H 'Accept:application/json' http://localhost:8080/schedules/{jobId}</code>
230
+ </pre>
231
+ </div>
232
+
233
+ <div id="openapi" class="tab-pane fade container-fluid">
234
+ <h1>REST API Reference</h1>
235
+ <div class="ratio ratio-1x1">
236
+ <!-- "scrolling" attribute is obsolete, but e.g. Chrome does not support "overflow:hidden" -->
237
+ <iframe src="/q/swagger-ui" style="overflow:hidden;" scrolling="no"></iframe>
238
+ </div>
239
+ </div>
240
+ </div>
241
+ <footer id="solverforge-auto-footer"></footer>
242
+ <div class="modal fadebd-example-modal-lg" id="scoreAnalysisModal" tabindex="-1"
243
+ aria-labelledby="scoreAnalysisModalLabel" aria-hidden="true">
244
+ <div class="modal-dialog modal-lg modal-dialog-scrollable">
245
+ <div class="modal-content">
246
+ <div class="modal-header">
247
+ <h1 class="modal-title fs-5" id="scoreAnalysisModalLabel">Score analysis <span
248
+ id="scoreAnalysisScoreLabel"></span></h1>
249
+
250
+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
251
+ </div>
252
+ <div class="modal-body" id="scoreAnalysisModalContent">
253
+ <!-- Filled in by app.js -->
254
+ </div>
255
+ <div class="modal-footer">
256
+ <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
257
+ </div>
258
+ </div>
259
+ </div>
260
+ </div>
261
+
262
+ <!-- Job Details Modal -->
263
+ <div class="modal fade" id="jobDetailsModal" tabindex="-1" aria-labelledby="jobDetailsModalLabel" aria-hidden="true">
264
+ <div class="modal-dialog">
265
+ <div class="modal-content">
266
+ <div class="modal-header">
267
+ <h5 class="modal-title" id="jobDetailsModalLabel">
268
+ <i class="fas fa-wrench me-2"></i><span id="jobDetailsName"></span>
269
+ </h5>
270
+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
271
+ </div>
272
+ <div class="modal-body">
273
+ <div class="row mb-3">
274
+ <div class="col-6">
275
+ <small class="text-muted">Assigned Crew</small>
276
+ <div id="jobDetailsCrew" class="fw-bold"></div>
277
+ </div>
278
+ <div class="col-6">
279
+ <small class="text-muted">Duration</small>
280
+ <div id="jobDetailsDuration" class="fw-bold"></div>
281
+ </div>
282
+ </div>
283
+ <div class="row mb-3">
284
+ <div class="col-6">
285
+ <small class="text-muted">Ready Date</small>
286
+ <div id="jobDetailsMinStart"></div>
287
+ </div>
288
+ <div class="col-6">
289
+ <small class="text-muted">Due Date</small>
290
+ <div id="jobDetailsMaxEnd"></div>
291
+ </div>
292
+ </div>
293
+ <div class="row mb-3">
294
+ <div class="col-6">
295
+ <small class="text-muted">Ideal End Date</small>
296
+ <div id="jobDetailsIdealEnd"></div>
297
+ </div>
298
+ <div class="col-6">
299
+ <small class="text-muted">Scheduled</small>
300
+ <div id="jobDetailsScheduled"></div>
301
+ </div>
302
+ </div>
303
+ <div class="mb-3">
304
+ <small class="text-muted">Tags</small>
305
+ <div id="jobDetailsTags"></div>
306
+ </div>
307
+ <div id="jobDetailsStatus" class="alert mb-0" style="display: none;"></div>
308
+ </div>
309
+ <div class="modal-footer">
310
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
311
+ </div>
312
+ </div>
313
+ </div>
314
+ </div>
315
+
316
+ <!-- Crew Details Modal -->
317
+ <div class="modal fade" id="crewDetailsModal" tabindex="-1" aria-labelledby="crewDetailsModalLabel" aria-hidden="true">
318
+ <div class="modal-dialog">
319
+ <div class="modal-content">
320
+ <div class="modal-header">
321
+ <h5 class="modal-title" id="crewDetailsModalLabel">
322
+ <i class="fas fa-hard-hat me-2"></i><span id="crewDetailsName"></span>
323
+ </h5>
324
+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
325
+ </div>
326
+ <div class="modal-body">
327
+ <div class="row mb-3">
328
+ <div class="col-6">
329
+ <small class="text-muted">Assigned Jobs</small>
330
+ <div id="crewDetailsJobCount" class="fw-bold fs-4"></div>
331
+ </div>
332
+ <div class="col-6">
333
+ <small class="text-muted">Total Workdays</small>
334
+ <div id="crewDetailsWorkdays" class="fw-bold fs-4"></div>
335
+ </div>
336
+ </div>
337
+ <h6>Assigned Jobs</h6>
338
+ <div id="crewDetailsJobList" class="list-group list-group-flush"></div>
339
+ </div>
340
+ <div class="modal-footer">
341
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
342
+ </div>
343
+ </div>
344
+ </div>
345
+ </div>
346
+
347
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
348
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js"></script>
349
+ <script src="https://cdn.jsdelivr.net/npm/@js-joda/core@5.6.3/dist/js-joda.min.js"></script>
350
+ <script src="/webjars/solverforge/js/solverforge-webui.js"></script>
351
+ <script src="https://cdn.jsdelivr.net/npm/vis-timeline@7.7.2/standalone/umd/vis-timeline-graph2d.min.js"
352
+ integrity="sha256-Jy2+UO7rZ2Dgik50z3XrrNpnc5+2PAx9MhL2CicodME=" crossorigin="anonymous"></script>
353
+ <script src="/score-analysis.js"></script>
354
+ <script src="/app.js"></script>
355
+ </body>
356
+ </html>
static/score-analysis.js ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function analyzeScore(solution, endpointPath) {
2
+ const modalElement = document.getElementById("scoreAnalysisModal");
3
+ const modal = bootstrap.Modal.getOrCreateInstance(modalElement);
4
+ modal.show();
5
+ const scoreAnalysisModalContent = $("#scoreAnalysisModalContent");
6
+ scoreAnalysisModalContent.children().remove();
7
+ scoreAnalysisModalContent.text("");
8
+
9
+ if (solution.score == null) {
10
+ scoreAnalysisModalContent.text("Score not ready for analysis, try to run the solver first or wait until it advances.");
11
+ } else {
12
+ visualizeScoreAnalysis(scoreAnalysisModalContent, solution, endpointPath)
13
+ }
14
+ }
15
+
16
+ function visualizeScoreAnalysis(scoreAnalysisModalContent, solution, endpointPath) {
17
+ $('#scoreAnalysisScoreLabel').text(`(${solution.score})`);
18
+ $.put(endpointPath, JSON.stringify(solution), function (scoreAnalysis) {
19
+ let constraints = scoreAnalysis.constraints;
20
+ constraints.sort(compareConstraintsBySeverity);
21
+ constraints.map(addDerivedScoreAttributes);
22
+ scoreAnalysis.constraints = constraints;
23
+
24
+ const analysisTable = $(`<table class="table"/>`).css({textAlign: 'center'});
25
+ const analysisTHead = $(`<thead/>`).append($(`<tr/>`)
26
+ .append($(`<th></th>`))
27
+ .append($(`<th>Constraint</th>`).css({textAlign: 'left'}))
28
+ .append($(`<th>Type</th>`))
29
+ .append($(`<th># Matches</th>`))
30
+ .append($(`<th>Weight</th>`))
31
+ .append($(`<th>Score</th>`))
32
+ .append($(`<th></th>`)));
33
+ analysisTable.append(analysisTHead);
34
+ const analysisTBody = $(`<tbody/>`)
35
+ $.each(scoreAnalysis.constraints, function (index, constraintAnalysis) {
36
+ visualizeConstraintAnalysis(analysisTBody, index, constraintAnalysis)
37
+ });
38
+ analysisTable.append(analysisTBody);
39
+ scoreAnalysisModalContent.append(analysisTable);
40
+ }).fail(function (xhr, ajaxOptions, thrownError) {
41
+ showError("Score analysis failed.", xhr);
42
+ },
43
+ "text");
44
+ }
45
+
46
+ function compareConstraintsBySeverity(a, b) {
47
+ let aComponents = getScoreComponents(a.score), bComponents = getScoreComponents(b.score);
48
+ if (aComponents.hard < 0 && bComponents.hard > 0) return -1;
49
+ if (aComponents.hard > 0 && bComponents.soft < 0) return 1;
50
+ if (Math.abs(aComponents.hard) > Math.abs(bComponents.hard)) {
51
+ return -1;
52
+ } else {
53
+ if (aComponents.medium < 0 && bComponents.medium > 0) return -1;
54
+ if (aComponents.medium > 0 && bComponents.medium < 0) return 1;
55
+ if (Math.abs(aComponents.medium) > Math.abs(bComponents.medium)) {
56
+ return -1;
57
+ } else {
58
+ if (aComponents.soft < 0 && bComponents.soft > 0) return -1;
59
+ if (aComponents.soft > 0 && bComponents.soft < 0) return 1;
60
+
61
+ return Math.abs(bComponents.soft) - Math.abs(aComponents.soft);
62
+ }
63
+ }
64
+ }
65
+
66
+ function addDerivedScoreAttributes(constraint) {
67
+ let components = getScoreComponents(constraint.weight);
68
+ constraint.type = components.hard != 0 ? 'hard' : (components.medium != 0 ? 'medium' : 'soft');
69
+ constraint.weight = components[constraint.type];
70
+ let scores = getScoreComponents(constraint.score);
71
+ constraint.implicitScore = scores.hard != 0 ? scores.hard : (scores.medium != 0 ? scores.medium : scores.soft);
72
+ }
73
+
74
+ function getScoreComponents(score) {
75
+ let components = {hard: 0, medium: 0, soft: 0};
76
+
77
+ $.each([...score.matchAll(/(-?[0-9]+)(hard|medium|soft)/g)], function (i, parts) {
78
+ components[parts[2]] = parseInt(parts[1], 10);
79
+ });
80
+
81
+ return components;
82
+ }
83
+
84
+ function visualizeConstraintAnalysis(analysisTBody, constraintIndex, constraintAnalysis, recommendation = false, recommendationIndex = null) {
85
+ let icon = constraintAnalysis.type == "hard" && constraintAnalysis.implicitScore < 0 ? '<span class="fas fa-exclamation-triangle" style="color: red"></span>' : '';
86
+ if (!icon) icon = constraintAnalysis.weight < 0 && constraintAnalysis.matches.length == 0 ? '<span class="fas fa-check-circle" style="color: green"></span>' : '';
87
+
88
+ let row = $(`<tr/>`);
89
+ row.append($(`<td/>`).html(icon))
90
+ .append($(`<td/>`).text(constraintAnalysis.name).css({textAlign: 'left'}))
91
+ .append($(`<td/>`).text(constraintAnalysis.type))
92
+ .append($(`<td/>`).html(`<b>${constraintAnalysis.matches.length}</b>`))
93
+ .append($(`<td/>`).text(constraintAnalysis.weight))
94
+ .append($(`<td/>`).text(recommendation ? constraintAnalysis.score : constraintAnalysis.implicitScore));
95
+
96
+ analysisTBody.append(row);
97
+ row.append($(`<td/>`));
98
+ }
static/webjars/solverforge/css/solverforge-webui.css ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ /* Keep in sync with .navbar height on a large screen. */
3
+ --ts-navbar-height: 109px;
4
+
5
+ --ts-green-1-rgb: #10b981;
6
+ --ts-green-2-rgb: #059669;
7
+ --ts-violet-1-rgb: #3E00FF;
8
+ --ts-violet-2-rgb: #3423A6;
9
+ --ts-violet-3-rgb: #2E1760;
10
+ --ts-violet-4-rgb: #200F4F;
11
+ --ts-violet-5-rgb: #000000; /* TODO FIXME */
12
+ --ts-violet-dark-1-rgb: #b6adfd;
13
+ --ts-violet-dark-2-rgb: #c1bbfd;
14
+ --ts-gray-rgb: #666666;
15
+ --ts-white-rgb: #FFFFFF;
16
+ --ts-light-rgb: #F2F2F2;
17
+ --ts-gray-border: #c5c5c5;
18
+
19
+ --tf-light-rgb-transparent: rgb(242,242,242,0.5); /* #F2F2F2 = rgb(242,242,242) */
20
+ --bs-body-bg: var(--ts-light-rgb); /* link to html bg */
21
+ --bs-link-color: var(--ts-violet-1-rgb);
22
+ --bs-link-hover-color: var(--ts-violet-2-rgb);
23
+
24
+ --bs-navbar-color: var(--ts-white-rgb);
25
+ --bs-navbar-hover-color: var(--ts-white-rgb);
26
+ --bs-nav-link-font-size: 18px;
27
+ --bs-nav-link-font-weight: 400;
28
+ --bs-nav-link-color: var(--ts-white-rgb);
29
+ --ts-nav-link-hover-border-color: var(--ts-violet-1-rgb);
30
+ }
31
+ .btn {
32
+ --bs-btn-border-radius: 1.5rem;
33
+ }
34
+ .btn-primary {
35
+ --bs-btn-bg: var(--ts-violet-1-rgb);
36
+ --bs-btn-border-color: var(--ts-violet-1-rgb);
37
+ --bs-btn-hover-bg: var(--ts-violet-2-rgb);
38
+ --bs-btn-hover-border-color: var(--ts-violet-2-rgb);
39
+ --bs-btn-active-bg: var(--ts-violet-2-rgb);
40
+ --bs-btn-active-border-bg: var(--ts-violet-2-rgb);
41
+ --bs-btn-disabled-bg: var(--ts-violet-1-rgb);
42
+ --bs-btn-disabled-border-color: var(--ts-violet-1-rgb);
43
+ }
44
+ .btn-outline-primary {
45
+ --bs-btn-color: var(--ts-violet-1-rgb);
46
+ --bs-btn-border-color: var(--ts-violet-1-rgb);
47
+ --bs-btn-hover-bg: var(--ts-violet-1-rgb);
48
+ --bs-btn-hover-border-color: var(--ts-violet-1-rgb);
49
+ --bs-btn-active-bg: var(--ts-violet-1-rgb);
50
+ --bs-btn-active-border-color: var(--ts-violet-1-rgb);
51
+ --bs-btn-disabled-color: var(--ts-violet-1-rgb);
52
+ --bs-btn-disabled-border-color: var(--ts-violet-1-rgb);
53
+ }
54
+ .navbar-dark {
55
+ --bs-link-color: var(--ts-violet-dark-1-rgb);
56
+ --bs-link-hover-color: var(--ts-violet-dark-2-rgb);
57
+ --bs-navbar-color: var(--ts-white-rgb);
58
+ --bs-navbar-hover-color: var(--ts-white-rgb);
59
+ }
60
+ .nav-pills {
61
+ --bs-nav-pills-link-active-bg: var(--ts-green-1-rgb);
62
+ }
63
+ .nav-pills .nav-link:hover {
64
+ color: var(--ts-green-1-rgb);
65
+ }
66
+ .nav-pills .nav-link.active:hover {
67
+ color: var(--ts-white-rgb);
68
+ }
static/webjars/solverforge/img/solverforge-favicon.svg ADDED
static/webjars/solverforge/img/solverforge-horizontal-white.svg ADDED
static/webjars/solverforge/img/solverforge-horizontal.svg ADDED
static/webjars/solverforge/img/solverforge-logo-stacked.svg ADDED
static/webjars/solverforge/js/solverforge-webui.js ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function replaceSolverForgeAutoHeaderFooter() {
2
+ const solverforgeHeader = $("header#solverforge-auto-header");
3
+ if (solverforgeHeader != null) {
4
+ solverforgeHeader.css("background-color", "#ffffff");
5
+ solverforgeHeader.append(
6
+ $(`<div class="container-fluid">
7
+ <nav class="navbar sticky-top navbar-expand-lg shadow-sm mb-3" style="background-color: #ffffff;">
8
+ <a class="navbar-brand" href="https://www.solverforge.org">
9
+ <img src="/webjars/solverforge/img/solverforge-horizontal.svg" alt="SolverForge logo" width="400">
10
+ </a>
11
+ </nav>
12
+ </div>`));
13
+ }
14
+ const solverforgeFooter = $("footer#solverforge-auto-footer");
15
+ if (solverforgeFooter != null) {
16
+ solverforgeFooter.append(
17
+ $(`<footer class="bg-light text-muted">
18
+ <div class="container">
19
+ <div class="hstack gap-3 p-4">
20
+ <div class="ms-auto"><a class="text-white" href="https://www.solverforge.org">SolverForge</a></div>
21
+ <div class="vr"></div>
22
+ <div><a class="text-white" href="https://www.solverforge.org/docs">Documentation</a></div>
23
+ <div class="vr"></div>
24
+ <div><a class="text-white" href="https://github.com/SolverForge/solverforge-legacy">Code</a></div>
25
+ <div class="vr"></div>
26
+ <div class="me-auto"><a class="text-white" href="mailto:info@solverforge.org">Support</a></div>
27
+ </div>
28
+ </div>
29
+ <div id="applicationInfo" class="container text-center"></div>
30
+ </footer>`));
31
+
32
+ applicationInfo();
33
+ }
34
+
35
+ }
36
+
37
+ function showSimpleError(title) {
38
+ const notification = $(`<div class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="min-width: 50rem"/>`)
39
+ .append($(`<div class="toast-header bg-danger">
40
+ <strong class="me-auto text-dark">Error</strong>
41
+ <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
42
+ </div>`))
43
+ .append($(`<div class="toast-body"/>`)
44
+ .append($(`<p/>`).text(title))
45
+ );
46
+ $("#notificationPanel").append(notification);
47
+ notification.toast({delay: 30000});
48
+ notification.toast('show');
49
+ }
50
+
51
+ function showError(title, xhr) {
52
+ var serverErrorMessage = !xhr.responseJSON ? `${xhr.status}: ${xhr.statusText}` : xhr.responseJSON.message;
53
+ var serverErrorCode = !xhr.responseJSON ? `unknown` : xhr.responseJSON.code;
54
+ var serverErrorId = !xhr.responseJSON ? `----` : xhr.responseJSON.id;
55
+ var serverErrorDetails = !xhr.responseJSON ? `no details provided` : xhr.responseJSON.details;
56
+
57
+ if (xhr.responseJSON && !serverErrorMessage) {
58
+ serverErrorMessage = JSON.stringify(xhr.responseJSON);
59
+ serverErrorCode = xhr.statusText + '(' + xhr.status + ')';
60
+ serverErrorId = `----`;
61
+ }
62
+
63
+ console.error(title + "\n" + serverErrorMessage + " : " + serverErrorDetails);
64
+ const notification = $(`<div class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="min-width: 50rem"/>`)
65
+ .append($(`<div class="toast-header bg-danger">
66
+ <strong class="me-auto text-dark">Error</strong>
67
+ <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
68
+ </div>`))
69
+ .append($(`<div class="toast-body"/>`)
70
+ .append($(`<p/>`).text(title))
71
+ .append($(`<pre/>`)
72
+ .append($(`<code/>`).text(serverErrorMessage + "\n\nCode: " + serverErrorCode + "\nError id: " + serverErrorId))
73
+ )
74
+ );
75
+ $("#notificationPanel").append(notification);
76
+ notification.toast({delay: 30000});
77
+ notification.toast('show');
78
+ }
79
+
80
+ // ****************************************************************************
81
+ // Application info
82
+ // ****************************************************************************
83
+
84
+ function applicationInfo() {
85
+ $.getJSON("info", function (info) {
86
+ $("#applicationInfo").append("<small>" + info.application + " (version: " + info.version + ", built at: " + info.built + ")</small>");
87
+ }).fail(function (xhr, ajaxOptions, thrownError) {
88
+ console.warn("Unable to collect application information");
89
+ });
90
+ }
91
+
92
+ // ****************************************************************************
93
+ // TangoColorFactory
94
+ // ****************************************************************************
95
+
96
+ const SEQUENCE_1 = [0x8AE234, 0xFCE94F, 0x729FCF, 0xE9B96E, 0xAD7FA8];
97
+ const SEQUENCE_2 = [0x73D216, 0xEDD400, 0x3465A4, 0xC17D11, 0x75507B];
98
+
99
+ var colorMap = new Map;
100
+ var nextColorCount = 0;
101
+
102
+ function pickColor(object) {
103
+ let color = colorMap[object];
104
+ if (color !== undefined) {
105
+ return color;
106
+ }
107
+ color = nextColor();
108
+ colorMap[object] = color;
109
+ return color;
110
+ }
111
+
112
+ function nextColor() {
113
+ let color;
114
+ let colorIndex = nextColorCount % SEQUENCE_1.length;
115
+ let shadeIndex = Math.floor(nextColorCount / SEQUENCE_1.length);
116
+ if (shadeIndex === 0) {
117
+ color = SEQUENCE_1[colorIndex];
118
+ } else if (shadeIndex === 1) {
119
+ color = SEQUENCE_2[colorIndex];
120
+ } else {
121
+ shadeIndex -= 3;
122
+ let floorColor = SEQUENCE_2[colorIndex];
123
+ let ceilColor = SEQUENCE_1[colorIndex];
124
+ let base = Math.floor((shadeIndex / 2) + 1);
125
+ let divisor = 2;
126
+ while (base >= divisor) {
127
+ divisor *= 2;
128
+ }
129
+ base = (base * 2) - divisor + 1;
130
+ let shadePercentage = base / divisor;
131
+ color = buildPercentageColor(floorColor, ceilColor, shadePercentage);
132
+ }
133
+ nextColorCount++;
134
+ return "#" + color.toString(16);
135
+ }
136
+
137
+ function buildPercentageColor(floorColor, ceilColor, shadePercentage) {
138
+ let red = (floorColor & 0xFF0000) + Math.floor(shadePercentage * ((ceilColor & 0xFF0000) - (floorColor & 0xFF0000))) & 0xFF0000;
139
+ let green = (floorColor & 0x00FF00) + Math.floor(shadePercentage * ((ceilColor & 0x00FF00) - (floorColor & 0x00FF00))) & 0x00FF00;
140
+ let blue = (floorColor & 0x0000FF) + Math.floor(shadePercentage * ((ceilColor & 0x0000FF) - (floorColor & 0x0000FF))) & 0x0000FF;
141
+ return red | green | blue;
142
+ }
static/webjars/timefold/css/timefold-webui.css ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ /* Keep in sync with .navbar height on a large screen. */
3
+ --ts-navbar-height: 109px;
4
+
5
+ --ts-violet-1-rgb: #3E00FF;
6
+ --ts-violet-2-rgb: #3423A6;
7
+ --ts-violet-3-rgb: #2E1760;
8
+ --ts-violet-4-rgb: #200F4F;
9
+ --ts-violet-5-rgb: #000000; /* TODO FIXME */
10
+ --ts-violet-dark-1-rgb: #b6adfd;
11
+ --ts-violet-dark-2-rgb: #c1bbfd;
12
+ --ts-gray-rgb: #666666;
13
+ --ts-white-rgb: #FFFFFF;
14
+ --ts-light-rgb: #F2F2F2;
15
+ --ts-gray-border: #c5c5c5;
16
+
17
+ --tf-light-rgb-transparent: rgb(242,242,242,0.5); /* #F2F2F2 = rgb(242,242,242) */
18
+ --bs-body-bg: var(--ts-light-rgb); /* link to html bg */
19
+ --bs-link-color: var(--ts-violet-1-rgb);
20
+ --bs-link-hover-color: var(--ts-violet-2-rgb);
21
+
22
+ --bs-navbar-color: var(--ts-white-rgb);
23
+ --bs-navbar-hover-color: var(--ts-white-rgb);
24
+ --bs-nav-link-font-size: 18px;
25
+ --bs-nav-link-font-weight: 400;
26
+ --bs-nav-link-color: var(--ts-white-rgb);
27
+ --ts-nav-link-hover-border-color: var(--ts-violet-1-rgb);
28
+ }
29
+ .btn {
30
+ --bs-btn-border-radius: 1.5rem;
31
+ }
32
+ .btn-primary {
33
+ --bs-btn-bg: var(--ts-violet-1-rgb);
34
+ --bs-btn-border-color: var(--ts-violet-1-rgb);
35
+ --bs-btn-hover-bg: var(--ts-violet-2-rgb);
36
+ --bs-btn-hover-border-color: var(--ts-violet-2-rgb);
37
+ --bs-btn-active-bg: var(--ts-violet-2-rgb);
38
+ --bs-btn-active-border-bg: var(--ts-violet-2-rgb);
39
+ --bs-btn-disabled-bg: var(--ts-violet-1-rgb);
40
+ --bs-btn-disabled-border-color: var(--ts-violet-1-rgb);
41
+ }
42
+ .btn-outline-primary {
43
+ --bs-btn-color: var(--ts-violet-1-rgb);
44
+ --bs-btn-border-color: var(--ts-violet-1-rgb);
45
+ --bs-btn-hover-bg: var(--ts-violet-1-rgb);
46
+ --bs-btn-hover-border-color: var(--ts-violet-1-rgb);
47
+ --bs-btn-active-bg: var(--ts-violet-1-rgb);
48
+ --bs-btn-active-border-color: var(--ts-violet-1-rgb);
49
+ --bs-btn-disabled-color: var(--ts-violet-1-rgb);
50
+ --bs-btn-disabled-border-color: var(--ts-violet-1-rgb);
51
+ }
52
+ .navbar-dark {
53
+ --bs-link-color: var(--ts-violet-dark-1-rgb);
54
+ --bs-link-hover-color: var(--ts-violet-dark-2-rgb);
55
+ --bs-navbar-color: var(--ts-white-rgb);
56
+ --bs-navbar-hover-color: var(--ts-white-rgb);
57
+ }
58
+ .nav-pills {
59
+ --bs-nav-pills-link-active-bg: var(--ts-violet-1-rgb);
60
+ }
static/webjars/timefold/img/timefold-favicon.svg ADDED
static/webjars/timefold/img/timefold-logo-horizontal-negative.svg ADDED
static/webjars/timefold/img/timefold-logo-horizontal-positive.svg ADDED
static/webjars/timefold/img/timefold-logo-stacked-positive.svg ADDED
static/webjars/timefold/js/timefold-webui.js ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function replaceTimefoldAutoHeaderFooter() {
2
+ const timefoldHeader = $("header#timefold-auto-header");
3
+ if (timefoldHeader != null) {
4
+ timefoldHeader.addClass("bg-black")
5
+ timefoldHeader.append(
6
+ $(`<div class="container-fluid">
7
+ <nav class="navbar sticky-top navbar-expand-lg navbar-dark shadow mb-3">
8
+ <a class="navbar-brand" href="https://timefold.ai">
9
+ <img src="/timefold/img/timefold-logo-horizontal-negative.svg" alt="Timefold logo" width="200">
10
+ </a>
11
+ </nav>
12
+ </div>`));
13
+ }
14
+ const timefoldFooter = $("footer#timefold-auto-footer");
15
+ if (timefoldFooter != null) {
16
+ timefoldFooter.append(
17
+ $(`<footer class="bg-black text-white-50">
18
+ <div class="container">
19
+ <div class="hstack gap-3 p-4">
20
+ <div class="ms-auto"><a class="text-white" href="https://timefold.ai">Timefold</a></div>
21
+ <div class="vr"></div>
22
+ <div><a class="text-white" href="https://timefold.ai/docs">Documentation</a></div>
23
+ <div class="vr"></div>
24
+ <div><a class="text-white" href="https://github.com/TimefoldAI/timefold-solver-python">Code</a></div>
25
+ <div class="vr"></div>
26
+ <div class="me-auto"><a class="text-white" href="https://timefold.ai/product/support/">Support</a></div>
27
+ </div>
28
+ </div>
29
+ <div id="applicationInfo" class="container text-center"></div>
30
+ </footer>`));
31
+
32
+ applicationInfo();
33
+ }
34
+
35
+ }
36
+
37
+ function showSimpleError(title) {
38
+ const notification = $(`<div class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="min-width: 50rem"/>`)
39
+ .append($(`<div class="toast-header bg-danger">
40
+ <strong class="me-auto text-dark">Error</strong>
41
+ <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
42
+ </div>`))
43
+ .append($(`<div class="toast-body"/>`)
44
+ .append($(`<p/>`).text(title))
45
+ );
46
+ $("#notificationPanel").append(notification);
47
+ notification.toast({delay: 30000});
48
+ notification.toast('show');
49
+ }
50
+
51
+ function showError(title, xhr) {
52
+ var serverErrorMessage = !xhr.responseJSON ? `${xhr.status}: ${xhr.statusText}` : xhr.responseJSON.message;
53
+ var serverErrorCode = !xhr.responseJSON ? `unknown` : xhr.responseJSON.code;
54
+ var serverErrorId = !xhr.responseJSON ? `----` : xhr.responseJSON.id;
55
+ var serverErrorDetails = !xhr.responseJSON ? `no details provided` : xhr.responseJSON.details;
56
+
57
+ if (xhr.responseJSON && !serverErrorMessage) {
58
+ serverErrorMessage = JSON.stringify(xhr.responseJSON);
59
+ serverErrorCode = xhr.statusText + '(' + xhr.status + ')';
60
+ serverErrorId = `----`;
61
+ }
62
+
63
+ console.error(title + "\n" + serverErrorMessage + " : " + serverErrorDetails);
64
+ const notification = $(`<div class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="min-width: 50rem"/>`)
65
+ .append($(`<div class="toast-header bg-danger">
66
+ <strong class="me-auto text-dark">Error</strong>
67
+ <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
68
+ </div>`))
69
+ .append($(`<div class="toast-body"/>`)
70
+ .append($(`<p/>`).text(title))
71
+ .append($(`<pre/>`)
72
+ .append($(`<code/>`).text(serverErrorMessage + "\n\nCode: " + serverErrorCode + "\nError id: " + serverErrorId))
73
+ )
74
+ );
75
+ $("#notificationPanel").append(notification);
76
+ notification.toast({delay: 30000});
77
+ notification.toast('show');
78
+ }
79
+
80
+ // ****************************************************************************
81
+ // Application info
82
+ // ****************************************************************************
83
+
84
+ function applicationInfo() {
85
+ $.getJSON("info", function (info) {
86
+ $("#applicationInfo").append("<small>" + info.application + " (version: " + info.version + ", built at: " + info.built + ")</small>");
87
+ }).fail(function (xhr, ajaxOptions, thrownError) {
88
+ console.warn("Unable to collect application information");
89
+ });
90
+ }
91
+
92
+ // ****************************************************************************
93
+ // TangoColorFactory
94
+ // ****************************************************************************
95
+
96
+ const SEQUENCE_1 = [0x8AE234, 0xFCE94F, 0x729FCF, 0xE9B96E, 0xAD7FA8];
97
+ const SEQUENCE_2 = [0x73D216, 0xEDD400, 0x3465A4, 0xC17D11, 0x75507B];
98
+
99
+ var colorMap = new Map;
100
+ var nextColorCount = 0;
101
+
102
+ function pickColor(object) {
103
+ let color = colorMap[object];
104
+ if (color !== undefined) {
105
+ return color;
106
+ }
107
+ color = nextColor();
108
+ colorMap[object] = color;
109
+ return color;
110
+ }
111
+
112
+ function nextColor() {
113
+ let color;
114
+ let colorIndex = nextColorCount % SEQUENCE_1.length;
115
+ let shadeIndex = Math.floor(nextColorCount / SEQUENCE_1.length);
116
+ if (shadeIndex === 0) {
117
+ color = SEQUENCE_1[colorIndex];
118
+ } else if (shadeIndex === 1) {
119
+ color = SEQUENCE_2[colorIndex];
120
+ } else {
121
+ shadeIndex -= 3;
122
+ let floorColor = SEQUENCE_2[colorIndex];
123
+ let ceilColor = SEQUENCE_1[colorIndex];
124
+ let base = Math.floor((shadeIndex / 2) + 1);
125
+ let divisor = 2;
126
+ while (base >= divisor) {
127
+ divisor *= 2;
128
+ }
129
+ base = (base * 2) - divisor + 1;
130
+ let shadePercentage = base / divisor;
131
+ color = buildPercentageColor(floorColor, ceilColor, shadePercentage);
132
+ }
133
+ nextColorCount++;
134
+ return "#" + color.toString(16);
135
+ }
136
+
137
+ function buildPercentageColor(floorColor, ceilColor, shadePercentage) {
138
+ let red = (floorColor & 0xFF0000) + Math.floor(shadePercentage * ((ceilColor & 0xFF0000) - (floorColor & 0xFF0000))) & 0xFF0000;
139
+ let green = (floorColor & 0x00FF00) + Math.floor(shadePercentage * ((ceilColor & 0x00FF00) - (floorColor & 0x00FF00))) & 0x00FF00;
140
+ let blue = (floorColor & 0x0000FF) + Math.floor(shadePercentage * ((ceilColor & 0x0000FF) - (floorColor & 0x0000FF))) & 0x0000FF;
141
+ return red | green | blue;
142
+ }
tests/__init__.py ADDED
File without changes
tests/test_constraints.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unit tests for the maintenance scheduling constraints using ConstraintVerifier.
3
+ """
4
+
5
+ from datetime import date, timedelta
6
+
7
+ from solverforge_legacy.solver.test import ConstraintVerifier
8
+
9
+ from maintenance_scheduling.domain import (
10
+ Crew,
11
+ Job,
12
+ MaintenanceSchedule,
13
+ WorkCalendar,
14
+ calculate_end_date,
15
+ )
16
+ from maintenance_scheduling.constraints import (
17
+ define_constraints,
18
+ crew_conflict,
19
+ min_start_date,
20
+ max_end_date,
21
+ before_ideal_end_date,
22
+ after_ideal_end_date,
23
+ tag_conflict,
24
+ )
25
+
26
+
27
+ # Test fixtures
28
+ CREW_A = Crew(id="A", name="Crew A")
29
+ CREW_B = Crew(id="B", name="Crew B")
30
+ START_DATE = date(2024, 1, 8) # A Monday
31
+ WORK_CALENDAR = WorkCalendar(
32
+ id="cal",
33
+ from_date=START_DATE,
34
+ to_date=START_DATE + timedelta(days=60)
35
+ )
36
+
37
+
38
+ constraint_verifier = ConstraintVerifier.build(
39
+ define_constraints, MaintenanceSchedule, Job
40
+ )
41
+
42
+
43
+ def create_job(
44
+ job_id: str,
45
+ duration: int = 3,
46
+ crew: Crew = None,
47
+ start_offset: int = 0,
48
+ tags: set = None,
49
+ min_start_offset: int = 0,
50
+ max_end_offset: int = 30,
51
+ ideal_end_offset: int = 20,
52
+ ) -> Job:
53
+ """Helper function to create a Job with computed dates."""
54
+ start = calculate_end_date(START_DATE, start_offset) if crew else None
55
+ min_start = calculate_end_date(START_DATE, min_start_offset)
56
+ max_end = calculate_end_date(START_DATE, max_end_offset)
57
+ ideal_end = calculate_end_date(START_DATE, ideal_end_offset)
58
+
59
+ return Job(
60
+ id=job_id,
61
+ name=f"Job {job_id}",
62
+ duration_in_days=duration,
63
+ min_start_date=min_start,
64
+ max_end_date=max_end,
65
+ ideal_end_date=ideal_end,
66
+ tags=tags or set(),
67
+ crew=crew,
68
+ start_date=start,
69
+ )
70
+
71
+
72
+ # ************************************************************************
73
+ # Crew conflict tests
74
+ # ************************************************************************
75
+
76
+
77
+ def test_crew_conflict_no_overlap():
78
+ """Two jobs with same crew but no time overlap should not penalize."""
79
+ # Job 1: days 0-2 (3 days)
80
+ job1 = create_job("1", duration=3, crew=CREW_A, start_offset=0)
81
+ # Job 2: days 5-7 (3 days) - no overlap
82
+ job2 = create_job("2", duration=3, crew=CREW_A, start_offset=5)
83
+
84
+ constraint_verifier.verify_that(crew_conflict).given(job1, job2).penalizes_by(0)
85
+
86
+
87
+ def test_crew_conflict_with_overlap():
88
+ """Two jobs with same crew and overlapping dates should penalize."""
89
+ # Job 1: days 0-4 (5 days)
90
+ job1 = create_job("1", duration=5, crew=CREW_A, start_offset=0)
91
+ # Job 2: days 3-7 (5 days) - overlaps on days 3-4
92
+ job2 = create_job("2", duration=5, crew=CREW_A, start_offset=3)
93
+
94
+ # Should penalize for the overlap
95
+ constraint_verifier.verify_that(crew_conflict).given(job1, job2).penalizes()
96
+
97
+
98
+ def test_different_crews_no_conflict():
99
+ """Two overlapping jobs with different crews should not penalize."""
100
+ job1 = create_job("1", duration=5, crew=CREW_A, start_offset=0)
101
+ job2 = create_job("2", duration=5, crew=CREW_B, start_offset=2)
102
+
103
+ constraint_verifier.verify_that(crew_conflict).given(job1, job2).penalizes_by(0)
104
+
105
+
106
+ # ************************************************************************
107
+ # Min start date tests
108
+ # ************************************************************************
109
+
110
+
111
+ def test_min_start_date_valid():
112
+ """Job starting on or after min start date should not penalize."""
113
+ job = create_job(
114
+ "1",
115
+ duration=3,
116
+ crew=CREW_A,
117
+ start_offset=5,
118
+ min_start_offset=0, # Can start from day 0
119
+ )
120
+
121
+ constraint_verifier.verify_that(min_start_date).given(job).penalizes_by(0)
122
+
123
+
124
+ def test_min_start_date_violation():
125
+ """Job starting before min start date should penalize."""
126
+ job = create_job(
127
+ "1",
128
+ duration=3,
129
+ crew=CREW_A,
130
+ start_offset=0,
131
+ min_start_offset=5, # Can't start until day 5
132
+ )
133
+
134
+ # Started 5 days early
135
+ constraint_verifier.verify_that(min_start_date).given(job).penalizes()
136
+
137
+
138
+ # ************************************************************************
139
+ # Max end date tests
140
+ # ************************************************************************
141
+
142
+
143
+ def test_max_end_date_valid():
144
+ """Job ending on or before max end date should not penalize."""
145
+ job = create_job(
146
+ "1",
147
+ duration=3,
148
+ crew=CREW_A,
149
+ start_offset=0,
150
+ max_end_offset=30, # Due day 30
151
+ )
152
+
153
+ constraint_verifier.verify_that(max_end_date).given(job).penalizes_by(0)
154
+
155
+
156
+ def test_max_end_date_violation():
157
+ """Job ending after max end date should penalize."""
158
+ job = create_job(
159
+ "1",
160
+ duration=10,
161
+ crew=CREW_A,
162
+ start_offset=0,
163
+ max_end_offset=5, # Due day 5, but job takes 10 days
164
+ )
165
+
166
+ constraint_verifier.verify_that(max_end_date).given(job).penalizes()
167
+
168
+
169
+ # ************************************************************************
170
+ # Before ideal end date tests
171
+ # ************************************************************************
172
+
173
+
174
+ def test_before_ideal_end_date_valid():
175
+ """Job ending at or after ideal end date should not penalize."""
176
+ job = create_job(
177
+ "1",
178
+ duration=15,
179
+ crew=CREW_A,
180
+ start_offset=0,
181
+ ideal_end_offset=10, # Ideal by day 10, job ends after
182
+ )
183
+
184
+ constraint_verifier.verify_that(before_ideal_end_date).given(job).penalizes_by(0)
185
+
186
+
187
+ def test_before_ideal_end_date_violation():
188
+ """Job ending before ideal end date should penalize."""
189
+ job = create_job(
190
+ "1",
191
+ duration=3,
192
+ crew=CREW_A,
193
+ start_offset=0,
194
+ ideal_end_offset=20, # Ideal by day 20, but job ends day 3
195
+ )
196
+
197
+ constraint_verifier.verify_that(before_ideal_end_date).given(job).penalizes()
198
+
199
+
200
+ # ************************************************************************
201
+ # After ideal end date tests
202
+ # ************************************************************************
203
+
204
+
205
+ def test_after_ideal_end_date_valid():
206
+ """Job ending at or before ideal end date should not penalize."""
207
+ job = create_job(
208
+ "1",
209
+ duration=3,
210
+ crew=CREW_A,
211
+ start_offset=0,
212
+ ideal_end_offset=20, # Ideal by day 20
213
+ )
214
+
215
+ constraint_verifier.verify_that(after_ideal_end_date).given(job).penalizes_by(0)
216
+
217
+
218
+ def test_after_ideal_end_date_violation():
219
+ """Job ending after ideal end date should penalize heavily."""
220
+ job = create_job(
221
+ "1",
222
+ duration=10,
223
+ crew=CREW_A,
224
+ start_offset=0,
225
+ ideal_end_offset=5, # Ideal by day 5, but job takes 10 days
226
+ )
227
+
228
+ constraint_verifier.verify_that(after_ideal_end_date).given(job).penalizes()
229
+
230
+
231
+ # ************************************************************************
232
+ # Tag conflict tests
233
+ # ************************************************************************
234
+
235
+
236
+ def test_tag_conflict_no_common_tags():
237
+ """Overlapping jobs with no common tags should not penalize."""
238
+ job1 = create_job("1", duration=5, crew=CREW_A, start_offset=0, tags={"Downtown"})
239
+ job2 = create_job("2", duration=5, crew=CREW_B, start_offset=2, tags={"Airport"})
240
+
241
+ constraint_verifier.verify_that(tag_conflict).given(job1, job2).penalizes_by(0)
242
+
243
+
244
+ def test_tag_conflict_with_common_tags():
245
+ """Overlapping jobs with common tags should penalize."""
246
+ job1 = create_job(
247
+ "1", duration=5, crew=CREW_A, start_offset=0,
248
+ tags={"Downtown", "Subway"}
249
+ )
250
+ job2 = create_job(
251
+ "2", duration=5, crew=CREW_B, start_offset=2,
252
+ tags={"Downtown"} # Shares "Downtown" tag
253
+ )
254
+
255
+ constraint_verifier.verify_that(tag_conflict).given(job1, job2).penalizes()
256
+
257
+
258
+ def test_tag_conflict_no_overlap():
259
+ """Non-overlapping jobs with common tags should not penalize."""
260
+ job1 = create_job("1", duration=3, crew=CREW_A, start_offset=0, tags={"Downtown"})
261
+ job2 = create_job("2", duration=3, crew=CREW_B, start_offset=10, tags={"Downtown"})
262
+
263
+ constraint_verifier.verify_that(tag_conflict).given(job1, job2).penalizes_by(0)