package web import ( "fmt" "strings" "time" "supermarket/internal/seo" ) // clickChart is the morning check's chart: clicks by day this week, as a // line, over the week before, as a fainter one, day for day. type clickChart struct { W, H int This, Prev string // polyline points Dots []chartDot Labels []chartLabel Max int MaxY int // where the top gridline is Empty bool } type chartDot struct { X, Y float64 Title string } type chartLabel struct { X float64 Text string } const ( chartW, chartH = 600, 170 chartLeft = 28 // room for the scale chartTop = 10 chartBottom = 22 // room for the days ) func newClickChart(this, prev []seo.Day) *clickChart { if len(this) == 0 { return nil } c := &clickChart{W: chartW, H: chartH, MaxY: chartTop} for _, d := range append(append([]seo.Day{}, this...), prev...) { c.Max = max(c.Max, d.Clicks) } c.Empty = c.Max == 0 scale := max(c.Max, 1) n := len(this) x := func(i int) float64 { if n == 1 { return chartLeft + float64(chartW-chartLeft)/2 } return chartLeft + 24 + float64(i)*float64(chartW-chartLeft-48)/float64(n-1) } y := func(v int) float64 { return chartTop + float64(chartH-chartTop-chartBottom)*(1-float64(v)/float64(scale)) } points := func(days []seo.Day) string { var p []string for i, d := range days { if i < n { p = append(p, fmt.Sprintf("%.1f,%.1f", x(i), y(d.Clicks))) } } return strings.Join(p, " ") } c.This, c.Prev = points(this), points(prev) for i, d := range this { was := "" if i < len(prev) { was = fmt.Sprintf(" (%d the week before, on %s)", prev[i].Clicks, dayName(prev[i].Date)) } c.Dots = append(c.Dots, chartDot{X: x(i), Y: y(d.Clicks), Title: fmt.Sprintf("%s: %d %s%s", dayName(d.Date), d.Clicks, clicksWord(d.Clicks), was)}) c.Labels = append(c.Labels, chartLabel{X: x(i), Text: dayName(d.Date)}) } return c } func dayName(date string) string { t, err := time.Parse("2006-01-02", date) if err != nil { return date } return t.Format("Mon 2") } func clicksWord(n int) string { if n == 1 { return "click" } return "clicks" }