/var/www/qr4y.com/server/delivery/api/controllers
Edit: /var/www/qr4y.com/server/delivery/api/controllers/table.controller.js (15454B)
const logger = require('../../logger')({ service: 'tableController' })
const { Op } = require('sequelize')
const checkPermission = require('../utils/checkPermission.util')
const { isSet, isEmpty, minLength, isPhone, isEmail } = require('../utils/validator.util')
const { NotFound, BadRequest, ApiError } = require('../responseModels/errors')
module.exports = function ({ db }) {
this.List = async (req, res, next) => {
logger.child({ path: req.path, request: req.query }).info()
let t1 = performance.now()
try {
const { roomId, status, limit, page } = req.query
let where = {}
if (roomId) {
where['roomId'] = parseInt(roomId)
}
if (status) {
where['status'] = status
}
let offset = page > 0 ? (page - 1) * (limit || 10) : 0
const tables = await db.table.findAll({
include: [
{
model: db.order,
include: [
{
model: db.user,
foreginKey: 'userId',
as: 'user',
include: { model: db.userPhone }
},
{
model: db.user,
foreginKey: 'operatorId',
as: 'operator',
include: { model: db.userPhone }
},
{ model: db.user, foreginKey: 'orderId', as: 'orderWaiters' }
]
}
],
where,
order: [['name', 'ASC']],
offset,
limit: parseInt(limit) || 10
})
if (tables.length == 0 || !tables) {
throw new NotFound({ lang: req.user?.languageCode })
}
const time = performance.now() - t1
return res.status(200).json({ list: tables, count: tables.length, time, page })
} catch (err) {
next(err)
}
}
this.Details = async (req, res, next) => {
logger.child({ path: req.path, request: req.params }).info()
try {
const { id } = req.params
if (!isSet(id) || isEmpty(id)) {
throw new BadRequest({ lang: req.user?.languageCode })
}
const table = await db.table.findOne({
include: [
{
model: db.room,
foreginKey: 'roomId',
include: {
model: db.branch,
foreginKey: 'branchId',
include: { model: db.company, foreginKey: 'companyId', as: 'company' }
}
}
],
where: { id }
})
if (!table) {
throw new NotFound({ lang: req.user?.languageCode })
}
return res.status(200).json(table)
} catch (err) {
next(err)
}
}
this.History = async (req, res, next) => {
logger.child({ path: req.path, request: req.query }).info()
try {
let t1 = performance.now()
let { tableId, limit, page, sort, event, eventExclude, eventHandled } = req.query
let where = {}
if (tableId) {
const table = await db.table.findOne({ where: { id: tableId } })
if (table) where['tableId'] = table.id
else throw new BadRequest({ lang: req.user?.languageCode })
} else {
// throw new BadRequest({ lang: req.user?.languageCode })
}
let offset = page > 0 ? (page - 1) * (limit || 10) : 0
if (eventHandled)
where['eventHandled'] = eventHandled === 'true' || eventHandled === 1 ? 1 : 0
if (eventExclude) {
if (statusExclude === 'true') {
where['event'] = {
[Op.not]: event.split(',').map((p) => {
return p.trim()
})
}
} else {
where['event'] = {
[Op.in]: event.split(',').map((p) => {
return p.trim()
})
}
}
}
const list = await db.tableHistory.findAll({
//include: [{ model: db.order }],
where,
offset,
order: [
['id', 'DESC']
// ['name', 'ASC'],
],
limit: parseInt(limit) || 10
// sort
})
if (list.length == 0 || !list) {
throw new NotFound({ lang: req.user?.languageCode })
}
const time = performance.now() - t1
return res.status(200).json({ list, time, count: list.length })
} catch (err) {
next(err)
}
}
this.Create = async (req, res, next) => {
logger.child({ path: req.path, request: req.body }).info()
try {
const { name, description, image, places, status, roomId } = req.body
if (!isSet(name) || isEmpty(name)) {
throw new BadRequest({ lang: req.user?.languageCode })
}
if (!isSet(roomId)) {
throw new BadRequest({ lang: req.user?.languageCode })
}
const table = await db.table.create({
name,
description,
image,
places,
roomId,
status
})
return res.status(200).json({
status: 'success',
id: table.id
})
} catch (err) {
next(err)
}
}
this.MultiCreate = async (req, res, next) => {
logger.child({ path: req.path, request: req.body }).info()
try {
let { count, image, places, status, roomId } = req.body
if (!isSet(count)) {
throw new BadRequest({ lang: req.user?.languageCode })
}
if (!isSet(roomId)) {
throw new BadRequest({ lang: req.user?.languageCode })
}
if (!places || parseInt(places) <= 0) {
places = 4
}
// посчитать кол-во столов в помещении
let tableNum = 0
const tables = await db.table.findAll({ where: { roomId } })
if (tables && tables.length > 0) {
tableNum = tables.length + 1
}
for (i = 0; i < count; i++) {
tableNum++
const table = await db.table.create({
name: tableNum,
image,
places,
roomId,
status
})
}
return res.status(200).json({
status: 'success'
})
} catch (err) {
next(err)
}
}
this.Edit = async (req, res, next) => {
logger.child({ path: req.path, request: req.body }).info()
try {
const { id, name, description, image, places, status, roomId, alarm } = req.body
if (!isSet(id) || isEmpty(id)) {
throw new BadRequest({ lang: req.user?.languageCode })
}
if (!isSet(name) || isEmpty(name)) {
throw new BadRequest({ lang: req.user?.languageCode })
}
const table = await db.table.findOne({
where: { id }
})
if (!table) {
throw new NotFound({ lang: req.user?.languageCode })
}
table.name = name ? name : table.name
table.description = description ? description : table.description
table.image = image ? image : table.image
table.status = status ? status : table.status
table.roomId = roomId ? parseInt(roomId) : table.roomId
table.places = places ? parseInt(places) : table.places
table.alarm = alarm ? alarm : table.alarm
await table.save()
return res.status(200).json(table)
} catch (err) {
next(err)
}
}
this.Delete = async (req, res, next) => {
logger.child({ path: req.path, request: req.body }).info()
try {
const { id } = req.body
const table = await db.table.findOne({
where: { id }
})
if (!table) {
throw new NotFound({ lang: req.user?.languageCode })
}
await db.table.destroy({ where: { id } })
return res.status(200).json({ status: 'success', id })
} catch (err) {
next(err)
}
}
this.Set = async (req, res, next) => {
logger.child({ path: req.path, request: req.body }).info()
try {
const { id, status } = req.body
if (!isSet(id) || isEmpty(id)) {
throw new BadRequest({ code: 1023, lang: req.user?.languageCode })
}
if (!isSet(status) || isEmpty(status)) {
throw new BadRequest({ code: 1022, lang: req.user?.languageCode })
}
const table = await db.table.findOne({
include: [db.room],
where: { id }
})
if (!table) {
throw new NotFound({ lang: req.user?.languageCode })
}
if (table.status == status) {
throw new ApiError({
code: 1021,
lang: req.user?.languageCode
})
}
table.status = status
await table.save()
await db.tableHistory.create({
tableId: table.id,
event: table.status,
created: req.user.app || 'system',
createdId: req.user.id,
eventHandled: true,
processed: 'system'
})
// TODO: Разослать по всем операторам и официантам этого филиала
const branchId = table.room?.branchId
if (branchId) {
const tableData = {
id: table.id,
status: table.status
}
await SERVICES.WebSocketService.SendToOperatorsByBranch(
branchId,
'tableStatus',
tableData
)
await SERVICES.WebSocketService.SendToWaitersByBranch(
branchId,
'tableStatus',
tableData
)
}
return res.status(200).json({ status: 'success', id: table.id, status: table.status })
} catch (err) {
next(err)
}
}
this.CallWaiter = async (req, res, next) => {
logger.child({ path: req.path, request: req.body }).info()
let transaction = await db.sequelize.transaction()
try {
const t1 = performance.now()
const { tableId } = req.body
const table = await db.table.findOne({
where: { id: tableId },
include: [
{ model: db.room, include: [{ model: db.branch }] },
{
model: db.order,
include: [
{
model: db.user,
through: 'order_waiters',
foreginKey: 'orderId',
as: 'orderWaiters',
required: false
}
],
required: false,
where: { status: { [Op.in]: [ORDER_STATUS.ACCEPT] } }
}
]
})
if (!table) throw new NotFound({ lang: req.user?.languageCode })
const historyItem = await db.tableHistory.create({
tableId: table.id,
event: 'waiter',
created: req.user.app,
createdId: req.user.id
})
if (table.orders && table.orders.length > 0) {
for (const order of table.orders) {
for (const waiter of order.orderWaiters) {
await SERVICES.WebSocketService.SendToWaiter(
waiter.id,
'tableEvent',
historyItem
)
}
}
} else {
await SERVICES.WebSocketService.SendToWaitersByBranch(
table.room.branch.id,
'tableEvent',
historyItem
)
}
await await SERVICES.WebSocketService.SendToOperatorsByBranch(
table.room.branch.id,
'tableEvent',
historyItem
)
const time = performance.now() - t1
transaction.commit()
transaction = null
return res.status(200).json({ status: 'success', event: historyItem, time })
} catch (err) {
transaction?.rollback()
next(err)
}
}
this.CallWaiterAccept = async (req, res, next) => {
logger.child({ path: req.path, request: req.body }).info()
let transaction = await db.sequelize.transaction()
try {
const t1 = performance.now()
const { tableId, eventId } = req.body
const table = await db.table.findOne({
where: { id: tableId },
include: [
{ model: db.room, include: [{ model: db.branch }] },
{
model: db.order,
include: [
{
model: db.user,
through: 'order_waiters',
foreginKey: 'orderId',
as: 'orderWaiters',
required: false
}
],
required: false,
where: { status: { [Op.in]: [ORDER_STATUS.ACCEPT] } }
}
]
})
if (!table) throw new NotFound({ lang: req.user?.languageCode })
let historyItem = await db.tableHistory.findOne({ where: { id: eventId } })
if (!historyItem) throw new NotFound({ lang: req.user?.languageCode })
historyItem.eventHandled = true
historyItem.processedId = req.user.id
historyItem.processed = 'waiter'
await historyItem.save()
if (table.orders && table.orders.length > 0) {
for (const order of table.orders) {
for (const waiter of order.orderWaiters) {
await SERVICES.WebSocketService.SendToWaiter(
waiter.id,
'tableEvent',
historyItem
)
}
}
} else {
await SERVICES.WebSocketService.SendToWaitersByBranch(
table.room.branch.id,
'tableEvent',
historyItem
)
}
await await SERVICES.WebSocketService.SendToOperatorsByBranch(
table.room.branch.id,
'tableEvent',
historyItem
)
if (historyItem.createdId) {
await SERVICES.WebSocketService.SendToClient(
historyItem.createdId,
'tableEvent',
historyItem
)
}
const time = performance.now() - t1
transaction.commit()
transaction = null
return res.status(200).json({ status: 'success', event: historyItem, time })
} catch (err) {
transaction?.rollback()
next(err)
}
}
this.PaymentCheck = async (req, res, next) => {
logger.child({ path: req.path, request: req.body }).info()
let transaction = await db.sequelize.transaction()
try {
const t1 = performance.now()
const { tableId, orderId } = req.body
const table = await db.table.findOne({
where: { id: tableId },
include: [
{ model: db.room, include: [{ model: db.branch }] },
{
model: db.order,
include: [
{
model: db.user,
through: 'order_waiters',
foreginKey: 'orderId',
as: 'orderWaiters',
required: false
}
],
required: false,
where: { status: { [Op.in]: [ORDER_STATUS.ACCEPT] } }
}
]
})
if (!table) throw new NotFound({ lang: req.user?.languageCode })
const order = await db.order.findOne({ where: { id: orderId } })
if (!order) throw new NotFound({ lang: req.user?.languageCode })
const historyItem = await db.tableHistory.create({
tableId: table.id,
orderId: order.id,
event: 'check',
created: req.user.app,
createdId: req.user.id
})
for (const order of table.orders) {
for (const waiter of order.orderWaiters) {
await SERVICES.WebSocketService.SendToWaiter(
waiter.id,
'tableEvent',
historyItem
)
}
}
await await SERVICES.WebSocketService.SendToOperatorsByBranch(
table.room.branch.id,
'tableEvent',
historyItem
)
const time = performance.now() - t1
transaction.commit()
transaction = null
return res.status(200).json({ status: 'success', event: historyItem, time })
} catch (err) {
transaction?.rollback()
next(err)
}
}
this.PaymentCheckAccept = async (req, res, next) => {
logger.child({ path: req.path, request: req.body }).info()
let transaction = await db.sequelize.transaction()
try {
const t1 = performance.now()
const { tableId, eventId } = req.body
const table = await db.table.findOne({
where: { id: tableId },
include: [
{ model: db.room, include: [{ model: db.branch }] },
{
model: db.order,
include: [
{
model: db.user,
through: 'order_waiters',
foreginKey: 'orderId',
as: 'orderWaiters',
required: false
}
],
required: false,
where: { status: { [Op.in]: [ORDER_STATUS.ACCEPT] } }
}
]
})
if (!table) throw new NotFound({ lang: req.user?.languageCode })
let historyItem = await db.tableHistory.findOne({ where: { id: eventId } })
if (!historyItem) throw new NotFound({ lang: req.user?.languageCode })
historyItem.eventHandled = true
historyItem.processedId = req.user.id
historyItem.processed = 'waiter'
await historyItem.save()
for (const order of table.orders) {
for (const waiter of order.orderWaiters) {
await SERVICES.WebSocketService.SendToWaiter(
waiter.id,
'tableEvent',
historyItem
)
}
}
if (historyItem.createdId) {
await SERVICES.WebSocketService.SendToClient(
historyItem.createdId,
'tableEvent',
historyItem
)
}
await await SERVICES.WebSocketService.SendToOperatorsByBranch(
table.room.branch.id,
'tableEvent',
historyItem
)
const time = performance.now() - t1
transaction.commit()
transaction = null
return res.status(200).json({ status: 'success', event: historyItem, time })
} catch (err) {
transaction?.rollback()
next(err)
}
}
}