Planner/core/polls.go

60 lines
1.5 KiB
Go
Raw Normal View History

2025-02-12 19:29:00 +01:00
package core
2024-11-09 19:35:44 +01:00
import (
2025-04-16 23:24:23 +02:00
"database/sql"
2024-11-09 19:35:44 +01:00
"fmt"
2025-04-16 23:24:23 +02:00
"slices"
2024-11-09 19:35:44 +01:00
"strings"
)
2025-04-16 23:24:23 +02:00
func (p *Poll) Create(db *sql.DB) error {
row := db.QueryRow(
"INSERT INTO polls(plan_id, options) VALUES(?,?) RETURNING id",
p.PlanId,
p.Options,
)
if err := row.Scan(&p.Id); err != nil {
return fmt.Errorf("Unable to create new poll for plan %d: %w", p.PlanId, err)
2024-11-09 19:35:44 +01:00
}
2025-04-16 23:24:23 +02:00
return nil
}
2024-11-09 19:35:44 +01:00
2025-04-16 23:24:23 +02:00
func PollGet(db *sql.DB, user User, id uint) (*Poll, error) {
var poll Poll
row := db.QueryRow("SELECT id,plan_id,options FROM polls WHERE id=?", id)
if err := row.Scan(&poll.Id, &poll.PlanId, &poll.Options); err != nil {
return nil, err
2024-11-09 19:35:44 +01:00
}
return &poll, nil
}
2025-04-16 23:24:23 +02:00
func PollsList(db *sql.DB, plan_id int) ([]Poll, error) {
var polls []Poll
rows, err := db.Query("SELECT id,plan_id,options FROM polls WHERE plan_id=?", plan_id)
if err != nil {
return polls, fmt.Errorf("Unable to query polls for plan %d: %w", plan_id, err)
2024-11-09 19:35:44 +01:00
}
2025-04-16 23:24:23 +02:00
defer rows.Close()
for rows.Next() {
var poll Poll
if err := rows.Scan(&poll.Id, &poll.PlanId, &poll.Options); err != nil {
return nil, fmt.Errorf("Unable to scan polls for plan %d: %w", plan_id, err)
}
polls = append(polls, poll)
2024-11-09 19:35:44 +01:00
}
2025-04-16 23:24:23 +02:00
return polls, nil
}
func (p *Poll) SetVote(db *sql.DB, member Member, option string) error {
options := strings.Split(p.Options, ",")
if !slices.Contains(options, option) {
return fmt.Errorf("%s is not a valid option (%s): %w", option, options, ErrInvalidOption)
2024-11-09 19:35:44 +01:00
}
2025-04-16 23:24:23 +02:00
_, err := db.Exec("INSERT INTO votes(poll_id,member_id,value) VALUES (?,?,?)", p.Id, member.Id, option)
2024-11-09 19:35:44 +01:00
2025-04-16 23:24:23 +02:00
return err
2024-11-09 19:35:44 +01:00
}