Open platform to collect and prioritize feedback
allow signed user to post ideas
goenningc5a335a7ad09
diff --git a/app/router.go b/app/router.goindex 675e854d0..5692094da 100644--- a/app/router.go+++ b/app/router.go@@ -29,9 +29,8 @@ type WechyServices struct {}func errorHandler(e error, c echo.Context) {- c.Logger().Debug(e)-if strings.Contains(e.Error(), "code=404") {+ c.Logger().Debug(e)c.Render(http.StatusNotFound, "404.html", echo.Map{})} else {c.Logger().Error(e)diff --git a/feedback/handler.go b/feedback/handler.goindex c4219c154..46d03c30a 100644--- a/feedback/handler.go+++ b/feedback/handler.go@@ -1,6 +1,8 @@package feedbackimport (+ "net/http"+"github.com/WeCanHearYou/wechy/identity""github.com/labstack/echo")@@ -27,20 +29,27 @@ func (h IndexHandlder) List() echo.HandlerFunc {}}-type newIdea struct {- Title string `json:"title"`+type newIdeaInput struct {+ Title string `json:"title"`+ Description string `json:"description"`}// Post creates a new idea on current tenantfunc (h IndexHandlder) Post() echo.HandlerFunc {return func(c echo.Context) error {- idea := new(newIdea)- c.Bind(idea)+ input := new(newIdeaInput)+ c.Bind(input)++ tenant := c.Get("Tenant").(*identity.Tenant)+ claims := c.Get("Claims").(*identity.WechyClaims)++ idea, err := h.ideaService.Save(tenant.ID, claims.UserID, input.Title, input.Description)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, err)+ }return c.JSON(200, echo.Map{- "tenant": c.Get("Tenant"),- "claims": c.Get("Claims"),- "idea": idea.Title,+ "idea": idea,})}}diff --git a/feedback/handler_test.go b/feedback/handler_test.goindex bb9265be5..427376a57 100644--- a/feedback/handler_test.go+++ b/feedback/handler_test.go@@ -15,6 +15,10 @@ func (svc mockIdeaService) GetAll(tenantID int64) ([]*feedback.Idea, error) {return make([]*feedback.Idea, 0), nil}+func (svc mockIdeaService) Save(tenantID, userID int64, title, description string) (*feedback.Idea, error) {+ return nil, nil+}+func TestIndexHandler(t *testing.T) {RegisterTestingT(t)diff --git a/feedback/model.go b/feedback/model.goindex 7a47fbf5f..c9738becb 100644--- a/feedback/model.go+++ b/feedback/model.go@@ -1,8 +1,13 @@package feedback+import (+ "time"+)+//Idea represents an idea on a tenant boardtype Idea struct {- ID int64 `json:"id"`- Title string `json:"title"`- Description string `json:"description"`+ ID int64 `json:"id"`+ Title string `json:"title"`+ Description string `json:"description"`+ CreatedOn time.Time `json:"createdOn"`}diff --git a/feedback/service.go b/feedback/service.goindex e8761681c..984a79f42 100644--- a/feedback/service.go+++ b/feedback/service.go@@ -3,4 +3,5 @@ package feedback// IdeaService contains read and write operations for ideastype IdeaService interface {GetAll(tenantID int64) ([]*Idea, error)+ Save(tenantID, userID int64, title, description string) (*Idea, error)}diff --git a/migrations/201703172030_add_ideas_userid.up.sql b/migrations/201703172030_add_ideas_userid.up.sqlnew file mode 100644index 000000000..86033b041--- /dev/null+++ b/migrations/201703172030_add_ideas_userid.up.sql@@ -0,0 +1 @@+alter table ideas add user_id int REFERENCES users (id)\ No newline at end of filediff --git a/migrations/201703172115_remove_col_defaults.up.sql b/migrations/201703172115_remove_col_defaults.up.sqlnew file mode 100644index 000000000..877e1452f--- /dev/null+++ b/migrations/201703172115_remove_col_defaults.up.sql@@ -0,0 +1,5 @@+alter table ideas drop column modified_on;+alter table ideas alter column created_on drop default;++alter table users drop column modified_on;+alter table users alter column created_on drop default;\ No newline at end of filediff --git a/package.json b/package.jsonindex 2bb31b173..8b9c7d741 100644--- a/package.json+++ b/package.json@@ -13,12 +13,14 @@"dependencies": {"axios": "^0.15.3","jquery": "^3.2.0",+ "moment": "^2.17.1","react": "^15.4.2","react-dom": "^15.4.2","semantic-ui-css": "^2.2.9"},"devDependencies": {"@types/jquery": "^2.0.41",+ "@types/moment": "^2.13.0","@types/react": "^15.0.16","@types/react-dom": "^0.14.23","clean-webpack-plugin": "^0.1.16",diff --git a/postgres/feedback.go b/postgres/feedback.goindex 37207db72..5ef11aa10 100644--- a/postgres/feedback.go+++ b/postgres/feedback.go@@ -3,6 +3,8 @@ package postgresimport ("database/sql"+ "time"+"github.com/WeCanHearYou/wechy/feedback")@@ -13,7 +15,7 @@ type IdeaService struct {// GetAll returns all tenant ideasfunc (svc IdeaService) GetAll(tenantID int64) ([]*feedback.Idea, error) {- rows, err := svc.DB.Query("SELECT id, title, description FROM ideas WHERE tenant_id = $1", tenantID)+ rows, err := svc.DB.Query("SELECT id, title, description, created_on FROM ideas WHERE tenant_id = $1", tenantID)if err != nil {return nil, err}@@ -21,9 +23,28 @@ func (svc IdeaService) GetAll(tenantID int64) ([]*feedback.Idea, error) {var ideas []*feedback.Ideafor rows.Next() {idea := &feedback.Idea{}- rows.Scan(&idea.ID, &idea.Title, &idea.Description)+ rows.Scan(&idea.ID, &idea.Title, &idea.Description, &idea.CreatedOn)ideas = append(ideas, idea)}return ideas, nil}++// Save a new idea in the database+func (svc IdeaService) Save(tenantID, userID int64, title, description string) (*feedback.Idea, error) {+ tx, err := svc.DB.Begin()+ if err != nil {+ return nil, err+ }++ idea := new(feedback.Idea)+ idea.Title = title+ idea.Description = description++ if err = tx.QueryRow("INSERT INTO ideas (title, description, tenant_id, user_id, created_on) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id", title, description, tenantID, userID, time.Now()).Scan(&idea.ID); err != nil {+ tx.Rollback()+ return nil, err+ }++ return idea, tx.Commit()+}diff --git a/postgres/feedback_test.go b/postgres/feedback_test.goindex 88c324334..ee5e63462 100644--- a/postgres/feedback_test.go+++ b/postgres/feedback_test.go@@ -3,6 +3,7 @@ package postgres_testimport ("database/sql/driver""testing"+ "time"sqlmock "gopkg.in/DATA-DOG/go-sqlmock.v1"@@ -32,17 +33,18 @@ func TestIdeaService_GetAll(t *testing.T) {db, mock, _ := sqlmock.New()defer db.Close()- rows := sqlmock.NewRows([]string{"id", "title", "description"})- rows.AddRow(1, "Idea #1", "Description #1")- rows.AddRow(2, "Idea #2", "Description #2")+ now := time.Now()+ rows := sqlmock.NewRows([]string{"id", "title", "description", "created_on"})+ rows.AddRow(1, "Idea #1", "Description #1", now)+ rows.AddRow(2, "Idea #2", "Description #2", now)- mock.ExpectQuery("SELECT id, title, description FROM ideas WHERE tenant_id = \\$1").WithArgs(2134).WillReturnRows(rows)+ mock.ExpectQuery("SELECT id, title, description, created_on FROM ideas WHERE tenant_id = \\$1").WithArgs(2134).WillReturnRows(rows)svc := &postgres.IdeaService{DB: db}ideas, err := svc.GetAll(2134)Expect(ideas).To(HaveLen(2))- Expect(ideas[0]).To(Equal(&feedback.Idea{ID: 1, Title: "Idea #1", Description: "Description #1"}))- Expect(ideas[1]).To(Equal(&feedback.Idea{ID: 2, Title: "Idea #2", Description: "Description #2"}))+ Expect(ideas[0]).To(Equal(&feedback.Idea{ID: 1, Title: "Idea #1", Description: "Description #1", CreatedOn: now}))+ Expect(ideas[1]).To(Equal(&feedback.Idea{ID: 2, Title: "Idea #2", Description: "Description #2", CreatedOn: now}))Expect(err).To(BeNil())}diff --git a/postgres/helpers_test.go b/postgres/helpers_test.gonew file mode 100644index 000000000..7ca34b505--- /dev/null+++ b/postgres/helpers_test.go@@ -0,0 +1,14 @@+package postgres_test++import (+ "database/sql/driver"+ "time"+)++type AnyTime struct{}++// Match satisfies sqlmock.Argument interface+func (a AnyTime) Match(v driver.Value) bool {+ _, ok := v.(time.Time)+ return ok+}diff --git a/postgres/identity.go b/postgres/identity.goindex e4431c0f9..6c9706dd1 100644--- a/postgres/identity.go+++ b/postgres/identity.go@@ -3,6 +3,7 @@ package postgresimport ("database/sql""strings"+ "time""github.com/WeCanHearYou/wechy/identity""github.com/WeCanHearYou/wechy/toolbox/env"@@ -32,7 +33,7 @@ func (svc UserService) Register(user *identity.User) error {return err}- if err = tx.QueryRow("INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id", user.Name, user.Email).Scan(&user.ID); err != nil {+ if err = tx.QueryRow("INSERT INTO users (name, email, created_on) VALUES ($1, $2, $3) RETURNING id", user.Name, user.Email, time.Now()).Scan(&user.ID); err != nil {tx.Rollback()return err}diff --git a/postgres/identity_test.go b/postgres/identity_test.goindex 9657601be..1bcc546b8 100644--- a/postgres/identity_test.go+++ b/postgres/identity_test.go@@ -57,8 +57,8 @@ func TestUserService_Register(t *testing.T) {mock.ExpectBegin()- query := mock.ExpectQuery("INSERT INTO users \\(name, email\\) VALUES \\(\\$1, \\$2\\) RETURNING id")- query.WithArgs("Jon Snow", "[email protected]")+ query := mock.ExpectQuery("INSERT INTO users \\(name, email, created_on\\) VALUES \\(\\$1, \\$2, \\$3\\) RETURNING id")+ query.WithArgs("Jon Snow", "[email protected]", AnyTime{})query.WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(int64(300)))exec := mock.ExpectExec("INSERT INTO user_providers \\(user_id, provider, provider_uid\\) VALUES \\(\\$1, \\$2, \\$3\\)")@@ -92,8 +92,8 @@ func TestUserService_Register_MultipleProviders(t *testing.T) {mock.ExpectBegin()- query := mock.ExpectQuery("INSERT INTO users \\(name, email\\) VALUES \\(\\$1, \\$2\\) RETURNING id")- query.WithArgs("Jon Snow", "[email protected]")+ query := mock.ExpectQuery("INSERT INTO users \\(name, email, created_on\\) VALUES \\(\\$1, \\$2, \\$3\\) RETURNING id")+ query.WithArgs("Jon Snow", "[email protected]", AnyTime{})query.WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(int64(300)))exec := mock.ExpectExec("INSERT INTO user_providers \\(user_id, provider, provider_uid\\) VALUES \\(\\$1, \\$2, \\$3\\)")diff --git a/public/components/IdeaInput.tsx b/public/components/IdeaInput.tsxindex 98e9e7b85..741b05a8e 100644--- a/public/components/IdeaInput.tsx+++ b/public/components/IdeaInput.tsx@@ -6,51 +6,65 @@ const claims = (window as any)._claims;interface IdeaInputState {idea: string;+ clicked: boolean;}export class IdeaInput extends React.Component<{}, IdeaInputState> {+ private description: HTMLTextAreaElement;constructor() {super();- this.state = { idea: "" };+ this.state = {+ idea: "",+ clicked: false+ };}public async submit() {+ this.setState({ clicked: true });+const response = await axios.post("/api/ideas", {- title: this.state.idea+ title: this.state.idea,+ description: this.description.value});++ location.reload();}public render() {+ const buttonClasses = `ui positive button ${this.state.clicked && "loading disabled"}`;const details = claims ?- <button className="ui positive button" onClick={async () => { await this.submit(); } }>- Submit Idea- </button> :<div>- <p>Please log in before posting an idea...</p>- <div className="ui list">- <div className="item">- <SocialSignInButton provider="facebook"/>+ <div className="field">+ <textarea ref={(ref) => this.description = ref }+ rows={6}+ placeholder="Describe your idea (optional)"></textarea></div>- <div className="item">- <SocialSignInButton provider="google"/>+ <button className={buttonClasses} onClick={async () => { await this.submit(); } }>+ Submit Idea+ </button>+ </div> :+ <div>+ <div className="ui message">+ <div className="header">+ Please log in before posting an idea</div>+ <p>This only takes a second and you'll be good to go!</p>+ <SocialSignInButton provider="facebook" small={true} />+ <SocialSignInButton provider="google" small={true} /></div></div>;- return <div>+ return <div className="ui form"><div className="ui fluid input"><input id="new-idea-input"type="text"+ maxLength={60}onKeyUp={(e) => { this.setState({ idea: e.currentTarget.value }); }}placeholder="Enter your idea, new feature or suggestion here ..." /></div>- <div id="new-idea-submit" className="ui grid">- <div className="four wide column">- { this.state.idea.length > 0 && details }- </div>- </div>+ { this.state.idea.length > 0 && details }</div>;}}diff --git a/public/components/Root.tsx b/public/components/Root.tsxindex 9851cb87e..c6c2a8e45 100644--- a/public/components/Root.tsx+++ b/public/components/Root.tsx@@ -1,3 +1,4 @@+import * as moment from "moment";import * as React from "react";import { Footer } from "./Footer";@@ -14,15 +15,12 @@ export class Root extends React.Component<{}, {}> {<div className="item" key={x.id}><div className="content"><a className="header">{ x.title }</a>- <div className="meta">- <span className="cinema">Union Square 14</span>- </div><div className="description"><p>{ x.title }</p></div><div className="extra">- <div className="ui label">IMAX</div>- <div className="ui label">Additional Languages</div>+ <i className="calendar icon"></i>+ shared { moment(x.createdOn).fromNow() }</div></div></div>);diff --git a/public/components/SocialSignInButton.tsx b/public/components/SocialSignInButton.tsxindex aa96c9454..5e3a1fce3 100644--- a/public/components/SocialSignInButton.tsx+++ b/public/components/SocialSignInButton.tsx@@ -4,6 +4,7 @@ const authEndpoint = (window as any)._authEndpoint;interface SocialSignInButtonProps {provider: string;+ small?: boolean;}interface SocialSignInButtonState {clicked: boolean;@@ -21,11 +22,20 @@ export class SocialSignInButton extends React.Component<SocialSignInButtonProps,const providerClassName = this.props.provider === "google" ? "google plus" : "facebook";const providerDisplayName = this.props.provider === "google" ? "Google" : "Facebook";const oauthUrl = `${authEndpoint}/oauth/${this.props.provider}?redirect=${location.href}`;- const cssClasses = `${providerClassName} ui fluid button ${this.state.clicked ? "loading" : ""}`;+ const cssClasses = `ui button+ ${providerClassName}+ ${this.state.clicked ? "loading disabled" : ""}+ ${this.props.small ? "circular icon" : "fluid"}`;- return <a href={oauthUrl} className={cssClasses} onClick={() => this.setState({clicked: true})}>- <i className={providerClassName + " icon"}></i>- Sign in with { providerDisplayName }- </a>;+ if (this.props.small) {+ return <a href={oauthUrl} className={cssClasses} onClick={() => this.setState({clicked: true})}>+ <i className={providerClassName + " icon"}></i>+ </a>;+ } else {+ return <a href={oauthUrl} className={cssClasses} onClick={() => this.setState({clicked: true})}>+ <i className={providerClassName + " icon"}></i>+ Sign in with { providerDisplayName }+ </a>;+ }}}