Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Delete user #73

Merged
merged 10 commits into from
Sep 4, 2019
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/data.sql
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ CREATE TABLE charges (

CREATE TABLE questions (
id serial PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users (id),
user_id INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
question TEXT NOT NULL,
response TEXT,
responder INTEGER REFERENCES users (id),
Expand Down
2 changes: 1 addition & 1 deletion backend/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ class User {

static async findOne(id) {
const result = await db.query(
`SELECT email, is_admin, first_name, last_name, current_company, hire_date, needs, goals
`SELECT id, email, is_admin, first_name, last_name, current_company, hire_date, needs, goals
FROM users
WHERE id = $1`,
[id]
Expand Down
27 changes: 20 additions & 7 deletions frontend/src/AdminPanel.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,24 @@ class AdminPanel extends Component {
users = await ElevateApi.getUsers();
questions = await ElevateApi.getQuestions();
} catch(err) {
console.log(err)
return err;
}

this.setState({ users });
this.setState({ questions });
this.setState({ users, questions });
}

changeView = view => {
this.setState({ view });
// get update users after delete a user in AdminUserView
mvatanya marked this conversation as resolved.
Show resolved Hide resolved
updateUserState = (users) => {
this.setState({users})
}

updateViewState = (view) => {
this.setState({view})
}

changeView = (view) => {
this.setState({ view })
}

mediaQueryChanged = () => {
Expand All @@ -49,8 +58,7 @@ class AdminPanel extends Component {
this.setState({ sideBarOpen: !this.state.sideBarOpen });
}

getUserDetail = async evt => {
const userId = +evt.target.parentNode.firstElementChild.innerText;
getUserDetail = async (userId) => {
const user = await ElevateApi.getUser(userId);

this.setState({ view: 'userDetail', userDetail: user });
Expand All @@ -72,7 +80,12 @@ class AdminPanel extends Component {
getUserDetail={ this.getUserDetail }
view={ this.state.view } /> : null
}
{this.state.view === 'userDetail' ? <AdminUserView user={this.state.userDetail}/> : null }
{this.state.view === 'userDetail'
mvatanya marked this conversation as resolved.
Show resolved Hide resolved
? <AdminUserView
user={this.state.userDetail}
updateUserState={this.updateUserState}
updateViewState={this.updateViewState} />
: null }
</div>

<div className="admin-navbar">
Expand Down
101 changes: 84 additions & 17 deletions frontend/src/AdminPanel.test.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,86 @@
import React from 'react';
import axios from 'axios';
import { shallow, mount } from 'enzyme';
import toJson from "enzyme-to-json";
import AdminPanel from './AdminPanel';

describe('AdminPanel', function() {
jest.mock('axios');
const users = { data:
{ "users": [
{ "id": 1,
"first_name": "Test",
"last_name": "User",
"company": "Google",
"hire_date": "2018-06-23T07:00:00.000Z",
"needs": "Talk to financial advisor about salary/equity negotiations.",
"goals": "Increase in equity." },
{ "id": 2,
"first_name": "Admin",
"last_name": "User",
"company": "",
"hire_date": "2019-06-23T07:00:00.000Z",
"needs": "", "goals": "" }
]
}
}
const user = { data:
{"user":
{"id":1,
"email":"[email protected]",
"is_admin":false,
"first_name":"Test",
"last_name":"User",
"current_company":"Google",
"hire_date":"2018-06-23T07:00:00.000Z",
"needs":"Talk to financial advisor about salary/equity negotiations.",
"goals":"Increase in equity."}
}
}

const questions = { data:
{ "questions": [
{ "user_id": 1,
"first_name": "Test",
"last_name": "User",
"email": "[email protected]",
"question": "My employer didnt pay me!",
"created_date": "2019-09-01T19:28:53.468Z",
"resolved": false },
{ "user_id": 2,
"first_name": "Admin",
"last_name": "User",
"email": "[email protected]",
"question": "My employer wants to pay me too much!",
"created_date": "2019-09-01T19:28:53.468Z",
"resolved": false }
]
}
}

axios.get.mockImplementation((reqUrl) => {
if (reqUrl.includes('17')) {
mvatanya marked this conversation as resolved.
Show resolved Hide resolved
return user;
}
if (reqUrl.includes('users')) {
return users;
}
if (reqUrl.includes('questions')) {
return questions;
}
});

describe('AdminPanel', function () {
let wrapper;
let users = [{
id: 17,
email: "[email protected]",
is_admin: true,
first_name: "admin",
last_name: "test",
current_company:"testcompany",
hire_date: "2018-06-23",
needs:"To test user data",
goals:"Test pass"
id: 17,
email: "[email protected]",
is_admin: true,
first_name: "admin",
last_name: "test",
current_company: "testcompany",
hire_date: "2018-06-23",
needs: "To test user data",
goals: "Test pass"
}]
let questions = [{
user_id: 17,
Expand All @@ -26,15 +92,16 @@ describe('AdminPanel', function() {
created_date: "2019-08-29"
}]

beforeEach(() => {
beforeEach(async () => {
wrapper = mount(<AdminPanel />);
wrapper.setState ({ users, questions })
await wrapper.instance().componentDidMount
mvatanya marked this conversation as resolved.
Show resolved Hide resolved
wrapper.setState({ users, questions })
});

it('renders without crashing', function () {
shallow(<AdminPanel />);
});

it('matches snapshot', function () {
const serialized = toJson(wrapper);

Expand Down Expand Up @@ -72,12 +139,12 @@ describe('AdminPanel', function() {
it('renders the users table when view state is users', function () {
wrapper.find('div[id="users"]').simulate('click');
wrapper.update();

expect(wrapper.find('table[id="users-table"]')).toHaveLength(1);
});

it('show expected user data in the table', function () {
wrapper.setState({users});
wrapper.setState({ users });
wrapper.find('div[id="users"]').simulate('click')
wrapper.update();

Expand All @@ -100,12 +167,12 @@ describe('AdminPanel', function() {
it('renders the questions table when view state is questions', function () {
wrapper.find('div[id="questions"]').simulate('click');
wrapper.update();

expect(wrapper.find('table[id="questions-table"]')).toHaveLength(1);
});

it('show expected question data in the table', function () {
wrapper.setState({questions})
wrapper.setState({ questions })
wrapper.find('div[id="questions"]').simulate('click')
wrapper.update();

Expand Down
9 changes: 5 additions & 4 deletions frontend/src/AdminTable.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ const maxColumCount = mql.matches ? 5 : 12;

class AdminTable extends Component {
handleClick = (evt) => {
this.props.getUserDetail(evt);
const id = evt.target.parentElement.id;
Nalipp marked this conversation as resolved.
Show resolved Hide resolved

this.props.getUserDetail(id);
}

createTableHeader() {
const keys = Object.keys(this.props.tableObjs[0]);

Expand Down Expand Up @@ -62,12 +63,12 @@ class AdminTable extends Component {

createTableRows(keys, values) {
return (
<tr key={values[0]} onClick={this.handleClick}>
<tr key={values[0]} onClick={this.handleClick} id={values[0]}>
{values.map((value, index) => {
value = this.concantinateText(value);

return (
<td key={`${values[0]}-${keys[index]}`}>{ value }</td>
<td key={`${values[0]}-${keys[index]}`} >{ value }</td>
);
}).filter((value, idx) => idx < maxColumCount)}
</tr>
Expand Down
18 changes: 16 additions & 2 deletions frontend/src/AdminUserView.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,23 @@
import React, { Component } from "react";
import './AdminUserView.css';
import ElevateApi from './ElevateApi';

class AdminUserView extends Component {
handleClickDeleteUser = async () => {
await ElevateApi.deleteUser(this.props.user.id)
let users;

try {
users = await ElevateApi.getUsers();
} catch(err) {
return err;
}
this.props.updateUserState(users)
this.props.updateViewState("users")
}
render(){
const { first_name, last_name, email, current_company, hire_date, needs, goals } = this.props.user;

console.log('AdminUserView')
return (
<div className='AdminUserView'>
<div>
Expand All @@ -21,7 +34,7 @@ class AdminUserView extends Component {
</tr>
<tr>
<td><b>Hire Date:</b></td>
<td>{ hire_date.slice(0, 10) }</td>
<td>{ hire_date && hire_date.slice(0,10) }</td>
</tr>
<tr>
<td><b>Needs:</b></td>
Expand All @@ -38,6 +51,7 @@ class AdminUserView extends Component {
</tbody>
</table>
</div>
<button id="delete-click" onClick={ (e) => { if (window.confirm('Are you sure you want to delete this user?')) this.handleClickDeleteUser(e) }}>Delete</button>
</div>
)
}
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/AdminUserView.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,7 @@ describe('AdminUserView', function() {
expect(wrapper.html()).toContain('Goals');
expect(wrapper.html()).toContain('Questions');
});

mvatanya marked this conversation as resolved.
Show resolved Hide resolved


});
19 changes: 15 additions & 4 deletions frontend/src/ElevateApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ const BASE_URL = process.env.BASE_URL || "http://localhost:3001";
class ElevateApi {
static async request(endpoint, params = {}, verb = "get") {
let _token = localStorage.getItem("token");

console.debug("API Call:", endpoint, params, verb);

let q;
Expand All @@ -19,6 +18,10 @@ class ElevateApi {
} else if (verb === "patch") {
q = axios.patch(
`${BASE_URL}/${endpoint}`, { _token, ...params });
} else if (verb === "delete") {
q = axios.delete(
`${BASE_URL}/${endpoint}`, { params: { _token, ...params } }
)
}

try {
Expand Down Expand Up @@ -56,9 +59,11 @@ class ElevateApi {
let res = await this.request(`users`);

// Format hire_date for each user
res.users.forEach(user => {
user.hire_date = user.hire_date.slice(0, 10);
});
if (res.users){
res.users.forEach(user => {
user.hire_date = user.hire_date && user.hire_date.slice(0, 10); // check if the user has hire_date then format
});
}

return res.users
}
Expand Down Expand Up @@ -90,6 +95,12 @@ class ElevateApi {
return res.questions
}

static async deleteUser(id) {
await this.request(`users/${id}`, {}, "delete")
// let _token = localStorage.getItem("token");
// await axios.delete(`http://localhost:3001/users/${id}`,_token);
}

}

export default ElevateApi;
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/LogInSignUpForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ class LoginSignUpForm extends Component {
evt.preventDefault();
let token;



try {
if (this.state.isLogin) {
const data = { email: this.state.email, password: this.state.password };
Expand All @@ -51,6 +49,7 @@ class LoginSignUpForm extends Component {
token = await ElevateApi.signup(data);
}
} catch (err) {
console.log(err)
return this.setState({ err })
}

Expand Down
4 changes: 2 additions & 2 deletions frontend/src/Routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ class Routes extends React.Component {
<Route exact path="/login" render={props =>
(<LogInSignUpForm {...props} getCurrentUser={this.props.getCurrentUser}/>)}/>

<AdminPrivateRoute exact path="/admin" render={() =>
(<AdminPanel />)}/>
<AdminPrivateRoute exact path="/admin" render={props =>
(<AdminPanel {...props} />)}/>

<UserPrivateRoute
path="/users/:userId"
Expand Down
1 change: 1 addition & 0 deletions frontend/src/__snapshots__/AdminTable.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ exports[`AdminTable matches snapshot 1`] = `
</thead>
<tbody>
<tr
id={17}
key="17"
onClick={[Function]}
>
Expand Down
6 changes: 6 additions & 0 deletions frontend/src/__snapshots__/AdminUserView.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,12 @@ exports[`AdminUserView matches snapshot 1`] = `
</tbody>
</table>
</div>
<button
id="delete-click"
onClick={[Function]}
>
Delete
</button>
</div>
</AdminUserView>
`;