Compare commits
1
Commits
c6f80e243d
...
posts-ui
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3ce29031f |
@@ -44,6 +44,16 @@ FROM thread
|
|||||||
JOIN users u ON u.id = thread.author_id
|
JOIN users u ON u.id = thread.author_id
|
||||||
ORDER BY thread.created_at, thread.id;
|
ORDER BY thread.created_at, thread.id;
|
||||||
|
|
||||||
|
-- name: GetRootPostVoteSummary :one
|
||||||
|
SELECT
|
||||||
|
COALESCE(SUM(value), 0)::bigint AS score,
|
||||||
|
COALESCE(
|
||||||
|
MAX(value) FILTER (WHERE user_id = sqlc.arg(viewer_id)),
|
||||||
|
0
|
||||||
|
)::bigint AS user_vote
|
||||||
|
FROM post_votes
|
||||||
|
WHERE post_id = sqlc.arg(root_id);
|
||||||
|
|
||||||
-- name: UpdatePost :execrows
|
-- name: UpdatePost :execrows
|
||||||
UPDATE posts
|
UPDATE posts
|
||||||
SET
|
SET
|
||||||
@@ -51,6 +61,14 @@ SET
|
|||||||
updated_at = sqlc.arg(updated_at)
|
updated_at = sqlc.arg(updated_at)
|
||||||
WHERE id = sqlc.arg(id);
|
WHERE id = sqlc.arg(id);
|
||||||
|
|
||||||
|
-- name: UpdateRootPostState :execrows
|
||||||
|
UPDATE posts
|
||||||
|
SET
|
||||||
|
post_state = sqlc.arg(post_state),
|
||||||
|
updated_at = sqlc.arg(updated_at)
|
||||||
|
WHERE id = sqlc.arg(id)
|
||||||
|
AND parent_id IS NULL;
|
||||||
|
|
||||||
-- name: ListRootPosts :many
|
-- name: ListRootPosts :many
|
||||||
WITH RECURSIVE roots AS (
|
WITH RECURSIVE roots AS (
|
||||||
SELECT p.*
|
SELECT p.*
|
||||||
@@ -100,6 +118,46 @@ LEFT JOIN post_votes viewer_vote
|
|||||||
ORDER BY score DESC, roots.created_at, roots.id
|
ORDER BY score DESC, roots.created_at, roots.id
|
||||||
LIMIT sqlc.arg(row_limit);
|
LIMIT sqlc.arg(row_limit);
|
||||||
|
|
||||||
|
-- name: ListRootPostsByAuthor :many
|
||||||
|
SELECT
|
||||||
|
p.id, p.parent_id, p.author_id,
|
||||||
|
u.name AS author_name, u.role AS author_role,
|
||||||
|
p.title, p.body, p.city, p.post_date,
|
||||||
|
p.post_state, p.created_at, p.updated_at
|
||||||
|
FROM posts p
|
||||||
|
JOIN users u ON u.id = p.author_id
|
||||||
|
WHERE p.parent_id IS NULL
|
||||||
|
AND p.author_id = sqlc.arg(author_id)
|
||||||
|
AND p.post_state <> sqlc.arg(hidden_state)
|
||||||
|
ORDER BY p.created_at DESC, p.id DESC
|
||||||
|
LIMIT sqlc.arg(row_limit);
|
||||||
|
|
||||||
|
-- name: ListRootPostsAnsweredBy :many
|
||||||
|
WITH RECURSIVE ancestors AS (
|
||||||
|
SELECT p.id, p.parent_id
|
||||||
|
FROM posts p
|
||||||
|
WHERE p.author_id = sqlc.arg(admin_id)
|
||||||
|
AND p.parent_id IS NOT NULL
|
||||||
|
|
||||||
|
UNION
|
||||||
|
|
||||||
|
SELECT parent.id, parent.parent_id
|
||||||
|
FROM posts parent
|
||||||
|
JOIN ancestors child ON child.parent_id = parent.id
|
||||||
|
)
|
||||||
|
SELECT DISTINCT
|
||||||
|
root.id, root.parent_id, root.author_id,
|
||||||
|
u.name AS author_name, u.role AS author_role,
|
||||||
|
root.title, root.body, root.city, root.post_date,
|
||||||
|
root.post_state, root.created_at, root.updated_at
|
||||||
|
FROM posts root
|
||||||
|
JOIN ancestors ON ancestors.id = root.id
|
||||||
|
JOIN users u ON u.id = root.author_id
|
||||||
|
WHERE root.parent_id IS NULL
|
||||||
|
AND root.post_state <> sqlc.arg(hidden_state)
|
||||||
|
ORDER BY root.created_at DESC, root.id DESC
|
||||||
|
LIMIT sqlc.arg(row_limit);
|
||||||
|
|
||||||
-- name: PostIsVisibleRoot :one
|
-- name: PostIsVisibleRoot :one
|
||||||
SELECT EXISTS(
|
SELECT EXISTS(
|
||||||
SELECT 1
|
SELECT 1
|
||||||
|
|||||||
@@ -438,6 +438,21 @@ func (m *Memory) GetPostThread(_ context.Context, rootID string) (*Post, error)
|
|||||||
return buildPostTree(posts, rootID)
|
return buildPostTree(posts, rootID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *Memory) GetPostThreadForViewer(ctx context.Context, rootID, viewerID string) (*Post, error) {
|
||||||
|
root, err := m.GetPostThread(ctx, rootID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
for _, value := range m.postVotes[rootID] {
|
||||||
|
root.Score += value
|
||||||
|
}
|
||||||
|
root.UserVote = m.postVotes[rootID][viewerID]
|
||||||
|
root.Answered = m.threadContainsAdminReply(rootID)
|
||||||
|
return root, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (m *Memory) UpdatePost(_ context.Context, post *Post) error {
|
func (m *Memory) UpdatePost(_ context.Context, post *Post) error {
|
||||||
if post == nil {
|
if post == nil {
|
||||||
return fmt.Errorf("%w: post is nil", ErrInvalidPost)
|
return fmt.Errorf("%w: post is nil", ErrInvalidPost)
|
||||||
@@ -489,6 +504,73 @@ func (m *Memory) ListRootPosts(_ context.Context, postDate, viewerID string) ([]
|
|||||||
return posts, nil
|
return posts, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *Memory) ListRootPostsByAuthor(_ context.Context, authorID string) ([]Post, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
posts := make([]Post, 0)
|
||||||
|
for _, post := range m.posts {
|
||||||
|
if post.ParentID != nil ||
|
||||||
|
post.AuthorID != authorID ||
|
||||||
|
post.PostState == PostStateHidden {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
posts = append(posts, *clonePostWithAuthor(post, m.users))
|
||||||
|
}
|
||||||
|
return sortProfilePosts(posts), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Memory) ListRootPostsAnsweredBy(_ context.Context, adminID string) ([]Post, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
posts := make([]Post, 0)
|
||||||
|
for _, root := range m.posts {
|
||||||
|
if root.ParentID != nil || root.PostState == PostStateHidden {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
participated := false
|
||||||
|
for _, post := range m.posts {
|
||||||
|
if post.AuthorID == adminID && m.postIsDescendantOf(post, root.ID) {
|
||||||
|
participated = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if participated {
|
||||||
|
posts = append(posts, *clonePostWithAuthor(root, m.users))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sortProfilePosts(posts), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Memory) SetRootPostState(_ context.Context, id string, state PostState) error {
|
||||||
|
switch state {
|
||||||
|
case PostStateVisible, PostStateHidden, PostStateLocked:
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("%w: invalid post state", ErrInvalidPost)
|
||||||
|
}
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
post, ok := m.posts[id]
|
||||||
|
if !ok || post.ParentID != nil {
|
||||||
|
return sql.ErrNoRows
|
||||||
|
}
|
||||||
|
post.PostState = state
|
||||||
|
post.UpdatedAt = time.Now().UTC().Format(time.RFC3339Nano)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func sortProfilePosts(posts []Post) []Post {
|
||||||
|
sort.Slice(posts, func(i, j int) bool {
|
||||||
|
if posts[i].CreatedAt != posts[j].CreatedAt {
|
||||||
|
return posts[i].CreatedAt > posts[j].CreatedAt
|
||||||
|
}
|
||||||
|
return posts[i].ID > posts[j].ID
|
||||||
|
})
|
||||||
|
if len(posts) > ProfileListLimit {
|
||||||
|
posts = posts[:ProfileListLimit]
|
||||||
|
}
|
||||||
|
return posts
|
||||||
|
}
|
||||||
|
|
||||||
func (m *Memory) VotePost(_ context.Context, userID, postID string, value int) error {
|
func (m *Memory) VotePost(_ context.Context, userID, postID string, value int) error {
|
||||||
m.mu.Lock()
|
m.mu.Lock()
|
||||||
defer m.mu.Unlock()
|
defer m.mu.Unlock()
|
||||||
|
|||||||
@@ -64,6 +64,9 @@ CREATE TABLE IF NOT EXISTS posts (
|
|||||||
{name: "index post replies", sql: `
|
{name: "index post replies", sql: `
|
||||||
CREATE INDEX IF NOT EXISTS idx_posts_parent_created
|
CREATE INDEX IF NOT EXISTS idx_posts_parent_created
|
||||||
ON posts(parent_id, created_at, id)`},
|
ON posts(parent_id, created_at, id)`},
|
||||||
|
{name: "index post authors", sql: `
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_posts_author_created
|
||||||
|
ON posts(author_id, created_at DESC, id DESC)`},
|
||||||
{name: "index root posts", sql: `
|
{name: "index root posts", sql: `
|
||||||
CREATE INDEX IF NOT EXISTS idx_posts_root_date
|
CREATE INDEX IF NOT EXISTS idx_posts_root_date
|
||||||
ON posts(post_date, post_state)
|
ON posts(post_date, post_state)
|
||||||
@@ -117,6 +120,15 @@ CREATE INDEX IF NOT EXISTS idx_post_votes_post_id
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func migratePostAuthorIndex(ctx context.Context, exec execContext) error {
|
||||||
|
if _, err := exec.ExecContext(ctx, `
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_posts_author_created
|
||||||
|
ON posts(author_id, created_at DESC, id DESC)`); err != nil {
|
||||||
|
return fmt.Errorf("idx_posts_author_created: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func migratePostDate(ctx context.Context, exec execContext) error {
|
func migratePostDate(ctx context.Context, exec execContext) error {
|
||||||
steps := []struct {
|
steps := []struct {
|
||||||
name string
|
name string
|
||||||
@@ -306,6 +318,7 @@ CREATE TABLE IF NOT EXISTS schema_migrations (
|
|||||||
{"005_post_vote_post_id_index", migratePostVoteIndex},
|
{"005_post_vote_post_id_index", migratePostVoteIndex},
|
||||||
{"006_post_date", migratePostDate},
|
{"006_post_date", migratePostDate},
|
||||||
{"007_post_state", migratePostState},
|
{"007_post_state", migratePostState},
|
||||||
|
{"008_post_author_index", migratePostAuthorIndex},
|
||||||
}
|
}
|
||||||
for _, m := range migrations {
|
for _, m := range migrations {
|
||||||
if applied[m.version] {
|
if applied[m.version] {
|
||||||
|
|||||||
@@ -138,6 +138,18 @@ WHERE schemaname = current_schema()
|
|||||||
if postVoteIndexCount != 1 {
|
if postVoteIndexCount != 1 {
|
||||||
t.Fatalf("post vote index count = %d, want 1", postVoteIndexCount)
|
t.Fatalf("post vote index count = %d, want 1", postVoteIndexCount)
|
||||||
}
|
}
|
||||||
|
var postAuthorIndexCount int
|
||||||
|
if err := conn.QueryRowContext(ctx, `
|
||||||
|
SELECT count(*)
|
||||||
|
FROM pg_indexes
|
||||||
|
WHERE schemaname = current_schema()
|
||||||
|
AND tablename = 'posts'
|
||||||
|
AND indexname = 'idx_posts_author_created'`).Scan(&postAuthorIndexCount); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if postAuthorIndexCount != 1 {
|
||||||
|
t.Fatalf("post author index count = %d, want 1", postAuthorIndexCount)
|
||||||
|
}
|
||||||
if _, err := conn.ExecContext(ctx, `
|
if _, err := conn.ExecContext(ctx, `
|
||||||
INSERT INTO post_votes (user_id, post_id, value)
|
INSERT INTO post_votes (user_id, post_id, value)
|
||||||
VALUES ('homeowner', 'question-1', -1)`); err == nil {
|
VALUES ('homeowner', 'question-1', -1)`); err == nil {
|
||||||
@@ -276,6 +288,39 @@ INSERT INTO posts (
|
|||||||
roots[0].UserVote != 1 {
|
roots[0].UserVote != 1 {
|
||||||
t.Fatalf("root annotations = %+v", roots)
|
t.Fatalf("root annotations = %+v", roots)
|
||||||
}
|
}
|
||||||
|
summary, err := queries.GetRootPostVoteSummary(ctx, sqlc.GetRootPostVoteSummaryParams{
|
||||||
|
ViewerID: "plumber",
|
||||||
|
RootID: "question-1",
|
||||||
|
})
|
||||||
|
if err != nil || summary.Score != 2 || summary.UserVote != 1 {
|
||||||
|
t.Fatalf("root vote summary = %+v, %v", summary, err)
|
||||||
|
}
|
||||||
|
byAuthor, err := queries.ListRootPostsByAuthor(ctx, sqlc.ListRootPostsByAuthorParams{
|
||||||
|
AuthorID: "homeowner",
|
||||||
|
HiddenState: string(PostStateHidden),
|
||||||
|
RowLimit: 50,
|
||||||
|
})
|
||||||
|
if err != nil || len(byAuthor) != 1 || byAuthor[0].ID != "question-1" {
|
||||||
|
t.Fatalf("roots by author = %+v, %v", byAuthor, err)
|
||||||
|
}
|
||||||
|
answeredBy, err := queries.ListRootPostsAnsweredBy(ctx, sqlc.ListRootPostsAnsweredByParams{
|
||||||
|
HiddenState: string(PostStateHidden),
|
||||||
|
AdminID: "plumber",
|
||||||
|
RowLimit: 50,
|
||||||
|
})
|
||||||
|
if err != nil || len(answeredBy) != 1 || answeredBy[0].ID != "question-1" {
|
||||||
|
t.Fatalf("roots answered by admin = %+v, %v", answeredBy, err)
|
||||||
|
}
|
||||||
|
for _, state := range []PostState{PostStateLocked, PostStateVisible} {
|
||||||
|
n, err := queries.UpdateRootPostState(ctx, sqlc.UpdateRootPostStateParams{
|
||||||
|
PostState: string(state),
|
||||||
|
UpdatedAt: "2026-08-26T10:10:00Z",
|
||||||
|
ID: "question-1",
|
||||||
|
})
|
||||||
|
if err != nil || n != 1 {
|
||||||
|
t.Fatalf("set root state %q rows=%d error=%v", state, n, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if _, err := conn.ExecContext(ctx, `
|
if _, err := conn.ExecContext(ctx, `
|
||||||
DROP INDEX idx_posts_root_date;
|
DROP INDEX idx_posts_root_date;
|
||||||
@@ -413,7 +458,7 @@ WHERE schemaname = current_schema()
|
|||||||
func TestMigratePostsReportsStep(t *testing.T) {
|
func TestMigratePostsReportsStep(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
exec := &failingMigrationExec{failAt: 5}
|
exec := &failingMigrationExec{failAt: 6}
|
||||||
err := migratePosts(context.Background(), exec)
|
err := migratePosts(context.Background(), exec)
|
||||||
if err == nil || !strings.Contains(err.Error(), "copy questions") {
|
if err == nil || !strings.Contains(err.Error(), "copy questions") {
|
||||||
t.Fatalf("error = %v, want copy questions context", err)
|
t.Fatalf("error = %v, want copy questions context", err)
|
||||||
|
|||||||
@@ -258,6 +258,39 @@ func GetPostThread(ctx context.Context, db *sql.DB, rootID string) (*Post, error
|
|||||||
return buildPostTree(posts, rootID)
|
return buildPostTree(posts, rootID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetPostThreadForViewer includes root voting and answered annotations.
|
||||||
|
func GetPostThreadForViewer(
|
||||||
|
ctx context.Context,
|
||||||
|
db *sql.DB,
|
||||||
|
rootID string,
|
||||||
|
viewerID string,
|
||||||
|
) (*Post, error) {
|
||||||
|
root, err := GetPostThread(ctx, db, rootID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
summary, err := sqlc.New(db).GetRootPostVoteSummary(ctx, sqlc.GetRootPostVoteSummaryParams{
|
||||||
|
ViewerID: viewerID,
|
||||||
|
RootID: rootID,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
root.Score = int(summary.Score)
|
||||||
|
root.UserVote = int(summary.UserVote)
|
||||||
|
root.Answered = postTreeContainsRole(root, RoleAdmin)
|
||||||
|
return root, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func postTreeContainsRole(post *Post, role Role) bool {
|
||||||
|
for _, reply := range post.Replies {
|
||||||
|
if reply.AuthorRole == role || postTreeContainsRole(reply, role) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func buildPostTree(posts []Post, rootID string) (*Post, error) {
|
func buildPostTree(posts []Post, rootID string) (*Post, error) {
|
||||||
byID := make(map[string]*Post, len(posts))
|
byID := make(map[string]*Post, len(posts))
|
||||||
for i := range posts {
|
for i := range posts {
|
||||||
@@ -334,6 +367,89 @@ func ListRootPosts(ctx context.Context, db *sql.DB, postDate, viewerID string) (
|
|||||||
return posts, nil
|
return posts, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListRootPostsByAuthor returns visible roots created by an author, newest first.
|
||||||
|
func ListRootPostsByAuthor(ctx context.Context, db *sql.DB, authorID string) ([]Post, error) {
|
||||||
|
rows, err := sqlc.New(db).ListRootPostsByAuthor(ctx, sqlc.ListRootPostsByAuthorParams{
|
||||||
|
AuthorID: authorID,
|
||||||
|
HiddenState: string(PostStateHidden),
|
||||||
|
RowLimit: ProfileListLimit,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
posts := make([]Post, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
posts = append(posts, postFromValues(
|
||||||
|
db,
|
||||||
|
r.ID,
|
||||||
|
r.ParentID,
|
||||||
|
r.AuthorID,
|
||||||
|
r.AuthorName,
|
||||||
|
r.AuthorRole,
|
||||||
|
r.Title,
|
||||||
|
r.Body,
|
||||||
|
r.City,
|
||||||
|
r.PostDate,
|
||||||
|
r.PostState,
|
||||||
|
r.CreatedAt,
|
||||||
|
r.UpdatedAt,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
return posts, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListRootPostsAnsweredBy returns visible roots containing a reply by adminID.
|
||||||
|
func ListRootPostsAnsweredBy(ctx context.Context, db *sql.DB, adminID string) ([]Post, error) {
|
||||||
|
rows, err := sqlc.New(db).ListRootPostsAnsweredBy(ctx, sqlc.ListRootPostsAnsweredByParams{
|
||||||
|
HiddenState: string(PostStateHidden),
|
||||||
|
AdminID: adminID,
|
||||||
|
RowLimit: ProfileListLimit,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
posts := make([]Post, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
posts = append(posts, postFromValues(
|
||||||
|
db,
|
||||||
|
r.ID,
|
||||||
|
r.ParentID,
|
||||||
|
r.AuthorID,
|
||||||
|
r.AuthorName,
|
||||||
|
r.AuthorRole,
|
||||||
|
r.Title,
|
||||||
|
r.Body,
|
||||||
|
r.City,
|
||||||
|
r.PostDate,
|
||||||
|
r.PostState,
|
||||||
|
r.CreatedAt,
|
||||||
|
r.UpdatedAt,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
return posts, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetRootPostState changes a root post's state.
|
||||||
|
func SetRootPostState(ctx context.Context, db *sql.DB, id string, state PostState) error {
|
||||||
|
switch state {
|
||||||
|
case PostStateVisible, PostStateHidden, PostStateLocked:
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("%w: invalid post state", ErrInvalidPost)
|
||||||
|
}
|
||||||
|
n, err := sqlc.New(db).UpdateRootPostState(ctx, sqlc.UpdateRootPostStateParams{
|
||||||
|
PostState: string(state),
|
||||||
|
UpdatedAt: time.Now().UTC().Format(time.RFC3339Nano),
|
||||||
|
ID: id,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
return sql.ErrNoRows
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// SetPostVote sets value to 1, -1, or 0 on a visible root post.
|
// SetPostVote sets value to 1, -1, or 0 on a visible root post.
|
||||||
func SetPostVote(ctx context.Context, db *sql.DB, userID, postID string, value int) error {
|
func SetPostVote(ctx context.Context, db *sql.DB, userID, postID string, value int) error {
|
||||||
if value != 1 && value != -1 && value != 0 {
|
if value != 1 && value != -1 && value != 0 {
|
||||||
|
|||||||
@@ -141,6 +141,26 @@ func TestMemoryPostLifecycle(t *testing.T) {
|
|||||||
if err := mem.VotePost(ctx, voter.ID, later.ID, 1); !errors.Is(err, ErrPostNotVotable) {
|
if err := mem.VotePost(ctx, voter.ID, later.ID, 1); !errors.Is(err, ErrPostNotVotable) {
|
||||||
t.Fatalf("reply vote error = %v", err)
|
t.Fatalf("reply vote error = %v", err)
|
||||||
}
|
}
|
||||||
|
byAuthor, err := mem.ListRootPostsByAuthor(ctx, homeowner.ID)
|
||||||
|
if err != nil || len(byAuthor) != 1 || byAuthor[0].ID != root.ID {
|
||||||
|
t.Fatalf("roots by author = %+v, %v", byAuthor, err)
|
||||||
|
}
|
||||||
|
answeredBy, err := mem.ListRootPostsAnsweredBy(ctx, plumber.ID)
|
||||||
|
if err != nil || len(answeredBy) != 1 || answeredBy[0].ID != root.ID {
|
||||||
|
t.Fatalf("roots answered by admin = %+v, %v", answeredBy, err)
|
||||||
|
}
|
||||||
|
if err := mem.SetRootPostState(ctx, later.ID, PostStateHidden); !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
t.Fatalf("reply state error = %v, want sql.ErrNoRows", err)
|
||||||
|
}
|
||||||
|
if err := mem.SetRootPostState(ctx, root.ID, PostStateHidden); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if roots, err := mem.ListRootPostsByAuthor(ctx, homeowner.ID); err != nil || len(roots) != 0 {
|
||||||
|
t.Fatalf("hidden author roots = %+v, %v", roots, err)
|
||||||
|
}
|
||||||
|
if roots, err := mem.ListRootPostsAnsweredBy(ctx, plumber.ID); err != nil || len(roots) != 0 {
|
||||||
|
t.Fatalf("hidden answered roots = %+v, %v", roots, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMemoryPostValidation(t *testing.T) {
|
func TestMemoryPostValidation(t *testing.T) {
|
||||||
|
|||||||
@@ -157,6 +157,10 @@ func (p *Postgres) GetPostThread(ctx context.Context, rootID string) (*Post, err
|
|||||||
return GetPostThread(ctx, p.db, rootID)
|
return GetPostThread(ctx, p.db, rootID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (p *Postgres) GetPostThreadForViewer(ctx context.Context, rootID, viewerID string) (*Post, error) {
|
||||||
|
return GetPostThreadForViewer(ctx, p.db, rootID, viewerID)
|
||||||
|
}
|
||||||
|
|
||||||
func (p *Postgres) UpdatePost(ctx context.Context, post *Post) error {
|
func (p *Postgres) UpdatePost(ctx context.Context, post *Post) error {
|
||||||
post.db = p.db
|
post.db = p.db
|
||||||
return post.Update(ctx)
|
return post.Update(ctx)
|
||||||
@@ -166,6 +170,18 @@ func (p *Postgres) ListRootPosts(ctx context.Context, postDate, viewerID string)
|
|||||||
return ListRootPosts(ctx, p.db, postDate, viewerID)
|
return ListRootPosts(ctx, p.db, postDate, viewerID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (p *Postgres) ListRootPostsByAuthor(ctx context.Context, authorID string) ([]Post, error) {
|
||||||
|
return ListRootPostsByAuthor(ctx, p.db, authorID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Postgres) ListRootPostsAnsweredBy(ctx context.Context, adminID string) ([]Post, error) {
|
||||||
|
return ListRootPostsAnsweredBy(ctx, p.db, adminID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Postgres) SetRootPostState(ctx context.Context, id string, state PostState) error {
|
||||||
|
return SetRootPostState(ctx, p.db, id, state)
|
||||||
|
}
|
||||||
|
|
||||||
func (p *Postgres) VotePost(ctx context.Context, userID, postID string, value int) error {
|
func (p *Postgres) VotePost(ctx context.Context, userID, postID string, value int) error {
|
||||||
return SetPostVote(ctx, p.db, userID, postID, value)
|
return SetPostVote(ctx, p.db, userID, postID, value)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -117,6 +117,34 @@ func (q *Queries) GetPost(ctx context.Context, id string) (GetPostRow, error) {
|
|||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const getRootPostVoteSummary = `-- name: GetRootPostVoteSummary :one
|
||||||
|
SELECT
|
||||||
|
COALESCE(SUM(value), 0)::bigint AS score,
|
||||||
|
COALESCE(
|
||||||
|
MAX(value) FILTER (WHERE user_id = $1),
|
||||||
|
0
|
||||||
|
)::bigint AS user_vote
|
||||||
|
FROM post_votes
|
||||||
|
WHERE post_id = $2
|
||||||
|
`
|
||||||
|
|
||||||
|
type GetRootPostVoteSummaryParams struct {
|
||||||
|
ViewerID string
|
||||||
|
RootID string
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetRootPostVoteSummaryRow struct {
|
||||||
|
Score int64
|
||||||
|
UserVote int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) GetRootPostVoteSummary(ctx context.Context, arg GetRootPostVoteSummaryParams) (GetRootPostVoteSummaryRow, error) {
|
||||||
|
row := q.db.QueryRowContext(ctx, getRootPostVoteSummary, arg.ViewerID, arg.RootID)
|
||||||
|
var i GetRootPostVoteSummaryRow
|
||||||
|
err := row.Scan(&i.Score, &i.UserVote)
|
||||||
|
return i, err
|
||||||
|
}
|
||||||
|
|
||||||
const listPostThread = `-- name: ListPostThread :many
|
const listPostThread = `-- name: ListPostThread :many
|
||||||
WITH RECURSIVE thread AS (
|
WITH RECURSIVE thread AS (
|
||||||
SELECT p.id, p.parent_id, p.author_id, p.title, p.body, p.city, p.post_date, p.post_state, p.created_at, p.updated_at
|
SELECT p.id, p.parent_id, p.author_id, p.title, p.body, p.city, p.post_date, p.post_state, p.created_at, p.updated_at
|
||||||
@@ -309,6 +337,162 @@ func (q *Queries) ListRootPosts(ctx context.Context, arg ListRootPostsParams) ([
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const listRootPostsAnsweredBy = `-- name: ListRootPostsAnsweredBy :many
|
||||||
|
WITH RECURSIVE ancestors AS (
|
||||||
|
SELECT p.id, p.parent_id
|
||||||
|
FROM posts p
|
||||||
|
WHERE p.author_id = $3
|
||||||
|
AND p.parent_id IS NOT NULL
|
||||||
|
|
||||||
|
UNION
|
||||||
|
|
||||||
|
SELECT parent.id, parent.parent_id
|
||||||
|
FROM posts parent
|
||||||
|
JOIN ancestors child ON child.parent_id = parent.id
|
||||||
|
)
|
||||||
|
SELECT DISTINCT
|
||||||
|
root.id, root.parent_id, root.author_id,
|
||||||
|
u.name AS author_name, u.role AS author_role,
|
||||||
|
root.title, root.body, root.city, root.post_date,
|
||||||
|
root.post_state, root.created_at, root.updated_at
|
||||||
|
FROM posts root
|
||||||
|
JOIN ancestors ON ancestors.id = root.id
|
||||||
|
JOIN users u ON u.id = root.author_id
|
||||||
|
WHERE root.parent_id IS NULL
|
||||||
|
AND root.post_state <> $1
|
||||||
|
ORDER BY root.created_at DESC, root.id DESC
|
||||||
|
LIMIT $2
|
||||||
|
`
|
||||||
|
|
||||||
|
type ListRootPostsAnsweredByParams struct {
|
||||||
|
HiddenState string
|
||||||
|
RowLimit int32
|
||||||
|
AdminID string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListRootPostsAnsweredByRow struct {
|
||||||
|
ID string
|
||||||
|
ParentID sql.NullString
|
||||||
|
AuthorID string
|
||||||
|
AuthorName string
|
||||||
|
AuthorRole string
|
||||||
|
Title string
|
||||||
|
Body string
|
||||||
|
City string
|
||||||
|
PostDate string
|
||||||
|
PostState string
|
||||||
|
CreatedAt string
|
||||||
|
UpdatedAt string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) ListRootPostsAnsweredBy(ctx context.Context, arg ListRootPostsAnsweredByParams) ([]ListRootPostsAnsweredByRow, error) {
|
||||||
|
rows, err := q.db.QueryContext(ctx, listRootPostsAnsweredBy, arg.HiddenState, arg.RowLimit, arg.AdminID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
items := []ListRootPostsAnsweredByRow{}
|
||||||
|
for rows.Next() {
|
||||||
|
var i ListRootPostsAnsweredByRow
|
||||||
|
if err := rows.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.ParentID,
|
||||||
|
&i.AuthorID,
|
||||||
|
&i.AuthorName,
|
||||||
|
&i.AuthorRole,
|
||||||
|
&i.Title,
|
||||||
|
&i.Body,
|
||||||
|
&i.City,
|
||||||
|
&i.PostDate,
|
||||||
|
&i.PostState,
|
||||||
|
&i.CreatedAt,
|
||||||
|
&i.UpdatedAt,
|
||||||
|
); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Close(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
const listRootPostsByAuthor = `-- name: ListRootPostsByAuthor :many
|
||||||
|
SELECT
|
||||||
|
p.id, p.parent_id, p.author_id,
|
||||||
|
u.name AS author_name, u.role AS author_role,
|
||||||
|
p.title, p.body, p.city, p.post_date,
|
||||||
|
p.post_state, p.created_at, p.updated_at
|
||||||
|
FROM posts p
|
||||||
|
JOIN users u ON u.id = p.author_id
|
||||||
|
WHERE p.parent_id IS NULL
|
||||||
|
AND p.author_id = $1
|
||||||
|
AND p.post_state <> $2
|
||||||
|
ORDER BY p.created_at DESC, p.id DESC
|
||||||
|
LIMIT $3
|
||||||
|
`
|
||||||
|
|
||||||
|
type ListRootPostsByAuthorParams struct {
|
||||||
|
AuthorID string
|
||||||
|
HiddenState string
|
||||||
|
RowLimit int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListRootPostsByAuthorRow struct {
|
||||||
|
ID string
|
||||||
|
ParentID sql.NullString
|
||||||
|
AuthorID string
|
||||||
|
AuthorName string
|
||||||
|
AuthorRole string
|
||||||
|
Title string
|
||||||
|
Body string
|
||||||
|
City string
|
||||||
|
PostDate string
|
||||||
|
PostState string
|
||||||
|
CreatedAt string
|
||||||
|
UpdatedAt string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) ListRootPostsByAuthor(ctx context.Context, arg ListRootPostsByAuthorParams) ([]ListRootPostsByAuthorRow, error) {
|
||||||
|
rows, err := q.db.QueryContext(ctx, listRootPostsByAuthor, arg.AuthorID, arg.HiddenState, arg.RowLimit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
items := []ListRootPostsByAuthorRow{}
|
||||||
|
for rows.Next() {
|
||||||
|
var i ListRootPostsByAuthorRow
|
||||||
|
if err := rows.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.ParentID,
|
||||||
|
&i.AuthorID,
|
||||||
|
&i.AuthorName,
|
||||||
|
&i.AuthorRole,
|
||||||
|
&i.Title,
|
||||||
|
&i.Body,
|
||||||
|
&i.City,
|
||||||
|
&i.PostDate,
|
||||||
|
&i.PostState,
|
||||||
|
&i.CreatedAt,
|
||||||
|
&i.UpdatedAt,
|
||||||
|
); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Close(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
const postIsVisibleRoot = `-- name: PostIsVisibleRoot :one
|
const postIsVisibleRoot = `-- name: PostIsVisibleRoot :one
|
||||||
SELECT EXISTS(
|
SELECT EXISTS(
|
||||||
SELECT 1
|
SELECT 1
|
||||||
@@ -353,6 +537,29 @@ func (q *Queries) UpdatePost(ctx context.Context, arg UpdatePostParams) (int64,
|
|||||||
return result.RowsAffected()
|
return result.RowsAffected()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const updateRootPostState = `-- name: UpdateRootPostState :execrows
|
||||||
|
UPDATE posts
|
||||||
|
SET
|
||||||
|
post_state = $1,
|
||||||
|
updated_at = $2
|
||||||
|
WHERE id = $3
|
||||||
|
AND parent_id IS NULL
|
||||||
|
`
|
||||||
|
|
||||||
|
type UpdateRootPostStateParams struct {
|
||||||
|
PostState string
|
||||||
|
UpdatedAt string
|
||||||
|
ID string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) UpdateRootPostState(ctx context.Context, arg UpdateRootPostStateParams) (int64, error) {
|
||||||
|
result, err := q.db.ExecContext(ctx, updateRootPostState, arg.PostState, arg.UpdatedAt, arg.ID)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return result.RowsAffected()
|
||||||
|
}
|
||||||
|
|
||||||
const upsertPostVoteOnVisibleRoot = `-- name: UpsertPostVoteOnVisibleRoot :execrows
|
const upsertPostVoteOnVisibleRoot = `-- name: UpsertPostVoteOnVisibleRoot :execrows
|
||||||
INSERT INTO post_votes (user_id, post_id, value)
|
INSERT INTO post_votes (user_id, post_id, value)
|
||||||
SELECT $1, $2, $3
|
SELECT $1, $2, $3
|
||||||
|
|||||||
@@ -40,8 +40,12 @@ type Store interface {
|
|||||||
CreatePost(ctx context.Context, post *Post) error
|
CreatePost(ctx context.Context, post *Post) error
|
||||||
GetPost(ctx context.Context, id string) (*Post, error)
|
GetPost(ctx context.Context, id string) (*Post, error)
|
||||||
GetPostThread(ctx context.Context, rootID string) (*Post, error)
|
GetPostThread(ctx context.Context, rootID string) (*Post, error)
|
||||||
|
GetPostThreadForViewer(ctx context.Context, rootID, viewerID string) (*Post, error)
|
||||||
UpdatePost(ctx context.Context, post *Post) error
|
UpdatePost(ctx context.Context, post *Post) error
|
||||||
ListRootPosts(ctx context.Context, postDate, viewerID string) ([]Post, error)
|
ListRootPosts(ctx context.Context, postDate, viewerID string) ([]Post, error)
|
||||||
|
ListRootPostsByAuthor(ctx context.Context, authorID string) ([]Post, error)
|
||||||
|
ListRootPostsAnsweredBy(ctx context.Context, adminID string) ([]Post, error)
|
||||||
|
SetRootPostState(ctx context.Context, id string, state PostState) error
|
||||||
VotePost(ctx context.Context, userID, postID string, value int) error
|
VotePost(ctx context.Context, userID, postID string, value int) error
|
||||||
|
|
||||||
// Vote sets the vote to 1, -1, or 0 (clear) on a visible question.
|
// Vote sets the vote to 1, -1, or 0 (clear) on a visible question.
|
||||||
|
|||||||
+40
-1
@@ -59,7 +59,7 @@ func (s *Server) handleCreatePost(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if !user.Admin() && user.ID != threadRoot.AuthorID {
|
if !canReplyToThread(user, threadRoot) {
|
||||||
http.Error(w, "forbidden", http.StatusForbidden)
|
http.Error(w, "forbidden", http.StatusForbidden)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -175,3 +175,42 @@ func canEditPost(user *store.User, post *store.Post) bool {
|
|||||||
}
|
}
|
||||||
return user.ID == post.AuthorID
|
return user.ID == post.AuthorID
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func canReplyToThread(user *store.User, root *store.Post) bool {
|
||||||
|
return user != nil &&
|
||||||
|
root != nil &&
|
||||||
|
root.PostState != store.PostStateHidden &&
|
||||||
|
(user.Admin() || user.ID == root.AuthorID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func postLabel(post *store.Post) string {
|
||||||
|
if post == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if post.ParentID == nil {
|
||||||
|
return "Question"
|
||||||
|
}
|
||||||
|
if post.AuthorRole == store.RoleAdmin {
|
||||||
|
return "Shop response"
|
||||||
|
}
|
||||||
|
return "Homeowner"
|
||||||
|
}
|
||||||
|
|
||||||
|
func postDepthClass(depth int) string {
|
||||||
|
switch depth {
|
||||||
|
case 0:
|
||||||
|
return "root"
|
||||||
|
case 1:
|
||||||
|
return "branch"
|
||||||
|
default:
|
||||||
|
return "deep"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func postPointers(posts []store.Post) []*store.Post {
|
||||||
|
out := make([]*store.Post, len(posts))
|
||||||
|
for i := range posts {
|
||||||
|
out[i] = &posts[i]
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|||||||
@@ -258,6 +258,93 @@ func TestEditPostRoutePermissions(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestQuestionPageRendersNestedPostControls(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
srv, mem := newTestServer(t, Config{})
|
||||||
|
handler := srv.Handler()
|
||||||
|
homeowner := seedUser(t, mem, uniq("homeowner"), "hunter22", store.RoleUser)
|
||||||
|
admin := seedUser(t, mem, uniq("admin"), "hunter22", store.RoleAdmin)
|
||||||
|
homeownerCookies := loginUser(t, handler, homeowner.Username, "hunter22")
|
||||||
|
adminCookies := loginUser(t, handler, admin.Username, "hunter22")
|
||||||
|
|
||||||
|
root := &store.Post{
|
||||||
|
AuthorID: homeowner.ID,
|
||||||
|
Title: "Leaky sink",
|
||||||
|
Body: "Water under the cabinet.",
|
||||||
|
City: "Oakland",
|
||||||
|
PostDate: pacific.Today(),
|
||||||
|
}
|
||||||
|
if err := mem.CreatePost(context.Background(), root); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
homeownerReply := &store.Post{
|
||||||
|
ParentID: &root.ID,
|
||||||
|
AuthorID: homeowner.ID,
|
||||||
|
Body: "The model number is 123.",
|
||||||
|
}
|
||||||
|
if err := mem.CreatePost(context.Background(), homeownerReply); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
adminReply := &store.Post{
|
||||||
|
ParentID: &homeownerReply.ID,
|
||||||
|
AuthorID: admin.ID,
|
||||||
|
Body: "Replace the cartridge.",
|
||||||
|
}
|
||||||
|
if err := mem.CreatePost(context.Background(), adminReply); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
homeownerReply.Body = "The model number is 123A."
|
||||||
|
if err := mem.UpdatePost(context.Background(), homeownerReply); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/questions/"+root.ID, nil)
|
||||||
|
for _, cookie := range homeownerCookies {
|
||||||
|
req.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
handler.ServeHTTP(rec, req)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("question page status = %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
body := rec.Body.String()
|
||||||
|
for _, want := range []string{
|
||||||
|
`id="post-` + root.ID + `"`,
|
||||||
|
`id="post-` + homeownerReply.ID + `"`,
|
||||||
|
`id="post-` + adminReply.ID + `"`,
|
||||||
|
`class="thread-post thread-post-branch`,
|
||||||
|
`class="thread-post thread-post-deep is-shop"`,
|
||||||
|
"Homeowner",
|
||||||
|
"Shop response",
|
||||||
|
"Edited",
|
||||||
|
`action="/posts"`,
|
||||||
|
`action="/posts/` + root.ID + `/edit"`,
|
||||||
|
`action="/posts/` + homeownerReply.ID + `/edit"`,
|
||||||
|
`>The model number is 123A.</textarea>`,
|
||||||
|
`removeAttribute('open')`,
|
||||||
|
} {
|
||||||
|
if !strings.Contains(body, want) {
|
||||||
|
t.Fatalf("question page missing %q: %s", want, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(body, `action="/posts/`+adminReply.ID+`/edit"`) {
|
||||||
|
t.Fatalf("homeowner can edit admin reply: %s", body)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/questions/"+root.ID, nil)
|
||||||
|
for _, cookie := range adminCookies {
|
||||||
|
req.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
handler.ServeHTTP(rec, req)
|
||||||
|
if rec.Code != http.StatusOK ||
|
||||||
|
!strings.Contains(rec.Body.String(), `action="/posts/`+adminReply.ID+`/edit"`) ||
|
||||||
|
strings.Contains(rec.Body.String(), `action="/posts/`+root.ID+`/edit"`) {
|
||||||
|
t.Fatalf("admin edit controls are incorrect: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func csrfForCookies(t *testing.T, handler http.Handler, cookies []*http.Cookie) string {
|
func csrfForCookies(t *testing.T, handler http.Handler, cookies []*http.Cookie) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
req := httptest.NewRequest(http.MethodGet, "/submit", nil)
|
req := httptest.NewRequest(http.MethodGet, "/submit", nil)
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ import (
|
|||||||
type profilePage struct {
|
type profilePage struct {
|
||||||
page
|
page
|
||||||
States []struct{ Code, Name string }
|
States []struct{ Code, Name string }
|
||||||
Questions []store.RankedQuestion
|
Posts []store.Post
|
||||||
QuestionsLabel string
|
QuestionsLabel string
|
||||||
UploadsEnabled bool
|
UploadsEnabled bool
|
||||||
Error string
|
Error string
|
||||||
@@ -255,16 +255,16 @@ func fitAvatar(img image.Image, maxDim int) image.Image {
|
|||||||
|
|
||||||
func (s *Server) renderProfile(w http.ResponseWriter, r *http.Request, u *store.User, errMsg, stateVal, emailVal string) {
|
func (s *Server) renderProfile(w http.ResponseWriter, r *http.Request, u *store.User, errMsg, stateVal, emailVal string) {
|
||||||
var (
|
var (
|
||||||
questions []store.RankedQuestion
|
posts []store.Post
|
||||||
label string
|
label string
|
||||||
err error
|
err error
|
||||||
)
|
)
|
||||||
if u.Admin() {
|
if u.Admin() {
|
||||||
label = "Questions you answered"
|
label = "Questions you answered"
|
||||||
questions, err = s.store.ListQuestionsAnsweredBy(r.Context(), u.ID)
|
posts, err = s.store.ListRootPostsAnsweredBy(r.Context(), u.ID)
|
||||||
} else {
|
} else {
|
||||||
label = "Your questions"
|
label = "Your questions"
|
||||||
questions, err = s.store.ListQuestionsByAuthor(r.Context(), u.ID)
|
posts, err = s.store.ListRootPostsByAuthor(r.Context(), u.ID)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "could not load questions", http.StatusInternalServerError)
|
http.Error(w, "could not load questions", http.StatusInternalServerError)
|
||||||
@@ -275,7 +275,7 @@ func (s *Server) renderProfile(w http.ResponseWriter, r *http.Request, u *store.
|
|||||||
s.exec(w, "profile", profilePage{
|
s.exec(w, "profile", profilePage{
|
||||||
page: p,
|
page: p,
|
||||||
States: geo.States,
|
States: geo.States,
|
||||||
Questions: questions,
|
Posts: posts,
|
||||||
QuestionsLabel: label,
|
QuestionsLabel: label,
|
||||||
UploadsEnabled: s.cfg.Blob.Enabled(),
|
UploadsEnabled: s.cfg.Blob.Enabled(),
|
||||||
Error: errMsg,
|
Error: errMsg,
|
||||||
|
|||||||
+71
-103
@@ -3,7 +3,6 @@ package web
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"database/sql"
|
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -64,13 +63,12 @@ type huntPage struct {
|
|||||||
Label string
|
Label string
|
||||||
IsToday bool
|
IsToday bool
|
||||||
IsYesterday bool
|
IsYesterday bool
|
||||||
Questions []store.RankedQuestion
|
Posts []*store.Post
|
||||||
}
|
}
|
||||||
|
|
||||||
type questionPage struct {
|
type questionPage struct {
|
||||||
page
|
page
|
||||||
Question *store.RankedQuestion
|
Question *store.Post
|
||||||
Answer *store.Answer
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type submitPage struct {
|
type submitPage struct {
|
||||||
@@ -90,11 +88,19 @@ type authPage struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type voteCtx struct {
|
type voteCtx struct {
|
||||||
User *store.User
|
User *store.User
|
||||||
CSRF string
|
CSRF string
|
||||||
View string
|
View string
|
||||||
Date string
|
Date string
|
||||||
Question store.RankedQuestion
|
Post *store.Post
|
||||||
|
}
|
||||||
|
|
||||||
|
type threadPostCtx struct {
|
||||||
|
User *store.User
|
||||||
|
CSRF string
|
||||||
|
Root *store.Post
|
||||||
|
Post *store.Post
|
||||||
|
Depth int
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(st store.Store, sessionStore scs.Store, templateFS fs.FS, staticFS fs.FS, cfg Config) (*Server, error) {
|
func New(st store.Store, sessionStore scs.Store, templateFS fs.FS, staticFS fs.FS, cfg Config) (*Server, error) {
|
||||||
@@ -105,12 +111,27 @@ func New(st store.Store, sessionStore scs.Store, templateFS fs.FS, staticFS fs.F
|
|||||||
cfg.Mail = mail.Nop{}
|
cfg.Mail = mail.Nop{}
|
||||||
}
|
}
|
||||||
funcMap := template.FuncMap{
|
funcMap := template.FuncMap{
|
||||||
"voteCtx": func(user *store.User, csrf, view, date string, q store.RankedQuestion) voteCtx {
|
"voteCtx": func(user *store.User, csrf, view, date string, post *store.Post) voteCtx {
|
||||||
return voteCtx{User: user, CSRF: csrf, View: view, Date: date, Question: q}
|
return voteCtx{User: user, CSRF: csrf, View: view, Date: date, Post: post}
|
||||||
|
},
|
||||||
|
"postCtx": func(user *store.User, csrf string, root, post *store.Post, depth int) threadPostCtx {
|
||||||
|
return threadPostCtx{User: user, CSRF: csrf, Root: root, Post: post, Depth: depth}
|
||||||
|
},
|
||||||
|
"add": func(a, b int) int { return a + b },
|
||||||
|
"rank": func(i int) int { return i + 1 },
|
||||||
|
"isAdmin": func(u *store.User) bool { return u.Admin() },
|
||||||
|
"canReply": canReplyToThread,
|
||||||
|
"canEditPost": canEditPost,
|
||||||
|
"postLabel": postLabel,
|
||||||
|
"postDepth": postDepthClass,
|
||||||
|
"isEdited": func(post *store.Post) bool { return post != nil && post.UpdatedAt != post.CreatedAt },
|
||||||
|
"postTime": func(value string) string {
|
||||||
|
t, err := time.Parse(time.RFC3339Nano, value)
|
||||||
|
if err != nil {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
return t.In(pacific.Loc).Format("Jan 2, 2006 · 3:04 PM")
|
||||||
},
|
},
|
||||||
"add": func(a, b int) int { return a + b },
|
|
||||||
"rank": func(i int) int { return i + 1 },
|
|
||||||
"isAdmin": func(u *store.User) bool { return u.Admin() },
|
|
||||||
"pacificLabel": pacific.Label,
|
"pacificLabel": pacific.Label,
|
||||||
"locationTag": func(u *store.User) string {
|
"locationTag": func(u *store.User) string {
|
||||||
if u != nil {
|
if u != nil {
|
||||||
@@ -281,7 +302,7 @@ func (s *Server) renderHunt(w http.ResponseWriter, r *http.Request, date string)
|
|||||||
if u := currentUser(r); u != nil {
|
if u := currentUser(r); u != nil {
|
||||||
viewer = u.ID
|
viewer = u.ID
|
||||||
}
|
}
|
||||||
questions, err := s.store.ListHunt(r.Context(), date, viewer)
|
posts, err := s.store.ListRootPosts(r.Context(), date, viewer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "could not load questions", http.StatusInternalServerError)
|
http.Error(w, "could not load questions", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
@@ -297,7 +318,7 @@ func (s *Server) renderHunt(w http.ResponseWriter, r *http.Request, date string)
|
|||||||
Label: label,
|
Label: label,
|
||||||
IsToday: pacific.IsToday(date),
|
IsToday: pacific.IsToday(date),
|
||||||
IsYesterday: pacific.IsYesterday(date),
|
IsYesterday: pacific.IsYesterday(date),
|
||||||
Questions: questions,
|
Posts: postPointers(posts),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -341,17 +362,17 @@ func (s *Server) handleSubmit(w http.ResponseWriter, r *http.Request) {
|
|||||||
if len(city) > 80 {
|
if len(city) > 80 {
|
||||||
city = truncateRunes(city, 80)
|
city = truncateRunes(city, 80)
|
||||||
}
|
}
|
||||||
q := &store.RankedQuestion{
|
post := &store.Post{
|
||||||
AuthorID: u.ID,
|
AuthorID: u.ID,
|
||||||
Title: title,
|
Title: title,
|
||||||
Body: body,
|
Body: body,
|
||||||
City: city,
|
City: city,
|
||||||
}
|
}
|
||||||
if err := s.store.CreateQuestion(r.Context(), q); err != nil {
|
if err := s.store.CreatePost(r.Context(), post); err != nil {
|
||||||
http.Error(w, "could not save question", http.StatusInternalServerError)
|
http.Error(w, "could not save question", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
http.Redirect(w, r, "/questions/"+url.PathEscape(q.ID), http.StatusSeeOther)
|
http.Redirect(w, r, "/questions/"+url.PathEscape(post.ID), http.StatusSeeOther)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleQuestion(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleQuestion(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -360,29 +381,14 @@ func (s *Server) handleQuestion(w http.ResponseWriter, r *http.Request) {
|
|||||||
if u := currentUser(r); u != nil {
|
if u := currentUser(r); u != nil {
|
||||||
viewer = u.ID
|
viewer = u.ID
|
||||||
}
|
}
|
||||||
q, err := s.store.GetQuestion(r.Context(), id, viewer)
|
post, err := s.store.GetPostThreadForViewer(r.Context(), id, viewer)
|
||||||
if err != nil || (q.Hidden && !currentUser(r).Admin()) {
|
if err != nil || (post.PostState == store.PostStateHidden && !currentUser(r).Admin()) {
|
||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var ans *store.Answer
|
|
||||||
if q.Answered {
|
|
||||||
ans, err = s.store.GetAnswer(r.Context(), q.ID)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
|
||||||
log.Printf("question %s marked answered but answer missing", q.ID)
|
|
||||||
http.Error(w, "answer unavailable", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Printf("get answer %s: %v", q.ID, err)
|
|
||||||
http.Error(w, "could not load answer", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
s.exec(w, "question", questionPage{
|
s.exec(w, "question", questionPage{
|
||||||
page: s.basePage(r, q.Title),
|
page: s.basePage(r, post.Title),
|
||||||
Question: q,
|
Question: post,
|
||||||
Answer: ans,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -412,8 +418,8 @@ func (s *Server) handleVote(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.Error(w, "invalid vote", http.StatusBadRequest)
|
http.Error(w, "invalid vote", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := s.store.Vote(r.Context(), u.ID, id, value); err != nil {
|
if err := s.store.VotePost(r.Context(), u.ID, id, value); err != nil {
|
||||||
if errors.Is(err, store.ErrHiddenOrMissing) {
|
if errors.Is(err, store.ErrPostNotVotable) {
|
||||||
http.Error(w, "not found", http.StatusNotFound)
|
http.Error(w, "not found", http.StatusNotFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -427,17 +433,17 @@ func (s *Server) handleVote(w http.ResponseWriter, r *http.Request) {
|
|||||||
s.renderLeaderboard(w, r, date)
|
s.renderLeaderboard(w, r, date)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
q, err := s.store.GetQuestion(r.Context(), id, u.ID)
|
post, err := s.store.GetPostThreadForViewer(r.Context(), id, u.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "not found", http.StatusNotFound)
|
http.Error(w, "not found", http.StatusNotFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.exec(w, "vote", voteCtx{
|
s.exec(w, "vote", voteCtx{
|
||||||
User: u,
|
User: u,
|
||||||
CSRF: s.sessions.GetString(r.Context(), "csrf"),
|
CSRF: s.sessions.GetString(r.Context(), "csrf"),
|
||||||
View: "question",
|
View: "question",
|
||||||
Date: q.HuntDate,
|
Date: post.PostDate,
|
||||||
Question: *q,
|
Post: post,
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -460,15 +466,15 @@ func (s *Server) renderLeaderboard(w http.ResponseWriter, r *http.Request, date
|
|||||||
if u := currentUser(r); u != nil {
|
if u := currentUser(r); u != nil {
|
||||||
viewer = u.ID
|
viewer = u.ID
|
||||||
}
|
}
|
||||||
questions, err := s.store.ListHunt(r.Context(), date, viewer)
|
posts, err := s.store.ListRootPosts(r.Context(), date, viewer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "could not load questions", http.StatusInternalServerError)
|
http.Error(w, "could not load questions", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.exec(w, "leaderboard", huntPage{
|
s.exec(w, "leaderboard", huntPage{
|
||||||
page: s.basePage(r, ""),
|
page: s.basePage(r, ""),
|
||||||
Date: date,
|
Date: date,
|
||||||
Questions: questions,
|
Posts: postPointers(posts),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -490,65 +496,27 @@ func (s *Server) handleAnswer(w http.ResponseWriter, r *http.Request) {
|
|||||||
if len(body) > 12000 {
|
if len(body) > 12000 {
|
||||||
body = truncateRunes(body, 12000)
|
body = truncateRunes(body, 12000)
|
||||||
}
|
}
|
||||||
q, err := s.store.GetQuestion(r.Context(), id, u.ID)
|
root, err := s.store.GetPost(r.Context(), id)
|
||||||
if err != nil {
|
if err != nil || root.ParentID != nil || root.PostState == store.PostStateHidden {
|
||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_, priorErr := s.store.GetAnswer(r.Context(), id)
|
reply := &store.Post{
|
||||||
wasNew := errors.Is(priorErr, sql.ErrNoRows)
|
ParentID: &root.ID,
|
||||||
if priorErr != nil && !wasNew {
|
AuthorID: u.ID,
|
||||||
http.Error(w, "could not load answer", http.StatusInternalServerError)
|
Body: body,
|
||||||
return
|
|
||||||
}
|
}
|
||||||
ans := &store.Answer{
|
if err := s.store.CreatePost(r.Context(), reply); err != nil {
|
||||||
QuestionID: id,
|
|
||||||
AuthorID: u.ID,
|
|
||||||
Body: body,
|
|
||||||
}
|
|
||||||
if err := s.store.UpsertAnswer(r.Context(), ans); err != nil {
|
|
||||||
http.Error(w, "could not save answer", http.StatusInternalServerError)
|
http.Error(w, "could not save answer", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if wasNew {
|
location := "/questions/" + url.PathEscape(id) + "#post-" + url.PathEscape(reply.ID)
|
||||||
s.notifyQuestionAnswered(q, body, u.ID)
|
|
||||||
}
|
|
||||||
saved, err := s.store.GetAnswer(r.Context(), id)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "could not load answer", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if isHTMX(r) {
|
if isHTMX(r) {
|
||||||
s.exec(w, "answer", questionPage{page: s.basePage(r, ""), Answer: saved})
|
w.Header().Set("HX-Redirect", location)
|
||||||
|
w.WriteHeader(http.StatusSeeOther)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
http.Redirect(w, r, "/questions/"+url.PathEscape(id), http.StatusSeeOther)
|
http.Redirect(w, r, location, http.StatusSeeOther)
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) notifyQuestionAnswered(q *store.RankedQuestion, answerBody, adminID string) {
|
|
||||||
if q == nil || s.cfg.Mail == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
author, err := s.store.UserByID(context.Background(), q.AuthorID)
|
|
||||||
if err != nil || author == nil || author.Email == "" || author.ID == adminID {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
msg := mail.QuestionAnswered{
|
|
||||||
ToEmail: author.Email,
|
|
||||||
ToName: author.Name,
|
|
||||||
QuestionID: q.ID,
|
|
||||||
QuestionTitle: q.Title,
|
|
||||||
AnswerBody: answerBody,
|
|
||||||
}
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
if err := s.cfg.Mail.NotifyQuestionAnswered(ctx, msg); err != nil {
|
|
||||||
log.Printf("notify answer %s: %v", q.ID, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Printf("notify answer %s: accepted", q.ID)
|
|
||||||
}()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleHide(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleHide(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -561,17 +529,17 @@ func (s *Server) handleHide(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
id := chi.URLParam(r, "id")
|
id := chi.URLParam(r, "id")
|
||||||
q, err := s.store.GetQuestion(r.Context(), id, u.ID)
|
post, err := s.store.GetPost(r.Context(), id)
|
||||||
if err != nil {
|
if err != nil || post.ParentID != nil {
|
||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := s.store.HideQuestion(r.Context(), id); err != nil {
|
if err := s.store.SetRootPostState(r.Context(), id, store.PostStateHidden); err != nil {
|
||||||
http.Error(w, "could not hide", http.StatusInternalServerError)
|
http.Error(w, "could not hide", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if isHTMX(r) && r.PostFormValue("view") == "list" {
|
if isHTMX(r) && r.PostFormValue("view") == "list" {
|
||||||
s.renderLeaderboard(w, r, q.HuntDate)
|
s.renderLeaderboard(w, r, post.PostDate)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if isHTMX(r) {
|
if isHTMX(r) {
|
||||||
|
|||||||
+40
-133
@@ -19,7 +19,6 @@ import (
|
|||||||
|
|
||||||
"plumber"
|
"plumber"
|
||||||
"plumber/internal/blob"
|
"plumber/internal/blob"
|
||||||
"plumber/internal/mail"
|
|
||||||
"plumber/internal/pacific"
|
"plumber/internal/pacific"
|
||||||
"plumber/internal/store"
|
"plumber/internal/store"
|
||||||
)
|
)
|
||||||
@@ -417,21 +416,21 @@ func TestProfileAdminAnsweredListAndAvatarUpload(t *testing.T) {
|
|||||||
alice := seedUser(t, mem, aliceName, "hunter22", store.RoleUser)
|
alice := seedUser(t, mem, aliceName, "hunter22", store.RoleUser)
|
||||||
adminCookies := loginUser(t, h, hubName, "hunter22")
|
adminCookies := loginUser(t, h, hubName, "hunter22")
|
||||||
|
|
||||||
q := &store.RankedQuestion{
|
root := &store.Post{
|
||||||
AuthorID: alice.ID,
|
AuthorID: alice.ID,
|
||||||
Title: "Drip",
|
Title: "Drip",
|
||||||
Body: "Under sink",
|
Body: "Under sink",
|
||||||
City: "Oakland",
|
City: "Oakland",
|
||||||
}
|
}
|
||||||
if err := mem.CreateQuestion(context.Background(), q); err != nil {
|
if err := mem.CreatePost(context.Background(), root); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
ans := &store.Answer{
|
reply := &store.Post{
|
||||||
QuestionID: q.ID,
|
ParentID: &root.ID,
|
||||||
AuthorID: hub.ID,
|
AuthorID: hub.ID,
|
||||||
Body: "Replace the cartridge.",
|
Body: "Replace the cartridge.",
|
||||||
}
|
}
|
||||||
if err := mem.UpsertAnswer(context.Background(), ans); err != nil {
|
if err := mem.CreatePost(context.Background(), reply); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -493,14 +492,14 @@ func TestMutationsVoteAnswerHideAndCSRF(t *testing.T) {
|
|||||||
adminCookies := loginUser(t, h, adminName, "hunter22")
|
adminCookies := loginUser(t, h, adminName, "hunter22")
|
||||||
userCookies := loginUser(t, h, userName, "hunter22")
|
userCookies := loginUser(t, h, userName, "hunter22")
|
||||||
|
|
||||||
q := &store.RankedQuestion{
|
q := &store.Post{
|
||||||
AuthorID: user.ID,
|
AuthorID: user.ID,
|
||||||
Title: "Pipe noise",
|
Title: "Pipe noise",
|
||||||
Body: "Clanking",
|
Body: "Clanking",
|
||||||
City: "SF",
|
City: "SF",
|
||||||
HuntDate: pacific.Today(),
|
PostDate: pacific.Today(),
|
||||||
}
|
}
|
||||||
if err := mem.CreateQuestion(context.Background(), q); err != nil {
|
if err := mem.CreatePost(context.Background(), q); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -556,7 +555,7 @@ func TestMutationsVoteAnswerHideAndCSRF(t *testing.T) {
|
|||||||
if rec.Code != 200 {
|
if rec.Code != 200 {
|
||||||
t.Fatalf("vote htmx %d %s", rec.Code, rec.Body.String())
|
t.Fatalf("vote htmx %d %s", rec.Code, rec.Body.String())
|
||||||
}
|
}
|
||||||
got, err := mem.GetQuestion(context.Background(), q.ID, user.ID)
|
got, err := mem.GetPostThreadForViewer(context.Background(), q.ID, user.ID)
|
||||||
if err != nil || got.UserVote != 1 || got.Score != 1 {
|
if err != nil || got.UserVote != 1 || got.Score != 1 {
|
||||||
t.Fatalf("vote not applied: %+v %v", got, err)
|
t.Fatalf("vote not applied: %+v %v", got, err)
|
||||||
}
|
}
|
||||||
@@ -581,7 +580,7 @@ func TestMutationsVoteAnswerHideAndCSRF(t *testing.T) {
|
|||||||
t.Fatalf("non-admin answer want 403, got %d", rec.Code)
|
t.Fatalf("non-admin answer want 403, got %d", rec.Code)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Admin answer success (HTMX)
|
// Admin answer compatibility route creates a reply and redirects the thread.
|
||||||
rec = httptest.NewRecorder()
|
rec = httptest.NewRecorder()
|
||||||
req = httptest.NewRequest(http.MethodGet, "/questions/"+q.ID, nil)
|
req = httptest.NewRequest(http.MethodGet, "/questions/"+q.ID, nil)
|
||||||
for _, c := range adminCookies {
|
for _, c := range adminCookies {
|
||||||
@@ -598,22 +597,37 @@ func TestMutationsVoteAnswerHideAndCSRF(t *testing.T) {
|
|||||||
}
|
}
|
||||||
rec = httptest.NewRecorder()
|
rec = httptest.NewRecorder()
|
||||||
h.ServeHTTP(rec, req)
|
h.ServeHTTP(rec, req)
|
||||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Tighten the nuts") {
|
if rec.Code != http.StatusSeeOther {
|
||||||
t.Fatalf("admin answer: %d %s", rec.Code, rec.Body.String())
|
t.Fatalf("admin answer: %d %s", rec.Code, rec.Body.String())
|
||||||
}
|
}
|
||||||
if body := rec.Body.String(); !strings.Contains(body, `class="answer-editor"`) ||
|
thread, err := mem.GetPostThread(context.Background(), q.ID)
|
||||||
!strings.Contains(body, "<summary>Edit answer</summary>") ||
|
if err != nil || len(thread.Replies) != 1 {
|
||||||
|
t.Fatalf("admin reply missing: %+v %v", thread, err)
|
||||||
|
}
|
||||||
|
adminReply := thread.Replies[0]
|
||||||
|
if adminReply.AuthorID != admin.ID || adminReply.Body != "Tighten the nuts." {
|
||||||
|
t.Fatalf("unexpected admin reply: %+v", adminReply)
|
||||||
|
}
|
||||||
|
if got := rec.Header().Get("HX-Redirect"); got != "/questions/"+q.ID+"#post-"+adminReply.ID {
|
||||||
|
t.Fatalf("admin answer redirect = %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/questions/"+q.ID, nil)
|
||||||
|
for _, c := range adminCookies {
|
||||||
|
req.AddCookie(c)
|
||||||
|
}
|
||||||
|
h.ServeHTTP(rec, req)
|
||||||
|
if body := rec.Body.String(); !strings.Contains(body, "Tighten the nuts.") ||
|
||||||
|
!strings.Contains(body, "<summary>Edit</summary>") ||
|
||||||
!strings.Contains(body, ">Tighten the nuts.</textarea>") ||
|
!strings.Contains(body, ">Tighten the nuts.</textarea>") ||
|
||||||
!strings.Contains(body, `type="reset" class="btn btn-ghost"`) ||
|
!strings.Contains(body, `type="reset" class="btn btn-ghost"`) ||
|
||||||
!strings.Contains(body, `removeAttribute('open')`) ||
|
!strings.Contains(body, `removeAttribute('open')`) ||
|
||||||
strings.Contains(body, `<details class="answer-editor" open`) {
|
strings.Contains(body, `<details class="post-composer" open`) {
|
||||||
t.Fatalf("admin answer editor is not collapsed and populated: %s", body)
|
t.Fatalf("admin reply editor is not collapsed and populated: %s", body)
|
||||||
}
|
|
||||||
if _, err := mem.GetAnswer(context.Background(), q.ID); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// The public answer is visible to its author, but editing remains admin-only.
|
// The public reply is visible to the root author, but editing remains admin-only.
|
||||||
rec = httptest.NewRecorder()
|
rec = httptest.NewRecorder()
|
||||||
req = httptest.NewRequest(http.MethodGet, "/questions/"+q.ID, nil)
|
req = httptest.NewRequest(http.MethodGet, "/questions/"+q.ID, nil)
|
||||||
for _, c := range userCookies {
|
for _, c := range userCookies {
|
||||||
@@ -623,8 +637,8 @@ func TestMutationsVoteAnswerHideAndCSRF(t *testing.T) {
|
|||||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Tighten the nuts.") {
|
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Tighten the nuts.") {
|
||||||
t.Fatalf("question author cannot see answer: %d %s", rec.Code, rec.Body.String())
|
t.Fatalf("question author cannot see answer: %d %s", rec.Code, rec.Body.String())
|
||||||
}
|
}
|
||||||
if strings.Contains(rec.Body.String(), `class="answer-editor"`) {
|
if strings.Contains(rec.Body.String(), `/posts/`+adminReply.ID+`/edit`) {
|
||||||
t.Fatalf("question author can see admin answer editor: %s", rec.Body.String())
|
t.Fatalf("question author can edit admin reply: %s", rec.Body.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hide invalid id
|
// Hide invalid id
|
||||||
@@ -659,8 +673,8 @@ func TestMutationsVoteAnswerHideAndCSRF(t *testing.T) {
|
|||||||
if rec.Code != http.StatusSeeOther {
|
if rec.Code != http.StatusSeeOther {
|
||||||
t.Fatalf("hide %d %s", rec.Code, rec.Body.String())
|
t.Fatalf("hide %d %s", rec.Code, rec.Body.String())
|
||||||
}
|
}
|
||||||
hidden, err := mem.GetQuestion(context.Background(), q.ID, admin.ID)
|
hidden, err := mem.GetPost(context.Background(), q.ID)
|
||||||
if err != nil || !hidden.Hidden {
|
if err != nil || hidden.PostState != store.PostStateHidden {
|
||||||
t.Fatalf("question not hidden: %+v %v", hidden, err)
|
t.Fatalf("question not hidden: %+v %v", hidden, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -713,113 +727,6 @@ func TestRegisterRequiresEmail(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAnswerNotifyFirstOnly(t *testing.T) {
|
|
||||||
recMail := &mail.Recording{}
|
|
||||||
srv, mem := newTestServer(t, Config{Mail: recMail})
|
|
||||||
h := srv.Handler()
|
|
||||||
adminName := uniq("adm")
|
|
||||||
askName := uniq("ask")
|
|
||||||
admin := seedUser(t, mem, adminName, "hunter22", store.RoleAdmin)
|
|
||||||
asker := seedUser(t, mem, askName, "hunter22", store.RoleUser)
|
|
||||||
adminCookies := loginUser(t, h, adminName, "hunter22")
|
|
||||||
|
|
||||||
q := &store.RankedQuestion{
|
|
||||||
AuthorID: asker.ID,
|
|
||||||
Title: "Leaky sink",
|
|
||||||
Body: "Drip",
|
|
||||||
City: "Oakland",
|
|
||||||
HuntDate: pacific.Today(),
|
|
||||||
}
|
|
||||||
if err := mem.CreateQuestion(context.Background(), q); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
postAnswer := func(body string) {
|
|
||||||
t.Helper()
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/questions/"+q.ID, nil)
|
|
||||||
for _, c := range adminCookies {
|
|
||||||
req.AddCookie(c)
|
|
||||||
}
|
|
||||||
h.ServeHTTP(w, req)
|
|
||||||
csrf := csrfFrom(w.Body.String())
|
|
||||||
form := strings.NewReader("_csrf=" + csrf + "&body=" + body)
|
|
||||||
req = httptest.NewRequest(http.MethodPost, "/questions/"+q.ID+"/answer", form)
|
|
||||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
||||||
req.Header.Set("HX-Request", "true")
|
|
||||||
for _, c := range adminCookies {
|
|
||||||
req.AddCookie(c)
|
|
||||||
}
|
|
||||||
w = httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(w, req)
|
|
||||||
if w.Code != 200 {
|
|
||||||
t.Fatalf("answer %d %s", w.Code, w.Body.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
postAnswer("First+reply")
|
|
||||||
deadline := time.Now().Add(2 * time.Second)
|
|
||||||
var msgs []mail.QuestionAnswered
|
|
||||||
for time.Now().Before(deadline) {
|
|
||||||
msgs = recMail.Snapshot()
|
|
||||||
if len(msgs) > 0 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
time.Sleep(10 * time.Millisecond)
|
|
||||||
}
|
|
||||||
if len(msgs) != 1 {
|
|
||||||
t.Fatalf("first answer notifies once, got %d", len(msgs))
|
|
||||||
}
|
|
||||||
if msgs[0].ToEmail != asker.Email || msgs[0].QuestionID != q.ID {
|
|
||||||
t.Fatalf("unexpected notify: %+v", msgs[0])
|
|
||||||
}
|
|
||||||
if msgs[0].AnswerBody != "First reply" {
|
|
||||||
t.Fatalf("answer body %q", msgs[0].AnswerBody)
|
|
||||||
}
|
|
||||||
|
|
||||||
postAnswer("Edited+reply")
|
|
||||||
time.Sleep(50 * time.Millisecond)
|
|
||||||
if recMail.Len() != 1 {
|
|
||||||
t.Fatalf("edit must not notify again, got %d", recMail.Len())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Author without email is skipped
|
|
||||||
recMail2 := &mail.Recording{}
|
|
||||||
srv2, mem2 := newTestServer(t, Config{Mail: recMail2})
|
|
||||||
h2 := srv2.Handler()
|
|
||||||
admin2 := seedUser(t, mem2, uniq("adm2"), "hunter22", store.RoleAdmin)
|
|
||||||
noMail := &store.User{Username: uniq("silent"), PasswordHash: admin.PasswordHash, Role: store.RoleUser, Email: ""}
|
|
||||||
hash, _ := bcrypt.GenerateFromPassword([]byte("hunter22"), bcrypt.MinCost)
|
|
||||||
noMail.PasswordHash = string(hash)
|
|
||||||
if err := mem2.CreateUser(context.Background(), noMail); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
q2 := &store.RankedQuestion{AuthorID: noMail.ID, Title: "Quiet", Body: "x", HuntDate: pacific.Today()}
|
|
||||||
if err := mem2.CreateQuestion(context.Background(), q2); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
cookies := loginUser(t, h2, admin2.Username, "hunter22")
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/questions/"+q2.ID, nil)
|
|
||||||
for _, c := range cookies {
|
|
||||||
req.AddCookie(c)
|
|
||||||
}
|
|
||||||
h2.ServeHTTP(w, req)
|
|
||||||
csrf := csrfFrom(w.Body.String())
|
|
||||||
form := strings.NewReader("_csrf=" + csrf + "&body=Hello")
|
|
||||||
req = httptest.NewRequest(http.MethodPost, "/questions/"+q2.ID+"/answer", form)
|
|
||||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
||||||
for _, c := range cookies {
|
|
||||||
req.AddCookie(c)
|
|
||||||
}
|
|
||||||
w = httptest.NewRecorder()
|
|
||||||
h2.ServeHTTP(w, req)
|
|
||||||
time.Sleep(50 * time.Millisecond)
|
|
||||||
if recMail2.Len() != 0 {
|
|
||||||
t.Fatalf("empty email must skip notify, got %d", recMail2.Len())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRegisterThrottleUsesTCPPeerThroughRouter ensures forged X-Forwarded-For
|
// TestRegisterThrottleUsesTCPPeerThroughRouter ensures forged X-Forwarded-For
|
||||||
// cannot bypass rate limits when the direct peer is outside TrustedProxies.
|
// cannot bypass rate limits when the direct peer is outside TrustedProxies.
|
||||||
// This must go through Handler() so middleware ordering bugs are caught.
|
// This must go through Handler() so middleware ordering bugs are caught.
|
||||||
|
|||||||
@@ -63,6 +63,9 @@ CREATE TABLE IF NOT EXISTS posts (
|
|||||||
CREATE INDEX IF NOT EXISTS idx_posts_parent_created
|
CREATE INDEX IF NOT EXISTS idx_posts_parent_created
|
||||||
ON posts(parent_id, created_at, id);
|
ON posts(parent_id, created_at, id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_posts_author_created
|
||||||
|
ON posts(author_id, created_at DESC, id DESC);
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_posts_root_date
|
CREATE INDEX IF NOT EXISTS idx_posts_root_date
|
||||||
ON posts(post_date, post_state)
|
ON posts(post_date, post_state)
|
||||||
WHERE parent_id IS NULL;
|
WHERE parent_id IS NULL;
|
||||||
|
|||||||
+104
-30
@@ -552,12 +552,14 @@ input:focus, textarea:focus, .btn:focus-visible, .chip:focus-visible, .vote-btn:
|
|||||||
padding: 18px 14px;
|
padding: 18px 14px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.post-content { min-width: 0; }
|
||||||
|
|
||||||
.question-page h1 {
|
.question-page h1 {
|
||||||
font-size: clamp(1.5rem, 3.5vw, 2.1rem);
|
font-size: clamp(1.5rem, 3.5vw, 2.1rem);
|
||||||
line-height: 1.15;
|
line-height: 1.15;
|
||||||
}
|
}
|
||||||
|
|
||||||
.q-body, .answer-body {
|
.post-body {
|
||||||
white-space: pre-wrap;
|
white-space: pre-wrap;
|
||||||
margin: 14px 0 0;
|
margin: 14px 0 0;
|
||||||
text-wrap: pretty;
|
text-wrap: pretty;
|
||||||
@@ -574,18 +576,7 @@ input:focus, textarea:focus, .btn:focus-visible, .chip:focus-visible, .vote-btn:
|
|||||||
}
|
}
|
||||||
.crumb a:hover { color: var(--signal); }
|
.crumb a:hover { color: var(--signal); }
|
||||||
|
|
||||||
.answer {
|
.post-kicker {
|
||||||
margin-top: 16px;
|
|
||||||
padding: 20px 18px;
|
|
||||||
background: var(--panel);
|
|
||||||
border: 1px solid var(--line);
|
|
||||||
}
|
|
||||||
|
|
||||||
.answer.is-in {
|
|
||||||
border-color: var(--signal);
|
|
||||||
}
|
|
||||||
|
|
||||||
.answer-kicker {
|
|
||||||
margin: 0 0 6px;
|
margin: 0 0 6px;
|
||||||
font-family: var(--mono);
|
font-family: var(--mono);
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
@@ -595,27 +586,99 @@ input:focus, textarea:focus, .btn:focus-visible, .chip:focus-visible, .vote-btn:
|
|||||||
color: var(--signal);
|
color: var(--signal);
|
||||||
}
|
}
|
||||||
|
|
||||||
.answer h2 {
|
.conversation {
|
||||||
margin: 0;
|
margin-top: 32px;
|
||||||
font-size: 1.15rem;
|
|
||||||
font-weight: 500;
|
|
||||||
letter-spacing: 0.04em;
|
|
||||||
text-transform: uppercase;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.byline {
|
.conversation-head {
|
||||||
|
margin-bottom: 12px;
|
||||||
|
padding-bottom: 12px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.conversation h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.conversation-head .eyebrow {
|
||||||
|
margin-bottom: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread {
|
||||||
|
display: grid;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-post {
|
||||||
|
position: relative;
|
||||||
|
padding: 16px;
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-left: 2px solid var(--zinc);
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-post.is-shop {
|
||||||
|
border-left-color: var(--signal);
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-post:target,
|
||||||
|
.q-detail:target {
|
||||||
|
outline: 2px solid var(--signal);
|
||||||
|
outline-offset: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-post-branch,
|
||||||
|
.thread-post-deep {
|
||||||
|
margin-left: clamp(12px, 4vw, 28px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-post-deep .thread-post-deep {
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.post-replies {
|
||||||
|
display: grid;
|
||||||
|
gap: 12px;
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.post-meta {
|
||||||
margin: 6px 0 0;
|
margin: 6px 0 0;
|
||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
font-family: var(--mono);
|
font-family: var(--mono);
|
||||||
font-size: 0.72rem;
|
font-size: 0.72rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.answer-editor {
|
.edited {
|
||||||
margin-top: 16px;
|
display: inline-block;
|
||||||
|
margin-left: 8px;
|
||||||
|
color: var(--zinc);
|
||||||
|
font-size: 0.65rem;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
.post-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 0 16px;
|
||||||
|
margin-top: 10px;
|
||||||
border-top: 1px solid var(--line);
|
border-top: 1px solid var(--line);
|
||||||
}
|
}
|
||||||
|
|
||||||
.answer-editor summary {
|
.post-composer {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.post-composer[open] {
|
||||||
|
flex: 1 0 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.post-composer summary {
|
||||||
display: flex;
|
display: flex;
|
||||||
width: fit-content;
|
width: fit-content;
|
||||||
min-height: 44px;
|
min-height: 44px;
|
||||||
@@ -630,23 +693,34 @@ input:focus, textarea:focus, .btn:focus-visible, .chip:focus-visible, .vote-btn:
|
|||||||
list-style: none;
|
list-style: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.answer-editor summary::-webkit-details-marker { display: none; }
|
.post-composer summary::-webkit-details-marker { display: none; }
|
||||||
.answer-editor summary:hover,
|
.post-composer summary::marker { content: ""; }
|
||||||
.answer-editor[open] summary { color: var(--signal); }
|
.post-composer summary:hover,
|
||||||
.answer-editor summary:focus-visible {
|
.post-composer[open] summary { color: var(--signal); }
|
||||||
|
.post-composer summary:focus-visible {
|
||||||
outline: 2px solid var(--signal);
|
outline: 2px solid var(--signal);
|
||||||
outline-offset: 2px;
|
outline-offset: 2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.answer-editor .answer-form { margin-top: 4px; }
|
.post-form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
width: 100%;
|
||||||
|
margin: 0 0 14px;
|
||||||
|
}
|
||||||
|
|
||||||
.answer-form-actions {
|
.post-form-actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.answer-form-actions .btn { flex: 1 1 10rem; }
|
.post-form-actions .btn { flex: 1 1 10rem; }
|
||||||
|
|
||||||
|
.post-hide {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
.waiting { color: var(--muted); margin: 0; font-family: var(--mono); font-size: 0.8rem; }
|
.waiting { color: var(--muted); margin: 0; font-family: var(--mono); font-size: 0.8rem; }
|
||||||
|
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
{{define "answer"}}
|
|
||||||
<section id="answer-block" class="answer{{if .Answer}} is-in{{end}}">
|
|
||||||
{{if .Answer}}
|
|
||||||
<p class="answer-kicker">Shop response</p>
|
|
||||||
<h2>Answer</h2>
|
|
||||||
<p class="byline">{{.Answer.AuthorName}} · 22 years, Bay Area</p>
|
|
||||||
<p class="answer-body">{{.Answer.Body}}</p>
|
|
||||||
{{if isAdmin .User}}
|
|
||||||
<details class="answer-editor">
|
|
||||||
<summary>Edit answer</summary>
|
|
||||||
<form class="answer-form" method="post" action="/questions/{{.Answer.QuestionID}}/answer"
|
|
||||||
hx-post="/questions/{{.Answer.QuestionID}}/answer" hx-target="#answer-block" hx-swap="outerHTML">
|
|
||||||
<input type="hidden" name="_csrf" value="{{.CSRF}}">
|
|
||||||
<label for="answer-body">Edit answer</label>
|
|
||||||
<textarea id="answer-body" name="body" rows="8" required maxlength="12000">{{.Answer.Body}}</textarea>
|
|
||||||
<div class="answer-form-actions">
|
|
||||||
<button type="submit" class="btn btn-primary">Save answer</button>
|
|
||||||
<button type="reset" class="btn btn-ghost"
|
|
||||||
onclick="this.closest('details').removeAttribute('open')">Cancel</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</details>
|
|
||||||
{{end}}
|
|
||||||
{{else}}
|
|
||||||
<p class="waiting">No answer yet. Check back after the hunt.</p>
|
|
||||||
{{end}}
|
|
||||||
</section>
|
|
||||||
{{end}}
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{{define "leaderboard"}}
|
{{define "leaderboard"}}
|
||||||
<ol id="leaderboard" class="board" start="1">
|
<ol id="leaderboard" class="board" start="1">
|
||||||
{{if not .Questions}}
|
{{if not .Posts}}
|
||||||
<li class="empty">
|
<li class="empty">
|
||||||
{{if eq .Date .Today}}
|
{{if eq .Date .Today}}
|
||||||
<p class="empty-kicker">Queue empty</p>
|
<p class="empty-kicker">Queue empty</p>
|
||||||
@@ -10,20 +10,20 @@
|
|||||||
{{end}}
|
{{end}}
|
||||||
</li>
|
</li>
|
||||||
{{else}}
|
{{else}}
|
||||||
{{range $i, $q := .Questions}}
|
{{range $i, $post := .Posts}}
|
||||||
<li class="row">
|
<li class="row">
|
||||||
<span class="rank" aria-hidden="true">{{rank $i}}</span>
|
<span class="rank" aria-hidden="true">{{rank $i}}</span>
|
||||||
{{template "vote" (voteCtx $.User $.CSRF "list" $.Date $q)}}
|
{{template "vote" (voteCtx $.User $.CSRF "list" $.Date $post)}}
|
||||||
<div class="row-body">
|
<div class="row-body">
|
||||||
<a class="q-title" href="/questions/{{$q.ID}}">{{$q.Title}}</a>
|
<a class="q-title" href="/questions/{{$post.ID}}">{{$post.Title}}</a>
|
||||||
<p class="meta">
|
<p class="meta">
|
||||||
<span>{{$q.AuthorName}}</span>
|
<span>{{$post.AuthorName}}</span>
|
||||||
{{if $q.City}}<span class="dot" aria-hidden="true">·</span><span>{{$q.City}}</span>{{end}}
|
{{if $post.City}}<span class="dot" aria-hidden="true">·</span><span>{{$post.City}}</span>{{end}}
|
||||||
{{if $q.Answered}}<span class="badge">Answered</span>{{end}}
|
{{if $post.Answered}}<span class="badge">Answered</span>{{end}}
|
||||||
</p>
|
</p>
|
||||||
{{if isAdmin $.User}}
|
{{if isAdmin $.User}}
|
||||||
<form class="inline-hide" method="post" action="/questions/{{$q.ID}}/hide"
|
<form class="inline-hide" method="post" action="/questions/{{$post.ID}}/hide"
|
||||||
hx-post="/questions/{{$q.ID}}/hide" hx-target="#leaderboard" hx-swap="outerHTML">
|
hx-post="/questions/{{$post.ID}}/hide" hx-target="#leaderboard" hx-swap="outerHTML">
|
||||||
<input type="hidden" name="_csrf" value="{{$.CSRF}}">
|
<input type="hidden" name="_csrf" value="{{$.CSRF}}">
|
||||||
<input type="hidden" name="view" value="list">
|
<input type="hidden" name="view" value="list">
|
||||||
<button type="submit" class="linkish">Hide</button>
|
<button type="submit" class="linkish">Hide</button>
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
{{define "postActions"}}
|
||||||
|
<div class="post-actions">
|
||||||
|
{{if canReply .User .Root}}
|
||||||
|
<details class="post-composer">
|
||||||
|
<summary>Reply</summary>
|
||||||
|
<form class="post-form" method="post" action="/posts">
|
||||||
|
<input type="hidden" name="_csrf" value="{{.CSRF}}">
|
||||||
|
<input type="hidden" name="parent_id" value="{{.Post.ID}}">
|
||||||
|
<label for="reply-{{.Post.ID}}">Reply to {{.Post.AuthorName}}</label>
|
||||||
|
<textarea id="reply-{{.Post.ID}}" name="body" rows="5" required maxlength="12000"></textarea>
|
||||||
|
<div class="post-form-actions">
|
||||||
|
<button type="submit" class="btn btn-primary">Post reply</button>
|
||||||
|
<button type="reset" class="btn btn-ghost"
|
||||||
|
onclick="this.closest('details').removeAttribute('open')">Cancel</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</details>
|
||||||
|
{{end}}
|
||||||
|
{{if canEditPost .User .Post}}
|
||||||
|
<details class="post-composer">
|
||||||
|
<summary>Edit</summary>
|
||||||
|
<form class="post-form" method="post" action="/posts/{{.Post.ID}}/edit">
|
||||||
|
<input type="hidden" name="_csrf" value="{{.CSRF}}">
|
||||||
|
<label for="edit-{{.Post.ID}}">Edit post</label>
|
||||||
|
<textarea id="edit-{{.Post.ID}}" name="body" rows="5" required
|
||||||
|
maxlength="12000">{{.Post.Body}}</textarea>
|
||||||
|
<div class="post-form-actions">
|
||||||
|
<button type="submit" class="btn btn-primary">Save changes</button>
|
||||||
|
<button type="reset" class="btn btn-ghost"
|
||||||
|
onclick="this.closest('details').removeAttribute('open')">Cancel</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</details>
|
||||||
|
{{end}}
|
||||||
|
{{if and (not .Post.ParentID) (isAdmin .User)}}
|
||||||
|
<form class="post-hide" method="post" action="/questions/{{.Post.ID}}/hide">
|
||||||
|
<input type="hidden" name="_csrf" value="{{.CSRF}}">
|
||||||
|
<button type="submit" class="linkish">Hide</button>
|
||||||
|
</form>
|
||||||
|
{{end}}
|
||||||
|
</div>
|
||||||
|
{{end}}
|
||||||
|
|
||||||
|
{{define "threadReply"}}
|
||||||
|
{{$ctx := .}}
|
||||||
|
<article id="post-{{.Post.ID}}"
|
||||||
|
class="thread-post thread-post-{{postDepth .Depth}}{{if eq .Post.AuthorRole "admin"}} is-shop{{end}}">
|
||||||
|
<header class="post-head">
|
||||||
|
<p class="post-kicker">{{postLabel .Post}}</p>
|
||||||
|
<p class="post-meta">
|
||||||
|
<span>{{.Post.AuthorName}}</span>
|
||||||
|
<span class="dot" aria-hidden="true">·</span>
|
||||||
|
<time datetime="{{.Post.CreatedAt}}">{{postTime .Post.CreatedAt}}</time>
|
||||||
|
{{if isEdited .Post}}<span class="edited">Edited</span>{{end}}
|
||||||
|
</p>
|
||||||
|
</header>
|
||||||
|
<p class="post-body">{{.Post.Body}}</p>
|
||||||
|
{{template "postActions" .}}
|
||||||
|
{{if .Post.Replies}}
|
||||||
|
<div class="post-replies">
|
||||||
|
{{range .Post.Replies}}
|
||||||
|
{{template "threadReply" (postCtx $ctx.User $ctx.CSRF $ctx.Root . (add $ctx.Depth 1))}}
|
||||||
|
{{end}}
|
||||||
|
</div>
|
||||||
|
{{end}}
|
||||||
|
</article>
|
||||||
|
{{end}}
|
||||||
@@ -1,26 +1,26 @@
|
|||||||
{{define "vote"}}
|
{{define "vote"}}
|
||||||
<div id="vote-{{.Question.ID}}" class="vote">
|
<div id="vote-{{.Post.ID}}" class="vote">
|
||||||
{{if .User}}
|
{{if .User}}
|
||||||
<form method="post" action="/questions/{{.Question.ID}}/vote"
|
<form method="post" action="/questions/{{.Post.ID}}/vote"
|
||||||
hx-post="/questions/{{.Question.ID}}/vote"
|
hx-post="/questions/{{.Post.ID}}/vote"
|
||||||
{{if eq .View "list"}}hx-target="#leaderboard" hx-swap="outerHTML"{{else}}hx-target="#vote-{{.Question.ID}}" hx-swap="outerHTML"{{end}}>
|
{{if eq .View "list"}}hx-target="#leaderboard" hx-swap="outerHTML"{{else}}hx-target="#vote-{{.Post.ID}}" hx-swap="outerHTML"{{end}}>
|
||||||
<input type="hidden" name="_csrf" value="{{.CSRF}}">
|
<input type="hidden" name="_csrf" value="{{.CSRF}}">
|
||||||
{{if eq .Question.UserVote 1}}<input type="hidden" name="value" value="0">{{else}}<input type="hidden" name="value" value="1">{{end}}
|
{{if eq .Post.UserVote 1}}<input type="hidden" name="value" value="0">{{else}}<input type="hidden" name="value" value="1">{{end}}
|
||||||
<input type="hidden" name="view" value="{{.View}}">
|
<input type="hidden" name="view" value="{{.View}}">
|
||||||
<input type="hidden" name="date" value="{{.Date}}">
|
<input type="hidden" name="date" value="{{.Date}}">
|
||||||
<button type="submit" class="vote-btn{{if eq .Question.UserVote 1}} is-up{{end}}" aria-label="Upvote" aria-pressed="{{if eq .Question.UserVote 1}}true{{else}}false{{end}}">
|
<button type="submit" class="vote-btn{{if eq .Post.UserVote 1}} is-up{{end}}" aria-label="Upvote" aria-pressed="{{if eq .Post.UserVote 1}}true{{else}}false{{end}}">
|
||||||
<svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><path d="M9 3.5 15 12H3z" fill="currentColor"/></svg>
|
<svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><path d="M9 3.5 15 12H3z" fill="currentColor"/></svg>
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
<span class="score" aria-label="Net score {{.Question.Score}}">{{.Question.Score}}</span>
|
<span class="score" aria-label="Net score {{.Post.Score}}">{{.Post.Score}}</span>
|
||||||
<form method="post" action="/questions/{{.Question.ID}}/vote"
|
<form method="post" action="/questions/{{.Post.ID}}/vote"
|
||||||
hx-post="/questions/{{.Question.ID}}/vote"
|
hx-post="/questions/{{.Post.ID}}/vote"
|
||||||
{{if eq .View "list"}}hx-target="#leaderboard" hx-swap="outerHTML"{{else}}hx-target="#vote-{{.Question.ID}}" hx-swap="outerHTML"{{end}}>
|
{{if eq .View "list"}}hx-target="#leaderboard" hx-swap="outerHTML"{{else}}hx-target="#vote-{{.Post.ID}}" hx-swap="outerHTML"{{end}}>
|
||||||
<input type="hidden" name="_csrf" value="{{.CSRF}}">
|
<input type="hidden" name="_csrf" value="{{.CSRF}}">
|
||||||
{{if eq .Question.UserVote -1}}<input type="hidden" name="value" value="0">{{else}}<input type="hidden" name="value" value="-1">{{end}}
|
{{if eq .Post.UserVote -1}}<input type="hidden" name="value" value="0">{{else}}<input type="hidden" name="value" value="-1">{{end}}
|
||||||
<input type="hidden" name="view" value="{{.View}}">
|
<input type="hidden" name="view" value="{{.View}}">
|
||||||
<input type="hidden" name="date" value="{{.Date}}">
|
<input type="hidden" name="date" value="{{.Date}}">
|
||||||
<button type="submit" class="vote-btn{{if eq .Question.UserVote -1}} is-down{{end}}" aria-label="Downvote" aria-pressed="{{if eq .Question.UserVote -1}}true{{else}}false{{end}}">
|
<button type="submit" class="vote-btn{{if eq .Post.UserVote -1}} is-down{{end}}" aria-label="Downvote" aria-pressed="{{if eq .Post.UserVote -1}}true{{else}}false{{end}}">
|
||||||
<svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><path d="M9 14.5 3 6h12z" fill="currentColor"/></svg>
|
<svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><path d="M9 14.5 3 6h12z" fill="currentColor"/></svg>
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
@@ -28,7 +28,7 @@
|
|||||||
<a class="vote-btn" href="/login" hx-get="/auth/prompt" hx-target="#flash" aria-label="Sign in to upvote">
|
<a class="vote-btn" href="/login" hx-get="/auth/prompt" hx-target="#flash" aria-label="Sign in to upvote">
|
||||||
<svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><path d="M9 3.5 15 12H3z" fill="currentColor"/></svg>
|
<svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><path d="M9 3.5 15 12H3z" fill="currentColor"/></svg>
|
||||||
</a>
|
</a>
|
||||||
<span class="score" aria-label="Net score {{.Question.Score}}">{{.Question.Score}}</span>
|
<span class="score" aria-label="Net score {{.Post.Score}}">{{.Post.Score}}</span>
|
||||||
<a class="vote-btn" href="/login" hx-get="/auth/prompt" hx-target="#flash" aria-label="Sign in to downvote">
|
<a class="vote-btn" href="/login" hx-get="/auth/prompt" hx-target="#flash" aria-label="Sign in to downvote">
|
||||||
<svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><path d="M9 14.5 3 6h12z" fill="currentColor"/></svg>
|
<svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><path d="M9 14.5 3 6h12z" fill="currentColor"/></svg>
|
||||||
</a>
|
</a>
|
||||||
|
|||||||
@@ -43,12 +43,12 @@
|
|||||||
|
|
||||||
<section class="profile-questions" aria-labelledby="profile-q-heading">
|
<section class="profile-questions" aria-labelledby="profile-q-heading">
|
||||||
<h2 id="profile-q-heading">{{.QuestionsLabel}}</h2>
|
<h2 id="profile-q-heading">{{.QuestionsLabel}}</h2>
|
||||||
{{if .Questions}}
|
{{if .Posts}}
|
||||||
<ul class="profile-q-list">
|
<ul class="profile-q-list">
|
||||||
{{range .Questions}}
|
{{range .Posts}}
|
||||||
<li>
|
<li>
|
||||||
<a href="/questions/{{.ID}}">{{.Title}}</a>
|
<a href="/questions/{{.ID}}">{{.Title}}</a>
|
||||||
<span class="meta">{{.HuntDate}}</span>
|
<span class="meta">{{.PostDate}}</span>
|
||||||
</li>
|
</li>
|
||||||
{{end}}
|
{{end}}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
+27
-23
@@ -1,37 +1,41 @@
|
|||||||
{{define "question"}}
|
{{define "question"}}
|
||||||
{{template "header" .}}
|
{{template "header" .}}
|
||||||
<main id="main" class="wrap question-page">
|
<main id="main" class="wrap question-page">
|
||||||
<p class="crumb"><a href="{{if eq .Question.HuntDate .Today}}/{{else}}/hunt/{{.Question.HuntDate}}{{end}}">← {{pacificLabel .Question.HuntDate}}</a></p>
|
<p class="crumb"><a href="{{if eq .Question.PostDate .Today}}/{{else}}/hunt/{{.Question.PostDate}}{{end}}">← {{pacificLabel .Question.PostDate}}</a></p>
|
||||||
<article class="q-detail">
|
<article id="post-{{.Question.ID}}" class="q-detail">
|
||||||
{{template "vote" (voteCtx .User .CSRF "question" .Question.HuntDate .Question)}}
|
{{template "vote" (voteCtx .User .CSRF "question" .Question.PostDate .Question)}}
|
||||||
<div>
|
<div class="post-content">
|
||||||
|
<p class="post-kicker">Question</p>
|
||||||
<h1>{{.Question.Title}}</h1>
|
<h1>{{.Question.Title}}</h1>
|
||||||
<p class="meta">
|
<p class="meta">
|
||||||
<span>{{.Question.AuthorName}}</span>
|
<span>{{.Question.AuthorName}}</span>
|
||||||
{{if .Question.City}}<span class="dot" aria-hidden="true">·</span><span>{{.Question.City}}</span>{{end}}
|
{{if .Question.City}}<span class="dot" aria-hidden="true">·</span><span>{{.Question.City}}</span>{{end}}
|
||||||
<span class="dot" aria-hidden="true">·</span>
|
<span class="dot" aria-hidden="true">·</span>
|
||||||
<a href="{{if eq .Question.HuntDate .Today}}/{{else}}/hunt/{{.Question.HuntDate}}{{end}}">{{.Question.HuntDate}}</a>
|
<a href="{{if eq .Question.PostDate .Today}}/{{else}}/hunt/{{.Question.PostDate}}{{end}}">{{.Question.PostDate}}</a>
|
||||||
|
{{if eq .Question.PostState "locked"}}<span class="badge">Locked</span>{{end}}
|
||||||
|
{{if eq .Question.PostState "hidden"}}<span class="badge">Hidden</span>{{end}}
|
||||||
|
{{if isEdited .Question}}<span class="edited">Edited</span>{{end}}
|
||||||
</p>
|
</p>
|
||||||
<p class="q-body">{{.Question.Body}}</p>
|
<p class="post-body">{{.Question.Body}}</p>
|
||||||
{{if isAdmin .User}}
|
{{template "postActions" (postCtx .User .CSRF .Question .Question 0)}}
|
||||||
<form method="post" action="/questions/{{.Question.ID}}/hide"
|
|
||||||
hx-post="/questions/{{.Question.ID}}/hide" hx-target="body">
|
|
||||||
<input type="hidden" name="_csrf" value="{{.CSRF}}">
|
|
||||||
<button type="submit" class="linkish">Hide this question</button>
|
|
||||||
</form>
|
|
||||||
{{end}}
|
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
{{template "answer" .}}
|
<section class="conversation" aria-labelledby="conversation-heading">
|
||||||
{{if and (isAdmin .User) (not .Answer)}}
|
<div class="conversation-head">
|
||||||
<form class="answer-form" method="post" action="/questions/{{.Question.ID}}/answer"
|
<p class="eyebrow">Thread</p>
|
||||||
hx-post="/questions/{{.Question.ID}}/answer" hx-target="#answer-block" hx-swap="outerHTML">
|
<h2 id="conversation-heading">Conversation</h2>
|
||||||
<input type="hidden" name="_csrf" value="{{.CSRF}}">
|
</div>
|
||||||
<label for="answer-body">Write the answer</label>
|
{{if .Question.Replies}}
|
||||||
<textarea id="answer-body" name="body" rows="8" required maxlength="12000"></textarea>
|
<div class="thread">
|
||||||
<button type="submit" class="btn btn-primary">Save answer</button>
|
{{$page := .}}
|
||||||
</form>
|
{{range .Question.Replies}}
|
||||||
{{end}}
|
{{template "threadReply" (postCtx $page.User $page.CSRF $page.Question . 1)}}
|
||||||
|
{{end}}
|
||||||
|
</div>
|
||||||
|
{{else}}
|
||||||
|
<p class="waiting">No replies yet.</p>
|
||||||
|
{{end}}
|
||||||
|
</section>
|
||||||
</main>
|
</main>
|
||||||
{{template "footer" .}}
|
{{template "footer" .}}
|
||||||
{{end}}
|
{{end}}
|
||||||
|
|||||||
Reference in New Issue
Block a user