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

Allow admin to update casefile attached to mission #84

Merged
merged 4 commits into from
Sep 26, 2017
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
96 changes: 96 additions & 0 deletions react-ui/src/components/Admin/AddCollectionToMission.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import React, { Component } from 'react';
import axios from 'axios';
import { Link, Redirect } from 'react-router-dom';
import CollectionItem from './CollectionItem';
import { Header, Table } from 'semantic-ui-react';

class AddCollectionToMission extends Component {
constructor(props) {
super(props);
this.updateCollectionID = this.updateCollectionID.bind(this);
this.submitNewPost = this.submitNewPost.bind(this);

this.state = {
collections: [],
collection_id: (this.props.mission && this.props.mission.casefile_id) || null,
name: this.props.mission && this.props.mission.name,
submitResult: false,
}
}

updateCollectionID(collection_id) {
this.setState({ collection_id: collection_id });
}

submitNewPost(e) {
e.preventDefault();
let thiz = this;

axios.patch('/api/update-mission', {
name: this.state.name,
casefile_id: this.state.collection_id - 1,
user_id: this.state.user_id,
})
.then((res) => thiz.setState({ submitResult: true }))
.catch((err) => console.log("error in updating mission: ", err));
}

componentDidMount() {
axios.get('/api/casefiles')
.then((res) => this.setState({ collections: res.data }))
.catch((err) => console.log(err))
}

render() {
return (
<div>
{this.state.submitResult && (
<Redirect to={'/admin'}/>
)}
<Header as="h3">
Choose a Case File
</Header>

<Header.Subheader>
<p>A Case File is a collection of articles that your Team of Agents will investigate.</p>
</Header.Subheader>


<Table celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell colSpan="2">
Choose an Exisiting Case File... OR
</Table.HeaderCell>
<Table.HeaderCell className="collapsing">
<Link to='/admin/collection/new' className="ui button primary right floated">
Create a New Case File
</Link>
</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{Object.keys(this.state.collections).map((key, id) => {
return (
<CollectionItem
name={this.state.collections[key][1]}
activeCollectionId={this.state.collection_id}
createdBy={this.state.collections[key][2]}
id={id + 1}
key={id}
updateCollection={this.updateCollectionID}
/>
)
})}
</Table.Body>
</Table>
<button className="ui button positive" type="button" onClick={(e) => this.submitNewPost(e)}>
Save Mission
</button>
</div>
);
}

}

export default AddCollectionToMission;
5 changes: 4 additions & 1 deletion react-ui/src/components/Admin/ArticleListItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@ class ArticleListItem extends React.Component {


render() {
// console.log("articlelistitem", this.props);
return (
<tr key={this.props.id}>
<td className="strong">{this.props.headline}</td>
<td><a href={this.props.url}>{this.props.url}</a></td>
<td>{this.props.type}</td>
<td className="collapsing">
{/* TODO: User missionId here instead? */}
<Link to={`/admin/mission/${'missionName'}/edit`} className="ui button blue">
Edit
</Link>
</td>
</tr>
)
Expand Down
6 changes: 1 addition & 5 deletions react-ui/src/components/Admin/CollectionItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@ class CollectionItem extends React.Component {
e.preventDefault();

// Update which row is highlighted
console.log("hEY LOOK HERE", this.props.id, "what it waS: ", this.props.activeCollectionId);
// this.props.id is zero (activeCollectionId is 1)
// why is id 0???
console.log("props", this.props);
this.props.updateCollection(this.props.id);
}

Expand All @@ -26,7 +22,7 @@ class CollectionItem extends React.Component {
const buttonText = isActive ? 'Selected' : 'Choose';

return (
<tr key={this.props.id} className={rowColorClasses}>
<tr className={rowColorClasses}>
<td>{this.props.name}</td>
<td>created by {this.props.createdBy}</td>
<td>
Expand Down
60 changes: 12 additions & 48 deletions react-ui/src/components/Admin/Mission.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,72 +2,36 @@ import React from 'react';
import axios from 'axios';
import { Header, Table } from 'semantic-ui-react';
import ArticleListItem from './ArticleListItem';
import AddCollectionToMission from './AddCollectionToMission';


class Mission extends React.Component {
constructor() {
super();
this.state = {
articles: []
mission: null,
}
}
// TODO add another state var called noArticles that is shown conditionally instead of the Object.keys stuff
componentDidMount() {
// get articles
console.log("component mounted", this.props.match.params.id);
axios.get('/api/articles/review/' + this.props.match.params.id, {
params: {name: this.props.match.params.id} })
.then((res) => {
console.log("artticels retrieved", res.data, typeof res.data);
// save relevant article info to state
if (typeof res.data === 'string') {
this.setState({ articles: res.data})
} else {
for(let key in res.data) {
// assign state to temporary arrays
let temp = this.state.articles.slice();
// push data to arrays
temp.push(res.data[key]);
// set the state
this.setState({
articles: temp
})
}
}


})
componentDidMount() {
// get mission details
axios.get(`/api/view-mission/${this.props.match.params.id}`)
.then((res) => this.setState({ mission: res.data }))
.catch((err) => {
console.log("get articles error in Mission.js", err);
})
}
// TODO should also display casefile name
// name comes from <Link to={`/admin/mission/${missionName}`} - does this.props.collection get passed through too?

render() {
console.log(this.state.mission)
let missionName = this.props.match.params.id.replace(/_/g, ' ');

return (
<div>
<h3>Mission: { missionName }</h3>
<Table celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell colSpan='3'>Articles</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{Object.keys(this.state.articles).map((key, id) => {
return (
<ArticleListItem
headline={this.state.articles[key][0]}
url={this.state.articles[key][1]}
type={this.state.articles[key][2]}
id={id}
key={id}
/>
)
})}
</Table.Body>
</Table>
{ this.state.mission &&
<AddCollectionToMission mission={this.state.mission} />
}
</div>
)
}
Expand Down
4 changes: 3 additions & 1 deletion react-ui/src/components/Admin/MissionListItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,10 @@ class MissionListItem extends React.Component {
<td className="strong">{this.props.name}</td>
<td>{this.props.collection}</td>
<td className="collapsing">
{/* TODO: We should probably replace the mission name with an id in
this route unless we are sure the missionName is unique. */}
<Link to={`/admin/mission/${missionName}/`} className="ui button blue">
Review
Edit
</Link>
<Button type="button" onClick={this.handleDelete} basic color="red">
Delete
Expand Down
10 changes: 2 additions & 8 deletions react-ui/src/components/Admin/NewGame.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,7 @@ class NewGame extends React.Component {
componentDidMount() {
axios.get('/api/casefiles')
.then((res) => {
console.log("api requesting", res.data);
this.setState({
collections: res.data,
})
this.setState({ collections: res.data });
})
.then(() => {
console.log("component mounted! casefile data retrieved!", this.state.collections);
Expand Down Expand Up @@ -63,7 +60,6 @@ class NewGame extends React.Component {
}

updateCollectionID(collection_id) {
console.log("updating colleciton id", collection_id); // THIS WORKS
this.setState({ collection_id: collection_id });
}

Expand Down Expand Up @@ -131,7 +127,7 @@ class NewGame extends React.Component {
defaultValue={this.state.name}
className="bump-right"
/>
<button className="ui button" type="submit" onClick={(e) => this.updateTitle(e)}>
<button className="ui button" type="submit" onClick={(e) => this.updateTitle(e)}>
Save
</button>
</div>
Expand Down Expand Up @@ -218,8 +214,6 @@ class NewGame extends React.Component {

export default NewGame;

// onSubmit={(e) => this.updateTitle(e)}

<form
ref={(input) => this.gameForm = input}
onSubmit={(e) => this.submitNewPost(e)}
Expand Down
3 changes: 0 additions & 3 deletions server/db/knex.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@

require('dotenv').config()

console.log("testing", process.env)
console.log("trying to connect to db in environment", process.env.NODE_ENV)
const env = process.env.NODE_ENV || 'development';
console.log('env:', env)
const knexConfig = require('../knexfile')[env];
const knex = require('knex')(knexConfig);
const bookshelf = require('bookshelf')(knex);
Expand Down
85 changes: 34 additions & 51 deletions server/routes/missions.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,58 +26,34 @@ router.get('/api/missions', (req, res, next) => {
// TODO where user_id === logged_in user (req.session.user)
let user = 1; // temporary workaround

Mission.forge().where({user_id: user}).query('orderBy', 'id', 'asc').fetchAll({withRelated: ['casefile'], debug:true})
.then((mission) => {
// convert data to JSON
mission = mission.toJSON();
//console.log("these are all the missions", mission);
// loop over data to get mission and casefile names
for (var i = 0; i < mission.length; i++) {
// save to files object
if (mission[i].casefile && mission[i].casefile.name) {
files[mission[i].name] = mission[i].casefile.name;
} else {
files[mission[i].name] = "no casefile added";
Mission.forge().where({user_id: user}).query('orderBy', 'id', 'asc')
.fetchAll({withRelated: ['casefile'], debug:true})
.then((mission) => {
// convert data to JSON
mission = mission.toJSON();
// loop over data to get mission and casefile names
for (var i = 0; i < mission.length; i++) {
// save to files object
if (mission[i].casefile && mission[i].casefile.name) {
files[mission[i].name] = mission[i].casefile.name;
} else {
files[mission[i].name] = "no casefile added";
}
}
}
// send files object
res.send(files)
})
// send files object
res.send(files)
})
});

// get mission by name / id
router.get('/api/view-mission/:name', function(req, res, next) {
let article_files = [];
let missionid, casefileid;
console.log("successnesses", req.params.name);
let mission_name = req.params.name.replace('_', " \s");
console.log("mission name", mission_name);
// get the casefile_id
Mission.forge().where({name: mission_name}).fetch()
.then((mission) => {
mission = mission.toJSON();
console.log("casefile id", mission.casefile_id);
//console.log(mission[0].casefile.name);
//get casefile name from mission.casefile_id
//get articles from articles.casefile_id
Article.forge().where({casefile_id: mission.casefile_id}).fetchAll()
.then((articles) => {
console.log("fetching articles", articles.toJSON());
console.log("squirrrrrel magic", articles.toJSON()[0].article);
for (var i = 0; i < articles.length; i++) {
article_files.push(articles.toJSON()[i].article);
}
//article_files.push(articles.toJSON());
})
.catch((err) => {
console.log("articles error", err);
})
})
.catch((err) => {
console.log("mission fetching error", err);
})
res.send(article_files);
}) // end get by name
let mission_name = req.params.name.split('_').join(' ');
let missionJSON;

Mission.forge().where({ name: mission_name }).fetch()
.then((mission) => res.send(mission))
.catch((err) => console.log("mission fetching error", err))
})

// create a new mission
router.post('/api/add-mission', (req, res, next) => {
Expand All @@ -92,7 +68,7 @@ router.post('/api/add-mission', (req, res, next) => {
// get user name from user id for mission url
User.forge().where({id: req.body.user_id}).fetch()
.then((user) => {
user = user.toJSON();
user = user.toJSON() || 'testamdmin';
username = user.name;
// strip punctuation, capitals, and spaces
username = username.replace(/[.\-`'\s]/g,"").toLowerCase();
Expand All @@ -105,8 +81,14 @@ router.post('/api/add-mission', (req, res, next) => {
.save({last_id: false}, {patch: true})
})
.then(() => {
// save mission name, user_id, url to mission table - casefile_id will be updated in patch when selected
Mission.forge({name: req.body.name, user_id: req.body.user_id, url: new_url, last_id: true})
// save mission name, user_id, url to mission table - casefile_id will be
// updated in patch when selected
Mission.forge({
name: req.body.name,
user_id: req.body.user_id,
url: new_url,
last_id: true
})
.save()
.then((mission) => {
res.sendStatus(200);
Expand All @@ -128,7 +110,8 @@ router.patch('/api/update-mission', (req, res, next) => {
// update mission table with selected casefile_id
console.log("fetched mission to patch", mission);
Mission.forge().where({id: mission.attributes.id})
.save({casefile_id: req.body.casefile_id+1}, {patch: true}) //TODO get casefile_id a better way
//TODO get casefile_id a better way
.save({casefile_id: req.body.casefile_id+1}, {patch: true})
.then((response) => {
console.log("mission updated successfully", response);
res.sendStatus(200);
Expand Down