Skip to content

Commit

Permalink
Merge pull request #46 from emccarthy510/makeCart
Browse files Browse the repository at this point in the history
Make cart
  • Loading branch information
vinayarv authored Jul 28, 2017
2 parents 8a6e26f + 828aca4 commit 6d3e393
Show file tree
Hide file tree
Showing 15 changed files with 205 additions and 120 deletions.
27 changes: 12 additions & 15 deletions CharSeed.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,43 @@ var db = require('./server/db');
var Character = require('./server/db/models/character');
var Bluebird = require('bluebird')

// EI: don't forget to update character price levels
var characters = [

{
name: "Albus Dumbledore",
price: "$$$",
imageUrl: "./characters/albus.jpg",
price: 1000,
imageUrl: "/characters/albus.jpg",
description: "Be Dumbledore. Live in the magical world of Harry Potter... Be the headmaster at Hogwarts",
inventory: "1"
inventory: 10
},
{
name: "Wonder Woman",
price: "$$$$",
price: 2000,
imageUrl: "/characters/ww.jpg",
description: "Be Wonder Woman. Super Awesome",
inventory: "3"
inventory: 3
},
{
name: "Frodo Baggins",
price: "$$",
price: 400,
imageUrl: "/characters/frodo.jpg",
description: "Live in the houses with the circle doors. Protect the world. Take the One ring to be destroyed?",
inventory: "14"
inventory: 14
},
{
name: "Hermione Granger",
price: "$$$",
price: 6000,
imageUrl: "/characters/hermione.jpg",
description: "The brightest witch of her Time. Enjoy the friendship of Ron and Harry",
inventory: "17"
inventory: 17
},
{
name: "Luke Skywalker",
price: "$",
price: 3000,
imageUrl: "/characters/luke_sky.jpg",
description: "The force will be with you if you choose Luke Skywalker",
inventory: "7"
inventory: 7
}


Expand All @@ -65,7 +66,3 @@ db.sync({ force: true })
console.log('connection to the database closed!')
})





Empty file added client/components/Cart.js
Empty file.
81 changes: 56 additions & 25 deletions client/components/SingleCharacter.js
Original file line number Diff line number Diff line change
@@ -1,55 +1,86 @@
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { fetchCharacter } from '../store';
import {fetchCharacter, addOrder} from '../store';


class SingleCharacter extends Component {
constructor(props) {
super(props);

this.state = {
name: '',
imageUrl: '',
price: '',
description: '',
rating: ''
quantity: 0,
decreaseEnabled: true,
increaseEnabled: false
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleQuantity = this.handleQuantity.bind(this);
}

componentDidMount() {
console.log("PRINT", this.props.match.params.characterId)
this.props.loadSingleCharacter(this.props.match.params.characterId)
}

render() {
const character = this.props.singleCharacter;
handleSubmit(evt){
const character = this.props.singleCharacter
const order = {
characterId: character.id,
quantity: this.state.quantity,
subTotal: this.state.quantity * character.price
}
console.log(order)
this.props.addOrder(order, character.id)
}

handleQuantity(evt) {

if(evt.target.name === "increase"){
this.setState({quantity: ++this.state.quantity});
} else {
this.setState({quantity: --this.state.quantity});
}
if (this.state.quantity === this.props.singleCharacter.inventory) {
this.setState({ increaseEnabled: true, decreaseEnabled: false });
} else if (this.state.quantity === 0) {
this.setState({ increaseEnabled: false, decreaseEnabled: true });
} else {
this.setState({ increaseEnabled: false, decreaseEnabled: false });
}
}

render () {
const character = this.props.singleCharacter;
return (
<li className="media">
<div className="media-left">
<a href="#">
<img className="media-object" src={character.imageUrl} alt="image" />
</a>
</div>
<div className="media-body">
<h4 className="media-heading">{character.name}</h4>
<h4>{character.price} </h4>
<h4 className="media-heading">{character.description}</h4>
</div>
</li>
<div className="media-left">
<a href="#">
<img className="media-object" src={ character.imageUrl } alt="image" />
</a>
</div>
<div className="media-body">
<h4 className="media-heading">{ character.name}</h4>
<h4>{character.price} </h4>
<button className="btn btn-default btn-xs" name ="decrease" onClick={this.handleQuantity} disabled= {this.state.decreaseEnabled} > - </button>
<div id="quantity">
{this.state.quantity}</div>
<button className="btn btn-default btn-xs" name ="increase" onClick={this.handleQuantity} disabled= {this.state.increaseEnabled} > + </button>
<button className = "btn btn-default btn-xs" onClick= {this.handleSubmit} > </button>
<h4 className="media-heading">{ character.description}</h4>
</div>
</li>

);
}
}
/* ----------------- CONTAINER ------------------ */
const mapStateToProps = ({ singleCharacter }) => ({ singleCharacter });
const mapStateToProps = ({singleCharacter}) => ({singleCharacter});
const mapDispatchToProps = (dispatch) => {

return {

loadSingleCharacter(characterId) {
loadSingleCharacter (characterId) {
dispatch(fetchCharacter(characterId));

},
addOrder(order, userId){
dispatch(addOrder(order, userId));
}
}
}
Expand Down
30 changes: 30 additions & 0 deletions client/store/cart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import axios from 'axios';

/* ------------ ACTION TYPES ------------------ */

const ADD_TO_CART = 'ADD_TO_CART';


/* ------------ ACTION CREATORS ------------------ */

const add = orderItem => ({ type: ADD_TO_CART, orderItem });

/* ------------ REDUCERS ------------------ */

export default function reducer (orderItems = [], action) {
switch (action.type) {
case ADD_TO_CART:
return [action.orderItem, ...orderItems];

default:
return orderItems;
}
}

/* ------------ THUNK CREATORS ------------------ */

export const addOrder = (order, userId) => dispatch => {
axios.post(`/${userId}/orders/current`)
.then(res => dispatch(add(res.data)))
.catch(err => console.error(`Adding order to user: ${userId} unsuccessful`, err));
}
4 changes: 3 additions & 1 deletion client/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import thunkMiddleware from 'redux-thunk';
import user from './user';
import allCharacters from './allCharacters';
import singleCharacter from './singleCharacter';
import cart from './cart';


const reducer = combineReducers({user, allCharacters, singleCharacter});
const reducer = combineReducers({user, allCharacters, singleCharacter, cart});
const middleware = applyMiddleware(thunkMiddleware, createLogger({collapsed: true}));
const store = createStore(reducer, middleware);

export default store;
export * from './user';
export * from './allCharacters';
export * from './singleCharacter';
export * from './cart';
55 changes: 0 additions & 55 deletions server/api/cart.js

This file was deleted.

2 changes: 1 addition & 1 deletion server/api/characters.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const Character = models.Character;

module.exports = router;


// EI: don't forget about query strings!
router.get('/', function (req, res, next) {
Character.findAll()
.then(character => res.json(character))
Expand Down
1 change: 1 addition & 0 deletions server/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module.exports = router;

router.use('/users', require('./users'));
router.use('/characters', require('./characters'));
router.use('/orders', require('./orders'));

router.use((req, res, next) => {
const error = new Error('Not Found');
Expand Down
32 changes: 32 additions & 0 deletions server/api/orders.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const router = require('express').Router();
const {Order, OrderItems} = require('../db/models');

/*
when order is clicked: update cart table.
change status: purchased
put total
*/

// EI:
// a more RESTful URL would be:
// PUT /users/:userId/orders/:orderId/purchase
// or
// PUT /orders/:orderId/purchase
//
// A good example of a RESTful API is Paypal's:
// https://developer.paypal.com/docs/api/

router.put('/:orderId/purchase', (req, res, next) => {
Order.update({
status: 'purchased',
total: req.body.total
}, {
where: {
userId: req.params.userId,
returning: true
}
})
.then( result => res.send(result[1].dataValues))
})

module.exports = router;
46 changes: 45 additions & 1 deletion server/api/users.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const router = require('express').Router()
const {User} = require('../db/models');
const {User, Order, OrderItems} = require('../db/models');
module.exports = router;

router.get('/', (req, res, next) => {
Expand All @@ -12,3 +12,47 @@ router.get('/', (req, res, next) => {
.then(users => res.json(users))
.catch(next);
});

/*
when addToCart is clicked push item to cart table.
if cart is not created:
create a cart for user.
Push the characters to cartItem table
if cart is present for user
push the items to cart
*/

// EI: in general, routes should look like this:
// /generalCategory/:idForThingInThatCategory
//
// a more RESTful route for adding to cart could be:
// POST /users/:userId/orders/:orderId/orderItems
// or
// PUT /users/:userId/orders/:orderId

router.post('/:userId/orders/current', (req, res, next) => {
Order.findOrCreate({
where:{
userId: req.params.userId,
status: 'pending'
}
})
.spread ((userCart, created) => {
OrderItems.create({
characterId: req.body.characterId,
quantity: req.body.quantity,
subtotal: req.body.subtotal,
orderId: userCart.id
})
})
.then( cartItem => res.send(cartItem))
.catch(next)
})


/*
when checkout is clicked
check if user has shipping address
yes: use it
no: add shipping address to user table.
*/
13 changes: 0 additions & 13 deletions server/db/models/cart.js

This file was deleted.

Loading

0 comments on commit 6d3e393

Please sign in to comment.