Skip to content

Commit

Permalink
changes to routes added addtocart functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
vinayarv committed Jul 28, 2017
1 parent 55e192e commit 828aca4
Show file tree
Hide file tree
Showing 10 changed files with 164 additions and 101 deletions.
56 changes: 43 additions & 13 deletions client/components/SingleCharacter.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,55 @@
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)

componentDidMount() {
this.props.loadSingleCharacter(this.props.match.params.characterId)
}

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">
Expand All @@ -34,7 +60,11 @@ class SingleCharacter extends Component {
<div className="media-body">
<h4 className="media-heading">{ character.name}</h4>
<h4>{character.price} </h4>
<button className = "btn btn-default btn-xs" onClick= { () => addOrder({}, character.id)} > </button>
<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>
Expand All @@ -45,12 +75,12 @@ class SingleCharacter extends Component {
/* ----------------- CONTAINER ------------------ */
const mapStateToProps = ({singleCharacter}) => ({singleCharacter});
const mapDispatchToProps = (dispatch) => {

return {

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';
76 changes: 0 additions & 76 deletions server/api/cart.js

This file was deleted.

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.
*/
12 changes: 6 additions & 6 deletions server/db/models/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const User = require('./user')
const Cart = require('./cart')
const CartItems = require('./cartItems')
const Order = require('./order')
const OrderItems = require('./orderItems')

const Review = require('./review')
const Movie = require('./movie')
Expand All @@ -20,17 +20,17 @@ const Character = require('./character.js');
* instead of: const User = require('../db/models/user')
*/

User.hasMany(Cart);
Cart.hasMany(CartItems);
User.hasMany(Order);
Order.hasMany(OrderItems);
Movie.hasMany(Character);
Character.belongsTo(Movie);
Review.belongsTo(User);
Review.belongsTo(Character);

module.exports = {
User,
Cart,
CartItems,
Order,
OrderItems,
Character,
Review,
Movie
Expand Down
4 changes: 2 additions & 2 deletions server/db/models/cart.js → server/db/models/order.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const Sequelize = require('sequelize')
const db = require('../db')

// Rename this model to be Order/'order'
const Cart = db.define('cart', {
const Order = db.define('order', {
status: {
type: Sequelize.ENUM('pending', 'purchased')
},
Expand All @@ -11,4 +11,4 @@ const Cart = db.define('cart', {
}
});

module.exports = Cart;
module.exports = Order;
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const Sequelize = require('sequelize')
const db = require('../db')

const CartItems = db.define('cart_items', {
const OrderItems = db.define('orderItems', {
characterId: {
type: Sequelize.INTEGER
},
Expand All @@ -13,4 +13,4 @@ const CartItems = db.define('cart_items', {
}
});

module.exports = CartItems;
module.exports = OrderItems;

0 comments on commit 828aca4

Please sign in to comment.