{"size": 2149, "ext": "js", "max_stars_repo_path": "models/Order.js", "max_stars_repo_name": "aji-shop/backend", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/Order.js", "max_issues_repo_name": "aji-shop/backend", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/Order.js", "max_forks_repo_name": "aji-shop/backend", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.6029411765, "max_line_length": 87, "alphanum_fraction": 0.4671940437}
const knex = require('../config/knex')
const jsonData = require('./jsonData')

const {getById} = require('./List')

module.exports.getAll = () =>
    knex('order')
    .join('user','user.id','=','order.user_id')
        .select(
            'order.id',
            'order.date',
            'order.state_id',
            'user.name',
            'user.email',
            'user.phone')
        .then(jsonData)

module.exports.getByStatusId = id =>
    knex('order')
        .where('state_id', id)
        .join('user','user.id','=','order.user_id')
        .select(
            'order.id',
            'order.date',
            'order.state_id',
            'user.name',
            'user.email',
            'user.phone')
        .then(jsonData)

module.exports.create = order =>
    knex('order')
        .insert({
            id: '' + order.id,
            state_id: order.state_id,
            user_id: order.user_id,
            date: order.date
        })
        .then(jsonData)

module.exports.updateStatus = order =>
    knex('order')
        .where('id', order.id)
        .select('state_id')
        .then(jsonData)
        .then(data => {
            if (data.state_id === 4 && order.state_id === 1) {
                throw new Error('"Executed" state cannot be changed to "Not Approved"')
            }
            if (data.state_id === 4 && order.state_id === 3) {
                throw new Error('"Executed" state cannot be changed to "Cancelled"')
            }
            if (data.state_id === 3 && order.state_id === 4) {
                throw new Error('"Cancelled" state cannot be changed to "Executed"')
            }
            if (data.state_id === 2 && order.state_id === 1) {
                throw new Error('"Approved" state cannot be changed to "Not Approved"')
            }
            if (order.state_id > 4) {
                throw new Error('State with id=' + order.state_id + ' does not exist')
            }

            return knex('order')
                        .where('id', order.id)
                        .update({
                            state_id: order.state_id
                        })
        })