agenda

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 36 Imported by: 0

README

Arandu

Arandu Agenda

Bookings on the agenda of a platform team, for a multi-tenant Arandu application: a customer of a space picks a service, a day and a free time, pays in advance when the service asks for it, is reminded near the time, and the team marks the visit as done.

There are two sides, and they are separate. The customer lists their own bookings, books a time, confirms, reschedules and cancels. The team lists every space's bookings, releases one without a payment as a courtesy, completes it, marks an absence, moves and cancels, and keeps its own services, weekly hours and closures. Each side has its own controllers, its own screens and its own prefix, and the application mounts each where its own session is valid: the team's session only on the operator console, the customer's only on the panel.

Every booking has a protocol number, AG-000123, taken from one sequence for all the spaces.

What it does not do

  • It takes no payment. A balance, a charge and a Pix belong to the application and to arandu-wallet. The module only knows a booking waits for payment until the application says the payment settled (Settle), or the team releases it as a courtesy (Release). The module has no price column either: what a service costs is the application's catalogue.
  • It sends no message. A reminder, a confirmation and a cancellation are an Event handed to the application's Notifier, which sends it by WhatsApp, e-mail or whatever it has.
  • It knows no table of users, no list of the team and no roles. Permissions are arandu-permission's, and the record of who did what is arandu-activitylog's.
  • It runs nothing by itself. Remind and ExpireHolds are two calls the application schedules.

Install

go get github.com/hyz-is/arandu-agenda

It requires arandu-activitylog and expects the application to administer permissions with arandu-permission.

Wire it

An Arandu application registers a module explicitly. There is no service provider, no container and no discovery, so these are the lines to paste into bootstrap/app.go and there are no others.

The import, with the other module imports:

import (
	agenda "github.com/hyz-is/arandu-agenda"
)

The construction, in Build, after the session store and the activity log exist and before k.Register:

	zone, err := time.LoadLocation("America/Sao_Paulo")
	if err != nil {
		return App{}, err
	}
	agendaModule, err := agenda.New(agenda.Config{
		// The tenant the platform team signs in to: the operator console's
		// realm. Required, with the zone the team's day is written in.
		TeamTenant: cfg.Auth.Tenant,
		Zone:       zone,

		// Two sides, two prefixes. The application's own addresses, in the
		// segments of its language.
		Prefix:     "/painel/agendamentos",
		TeamPrefix: "/admin/agenda",
		Paths:      agenda.PortuguesePaths,

		// The rules of the agenda. All optional; these are the defaults.
		Capacity:     1,               // bookings one time takes
		SlotStep:     20 * time.Minute, // distance between two starts offered
		MinNotice:    24 * time.Hour,   // earliest bookable start from now
		Horizon:      30 * 24 * time.Hour,
		PaymentHold:  24 * time.Hour,   // an unpaid booking keeps its slot this long
		RemindBefore: 3 * time.Hour,
		ChangeUntil:  2 * time.Hour,    // the customer may move or cancel until here

		Notifier:   agendaNotifier{whatsapp: whatsapp}, // the application's own channel
		Directory:  teamDirectory{users: users},        // names (optional)
		Subjects:   cameraSubjects{cameras: cameras},   // checks the camera is theirs (optional)
		PaymentURL: func(b agenda.Summary) string { return "/painel/pagamentos/agenda/" + b.ID },

		Activity: activityModule.Logger(), // arandu-activitylog

		// The actions arandu-permission fills are resolved on each request,
		// so its Roles() runs on every route; the console's guard runs on the
		// team's alone.
		Middleware:     []func(http.Handler) http.Handler{permissionModule.Roles()},
		TeamMiddleware: []func(http.Handler) http.Handler{consoleGuard},
	}, db, sessions)
	if err != nil {
		return App{}, err
	}

And the registration, inside the k.Register(...) call already there:

		agendaModule,

An application that keeps the two sides on different routers mounts them itself, each with its own guards, instead of registering the routes through Routes:

agendaModule.CustomerRoutes(panelRouter) // under Prefix
agendaModule.TeamRoutes(consoleRouter)   // under TeamPrefix

The package owns five tables, so run its migrations. They never run at boot:

aru migrate

New returns an error rather than starting half-wired: a team tenant that is not one, no zone, a relative prefix, a prefix under /_arandu, a segment with a wildcard, a step that is not whole minutes, a nil database or a nil session store.

Give people access

The policies are in policy.go, and the actions reach them through the subject, which arandu-permission fills. A role opens nothing: a subject that holds no action is refused everything, an administrator included.

Declare the actions in the permission catalogue beside the application's own. The customer's and the team's are two lists, so a catalogue an organization grants from never holds a team action:

permission.Config{
	Actions: append(append(app.Actions(), permission.Actions()...), agenda.Actions()...),
	// ...
}
// and, in the catalogue of the platform's own team only:
//   agenda.TeamActions()
action side what it opens
agenda.book customer looking at the services and the free times, and booking one in the subject's own space
agenda.view_own customer reading the bookings the subject made
agenda.view_space customer reading every booking of the space, whoever made it; with agenda.change, changing them too
agenda.change customer confirming, rescheduling and cancelling a booking the subject can read
agenda.view_all team reading every space's bookings, and the team's services, hours and closures
agenda.manage team releasing a booking as a courtesy, completing it, marking an absence, moving and cancelling it
agenda.configure team creating, changing and deleting services, weekly hours and closures
agenda.settle none the application putting a payment on a booking from its own code; no person holds it
agenda.run_tasks none the scheduler running Remind and ExpireHolds; no person holds it

Each action opens what it names and nothing else, and the Grants for reading (agenda.view_own, agenda.view_space, agenda.view_all) only read, so the database refuses a write made with one.

A member of the team is a subject of Config.TeamTenant who holds the team's actions. TeamPolicy refuses a subject of any other tenant whatever it carries, and a subject somebody else is viewing as.

What the application provides

Notifier
type Notifier interface {
	Notify(ctx context.Context, e agenda.Event) error
}

Notify runs after the change is stored, and its error does not undo the change: the booking is already made and the slot already taken. The failure is logged with the kind of the event, the booking's identifier and the type of the error, and no personal text. An application that must not lose a notification enqueues it here and delivers it from its queue.

Event.Kind when who is told
EventBooked a booking was made; AwaitingPayment says whether it waits for a payment the team, and the customer
EventScheduled the payment settled, or the team released it the customer
EventReminder Remind found it near; carries ConfirmURL and RescheduleURL the customer
EventConfirmed the customer confirmed the team
EventRescheduled moved; By says by whom the side that did not act
EventCancelled cancelled; By says by whom the side that did not act
EventCompleted the team did the work the customer
EventHoldExpired the hold of an unpaid booking lapsed the customer

Event.ForTeam() answers whether the team is the one to tell, and Kind.ForTeam() does for the kinds that do not depend on who acted. The event carries a Summary of the booking after the change: protocol, service, subject, requester, start and end, status.

type agendaNotifier struct{ whatsapp *whatsapp.Client }

func (n agendaNotifier) Notify(ctx context.Context, e agenda.Event) error {
	switch e.Kind {
	case agenda.EventReminder:
		phone, err := n.phoneOf(ctx, e.Booking.Tenant, e.Booking.RequesterID)
		if err != nil {
			return err
		}
		return n.whatsapp.Send(ctx, phone, fmt.Sprintf(
			"Lembrete: %s em %s. Confirme ou reagende: %s%s",
			e.Booking.ServiceName, e.Booking.StartsAt.In(zone).Format("02/01 15:04"), baseURL, e.ConfirmURL))
	}
	return nil
}
Directory (optional)

Names the requester when a booking is made, and the team members who released or completed one. Without one, the screens show the identifiers.

type Directory interface {
	Person(ctx context.Context, tenant, id string) (agenda.Person, error)
}
SubjectResolver (optional)

A booking is about something the application understands -- "camera", its identifier, a label -- and the module keeps it opaque. A SubjectResolver lets the application check that the camera is the customer's and gives the label itself, so the request cannot name another space's camera:

type SubjectResolver interface {
	Resolve(ctx context.Context, tenant string, subject agenda.BookingSubject) (label string, err error)
}

URLs().NewFor("reconfiguracao", agenda.BookingSubject{Type: "camera", ID: "42", Label: "Portaria"}) is the address of the booking form with the booking already about that camera.

PaymentURL (optional)

Config.PaymentURL answers the address where the customer pays a booking that waits for it: the application's page, since the module knows nothing of money. An empty answer shows the booking as waiting and offers no link.

The payment

A service with requires_payment leaves a booking in awaiting_payment, holding the slot until HoldUntil (Config.PaymentHold from now). The application charges however it does, and when the payment is real it tells the module, with a Grant it issues itself for that space:

//arandu:system-grant the payment webhook was verified; the tenant is the booking's own
grant := security.SystemGrant(agenda.AgendaSettle, booking.Tenant)
booking, err := agendaModule.Settle(ctx, grant, bookingID, "pix-e2e-9f3a")
switch {
case errors.Is(err, agenda.ErrSlotTaken):
	// The hold lapsed and somebody booked the slot meanwhile: refund, or book again.
case errors.Is(err, agenda.ErrNotSettleable):
	// Cancelled, or already settled with another reference: refund.
}

Settle is idempotent: the same reference delivered twice answers the booking as it is, and nothing is written or told again. A booking whose hold lapsed is settled only if its slot is still free. Find(ctx, grant, "AG-000123") looks a booking up by protocol or identifier in the Grant's space.

Tasks

Two calls, to schedule every five minutes. Each returns how many it touched, and neither sends anything itself:

n, err := agendaModule.Remind(ctx)      // one Reminder per booking still to be confirmed that starts within RemindBefore
n, err := agendaModule.ExpireHolds(ctx) // marks the unpaid bookings past their hold as expired and emits HoldExpired

Remind reminds a scheduled booking once: the moment is written before the Notifier is asked, by a statement that only one of two overlapping runs wins. A confirmed booking is not reminded, and a booking moved to another time is reminded again for the new one. A lapsed hold frees its slot as soon as the clock passes it -- availability reads the clock, not the status -- so ExpireHolds only keeps the statuses honest and tells the customer.

The lifecycle

status meaning
awaiting_payment holds the slot until hold_until, waiting for Settle or a courtesy
scheduled holds the slot: paid, released, or a service that asks for no payment
confirmed scheduled, and the customer confirmed
completed the team did it
cancelled cancelled by the customer or by the team
expired the hold lapsed before a payment came
no_show the customer did not turn up

The customer moves or cancels a booking until Config.ChangeUntil before its start; after that only the team does. A booking can be moved to a start that Slots offers: inside the team's hours, outside its closures, with a place free, no sooner than MinNotice and no later than Horizon.

Whether a time is free is a function of data, in Schedule, and an application can ask the same question the screens do. Two people asking for the last place take turns: the check is made again inside a transaction that holds the lock of the protocol counter, and the second is told ErrSlotTaken.

Publish the views

This package carries the markup of its own twelve pages and hands it over instead of rendering it from the inside, because a page you cannot edit is a page that says the wrong thing in your product.

Look at what would be written, then write it:

aru vendor:publish --tag=view
aru vendor:publish --tag=view --apply

Nothing is written without --apply. The files land under resources/views/modules/agenda/, and from that point they are yours: the customer's index, form, show and reschedule, and the team's admin/index, admin/show, admin/services, admin/service_form, admin/hours, admin/hour_form, admin/closures and admin/closure_form.

Two steps are left to you. Compile what was written:

aru view:build

and import the two directories it wrote into, with the other imports:

	_ "your/module/path/storage/framework/views/modules/agenda"
	_ "your/module/path/storage/framework/views/modules/agenda/admin"

Without those imports the views are not in the binary, and the module refuses to boot rather than answering the first request that reaches one of them with a 500. The pages extend your layouts.app and use the Kyse components: a DataTable paged, searched, ordered and filtered on the server for every list, DatePicker with the calendar in Portuguese for every date, RadioGroup for the free times. They draw no inline style and no inline script, so a content security policy of 'self' holds. Every sentence is Brazilian Portuguese, in resources/lang/pt-BR/agenda.json; override any line with the application's own Config.Translator.

Configuration

TeamTenant and Zone are the two required settings.

field meaning
TeamTenant the tenant the team signs in to; its services, hours and closures are the agenda's
Zone the timezone the team's day, the weekly hours and every screen are written in
Prefix, TeamPrefix, Paths where the routes are mounted; PortuguesePaths is the whole set in Portuguese
Capacity bookings one time takes; default 1
SlotStep distance between two starts offered; default 20 minutes, whole minutes
MinNotice earliest bookable start from now; default 24 hours, negative for none
Horizon latest bookable start from now; default 30 days
PaymentHold how long an unpaid booking keeps its slot; default 24 hours
RemindBefore how long before the start the reminder goes; default 3 hours
ChangeUntil how long before the start the customer may still move or cancel; default 2 hours
PageSize rows per page; default 25, refused above 100
Notifier, Directory, Subjects, PaymentURL what the application provides
Activity arandu-activitylog's logger; every write is recorded under the Grant it was authorized with
Middleware, TeamMiddleware guards that run after RequireAuth, on both sides and on the team's alone
Translator, Locale, TitleSeparator, Chrome the sentences, the document title and the layout's chrome
Now, Logger the clock and the log; a test holds the clock still

Routes

Every route sits behind RequireAuth, mounted by the package itself. A request with no session is sent to /auth/login. Build addresses from URLs() and the route names (aru route:list), never by writing a path a second time. Every GET answers the screen to a browser and JSON to a client that asks for it.

method path (customer, under Prefix) name
GET / agenda.index
GET /new?service=&day= agenda.create
POST / agenda.store
GET /{id} agenda.show
POST /{id}/confirmation agenda.confirm
GET, POST /{id}/rescheduling agenda.reschedule, agenda.rescheduled
POST /{id}/cancellation agenda.cancel
method path (team, under TeamPrefix) name
GET /?day=&status=&q= agenda.team.index
GET /{id} agenda.team.show
POST /{id}/completion, /release, /no-show, /cancellation, /rescheduling agenda.team.complete, .release, .no_show, .cancel, .reschedule
GET, POST, DELETE /settings/services, /new, /{id} agenda.team.services*
GET, POST, DELETE /settings/hours, /new, /{id} agenda.team.hours*
GET, POST, DELETE /settings/closures, /new, /{id} agenda.team.closures*

The tenant is never a parameter of any of them: it is the Grant's.

What is recorded

Every write is an entry of arandu-activitylog, in the log named agenda, under the Grant the act was authorized with, so a space reads its own entries and the platform administrator reads them all. The causer is the person who acted -- the team member who released a booking, in the customer's space -- and a task has none. The events are agenda.booked, agenda.settled, agenda.released, agenda.confirmed, agenda.rescheduled, agenda.cancelled, agenda.completed, agenda.no_show, agenda.hold_expired, agenda.reminded and agenda.service_created, _updated and _deleted, agenda.hour_created and _deleted, agenda.closure_created and _deleted. An entry carries the protocol and identifiers, and never what a person typed: not the customer's note, not a reason, not a name.

The data path

Booking embeds model.Model, and each table is declared once, beside the entity, in model.go. aru model:build generates BookingQuery.go and the others from them: Bookings(db), which starts a *BookingQuery, and BookingCollection. The files are committed and never edited by hand; regenerate them after changing an entity, and aru model:build --check fails when one is out of date.

BookingService, TeamService and AppService own *data.DB and follow validate -> security.Authorize -> Grant -> Model terminal; handlers never hold the database or start a query. The tenant of every write is data.Tenant(g), from the Grant, never from the path, the body, the query string or a header.

The agenda is one for every space, so the schema is too:

  • agenda_bookings has a tenant_id; a customer reads and writes it through the tenant's own model, and another space's booking is not found.
  • agenda_services, agenda_hours, agenda_closures and agenda_counters belong to no customer and have no tenant column: the services, the week and the closures are the team's, written only after TeamPolicy answered, and read by a customer only to book.
  • Whether a time is free depends on the bookings of every space, so the availability reads them across tenants through internal/platform, which no application can import -- for the columns that say when and whether a place is taken, and no name, no note, no space.

Two Grants are issued without a signed-in customer, both in grants.go and nowhere else: the scheduler's, for the realm, and the team's, scoped to the one tenant a booking is in, after TeamPolicy allowed the member (or the task Grant was issued) and only for the action the realm's Grant was issued for. The application's hooks take a Grant the application issued, which appGrant checks.

Layout

module.go        registration, routes, the contract with the framework
config.go        what the application passes in, and the route table
contracts.go     what the application implements: notifier, directory, subjects
model.go         the entities, their own rules, and what they may answer with
schedule.go      the team's availability as pure data: which times are free
policy.go        who may do what, for a customer and for the team
service.go       the customer's use cases, and Model access after authorization
team.go          the team's use cases and its settings
app.go           the application's hooks (Settle, Find) and the two tasks
grants.go        the Grants issued without a customer
activity.go      the activity log and the notifier
handlers.go      the controllers of both sides
pages.go         what the screens are handed
screens.go       building it from what a service answered
migrations.go    the schema
translation.go   the sentences, in resources/lang
views.go         the files the application takes ownership of

Tests

export GOWORK=off
go test -race ./...

The denial suite constructs the services with a nil database, so even building Bookings(nil) would panic. The structural twin reads every exported service method and checks the same order on the allowed path, that a system Grant is issued in grants.go alone, and that the table that reads every tenant is reached only after a policy or the task Grant answered. The schedule is tested as pure data, in the zone of Sao Paulo. The feature suite runs the whole thing over a real SQLite database -- two people asking for the last place at once, the hold that lapses, the payment that arrives twice, the tenant that is never the request's -- and over the router with sessions. The views are published into a scratch project, compiled with the view compiler an application runs, and drawn once with sample data.

Licence

MIT. See LICENSE.md. Copyright HYZIS.

Documentation

Overview

Package agenda is an Arandu module: bookings on the agenda of a platform team, for the customers of a multi-tenant application.

A customer of a space books a time with the team -- a camera reconfiguration, an installation -- picking a service, a day and one of the free times, and gets a protocol number. A service that asks for a payment leaves the booking waiting for it, holding the slot for a while; the application, which owns the money, tells the module when it settled. Near the time the customer is reminded and asked to confirm or move it, and the team marks it done. The team lists every space's bookings, releases one without a payment as a courtesy, completes it, marks an absence, moves and cancels, and keeps its own services, weekly hours and closures. The two sides are separate: each has its own controllers, its own screens and its own prefix, and the application mounts each where its own session is valid.

The module takes no payment and sends no message. A balance, a charge and a Pix are the application's and arandu-wallet's; a WhatsApp message or an e-mail is whatever the application's Notifier does with an Event.

The files are laid out by role rather than by layer, so the whole package reads top to bottom:

module.go      -> registration, routes and the contract with the framework
config.go      -> what the application passes in, and the route table
contracts.go   -> what the application implements: notifier, directory, subjects
model.go       -> the entities, their own rules, and what they may answer with
schedule.go    -> the team's availability as pure data: which times are free
policy.go      -> who may do what, for a customer and for the team
service.go     -> the customer's use cases, and Model access after authorization
team.go        -> the team's use cases and its settings
app.go         -> the application's hooks and the two tasks
grants.go      -> the places a Grant is issued without a signed-in customer
activity.go    -> what is recorded in arandu-activitylog, and what is told
handlers.go    -> the controllers of both sides
pages.go       -> what the screens are handed
screens.go     -> building it from what a service answered
migrations.go  -> the schema
views.go       -> the files the application takes ownership of

An application registers it explicitly. There is no service provider, no container and no discovery: the wiring is the lines somebody wrote, and reading them is how they learn what the application is made of.

Index

Constants

View Source
const (
	// ActivityRefBooking is the subject of an entry about a booking.
	ActivityRefBooking = "agenda_booking"
	// ActivityRefService is the subject of an entry about a service.
	ActivityRefService = "agenda_service"
	// ActivityRefHour is the subject of an entry about a window of the week.
	ActivityRefHour = "agenda_hour"
	// ActivityRefClosure is the subject of an entry about a closure.
	ActivityRefClosure = "agenda_closure"
)

The kinds of subject an entry names.

View Source
const (
	ActivityBooked         = "agenda.booked"
	ActivitySettled        = "agenda.settled"
	ActivityReleased       = "agenda.released"
	ActivityConfirmed      = "agenda.confirmed"
	ActivityRescheduled    = "agenda.rescheduled"
	ActivityCancelled      = "agenda.cancelled"
	ActivityCompleted      = "agenda.completed"
	ActivityNoShow         = "agenda.no_show"
	ActivityHoldExpired    = "agenda.hold_expired"
	ActivityReminded       = "agenda.reminded"
	ActivityServiceCreated = "agenda.service_created"
	ActivityServiceUpdated = "agenda.service_updated"
	ActivityServiceDeleted = "agenda.service_deleted"
	ActivityHourCreated    = "agenda.hour_created"
	ActivityHourDeleted    = "agenda.hour_deleted"
	ActivityClosureCreated = "agenda.closure_created"
	ActivityClosureDeleted = "agenda.closure_deleted"
)

The events this package records, one per act that changes something. The subject of each entry is the booking, the service, the window or the closure.

No entry carries free text a person typed -- the customer's note, the reason of a cancellation, the team's note -- and none carries a name: the code and the identifiers are what the log keeps, and what was said stays on the booking, where the side that may read it reads it.

View Source
const (
	// DefaultPrefix is where the customer's routes are mounted when Config
	// leaves Prefix empty.
	DefaultPrefix = "/agenda"
	// DefaultTeamPrefix is where the team's routes are mounted when Config
	// leaves TeamPrefix empty.
	DefaultTeamPrefix = "/admin/agenda"
	// DefaultPageSize is how many rows one page of a list answers with when
	// Config leaves PageSize at zero.
	DefaultPageSize = 25
	// MaxPageSize is the ceiling PageSize is refused above. A page nobody
	// bounded is a page that reads the whole table on the day the table is
	// large.
	MaxPageSize = 100
	// DefaultLocale is the language of the screens, the messages and the
	// activity descriptions when Config.Locale names none.
	DefaultLocale = "pt-BR"
	// FallbackLocale answers every line the locale in use does not have.
	FallbackLocale = "en"
	// DefaultCapacity is how many bookings one slot takes.
	DefaultCapacity = 1
	// MaxCapacity is the ceiling Capacity is refused above.
	MaxCapacity = 50
	// DefaultSlotStep is the distance between two starts offered on a day.
	DefaultSlotStep = 20 * time.Minute
	// DefaultMinNotice is how far ahead of now the earliest bookable start is.
	DefaultMinNotice = 24 * time.Hour
	// DefaultHorizon is how far ahead of now the latest bookable start is.
	DefaultHorizon = 30 * 24 * time.Hour
	// MaxHorizon is the ceiling Horizon is refused above.
	MaxHorizon = 366 * 24 * time.Hour
	// DefaultPaymentHold is how long an unpaid booking keeps its slot.
	DefaultPaymentHold = 24 * time.Hour
	// DefaultRemindBefore is how long before the start the reminder goes.
	DefaultRemindBefore = 3 * time.Hour
	// DefaultChangeUntil is how long before the start a customer can still
	// reschedule or cancel.
	DefaultChangeUntil = 2 * time.Hour
	// DefaultLocation is the name of the zone the screens are written in when
	// the application passes none. The zone is required, so it is only the
	// value a documentation example uses.
	DefaultLocation = "America/Sao_Paulo"
)

The defaults for the optional settings. They are constants rather than literals inside Config.withDefaults, so the value a reader finds here is the value the package uses.

View Source
const (
	// ByCustomer is the requester or a member of their space.
	ByCustomer = "customer"
	// ByTeam is a member of the platform team.
	ByTeam = "team"
	// BySystem is a task: Remind and ExpireHolds.
	BySystem = "system"
)

The sides that can act on a booking, as Event.By and the activity log name them.

View Source
const (
	ViewIndex           = "modules.agenda.index"
	ViewNew             = "modules.agenda.form"
	ViewShow            = "modules.agenda.show"
	ViewReschedule      = "modules.agenda.reschedule"
	ViewTeamIndex       = "modules.agenda.admin.index"
	ViewTeamShow        = "modules.agenda.admin.show"
	ViewTeamServices    = "modules.agenda.admin.services"
	ViewTeamServiceForm = "modules.agenda.admin.service_form"
	ViewTeamHours       = "modules.agenda.admin.hours"
	ViewTeamHourForm    = "modules.agenda.admin.hour_form"
	ViewTeamClosures    = "modules.agenda.admin.closures"
	ViewTeamClosureForm = "modules.agenda.admin.closure_form"
)

The screens this package renders, by the name their path gives them.

View Source
const (
	// AgendaBook is looking at the services and the free times, and booking one
	// in the subject's own space.
	AgendaBook security.Action = "agenda.book"
	// AgendaViewOwn is reading the bookings the subject made themselves.
	AgendaViewOwn security.Action = "agenda.view_own"
	// AgendaViewSpace is reading every booking of the subject's space, whoever
	// made it: for the people who run the space, beside those they run it for.
	AgendaViewSpace security.Action = "agenda.view_space"
	// AgendaChange is confirming, rescheduling and cancelling a booking the
	// subject can read.
	AgendaChange security.Action = "agenda.change"

	// AgendaViewAll is the team reading every booking of every space.
	AgendaViewAll security.Action = "agenda.view_all"
	// AgendaManage is the team acting on a booking: releasing it as a courtesy,
	// completing it, marking the customer absent, moving and cancelling it.
	AgendaManage security.Action = "agenda.manage"
	// AgendaConfigure is the team changing its services, its weekly hours and its
	// closures.
	AgendaConfigure security.Action = "agenda.configure"

	// AgendaSettle is the application putting a payment on a booking, or looking
	// a booking up, from its own code. It is not a subject's action: no person
	// holds it, and the application issues a Grant for it after it decided that
	// the payment is real.
	AgendaSettle security.Action = "agenda.settle"
	// AgendaRunTasks is the scheduler running Remind and ExpireHolds. It is not a
	// subject's action either: there is nobody signed in, and the tasks issue
	// the Grant for it themselves.
	AgendaRunTasks security.Action = "agenda.run_tasks"
)

The actions of this package. Constants rather than strings at the call site: a typo in an action name would silently authorize nothing, or worse, everything.

They carry the entity in the name because an application registers many packages, and the name of an action shows up in logs and in audit trails where "view" on its own says nothing about what was viewed.

The actions are what an arandu-permission group carries: the application declares them in the catalogue (Actions and TeamActions), an organization or the platform grants them to whom it decides, and arandu-permission fills the subject's actions on every request. Nothing here is decided by a role.

View Source
const ActivityLogName = "agenda"

ActivityLogName is the log every entry of this package is recorded in.

View Source
const PublishCommand = "aru vendor:publish --apply"

PublishCommand is what an application runs to take ownership of the views this package offers.

It is spelled out as a constant so that whatever says it -- the refusal below, or a message an application writes for its own operators -- says one thing. A person who is told two different commands for one job tries both.

The command reads the modules the application registered and writes what each one declares, which is why it is the application's command and not this package's: nothing outside the application knows which modules it holds.

View Source
const TranslationGroup = "agenda"

TranslationGroup is the file every key of this package lives in, and the prefix of every key: "agenda.screen.index_title".

Variables

View Source
var DefaultPaths = Paths{
	New: "/new", Confirmation: "/confirmation", Rescheduling: "/rescheduling", Cancellation: "/cancellation",
	Completion: "/completion", Release: "/release", NoShow: "/no-show",
	Settings: "/settings", Services: "/services", Hours: "/hours", Closures: "/closures",
}

DefaultPaths are the English segments.

View Source
var ErrNoAccount = errors.New("agenda: the directory does not know that person")

ErrNoAccount is what a Directory answers when it does not know the person.

View Source
var ErrNotFound = fmt.Errorf("agenda: record not found: %w", model.ErrModelNotFound)

ErrNotFound is returned when no row matches, including when the row exists in another tenant. The two cases are deliberately indistinguishable.

It wraps model.ErrModelNotFound, so the router answers it with 404 and a caller can still ask for it by name with errors.Is.

View Source
var ErrNotSettleable = errors.New("agenda: that booking cannot take a payment in its state")

ErrNotSettleable is what Settle answers for a booking that cannot take a payment: it was cancelled, completed or never waited for one.

View Source
var ErrSlotTaken = errors.New("agenda: that time is not available any more")

ErrSlotTaken is what Book, Reschedule, Settle and Release answer when the start asked for is not free any more: somebody else took the last place, the team closed the day, or the hold of an unpaid booking lapsed and another booking was made in its place. An application that paid for a booking it then cannot keep refunds it, or books again.

View Source
var PortuguesePaths = Paths{
	New: "/novo", Confirmation: "/confirmacao", Rescheduling: "/reagendamento", Cancellation: "/cancelamento",
	Completion: "/conclusao", Release: "/liberacao", NoShow: "/ausencia",
	Settings: "/configuracoes", Services: "/servicos", Hours: "/horarios", Closures: "/bloqueios",
}

PortuguesePaths are the segments in Brazilian Portuguese, for an application whose addresses are written in it. Mounted at "/painel/agendamentos" and "/admin/agenda" they read /painel/agendamentos/novo, /painel/agendamentos/{id}/confirmacao and /admin/agenda/{id}/conclusao.

Statuses are every status, in the order the screens list them.

Functions

func Actions

func Actions() []security.Action

Actions are the customer's actions, for an application to declare in arandu-permission's catalogue beside its own, so an organization grants them to whom it decides.

func Lines

func Lines(locale string) translation.Lines

Lines are the sentences this package ships for one locale, keyed the way a translator asks for them ("agenda.validation.required"), and nil for a locale it does not ship. An application reads them to see what there is to override, or to check a catalogue of its own against them.

func Locales

func Locales() []string

Locales are the languages the package ships.

func Minutes

func Minutes(n int) string

Minutes writes minutes since midnight as a time of day: 540 is "09:00".

func PublishedPaths

func PublishedPaths() []string

PublishedPaths are the files in the archive, each relative to the root of the application, sorted.

func StatusVariant

func StatusVariant(key string) string

StatusVariant is the badge variant a status wears: the ones that wait stand out, the ones that are over fade.

func TeamActions

func TeamActions() []security.Action

TeamActions are the platform team's actions. They are declared apart from Actions so a catalogue an organization grants from never holds them: an application gives them to the groups of its own team only, and TeamPolicy refuses them to any subject outside Config.TeamTenant besides.

func ViewNames

func ViewNames() []string

ViewNames are the names the published views are rendered by, sorted.

The name is the path under the view root with its separators turned into dots, which is what the view compiler writes into the registration call. It is derived from the same archive the publication carries, so a view that was renamed cannot keep an old name here.

func ViewPackages

func ViewPackages() []string

ViewPackages are the directories the compiled views land in, each relative to the root of the application, sorted and without repeats.

Importing one is what puts its views in the binary: a compiled view calls the registry from init(), and a package nothing imports is not linked at all. The import is named rather than written into bootstrap/app.go, because one line somebody reads beats a file that changed while they were not looking.

Types

type AppService

type AppService struct {
	// contains filtered or unexported fields
}

AppService is what the application's own code calls: the payment that settles a booking, the lookup of one by its protocol, and the two tasks the scheduler runs.

It authorizes by Grant and not by subject. Settle and Find take a Grant the application issued for AgendaSettle for the space of the booking, after it decided that the payment is real -- a webhook it verified, a balance it debited. The tasks have nobody signed in, and issue their own, in grants.go. Nothing here is reachable from a route.

func NewAppService

func NewAppService(db *data.DB, cfg Config) *AppService

NewAppService wires the service over the application's database handle.

func (*AppService) ExpireHolds

func (s *AppService) ExpireHolds(ctx context.Context) (int, error)

ExpireHolds frees the slot of every booking that waited for a payment past its hold: it becomes expired, and the customer is told. A booking whose payment arrives afterwards can still be settled if its slot is free. It returns how many it expired.

The application schedules it every few minutes. Until it runs, a lapsed hold already frees its slot -- availability reads the clock, not the status -- so the task only keeps the statuses honest and tells the customer.

func (*AppService) Find

func (s *AppService) Find(ctx context.Context, g security.Grant, ref string) (*Booking, error)

Find returns a booking of the Grant's space by its identifier or by its protocol code ("AG-000123"). A booking of another space is not found.

func (*AppService) Remind

func (s *AppService) Remind(ctx context.Context) (int, error)

Remind tells the customer of every booking that is still to be confirmed and starts within Config.RemindBefore: one Reminder each, carrying the paths of the screens where they confirm or move it. A booking is reminded once -- the moment is written before the Notifier is asked, by a statement that only the first of two overlapping runs wins -- and a booking moved to another time is reminded again for the new one. It returns how many it reminded.

The application schedules it every few minutes.

func (*AppService) Settle

func (s *AppService) Settle(ctx context.Context, g security.Grant, bookingID, paymentRef string) (*Booking, error)

Settle puts the application's payment on a booking that waits for one: it holds its slot for good, and the customer is told.

It is idempotent. A payment delivered twice -- a webhook that is retried -- is the second call finding the booking settled with the same reference, and it answers the booking as it is, with nothing written and nobody told again.

A booking whose hold lapsed is settled only if its slot is still free. When it is not -- somebody booked it in the meantime -- the answer is ErrSlotTaken, and the application refunds the payment or books again. A booking in a state that takes no payment -- cancelled, or already settled with another reference -- answers ErrNotSettleable, for the same reason.

type BookInput

type BookInput struct {
	// Service is the key of the service: "reconfiguracao".
	Service string
	// Start is the start asked for, an instant. It has to be one of the starts
	// Slots offers for its day.
	Start time.Time
	// Subject is what the booking is about; see BookingSubject.
	Subject BookingSubject
	// Note is a free line from the customer to the team.
	Note string
}

BookInput is what a customer asks for when booking. There is no tenant, no requester and no status here and there must never be one: the tenant and the requester come from the Grant and the subject, and the status is the module's.

type Booking

type Booking struct {
	model.Model

	// ID is the identifier, generated by the application.
	ID string `db:"id"`

	// TenantID is the space the booking belongs to. It is written from the Grant
	// and read back so the policy can compare it against the subject's tenant.
	TenantID string `db:"tenant_id"`

	// Code is the protocol number people say: "AG-000123". It is taken from the
	// counter, which every space shares, so it names one booking.
	Code string `db:"code"`

	// ServiceKey and ServiceName are the service as it was when the booking was
	// made. The name is a copy: renaming a service does not rewrite what a
	// customer booked.
	ServiceKey  string `db:"service_key"`
	ServiceName string `db:"service_name"`

	// SubjectType, SubjectID and SubjectLabel are what the booking is about,
	// opaque to this package: the application passes "camera", its own
	// identifier and a name for the screens.
	SubjectType  string `db:"subject_type"`
	SubjectID    string `db:"subject_id"`
	SubjectLabel string `db:"subject_label"`

	// RequesterID is the user of the tenant who booked. The application owns
	// what a user is; this package only compares the identifier with the
	// subject's. RequesterName is who they were when they booked, as the
	// Directory answered.
	RequesterID   string `db:"requester_id"`
	RequesterName string `db:"requester_name"`

	// CustomerNote is the line the customer left for the team.
	CustomerNote string `db:"customer_note"`

	// StartsAt and EndsAt are the slot the booking holds, in UTC.
	StartsAt time.Time `db:"starts_at"`
	EndsAt   time.Time `db:"ends_at"`

	// Status is where the booking stands.
	Status Status `db:"status"`

	// HoldUntil is when a booking that waits for payment gives its slot up. It
	// is nil once the booking holds its slot for good.
	HoldUntil *time.Time `db:"hold_until"`

	// PaymentRef is the application's reference of the payment that settled the
	// booking. Empty while nothing did.
	PaymentRef string `db:"payment_ref"`

	// ReleasedBy and ReleasedReason say who let the booking through without a
	// payment, and why.
	ReleasedBy     string `db:"released_by"`
	ReleasedReason string `db:"released_reason"`

	// ConfirmedAt is when the customer confirmed, RemindedAt when the reminder
	// went, CompletedAt when the team did the work. All in UTC.
	ConfirmedAt *time.Time `db:"confirmed_at"`
	RemindedAt  *time.Time `db:"reminded_at"`
	CompletedAt *time.Time `db:"completed_at"`

	// CompletedBy is the team member who marked it done, and TeamNote what they
	// wrote. The customer reads neither.
	CompletedBy string `db:"completed_by"`
	TeamNote    string `db:"team_note"`

	// Reschedules counts how many times the booking was moved.
	Reschedules int `db:"reschedules"`

	// CancelReason and CancelledBy say why a booking was cancelled and which
	// side did it.
	CancelReason string `db:"cancel_reason"`
	CancelledBy  string `db:"cancelled_by"`

	// CreatedAt is when the row was written, in UTC, and UpdatedAt when it last
	// changed.
	CreatedAt time.Time `db:"created_at"`
	UpdatedAt time.Time `db:"updated_at"`
}

Booking is one place taken on the team's agenda by a customer of a tenant.

It embeds the model, so a row returned by a query carries the connection and can be saved again. Build a new row with Bookings(db).New(): a struct literal has no connection and its write methods return model.ErrUnwired.

Bookings, BookingQuery and BookingCollection are generated beside this file, in BookingQuery.go, by aru model:build.

func (Booking) CanComplete

func (b Booking) CanComplete() bool

CanComplete reports whether the team can mark the booking as done.

func (Booking) CanConfirm

func (b Booking) CanConfirm(now time.Time) bool

CanConfirm reports whether the customer can confirm the booking: it holds its slot for good, it was not confirmed yet, and it has not started.

func (Booking) CanMove

func (b Booking) CanMove() bool

CanMove reports whether the booking can be moved to another time: it still has a place to give up.

func (Booking) CanNoShow

func (b Booking) CanNoShow(now time.Time) bool

CanNoShow reports whether the customer can be marked as absent: the booking held its slot and its start has passed.

func (Booking) CanSettle

func (b Booking) CanSettle() bool

CanSettle reports whether a payment can be put on the booking: it waits for one, or its hold lapsed.

func (*Booking) Cancel

func (b *Booking) Cancel(side, reason string, now time.Time) error

Cancel gives the slot up. side is who did it: ByCustomer or ByTeam.

func (Booking) ChangeOpen

func (b Booking) ChangeOpen(now time.Time, until time.Duration) bool

ChangeOpen reports whether a customer can still move or cancel the booking: it can be moved, and the start is further away than until.

func (*Booking) Complete

func (b *Booking) Complete(by, note string, now time.Time) error

Complete records that the team did the work.

func (*Booking) Confirm

func (b *Booking) Confirm(now time.Time) error

Confirm records that the customer will come.

func (*Booking) Expire

func (b *Booking) Expire(now time.Time) error

Expire gives up the slot of a booking whose hold is over.

func (*Booking) Fresh

func (row *Booking) Fresh(ctx context.Context, g auth.Grant, with ...string) (*Booking, error)

Fresh reads the row again, as a new Booking; it shadows the untyped one the embedded model promotes.

func (Booking) Lapsed

func (b Booking) Lapsed(now time.Time) bool

Lapsed reports whether the booking waited for a payment and its hold is over, whether or not ExpireHolds already said so.

func (*Booking) MarkNoShow

func (b *Booking) MarkNoShow(now time.Time) error

MarkNoShow records that the customer did not turn up.

func (*Booking) Move

func (b *Booking) Move(start, end, now time.Time) error

Move gives the booking another time. The payment, the code and the hold stay; the confirmation and the reminder belong to the old time and go, so the new one is reminded and confirmed on its own.

func (Booking) Occupies

func (b Booking) Occupies(now time.Time) bool

Occupies reports whether the booking holds its slot at that moment: it is scheduled or confirmed, or it waits for a payment inside its hold.

func (*Booking) Release

func (b *Booking) Release(by, reason string, now time.Time) error

Release lets the booking through without a payment, and keeps who did it and why.

func (*Booking) Replicate

func (row *Booking) Replicate(except ...string) (*Booking, error)

Replicate returns an unsaved copy of the row without its key; it shadows the untyped one the embedded model promotes.

func (*Booking) Settle

func (b *Booking) Settle(ref string, now time.Time) error

Settle puts the application's payment on the booking: the slot is held for good and the hold is over.

type BookingCollection

type BookingCollection []*Booking

BookingCollection is rows of Booking, as a query returns them.

func BookingCollectionOf

func BookingCollectionOf(rows model.Rows) BookingCollection

BookingCollectionOf converts rows of the table of Booking. A nil input is a nil collection.

func (BookingCollection) Contains

func (c BookingCollection) Contains(key any) bool

func (BookingCollection) Except

func (c BookingCollection) Except(keys ...any) BookingCollection

func (BookingCollection) Find

func (c BookingCollection) Find(key any) *Booking

func (BookingCollection) FindOrFail

func (c BookingCollection) FindOrFail(key any) (*Booking, error)

func (BookingCollection) Fresh

func (BookingCollection) Load

func (c BookingCollection) Load(ctx context.Context, g auth.Grant, relations ...string) error

func (BookingCollection) LoadCount

func (c BookingCollection) LoadCount(ctx context.Context, g auth.Grant, relations ...string) error

func (BookingCollection) LoadMissing

func (c BookingCollection) LoadMissing(ctx context.Context, g auth.Grant, relations ...string) error

func (BookingCollection) ModelKeys

func (c BookingCollection) ModelKeys() []any

func (BookingCollection) Only

func (c BookingCollection) Only(keys ...any) BookingCollection

func (BookingCollection) Pluck

func (c BookingCollection) Pluck(column string) []any

func (BookingCollection) Rows

func (c BookingCollection) Rows() model.Rows

Rows converts the collection back to the core's rows.

func (BookingCollection) ToArray

func (c BookingCollection) ToArray() []map[string]any

func (BookingCollection) Unique

type BookingPolicy

type BookingPolicy struct{}

BookingPolicy is the only authority over what a customer does with a Booking.

It denies unless a rule below says otherwise, and every rule reads what the subject was granted: a subject with no actions, an administrator included, is refused everything. Ownership decides the rest -- a customer reads and changes the bookings they made, and the whole space's only with AgendaViewSpace -- and the tenant of the record is checked first, before any rule, so a rule that opens an action opens it inside one space only.

func (BookingPolicy) Can

Can decides whether the subject may perform the action on the record.

It is the only place that decides. The service reaches the Model only after Authorize turns this method's nil result into a Grant.

The record is the empty Booking where the question is "may this subject do this kind of thing at all", and the loaded row where it is "may they do it to this booking". Both are asked, in that order, and the second is what a rule about ownership answers.

func (BookingPolicy) Writes

func (BookingPolicy) Writes(a security.Action) bool

Writes reports whether a Grant issued for the action may change anything.

type BookingQuery

type BookingQuery struct {
	// contains filtered or unexported fields
}

BookingQuery is a query on the table of Booking.

The methods that build return the query, so they chain. The methods that run take a context and an auth.Grant, and return Booking rows or a value; there is no way to run one without a Grant.

func Bookings

func Bookings(db model.DB) *BookingQuery

Bookings starts a query on the table of Booking, through db.

Global scopes are on and, unless the table is Global, every statement is filtered by the tenant of the Grant its terminal takes.

func (*BookingQuery) AddSelect

func (q *BookingQuery) AddSelect(columns ...any) *BookingQuery

func (*BookingQuery) ApplyListing

func (q *BookingQuery) ApplyListing(state pagination.ListingState) *BookingQuery

ApplyListing narrows and orders the query as a listing state asks: the search, the facets and the sort with its tie-break. Every column comes from the spec the state was read with, never from the request.

func (*BookingQuery) Avg

func (q *BookingQuery) Avg(ctx context.Context, g auth.Grant, column any) (any, error)

func (*BookingQuery) Base

func (q *BookingQuery) Base() *model.Builder

Base returns the core builder the query forwards to. It is for code in this package -- a local scope in the custom block of model.go -- and for the factory, which builds rows through it.

func (*BookingQuery) Chunk

func (q *BookingQuery) Chunk(ctx context.Context, g auth.Grant, count int, callback func(BookingCollection, int) (bool, error)) error

func (*BookingQuery) Clone

func (q *BookingQuery) Clone() *BookingQuery

Clone returns an independent copy of the query.

func (*BookingQuery) Count

func (q *BookingQuery) Count(ctx context.Context, g auth.Grant, columns ...any) (int64, error)

func (*BookingQuery) Create

func (q *BookingQuery) Create(ctx context.Context, g auth.Grant, attributes map[string]any) (*Booking, error)

func (*BookingQuery) Cursor

func (q *BookingQuery) Cursor(ctx context.Context, g auth.Grant) iter.Seq2[*Booking, error]

func (*BookingQuery) CursorPaginate

func (q *BookingQuery) CursorPaginate(ctx context.Context, g auth.Grant, perPage int, cursor *pagination.Cursor, opts pagination.Options, columns ...any) (BookingCollection, *pagination.CursorPage, error)

func (*BookingQuery) Decrement

func (q *BookingQuery) Decrement(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*BookingQuery) Delete

func (q *BookingQuery) Delete(ctx context.Context, g auth.Grant) (int64, error)

func (*BookingQuery) DoesntExist

func (q *BookingQuery) DoesntExist(ctx context.Context, g auth.Grant) (bool, error)

func (*BookingQuery) DoesntHave

func (q *BookingQuery) DoesntHave(relation, boolean string, callback func(*query.Builder)) *BookingQuery

func (*BookingQuery) Each

func (q *BookingQuery) Each(ctx context.Context, g auth.Grant, count int, callback func(*Booking, int) (bool, error)) error

func (*BookingQuery) Exists

func (q *BookingQuery) Exists(ctx context.Context, g auth.Grant) (bool, error)

func (*BookingQuery) Find

func (q *BookingQuery) Find(ctx context.Context, g auth.Grant, id any, columns ...any) (*Booking, error)

func (*BookingQuery) FindMany

func (q *BookingQuery) FindMany(ctx context.Context, g auth.Grant, ids []any, columns ...any) (BookingCollection, error)

func (*BookingQuery) FindOrFail

func (q *BookingQuery) FindOrFail(ctx context.Context, g auth.Grant, id any, columns ...any) (*Booking, error)

func (*BookingQuery) FindOrNew

func (q *BookingQuery) FindOrNew(ctx context.Context, g auth.Grant, id any, columns ...any) (*Booking, error)

func (*BookingQuery) First

func (q *BookingQuery) First(ctx context.Context, g auth.Grant, columns ...any) (*Booking, error)

First returns the first row, or nil and no error when there is none.

func (*BookingQuery) FirstOrCreate

func (q *BookingQuery) FirstOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Booking, error)

func (*BookingQuery) FirstOrFail

func (q *BookingQuery) FirstOrFail(ctx context.Context, g auth.Grant, columns ...any) (*Booking, error)

func (*BookingQuery) FirstOrNew

func (q *BookingQuery) FirstOrNew(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Booking, error)

func (*BookingQuery) FirstWhere

func (q *BookingQuery) FirstWhere(ctx context.Context, g auth.Grant, column any, args ...any) (*Booking, error)

func (*BookingQuery) ForPage

func (q *BookingQuery) ForPage(page, perPage int) *BookingQuery

func (*BookingQuery) ForceCreate

func (q *BookingQuery) ForceCreate(ctx context.Context, g auth.Grant, attributes map[string]any) (*Booking, error)

func (*BookingQuery) Get

func (q *BookingQuery) Get(ctx context.Context, g auth.Grant, columns ...any) (BookingCollection, error)

Get runs the query and returns the rows.

func (*BookingQuery) GroupBy

func (q *BookingQuery) GroupBy(groups ...any) *BookingQuery

func (*BookingQuery) Has

func (q *BookingQuery) Has(relation, operator string, count int, boolean string, callback func(*query.Builder)) *BookingQuery

func (*BookingQuery) Increment

func (q *BookingQuery) Increment(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*BookingQuery) Insert

func (q *BookingQuery) Insert(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*BookingQuery) InsertOrIgnore

func (q *BookingQuery) InsertOrIgnore(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*BookingQuery) Join

func (q *BookingQuery) Join(table any, first any, args ...any) *BookingQuery

func (*BookingQuery) Latest

func (q *BookingQuery) Latest(column ...string) *BookingQuery

func (*BookingQuery) Limit

func (q *BookingQuery) Limit(value int) *BookingQuery

func (*BookingQuery) Listing

Listing runs the query as a listing state asks and returns the rows of the page beside the result a table is drawn from: the state, the page with its total and the count of every facet value. Every statement it issues carries the tenant of g.

func (*BookingQuery) Max

func (q *BookingQuery) Max(ctx context.Context, g auth.Grant, column any) (any, error)

func (*BookingQuery) Min

func (q *BookingQuery) Min(ctx context.Context, g auth.Grant, column any) (any, error)

func (*BookingQuery) New

func (q *BookingQuery) New() (*Booking, error)

New returns an empty Booking on the query's connection, not yet saved, filled with what WithAttributes recorded on the query.

func (*BookingQuery) Offset

func (q *BookingQuery) Offset(value int) *BookingQuery

func (*BookingQuery) Oldest

func (q *BookingQuery) Oldest(column ...string) *BookingQuery

func (*BookingQuery) OrDoesntHave

func (q *BookingQuery) OrDoesntHave(relation string) *BookingQuery

func (*BookingQuery) OrHas

func (q *BookingQuery) OrHas(relation, operator string, count int) *BookingQuery

func (*BookingQuery) OrWhere

func (q *BookingQuery) OrWhere(column any, args ...any) *BookingQuery

OrWhere adds an or-where clause; a func(*BookingQuery) in place of the column adds a group.

func (*BookingQuery) OrWhereDoesntHave

func (q *BookingQuery) OrWhereDoesntHave(relation string, callback func(*query.Builder)) *BookingQuery

func (*BookingQuery) OrWhereHas

func (q *BookingQuery) OrWhereHas(relation string, callback func(*query.Builder)) *BookingQuery

func (*BookingQuery) OrWhereNot

func (q *BookingQuery) OrWhereNot(column any, args ...any) *BookingQuery

OrWhereNot adds an or-joined negated where clause, or a negated group.

func (*BookingQuery) OrWhereRelation

func (q *BookingQuery) OrWhereRelation(relation string, column any, args ...any) *BookingQuery

func (*BookingQuery) OrderBy

func (q *BookingQuery) OrderBy(column any, direction ...string) *BookingQuery

func (*BookingQuery) OrderByDesc

func (q *BookingQuery) OrderByDesc(column any) *BookingQuery

func (*BookingQuery) Paginate

func (q *BookingQuery) Paginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (BookingCollection, *pagination.LengthAwarePage, error)

func (*BookingQuery) Pluck

func (q *BookingQuery) Pluck(ctx context.Context, g auth.Grant, column string) ([]any, error)

func (*BookingQuery) Select

func (q *BookingQuery) Select(columns ...any) *BookingQuery

func (*BookingQuery) SelectRaw

func (q *BookingQuery) SelectRaw(expression string, bindings ...any) *BookingQuery

func (*BookingQuery) SimplePaginate

func (q *BookingQuery) SimplePaginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (BookingCollection, *pagination.Page, error)

func (*BookingQuery) Sole

func (q *BookingQuery) Sole(ctx context.Context, g auth.Grant, columns ...any) (*Booking, error)

func (*BookingQuery) SoleValue

func (q *BookingQuery) SoleValue(ctx context.Context, g auth.Grant, column string) (any, error)

func (*BookingQuery) Sum

func (q *BookingQuery) Sum(ctx context.Context, g auth.Grant, column any) (any, error)

func (*BookingQuery) Touch

func (q *BookingQuery) Touch(ctx context.Context, g auth.Grant, column ...string) (int64, error)

func (*BookingQuery) Update

func (q *BookingQuery) Update(ctx context.Context, g auth.Grant, values map[string]any) (int64, error)

func (*BookingQuery) UpdateOrCreate

func (q *BookingQuery) UpdateOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Booking, error)

func (*BookingQuery) Upsert

func (q *BookingQuery) Upsert(ctx context.Context, g auth.Grant, values []map[string]any, uniqueBy, update []string) (int64, error)

func (*BookingQuery) Value

func (q *BookingQuery) Value(ctx context.Context, g auth.Grant, column string) (any, error)

func (*BookingQuery) ValueOrFail

func (q *BookingQuery) ValueOrFail(ctx context.Context, g auth.Grant, column string) (any, error)

func (*BookingQuery) Where

func (q *BookingQuery) Where(column any, args ...any) *BookingQuery

Where adds a where clause; a func(*BookingQuery) in place of the column adds a group.

func (*BookingQuery) WhereBelongsTo

func (q *BookingQuery) WhereBelongsTo(relationshipName string, related ...model.Entity) *BookingQuery

func (*BookingQuery) WhereBetween

func (q *BookingQuery) WhereBetween(column any, from, to any) *BookingQuery

func (*BookingQuery) WhereColumn

func (q *BookingQuery) WhereColumn(first any, args ...any) *BookingQuery

func (*BookingQuery) WhereDoesntHave

func (q *BookingQuery) WhereDoesntHave(relation string, callback func(*query.Builder)) *BookingQuery

func (*BookingQuery) WhereExists

func (q *BookingQuery) WhereExists(callback func(*query.Builder)) *BookingQuery

func (*BookingQuery) WhereHas

func (q *BookingQuery) WhereHas(relation string, callback func(*query.Builder)) *BookingQuery

func (*BookingQuery) WhereHasCount

func (q *BookingQuery) WhereHasCount(relation string, callback func(*query.Builder), operator string, count int) *BookingQuery

func (*BookingQuery) WhereIn

func (q *BookingQuery) WhereIn(column any, values []any) *BookingQuery

func (*BookingQuery) WhereKey

func (q *BookingQuery) WhereKey(id any) *BookingQuery

func (*BookingQuery) WhereNot

func (q *BookingQuery) WhereNot(column any, args ...any) *BookingQuery

WhereNot adds a negated where clause, or a negated group.

func (*BookingQuery) WhereNotExists

func (q *BookingQuery) WhereNotExists(callback func(*query.Builder)) *BookingQuery

func (*BookingQuery) WhereNotIn

func (q *BookingQuery) WhereNotIn(column any, values []any) *BookingQuery

func (*BookingQuery) WhereNotNull

func (q *BookingQuery) WhereNotNull(columns ...any) *BookingQuery

func (*BookingQuery) WhereNull

func (q *BookingQuery) WhereNull(columns ...any) *BookingQuery

func (*BookingQuery) WhereRelation

func (q *BookingQuery) WhereRelation(relation string, column any, args ...any) *BookingQuery

func (*BookingQuery) With

func (q *BookingQuery) With(relations ...string) *BookingQuery

func (*BookingQuery) WithAvg

func (q *BookingQuery) WithAvg(relation, column string) *BookingQuery

func (*BookingQuery) WithCount

func (q *BookingQuery) WithCount(relations ...string) *BookingQuery

func (*BookingQuery) WithExists

func (q *BookingQuery) WithExists(relation string) *BookingQuery

func (*BookingQuery) WithMax

func (q *BookingQuery) WithMax(relation, column string) *BookingQuery

func (*BookingQuery) WithMin

func (q *BookingQuery) WithMin(relation, column string) *BookingQuery

func (*BookingQuery) WithSum

func (q *BookingQuery) WithSum(relation, column string) *BookingQuery

func (*BookingQuery) Without

func (q *BookingQuery) Without(relations ...string) *BookingQuery

func (*BookingQuery) WithoutGlobalScope

func (q *BookingQuery) WithoutGlobalScope(identifier string) *BookingQuery

func (*BookingQuery) WithoutGlobalScopes

func (q *BookingQuery) WithoutGlobalScopes(identifiers ...string) *BookingQuery

type BookingRow

type BookingRow struct {
	ID, Code             string
	Service, ServiceKey  string
	Subject, SubjectType string
	SubjectID            string
	Status, StatusKey    string
	Day, Time, Ends      string
	When                 string
	Requester            string
	RequesterID          string
	Space                string
	Note                 string
	PaymentRef           string
	HoldUntil            string
	Confirmed, Reminded  string
	Completed            string
	CompletedBy          string
	TeamNote             string
	ReleasedBy           string
	ReleasedReason       string
	CancelReason         string
	CancelledBy          string
	Created, Updated     string
	// StartsSort orders like the instant it stands for.
	StartsSort  string
	Reschedules int
	URL         string
}

BookingRow is one booking as a list or a page shows it.

type BookingService

type BookingService struct {
	// contains filtered or unexported fields
}

BookingService orchestrates what a customer does with the agenda: it validates the request, asks the policy for a Grant, applies the rules the entity holds for itself, and persists with that Grant.

It receives its collaborators through the constructor. There is no container and no resolution by reflection: what this service is made of is written at the one place that builds it, and reading that place is how somebody learns what the package touches.

Everything a handler is allowed to do for a customer goes through here. The service is the only owner of the database handle on this side, so the request layer cannot reach a Model before the policy has answered.

func NewBookingService

func NewBookingService(db *data.DB, cfg Config) *BookingService

NewBookingService wires the service over the application's database handle.

func (*BookingService) Book

func (s *BookingService) Book(ctx context.Context, actor security.Subject, in BookInput) (*Booking, error)

Book takes a place on the team's agenda for the signed-in customer, in their own space.

The slot is checked again inside a transaction that holds the lock of the protocol counter, so two people asking for the last place take turns and the second is told ErrSlotTaken. A service that asks for a payment leaves the booking waiting for it, holding the slot for Config.PaymentHold; any other is scheduled at once.

func (*BookingService) Booking

func (s *BookingService) Booking(ctx context.Context, actor security.Subject, id string) (Summary, error)

Booking returns one booking the customer may read. A booking of another space, and one of the same space the subject may not read, are not found.

func (*BookingService) Bookings

func (s *BookingService) Bookings(ctx context.Context, actor security.Subject, q ListQuery) (Page, error)

Bookings returns a page of the customer's bookings: their own, or the whole space's when the policy allows it, searched, filtered by status and ordered by the server.

func (*BookingService) CanBook

func (s *BookingService) CanBook(ctx context.Context, actor security.Subject) error

CanBook answers whether the subject may book, for the screen that draws the form and the button that opens it. It asks the policy exactly as Book does, and the refusal it returns is the one Book would.

func (*BookingService) Cancel

func (s *BookingService) Cancel(ctx context.Context, actor security.Subject, id, reason string) (*Booking, error)

Cancel gives the slot up, until Config.ChangeUntil before the start. The reason is the customer's own words, kept on the booking and never in the log.

func (*BookingService) Confirm

func (s *BookingService) Confirm(ctx context.Context, actor security.Subject, id string) (*Booking, error)

Confirm records that the customer will come. Only a booking that holds its slot for good, and has not started, can be confirmed.

func (*BookingService) Reschedule

func (s *BookingService) Reschedule(ctx context.Context, actor security.Subject, id string, newStart time.Time) (*Booking, error)

Reschedule moves the booking to another start, which has to be one Slots offers, until Config.ChangeUntil before the start it has. The payment, the protocol and the hold stay; the confirmation and the reminder belong to the old time and go.

func (*BookingService) Services

func (s *BookingService) Services(ctx context.Context, actor security.Subject) ([]ServiceView, error)

Services returns the services the team offers, the ones a customer can book.

func (*BookingService) Slots

func (s *BookingService) Slots(ctx context.Context, actor security.Subject, serviceKey string, day time.Time) ([]time.Time, error)

Slots returns the free starts of one day for a service, sorted: inside the team's weekly hours, outside its closures, with a place free, no sooner than Config.MinNotice and no later than Config.Horizon from now. Only the calendar date of day counts, read in Config.Zone.

type BookingSubject

type BookingSubject struct {
	Type  string
	ID    string
	Label string
}

BookingSubject is what a booking is about, opaque to this package: the application passes a kind, its own identifier and a label for the screens.

type ChromeRequest

type ChromeRequest struct {
	// Title is the screen's title, already in the screen's language, without
	// the application's name Config.TitleSeparator adds to the document title.
	Title string
	// Team says the screen is one of the team's, mounted under TeamPrefix.
	Team bool
	// Subject is who is asking, as RequireAuth and Config.Middleware left it.
	Subject security.Subject
}

ChromeRequest is what Config.Chrome is asked about one screen.

type Closure

type Closure struct {
	model.Model

	// ID is the identifier, generated by the application.
	ID string `db:"id"`

	// StartsAt and EndsAt are the range, in UTC.
	StartsAt time.Time `db:"starts_at"`
	EndsAt   time.Time `db:"ends_at"`

	// Reason is a short line for the team.
	Reason string `db:"reason"`

	// CreatedAt is when the row was written, in UTC.
	CreatedAt time.Time `db:"created_at"`
}

Closure is a range of time the team takes no booking in: a holiday, a day of training. A booking made inside it is refused; one already made is left to the team to move.

func (*Closure) Fresh

func (row *Closure) Fresh(ctx context.Context, g auth.Grant, with ...string) (*Closure, error)

Fresh reads the row again, as a new Closure; it shadows the untyped one the embedded model promotes.

func (*Closure) Replicate

func (row *Closure) Replicate(except ...string) (*Closure, error)

Replicate returns an unsaved copy of the row without its key; it shadows the untyped one the embedded model promotes.

type ClosureCollection

type ClosureCollection []*Closure

ClosureCollection is rows of Closure, as a query returns them.

func ClosureCollectionOf

func ClosureCollectionOf(rows model.Rows) ClosureCollection

ClosureCollectionOf converts rows of the table of Closure. A nil input is a nil collection.

func (ClosureCollection) Contains

func (c ClosureCollection) Contains(key any) bool

func (ClosureCollection) Except

func (c ClosureCollection) Except(keys ...any) ClosureCollection

func (ClosureCollection) Find

func (c ClosureCollection) Find(key any) *Closure

func (ClosureCollection) FindOrFail

func (c ClosureCollection) FindOrFail(key any) (*Closure, error)

func (ClosureCollection) Fresh

func (ClosureCollection) Load

func (c ClosureCollection) Load(ctx context.Context, g auth.Grant, relations ...string) error

func (ClosureCollection) LoadCount

func (c ClosureCollection) LoadCount(ctx context.Context, g auth.Grant, relations ...string) error

func (ClosureCollection) LoadMissing

func (c ClosureCollection) LoadMissing(ctx context.Context, g auth.Grant, relations ...string) error

func (ClosureCollection) ModelKeys

func (c ClosureCollection) ModelKeys() []any

func (ClosureCollection) Only

func (c ClosureCollection) Only(keys ...any) ClosureCollection

func (ClosureCollection) Pluck

func (c ClosureCollection) Pluck(column string) []any

func (ClosureCollection) Rows

func (c ClosureCollection) Rows() model.Rows

Rows converts the collection back to the core's rows.

func (ClosureCollection) ToArray

func (c ClosureCollection) ToArray() []map[string]any

func (ClosureCollection) Unique

type ClosureFormPageData

type ClosureFormPageData struct {
	Screen
	Action, BackURL   string
	FromDay, FromTime string
	ToDay, ToTime     string
	Reason            string
}

ClosureFormPageData is the form that adds a closure.

type ClosureInput

type ClosureInput struct {
	StartsAt time.Time
	EndsAt   time.Time
	Reason   string
}

ClosureInput is a range the team does not take bookings in.

type ClosureQuery

type ClosureQuery struct {
	// contains filtered or unexported fields
}

ClosureQuery is a query on the table of Closure.

The methods that build return the query, so they chain. The methods that run take a context and an auth.Grant, and return Closure rows or a value; there is no way to run one without a Grant.

func Closures

func Closures(db model.DB) *ClosureQuery

Closures starts a query on the table of Closure, through db.

Global scopes are on and, unless the table is Global, every statement is filtered by the tenant of the Grant its terminal takes.

func (*ClosureQuery) AddSelect

func (q *ClosureQuery) AddSelect(columns ...any) *ClosureQuery

func (*ClosureQuery) ApplyListing

func (q *ClosureQuery) ApplyListing(state pagination.ListingState) *ClosureQuery

ApplyListing narrows and orders the query as a listing state asks: the search, the facets and the sort with its tie-break. Every column comes from the spec the state was read with, never from the request.

func (*ClosureQuery) Avg

func (q *ClosureQuery) Avg(ctx context.Context, g auth.Grant, column any) (any, error)

func (*ClosureQuery) Base

func (q *ClosureQuery) Base() *model.Builder

Base returns the core builder the query forwards to. It is for code in this package -- a local scope in the custom block of model.go -- and for the factory, which builds rows through it.

func (*ClosureQuery) Chunk

func (q *ClosureQuery) Chunk(ctx context.Context, g auth.Grant, count int, callback func(ClosureCollection, int) (bool, error)) error

func (*ClosureQuery) Clone

func (q *ClosureQuery) Clone() *ClosureQuery

Clone returns an independent copy of the query.

func (*ClosureQuery) Count

func (q *ClosureQuery) Count(ctx context.Context, g auth.Grant, columns ...any) (int64, error)

func (*ClosureQuery) Create

func (q *ClosureQuery) Create(ctx context.Context, g auth.Grant, attributes map[string]any) (*Closure, error)

func (*ClosureQuery) Cursor

func (q *ClosureQuery) Cursor(ctx context.Context, g auth.Grant) iter.Seq2[*Closure, error]

func (*ClosureQuery) CursorPaginate

func (q *ClosureQuery) CursorPaginate(ctx context.Context, g auth.Grant, perPage int, cursor *pagination.Cursor, opts pagination.Options, columns ...any) (ClosureCollection, *pagination.CursorPage, error)

func (*ClosureQuery) Decrement

func (q *ClosureQuery) Decrement(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*ClosureQuery) Delete

func (q *ClosureQuery) Delete(ctx context.Context, g auth.Grant) (int64, error)

func (*ClosureQuery) DoesntExist

func (q *ClosureQuery) DoesntExist(ctx context.Context, g auth.Grant) (bool, error)

func (*ClosureQuery) DoesntHave

func (q *ClosureQuery) DoesntHave(relation, boolean string, callback func(*query.Builder)) *ClosureQuery

func (*ClosureQuery) Each

func (q *ClosureQuery) Each(ctx context.Context, g auth.Grant, count int, callback func(*Closure, int) (bool, error)) error

func (*ClosureQuery) Exists

func (q *ClosureQuery) Exists(ctx context.Context, g auth.Grant) (bool, error)

func (*ClosureQuery) Find

func (q *ClosureQuery) Find(ctx context.Context, g auth.Grant, id any, columns ...any) (*Closure, error)

func (*ClosureQuery) FindMany

func (q *ClosureQuery) FindMany(ctx context.Context, g auth.Grant, ids []any, columns ...any) (ClosureCollection, error)

func (*ClosureQuery) FindOrFail

func (q *ClosureQuery) FindOrFail(ctx context.Context, g auth.Grant, id any, columns ...any) (*Closure, error)

func (*ClosureQuery) FindOrNew

func (q *ClosureQuery) FindOrNew(ctx context.Context, g auth.Grant, id any, columns ...any) (*Closure, error)

func (*ClosureQuery) First

func (q *ClosureQuery) First(ctx context.Context, g auth.Grant, columns ...any) (*Closure, error)

First returns the first row, or nil and no error when there is none.

func (*ClosureQuery) FirstOrCreate

func (q *ClosureQuery) FirstOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Closure, error)

func (*ClosureQuery) FirstOrFail

func (q *ClosureQuery) FirstOrFail(ctx context.Context, g auth.Grant, columns ...any) (*Closure, error)

func (*ClosureQuery) FirstOrNew

func (q *ClosureQuery) FirstOrNew(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Closure, error)

func (*ClosureQuery) FirstWhere

func (q *ClosureQuery) FirstWhere(ctx context.Context, g auth.Grant, column any, args ...any) (*Closure, error)

func (*ClosureQuery) ForPage

func (q *ClosureQuery) ForPage(page, perPage int) *ClosureQuery

func (*ClosureQuery) ForceCreate

func (q *ClosureQuery) ForceCreate(ctx context.Context, g auth.Grant, attributes map[string]any) (*Closure, error)

func (*ClosureQuery) Get

func (q *ClosureQuery) Get(ctx context.Context, g auth.Grant, columns ...any) (ClosureCollection, error)

Get runs the query and returns the rows.

func (*ClosureQuery) GroupBy

func (q *ClosureQuery) GroupBy(groups ...any) *ClosureQuery

func (*ClosureQuery) Has

func (q *ClosureQuery) Has(relation, operator string, count int, boolean string, callback func(*query.Builder)) *ClosureQuery

func (*ClosureQuery) Increment

func (q *ClosureQuery) Increment(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*ClosureQuery) Insert

func (q *ClosureQuery) Insert(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*ClosureQuery) InsertOrIgnore

func (q *ClosureQuery) InsertOrIgnore(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*ClosureQuery) Join

func (q *ClosureQuery) Join(table any, first any, args ...any) *ClosureQuery

func (*ClosureQuery) Latest

func (q *ClosureQuery) Latest(column ...string) *ClosureQuery

func (*ClosureQuery) Limit

func (q *ClosureQuery) Limit(value int) *ClosureQuery

func (*ClosureQuery) Listing

Listing runs the query as a listing state asks and returns the rows of the page beside the result a table is drawn from: the state, the page with its total and the count of every facet value. Every statement it issues carries the tenant of g.

func (*ClosureQuery) Max

func (q *ClosureQuery) Max(ctx context.Context, g auth.Grant, column any) (any, error)

func (*ClosureQuery) Min

func (q *ClosureQuery) Min(ctx context.Context, g auth.Grant, column any) (any, error)

func (*ClosureQuery) New

func (q *ClosureQuery) New() (*Closure, error)

New returns an empty Closure on the query's connection, not yet saved, filled with what WithAttributes recorded on the query.

func (*ClosureQuery) Offset

func (q *ClosureQuery) Offset(value int) *ClosureQuery

func (*ClosureQuery) Oldest

func (q *ClosureQuery) Oldest(column ...string) *ClosureQuery

func (*ClosureQuery) OrDoesntHave

func (q *ClosureQuery) OrDoesntHave(relation string) *ClosureQuery

func (*ClosureQuery) OrHas

func (q *ClosureQuery) OrHas(relation, operator string, count int) *ClosureQuery

func (*ClosureQuery) OrWhere

func (q *ClosureQuery) OrWhere(column any, args ...any) *ClosureQuery

OrWhere adds an or-where clause; a func(*ClosureQuery) in place of the column adds a group.

func (*ClosureQuery) OrWhereDoesntHave

func (q *ClosureQuery) OrWhereDoesntHave(relation string, callback func(*query.Builder)) *ClosureQuery

func (*ClosureQuery) OrWhereHas

func (q *ClosureQuery) OrWhereHas(relation string, callback func(*query.Builder)) *ClosureQuery

func (*ClosureQuery) OrWhereNot

func (q *ClosureQuery) OrWhereNot(column any, args ...any) *ClosureQuery

OrWhereNot adds an or-joined negated where clause, or a negated group.

func (*ClosureQuery) OrWhereRelation

func (q *ClosureQuery) OrWhereRelation(relation string, column any, args ...any) *ClosureQuery

func (*ClosureQuery) OrderBy

func (q *ClosureQuery) OrderBy(column any, direction ...string) *ClosureQuery

func (*ClosureQuery) OrderByDesc

func (q *ClosureQuery) OrderByDesc(column any) *ClosureQuery

func (*ClosureQuery) Paginate

func (q *ClosureQuery) Paginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (ClosureCollection, *pagination.LengthAwarePage, error)

func (*ClosureQuery) Pluck

func (q *ClosureQuery) Pluck(ctx context.Context, g auth.Grant, column string) ([]any, error)

func (*ClosureQuery) Select

func (q *ClosureQuery) Select(columns ...any) *ClosureQuery

func (*ClosureQuery) SelectRaw

func (q *ClosureQuery) SelectRaw(expression string, bindings ...any) *ClosureQuery

func (*ClosureQuery) SimplePaginate

func (q *ClosureQuery) SimplePaginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (ClosureCollection, *pagination.Page, error)

func (*ClosureQuery) Sole

func (q *ClosureQuery) Sole(ctx context.Context, g auth.Grant, columns ...any) (*Closure, error)

func (*ClosureQuery) SoleValue

func (q *ClosureQuery) SoleValue(ctx context.Context, g auth.Grant, column string) (any, error)

func (*ClosureQuery) Sum

func (q *ClosureQuery) Sum(ctx context.Context, g auth.Grant, column any) (any, error)

func (*ClosureQuery) Touch

func (q *ClosureQuery) Touch(ctx context.Context, g auth.Grant, column ...string) (int64, error)

func (*ClosureQuery) Update

func (q *ClosureQuery) Update(ctx context.Context, g auth.Grant, values map[string]any) (int64, error)

func (*ClosureQuery) UpdateOrCreate

func (q *ClosureQuery) UpdateOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Closure, error)

func (*ClosureQuery) Upsert

func (q *ClosureQuery) Upsert(ctx context.Context, g auth.Grant, values []map[string]any, uniqueBy, update []string) (int64, error)

func (*ClosureQuery) Value

func (q *ClosureQuery) Value(ctx context.Context, g auth.Grant, column string) (any, error)

func (*ClosureQuery) ValueOrFail

func (q *ClosureQuery) ValueOrFail(ctx context.Context, g auth.Grant, column string) (any, error)

func (*ClosureQuery) Where

func (q *ClosureQuery) Where(column any, args ...any) *ClosureQuery

Where adds a where clause; a func(*ClosureQuery) in place of the column adds a group.

func (*ClosureQuery) WhereBelongsTo

func (q *ClosureQuery) WhereBelongsTo(relationshipName string, related ...model.Entity) *ClosureQuery

func (*ClosureQuery) WhereBetween

func (q *ClosureQuery) WhereBetween(column any, from, to any) *ClosureQuery

func (*ClosureQuery) WhereColumn

func (q *ClosureQuery) WhereColumn(first any, args ...any) *ClosureQuery

func (*ClosureQuery) WhereDoesntHave

func (q *ClosureQuery) WhereDoesntHave(relation string, callback func(*query.Builder)) *ClosureQuery

func (*ClosureQuery) WhereExists

func (q *ClosureQuery) WhereExists(callback func(*query.Builder)) *ClosureQuery

func (*ClosureQuery) WhereHas

func (q *ClosureQuery) WhereHas(relation string, callback func(*query.Builder)) *ClosureQuery

func (*ClosureQuery) WhereHasCount

func (q *ClosureQuery) WhereHasCount(relation string, callback func(*query.Builder), operator string, count int) *ClosureQuery

func (*ClosureQuery) WhereIn

func (q *ClosureQuery) WhereIn(column any, values []any) *ClosureQuery

func (*ClosureQuery) WhereKey

func (q *ClosureQuery) WhereKey(id any) *ClosureQuery

func (*ClosureQuery) WhereNot

func (q *ClosureQuery) WhereNot(column any, args ...any) *ClosureQuery

WhereNot adds a negated where clause, or a negated group.

func (*ClosureQuery) WhereNotExists

func (q *ClosureQuery) WhereNotExists(callback func(*query.Builder)) *ClosureQuery

func (*ClosureQuery) WhereNotIn

func (q *ClosureQuery) WhereNotIn(column any, values []any) *ClosureQuery

func (*ClosureQuery) WhereNotNull

func (q *ClosureQuery) WhereNotNull(columns ...any) *ClosureQuery

func (*ClosureQuery) WhereNull

func (q *ClosureQuery) WhereNull(columns ...any) *ClosureQuery

func (*ClosureQuery) WhereRelation

func (q *ClosureQuery) WhereRelation(relation string, column any, args ...any) *ClosureQuery

func (*ClosureQuery) With

func (q *ClosureQuery) With(relations ...string) *ClosureQuery

func (*ClosureQuery) WithAvg

func (q *ClosureQuery) WithAvg(relation, column string) *ClosureQuery

func (*ClosureQuery) WithCount

func (q *ClosureQuery) WithCount(relations ...string) *ClosureQuery

func (*ClosureQuery) WithExists

func (q *ClosureQuery) WithExists(relation string) *ClosureQuery

func (*ClosureQuery) WithMax

func (q *ClosureQuery) WithMax(relation, column string) *ClosureQuery

func (*ClosureQuery) WithMin

func (q *ClosureQuery) WithMin(relation, column string) *ClosureQuery

func (*ClosureQuery) WithSum

func (q *ClosureQuery) WithSum(relation, column string) *ClosureQuery

func (*ClosureQuery) Without

func (q *ClosureQuery) Without(relations ...string) *ClosureQuery

func (*ClosureQuery) WithoutGlobalScope

func (q *ClosureQuery) WithoutGlobalScope(identifier string) *ClosureQuery

func (*ClosureQuery) WithoutGlobalScopes

func (q *ClosureQuery) WithoutGlobalScopes(identifiers ...string) *ClosureQuery

type ClosureRow

type ClosureRow struct {
	ID, From, To, Reason string
	DeleteURL            string
}

ClosureRow is a closure as the settings list shows it.

type ClosureView

type ClosureView struct {
	ID       string
	StartsAt time.Time
	EndsAt   time.Time
	Reason   string
}

ClosureView is a closure as a screen carries it.

type ClosuresPageData

type ClosuresPageData struct {
	Screen
	Rows                               []ClosureRow
	Query                              string
	SortKey, SortDir                   string
	URL, NewURL                        string
	Pager                              components.Paginator
	CurrentPage                        int
	Pages, Total                       int
	PerPage                            int
	CanConfigure                       bool
	ServicesURL, HoursURL, ClosuresURL string
}

ClosuresPageData is the team's list of closures.

func (ClosuresPageData) TableState

TableState is the list as the data table draws its addresses from.

type Config

type Config struct {
	// TeamTenant is the tenant the platform's own team signs in to: the realm
	// of the operator console. A team member is a subject of this tenant who
	// holds the team's actions, and the team policy refuses any other tenant's
	// subject whatever actions they carry. The services, the weekly hours and
	// the closures are the team's, and only a subject of this tenant changes
	// them. It comes from the application's own configuration, never from a
	// request. Required.
	TeamTenant string

	// Prefix is the path the customer's routes are mounted under. Empty means
	// DefaultPrefix.
	Prefix string

	// TeamPrefix is the path the team's routes are mounted under. Empty means
	// DefaultTeamPrefix. The two sides are separate: the team's session is
	// valid on this side only, and the customer's on the other.
	TeamPrefix string

	// Paths are the segments every route is built from, under Prefix and
	// TeamPrefix. A field left empty keeps its DefaultPaths value;
	// PortuguesePaths is the whole set in Brazilian Portuguese.
	Paths Paths

	// Zone is the timezone the team's day is written in: the weekly hours are
	// "09:00 to 18:00" in it, a day is midnight to midnight in it, and every
	// screen writes an instant in it. Required: a schedule with no zone has no
	// meaning, and a default here would be a wrong answer for somebody.
	Zone *time.Location

	// Capacity is how many bookings one slot takes at the same time. Zero means
	// DefaultCapacity.
	Capacity int

	// SlotStep is the distance between two starts offered on a day: 20 minutes
	// offers 09:00, 09:20, 09:40. Zero means DefaultSlotStep. It has to be a
	// whole number of minutes.
	SlotStep time.Duration

	// MinNotice is the earliest bookable start from now: with 24 hours, nothing
	// that starts before this time tomorrow is offered. Zero means
	// DefaultMinNotice; a negative value means no notice at all.
	MinNotice time.Duration

	// Horizon is the latest bookable start from now. Zero means
	// DefaultHorizon, and anything above MaxHorizon is refused.
	Horizon time.Duration

	// PaymentHold is how long a booking that waits for payment keeps its slot
	// before ExpireHolds frees it. Zero means DefaultPaymentHold.
	PaymentHold time.Duration

	// RemindBefore is how long before the start Remind tells the customer. Zero
	// means DefaultRemindBefore.
	RemindBefore time.Duration

	// ChangeUntil is how long before the start a customer can still reschedule
	// or cancel. Zero means DefaultChangeUntil; a negative value means up to
	// the start.
	ChangeUntil time.Duration

	// PageSize is how many rows one page of a list answers with. Zero means
	// DefaultPageSize, and anything above MaxPageSize is refused rather than
	// clamped: a number somebody wrote and did not get is worse than a number
	// somebody wrote and was told about.
	PageSize int

	// Middleware runs on every route of this package after RequireAuth, in
	// order, and TeamMiddleware after it on the team's routes only. An
	// application whose permissions arandu-permission administers mounts its
	// Roles() in Middleware: RequireAuth puts the subject as the session
	// resolved it, without the actions arandu-permission resolves on each
	// request. A guard of the application's own side -- the operator console's
	// -- goes in TeamMiddleware. A guard answers "is this request on the right
	// side" and stops; the policy still decides.
	Middleware     []func(http.Handler) http.Handler
	TeamMiddleware []func(http.Handler) http.Handler

	// Notifier is told what happens to a booking. Nil tells nobody. See
	// Notifier. This package sends no message of its own.
	Notifier Notifier

	// Directory names the people of a booking. Optional; see Directory.
	Directory Directory

	// Subjects checks what a booking is about, and names it. Optional; see
	// SubjectResolver. Without one the label the request carried is kept as it
	// is, clipped.
	Subjects SubjectResolver

	// PaymentURL is the address where the customer pays a booking that waits for
	// payment: the application's own page, as the module knows nothing of money.
	// An empty answer shows the booking as waiting and offers no link. Nil is the
	// same as always empty.
	PaymentURL func(Summary) string

	// Activity is arandu-activitylog's logger, the application's one instance
	// (activityModule.Logger()). Every act that changes something is recorded
	// under the Grant it was authorized with, in the log named ActivityLogName.
	// Nil records nothing.
	Activity *activitylog.Logger

	// Translator is the application's own catalogue, asked before the one this
	// package ships, key by key: "agenda.screen.index_title". Optional.
	Translator *translation.Translator

	// Locale is the language every screen, validation message and activity
	// description of this package is written in. Empty means DefaultLocale. The
	// package ships the locales Locales() lists; any other reads the
	// application's Translator first and English after it.
	Locale string

	// TitleSeparator joins a screen's title to the application's name in the
	// document title: with " — ", the list is titled "Agendamentos — Alpr.sh".
	// Empty titles a screen with its own title alone.
	TitleSeparator string

	// Chrome is what the application's layout draws around a screen of this
	// package: its sidebar, its navigation, the account menu. It is called once
	// per screen, after RequireAuth and before the page is rendered, and what it
	// answers is carried on the page as Screen.Chrome, where a layout asserts
	// the interface it draws from. An error is returned as the handler's. Nil
	// draws the screens with the page hesape's view.New builds and nothing
	// more.
	Chrome func(ctx *fhttp.Context, req ChromeRequest) (any, error)

	// Now is the clock: every timestamp a row carries and every comparison with
	// the present is read from it. Nil means time.Now. A test holds it still; an
	// application leaves it nil.
	Now func() time.Time

	// Logger receives what the package cannot return to anybody: a Notifier
	// that failed after the change was stored. Nil means slog.Default().
	Logger *slog.Logger
}

Config is what the application passes when it wires this package.

A typed struct rather than a map: a misspelled key in a map is a setting that silently keeps its default, and the failure shows up as behaviour nobody asked for rather than as an error. Here a field that does not exist does not compile.

It names no tenant for the customers, and that is deliberate. Every route sits behind RequireAuth, so the tenant of every customer statement is the one the Grant carries, from the session of whoever is asking; a tenant written here would be a second place for one to come from. The one tenant it does name is the team's own, TeamTenant, because the team is not a customer.

func (Config) Validate

func (c Config) Validate() error

Validate reports what the configuration cannot be used with.

It is called by New, so an application with a setting that cannot work fails where it is wired rather than on the first request that needed it.

type ConfigQuery

type ConfigQuery struct {
	Search  string
	Sort    string
	Dir     string
	Page    int
	PerPage int
}

ConfigQuery narrows a list of the team's settings. Page counts from one.

type Counter

type Counter struct {
	model.Model

	ID         string    `db:"id"`
	LastNumber int64     `db:"last_number"`
	UpdatedAt  time.Time `db:"updated_at"`
}

Counter is the last number the bookings were given. There is one row, and it is every space's: the protocol is one sequence, and the row is also the lock that makes two people booking the last place take turns. It is bookkeeping: an application never reads or writes it.

func (*Counter) Fresh

func (row *Counter) Fresh(ctx context.Context, g auth.Grant, with ...string) (*Counter, error)

Fresh reads the row again, as a new Counter; it shadows the untyped one the embedded model promotes.

func (*Counter) Replicate

func (row *Counter) Replicate(except ...string) (*Counter, error)

Replicate returns an unsaved copy of the row without its key; it shadows the untyped one the embedded model promotes.

type CounterCollection

type CounterCollection []*Counter

CounterCollection is rows of Counter, as a query returns them.

func CounterCollectionOf

func CounterCollectionOf(rows model.Rows) CounterCollection

CounterCollectionOf converts rows of the table of Counter. A nil input is a nil collection.

func (CounterCollection) Contains

func (c CounterCollection) Contains(key any) bool

func (CounterCollection) Except

func (c CounterCollection) Except(keys ...any) CounterCollection

func (CounterCollection) Find

func (c CounterCollection) Find(key any) *Counter

func (CounterCollection) FindOrFail

func (c CounterCollection) FindOrFail(key any) (*Counter, error)

func (CounterCollection) Fresh

func (CounterCollection) Load

func (c CounterCollection) Load(ctx context.Context, g auth.Grant, relations ...string) error

func (CounterCollection) LoadCount

func (c CounterCollection) LoadCount(ctx context.Context, g auth.Grant, relations ...string) error

func (CounterCollection) LoadMissing

func (c CounterCollection) LoadMissing(ctx context.Context, g auth.Grant, relations ...string) error

func (CounterCollection) ModelKeys

func (c CounterCollection) ModelKeys() []any

func (CounterCollection) Only

func (c CounterCollection) Only(keys ...any) CounterCollection

func (CounterCollection) Pluck

func (c CounterCollection) Pluck(column string) []any

func (CounterCollection) Rows

func (c CounterCollection) Rows() model.Rows

Rows converts the collection back to the core's rows.

func (CounterCollection) ToArray

func (c CounterCollection) ToArray() []map[string]any

func (CounterCollection) Unique

type CounterQuery

type CounterQuery struct {
	// contains filtered or unexported fields
}

CounterQuery is a query on the table of Counter.

The methods that build return the query, so they chain. The methods that run take a context and an auth.Grant, and return Counter rows or a value; there is no way to run one without a Grant.

func Counters

func Counters(db model.DB) *CounterQuery

Counters starts a query on the table of Counter, through db.

Global scopes are on and, unless the table is Global, every statement is filtered by the tenant of the Grant its terminal takes.

func (*CounterQuery) AddSelect

func (q *CounterQuery) AddSelect(columns ...any) *CounterQuery

func (*CounterQuery) ApplyListing

func (q *CounterQuery) ApplyListing(state pagination.ListingState) *CounterQuery

ApplyListing narrows and orders the query as a listing state asks: the search, the facets and the sort with its tie-break. Every column comes from the spec the state was read with, never from the request.

func (*CounterQuery) Avg

func (q *CounterQuery) Avg(ctx context.Context, g auth.Grant, column any) (any, error)

func (*CounterQuery) Base

func (q *CounterQuery) Base() *model.Builder

Base returns the core builder the query forwards to. It is for code in this package -- a local scope in the custom block of model.go -- and for the factory, which builds rows through it.

func (*CounterQuery) Chunk

func (q *CounterQuery) Chunk(ctx context.Context, g auth.Grant, count int, callback func(CounterCollection, int) (bool, error)) error

func (*CounterQuery) Clone

func (q *CounterQuery) Clone() *CounterQuery

Clone returns an independent copy of the query.

func (*CounterQuery) Count

func (q *CounterQuery) Count(ctx context.Context, g auth.Grant, columns ...any) (int64, error)

func (*CounterQuery) Create

func (q *CounterQuery) Create(ctx context.Context, g auth.Grant, attributes map[string]any) (*Counter, error)

func (*CounterQuery) Cursor

func (q *CounterQuery) Cursor(ctx context.Context, g auth.Grant) iter.Seq2[*Counter, error]

func (*CounterQuery) CursorPaginate

func (q *CounterQuery) CursorPaginate(ctx context.Context, g auth.Grant, perPage int, cursor *pagination.Cursor, opts pagination.Options, columns ...any) (CounterCollection, *pagination.CursorPage, error)

func (*CounterQuery) Decrement

func (q *CounterQuery) Decrement(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*CounterQuery) Delete

func (q *CounterQuery) Delete(ctx context.Context, g auth.Grant) (int64, error)

func (*CounterQuery) DoesntExist

func (q *CounterQuery) DoesntExist(ctx context.Context, g auth.Grant) (bool, error)

func (*CounterQuery) DoesntHave

func (q *CounterQuery) DoesntHave(relation, boolean string, callback func(*query.Builder)) *CounterQuery

func (*CounterQuery) Each

func (q *CounterQuery) Each(ctx context.Context, g auth.Grant, count int, callback func(*Counter, int) (bool, error)) error

func (*CounterQuery) Exists

func (q *CounterQuery) Exists(ctx context.Context, g auth.Grant) (bool, error)

func (*CounterQuery) Find

func (q *CounterQuery) Find(ctx context.Context, g auth.Grant, id any, columns ...any) (*Counter, error)

func (*CounterQuery) FindMany

func (q *CounterQuery) FindMany(ctx context.Context, g auth.Grant, ids []any, columns ...any) (CounterCollection, error)

func (*CounterQuery) FindOrFail

func (q *CounterQuery) FindOrFail(ctx context.Context, g auth.Grant, id any, columns ...any) (*Counter, error)

func (*CounterQuery) FindOrNew

func (q *CounterQuery) FindOrNew(ctx context.Context, g auth.Grant, id any, columns ...any) (*Counter, error)

func (*CounterQuery) First

func (q *CounterQuery) First(ctx context.Context, g auth.Grant, columns ...any) (*Counter, error)

First returns the first row, or nil and no error when there is none.

func (*CounterQuery) FirstOrCreate

func (q *CounterQuery) FirstOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Counter, error)

func (*CounterQuery) FirstOrFail

func (q *CounterQuery) FirstOrFail(ctx context.Context, g auth.Grant, columns ...any) (*Counter, error)

func (*CounterQuery) FirstOrNew

func (q *CounterQuery) FirstOrNew(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Counter, error)

func (*CounterQuery) FirstWhere

func (q *CounterQuery) FirstWhere(ctx context.Context, g auth.Grant, column any, args ...any) (*Counter, error)

func (*CounterQuery) ForPage

func (q *CounterQuery) ForPage(page, perPage int) *CounterQuery

func (*CounterQuery) ForceCreate

func (q *CounterQuery) ForceCreate(ctx context.Context, g auth.Grant, attributes map[string]any) (*Counter, error)

func (*CounterQuery) Get

func (q *CounterQuery) Get(ctx context.Context, g auth.Grant, columns ...any) (CounterCollection, error)

Get runs the query and returns the rows.

func (*CounterQuery) GroupBy

func (q *CounterQuery) GroupBy(groups ...any) *CounterQuery

func (*CounterQuery) Has

func (q *CounterQuery) Has(relation, operator string, count int, boolean string, callback func(*query.Builder)) *CounterQuery

func (*CounterQuery) Increment

func (q *CounterQuery) Increment(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*CounterQuery) Insert

func (q *CounterQuery) Insert(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*CounterQuery) InsertOrIgnore

func (q *CounterQuery) InsertOrIgnore(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*CounterQuery) Join

func (q *CounterQuery) Join(table any, first any, args ...any) *CounterQuery

func (*CounterQuery) Latest

func (q *CounterQuery) Latest(column ...string) *CounterQuery

func (*CounterQuery) Limit

func (q *CounterQuery) Limit(value int) *CounterQuery

func (*CounterQuery) Listing

Listing runs the query as a listing state asks and returns the rows of the page beside the result a table is drawn from: the state, the page with its total and the count of every facet value. Every statement it issues carries the tenant of g.

func (*CounterQuery) Max

func (q *CounterQuery) Max(ctx context.Context, g auth.Grant, column any) (any, error)

func (*CounterQuery) Min

func (q *CounterQuery) Min(ctx context.Context, g auth.Grant, column any) (any, error)

func (*CounterQuery) New

func (q *CounterQuery) New() (*Counter, error)

New returns an empty Counter on the query's connection, not yet saved, filled with what WithAttributes recorded on the query.

func (*CounterQuery) Offset

func (q *CounterQuery) Offset(value int) *CounterQuery

func (*CounterQuery) Oldest

func (q *CounterQuery) Oldest(column ...string) *CounterQuery

func (*CounterQuery) OrDoesntHave

func (q *CounterQuery) OrDoesntHave(relation string) *CounterQuery

func (*CounterQuery) OrHas

func (q *CounterQuery) OrHas(relation, operator string, count int) *CounterQuery

func (*CounterQuery) OrWhere

func (q *CounterQuery) OrWhere(column any, args ...any) *CounterQuery

OrWhere adds an or-where clause; a func(*CounterQuery) in place of the column adds a group.

func (*CounterQuery) OrWhereDoesntHave

func (q *CounterQuery) OrWhereDoesntHave(relation string, callback func(*query.Builder)) *CounterQuery

func (*CounterQuery) OrWhereHas

func (q *CounterQuery) OrWhereHas(relation string, callback func(*query.Builder)) *CounterQuery

func (*CounterQuery) OrWhereNot

func (q *CounterQuery) OrWhereNot(column any, args ...any) *CounterQuery

OrWhereNot adds an or-joined negated where clause, or a negated group.

func (*CounterQuery) OrWhereRelation

func (q *CounterQuery) OrWhereRelation(relation string, column any, args ...any) *CounterQuery

func (*CounterQuery) OrderBy

func (q *CounterQuery) OrderBy(column any, direction ...string) *CounterQuery

func (*CounterQuery) OrderByDesc

func (q *CounterQuery) OrderByDesc(column any) *CounterQuery

func (*CounterQuery) Paginate

func (q *CounterQuery) Paginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (CounterCollection, *pagination.LengthAwarePage, error)

func (*CounterQuery) Pluck

func (q *CounterQuery) Pluck(ctx context.Context, g auth.Grant, column string) ([]any, error)

func (*CounterQuery) Select

func (q *CounterQuery) Select(columns ...any) *CounterQuery

func (*CounterQuery) SelectRaw

func (q *CounterQuery) SelectRaw(expression string, bindings ...any) *CounterQuery

func (*CounterQuery) SimplePaginate

func (q *CounterQuery) SimplePaginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (CounterCollection, *pagination.Page, error)

func (*CounterQuery) Sole

func (q *CounterQuery) Sole(ctx context.Context, g auth.Grant, columns ...any) (*Counter, error)

func (*CounterQuery) SoleValue

func (q *CounterQuery) SoleValue(ctx context.Context, g auth.Grant, column string) (any, error)

func (*CounterQuery) Sum

func (q *CounterQuery) Sum(ctx context.Context, g auth.Grant, column any) (any, error)

func (*CounterQuery) Touch

func (q *CounterQuery) Touch(ctx context.Context, g auth.Grant, column ...string) (int64, error)

func (*CounterQuery) Update

func (q *CounterQuery) Update(ctx context.Context, g auth.Grant, values map[string]any) (int64, error)

func (*CounterQuery) UpdateOrCreate

func (q *CounterQuery) UpdateOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Counter, error)

func (*CounterQuery) Upsert

func (q *CounterQuery) Upsert(ctx context.Context, g auth.Grant, values []map[string]any, uniqueBy, update []string) (int64, error)

func (*CounterQuery) Value

func (q *CounterQuery) Value(ctx context.Context, g auth.Grant, column string) (any, error)

func (*CounterQuery) ValueOrFail

func (q *CounterQuery) ValueOrFail(ctx context.Context, g auth.Grant, column string) (any, error)

func (*CounterQuery) Where

func (q *CounterQuery) Where(column any, args ...any) *CounterQuery

Where adds a where clause; a func(*CounterQuery) in place of the column adds a group.

func (*CounterQuery) WhereBelongsTo

func (q *CounterQuery) WhereBelongsTo(relationshipName string, related ...model.Entity) *CounterQuery

func (*CounterQuery) WhereBetween

func (q *CounterQuery) WhereBetween(column any, from, to any) *CounterQuery

func (*CounterQuery) WhereColumn

func (q *CounterQuery) WhereColumn(first any, args ...any) *CounterQuery

func (*CounterQuery) WhereDoesntHave

func (q *CounterQuery) WhereDoesntHave(relation string, callback func(*query.Builder)) *CounterQuery

func (*CounterQuery) WhereExists

func (q *CounterQuery) WhereExists(callback func(*query.Builder)) *CounterQuery

func (*CounterQuery) WhereHas

func (q *CounterQuery) WhereHas(relation string, callback func(*query.Builder)) *CounterQuery

func (*CounterQuery) WhereHasCount

func (q *CounterQuery) WhereHasCount(relation string, callback func(*query.Builder), operator string, count int) *CounterQuery

func (*CounterQuery) WhereIn

func (q *CounterQuery) WhereIn(column any, values []any) *CounterQuery

func (*CounterQuery) WhereKey

func (q *CounterQuery) WhereKey(id any) *CounterQuery

func (*CounterQuery) WhereNot

func (q *CounterQuery) WhereNot(column any, args ...any) *CounterQuery

WhereNot adds a negated where clause, or a negated group.

func (*CounterQuery) WhereNotExists

func (q *CounterQuery) WhereNotExists(callback func(*query.Builder)) *CounterQuery

func (*CounterQuery) WhereNotIn

func (q *CounterQuery) WhereNotIn(column any, values []any) *CounterQuery

func (*CounterQuery) WhereNotNull

func (q *CounterQuery) WhereNotNull(columns ...any) *CounterQuery

func (*CounterQuery) WhereNull

func (q *CounterQuery) WhereNull(columns ...any) *CounterQuery

func (*CounterQuery) WhereRelation

func (q *CounterQuery) WhereRelation(relation string, column any, args ...any) *CounterQuery

func (*CounterQuery) With

func (q *CounterQuery) With(relations ...string) *CounterQuery

func (*CounterQuery) WithAvg

func (q *CounterQuery) WithAvg(relation, column string) *CounterQuery

func (*CounterQuery) WithCount

func (q *CounterQuery) WithCount(relations ...string) *CounterQuery

func (*CounterQuery) WithExists

func (q *CounterQuery) WithExists(relation string) *CounterQuery

func (*CounterQuery) WithMax

func (q *CounterQuery) WithMax(relation, column string) *CounterQuery

func (*CounterQuery) WithMin

func (q *CounterQuery) WithMin(relation, column string) *CounterQuery

func (*CounterQuery) WithSum

func (q *CounterQuery) WithSum(relation, column string) *CounterQuery

func (*CounterQuery) Without

func (q *CounterQuery) Without(relations ...string) *CounterQuery

func (*CounterQuery) WithoutGlobalScope

func (q *CounterQuery) WithoutGlobalScope(identifier string) *CounterQuery

func (*CounterQuery) WithoutGlobalScopes

func (q *CounterQuery) WithoutGlobalScopes(identifiers ...string) *CounterQuery

type Directory

type Directory interface {
	// Person returns a user of a tenant, or ErrNoAccount when there is none.
	Person(ctx context.Context, tenant, id string) (Person, error)
}

Directory names people. It is optional: without one a booking keeps the name of its requester empty and a screen shows the identifier instead.

type Event

type Event struct {
	Kind EventKind
	// Booking is the booking after the change.
	Booking Summary
	// By is the side that acted: ByCustomer, ByTeam or BySystem.
	By string
	// AwaitingPayment, on EventBooked, says the booking holds its slot until
	// Booking.HoldUntil and becomes a scheduled one when the payment settles.
	AwaitingPayment bool
	// ConfirmURL and RescheduleURL, on EventReminder, are the paths of the
	// customer's own screens: the booking, which has the button that confirms,
	// and the form that moves it. They are paths and not addresses, because the
	// module does not know the host; the application puts its own in front. Both
	// need the customer signed in.
	ConfirmURL    string
	RescheduleURL string
}

Event is what a Notifier is handed.

func (Event) ForTeam

func (e Event) ForTeam() bool

ForTeam says whether the team is the one to tell. For a rescheduling or a cancellation that is the case when the customer was the one who acted; when the team acted, the requester is told. A booking that expired and a reminder are the requester's.

type EventKind

type EventKind string

EventKind says what happened to a booking that somebody should be told about.

const (
	// EventBooked is a booking just made. Event.AwaitingPayment says whether it
	// waits for a payment. The team is the one to tell, and the customer too:
	// the customer's copy is the receipt, with the payment link when it waits.
	EventBooked EventKind = "agenda.booked"
	// EventScheduled is a booking that waited for a payment and now holds its
	// slot: the application settled it, or the team released it as a courtesy.
	EventScheduled EventKind = "agenda.scheduled"
	// EventReminder is the reminder that goes before the start, asking the
	// customer to confirm or to reschedule. It carries the two paths.
	EventReminder EventKind = "agenda.reminder"
	// EventConfirmed is a booking the customer confirmed.
	EventConfirmed EventKind = "agenda.confirmed"
	// EventRescheduled is a booking moved to another time.
	EventRescheduled EventKind = "agenda.rescheduled"
	// EventCancelled is a booking cancelled. Event.By says by whom.
	EventCancelled EventKind = "agenda.cancelled"
	// EventCompleted is a booking the team marked as done.
	EventCompleted EventKind = "agenda.completed"
	// EventHoldExpired is a booking that waited for a payment that never came,
	// and lost its slot.
	EventHoldExpired EventKind = "agenda.hold_expired"
)

The events a Notifier is told about.

func (EventKind) ForTeam

func (k EventKind) ForTeam() bool

ForTeam says whether the team is the one to tell for an event whose side does not depend on who acted. When it is not, the requester of the booking is. For EventRescheduled and EventCancelled the side that did not act is the one to tell, which only the event knows: see Event.ForTeam.

type Flag

type Flag bool

Flag is a yes-or-no a column holds as an integer, read back from whatever an engine answers with: the engines disagree about booleans and one place has to flatten them.

func (*Flag) Scan

func (f *Flag) Scan(value any) error

Scan reads the flag back. Anything it cannot read is refused rather than read as false.

func (Flag) Value

func (f Flag) Value() (driver.Value, error)

Value writes the flag as the integer the column holds.

type FormState

type FormState struct{ hview.Page }

FormState is what a form field reads from the page it is drawn on: what was typed before a refusal, and the message for each field.

func (FormState) ErrorSummary

func (f FormState) ErrorSummary() []string

ErrorSummary is one line per rejected field.

func (FormState) FieldError

func (f FormState) FieldError(name string) string

FieldError is the first message for one field, empty when it was accepted.

func (FormState) FieldErrors

func (f FormState) FieldErrors(name string) []string

FieldErrors is every message for one field.

func (FormState) HasErrors

func (f FormState) HasErrors() bool

HasErrors says whether the attempt that landed here was rejected.

func (FormState) LogValue

func (f FormState) LogValue() slog.Value

LogValue is the form state as a log line carries it, the token redacted.

func (FormState) MarshalJSON

func (f FormState) MarshalJSON() ([]byte, error)

MarshalJSON writes the form state with the CSRF token redacted.

type Hour

type Hour struct {
	model.Model

	// ID is the identifier, generated by the application.
	ID string `db:"id"`

	// Weekday is 0 for Sunday to 6 for Saturday, as time.Weekday counts.
	Weekday int `db:"weekday"`

	// StartMinute and EndMinute are minutes since midnight: 540 to 1080 is 09:00
	// to 18:00.
	StartMinute int `db:"start_minute"`
	EndMinute   int `db:"end_minute"`

	// CreatedAt is when the row was written, in UTC.
	CreatedAt time.Time `db:"created_at"`
}

Hour is a window of the team's week: the team takes bookings on that weekday between the two minutes, in Config.Zone. A day may have several windows.

func (*Hour) Fresh

func (row *Hour) Fresh(ctx context.Context, g auth.Grant, with ...string) (*Hour, error)

Fresh reads the row again, as a new Hour; it shadows the untyped one the embedded model promotes.

func (*Hour) Replicate

func (row *Hour) Replicate(except ...string) (*Hour, error)

Replicate returns an unsaved copy of the row without its key; it shadows the untyped one the embedded model promotes.

type HourCollection

type HourCollection []*Hour

HourCollection is rows of Hour, as a query returns them.

func HourCollectionOf

func HourCollectionOf(rows model.Rows) HourCollection

HourCollectionOf converts rows of the table of Hour. A nil input is a nil collection.

func (HourCollection) Contains

func (c HourCollection) Contains(key any) bool

func (HourCollection) Except

func (c HourCollection) Except(keys ...any) HourCollection

func (HourCollection) Find

func (c HourCollection) Find(key any) *Hour

func (HourCollection) FindOrFail

func (c HourCollection) FindOrFail(key any) (*Hour, error)

func (HourCollection) Fresh

func (c HourCollection) Fresh(ctx context.Context, g auth.Grant, with ...string) (HourCollection, error)

func (HourCollection) Load

func (c HourCollection) Load(ctx context.Context, g auth.Grant, relations ...string) error

func (HourCollection) LoadCount

func (c HourCollection) LoadCount(ctx context.Context, g auth.Grant, relations ...string) error

func (HourCollection) LoadMissing

func (c HourCollection) LoadMissing(ctx context.Context, g auth.Grant, relations ...string) error

func (HourCollection) ModelKeys

func (c HourCollection) ModelKeys() []any

func (HourCollection) Only

func (c HourCollection) Only(keys ...any) HourCollection

func (HourCollection) Pluck

func (c HourCollection) Pluck(column string) []any

func (HourCollection) Rows

func (c HourCollection) Rows() model.Rows

Rows converts the collection back to the core's rows.

func (HourCollection) ToArray

func (c HourCollection) ToArray() []map[string]any

func (HourCollection) Unique

func (c HourCollection) Unique() HourCollection

type HourFormPageData

type HourFormPageData struct {
	Screen
	Action, BackURL string
	WeekdayOptions  []components.SelectOption
	Weekday         string
	Start, End      string
}

HourFormPageData is the form that adds a window.

type HourInput

type HourInput struct {
	Weekday     int
	StartMinute int
	EndMinute   int
}

HourInput is a window of the team's week, in minutes since midnight of Config.Zone.

type HourQuery

type HourQuery struct {
	// contains filtered or unexported fields
}

HourQuery is a query on the table of Hour.

The methods that build return the query, so they chain. The methods that run take a context and an auth.Grant, and return Hour rows or a value; there is no way to run one without a Grant.

func Hours

func Hours(db model.DB) *HourQuery

Hours starts a query on the table of Hour, through db.

Global scopes are on and, unless the table is Global, every statement is filtered by the tenant of the Grant its terminal takes.

func (*HourQuery) AddSelect

func (q *HourQuery) AddSelect(columns ...any) *HourQuery

func (*HourQuery) ApplyListing

func (q *HourQuery) ApplyListing(state pagination.ListingState) *HourQuery

ApplyListing narrows and orders the query as a listing state asks: the search, the facets and the sort with its tie-break. Every column comes from the spec the state was read with, never from the request.

func (*HourQuery) Avg

func (q *HourQuery) Avg(ctx context.Context, g auth.Grant, column any) (any, error)

func (*HourQuery) Base

func (q *HourQuery) Base() *model.Builder

Base returns the core builder the query forwards to. It is for code in this package -- a local scope in the custom block of model.go -- and for the factory, which builds rows through it.

func (*HourQuery) Chunk

func (q *HourQuery) Chunk(ctx context.Context, g auth.Grant, count int, callback func(HourCollection, int) (bool, error)) error

func (*HourQuery) Clone

func (q *HourQuery) Clone() *HourQuery

Clone returns an independent copy of the query.

func (*HourQuery) Count

func (q *HourQuery) Count(ctx context.Context, g auth.Grant, columns ...any) (int64, error)

func (*HourQuery) Create

func (q *HourQuery) Create(ctx context.Context, g auth.Grant, attributes map[string]any) (*Hour, error)

func (*HourQuery) Cursor

func (q *HourQuery) Cursor(ctx context.Context, g auth.Grant) iter.Seq2[*Hour, error]

func (*HourQuery) CursorPaginate

func (q *HourQuery) CursorPaginate(ctx context.Context, g auth.Grant, perPage int, cursor *pagination.Cursor, opts pagination.Options, columns ...any) (HourCollection, *pagination.CursorPage, error)

func (*HourQuery) Decrement

func (q *HourQuery) Decrement(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*HourQuery) Delete

func (q *HourQuery) Delete(ctx context.Context, g auth.Grant) (int64, error)

func (*HourQuery) DoesntExist

func (q *HourQuery) DoesntExist(ctx context.Context, g auth.Grant) (bool, error)

func (*HourQuery) DoesntHave

func (q *HourQuery) DoesntHave(relation, boolean string, callback func(*query.Builder)) *HourQuery

func (*HourQuery) Each

func (q *HourQuery) Each(ctx context.Context, g auth.Grant, count int, callback func(*Hour, int) (bool, error)) error

func (*HourQuery) Exists

func (q *HourQuery) Exists(ctx context.Context, g auth.Grant) (bool, error)

func (*HourQuery) Find

func (q *HourQuery) Find(ctx context.Context, g auth.Grant, id any, columns ...any) (*Hour, error)

func (*HourQuery) FindMany

func (q *HourQuery) FindMany(ctx context.Context, g auth.Grant, ids []any, columns ...any) (HourCollection, error)

func (*HourQuery) FindOrFail

func (q *HourQuery) FindOrFail(ctx context.Context, g auth.Grant, id any, columns ...any) (*Hour, error)

func (*HourQuery) FindOrNew

func (q *HourQuery) FindOrNew(ctx context.Context, g auth.Grant, id any, columns ...any) (*Hour, error)

func (*HourQuery) First

func (q *HourQuery) First(ctx context.Context, g auth.Grant, columns ...any) (*Hour, error)

First returns the first row, or nil and no error when there is none.

func (*HourQuery) FirstOrCreate

func (q *HourQuery) FirstOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Hour, error)

func (*HourQuery) FirstOrFail

func (q *HourQuery) FirstOrFail(ctx context.Context, g auth.Grant, columns ...any) (*Hour, error)

func (*HourQuery) FirstOrNew

func (q *HourQuery) FirstOrNew(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Hour, error)

func (*HourQuery) FirstWhere

func (q *HourQuery) FirstWhere(ctx context.Context, g auth.Grant, column any, args ...any) (*Hour, error)

func (*HourQuery) ForPage

func (q *HourQuery) ForPage(page, perPage int) *HourQuery

func (*HourQuery) ForceCreate

func (q *HourQuery) ForceCreate(ctx context.Context, g auth.Grant, attributes map[string]any) (*Hour, error)

func (*HourQuery) Get

func (q *HourQuery) Get(ctx context.Context, g auth.Grant, columns ...any) (HourCollection, error)

Get runs the query and returns the rows.

func (*HourQuery) GroupBy

func (q *HourQuery) GroupBy(groups ...any) *HourQuery

func (*HourQuery) Has

func (q *HourQuery) Has(relation, operator string, count int, boolean string, callback func(*query.Builder)) *HourQuery

func (*HourQuery) Increment

func (q *HourQuery) Increment(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*HourQuery) Insert

func (q *HourQuery) Insert(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*HourQuery) InsertOrIgnore

func (q *HourQuery) InsertOrIgnore(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*HourQuery) Join

func (q *HourQuery) Join(table any, first any, args ...any) *HourQuery

func (*HourQuery) Latest

func (q *HourQuery) Latest(column ...string) *HourQuery

func (*HourQuery) Limit

func (q *HourQuery) Limit(value int) *HourQuery

func (*HourQuery) Listing

func (q *HourQuery) Listing(ctx context.Context, g auth.Grant, state pagination.ListingState, path string, columns ...any) (HourCollection, *pagination.ListingResult, error)

Listing runs the query as a listing state asks and returns the rows of the page beside the result a table is drawn from: the state, the page with its total and the count of every facet value. Every statement it issues carries the tenant of g.

func (*HourQuery) Max

func (q *HourQuery) Max(ctx context.Context, g auth.Grant, column any) (any, error)

func (*HourQuery) Min

func (q *HourQuery) Min(ctx context.Context, g auth.Grant, column any) (any, error)

func (*HourQuery) New

func (q *HourQuery) New() (*Hour, error)

New returns an empty Hour on the query's connection, not yet saved, filled with what WithAttributes recorded on the query.

func (*HourQuery) Offset

func (q *HourQuery) Offset(value int) *HourQuery

func (*HourQuery) Oldest

func (q *HourQuery) Oldest(column ...string) *HourQuery

func (*HourQuery) OrDoesntHave

func (q *HourQuery) OrDoesntHave(relation string) *HourQuery

func (*HourQuery) OrHas

func (q *HourQuery) OrHas(relation, operator string, count int) *HourQuery

func (*HourQuery) OrWhere

func (q *HourQuery) OrWhere(column any, args ...any) *HourQuery

OrWhere adds an or-where clause; a func(*HourQuery) in place of the column adds a group.

func (*HourQuery) OrWhereDoesntHave

func (q *HourQuery) OrWhereDoesntHave(relation string, callback func(*query.Builder)) *HourQuery

func (*HourQuery) OrWhereHas

func (q *HourQuery) OrWhereHas(relation string, callback func(*query.Builder)) *HourQuery

func (*HourQuery) OrWhereNot

func (q *HourQuery) OrWhereNot(column any, args ...any) *HourQuery

OrWhereNot adds an or-joined negated where clause, or a negated group.

func (*HourQuery) OrWhereRelation

func (q *HourQuery) OrWhereRelation(relation string, column any, args ...any) *HourQuery

func (*HourQuery) OrderBy

func (q *HourQuery) OrderBy(column any, direction ...string) *HourQuery

func (*HourQuery) OrderByDesc

func (q *HourQuery) OrderByDesc(column any) *HourQuery

func (*HourQuery) Paginate

func (q *HourQuery) Paginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (HourCollection, *pagination.LengthAwarePage, error)

func (*HourQuery) Pluck

func (q *HourQuery) Pluck(ctx context.Context, g auth.Grant, column string) ([]any, error)

func (*HourQuery) Select

func (q *HourQuery) Select(columns ...any) *HourQuery

func (*HourQuery) SelectRaw

func (q *HourQuery) SelectRaw(expression string, bindings ...any) *HourQuery

func (*HourQuery) SimplePaginate

func (q *HourQuery) SimplePaginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (HourCollection, *pagination.Page, error)

func (*HourQuery) Sole

func (q *HourQuery) Sole(ctx context.Context, g auth.Grant, columns ...any) (*Hour, error)

func (*HourQuery) SoleValue

func (q *HourQuery) SoleValue(ctx context.Context, g auth.Grant, column string) (any, error)

func (*HourQuery) Sum

func (q *HourQuery) Sum(ctx context.Context, g auth.Grant, column any) (any, error)

func (*HourQuery) Touch

func (q *HourQuery) Touch(ctx context.Context, g auth.Grant, column ...string) (int64, error)

func (*HourQuery) Update

func (q *HourQuery) Update(ctx context.Context, g auth.Grant, values map[string]any) (int64, error)

func (*HourQuery) UpdateOrCreate

func (q *HourQuery) UpdateOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Hour, error)

func (*HourQuery) Upsert

func (q *HourQuery) Upsert(ctx context.Context, g auth.Grant, values []map[string]any, uniqueBy, update []string) (int64, error)

func (*HourQuery) Value

func (q *HourQuery) Value(ctx context.Context, g auth.Grant, column string) (any, error)

func (*HourQuery) ValueOrFail

func (q *HourQuery) ValueOrFail(ctx context.Context, g auth.Grant, column string) (any, error)

func (*HourQuery) Where

func (q *HourQuery) Where(column any, args ...any) *HourQuery

Where adds a where clause; a func(*HourQuery) in place of the column adds a group.

func (*HourQuery) WhereBelongsTo

func (q *HourQuery) WhereBelongsTo(relationshipName string, related ...model.Entity) *HourQuery

func (*HourQuery) WhereBetween

func (q *HourQuery) WhereBetween(column any, from, to any) *HourQuery

func (*HourQuery) WhereColumn

func (q *HourQuery) WhereColumn(first any, args ...any) *HourQuery

func (*HourQuery) WhereDoesntHave

func (q *HourQuery) WhereDoesntHave(relation string, callback func(*query.Builder)) *HourQuery

func (*HourQuery) WhereExists

func (q *HourQuery) WhereExists(callback func(*query.Builder)) *HourQuery

func (*HourQuery) WhereHas

func (q *HourQuery) WhereHas(relation string, callback func(*query.Builder)) *HourQuery

func (*HourQuery) WhereHasCount

func (q *HourQuery) WhereHasCount(relation string, callback func(*query.Builder), operator string, count int) *HourQuery

func (*HourQuery) WhereIn

func (q *HourQuery) WhereIn(column any, values []any) *HourQuery

func (*HourQuery) WhereKey

func (q *HourQuery) WhereKey(id any) *HourQuery

func (*HourQuery) WhereNot

func (q *HourQuery) WhereNot(column any, args ...any) *HourQuery

WhereNot adds a negated where clause, or a negated group.

func (*HourQuery) WhereNotExists

func (q *HourQuery) WhereNotExists(callback func(*query.Builder)) *HourQuery

func (*HourQuery) WhereNotIn

func (q *HourQuery) WhereNotIn(column any, values []any) *HourQuery

func (*HourQuery) WhereNotNull

func (q *HourQuery) WhereNotNull(columns ...any) *HourQuery

func (*HourQuery) WhereNull

func (q *HourQuery) WhereNull(columns ...any) *HourQuery

func (*HourQuery) WhereRelation

func (q *HourQuery) WhereRelation(relation string, column any, args ...any) *HourQuery

func (*HourQuery) With

func (q *HourQuery) With(relations ...string) *HourQuery

func (*HourQuery) WithAvg

func (q *HourQuery) WithAvg(relation, column string) *HourQuery

func (*HourQuery) WithCount

func (q *HourQuery) WithCount(relations ...string) *HourQuery

func (*HourQuery) WithExists

func (q *HourQuery) WithExists(relation string) *HourQuery

func (*HourQuery) WithMax

func (q *HourQuery) WithMax(relation, column string) *HourQuery

func (*HourQuery) WithMin

func (q *HourQuery) WithMin(relation, column string) *HourQuery

func (*HourQuery) WithSum

func (q *HourQuery) WithSum(relation, column string) *HourQuery

func (*HourQuery) Without

func (q *HourQuery) Without(relations ...string) *HourQuery

func (*HourQuery) WithoutGlobalScope

func (q *HourQuery) WithoutGlobalScope(identifier string) *HourQuery

func (*HourQuery) WithoutGlobalScopes

func (q *HourQuery) WithoutGlobalScopes(identifiers ...string) *HourQuery

type HourRow

type HourRow struct {
	ID, Weekday, From, To string
	DeleteURL             string
}

HourRow is a window of the week as the settings list shows it.

type HourView

type HourView struct {
	ID          string
	Weekday     int
	StartMinute int
	EndMinute   int
}

HourView is a window of the team's week as a screen carries it.

type HoursPageData

type HoursPageData struct {
	Screen
	Rows                               []HourRow
	SortKey, SortDir                   string
	URL, NewURL                        string
	Pager                              components.Paginator
	CurrentPage                        int
	Pages, Total                       int
	PerPage                            int
	CanConfigure                       bool
	ServicesURL, HoursURL, ClosuresURL string
}

HoursPageData is the team's list of weekly windows.

func (HoursPageData) TableState

func (d HoursPageData) TableState() components.DataTableState

TableState is the list as the data table draws its addresses from.

type IndexPageData

type IndexPageData struct {
	Screen
	Rows          []BookingRow
	Query         string
	Statuses      []string
	SortKey       string
	SortDir       string
	URL, NewURL   string
	CanBook       bool
	Pager         components.Paginator
	CurrentPage   int
	Pages, Total  int
	PerPage       int
	StatusOptions []components.SelectOption
}

IndexPageData is the customer's list, a page at a time, filtered, searched and ordered on the server.

func (IndexPageData) TableState

func (d IndexPageData) TableState() components.DataTableState

TableState is the customer's list as the data table draws its addresses from: what is searched, the order in force (the next start first when nobody ordered), the statuses chosen, the page and its size. Every control of the table builds its address from it, so a step keeps the others.

type Labels

type Labels struct {
	Locale string
	// contains filtered or unexported fields
}

Labels are the sentences of this package in one locale.

func (Labels) By

func (l Labels) By(side string) string

By is the label of the side that acted: ByCustomer, ByTeam or BySystem.

func (Labels) Field

func (l Labels) Field(name string) string

Field is what a person reads in place of an input's name, in a summary of the rejected fields: "service" reads "Serviço". A field with no line reads the way the input was named.

func (Labels) Status

func (l Labels) Status(s Status) string

Status is the label of a booking's status.

func (Labels) Summary

func (l Labels) Summary(errs validation.Errors) []string

Summary is one line per rejected message, the field named before it, for the banner above a form. Nil when nothing was rejected, so a layout that ranges over it draws no banner.

func (Labels) T

func (l Labels) T(key string) string

T reads a key of this package: "screen.index_title".

func (Labels) Weekday

func (l Labels) Weekday(n int) string

Weekday is the name of a day of the week, 0 for Sunday.

type ListQuery

type ListQuery struct {
	Search   string
	Statuses []Status
	Sort     string
	Dir      string
	Page     int
	PerPage  int
}

ListQuery narrows the customer's list. Page counts from one.

type Listing

type Listing[T any] struct {
	Rows  []T
	Total int
	Page  int
	Pages int
}

Listing is one page of a list of the team's settings.

type Module

type Module struct {
	// contains filtered or unexported fields
}

Module is what the application registers.

It implements foundation.Module, which is Name and Routes and nothing else -- that pair is the whole public contract between a package and the framework.

It also implements foundation.Migratable, because it owns tables, and foundation.Publishable, because it hands view sources to the project. The other optional interfaces are declared beside Module in the framework and are opted into the same way, by implementing them: Bootable to prepare state at boot, Background to run a loop of its own, Schedulable to declare work for the scheduler, Health to report on the storage it depends on, Closable to give resources back at shutdown.

func New

func New(cfg Config, db *data.DB, sessions *security.SessionStore) (*Module, error)

New returns the module, or the reason it cannot be built.

The collaborators are parameters and not fields somebody fills in afterwards: a module that could be registered half-wired is a module whose first request is the thing that reports the missing half.

It returns an error rather than panicking or carrying on, because everything it refuses is a wiring mistake, and a wiring mistake found at boot costs one restart. The same mistake found later is a request that reached a nil handle.

func (*Module) App

func (m *Module) App() *AppService

App is the application's hooks and tasks. Settle and Find take the Grant the application issued; Remind and ExpireHolds issue their own.

func (*Module) Bookings

func (m *Module) Bookings() *BookingService

Bookings is the customer's use cases, for an application that calls them from its own code. Every method asks the policy, so handing it out opens nothing.

func (*Module) Boot

func (m *Module) Boot(context.Context) error

Boot refuses to serve when a view this package renders is not in the binary.

A compiled view registers itself from init(), so by the time anything boots the question has one answer already: either the application published the files, compiled them and imported the package they became, or it did not. Asking here turns "did anybody run the install command" into one refusal at start-up that names the views and the command, instead of a 500 on the first request that reached one of them -- which is where it used to be answered, once per page, to whoever happened to open it.

It also holds the destination. Every file the archive offers has to land under the module directory named after this module: an archive that reached resources/views/home.kyse.go would land on a page the application wrote, and what publishes the files writes what the archive says.

func (*Module) CustomerRoutes

func (m *Module) CustomerRoutes(r *fhttp.Router)

CustomerRoutes registers the customer's routes alone, under Prefix, for an application that mounts them inside its own side -- a customer's panel -- with that side's guards on r.

func (*Module) ExpireHolds

func (m *Module) ExpireHolds(ctx context.Context) (int, error)

ExpireHolds frees the slots of the bookings whose payment never came. See AppService.ExpireHolds. The application schedules it every five minutes.

func (*Module) Find

func (m *Module) Find(ctx context.Context, g security.Grant, ref string) (*Booking, error)

Find looks a booking of the Grant's space up by its identifier or protocol. See AppService.Find.

func (*Module) Labels

func (m *Module) Labels() Labels

Labels answers the sentences of the module's locale.

func (*Module) Migrations

func (m *Module) Migrations() []foundation.Migration

Migrations declares the schema this module owns.

They are returned in the order their names sort in, which is the order they apply in: the name carries the order, and nothing else decides it.

func (*Module) Name

func (m *Module) Name() string

Name is the module identifier: a lowercase slug, stable, no spaces.

It is what `aru route:list` groups by and what the route names are prefixed with, so changing it changes addresses that other code has already written down.

func (*Module) Publishes

func (m *Module) Publishes() []foundation.Publication

Publishes declares the files this package offers, each at the path it takes relative to the root of the project.

One tree, under one tag. A publication may carry a page, a component, a configuration file, a migration, a catalogue of sentences or an asset, and this package offers the first of those and nothing else. Each absence is a decision rather than an omission:

  • configuration is the Config struct New is handed, checked by the compiler and validated before the module exists. A file copied into the project beside it would be a second place to say the same thing, and only one of the two could be the one the code reads.
  • a stylesheet, a script or any other asset is registered with the view layer and served from an address derived from its own bytes. Copying one into the project would put a second copy of those bytes under a second address, and a page can only reference one of them.
  • translations are overridden by writing the lines the application wants into its own override tree, which the catalogue loader already reads. A copy of every line this package ships is a copy that goes stale, and it goes stale without saying so.
  • migrations are declared and collected, never copied. A copy in the project's own migration directory is found by the runner as well, so one schema change applies twice under two names.

What is left is the markup, and it is here for the reason the others are not: it is the one thing the project is expected to edit. A package cannot know what a screen should say in a product it has never seen.

func (*Module) Remind

func (m *Module) Remind(ctx context.Context) (int, error)

Remind sends the reminders that are due. See AppService.Remind. The application schedules it every five minutes.

func (*Module) Routes

func (m *Module) Routes(r *fhttp.Router)

Routes registers every route of the module: the customer's and the team's.

An application that keeps the two sides apart -- and the team's session is valid on its own side only -- registers them separately with CustomerRoutes and TeamRoutes, each on the router group its own guards are on.

Every route needs somebody signed in, so the guard is mounted once per side, on the router the routes are registered on, rather than route by route: r is replaced by the guarded group before the first registration, and no unguarded router is left in scope for the next route to be added to. RequireAuth sends a request with no session to the sign-in screen, and puts the subject of one that has a session on its context, where a handler reads it with ctx.User; Config.Middleware runs after it, and Config.TeamMiddleware after that on the team's routes.

func (*Module) Settle

func (m *Module) Settle(ctx context.Context, g security.Grant, bookingID, paymentRef string) (*Booking, error)

Settle puts the application's payment on a booking that waits for one. See AppService.Settle.

func (*Module) Team

func (m *Module) Team() *TeamService

Team is the team's use cases, for an application that calls them from its own code. Every method asks TeamPolicy, so handing it out opens nothing.

func (*Module) TeamRoutes

func (m *Module) TeamRoutes(r *fhttp.Router)

TeamRoutes registers the team's routes alone, under TeamPrefix, for an application that mounts them inside its operator console with that console's guards on r.

func (*Module) URLs

func (m *Module) URLs() URLs

URLs are the addresses of the routes, for an application that links to them: a menu, an e-mail.

type NewPageData

type NewPageData struct {
	Screen
	// Action is where the booking is posted, and FormURL where the free times of
	// a day are asked for.
	Action, FormURL, BackURL string
	ServiceOptions           []components.SelectOption
	ServiceKey               string
	// ServiceNote says how long the service takes and whether it asks for a
	// payment.
	ServiceNote     string
	RequiresPayment bool
	NoServices      bool
	Day             string
	MinDay, MaxDay  string
	// Searched says a day was chosen, so an empty list of times means none are
	// free and not that nobody asked.
	Searched bool
	Slots    []components.RadioOption
	Subject  BookingSubject
}

NewPageData is the form that books: the service and the day the customer is looking at, and the free times of that day.

type Notifier

type Notifier interface {
	Notify(ctx context.Context, e Event) error
}

Notifier tells people that something happened to a booking.

The application implements it with its own channel -- a WhatsApp message, an e-mail: this package sends none. Notify runs after the change is stored, and its error does not undo the change: the booking is already made and the slot already taken, and a channel that is down is no reason for a customer to book it twice. The error is logged, with no personal text, and the request goes on. An application that must not lose a notification enqueues it here and delivers it from its queue.

type Page

type Page struct {
	Rows  []Summary
	Total int
	Page  int
	Pages int
}

Page is one page of a list of bookings, and how many rows the whole list has.

type Paths

type Paths struct {
	New, Confirmation, Rescheduling, Cancellation string
	Completion, Release, NoShow                   string
	Settings, Services, Hours, Closures           string
}

Paths are the segments the routes of this package are built from. Each one starts with "/" and holds no wildcard.

GET    Prefix                                 the customer's bookings
GET    Prefix + New                           the form that books, and the free times of a day
POST   Prefix                                 book
GET    Prefix + /{id}                         one booking
POST   Prefix + /{id} + Confirmation          confirm
GET    Prefix + /{id} + Rescheduling          the form that moves it
POST   Prefix + /{id} + Rescheduling          move it
POST   Prefix + /{id} + Cancellation          cancel

and under TeamPrefix the list, one booking, Completion, Release, NoShow, Cancellation and Rescheduling, and under TeamPrefix + Settings the team's configuration: Services, Hours and Closures, each with a list, New, a creation, and a deletion by DELETE on /{id}. The settings sit under a segment of their own so that no booking identifier can be read as one.

type Person

type Person struct {
	ID    string
	Name  string
	Email string
}

Person is somebody the application knows, as the screens name them.

type ReschedulePageData

type ReschedulePageData struct {
	Screen
	Booking                  BookingRow
	Action, FormURL, BackURL string
	Day                      string
	MinDay, MaxDay           string
	Searched                 bool
	Slots                    []components.RadioOption
}

ReschedulePageData is the customer's form that moves a booking.

type Schedule

type Schedule struct {
	// Zone is the timezone the weekly windows and the days are written in.
	Zone *time.Location
	// Weekly are the windows of the week.
	Weekly []Window
	// Closures are the ranges nothing is booked in.
	Closures []Span
	// Busy are the bookings that hold the team at the moment the schedule is
	// asked about. The caller decides which are: Booking.Occupies.
	Busy []Span
	// Capacity is how many bookings one time takes at once. Below one it is one.
	Capacity int
	// Step is the distance between two starts offered on a day. Below a minute
	// it is the DefaultSlotStep.
	Step time.Duration
	// MinNotice is how far ahead of now the earliest start is, and Horizon how
	// far ahead the latest is. A Horizon of zero or less leaves the future
	// unbounded.
	MinNotice time.Duration
	Horizon   time.Duration
}

Schedule is the team's availability as pure data: what a day offers, and whether a time is free. It reads no database and no clock, so the rules of the agenda are a function of what it is handed and nothing else, and an application can ask the same questions the screens do ("when is the next free start?") with the same answer.

func (Schedule) Free

func (s Schedule) Free(span Span) bool

Free reports whether the range is outside every closure and has a place free, whatever the weekly windows, MinNotice and Horizon say. It is the check for a booking that is moved by the team, or one whose payment arrives after the hold: the time was offered once, and what can have changed since is who else holds it.

func (Schedule) Offers

func (s Schedule) Offers(now, start time.Time, duration time.Duration) bool

Offers reports whether start is one of the starts Slots offers for its day. It is how a booking is checked: what the screen offered is the only thing a request can ask for, so a start made up by hand is refused like a start that was taken in the meantime.

func (Schedule) Slots

func (s Schedule) Slots(now, day time.Time, duration time.Duration) []time.Time

Slots are the starts a day offers for something that takes duration, sorted: every step inside a window of that weekday where the whole of it fits in the window, clears MinNotice and Horizon from now, stays out of every closure and finds a place free.

Only the calendar date of day counts: the year, month and day it carries, read as written, and not the zone it is in. The weekday, the windows and the midnight they count from are Schedule.Zone's.

type Screen

type Screen struct {
	hview.Page
	Labels Labels
	// URLs are the addresses of the package's routes.
	URLs URLs
	// Location is the timezone instants are written in.
	Location *time.Location
	// contains filtered or unexported fields
}

Screen is what every page of this package carries: the page hesape's view.New builds, the application's chrome, and the sentences.

It embeds hesape's view.Page, so every page of this package is a hesape/view.Layout -- what the layouts of an application on Arandu framework v0.62 and newer assert -- and it answers HasErrors and ErrorSummary as well, so it is also the framework/view.Layout an older layout asks for.

func (Screen) All

func (s Screen) All() []string

All is one line per rejected message, for the banner above a form, in the screen's language: the field is named by its label in the catalogue ("Serviço: Preencha este campo.").

func (Screen) Chrome

func (s Screen) Chrome() any

Chrome is what Config.Chrome answered for this screen: the application's sidebar, navigation and account menu, in whatever type its layout draws from. A layout asserts that type on it; nil when Config.Chrome is nil.

func (Screen) Clock

func (s Screen) Clock(t time.Time) string

Clock is the time of day of an instant, in the screen's timezone.

func (Screen) DatePicker

DatePicker is a date field with the Kyse calendar beside it, in the screen's language. The field is still a date input: it holds the value, submits it as 2026-11-10 whatever the reader sees, and the browser draws it in the reader's own order (dd/mm/aaaa in Brazil). The calendar writes into it. What the caller already set is kept.

func (Screen) Day

func (s Screen) Day(t time.Time) string

Day is the date of an instant, in the screen's timezone.

func (Screen) ErrorSummary

func (s Screen) ErrorSummary() []string

ErrorSummary is one line per rejected field: framework/view.Layout's name for All.

func (Screen) FieldErrors

func (s Screen) FieldErrors(name string) []string

FieldErrors is every message for one field.

func (Screen) Form

func (s Screen) Form() FormState

Form is the form state of the page.

func (Screen) HasErrors

func (s Screen) HasErrors() bool

HasErrors says whether the attempt that landed here was rejected: framework/view.Layout's name for hesape's Any.

func (Screen) LogValue

func (s Screen) LogValue() slog.Value

LogValue is the page as a log line carries it, the token redacted.

func (Screen) MarshalJSON

func (s Screen) MarshalJSON() ([]byte, error)

MarshalJSON writes the page with the CSRF token redacted, as framework/view.Page does: a page dumped for debugging never publishes the token. It answers for every page data that embeds Screen.

func (Screen) SearchLabel

func (s Screen) SearchLabel(table string) string

SearchLabel is the name a screen reader gives a table's search box: "Buscar em Agendamentos".

func (Screen) StatusOptions

func (s Screen) StatusOptions() []components.SelectOption

StatusOptions are the statuses as options of a filter or a select.

func (Screen) TableLines

func (s Screen) TableLines() components.DataTableLines

TableLines are the sentences a data table on these screens says, every one from the package's catalogue (the keys under "table"), so the table speaks the screen's language and not the English underneath. The placeholders ({label}, {total}, {n}, {column}) are the table's own and are filled when it draws them.

func (Screen) TimePicker

TimePicker is a time field, in whole minutes.

func (Screen) WeekdayOptions

func (s Screen) WeekdayOptions() []components.SelectOption

WeekdayOptions are the days of the week as options of a select, Sunday first.

func (Screen) When

func (s Screen) When(t time.Time) string

When is an instant as Brazilians write it, in the screen's timezone.

type Service

type Service struct {
	model.Model

	// ID is the identifier, generated by the application.
	ID string `db:"id"`

	// Key is the stable name the application and a booking refer to it by:
	// "instalacao", "reconfiguracao". It is unique.
	Key string `db:"key"`

	// Name and Description are what the screens show.
	Name        string `db:"name"`
	Description string `db:"description"`

	// DurationMinutes is how long the team takes, and so how long a booking
	// holds its slot.
	DurationMinutes int `db:"duration_minutes"`

	// RequiresPayment says a booking of this service waits for a payment.
	RequiresPayment Flag `db:"requires_payment"`

	// Active says the service is offered. An inactive one keeps the bookings
	// already made and takes no new one.
	Active Flag `db:"active"`

	// CreatedAt and UpdatedAt are when the row was written and last changed, in
	// UTC.
	CreatedAt time.Time `db:"created_at"`
	UpdatedAt time.Time `db:"updated_at"`
}

Service is something the team does for a customer at a time: a camera reconfiguration, an installation. The team's catalogue of them is shared by every space, so the table has no tenant column: it is Global, written only by the team's service after the team's policy answered, and read by a customer only to book.

It carries no price. What a service costs is the application's catalogue, and RequiresPayment only says the booking waits for the application's word that it was paid.

Services, ServiceQuery and ServiceCollection are generated beside this file, in ServiceQuery.go, by aru model:build.

func (*Service) Fresh

func (row *Service) Fresh(ctx context.Context, g auth.Grant, with ...string) (*Service, error)

Fresh reads the row again, as a new Service; it shadows the untyped one the embedded model promotes.

func (*Service) Replicate

func (row *Service) Replicate(except ...string) (*Service, error)

Replicate returns an unsaved copy of the row without its key; it shadows the untyped one the embedded model promotes.

type ServiceCollection

type ServiceCollection []*Service

ServiceCollection is rows of Service, as a query returns them.

func ServiceCollectionOf

func ServiceCollectionOf(rows model.Rows) ServiceCollection

ServiceCollectionOf converts rows of the table of Service. A nil input is a nil collection.

func (ServiceCollection) Contains

func (c ServiceCollection) Contains(key any) bool

func (ServiceCollection) Except

func (c ServiceCollection) Except(keys ...any) ServiceCollection

func (ServiceCollection) Find

func (c ServiceCollection) Find(key any) *Service

func (ServiceCollection) FindOrFail

func (c ServiceCollection) FindOrFail(key any) (*Service, error)

func (ServiceCollection) Fresh

func (ServiceCollection) Load

func (c ServiceCollection) Load(ctx context.Context, g auth.Grant, relations ...string) error

func (ServiceCollection) LoadCount

func (c ServiceCollection) LoadCount(ctx context.Context, g auth.Grant, relations ...string) error

func (ServiceCollection) LoadMissing

func (c ServiceCollection) LoadMissing(ctx context.Context, g auth.Grant, relations ...string) error

func (ServiceCollection) ModelKeys

func (c ServiceCollection) ModelKeys() []any

func (ServiceCollection) Only

func (c ServiceCollection) Only(keys ...any) ServiceCollection

func (ServiceCollection) Pluck

func (c ServiceCollection) Pluck(column string) []any

func (ServiceCollection) Rows

func (c ServiceCollection) Rows() model.Rows

Rows converts the collection back to the core's rows.

func (ServiceCollection) ToArray

func (c ServiceCollection) ToArray() []map[string]any

func (ServiceCollection) Unique

type ServiceFormPageData

type ServiceFormPageData struct {
	Screen
	Action, BackURL string
	Editing         bool
	Key             string
	Name            string
	Description     string
	Duration        string
	RequiresPayment bool
	Active          bool
}

ServiceFormPageData is the form that adds or changes a service.

type ServiceInput

type ServiceInput struct {
	Key             string
	Name            string
	Description     string
	DurationMinutes int
	RequiresPayment bool
	Active          bool
}

ServiceInput is what the team writes when it creates or changes a service. There is no price: what a service costs is the application's catalogue.

type ServiceQuery

type ServiceQuery struct {
	// contains filtered or unexported fields
}

ServiceQuery is a query on the table of Service.

The methods that build return the query, so they chain. The methods that run take a context and an auth.Grant, and return Service rows or a value; there is no way to run one without a Grant.

func Services

func Services(db model.DB) *ServiceQuery

Services starts a query on the table of Service, through db.

Global scopes are on and, unless the table is Global, every statement is filtered by the tenant of the Grant its terminal takes.

func (*ServiceQuery) AddSelect

func (q *ServiceQuery) AddSelect(columns ...any) *ServiceQuery

func (*ServiceQuery) ApplyListing

func (q *ServiceQuery) ApplyListing(state pagination.ListingState) *ServiceQuery

ApplyListing narrows and orders the query as a listing state asks: the search, the facets and the sort with its tie-break. Every column comes from the spec the state was read with, never from the request.

func (*ServiceQuery) Avg

func (q *ServiceQuery) Avg(ctx context.Context, g auth.Grant, column any) (any, error)

func (*ServiceQuery) Base

func (q *ServiceQuery) Base() *model.Builder

Base returns the core builder the query forwards to. It is for code in this package -- a local scope in the custom block of model.go -- and for the factory, which builds rows through it.

func (*ServiceQuery) Chunk

func (q *ServiceQuery) Chunk(ctx context.Context, g auth.Grant, count int, callback func(ServiceCollection, int) (bool, error)) error

func (*ServiceQuery) Clone

func (q *ServiceQuery) Clone() *ServiceQuery

Clone returns an independent copy of the query.

func (*ServiceQuery) Count

func (q *ServiceQuery) Count(ctx context.Context, g auth.Grant, columns ...any) (int64, error)

func (*ServiceQuery) Create

func (q *ServiceQuery) Create(ctx context.Context, g auth.Grant, attributes map[string]any) (*Service, error)

func (*ServiceQuery) Cursor

func (q *ServiceQuery) Cursor(ctx context.Context, g auth.Grant) iter.Seq2[*Service, error]

func (*ServiceQuery) CursorPaginate

func (q *ServiceQuery) CursorPaginate(ctx context.Context, g auth.Grant, perPage int, cursor *pagination.Cursor, opts pagination.Options, columns ...any) (ServiceCollection, *pagination.CursorPage, error)

func (*ServiceQuery) Decrement

func (q *ServiceQuery) Decrement(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*ServiceQuery) Delete

func (q *ServiceQuery) Delete(ctx context.Context, g auth.Grant) (int64, error)

func (*ServiceQuery) DoesntExist

func (q *ServiceQuery) DoesntExist(ctx context.Context, g auth.Grant) (bool, error)

func (*ServiceQuery) DoesntHave

func (q *ServiceQuery) DoesntHave(relation, boolean string, callback func(*query.Builder)) *ServiceQuery

func (*ServiceQuery) Each

func (q *ServiceQuery) Each(ctx context.Context, g auth.Grant, count int, callback func(*Service, int) (bool, error)) error

func (*ServiceQuery) Exists

func (q *ServiceQuery) Exists(ctx context.Context, g auth.Grant) (bool, error)

func (*ServiceQuery) Find

func (q *ServiceQuery) Find(ctx context.Context, g auth.Grant, id any, columns ...any) (*Service, error)

func (*ServiceQuery) FindMany

func (q *ServiceQuery) FindMany(ctx context.Context, g auth.Grant, ids []any, columns ...any) (ServiceCollection, error)

func (*ServiceQuery) FindOrFail

func (q *ServiceQuery) FindOrFail(ctx context.Context, g auth.Grant, id any, columns ...any) (*Service, error)

func (*ServiceQuery) FindOrNew

func (q *ServiceQuery) FindOrNew(ctx context.Context, g auth.Grant, id any, columns ...any) (*Service, error)

func (*ServiceQuery) First

func (q *ServiceQuery) First(ctx context.Context, g auth.Grant, columns ...any) (*Service, error)

First returns the first row, or nil and no error when there is none.

func (*ServiceQuery) FirstOrCreate

func (q *ServiceQuery) FirstOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Service, error)

func (*ServiceQuery) FirstOrFail

func (q *ServiceQuery) FirstOrFail(ctx context.Context, g auth.Grant, columns ...any) (*Service, error)

func (*ServiceQuery) FirstOrNew

func (q *ServiceQuery) FirstOrNew(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Service, error)

func (*ServiceQuery) FirstWhere

func (q *ServiceQuery) FirstWhere(ctx context.Context, g auth.Grant, column any, args ...any) (*Service, error)

func (*ServiceQuery) ForPage

func (q *ServiceQuery) ForPage(page, perPage int) *ServiceQuery

func (*ServiceQuery) ForceCreate

func (q *ServiceQuery) ForceCreate(ctx context.Context, g auth.Grant, attributes map[string]any) (*Service, error)

func (*ServiceQuery) Get

func (q *ServiceQuery) Get(ctx context.Context, g auth.Grant, columns ...any) (ServiceCollection, error)

Get runs the query and returns the rows.

func (*ServiceQuery) GroupBy

func (q *ServiceQuery) GroupBy(groups ...any) *ServiceQuery

func (*ServiceQuery) Has

func (q *ServiceQuery) Has(relation, operator string, count int, boolean string, callback func(*query.Builder)) *ServiceQuery

func (*ServiceQuery) Increment

func (q *ServiceQuery) Increment(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*ServiceQuery) Insert

func (q *ServiceQuery) Insert(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*ServiceQuery) InsertOrIgnore

func (q *ServiceQuery) InsertOrIgnore(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*ServiceQuery) Join

func (q *ServiceQuery) Join(table any, first any, args ...any) *ServiceQuery

func (*ServiceQuery) Latest

func (q *ServiceQuery) Latest(column ...string) *ServiceQuery

func (*ServiceQuery) Limit

func (q *ServiceQuery) Limit(value int) *ServiceQuery

func (*ServiceQuery) Listing

Listing runs the query as a listing state asks and returns the rows of the page beside the result a table is drawn from: the state, the page with its total and the count of every facet value. Every statement it issues carries the tenant of g.

func (*ServiceQuery) Max

func (q *ServiceQuery) Max(ctx context.Context, g auth.Grant, column any) (any, error)

func (*ServiceQuery) Min

func (q *ServiceQuery) Min(ctx context.Context, g auth.Grant, column any) (any, error)

func (*ServiceQuery) New

func (q *ServiceQuery) New() (*Service, error)

New returns an empty Service on the query's connection, not yet saved, filled with what WithAttributes recorded on the query.

func (*ServiceQuery) Offset

func (q *ServiceQuery) Offset(value int) *ServiceQuery

func (*ServiceQuery) Oldest

func (q *ServiceQuery) Oldest(column ...string) *ServiceQuery

func (*ServiceQuery) OrDoesntHave

func (q *ServiceQuery) OrDoesntHave(relation string) *ServiceQuery

func (*ServiceQuery) OrHas

func (q *ServiceQuery) OrHas(relation, operator string, count int) *ServiceQuery

func (*ServiceQuery) OrWhere

func (q *ServiceQuery) OrWhere(column any, args ...any) *ServiceQuery

OrWhere adds an or-where clause; a func(*ServiceQuery) in place of the column adds a group.

func (*ServiceQuery) OrWhereDoesntHave

func (q *ServiceQuery) OrWhereDoesntHave(relation string, callback func(*query.Builder)) *ServiceQuery

func (*ServiceQuery) OrWhereHas

func (q *ServiceQuery) OrWhereHas(relation string, callback func(*query.Builder)) *ServiceQuery

func (*ServiceQuery) OrWhereNot

func (q *ServiceQuery) OrWhereNot(column any, args ...any) *ServiceQuery

OrWhereNot adds an or-joined negated where clause, or a negated group.

func (*ServiceQuery) OrWhereRelation

func (q *ServiceQuery) OrWhereRelation(relation string, column any, args ...any) *ServiceQuery

func (*ServiceQuery) OrderBy

func (q *ServiceQuery) OrderBy(column any, direction ...string) *ServiceQuery

func (*ServiceQuery) OrderByDesc

func (q *ServiceQuery) OrderByDesc(column any) *ServiceQuery

func (*ServiceQuery) Paginate

func (q *ServiceQuery) Paginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (ServiceCollection, *pagination.LengthAwarePage, error)

func (*ServiceQuery) Pluck

func (q *ServiceQuery) Pluck(ctx context.Context, g auth.Grant, column string) ([]any, error)

func (*ServiceQuery) Select

func (q *ServiceQuery) Select(columns ...any) *ServiceQuery

func (*ServiceQuery) SelectRaw

func (q *ServiceQuery) SelectRaw(expression string, bindings ...any) *ServiceQuery

func (*ServiceQuery) SimplePaginate

func (q *ServiceQuery) SimplePaginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (ServiceCollection, *pagination.Page, error)

func (*ServiceQuery) Sole

func (q *ServiceQuery) Sole(ctx context.Context, g auth.Grant, columns ...any) (*Service, error)

func (*ServiceQuery) SoleValue

func (q *ServiceQuery) SoleValue(ctx context.Context, g auth.Grant, column string) (any, error)

func (*ServiceQuery) Sum

func (q *ServiceQuery) Sum(ctx context.Context, g auth.Grant, column any) (any, error)

func (*ServiceQuery) Touch

func (q *ServiceQuery) Touch(ctx context.Context, g auth.Grant, column ...string) (int64, error)

func (*ServiceQuery) Update

func (q *ServiceQuery) Update(ctx context.Context, g auth.Grant, values map[string]any) (int64, error)

func (*ServiceQuery) UpdateOrCreate

func (q *ServiceQuery) UpdateOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Service, error)

func (*ServiceQuery) Upsert

func (q *ServiceQuery) Upsert(ctx context.Context, g auth.Grant, values []map[string]any, uniqueBy, update []string) (int64, error)

func (*ServiceQuery) Value

func (q *ServiceQuery) Value(ctx context.Context, g auth.Grant, column string) (any, error)

func (*ServiceQuery) ValueOrFail

func (q *ServiceQuery) ValueOrFail(ctx context.Context, g auth.Grant, column string) (any, error)

func (*ServiceQuery) Where

func (q *ServiceQuery) Where(column any, args ...any) *ServiceQuery

Where adds a where clause; a func(*ServiceQuery) in place of the column adds a group.

func (*ServiceQuery) WhereBelongsTo

func (q *ServiceQuery) WhereBelongsTo(relationshipName string, related ...model.Entity) *ServiceQuery

func (*ServiceQuery) WhereBetween

func (q *ServiceQuery) WhereBetween(column any, from, to any) *ServiceQuery

func (*ServiceQuery) WhereColumn

func (q *ServiceQuery) WhereColumn(first any, args ...any) *ServiceQuery

func (*ServiceQuery) WhereDoesntHave

func (q *ServiceQuery) WhereDoesntHave(relation string, callback func(*query.Builder)) *ServiceQuery

func (*ServiceQuery) WhereExists

func (q *ServiceQuery) WhereExists(callback func(*query.Builder)) *ServiceQuery

func (*ServiceQuery) WhereHas

func (q *ServiceQuery) WhereHas(relation string, callback func(*query.Builder)) *ServiceQuery

func (*ServiceQuery) WhereHasCount

func (q *ServiceQuery) WhereHasCount(relation string, callback func(*query.Builder), operator string, count int) *ServiceQuery

func (*ServiceQuery) WhereIn

func (q *ServiceQuery) WhereIn(column any, values []any) *ServiceQuery

func (*ServiceQuery) WhereKey

func (q *ServiceQuery) WhereKey(id any) *ServiceQuery

func (*ServiceQuery) WhereNot

func (q *ServiceQuery) WhereNot(column any, args ...any) *ServiceQuery

WhereNot adds a negated where clause, or a negated group.

func (*ServiceQuery) WhereNotExists

func (q *ServiceQuery) WhereNotExists(callback func(*query.Builder)) *ServiceQuery

func (*ServiceQuery) WhereNotIn

func (q *ServiceQuery) WhereNotIn(column any, values []any) *ServiceQuery

func (*ServiceQuery) WhereNotNull

func (q *ServiceQuery) WhereNotNull(columns ...any) *ServiceQuery

func (*ServiceQuery) WhereNull

func (q *ServiceQuery) WhereNull(columns ...any) *ServiceQuery

func (*ServiceQuery) WhereRelation

func (q *ServiceQuery) WhereRelation(relation string, column any, args ...any) *ServiceQuery

func (*ServiceQuery) With

func (q *ServiceQuery) With(relations ...string) *ServiceQuery

func (*ServiceQuery) WithAvg

func (q *ServiceQuery) WithAvg(relation, column string) *ServiceQuery

func (*ServiceQuery) WithCount

func (q *ServiceQuery) WithCount(relations ...string) *ServiceQuery

func (*ServiceQuery) WithExists

func (q *ServiceQuery) WithExists(relation string) *ServiceQuery

func (*ServiceQuery) WithMax

func (q *ServiceQuery) WithMax(relation, column string) *ServiceQuery

func (*ServiceQuery) WithMin

func (q *ServiceQuery) WithMin(relation, column string) *ServiceQuery

func (*ServiceQuery) WithSum

func (q *ServiceQuery) WithSum(relation, column string) *ServiceQuery

func (*ServiceQuery) Without

func (q *ServiceQuery) Without(relations ...string) *ServiceQuery

func (*ServiceQuery) WithoutGlobalScope

func (q *ServiceQuery) WithoutGlobalScope(identifier string) *ServiceQuery

func (*ServiceQuery) WithoutGlobalScopes

func (q *ServiceQuery) WithoutGlobalScopes(identifiers ...string) *ServiceQuery

type ServiceRow

type ServiceRow struct {
	ID, Key, Name, Description string
	Duration                   string
	Payment, Active            string
	EditURL, DeleteURL         string
}

ServiceRow is a service as the settings list shows it.

type ServiceView

type ServiceView struct {
	ID              string
	Key             string
	Name            string
	Description     string
	DurationMinutes int
	RequiresPayment bool
	Active          bool
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

ServiceView is a service as a screen, a response or a customer's form carries it.

type ServicesPageData

type ServicesPageData struct {
	Screen
	Rows                               []ServiceRow
	Query                              string
	SortKey, SortDir                   string
	URL, NewURL                        string
	Pager                              components.Paginator
	CurrentPage                        int
	Pages, Total                       int
	PerPage                            int
	CanConfigure                       bool
	ServicesURL, HoursURL, ClosuresURL string
}

ServicesPageData is the team's list of services.

func (ServicesPageData) TableState

TableState is the list as the data table draws its addresses from.

type ShowPageData

type ShowPageData struct {
	Screen
	Booking                              BookingRow
	BackURL                              string
	ConfirmURL, RescheduleURL, CancelURL string
	CanConfirm, CanReschedule, CanCancel bool
	AwaitingPayment                      bool
	PaymentURL                           string
	ChangeClosed                         bool
	HoldExpired                          bool
}

ShowPageData is one booking, for the customer.

type Span

type Span struct {
	Start time.Time
	End   time.Time
}

Span is a range of time: a booking that holds the team, or a closure. It holds from Start up to, and not including, End.

type Status

type Status string

Status is where a booking stands.

const (
	// StatusAwaitingPayment is a booking that holds its slot until HoldUntil and
	// waits for the application to say the payment settled.
	StatusAwaitingPayment Status = "awaiting_payment"
	// StatusScheduled is a booking that holds its slot: paid, released as a
	// courtesy, or made for a service that asks for no payment.
	StatusScheduled Status = "scheduled"
	// StatusConfirmed is a scheduled booking the customer confirmed.
	StatusConfirmed Status = "confirmed"
	// StatusCompleted is a booking the team did.
	StatusCompleted Status = "completed"
	// StatusCancelled is a booking nobody will show up to, cancelled by the
	// customer or by the team.
	StatusCancelled Status = "cancelled"
	// StatusExpired is a booking whose hold lapsed before a payment came.
	StatusExpired Status = "expired"
	// StatusNoShow is a booking the customer did not turn up for.
	StatusNoShow Status = "no_show"
)

The statuses of a booking.

func (Status) Valid

func (s Status) Valid() bool

Valid reports whether the status is one of the seven.

type SubjectResolver

type SubjectResolver interface {
	// Resolve returns the label of the subject, or an error when the subject
	// does not exist or is not the tenant's. An error rejects the booking.
	Resolve(ctx context.Context, tenant string, subject BookingSubject) (label string, err error)
}

SubjectResolver checks what a booking is about and names it. It is optional, and it is the application's: the module keeps the subject opaque -- a type, an identifier and a label the application understands, "camera", "42", "Portaria" -- and cannot know whether the camera is the customer's.

type Summary

type Summary struct {
	ID              string
	Tenant          string
	Code            string
	ServiceKey      string
	ServiceName     string
	Subject         BookingSubject
	RequesterID     string
	RequesterName   string
	CustomerNote    string
	StartsAt        time.Time
	EndsAt          time.Time
	Status          Status
	HoldUntil       *time.Time
	PaymentRef      string
	ReleasedBy      string
	ReleasedReason  string
	ConfirmedAt     *time.Time
	RemindedAt      *time.Time
	CompletedAt     *time.Time
	CompletedBy     string
	TeamNote        string
	Reschedules     int
	CancelReason    string
	CancelledBy     string
	CreatedAt       time.Time
	UpdatedAt       time.Time
	ReleasedByName  string
	CompletedByName string
}

Summary is a booking as a list, a response or a notification carries it: plain values, with no connection to the database.

type TeamIndexPageData

type TeamIndexPageData struct {
	Screen
	Rows          []BookingRow
	Query         string
	Statuses      []string
	Day           string
	SortKey       string
	SortDir       string
	URL           string
	Pager         components.Paginator
	CurrentPage   int
	Pages, Total  int
	PerPage       int
	StatusOptions []components.SelectOption
	// SettingsURLs are the team's settings pages, for the links above the list.
	ServicesURL, HoursURL, ClosuresURL string
	CanConfigure                       bool
}

TeamIndexPageData is the team's list, a page at a time, filtered, searched and ordered on the server.

func (TeamIndexPageData) TableState

TableState is the team's list as the data table draws its addresses from; see IndexPageData.TableState. The day travels as a facet, so a step of the table keeps it.

type TeamPolicy

type TeamPolicy struct {
	// Realm is the tenant the team signs in to. Empty refuses everybody.
	Realm string
}

TeamPolicy is the only authority over what the platform team does with the bookings of any space and with its own agenda.

It denies unless the subject is a member of the team -- a subject of Realm, the tenant the team signs in to -- who was granted the action. A subject of any other tenant is refused whatever actions it carries, and so is a subject somebody else is viewing as: an operator inside a customer's account acts as the customer and reads no other space.

It is the one policy that does not compare a record's tenant with the subject's, because crossing tenants is what the team does. The tenant of the work itself is not the subject's: the service reads the booking to find it, and then acts in that tenant under a Grant scoped to it, issued only after this policy allowed the action.

func (TeamPolicy) Can

Can decides whether the subject may perform the action.

func (TeamPolicy) Writes

func (TeamPolicy) Writes(a security.Action) bool

Writes reports whether a Grant issued for the action may change anything.

type TeamQuery

type TeamQuery struct {
	// Search matches the code, the requester's name, the service and the
	// subject's label.
	Search   string
	Statuses []Status
	// Day narrows the list to the bookings that start on that day of
	// Config.Zone, as "2026-11-10". Empty means every day.
	Day string
	// Tenant narrows the list to one space.
	Tenant  string
	Sort    string
	Dir     string
	Page    int
	PerPage int
}

TeamQuery narrows the team's list. Page counts from one.

type TeamService

type TeamService struct {
	// contains filtered or unexported fields
}

TeamService orchestrates what the platform team does with the bookings of every space and with its own agenda.

A member of the team is a subject of Config.TeamTenant, and TeamPolicy decides what they may do. The bookings are in the customers' tenants, so a use case on one goes in two steps: it asks the policy for a Grant in the team's own realm, finds the booking's tenant with it, and then acts with a Grant scoped to that one tenant, which exists only because the first one was issued for the same action. Nothing a request names chooses the tenant: it is the one the booking's row says. The team's services, hours and closures belong to no customer: the realm Grant is the one they are read and written with.

func NewTeamService

func NewTeamService(db *data.DB, cfg Config) *TeamService

NewTeamService wires the service over the application's database handle.

func (*TeamService) Booking

func (s *TeamService) Booking(ctx context.Context, actor security.Subject, id string) (Summary, error)

Booking returns one booking of any space, with what the team wrote on it and the names of the team members who acted.

func (*TeamService) Bookings

func (s *TeamService) Bookings(ctx context.Context, actor security.Subject, q TeamQuery) (Page, error)

Bookings returns a page of the bookings of every space: searched by code, requester, service and subject, filtered by status, day and space, and ordered by the server.

func (*TeamService) CanConfigure

func (s *TeamService) CanConfigure(ctx context.Context, actor security.Subject) error

CanConfigure answers whether the subject may change the team's settings, for the screen that draws a form. It asks the policy exactly as the change does, and the refusal it returns is the one the change would.

func (*TeamService) Cancel

func (s *TeamService) Cancel(ctx context.Context, actor security.Subject, id, reason string) (*Booking, error)

Cancel gives the booking's slot up on the team's behalf, at any time before it is done. The customer is told.

func (*TeamService) Closures

Closures returns a page of the team's closures.

func (*TeamService) Complete

func (s *TeamService) Complete(ctx context.Context, actor security.Subject, id, note string) (*Booking, error)

Complete records that the team did the work. The note is the team's and the customer never reads it.

func (*TeamService) CreateClosure

func (s *TeamService) CreateClosure(ctx context.Context, actor security.Subject, in ClosureInput) (*Closure, error)

CreateClosure adds a range the team takes no booking in.

func (*TeamService) CreateHour

func (s *TeamService) CreateHour(ctx context.Context, actor security.Subject, in HourInput) (*Hour, error)

CreateHour adds a window to the team's week. It cannot overlap one the same weekday already has.

func (*TeamService) CreateService

func (s *TeamService) CreateService(ctx context.Context, actor security.Subject, in ServiceInput) (*Service, error)

CreateService adds a service to the team's catalogue.

func (*TeamService) DeleteClosure

func (s *TeamService) DeleteClosure(ctx context.Context, actor security.Subject, id string) error

DeleteClosure removes a closure.

func (*TeamService) DeleteHour

func (s *TeamService) DeleteHour(ctx context.Context, actor security.Subject, id string) error

DeleteHour removes a window from the team's week.

func (*TeamService) DeleteService

func (s *TeamService) DeleteService(ctx context.Context, actor security.Subject, id string) error

DeleteService removes a service from the catalogue. The bookings already made keep the key and the name they were made with.

func (*TeamService) Hours

Hours returns a page of the windows of the team's week.

func (*TeamService) NoShow

func (s *TeamService) NoShow(ctx context.Context, actor security.Subject, id string) (*Booking, error)

NoShow records that the customer did not turn up. It is possible once the start has passed.

func (*TeamService) Release

func (s *TeamService) Release(ctx context.Context, actor security.Subject, id, reason string) (*Booking, error)

Release lets a booking that waits for a payment through as a courtesy: it holds its slot for good, and who did it and why are kept on the booking and in the log. A booking whose hold lapsed is released only if its slot is still free.

func (*TeamService) Reschedule

func (s *TeamService) Reschedule(ctx context.Context, actor security.Subject, id string, newStart time.Time) (*Booking, error)

Reschedule moves a booking to the start the team chose, at any time before it is done. The team is not held to the weekly hours, the notice or the horizon: it can fit somebody in. It is held to the closures and to the capacity, which are about whether the team is there. The customer is told.

func (*TeamService) Service

func (s *TeamService) Service(ctx context.Context, actor security.Subject, id string) (ServiceView, error)

Service returns one service of the team.

func (*TeamService) Services

Services returns a page of the team's services, the inactive ones too.

func (*TeamService) UpdateService

func (s *TeamService) UpdateService(ctx context.Context, actor security.Subject, id string, in ServiceInput) (*Service, error)

UpdateService changes a service. Its key is changed with it, so the bookings made under the old key keep the key they were made with.

type TeamShowPageData

type TeamShowPageData struct {
	Screen
	Booking                                                      BookingRow
	BackURL                                                      string
	CompleteURL, ReleaseURL, NoShowURL, CancelURL, RescheduleURL string
	CanComplete, CanRelease, CanNoShow, CanCancel, CanReschedule bool
	Day, Time                                                    string
	MinDay                                                       string
}

TeamShowPageData is one booking, for the team, with what the team wrote and the controls that act on it.

type URLs

type URLs struct {
	// contains filtered or unexported fields
}

URLs are the addresses of the routes under the module's configuration. A link is built from here and never written out a second time: under another Prefix the paths move and the names do not.

func NewURLs

func NewURLs(prefix, teamPrefix string, paths Paths) URLs

NewURLs are the addresses of the routes under a pair of prefixes and the segments, for a screen built outside a request: a test that draws a page, an e-mail that links to one. Empty values are the defaults.

func (URLs) Cancel

func (u URLs) Cancel(id string) string

Cancel is where the customer posts a cancellation.

func (URLs) Confirm

func (u URLs) Confirm(id string) string

Confirm is where the customer posts a confirmation.

func (URLs) Index

func (u URLs) Index() string

Index is the customer's list.

func (URLs) New

func (u URLs) New() string

New is the form that books, and where a day's free times are asked for.

func (URLs) NewFor

func (u URLs) NewFor(service string, subject BookingSubject) string

NewFor is New for a service and a subject, so the application can link a customer to the form with the booking already about something: NewFor("reconfiguracao", BookingSubject{Type: "camera", ID: "42", Label: "Portaria"}).

func (URLs) Reschedule

func (u URLs) Reschedule(id string) string

Reschedule is the customer's form that moves a booking, and where it is posted.

func (URLs) Show

func (u URLs) Show(id string) string

Show is one booking, for the customer.

func (URLs) TeamCancel

func (u URLs) TeamCancel(id string) string

TeamCancel is where the team posts a cancellation.

func (URLs) TeamClosure

func (u URLs) TeamClosure(id string) string

TeamClosure is one closure: where it is deleted.

func (URLs) TeamClosureNew

func (u URLs) TeamClosureNew() string

TeamClosureNew is the form that adds a closure.

func (URLs) TeamClosures

func (u URLs) TeamClosures() string

TeamClosures is the team's list of closures.

func (URLs) TeamComplete

func (u URLs) TeamComplete(id string) string

TeamComplete is where the team posts that the work was done.

func (URLs) TeamHour

func (u URLs) TeamHour(id string) string

TeamHour is one window: where it is deleted.

func (URLs) TeamHourNew

func (u URLs) TeamHourNew() string

TeamHourNew is the form that adds a window.

func (URLs) TeamHours

func (u URLs) TeamHours() string

TeamHours is the team's list of weekly windows.

func (URLs) TeamIndex

func (u URLs) TeamIndex() string

TeamIndex is the team's list.

func (URLs) TeamNoShow

func (u URLs) TeamNoShow(id string) string

TeamNoShow is where the team posts an absence.

func (URLs) TeamRelease

func (u URLs) TeamRelease(id string) string

TeamRelease is where the team posts a courtesy.

func (URLs) TeamReschedule

func (u URLs) TeamReschedule(id string) string

TeamReschedule is where the team posts a new time.

func (URLs) TeamService

func (u URLs) TeamService(id string) string

TeamService is one service: where it is edited, saved and deleted.

func (URLs) TeamServiceNew

func (u URLs) TeamServiceNew() string

TeamServiceNew is the form that adds a service.

func (URLs) TeamServices

func (u URLs) TeamServices() string

TeamServices is the team's list of services.

func (URLs) TeamShow

func (u URLs) TeamShow(id string) string

TeamShow is one booking, for the team.

type Window

type Window struct {
	// Weekday is 0 for Sunday to 6 for Saturday, as time.Weekday counts.
	Weekday int
	// StartMinute and EndMinute are minutes since midnight: 540 to 1080 is 09:00
	// to 18:00.
	StartMinute int
	EndMinute   int
}

Window is a stretch of the team's week: the team takes bookings on that weekday between the two minutes, counted since midnight in Schedule.Zone.

Directories

Path Synopsis
internal
platform
Package platform is the bookings table read without the tenant filter.
Package platform is the bookings table read without the tenant filter.

Jump to

Keyboard shortcuts

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