reports

package
v0.0.16 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package reports owns report definitions and their execution.

Index

Constants

This section is empty.

Variables

View Source
var ErrDuplicateName = errors.New("report with this name already exists")

ErrDuplicateName is returned when Create is called with a name that already exists for the user.

View Source
var ErrInvalidGoal = errors.New("invalid time goal")

ErrInvalidGoal is returned when a time goal string cannot be parsed.

View Source
var ErrInvalidMetric = errors.New("invalid metric")

ErrInvalidMetric is returned when a metric is not "time" or "amount".

View Source
var ErrInvalidName = errors.New("invalid report name")

ErrInvalidName is returned when a report name doesn't match the allowed pattern.

View Source
var ErrInvalidPeriodWeeks = errors.New("invalid period weeks")

ErrInvalidPeriodWeeks is returned when a period in weeks is not a positive integer.

View Source
var ErrInvalidStyle = errors.New("invalid style")

ErrInvalidStyle is returned when a style is not "total" or "average".

View Source
var ErrNoEntries = errors.New("report must have at least one entry")

ErrNoEntries is returned when Create is called with no entries.

View Source
var ErrNotFound = errors.New("report not found")

ErrNotFound is returned when a report cannot be found for the given user/name.

View Source
var ErrTicketNotOwned = errors.New("ticket not owned by user")

ErrTicketNotOwned is returned when an entry references a ticket that does not belong to the calling user (or does not exist).

View Source
var NameRegex = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)

NameRegex is the regex enforced both client-side and at the DB CHECK level.

Functions

func Delete

func Delete(ctx context.Context, userID uuid.UUID, name string) error

Delete removes a report by name for the given user. Cascade drops entries. Returns ErrNotFound if no row matched.

func DeleteEntry

func DeleteEntry(ctx context.Context, userID, entryID uuid.UUID) error

DeleteEntry removes a single report entry scoped to userID via its parent report. Deleting the last entry of a report is permitted. Returns ErrNotFound if the entry is not owned by userID.

func DeriveValue

func DeriveValue(style string, days int, raw float64) float64

DeriveValue converts a raw total to a per-entry value based on style. "average" divides by the day count; "total" (and anything else) is a passthrough.

func FormatDelta

func FormatDelta(metric, style string, value, goal float64) string

FormatDelta renders (value-goal) (seconds for time metric) using metric+style display rules, preserving sign. Unknown metric/style returns "".

func FormatGoal

func FormatGoal(metric string, goal float64) string

FormatGoal renders a goal using the metric's display rules (time goals are seconds, rendered as H:MM; amount goals as %.2f).

func FormatPercent

func FormatPercent(value, goal float64) string

FormatPercent renders Percent as "X.X%". Returns "" when goal is zero.

func FormatToday added in v0.0.14

func FormatToday(metric string, today float64) string

FormatToday renders an entry's Today total (seconds for time metric). It is always a raw total, so it uses the "total" style rules regardless of the entry's own style: "H:MM" for time, "%.2f" for amount.

func FormatValue

func FormatValue(metric, style string, value float64) string

FormatValue renders an executed entry's value (seconds for time metric) using metric+style display rules. time/total → "H:MM", time/average → "H:MM/day", amount/total → "%.2f", amount/average → "%.2f/day". Unknown metric/style combinations return "".

func ParseTimeGoal

func ParseTimeGoal(s string) (float64, error)

ParseTimeGoal parses a time goal into seconds. Accepted forms:

bare decimal — hours: "2" → 7200, "1.5" → 5400
H:MM         — "1:30" → 5400, "0:45" → 2700 (MM must be 00–59)
Go duration  — "90m", "2h", "1h30m", "1.5h", "45s" (time.ParseDuration)

Negative and unparseable inputs are rejected; zero is allowed.

func Percent

func Percent(value, goal float64) float64

Percent returns value / goal * 100, or +Inf if goal is zero. Used both for presentation (FormatPercent) and for sort ordering on the report tables.

func StartOfDay added in v0.0.14

func StartOfDay(now time.Time, loc *time.Location) time.Time

StartOfDay returns local midnight of now's calendar day in loc.

func ValidateMetric

func ValidateMetric(metric string) error

ValidateMetric returns nil if metric is "time" or "amount".

func ValidateName

func ValidateName(name string) error

ValidateName returns nil if name is filename-safe and matches the DB CHECK.

func ValidatePeriodWeeks

func ValidatePeriodWeeks(weeks int32) error

ValidatePeriodWeeks returns nil if weeks is a positive integer.

func ValidateStyle

func ValidateStyle(style string) error

ValidateStyle returns nil if style is "total" or "average".

func WindowFor

func WindowFor(weeks int32) (time.Duration, int)

WindowFor returns the rolling window duration and the integer day count (denominator for "average" style) for a period given in weeks. Non-positive values return (0, 0).

Types

type Entry

type Entry struct {
	CreatedAt   time.Time `db:"created_at"`
	UpdatedAt   time.Time `db:"updated_at"`
	Metric      string    `db:"metric"`
	Style       string    `db:"style"`
	ID          uuid.UUID `db:"id"`
	ReportID    uuid.UUID `db:"report_id"`
	TicketID    uuid.UUID `db:"ticket_id"`
	Order       float64   `db:"order"`
	Goal        float64   `db:"goal"`
	PeriodWeeks int32     `db:"period_weeks"`
}

Entry is one row in a report: ticket × metric × style × period_weeks × goal. Time-metric goals are seconds (seconds per day for "average" style).

func AddEntry

func AddEntry(ctx context.Context, userID uuid.UUID, reportName string, e *Entry) (*Entry, error)

AddEntry appends a new entry to an existing report owned by userID. The caller must have validated e.Metric, e.Style, e.PeriodWeeks. Ticket ownership is enforced here. The new entry is ordered after all existing entries. e.ID and e.Order on input are ignored; the server assigns them. Returns ErrNotFound if the report does not exist, ErrTicketNotOwned if the ticket is not owned by userID.

func UpdateEntry

func UpdateEntry(ctx context.Context, userID, entryID uuid.UUID, p EntryPatch) (*Entry, error)

UpdateEntry applies a partial update to a single report entry, scoped to userID via the entry's parent report. Validates any changed metric/style/ period_weeks and re-checks ticket ownership only when TicketID changes. Returns ErrNotFound if the entry is not owned by userID.

type EntryPatch

type EntryPatch struct {
	TicketID    *uuid.UUID
	Metric      *string
	Style       *string
	PeriodWeeks *int32
	Goal        *float64
}

EntryPatch is a partial update to a report entry. Nil fields are left unchanged. TicketID, if set, must reference a ticket owned by the user.

type Executed

type Executed struct {
	GeneratedAt time.Time
	Name        string
	Entries     []ExecutedEntry
}

Executed is the result of running one report definition.

func RunAll

func RunAll(ctx context.Context, userID uuid.UUID) ([]Executed, error)

RunAll executes every report owned by userID at the current wall-clock time and returns one Executed per definition.

func RunOne

func RunOne(ctx context.Context, userID uuid.UUID, def *Report) (Executed, error)

RunOne executes a single report definition at the current wall-clock time. Use this when the caller already has the *Report (e.g., from GetByName) and only needs one Executed result.

func (*Executed) EntriesByPercent

func (e *Executed) EntriesByPercent() []ExecutedEntry

EntriesByPercent returns the entries sorted ascending by Percent (value/goal). Used by the HTML and Markdown renderers to put the most-behind-goal rows first.

func (*Executed) GeneratedAtPtr

func (e *Executed) GeneratedAtPtr() *time.Time

GeneratedAtPtr returns a pointer to the report's generation time. Templates using `formatDateTime` require a pointer.

type ExecutedEntry

type ExecutedEntry struct {
	TicketDescription string
	Metric            string
	Style             string
	TicketID          uuid.UUID
	PeriodWeeks       int32
	Goal              float64
	Value             float64
	Today             float64
}

ExecutedEntry is one entry's evaluated result, paired with its definition. Time-metric Goal and Value are seconds (seconds per day for "average" style). Today is the raw subtree total since local midnight in the user's timezone (seconds for the time metric); it is never averaged.

type Report

type Report struct {
	CreatedAt time.Time `db:"created_at"`
	UpdatedAt time.Time `db:"updated_at"`
	Name      string    `db:"name"`
	Entries   []Entry   `db:"-"`
	ID        uuid.UUID `db:"id"`
	UserID    uuid.UUID `db:"user_id"`
}

Report is a named collection of entries owned by one user.

func Create

func Create(ctx context.Context, userID uuid.UUID, name string, entries []Entry) (*Report, error)

Create inserts a report and its entries inside a single transaction. The caller must have validated name, metric, style, period before calling. Ticket ownership is enforced here: any entry referencing a ticket not owned by userID returns ErrTicketNotOwned.

func GetByName

func GetByName(ctx context.Context, userID uuid.UUID, name string) (*Report, error)

GetByName returns one report by name for the given user, with entries loaded and sorted by order. Returns ErrNotFound if no row matches.

func List

func List(ctx context.Context, userID uuid.UUID) ([]Report, error)

List returns all reports for a user, alphabetically by name, with entries loaded and sorted by order.

func Rename

func Rename(ctx context.Context, userID uuid.UUID, oldName, newName string) (*Report, error)

Rename changes a report's name for the given user. Validates the new name, maps a unique-name conflict to ErrDuplicateName, and returns the renamed report with its entries loaded. Returns ErrNotFound if no report matched.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址