setup-go@v5 aborts when go.sum is missing, and this stdlib-only module has none. Disable the action cache and cap the job at 10 minutes. Lead the README with what the service does and a runnable quick start, fix stale contract and cache comments, and remove comments that only restate the code.
324 lines
8.4 KiB
Go
324 lines
8.4 KiB
Go
// Package staffing turns forecast points into an explainable shift plan using
|
||
// the deterministic heuristic in the API contract. It never calls the model.
|
||
package staffing
|
||
|
||
import (
|
||
"fmt"
|
||
"math"
|
||
"sort"
|
||
"time"
|
||
|
||
"pulsecast/api/internal/model"
|
||
)
|
||
|
||
// Build creates a plan for one sensor/scenario/standard from the forecast's
|
||
// complete store days.
|
||
func Build(sensor, scenario, standard string, points []model.ForecastPoint, ctx model.ContextData) (model.StaffingResponse, error) {
|
||
perStaff, ok := visitorsPerStaff(standard)
|
||
if !ok {
|
||
return model.StaffingResponse{}, fmt.Errorf("unknown standard %q", standard)
|
||
}
|
||
|
||
loc, err := time.LoadLocation(model.StoreHours.TZ)
|
||
if err != nil {
|
||
return model.StaffingResponse{}, fmt.Errorf("load timezone: %w", err)
|
||
}
|
||
|
||
days, err := groupStoreHours(points, loc)
|
||
if err != nil {
|
||
return model.StaffingResponse{}, err
|
||
}
|
||
|
||
assumptions := model.StaffingAssumptions{
|
||
VisitorsPerStaffHour: perStaff,
|
||
SafetyFactor: model.SafetyFactor,
|
||
MinStaff: model.MinStaff,
|
||
ShiftLengthH: model.ShiftLengthHours,
|
||
LaborCostEURH: model.LaborCostEURPerHour,
|
||
StoreHours: model.StoreHoursSpec{
|
||
Open: "10:00",
|
||
Close: "20:00",
|
||
TZ: model.StoreHours.TZ,
|
||
},
|
||
}
|
||
|
||
var hours []model.StaffingHour
|
||
var shifts []model.Shift
|
||
requiredByDate := make(map[string][]int)
|
||
totalCost := 0.0
|
||
|
||
for _, day := range days {
|
||
// Required staff per hour first; blocks need maxima across the day.
|
||
required := make(map[int]int, len(day.hours))
|
||
for _, h := range day.hours {
|
||
req := int(math.Ceil(math.Max(0, h.point.V) / float64(perStaff) * model.SafetyFactor))
|
||
if req < model.MinStaff {
|
||
req = model.MinStaff
|
||
}
|
||
required[h.hour] = req
|
||
requiredByDate[day.date] = append(requiredByDate[day.date], req)
|
||
}
|
||
|
||
scheduled := make(map[int]int, len(day.hours))
|
||
for _, block := range blocks(day.hours) {
|
||
staff := 0
|
||
for _, h := range block.hours {
|
||
if req := required[h.hour]; req > staff {
|
||
staff = req
|
||
}
|
||
}
|
||
for _, h := range block.hours {
|
||
scheduled[h.hour] = staff
|
||
}
|
||
shifts = append(shifts, model.Shift{
|
||
Date: day.date,
|
||
Start: clock(block.start),
|
||
End: clock(block.end),
|
||
Staff: staff,
|
||
})
|
||
totalCost += float64(staff) * float64(block.minutes()) / 60 * model.LaborCostEURPerHour
|
||
}
|
||
|
||
for _, h := range day.hours {
|
||
req := required[h.hour]
|
||
sched := scheduled[h.hour]
|
||
coverage := "ok"
|
||
switch {
|
||
case sched < req:
|
||
coverage = "under"
|
||
case sched > req:
|
||
coverage = "over"
|
||
}
|
||
hours = append(hours, model.StaffingHour{
|
||
T: h.point.T.UTC(),
|
||
Footfall: h.point.V,
|
||
RequiredStaff: req,
|
||
ScheduledStaff: sched,
|
||
Coverage: coverage,
|
||
})
|
||
}
|
||
}
|
||
|
||
if len(hours) == 0 {
|
||
return model.StaffingResponse{}, fmt.Errorf("no store-hour forecast points")
|
||
}
|
||
|
||
summary := summarise(hours, requiredByDate, totalCost, loc)
|
||
why := explain(days, ctx, scenario, loc)
|
||
|
||
return model.StaffingResponse{
|
||
Sensor: sensor,
|
||
Scenario: scenario,
|
||
Standard: standard,
|
||
Assumptions: assumptions,
|
||
Hours: hours,
|
||
Shifts: shifts,
|
||
Summary: summary,
|
||
Why: why,
|
||
}, nil
|
||
}
|
||
|
||
func visitorsPerStaff(standard string) (int, bool) {
|
||
switch standard {
|
||
case "relaxed":
|
||
return model.VisitorsPerStaffRelaxed, true
|
||
case "standard":
|
||
return model.VisitorsPerStaffStandard, true
|
||
case "premium":
|
||
return model.VisitorsPerStaffPremium, true
|
||
default:
|
||
return 0, false
|
||
}
|
||
}
|
||
|
||
type hourPoint struct {
|
||
hour int
|
||
point model.ForecastPoint
|
||
}
|
||
|
||
type dayPlan struct {
|
||
date string
|
||
hours []hourPoint
|
||
}
|
||
|
||
// groupStoreHours keeps only points that fall inside 10:00–20:00 local time,
|
||
// first seven local dates, sorted chronologically.
|
||
func groupStoreHours(points []model.ForecastPoint, loc *time.Location) ([]dayPlan, error) {
|
||
type key struct {
|
||
date string
|
||
hour int
|
||
}
|
||
seen := make(map[key]model.ForecastPoint)
|
||
var dates []string
|
||
dateSet := make(map[string]bool)
|
||
|
||
for _, point := range points {
|
||
local := point.T.In(loc)
|
||
if local.Hour() < model.StoreHours.Open || local.Hour() >= model.StoreHours.Close {
|
||
continue
|
||
}
|
||
k := key{date: local.Format("2006-01-02"), hour: local.Hour()}
|
||
seen[k] = point
|
||
if !dateSet[k.date] {
|
||
dateSet[k.date] = true
|
||
dates = append(dates, k.date)
|
||
}
|
||
}
|
||
sort.Strings(dates)
|
||
if len(dates) > 7 {
|
||
dates = dates[:7]
|
||
}
|
||
|
||
days := make([]dayPlan, 0, len(dates))
|
||
for _, date := range dates {
|
||
day := dayPlan{date: date}
|
||
for hour := model.StoreHours.Open; hour < model.StoreHours.Close; hour++ {
|
||
if point, ok := seen[key{date: date, hour: hour}]; ok {
|
||
day.hours = append(day.hours, hourPoint{hour: hour, point: point})
|
||
}
|
||
}
|
||
// A day is only usable if every store hour has a forecast point.
|
||
if len(day.hours) == model.StoreHours.Close-model.StoreHours.Open {
|
||
days = append(days, day)
|
||
}
|
||
}
|
||
if len(days) == 0 {
|
||
return nil, fmt.Errorf("no complete store-day in forecast")
|
||
}
|
||
return days, nil
|
||
}
|
||
|
||
type block struct {
|
||
start int // local hour
|
||
end int // local hour, exclusive
|
||
hours []hourPoint
|
||
}
|
||
|
||
func (b block) minutes() int { return (b.end - b.start) * 60 }
|
||
|
||
// blocks walks the store day in 4-hour chunks; the final chunk is shorter
|
||
// (18:00–20:00) rather than extending past closing time.
|
||
func blocks(hours []hourPoint) []block {
|
||
var out []block
|
||
for start := model.StoreHours.Open; start < model.StoreHours.Close; start += model.ShiftLengthHours {
|
||
end := start + model.ShiftLengthHours
|
||
if end > model.StoreHours.Close {
|
||
end = model.StoreHours.Close
|
||
}
|
||
var inBlock []hourPoint
|
||
for _, h := range hours {
|
||
if h.hour >= start && h.hour < end {
|
||
inBlock = append(inBlock, h)
|
||
}
|
||
}
|
||
if len(inBlock) > 0 {
|
||
out = append(out, block{start: start, end: end, hours: inBlock})
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
|
||
func summarise(hours []model.StaffingHour, requiredByDate map[string][]int, totalCost float64, loc *time.Location) model.StaffingSummary {
|
||
covered := 0
|
||
over := 0
|
||
under := 0
|
||
for _, h := range hours {
|
||
switch {
|
||
case h.ScheduledStaff >= h.RequiredStaff:
|
||
covered++
|
||
}
|
||
if h.ScheduledStaff > h.RequiredStaff {
|
||
over++
|
||
}
|
||
if h.ScheduledStaff < h.RequiredStaff {
|
||
under++
|
||
}
|
||
}
|
||
|
||
maxRequired := 0
|
||
for _, reqs := range requiredByDate {
|
||
for _, req := range reqs {
|
||
if req > maxRequired {
|
||
maxRequired = req
|
||
}
|
||
}
|
||
}
|
||
flatCost := float64(maxRequired) * float64(len(hours)) * model.LaborCostEURPerHour
|
||
|
||
coveragePct := 0.0
|
||
if len(hours) > 0 {
|
||
coveragePct = math.Round(float64(covered)/float64(len(hours))*1000) / 10
|
||
}
|
||
|
||
return model.StaffingSummary{
|
||
CoveragePct: coveragePct,
|
||
CostEUR: int(math.Round(totalCost)),
|
||
FlatScheduleCostEUR: int(math.Round(flatCost)),
|
||
OverstaffedHours: over,
|
||
UnderstaffedHours: under,
|
||
}
|
||
}
|
||
|
||
// explain names the observable weather/holiday context and the scenario
|
||
// assumptions. It does not claim causality.
|
||
func explain(days []dayPlan, ctx model.ContextData, scenario string, loc *time.Location) []string {
|
||
if len(days) == 0 {
|
||
return nil
|
||
}
|
||
first, _ := time.ParseInLocation("2006-01-02", days[0].date, loc)
|
||
last, _ := time.ParseInLocation("2006-01-02", days[len(days)-1].date, loc)
|
||
|
||
var why []string
|
||
for _, holiday := range ctx.Holidays {
|
||
hDate, err := time.ParseInLocation("2006-01-02", holiday.Date, loc)
|
||
if err != nil {
|
||
continue
|
||
}
|
||
if !hDate.Before(first) && !hDate.After(last) {
|
||
why = append(why, "Public holiday: "+holiday.Name+" ("+holiday.Date+")")
|
||
}
|
||
}
|
||
|
||
var precip float64
|
||
var tempSum float64
|
||
var n int
|
||
for _, point := range ctx.Weather.Forecast {
|
||
local := point.T.In(loc)
|
||
day := local.Format("2006-01-02")
|
||
if day < days[0].date || day > days[len(days)-1].date {
|
||
continue
|
||
}
|
||
precip += point.PrecipMM
|
||
tempSum += point.TempC
|
||
n++
|
||
}
|
||
if n > 0 {
|
||
avg := tempSum / float64(n)
|
||
switch {
|
||
case precip >= 5:
|
||
why = append(why, fmt.Sprintf("Wet week in the forecast (%.1f mm)", precip))
|
||
case precip >= 0.5:
|
||
why = append(why, fmt.Sprintf("Some rain in the forecast (%.1f mm)", precip))
|
||
default:
|
||
why = append(why, "Mostly dry week in the forecast")
|
||
}
|
||
why = append(why, fmt.Sprintf("Average forecast temperature %.0f°C", avg))
|
||
}
|
||
|
||
switch scenario {
|
||
case "sunny-saturday-market":
|
||
why = append(why, "Scenario assumes a sunny Saturday market uplift")
|
||
case "rainy-saturday":
|
||
why = append(why, "Scenario assumes a rainy Saturday")
|
||
case "weekday-event":
|
||
why = append(why, "Scenario assumes a weekday evening event uplift")
|
||
default:
|
||
why = append(why, "Base scenario: no weather delta or event uplift")
|
||
}
|
||
return why
|
||
}
|
||
|
||
func clock(hour int) string {
|
||
return fmt.Sprintf("%02d:00", hour)
|
||
}
|