polls

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrPollVoteForbidden - no user, a poll of results only, outside its
	// dates or not public.
	ErrPollVoteForbidden = errors.New("poll vote not allowed")
	// ErrPollVoteInvalid - no options, more than MaxAnswers, one twice or one
	// not of the poll.
	ErrPollVoteInvalid = errors.New("poll vote invalid options")
	// ErrPollRevoteNotAllowed - the user has voted and the poll doesn't let a
	// vote change.
	ErrPollRevoteNotAllowed = errors.New("poll revote not allowed")
)

The refusals of a vote (Vote).

View Source
var Assets embed.FS

Assets - the module's templates/ and static/, built into the binary (modules.Assets, paths.SetModuleAssets): a site runs without the module's source directory.

Functions

func ParsePollDatetimeLocal

func ParsePollDatetimeLocal(s string, loc *time.Location) (*time.Time, error)

ParsePollDatetimeLocal parses a datetime-local value (2006-01-02T15:04) in loc; an empty one is nil.

func RegisterPollVoteRoutes

func RegisterPollVoteRoutes(r modulekit.Mux, store *sessions.CookieStore, pc *PollController, voteRL *ratelimit.RateLimiter)

RegisterPollVoteRoutes registers authenticated POST for casting poll votes (CSRF checked in handler), rate limited per client IP, and the poll alone for the "Poll" block (any visitor).

func Wire

func Wire(d modulekit.Deps) modulekit.Parts

Wire - the module's service, controller (the poll content type's pages), vote routes, the "Poll" block's polls and [[poll:<id>]] in texts (modulekit).

Types

type DefaultPollService

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

DefaultPollService - PollService on a PollRepository.

func (*DefaultPollService) BlockTargets

BlockTargets - see PollService.BlockTargets.

func (*DefaultPollService) BuildView

func (s *DefaultPollService) BuildView(ctx context.Context, p *Poll, userID int, loggedIn bool) (*PollView, error)

BuildView - the poll's page data for the user (loggedIn false - a visitor): the votes per option and in all, the user's choices, whether they can vote and get the form, whether the poll is yet to open or over.

func (*DefaultPollService) ByNodeID

func (s *DefaultPollService) ByNodeID(ctx context.Context, nodeID int) (*Poll, error)

ByNodeID - the node's poll with its options and its node.

func (*DefaultPollService) BySlug

func (s *DefaultPollService) BySlug(ctx context.Context, slug string) (*Poll, error)

BySlug - the poll whose node has the address slug (a node of another type - not found).

func (*DefaultPollService) Create

func (s *DefaultPollService) Create(ctx context.Context, p *Poll) (*Poll, error)

Create stores a new poll (a slug from its title when it has none); the action log gets "Content created".

func (*DefaultPollService) Update

func (s *DefaultPollService) Update(ctx context.Context, p *Poll) (*Poll, error)

Update stores the poll (an empty slug keeps the old one); what it changed of the content (status, author, address) goes to the action log.

func (*DefaultPollService) Vote

func (s *DefaultPollService) Vote(ctx context.Context, nodeID, userID int, optionIDs []int) error

Vote stores the user's choice of options in the node's poll instead of their earlier one; a refused vote is ErrPollVoteForbidden, ErrPollVoteInvalid or ErrPollRevoteNotAllowed.

func (*DefaultPollService) VoteAudit

func (s *DefaultPollService) VoteAudit(ctx context.Context, nodeID int) (*Poll, []PollVoteAuditRow, error)

VoteAudit - the node's poll and its votes one by one, newest first: who chose which option and when.

type EntPollRepository

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

EntPollRepository - the polls: their rows in the module's tables, each one's node in the core's, written together in one transaction (modulekit.InTx: the core's repository and the module's client).

func NewPollRepository

func NewPollRepository(db *sql.DB, nodes modulekit.NodesRepository, users modulekit.UserRepository) *EntPollRepository

NewPollRepository - the polls on db, on the module's own ent schema (ent/); a poll's node and its voters are the core's (nodes, users).

func (EntPollRepository) BlockTargets

BlockTargets - the polls, the newest first: node ID → question.

func (EntPollRepository) ByNodeID

func (r EntPollRepository) ByNodeID(ctx context.Context, nodeID int) (*Poll, error)

ByNodeID returns the node's poll with its options in their order, its node and the node's page SEO.

func (EntPollRepository) BySlug

func (r EntPollRepository) BySlug(ctx context.Context, slug string) (*Poll, error)

BySlug - the poll whose node has the address slug.

func (EntPollRepository) Create

func (r EntPollRepository) Create(ctx context.Context, p *Poll) (*Poll, error)

Create stores the poll's node, poll row and options in one transaction.

func (EntPollRepository) SaveUserVotes

func (r EntPollRepository) SaveUserVotes(ctx context.Context, pollID, userID int, optionIDs []int, revote bool) (saved bool, err error)

SaveUserVotes stores the user's votes in the poll, in one transaction holding the poll's row (lockPoll): with revote, instead of their earlier ones; without it, only if they have none yet (saved false - they voted already). Two votes of one user at once don't both pass the check, nor leave both sets.

func (EntPollRepository) Update

func (r EntPollRepository) Update(ctx context.Context, p *Poll) (*Poll, error)

Update stores the poll row, its node and its options in one transaction (an option with votes is kept even when removed).

func (EntPollRepository) UserOptionVotes

func (r EntPollRepository) UserOptionVotes(ctx context.Context, pollID, userID int) ([]int, error)

UserOptionVotes returns the options the user voted for in the poll (none - not voted).

func (EntPollRepository) VoteAuditRows

func (r EntPollRepository) VoteAuditRows(ctx context.Context, pollID int) ([]PollVoteAuditRow, error)

VoteAuditRows returns the poll's votes, newest first, with their voters' names and the options' labels.

func (EntPollRepository) VoteCounts

func (r EntPollRepository) VoteCounts(ctx context.Context, pollID int) (map[int]int, int, error)

VoteCounts - the poll's votes per option and in all, counted by the database (a poll may have many).

type Poll

type Poll struct {
	ID            int
	Node          modulekit.Node
	Description   string
	MaxAnswers    int
	AvailableFrom *time.Time
	AvailableTo   *time.Time
	ResultsOnly   bool
	AllowRevote   bool // false - one vote per user, no changing it
	Options       PollOptions
}

Poll - a poll, a node of the poll content type (its question is the node's title): its description, how many answers a vote may choose, when it is open, and its options.

func ToPollEntity

func ToPollEntity(p *generated.Poll) *Poll

ToPollEntity - a poll row with its options (its node - the core's - set by the repository).

type PollController

type PollController struct {
	*modulekit.BaseController
	// contains filtered or unexported fields
}

PollController - the pages of the poll content type: the poll's page and block, its create and edit forms, voting and the votes' log.

func NewPollController

func NewPollController(deps modulekit.BaseDeps, d PollDeps) *PollController

NewPollController - the polls controller on the base dependencies and d (the polls and nodes services, the node deleter).

func (*PollController) Create

func (c *PollController) Create(w http.ResponseWriter, r *http.Request)

Create saves a new poll from its form (POST /create/{type} of the poll type): an invalid form comes back with its errors; then the poll's page.

func (*PollController) CreateForm

func (c *PollController) CreateForm(w http.ResponseWriter, r *http.Request)

CreateForm renders the form of a new poll (GET /create/{type} of the poll type).

func (*PollController) Delete

func (c *PollController) Delete(w http.ResponseWriter, r *http.Request)

Delete deletes the poll's node (POST /node/{id}/delete); then the front page.

func (*PollController) Detail

func (c *PollController) Detail(w http.ResponseWriter, r *http.Request)

Detail renders the poll's page at its address (GET /<slug>, the node page of a poll): its question, results and vote form, the edit and delete links for those who may.

func (*PollController) Edit

Edit renders the poll's edit form (GET /node/{id}/edit).

func (*PollController) Embed

func (c *PollController) Embed(w http.ResponseWriter, r *http.Request)

Embed handles GET /node/{id}/poll/embed: the poll alone (poll_block of poll/detail.html - its question linking its page, the results and the vote form) for the "Poll" block, loaded by polls.js. Per visitor (their vote, the form's token), so a cached page still shows each one theirs.

func (*PollController) Save

Save saves the poll from its edit form (POST /node/{id}/edit): an invalid form comes back with its errors, its publishing changes only for who administers content; then the poll's page.

func (*PollController) VoteAPI

func (c *PollController) VoteAPI(w http.ResponseWriter, r *http.Request)

VoteAPI accepts JSON and returns updated counts; session cookie required (AuthJSONMiddleware).

func (*PollController) VoteSubmit

func (c *PollController) VoteSubmit(w http.ResponseWriter, r *http.Request)

VoteSubmit casts the signed-in user's vote from the poll's form (POST /node/{id}/poll/vote): a refused vote is a bad request; then the poll's page.

func (*PollController) VotesAudit

func (c *PollController) VotesAudit(w http.ResponseWriter, r *http.Request)

VotesAudit lists individual votes (manifest.PermViewVotes). GET /node/{id}/poll/votes

type PollDeps

type PollDeps struct {
	PollService  PollService
	NodesService modulekit.NodesService
	NodeDeleter  modulekit.NodeDeleter
}

PollDeps - what NewPollController needs besides the BaseDeps.

type PollForm

type PollForm struct {
	modulekit.NodeMetaFields
	NodeID        int
	Title         string
	Slug          string
	Description   string
	MaxAnswers    int
	AvailableFrom string // datetime-local ("2006-01-02T15:04") or empty
	AvailableTo   string
	ResultsOnly   bool
	AllowRevote   bool // allow changing the vote
	Status        int
	OnModeration  int
	OptionLabels  []string
	OptionIDs     []int // parallel to labels for edit; 0 = new
	// CommentMode - see modulekit.CommentMode's doc comment. Empty means
	// "keep the existing node's value" (or "open" on create).
	CommentMode string
}

PollForm - the poll's create and edit form: the question, the options, the voting settings and the node's settings.

func (*PollForm) ParsePollForm

func (f *PollForm) ParsePollForm(r *http.Request) error

ParsePollForm fills the form from the request's fields (the description sanitized, options with empty labels dropped); it always returns nil.

func (*PollForm) Validate

func (f *PollForm) Validate(ctx context.Context) map[string]string

Validate - the form's errors by field: no question, fewer than two options (empty - valid).

type PollOption

type PollOption struct {
	ID     int
	PollID int
	Label  string
	Weight int
}

PollOption - an answer option of a poll: its label and its place among the options (Weight).

type PollOptionCount

type PollOptionCount struct {
	PollOption
	Count    int
	Percent  float64 // 0-100 when TotalVotes > 0
	Selected bool    // current user voted for this option
}

PollOptionCount is an option with aggregated vote count for display.

type PollOptions

type PollOptions []PollOption

PollOptions - a poll's answer options, in their order.

type PollRepository

type PollRepository interface {
	ByNodeID(ctx context.Context, nodeID int) (*Poll, error)
	BySlug(ctx context.Context, slug string) (*Poll, error)
	Create(ctx context.Context, p *Poll) (*Poll, error)
	Update(ctx context.Context, p *Poll) (*Poll, error)
	VoteCounts(ctx context.Context, pollID int) (map[int]int, int, error)
	UserOptionVotes(ctx context.Context, pollID, userID int) ([]int, error)
	SaveUserVotes(ctx context.Context, pollID, userID int, optionIDs []int, revote bool) (bool, error)
	VoteAuditRows(ctx context.Context, pollID int) ([]PollVoteAuditRow, error)
	BlockTargets(ctx context.Context) ([]modulekit.PluginBlockTarget, error)
}

PollRepository - the store of polls: their nodes, options and votes.

type PollService

type PollService interface {
	ByNodeID(ctx context.Context, nodeID int) (*Poll, error)
	BySlug(ctx context.Context, slug string) (*Poll, error)
	Create(ctx context.Context, p *Poll) (*Poll, error)
	Update(ctx context.Context, p *Poll) (*Poll, error)
	BuildView(ctx context.Context, p *Poll, userID int, loggedIn bool) (*PollView, error)
	Vote(ctx context.Context, nodeID, userID int, optionIDs []int) error
	VoteAudit(ctx context.Context, nodeID int) (*Poll, []PollVoteAuditRow, error)
	// BlockTargets - the polls the "Poll" block can show (its placement
	// page): node ID → question.
	BlockTargets(ctx context.Context) ([]modulekit.PluginBlockTarget, error)
}

PollService - the polls: their pages' data and the votes in them.

func NewPollService

func NewPollService(
	repository PollRepository,
	nodes modulekit.NodesService,
	baseLogger *slog.Logger,
) PollService

NewPollService - the polls service on repository; nodes makes a new poll's address from its question when it has none (GenerateUniqueSlug).

type PollView

type PollView struct {
	Poll         Poll
	OptionCounts []PollOptionCount
	TotalVotes   int
	CanVote      bool
	ShowForm     bool
	BeforeStart  bool
	AfterEnd     bool
}

PollView aggregates data for the poll detail page.

type PollVoteAuditRow

type PollVoteAuditRow struct {
	UserID      int
	Username    string
	UserSlug    string
	OptionLabel string
	VotedAt     time.Time
}

PollVoteAuditRow is one row of the vote log (for admins/moderators).

Directories

Path Synopsis
ent
Package ent - the polls module's own ent schema (schema/), its generated client (generated/, go generate) and migration files (migrations/<dialect>/, scripts/migrations_gen.sh writes them), apart from the core's: the module's set of migrations (Schema).
Package ent - the polls module's own ent schema (schema/), its generated client (generated/, go generate) and migration files (migrations/<dialect>/, scripts/migrations_gen.sh writes them), apart from the core's: the module's set of migrations (Schema).
schema
Package schema - the polls module's own ent schema: its tables, apart from the core's.
Package schema - the polls module's own ent schema: its tables, apart from the core's.
Package manifest declares the polls module (its registry entry).
Package manifest declares the polls module (its registry entry).

Jump to

Keyboard shortcuts

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