Open platform to collect and prioritize feedback
Allow members to update idea's title and description (#157)
Guilherme Oenningbd1097cfbbd4
diff --git a/app/actions/idea.go b/app/actions/idea.goindex 9754e8d4d..a31a8f5df 100644--- a/app/actions/idea.go+++ b/app/actions/idea.go@@ -39,6 +39,42 @@ func (input *CreateNewIdea) Validate(services *app.Services) *validate.Result {return result}+// UpdateIdea is used to edit an existing new idea+type UpdateIdea struct {+ Model *models.UpdateIdea+}++// Initialize the model+func (input *UpdateIdea) Initialize() interface{} {+ input.Model = new(models.UpdateIdea)+ return input.Model+}++// IsAuthorized returns true if current user is authorized to perform this action+func (input *UpdateIdea) IsAuthorized(user *models.User) bool {+ return user != nil && user.IsCollaborator()+}++// Validate is current model is valid+func (input *UpdateIdea) Validate(services *app.Services) *validate.Result {+ result := validate.Success()++ if input.Model.Title == "" {+ result.AddFieldFailure("title", "Title is required.")+ }++ if len(input.Model.Title) < 10 || len(strings.Split(input.Model.Title, " ")) < 3 {+ result.AddFieldFailure("title", "Title needs to be more descriptive.")+ }++ _, err := services.Ideas.GetByNumber(input.Model.Number)+ if err != nil {+ return validate.Error(err)+ }++ return result+}+// AddNewComment represents a new comment to be addedtype AddNewComment struct {Model *models.NewCommentdiff --git a/app/handlers/idea.go b/app/handlers/idea.goindex 300fc1cfa..bcb74aee7 100644--- a/app/handlers/idea.go+++ b/app/handlers/idea.go@@ -45,27 +45,17 @@ func PostIdea() web.HandlerFunc {// UpdateIdea updates an existing ideaof current tenantfunc UpdateIdea() web.HandlerFunc {return func(c web.Context) error {- number, err := c.ParamAsInt("number")- if err != nil {- return c.Failure(err)- }-- input := new(actions.CreateNewIdea)+ input := new(actions.UpdateIdea)if result := c.BindTo(input); !result.Ok {return c.HandleValidation(result)}- idea, err := c.Services().Ideas.GetByNumber(number)- if idea.CanBeChangedBy(c.User()) {- idea, err = c.Services().Ideas.Update(number, input.Model.Title, input.Model.Description)- if err != nil {- return c.Failure(err)- }- } else {- return c.Unauthorized()+ _, err := c.Services().Ideas.Update(input.Model.Number, input.Model.Title, input.Model.Description)+ if err != nil {+ return c.Failure(err)}- return c.Ok(idea)+ return c.Ok(web.Map{})}}diff --git a/app/handlers/idea_test.go b/app/handlers/idea_test.goindex b9d87908f..62acf07d8 100644--- a/app/handlers/idea_test.go+++ b/app/handlers/idea_test.go@@ -79,7 +79,7 @@ func TestPostIdeaHandler_WithoutTitle(t *testing.T) {Expect(err).NotTo(BeNil())}-func TestUpdateIdeaHandler_IdeaOwner(t *testing.T) {+func TestUpdateIdeaHandler_TenantStaff(t *testing.T) {RegisterTestingT(t)server, services := mock.NewServer()@@ -87,7 +87,7 @@ func TestUpdateIdeaHandler_IdeaOwner(t *testing.T) {code, _ := server.OnTenant(mock.DemoTenant).- AsUser(mock.AryaStark).+ AsUser(mock.JonSnow).AddParam("number", idea.Number).ExecutePost(handlers.UpdateIdea(), `{ "title": "the new title", "description": "new description" }`)@@ -97,25 +97,22 @@ func TestUpdateIdeaHandler_IdeaOwner(t *testing.T) {Expect(idea.Description).To(Equal("new description"))}-func TestUpdateIdeaHandler_TenantStaff(t *testing.T) {+func TestUpdateIdeaHandler_NonAuthorized(t *testing.T) {RegisterTestingT(t)server, services := mock.NewServer()- idea, _ := services.Ideas.Add("My First Idea", "With a description", mock.AryaStark.ID)+ idea, _ := services.Ideas.Add("My First Idea", "With a description", mock.JonSnow.ID)code, _ := server.OnTenant(mock.DemoTenant).- AsUser(mock.JonSnow).+ AsUser(mock.AryaStark).AddParam("number", idea.Number).ExecutePost(handlers.UpdateIdea(), `{ "title": "the new title", "description": "new description" }`)- idea, _ = services.Ideas.GetByNumber(idea.Number)- Expect(code).To(Equal(200))- Expect(idea.Title).To(Equal("the new title"))- Expect(idea.Description).To(Equal("new description"))+ Expect(code).To(Equal(http.StatusForbidden))}-func TestUpdateIdeaHandler_NonAuthorized(t *testing.T) {+func TestUpdateIdeaHandler_InvalidTitle(t *testing.T) {RegisterTestingT(t)server, services := mock.NewServer()@@ -123,11 +120,25 @@ func TestUpdateIdeaHandler_NonAuthorized(t *testing.T) {code, _ := server.OnTenant(mock.DemoTenant).- AsUser(mock.AryaStark).+ AsUser(mock.JonSnow).AddParam("number", idea.Number).- ExecutePost(handlers.UpdateIdea(), `{ "title": "the new title", "description": "new description" }`)+ ExecutePost(handlers.UpdateIdea(), `{ "title": "", "description": "" }`)- Expect(code).To(Equal(http.StatusForbidden))+ Expect(code).To(Equal(http.StatusBadRequest))+}++func TestUpdateIdeaHandler_InvalidIdea(t *testing.T) {+ RegisterTestingT(t)++ server, _ := mock.NewServer()++ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ AddParam("number", 999).+ ExecutePost(handlers.UpdateIdea(), `{ "title": "This is a good title!", "description": "And description too..." }`)++ Expect(code).To(Equal(http.StatusNotFound))}func TestPostCommentHandler(t *testing.T) {diff --git a/app/models/feedback.go b/app/models/feedback.goindex 91638ff46..0f608f0ff 100644--- a/app/models/feedback.go+++ b/app/models/feedback.go@@ -19,17 +19,19 @@ type Idea struct {Response *IdeaResponse `json:"response"`}-//CanBeChangedBy returns true if given user can change this idea-func (i *Idea) CanBeChangedBy(user *User) bool {- return user.IsCollaborator() || i.User.ID == user.ID-}-// NewIdea represents a new ideatype NewIdea struct {Title string `json:"title"`Description string `json:"description"`}+// UpdateIdea represents a request to edit an existing idea+type UpdateIdea struct {+ Number int `route:"number"`+ Title string `json:"title"`+ Description string `json:"description"`+}+// NewComment represents a new commenttype NewComment struct {Number int `route:"number"`diff --git a/main.go b/main.goindex 9ef4d5d9a..e58ba3cfa 100644--- a/main.go+++ b/main.go@@ -13,7 +13,7 @@ import ()var buildtime string-var version = "0.7.0"+var version = "0.8.0-beta"func main() {fmt.Printf("Application is starting...\n")diff --git a/public/assets/styles/main.scss b/public/assets/styles/main.scssindex ab8565813..2c60a2bf7 100644--- a/public/assets/styles/main.scss+++ b/public/assets/styles/main.scss@@ -6,6 +6,10 @@text-align: center;}+.ui.button.text-left {+ text-align: left;+}+body {background-color: $bg-color;}@@ -180,7 +184,10 @@ code {}}-.ui[class*="bottom pointing"].label:before, .ui[class*="pointing below"].label:before {+.ui[class*="top pointing"].label:before,+.ui[class*="pointing above"].label:before ,+.ui[class*="bottom pointing"].label:before,+.ui[class*="pointing below"].label:before {left: 20px;}@@ -207,6 +214,12 @@ code {border-right: none;border-top: none;}++ &.above {+ border-left: none;+ border-right: none;+ border-bottom: none;+ }}.signin-message {diff --git a/public/components/ResponseForm.tsx b/public/components/ResponseForm.tsxindex a4ccc9cb1..a6784f141 100644--- a/public/components/ResponseForm.tsx+++ b/public/components/ResponseForm.tsx@@ -54,7 +54,9 @@ export class ResponseForm extends React.Component<ResponseFormProps, ResponseFor}public render() {- const button = <Button className="primary" onClick={async () => this.showModal()}>Respond</Button>;+ const button = <Button className="icon fluid text-left" onClick={async () => this.showModal()}>+ <i className="announcement icon"></i> Respond+ </Button>;const modal = <div className="ui form modal" ref={(e) => this.modal = e! }>diff --git a/public/components/common/DisplayError.tsx b/public/components/common/DisplayError.tsxindex 9e8ec9e6c..332a76193 100644--- a/public/components/common/DisplayError.tsx+++ b/public/components/common/DisplayError.tsx@@ -6,6 +6,7 @@ const arrayToTag = (items: string[]) => {};interface DisplayErrorProps {+ pointing?: 'above' | 'below';error?: Failure;fields?: string[];}@@ -15,6 +16,8 @@ export const DisplayError = (props: DisplayErrorProps) => {return <div></div>;}+ const pointing = props.pointing || 'below';+let items: JSX.Element[] = [];if (props.error.messages && !props.fields) {@@ -28,7 +31,7 @@ export const DisplayError = (props: DisplayErrorProps) => {}}- return items.length > 0 ? <div className="display-error ui pointing below red basic label">+ return items.length > 0 ? <div className={`display-error ui pointing ${pointing} red basic label`}><ul>{ items }</ul></div> : null;};diff --git a/public/pages/site/ShowIdeaPage.scss b/public/pages/site/ShowIdeaPage.scssindex fa891f06c..392e5f3e8 100644--- a/public/pages/site/ShowIdeaPage.scss+++ b/public/pages/site/ShowIdeaPage.scss@@ -1,5 +1,6 @@#fdr-show-idea-page {.idea-header {+ width: 100%;h1 {font-weight: 400;margin: 0px;diff --git a/public/pages/site/ShowIdeaPage.tsx b/public/pages/site/ShowIdeaPage.tsxindex ca3546468..17d2d06a5 100644--- a/public/pages/site/ShowIdeaPage.tsx+++ b/public/pages/site/ShowIdeaPage.tsx@@ -7,14 +7,22 @@ import { CommentInput } from '@fider/components/CommentInput';import { ResponseForm } from '@fider/components/ResponseForm';import { SupportCounter } from '@fider/components/SupportCounter';import { ShowIdeaResponse } from '@fider/components/ShowIdeaResponse';-import { Button, UserName, Gravatar, Moment, MultiLineText, Footer, Header, SocialSignInButton } from '@fider/components/common';+import { DisplayError, Button, UserName, Gravatar, Moment, Form, MultiLineText, Footer, Header, SocialSignInButton } from '@fider/components/common';+import Textarea from 'react-textarea-autosize';import { inject, injectables } from '@fider/di';-import { Session } from '@fider/services';+import { Session, IdeaService, Failure } from '@fider/services';import './ShowIdeaPage.scss';-export class ShowIdeaPage extends React.Component<{}, {}> {+interface ShowIdeaPageState {+ editMode: boolean;+ newTitle: string;+ newDescription: string;+ error?: Failure;+}++export class ShowIdeaPage extends React.Component<{}, ShowIdeaPageState> {private user?: CurrentUser;private idea: Idea;private comments: Comment[];@@ -22,15 +30,42 @@ export class ShowIdeaPage extends React.Component<{}, {}> {@inject(injectables.Session)public session: Session;+ @inject(injectables.IdeaService)+ public ideaService: IdeaService;+constructor(props: {}) {super(props);this.user = this.session.getCurrentUser();this.idea = this.session.get<Idea>('idea');this.comments = this.session.getArray<Comment>('comments');++ this.state = {+ editMode: false,+ newTitle: this.idea.title,+ newDescription: this.idea.description+ };+setTitle(`${this.idea.title} · ${document.title}`);}+ private async saveChanges() {+ const result = await this.ideaService.updateIdea(this.idea.number, this.state.newTitle, this.state.newDescription);+ if (result.ok) {+ this.setState({+ error: undefined,+ editMode: false+ });+ this.idea.title = this.state.newTitle;+ this.idea.description = this.state.newDescription;+ this.forceUpdate();+ } else {+ this.setState({+ error: result.error+ });+ }+ }+public render() {const commentsList = this.comments.map((c) =>@@ -52,13 +87,21 @@ export class ShowIdeaPage extends React.Component<{}, {}> {<Header /><div className="page ui container"><div className="ui stackable grid container">- <div className="twelve wide column">+ <div className="thirteen wide column"><div className="ui items unstackable"><div className="item"><SupportCounter user={this.user} idea={this.idea} /><div className="idea-header">- <h1 className="ui header">{ this.idea.title }</h1>+ { this.state.editMode+ ? [+ <div key={1} className="ui input huge fluid">+ <input type="text" onChange={(e) => this.setState({ newTitle: e.currentTarget.value }) } defaultValue={ this.state.newTitle } />+ </div>,+ <DisplayError key={0} fields={['title']} pointing="above" error={this.state.error} />+ ]+ : <h1 className="ui header">{ this.idea.title }</h1>+ }<span className="info">Shared <Moment date={this.idea.createdOn} /> by <Gravatar user={ this.idea.user } /> <UserName user={this.idea.user} />@@ -69,7 +112,14 @@ export class ShowIdeaPage extends React.Component<{}, {}> {<span className="subtitle">Description</span>{- this.idea.description+ this.state.editMode+ ? <div className="ui form">+ <div className="field">+ <DisplayError fields={['description']} error={this.state.error} />+ <Textarea onChange={(e) => this.setState({ newDescription: e.currentTarget.value }) } defaultValue={ this.state.newDescription } />+ </div>+ </div>+ : this.idea.description? <MultiLineText className="description" text={ this.idea.description } style="simple" />: <p className="description">This idea doesn't have a description.</p>}@@ -80,13 +130,37 @@ export class ShowIdeaPage extends React.Component<{}, {}> {{this.session.isCollaborator() &&- <div className="four wide column">+ <div className="three wide column"><span className="subtitle">Actions</span>- <br /><br />- <ResponseForm idea={ this.idea } />+ { this.state.editMode && <div className="ui list">+ <div className="item">+ <Button className="positive icon fluid text-left" onClick={async () => this.saveChanges() }>+ <i className="save icon"></i> Save+ </Button>+ </div>+ <div className="item">+ <Button className="icon fluid text-left" onClick={async () => this.setState({ error: undefined, editMode: false }) }>+ <i className="cancel icon"></i> Cancel+ </Button>+ </div>+ </div>+ }++ { !this.state.editMode && <div className="ui list">+ <div className="item">+ <Button className="icon fluid text-left" onClick={async () => this.setState({ editMode: true }) }>+ <i className="edit icon"></i> Edit+ </Button>+ </div>+ <div className="item">+ <ResponseForm idea={ this.idea } />+ </div>+ </div>+ }</div>}+<div className="sixteen wide column"><div className="ui comments"><span className="subtitle">Discussion</span>diff --git a/public/services/IdeaService.ts b/public/services/IdeaService.tsindex ee6ae1757..7009692a1 100644--- a/public/services/IdeaService.ts+++ b/public/services/IdeaService.ts@@ -8,6 +8,7 @@ export interface IdeaService {addComment(ideaNumber: number, content: string): Promise<Result>;setResponse(ideaNumber: number, status: number, text: string): Promise<Result>;addIdea(title: string, description: string): Promise<Result<Idea>>;+ updateIdea(ideaNumber: number, title: string, description: string): Promise<Result>;}@injectable()@@ -31,4 +32,8 @@ export class HttpIdeaService implements IdeaService {public async addIdea(title: string, description: string): Promise<Result<Idea>> {return await post<Idea>(`/api/ideas`, { title, description });}++ public async updateIdea(ideaNumber: number, title: string, description: string): Promise<Result> {+ return await post(`/api/ideas/${ideaNumber}`, { title, description });+ }}diff --git a/routes.go b/routes.goindex c7254659d..4dba75935 100644--- a/routes.go+++ b/routes.go@@ -98,6 +98,7 @@ func GetMainEngine(settings *models.AppSettings) *web.Engine {private.Get("/settings", handlers.Page())private.Post("/api/ideas", handlers.PostIdea())+ private.Post("/api/ideas/:number", handlers.UpdateIdea())private.Post("/api/ideas/:number/comments", handlers.PostComment())private.Post("/api/ideas/:number/status", handlers.SetResponse())private.Post("/api/ideas/:number/support", handlers.AddSupporter())