{"size": 2086, "ext": "js", "max_stars_repo_path": "server/api/orders.js", "max_stars_repo_name": "ampd-shoppers/mugshop", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "server/api/orders.js", "max_issues_repo_name": "ampd-shoppers/mugshop", "max_issues_repo_issues_event_min_datetime": "2021-03-09T08:06:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-09T03:57:10.000Z", "max_forks_repo_path": "server/api/orders.js", "max_forks_repo_name": "ampd-shoppers/mugshop", "max_forks_repo_forks_event_min_datetime": "2019-06-11T16:15:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-11T16:15:35.000Z"}
{"max_stars_count": null, "max_issues_count": 2, "max_forks_count": 1, "avg_line_length": 20.86, "max_line_length": 87, "alphanum_fraction": 0.5115052733}
const router = require('express').Router()
const {CartItem, User, Mug, Order, OrderItem} = require('../db/models')
module.exports = router

router.get('/', async (req, res, next) => {
  try {
    if (req.user) {
      var userOrders = await Order.findAll({
        where: {userId: req.user.id},
        order: [['id', 'ASC']]
      })
    } else {
      var userOrders = await Order.findAll({
        where: {sessionId: req.sessionID},
        order: [['id', 'ASC']]
      })
    }
    res.json(userOrders)
  } catch (err) {
    next(err)
  }
})
router.get('/all', async (req, res, next) => {
  try {
    if (req.isAdmin) {
      let allOrders = await Order.findAll({
        order: [['id', 'ASC']]
      })
      res.json(allOrders)
    } else {
      res.send(
        'You are not an Admin. Please log in or contact support if this is not correct'
      )
    }
  } catch (err) {
    next(err)
  }
})

router.get('/:orderId', async (req, res, next) => {
  try {
    const orderId = await OrderItem.findAll({
      where: {orderId: req.params.orderId},
      include: [
        {
          model: Mug
        }
      ]
    })
    if (orderId) {
      res.json(orderId)
    } else {
      res.send('order not found')
    }
  } catch (err) {
    next(err)
  }
})

router.get('/:orderId', async (req, res, next) => {
  try {
    const orderId = await OrderItem.findAll({
      where: {orderId: req.params.orderId},
      include: [
        {
          model: Mug
        }
      ]
    })
    if (orderId) {
      res.json(orderId)
    } else {
      res.send('order not found')
    }
  } catch (err) {
    next(err)
  }
})

router.put('/:orderId', async (req, res, next) => {
  try {
    if (req.isAdmin) {
      let updatedOrder = await Order.update(
        {progress: req.body.progress},
        {
          where: {id: req.params.orderId},
          returning: true
        }
      )
      res.json(updatedOrder)
    } else {
      res.send(
        'You are not an Admin. Please log in or contact support if this is not correct'
      )
    }
  } catch (err) {
    next(err)
  }
})
