Open platform to collect and prioritize feedback
feature: add attachments to comments (#734)
Guilherme Oenning851cef85f0e2
diff --git a/app/actions/post.go b/app/actions/post.goindex 8a89538b3..cf45994ec 100644--- a/app/actions/post.go+++ b/app/actions/post.go@@ -146,6 +146,16 @@ func (input *AddNewComment) Validate(user *models.User, services *app.Services)result.AddFieldFailure("content", "Comment is required.")}+ messages, err := validate.MultiImageUpload(nil, input.Model.Attachments, validate.MultiImageUploadOpts{+ MaxUploads: 2,+ MaxKilobytes: 5120,+ ExactRatio: false,+ })+ if err != nil {+ return validate.Error(err)+ }+ result.AddFieldFailure("attachments", messages...)+return result}@@ -235,7 +245,9 @@ func (input *DeletePost) Validate(user *models.User, services *app.Services) *va// EditComment represents the action to update an existing commenttype EditComment struct {- Model *models.EditComment+ Model *models.EditComment+ Post *models.Post+ Comment *models.Comment}// Initialize the model@@ -246,11 +258,18 @@ func (input *EditComment) Initialize() interface{} {// IsAuthorized returns true if current user is authorized to perform this actionfunc (input *EditComment) IsAuthorized(user *models.User, services *app.Services) bool {+ post, err := services.Posts.GetByNumber(input.Model.PostNumber)+ if err != nil {+ return false+ }+comment, err := services.Posts.GetCommentByID(input.Model.ID)if err != nil {return false}+ input.Post = post+ input.Comment = commentreturn user.ID == comment.User.ID || user.IsCollaborator()}@@ -262,6 +281,21 @@ func (input *EditComment) Validate(user *models.User, services *app.Services) *vresult.AddFieldFailure("content", "Comment is required.")}+ attachments, err := services.Posts.GetAttachments(input.Post, input.Comment)+ if err != nil {+ return validate.Error(err)+ }++ messages, err := validate.MultiImageUpload(attachments, input.Model.Attachments, validate.MultiImageUploadOpts{+ MaxUploads: 2,+ MaxKilobytes: 5120,+ ExactRatio: false,+ })+ if err != nil {+ return validate.Error(err)+ }+ result.AddFieldFailure("attachments", messages...)+return result}diff --git a/app/handlers/apiv1/post.go b/app/handlers/apiv1/post.goindex 923a419e9..c9e2f2d90 100644--- a/app/handlers/apiv1/post.go+++ b/app/handlers/apiv1/post.go@@ -206,6 +206,11 @@ func PostComment() web.HandlerFunc {return c.HandleValidation(result)}+ err := webutil.ProcessMultiImageUpload(c, input.Model.Attachments, "attachments")+ if err != nil {+ return c.Failure(err)+ }+post, err := c.Services().Posts.GetByNumber(input.Model.Number)if err != nil {return c.Failure(err)@@ -216,6 +221,16 @@ func PostComment() web.HandlerFunc {return c.Failure(err)}+ comment, err := c.Services().Posts.GetCommentByID(id)+ if err != nil {+ return c.Failure(err)+ }++ err = c.Services().Posts.SetAttachments(post, comment, input.Model.Attachments)+ if err != nil {+ return c.Failure(err)+ }+c.Enqueue(tasks.NotifyAboutNewComment(post, input.Model))return c.Ok(web.Map{@@ -232,7 +247,17 @@ func UpdateComment() web.HandlerFunc {return c.HandleValidation(result)}- err := c.Services().Posts.UpdateComment(input.Model.ID, input.Model.Content)+ err := webutil.ProcessMultiImageUpload(c, input.Model.Attachments, "attachments")+ if err != nil {+ return c.Failure(err)+ }++ err = c.Services().Posts.UpdateComment(input.Model.ID, input.Model.Content)+ if err != nil {+ return c.Failure(err)+ }++ err = c.Services().Posts.SetAttachments(input.Post, input.Comment, input.Model.Attachments)if err != nil {return c.Failure(err)}diff --git a/app/models/feedback.go b/app/models/feedback.goindex 7c840c844..67092cc0e 100644--- a/app/models/feedback.go+++ b/app/models/feedback.go@@ -64,15 +64,17 @@ type DeletePost struct {// NewComment represents a new commenttype NewComment struct {- Number int `route:"number"`- Content string `json:"content"`+ Number int `route:"number"`+ Content string `json:"content"`+ Attachments []*ImageUpload `json:"attachments"`}// EditComment represents a request to edit existing commenttype EditComment struct {- PostNumber int `route:"number"`- ID int `route:"id"`- Content string `json:"content"`+ PostNumber int `route:"number"`+ ID int `route:"id"`+ Content string `json:"content"`+ Attachments []*ImageUpload `json:"attachments"`}// DeleteComment represents a request to delete an existing comment@@ -107,12 +109,13 @@ type OriginalPost struct {//Comment represents an user comment on an posttype Comment struct {- ID int `json:"id"`- Content string `json:"content"`- CreatedAt time.Time `json:"createdAt"`- User *User `json:"user"`- EditedAt *time.Time `json:"editedAt,omitempty"`- EditedBy *User `json:"editedBy,omitempty"`+ ID int `json:"id"`+ Content string `json:"content"`+ CreatedAt time.Time `json:"createdAt"`+ User *User `json:"user"`+ Attachments []string `json:"attachments,omitempty"`+ EditedAt *time.Time `json:"editedAt,omitempty"`+ EditedBy *User `json:"editedBy,omitempty"`}//Tag represents a simple tagdiff --git a/app/storage/postgres/post.go b/app/storage/postgres/post.goindex 4d65ea47c..e64c1cdf5 100644--- a/app/storage/postgres/post.go+++ b/app/storage/postgres/post.go@@ -74,20 +74,22 @@ func (i *dbPost) toModel(ctx storage.Context) *models.Post {}type dbComment struct {- ID int `db:"id"`- Content string `db:"content"`- CreatedAt time.Time `db:"created_at"`- User *dbUser `db:"user"`- EditedAt dbx.NullTime `db:"edited_at"`- EditedBy *dbUser `db:"edited_by"`+ ID int `db:"id"`+ Content string `db:"content"`+ CreatedAt time.Time `db:"created_at"`+ User *dbUser `db:"user"`+ Attachments []string `db:"attachment_bkeys"`+ EditedAt dbx.NullTime `db:"edited_at"`+ EditedBy *dbUser `db:"edited_by"`}func (c *dbComment) toModel(ctx storage.Context) *models.Comment {comment := &models.Comment{- ID: c.ID,- Content: c.Content,- CreatedAt: c.CreatedAt,- User: c.User.toModel(ctx),+ ID: c.ID,+ Content: c.Content,+ CreatedAt: c.CreatedAt,+ User: c.User.toModel(ctx),+ Attachments: c.Attachments,}if c.EditedAt.Valid {comment.EditedBy = c.EditedBy.toModel(ctx)@@ -369,7 +371,21 @@ func (s *PostStorage) Search(query, view, limit string, tags []string) ([]*modelfunc (s *PostStorage) GetCommentsByPost(post *models.Post) ([]*models.Comment, error) {comments := []*dbComment{}err := s.trx.Select(&comments,- `SELECT c.id,+ `WITH agg_attachments AS (+ SELECT+ c.id as comment_id,+ ARRAY_REMOVE(ARRAY_AGG(at.attachment_bkey), NULL) as attachment_bkeys+ FROM attachments at+ INNER JOIN comments c+ ON at.tenant_id = c.tenant_id+ AND at.post_id = c.post_id+ AND at.comment_id = c.id+ WHERE at.post_id = $1+ AND at.tenant_id = $2+ AND at.comment_id IS NOT NULL+ GROUP BY c.id+ )+ SELECT c.id,c.content,c.created_at,c.edited_at,@@ -386,7 +402,8 @@ func (s *PostStorage) GetCommentsByPost(post *models.Post) ([]*models.Comment, ee.role AS edited_by_role,e.status AS edited_by_status,e.avatar_type AS edited_by_avatar_type,- e.avatar_bkey AS edited_by_avatar_bkey+ e.avatar_bkey AS edited_by_avatar_bkey,+ at.attachment_bkeysFROM comments cINNER JOIN posts pON p.id = c.post_id@@ -397,6 +414,8 @@ func (s *PostStorage) GetCommentsByPost(post *models.Post) ([]*models.Comment, eLEFT JOIN users eON e.id = c.edited_by_idAND e.tenant_id = c.tenant_id+ LEFT JOIN agg_attachments at+ ON at.comment_id = c.idWHERE p.id = $1AND p.tenant_id = $2AND c.deleted_at IS NULLdiff --git a/public/models/post.ts b/public/models/post.tsindex 3e5082108..7be85d56b 100644--- a/public/models/post.ts+++ b/public/models/post.ts@@ -69,6 +69,7 @@ export interface Comment {content: string;createdAt: string;user: User;+ attachments?: string[];editedAt?: string;editedBy?: User;}diff --git a/public/pages/ShowPost/components/CommentInput.tsx b/public/pages/ShowPost/components/CommentInput.tsxindex 15ecd79b2..96185b67b 100644--- a/public/pages/ShowPost/components/CommentInput.tsx+++ b/public/pages/ShowPost/components/CommentInput.tsx@@ -1,7 +1,7 @@import React from "react";-import { Post } from "@fider/models";-import { Avatar, UserName, Button, TextArea, Form } from "@fider/components/common";+import { Post, ImageUpload } from "@fider/models";+import { Avatar, UserName, Button, TextArea, Form, MultiImageUploader } from "@fider/components/common";import { SignInModal } from "@fider/components";import { cache, actions, Failure, Fider } from "@fider/services";@@ -14,6 +14,7 @@ interface CommentInputState {content: string;error?: Failure;showSignIn: boolean;+ attachments: ImageUpload[];}const CACHE_TITLE_KEY = "CommentInput-Comment-";@@ -26,7 +27,8 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInputhis.state = {content: (Fider.session.isAuthenticated && cache.session.get(this.getCacheKey())) || "",- showSignIn: false+ showSignIn: false,+ attachments: []};}@@ -39,12 +41,16 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInputhis.setState({ content });};+ private setAttachments = (attachments: ImageUpload[]) => {+ this.setState({ attachments });+ };+public submit = async () => {this.setState({error: undefined});- const result = await actions.createComment(this.props.post.number, this.state.content);+ const result = await actions.createComment(this.props.post.number, this.state.content, this.state.attachments);if (result.ok) {cache.session.remove(this.getCacheKey());location.reload();@@ -83,6 +89,14 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInpuonFocus={this.handleOnFocus}inputRef={this.setInputRef}/>+ {this.state.content && (+ <MultiImageUploader+ field="attachments"+ maxUploads={2}+ previewMaxWidth={100}+ onChange={this.setAttachments}+ />+ )}{this.state.content && (<Button color="positive" onClick={this.submit}>Submitdiff --git a/public/pages/ShowPost/components/ShowComment.tsx b/public/pages/ShowPost/components/ShowComment.tsxindex 8ee202d15..be31b68f3 100644--- a/public/pages/ShowPost/components/ShowComment.tsx+++ b/public/pages/ShowPost/components/ShowComment.tsx@@ -1,5 +1,5 @@import React from "react";-import { Comment, Post } from "@fider/models";+import { Comment, Post, ImageUpload } from "@fider/models";import {Avatar,UserName,@@ -10,7 +10,9 @@ import {MultiLineText,DropDown,DropDownItem,- Modal+ Modal,+ ImageViewer,+ MultiImageUploader} from "@fider/components";import { formatDate, Failure, actions, Fider } from "@fider/services";import { FaEllipsisH } from "react-icons/fa";@@ -24,6 +26,7 @@ interface ShowCommentState {comment: Comment;isEditing: boolean;newContent: string;+ attachments: ImageUpload[];error?: Failure;showDeleteConfirmation: boolean;}@@ -35,7 +38,8 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentStcomment: props.comment,isEditing: false,newContent: "",- showDeleteConfirmation: false+ showDeleteConfirmation: false,+ attachments: []};}@@ -55,15 +59,14 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentSt};private saveEdit = async () => {- const response = await actions.updateComment(this.props.post.number, this.state.comment.id, this.state.newContent);+ const response = await actions.updateComment(+ this.props.post.number,+ this.state.comment.id,+ this.state.newContent,+ this.state.attachments+ );if (response.ok) {- this.state.comment.content = this.state.newContent;- this.state.comment.editedAt = new Date().toISOString();- this.state.comment.editedBy = Fider.session.user;- this.setState({- comment: this.state.comment- });- this.cancelEdit();+ location.reload();} else {this.setState({ error: response.error });}@@ -73,6 +76,10 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentStthis.setState({ newContent });};+ private setAttachments = (attachments: ImageUpload[]) => {+ this.setState({ attachments });+ };+private renderEllipsis = () => {return <FaEllipsisH />;};@@ -162,6 +169,13 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentStplaceholder={c.content}onChange={this.setNewContent}/>+ <MultiImageUploader+ field="attachments"+ bkeys={c.attachments}+ maxUploads={2}+ previewMaxWidth={100}+ onChange={this.setAttachments}+ /><Button size="tiny" onClick={this.saveEdit} color="positive">Save</Button>@@ -170,7 +184,10 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentSt</Button></Form>) : (- <MultiLineText text={c.content} style="simple" />+ <>+ <MultiLineText text={c.content} style="simple" />+ {c.attachments && c.attachments.map(x => <ImageViewer key={x} bkey={x} />)}+ </>)}</div></div>diff --git a/public/services/actions/post.ts b/public/services/actions/post.tsindex 3fa986a08..3352e7138 100644--- a/public/services/actions/post.ts+++ b/public/services/actions/post.ts@@ -51,13 +51,24 @@ export const listVotes = async (postNumber: number): Promise<Result<Vote[]>> =>return http.get<Vote[]>(`/api/v1/posts/${postNumber}/votes`);};-export const createComment = async (postNumber: number, content: string): Promise<Result> => {- return http.post(`/api/v1/posts/${postNumber}/comments`, { content }).then(http.event("comment", "create"));+export const createComment = async (+ postNumber: number,+ content: string,+ attachments: ImageUpload[]+): Promise<Result> => {+ return http+ .post(`/api/v1/posts/${postNumber}/comments`, { content, attachments })+ .then(http.event("comment", "create"));};-export const updateComment = async (postNumber: number, commentID: number, content: string): Promise<Result> => {+export const updateComment = async (+ postNumber: number,+ commentID: number,+ content: string,+ attachments: ImageUpload[]+): Promise<Result> => {return http- .put(`/api/v1/posts/${postNumber}/comments/${commentID}`, { content })+ .put(`/api/v1/posts/${postNumber}/comments/${commentID}`, { content, attachments }).then(http.event("comment", "update"));};