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
18 changes: 11 additions & 7 deletions webdevadv/src/main/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,9 @@ app.whenReady().then(() => {

// IPC test
ipcMain.on('ping', () => console.log('pong'))
ipcMain.handle('solve', (_, data) => {
if (!data || !data.rules || !Array.isArray(data.servers) || !Array.isArray(data.shows)) {
return { ok: false, error: 'Invalid request: expected rules plus lists of servers and shows' }
}
return runSolver(
// Runs the solver: Python in development, the bundled program in the installed app.
const solve = (data) =>
runSolver(
data,
solverCommand({
isPackaged: app.isPackaged,
Expand All @@ -71,9 +69,14 @@ app.whenReady().then(() => {
platform: process.platform
})
)

ipcMain.handle('solve', (_, data) => {
if (!data || !data.rules || !Array.isArray(data.servers) || !Array.isArray(data.shows)) {
return { ok: false, error: 'Invalid request: expected rules plus lists of servers and shows' }
}
return solve(data)
})

// Employees, spreadsheet parser and saved schedules (see ./ipc.js)
registerIpcHandlers(ipcMain, {
employees: employeeDB,
pickFile: async () => {
Expand All @@ -85,7 +88,8 @@ app.whenReady().then(() => {
},
parseFile: (filePath) => parseSheet(XLSX.readFile(filePath, { cellDates: true })),
saveSchedule: (scheduleJson) => addToTable(scheduleJson, db),
loadSchedules: () => readSchedules(db)
loadSchedules: () => readSchedules(db),
solve
})

createWindow()
Expand Down
24 changes: 21 additions & 3 deletions webdevadv/src/main/ipc.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Connects the app's features (employees, spreadsheet parser, saved schedules)
// Connects the app's features (employees, spreadsheet parser, schedules)
// to the renderer. The renderer can't touch the database or the file system
// directly, so each feature gets an IPC channel here and a matching function
// in src/preload/index.js (window.api.*).
Expand All @@ -12,9 +12,12 @@ export const CHANNELS = {
getEmployees: 'employees:getAll',
openSpreadsheet: 'spreadsheet:open',
saveSchedule: 'schedules:save',
getSchedules: 'schedules:getAll'
getSchedules: 'schedules:getAll',
generateSchedule: 'schedules:generate'
}

import { buildSolverInput } from './schedule.js'

const SPREADSHEET_FILTERS = [{ name: 'Spreadsheets', extensions: ['xlsx', 'xls', 'csv'] }]

function fail(err) {
Expand All @@ -28,7 +31,8 @@ function fail(err) {
// parseFile: (path) => { shows: [...] }
// saveSchedule: (scheduleJsonString) => void
// loadSchedules: () => [{ id, date, schedule: JSON text }]
export function createHandlers({ employees, pickFile, parseFile, saveSchedule, loadSchedules }) {
// solve: async (solverInput) => { ok, schedule } or { ok: false, error } (main/solver.js)
export function createHandlers({ employees, pickFile, parseFile, saveSchedule, loadSchedules, solve }) {
return {
addEmployee(employee) {
try {
Expand Down Expand Up @@ -68,6 +72,19 @@ export function createHandlers({ employees, pickFile, parseFile, saveSchedule, l
}
},

// The Manage Schedule page sends { date, shows, staff }. This builds the
// solver input (adding the default rules) and runs the solver.
// Returns the solver's { ok, schedule } or { ok: false, error }.
async generateSchedule(request) {
try {
const built = buildSolverInput(request ?? {})
if (!built.ok) return built
return await solve(built.input)
} catch (err) {
return fail(err)
}
},

getSchedules() {
try {
const schedules = loadSchedules().map((row) => ({
Expand All @@ -91,6 +108,7 @@ export function registerIpcHandlers(ipcMain, deps) {
ipcMain.handle(CHANNELS.openSpreadsheet, () => handlers.openSpreadsheet())
ipcMain.handle(CHANNELS.saveSchedule, (_, schedule) => handlers.saveSchedule(schedule))
ipcMain.handle(CHANNELS.getSchedules, () => handlers.getSchedules())
ipcMain.handle(CHANNELS.generateSchedule, (_, request) => handlers.generateSchedule(request))
return handlers
}

Expand Down
69 changes: 69 additions & 0 deletions webdevadv/src/main/schedule.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Turns what the manager enters on the Manage Schedule page into the exact
// input the solver (solver/solver.py) expects.
//
// The page only needs to collect three things:
// date: 'YYYY-MM-DD' (an <input type="date"> gives this format)
// shows: the list from window.api.openSpreadsheet()
// staff: the employees working that day, each with their shift times:
// [{ id, employee_name, shift_start: 'HH:MM', shift_end: 'HH:MM' }]
// (rows from window.api.getEmployees() plus two <input type="time"> values;
// `name` works in place of `employee_name`)
//
// The rules live here so every schedule uses the same ones.

// Values confirmed with David (see solver/sample_input.json).
export const DEFAULT_RULES = Object.freeze({
first_show_after_shift_start: 60, // no shows in the first hour of a shift
no_show_before_shift_end: 30, // no shows in the last 30 minutes of a shift
min_minutes_between_show_starts: 45, // a server's shows start at least 45 min apart
preferred_minutes_between_show_starts: 60, // ...ideally 60
min_shows_per_server: 4,
min_servers_per_show: 1,
max_servers_per_show: 2
})

const DATE_FORMAT = /^\d{4}-\d{2}-\d{2}$/
const TIME_FORMAT = /^([01]?\d|2[0-3]):[0-5]\d$/

function fail(error) {
return { ok: false, error }
}

// Returns { ok: true, input } ready for the solver, or { ok: false, error }
// with a message the page can show as is.
export function buildSolverInput({ date, shows, staff } = {}, rules = DEFAULT_RULES) {
if (!date || !DATE_FORMAT.test(date)) return fail('Pick a date for the schedule')
if (!Array.isArray(shows) || shows.length === 0) {
return fail('Upload the showtimes spreadsheet first')
}
if (!Array.isArray(staff) || staff.length === 0) {
return fail('Select at least one employee who is working')
}

const servers = []
for (const person of staff) {
const name = (person?.employee_name ?? person?.name ?? '').trim()
if (person?.id === undefined || person?.id === null || !name) {
return fail('Every selected employee needs an id and a name')
}
if (!TIME_FORMAT.test(person.shift_start ?? '') || !TIME_FORMAT.test(person.shift_end ?? '')) {
return fail(`Enter a shift start and end time for ${name}`)
}
servers.push({
id: String(person.id),
name,
shift_start: person.shift_start,
shift_end: person.shift_end
})
}

return {
ok: true,
input: {
date,
rules: { ...rules },
servers,
shows
}
}
}
7 changes: 6 additions & 1 deletion webdevadv/src/preload/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@ const api = {
saveSchedule: (schedule) => ipcRenderer.invoke('schedules:save', schedule),

// Saved schedules, newest first -> { ok, schedules: [{ id, date, schedule }] }
getSchedules: () => ipcRenderer.invoke('schedules:getAll')
getSchedules: () => ipcRenderer.invoke('schedules:getAll'),

// Builds the solver input and runs the solver in one call.
// generateSchedule({ date: 'YYYY-MM-DD', shows, staff: [{ id, employee_name, shift_start, shift_end }] })
// -> { ok: true, schedule } or { ok: false, error }
generateSchedule: (request) => ipcRenderer.invoke('schedules:generate', request)
}

// Use `contextBridge` APIs to expose Electron APIs to
Expand Down
56 changes: 56 additions & 0 deletions webdevadv/src/test/ipc.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ function fakeDeps(overrides = {}) {
parseFile: () => ({ shows: [{ id: 'm1', title: 'Movie 1', start: '12:30', auditorium: 1 }] }),
saveSchedule: (json) => saved.push(json),
loadSchedules: () => saved.map((schedule, i) => ({ id: i + 1, date: '2026-11-28', schedule })).reverse(),
solve: async (input) => ({ ok: true, schedule: { date: input.date, status: 'OPTIMAL', assignments: [], warnings: [] } }),
...overrides
}
}
Expand Down Expand Up @@ -130,6 +131,61 @@ describe('schedules', () => {
})
})

describe('generate schedule', () => {
const request = {
date: '2026-10-30',
shows: [{ id: 'm1', title: 'Movie 1', start: '12:30', auditorium: 1 }],
staff: [{ id: 1, employee_name: 'Alex', shift_start: '11:30', shift_end: '18:00' }]
}

test('builds the solver input and returns the schedule', async () => {
let sentToSolver
const { deps } = fakeDeps({
solve: async (input) => {
sentToSolver = input
return { ok: true, schedule: { date: input.date, status: 'OPTIMAL', assignments: [], warnings: [] } }
}
})
const result = await createHandlers(deps).generateSchedule(request)

expect(result.ok).toBe(true)
expect(result.schedule.date).toBe('2026-10-30')
expect(sentToSolver.servers).toEqual([
{ id: '1', name: 'Alex', shift_start: '11:30', shift_end: '18:00' }
])
expect(sentToSolver.rules.min_shows_per_server).toBe(4)
})

test('does not call the solver when the request is incomplete', async () => {
const solve = vi.fn()
const { deps } = fakeDeps({ solve })
const result = await createHandlers(deps).generateSchedule({ ...request, staff: [] })

expect(result).toEqual({ ok: false, error: 'Select at least one employee who is working' })
expect(solve).not.toHaveBeenCalled()
})

test('passes the solver error through', async () => {
const { deps } = fakeDeps({
solve: async () => ({ ok: false, error: "Can't build the schedule:\n- No shows to schedule" })
})
const result = await createHandlers(deps).generateSchedule(request)
expect(result).toEqual({ ok: false, error: "Can't build the schedule:\n- No shows to schedule" })
})

test('returns an error instead of throwing if the solver crashes', async () => {
const { deps } = fakeDeps({
solve: async () => {
throw new Error('spawn failed')
}
})
expect(await createHandlers(deps).generateSchedule(request)).toEqual({
ok: false,
error: 'spawn failed'
})
})
})

test('registers one handler per channel', () => {
const { deps } = fakeDeps()
const ipcMain = { handle: vi.fn() }
Expand Down
101 changes: 101 additions & 0 deletions webdevadv/src/test/schedule.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { existsSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { describe, expect, test } from 'vitest'
import { buildSolverInput, DEFAULT_RULES } from '../main/schedule.js'
import { runSolver } from '../main/solver.js'

// What the Manage Schedule page would send.
function request(overrides = {}) {
return {
date: '2026-10-30',
shows: [
{ id: 'm1', title: 'Movie 1', start: '12:30', auditorium: 1 },
{ id: 'm2', title: 'Movie 2', start: '13:00', auditorium: 2 }
],
staff: [
{ id: 1, employee_name: 'Alex', occupation: 'Server', shift_start: '11:30', shift_end: '18:00' },
{ id: 2, name: 'Sam', shift_start: '12:00', shift_end: '19:00' }
],
...overrides
}
}

describe('buildSolverInput', () => {
test('builds the solver input with the default rules', () => {
const result = buildSolverInput(request())
expect(result.ok).toBe(true)
expect(result.input.date).toBe('2026-10-30')
expect(result.input.rules).toEqual(DEFAULT_RULES)
expect(result.input.shows).toHaveLength(2)
})

test('turns employee rows into solver servers', () => {
const { input } = buildSolverInput(request())
expect(input.servers).toEqual([
{ id: '1', name: 'Alex', shift_start: '11:30', shift_end: '18:00' },
{ id: '2', name: 'Sam', shift_start: '12:00', shift_end: '19:00' }
])
})

test('returns a copy of the rules, so changing one schedule cannot change the defaults', () => {
const { input } = buildSolverInput(request())
input.rules.min_shows_per_server = 99
expect(DEFAULT_RULES.min_shows_per_server).toBe(4)
})

test.each([
['no date', { date: '' }, 'Pick a date'],
['wrong date format', { date: '10/30/2026' }, 'Pick a date'],
['no spreadsheet yet', { shows: [] }, 'Upload the showtimes spreadsheet'],
['nobody selected', { staff: [] }, 'Select at least one employee'],
['missing shift time', { staff: [{ id: 1, employee_name: 'Alex', shift_start: '11:30' }] }, 'Enter a shift start and end time for Alex'],
['12-hour time', { staff: [{ id: 1, employee_name: 'Alex', shift_start: '11:30', shift_end: '6:00pm' }] }, 'Enter a shift start and end time for Alex'],
['employee without a name', { staff: [{ id: 1, shift_start: '11:30', shift_end: '18:00' }] }, 'needs an id and a name']
])('refuses %s with a readable message', (_name, overrides, message) => {
const result = buildSolverInput(request(overrides))
expect(result.ok).toBe(false)
expect(result.error).toContain(message)
})

test('handles being called with nothing', () => {
expect(buildSolverInput().ok).toBe(false)
})
})

// End to end: the page's request -> buildSolverInput -> the real Python solver.
// Proves the built input is something the solver actually accepts.
describe('built input runs through the real solver', () => {
const VENV_PYTHON =
process.platform === 'win32'
? join('solver', '.venv', 'Scripts', 'python.exe')
: join('solver', '.venv', 'bin', 'python')

function solverOptions() {
const options = { script: join('solver', 'solver.py') }
if (!process.env.PYTHON_PATH && existsSync(VENV_PYTHON)) options.python = VENV_PYTHON
return options
}

test('a full day from the sample file produces a schedule', { timeout: 30_000 }, async () => {
const sample = JSON.parse(await readFile(join('solver', 'sample_input.json'), 'utf8'))
// Shape the sample like the page would: employee rows + shift times
const staff = sample.servers.map((s, i) => ({
id: i + 1,
employee_name: s.name,
occupation: 'Server',
shift_start: s.shift_start,
shift_end: s.shift_end
}))

const built = buildSolverInput({ date: sample.date, shows: sample.shows, staff })
expect(built.ok).toBe(true)

const res = await runSolver(built.input, solverOptions())
expect(res.ok, `Solver failed: ${res.error}`).toBe(true)
expect(['OPTIMAL', 'FEASIBLE']).toContain(res.schedule.status)
expect(res.schedule.date).toBe(sample.date)
expect(res.schedule.assignments.map((a) => a.name)).toEqual(staff.map((s) => s.employee_name))
expect(res.schedule.warnings).toEqual([])
})
})
Loading