Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions .github/scripts/check_solver_output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
"""Checks that the packaged solver made a valid schedule.

Used by the "Build installers" workflow after each installer is built.

The solver can return a different schedule each run when several schedules are
equally good, so this doesn't compare against solver.py's exact output. It checks
the same rules as src/test/solver.test.js instead:
- the solver found a schedule (OPTIMAL or FEASIBLE)
- every server is listed, and every show and server in the output is real
- each show is inside the server's shift window
- a server's shows are far enough apart
- no show has too many servers, and every show has enough
- every server gets their minimum number of shows
- a fully staffed day gives no warnings

Usage: python check_solver_output.py <input.json> <packaged-output.json>
"""

import json
import sys


def to_minutes(hhmm):
hours, minutes = hhmm.split(":")
return int(hours) * 60 + int(minutes)


def find_problems(data, schedule):
rules, servers, shows = data["rules"], data["servers"], data["shows"]
servers_by_id = {s["id"]: s for s in servers}
shows_by_id = {m["id"]: m for m in shows}
servers_per_show = {m["id"]: 0 for m in shows}
problems = []

if schedule.get("status") not in ("OPTIMAL", "FEASIBLE"):
return [f"solver status is {schedule.get('status')}, not OPTIMAL or FEASIBLE"]

assignments = schedule.get("assignments") or []
if len(assignments) != len(servers):
problems.append(f"{len(assignments)} servers in the output, expected {len(servers)}")

for a in assignments:
server = servers_by_id.get(a["server_id"])
if server is None:
problems.append(f"unknown server in output: {a['server_id']}")
continue
earliest = to_minutes(server["shift_start"]) + rules["first_show_after_shift_start"]
latest = to_minutes(server["shift_end"]) - rules["no_show_before_shift_end"]
starts = []
for s in a["shows"]:
show = shows_by_id.get(s["show_id"])
if show is None:
problems.append(f"unknown show in output: {s['show_id']}")
continue
start = to_minutes(show["start"])
if start < earliest or start > latest:
problems.append(f"{server['name']} has {show['start']}, outside their shift window")
servers_per_show[show["id"]] += 1
starts.append((start, show["start"]))

starts.sort()
for (prev, prev_label), (cur, cur_label) in zip(starts, starts[1:]):
if cur - prev < rules["min_minutes_between_show_starts"]:
problems.append(f"{server['name']} has {prev_label} and {cur_label}, too close together")

if len(a["shows"]) < rules["min_shows_per_server"]:
problems.append(f"{server['name']} has {len(a['shows'])} shows, minimum is {rules['min_shows_per_server']}")

for show_id, count in servers_per_show.items():
if count > rules["max_servers_per_show"]:
problems.append(f"show {show_id} has {count} servers, max is {rules['max_servers_per_show']}")
if count < rules["min_servers_per_show"]:
problems.append(f"show {show_id} has {count} servers, minimum is {rules['min_servers_per_show']}")

if schedule.get("warnings"):
problems.append(f"a fully staffed day should have no warnings, got: {schedule['warnings']}")

return problems


def main():
input_path, output_path = sys.argv[1], sys.argv[2]
with open(input_path, encoding="utf-8") as f:
data = json.load(f)
with open(output_path, encoding="utf-8") as f:
schedule = json.load(f)

print("Packaged solver status:", schedule.get("status"),
"| servers scheduled:", len(schedule.get("assignments") or []))
problems = find_problems(data, schedule)
if problems:
print("FAIL: the packaged solver's schedule breaks the rules:")
for p in problems:
print(" -", p)
sys.exit(1)
print("PASS: the packaged solver made a valid schedule")


if __name__ == "__main__":
main()
19 changes: 5 additions & 14 deletions .github/workflows/build-installers.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,25 +76,16 @@ jobs:
- name: Build installer (solver bundle, app, installer)
run: npm run ${{ matrix.build }}

# Runs the solver that was packed into the app on the sample data, and checks it
# gives the same schedule as running solver.py with Python. Fails the build if not.
# Runs the solver that was packed into the app on the sample data, and checks the
# schedule follows the scheduling rules (.github/scripts/check_solver_output.py).
# It doesn't compare against solver.py's exact output: when several schedules are
# equally good, the solver can pick a different one each run.
- name: Check the packaged solver makes a schedule
shell: bash
run: |
if [ "$RUNNER_OS" = "Windows" ]; then PY=.venv/Scripts/python.exe; else PY=.venv/bin/python; fi
"${{ matrix.solver }}" < solver/sample_input.json > packaged-output.json
"$PY" solver/solver.py < solver/sample_input.json > python-output.json
"$PY" - <<'EOF'
import json, sys
packaged = json.load(open("packaged-output.json"))
python = json.load(open("python-output.json"))
print("Packaged solver status:", packaged["status"], "| servers scheduled:", len(packaged["assignments"]))
if packaged["status"] not in ("OPTIMAL", "FEASIBLE") or not packaged["assignments"]:
sys.exit("FAIL: the packaged solver did not make a schedule")
if (packaged["status"], packaged["assignments"]) != (python["status"], python["assignments"]):
sys.exit("FAIL: the packaged solver's schedule is different from solver.py's")
print("PASS: same schedule as solver.py")
EOF
"$PY" ../.github/scripts/check_solver_output.py solver/sample_input.json packaged-output.json

- name: Upload installer
uses: actions/upload-artifact@v4
Expand Down
6 changes: 3 additions & 3 deletions webdevadv/src/main/ipc.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ function fail(err) {

// Builds the handler functions from their dependencies. Kept separate from
// Electron so the logic can be unit tested with fakes.
// employees: { writeToDB(name, occupation), retrieveAllFromDB() }
// employees: { addEmployee(name, occupation), retrieveAllEmployees() } (employee/empDBLogic.js)
// pickFile: async () => file path, or null if the user cancels
// parseFile: (path) => { shows: [...] }
// saveSchedule: (scheduleJsonString) => void
Expand All @@ -32,7 +32,7 @@ export function createHandlers({ employees, pickFile, parseFile, saveSchedule, l
return {
addEmployee(employee) {
try {
const id = employees.writeToDB(employee?.name, employee?.occupation)
const id = employees.addEmployee(employee?.name, employee?.occupation)
return { ok: true, id: Number(id) }
} catch (err) {
return fail(err)
Expand All @@ -41,7 +41,7 @@ export function createHandlers({ employees, pickFile, parseFile, saveSchedule, l

getEmployees() {
try {
return { ok: true, employees: employees.retrieveAllFromDB() }
return { ok: true, employees: employees.retrieveAllEmployees() }
} catch (err) {
return fail(err)
}
Expand Down
16 changes: 12 additions & 4 deletions webdevadv/src/test/ipc.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ function fakeDeps(overrides = {}) {
saved,
deps: {
employees: {
writeToDB: (name, occupation) => {
addEmployee: (name, occupation) => {
if (!name?.trim() || !occupation?.trim()) throw new Error('Name and occupation are required')
rows.push({ id: rows.length + 1, employee_name: name, occupation })
return BigInt(rows.length)
},
retrieveAllFromDB: () => rows
retrieveAllEmployees: () => rows
},
pickFile: async () => '/fake/MovieData.xlsx',
parseFile: () => ({ shows: [{ id: 'm1', title: 'Movie 1', start: '12:30', auditorium: 1 }] }),
Expand Down Expand Up @@ -48,8 +48,8 @@ describe('employees', () => {
test('returns an error if the database is not ready', () => {
const { deps } = fakeDeps({
employees: {
writeToDB: () => {},
retrieveAllFromDB: () => {
addEmployee: () => {},
retrieveAllEmployees: () => {
throw new Error('Database not initialized')
}
}
Expand Down Expand Up @@ -137,3 +137,11 @@ test('registers one handler per channel', () => {
const channels = ipcMain.handle.mock.calls.map(([channel]) => channel)
expect(channels.sort()).toEqual(Object.values(CHANNELS).sort())
})

// Guards against renames: the real employee module must have the functions
// the IPC handlers call (a rename in empDBLogic.js broke this once).
test('the real employee module has the functions the handlers use', async () => {
const { default: employeeDB } = await import('../../employee/empDBLogic.js')
expect(typeof employeeDB.addEmployee).toBe('function')
expect(typeof employeeDB.retrieveAllEmployees).toBe('function')
})
Loading