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 all 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
10 changes: 8 additions & 2 deletions backend/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,13 @@ class User {

static async findAll() {
const result = await db.query(
`SELECT id, first_name, last_name, current_company AS company, hire_date, needs, goals
`SELECT id,
first_name,
last_name,
current_company AS company,
hire_date,
needs,
goals
FROM users
ORDER BY id`
);
Expand All @@ -101,7 +107,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
23 changes: 16 additions & 7 deletions frontend/src/AdminPanel.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,20 @@ 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})
}

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

mediaQueryChanged = () => {
Expand All @@ -49,8 +54,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 +76,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' &&
<AdminUserView
user={this.state.userDetail}
updateUserState={this.updateUserState}
changeView={this.changeView} />
}
</div>

<div className="admin-navbar">
Expand Down
104 changes: 84 additions & 20 deletions frontend/src/AdminPanel.test.js
Original file line number Diff line number Diff line change
@@ -1,23 +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": [
{ "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." },
{ "first_name": "Admin",
"last_name": "User",
"company": "",
"hire_date": "2019-06-23T07:00:00.000Z",
"needs": "", "goals": "" }
]
}
}
const user = { data:
{"user":
{"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": [
{ "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 },
{ "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 }
]
}
}

const id = "17"
axios.get.mockImplementation((reqUrl) => {
if (reqUrl.includes(id)) {
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: id,
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,
user_id: id,
question: "My employer didn't pay me",
resolved: false,
email: "[email protected]",
Expand All @@ -26,15 +89,16 @@ describe('AdminPanel', function() {
created_date: "2019-08-29"
}]

beforeEach(() => {
beforeEach(async () => {
wrapper = mount(<AdminPanel />);
wrapper.setState ({ users, questions })
await wrapper.instance().componentDidMount()
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 +136,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 @@ -86,7 +150,7 @@ describe('AdminPanel', function() {

const dataRow = rows.first().find('td').map(column => column.text())
expect(dataRow.length).toEqual(9);
expect(dataRow[0]).toEqual("17");
expect(dataRow[0]).toEqual(id);
expect(dataRow[1]).toEqual("[email protected]");
expect(dataRow[2]).toEqual("");
expect(dataRow[3]).toEqual("admin");
Expand All @@ -100,12 +164,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 All @@ -114,7 +178,7 @@ describe('AdminPanel', function() {

const dataRow = rows.first().find('td').map(column => column.text());
expect(dataRow.length).toEqual(7);
expect(dataRow[0]).toEqual("17");
expect(dataRow[0]).toEqual(id);
expect(dataRow[1]).toEqual("My employer didn't pay me");
expect(dataRow[2]).toEqual("");
expect(dataRow[3]).toEqual("[email protected]");
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
31 changes: 28 additions & 3 deletions frontend/src/AdminUserView.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,29 @@
import React, { Component } from "react";
import './AdminUserView.css';
import ElevateApi from './ElevateApi';

class AdminUserView extends Component {
render(){
const { first_name, last_name, email, current_company, hire_date, needs, goals } = this.props.user;
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.changeView("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 +40,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 +57,12 @@ 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
18 changes: 14 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,12 @@ 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 => {
// check if the user has hire_date then format
user.hire_date = (user.hire_date && user.hire_date.slice(0, 10));
});
}

return res.users
}
Expand Down Expand Up @@ -88,6 +94,10 @@ class ElevateApi {
return res.questions
}

static async deleteUser(id) {
await this.request(`users/${id}`, {}, "delete")
}

}

export default ElevateApi;
6 changes: 2 additions & 4 deletions frontend/src/LogInSignUpForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,10 @@ class LoginSignUpForm extends Component {
evt.preventDefault();
let token;



try {
if (this.state.isLogin) {
const data = { email: this.state.email, password: this.state.password };
const data = { email: this.state.email,
password: this.state.password };
token = await ElevateApi.login(data)
} else {
const data = {
Expand All @@ -55,7 +54,6 @@ class LoginSignUpForm extends Component {
} catch (errors) {
return this.setState({ errors })
}

localStorage.setItem("token", token);
await this.props.getCurrentUser();
this.props.history.push("/");
Expand Down
Loading