Commit 01ea76a8 by yixinjj

重构服务类

1 parent d01edbac
...@@ -13,11 +13,10 @@ export function IsNumberOrNumberString(validationOptions?: ValidationOptions) { ...@@ -13,11 +13,10 @@ export function IsNumberOrNumberString(validationOptions?: ValidationOptions) {
validator: { validator: {
validate(value: any, args: ValidationArguments) { validate(value: any, args: ValidationArguments) {
// 如果值为空(null, undefined, ''),则验证通过 // 如果值为空(null, undefined, ''),则验证通过
if(value === '') return false if (value === '') return false
if (value === null || value === undefined) { if (value === null || value === undefined) {
return true return true
} }
// 尝试将值转换为数字,如果转换成功或原本就是数字,则验证通过 // 尝试将值转换为数字,如果转换成功或原本就是数字,则验证通过
// 注意:这里使用了 Number.isNaN 来检查转换结果是否为 NaN,从而排除非数字字符串 // 注意:这里使用了 Number.isNaN 来检查转换结果是否为 NaN,从而排除非数字字符串
return !Number.isNaN(Number(value)) return !Number.isNaN(Number(value))
......
...@@ -16,13 +16,6 @@ model log_config { ...@@ -16,13 +16,6 @@ model log_config {
export class LogConfigDto { export class LogConfigDto {
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: '设备信息ID',
required: false,
default: 0
})
id: number
@ApiProperty({
type: Number,
description: '设备ID', description: '设备ID',
required: true, required: true,
default: 0 default: 0
...@@ -54,13 +47,16 @@ export class LogConfigDto { ...@@ -54,13 +47,16 @@ export class LogConfigDto {
default: '' default: ''
}) })
updated_at: Date | string updated_at: Date | string
}
export class LogConfigUpdateDto {
@ApiProperty({ @ApiProperty({
type: Array, type: Number,
description: '需要上传的用户字段', description: '日志保存天数',
required: false, required: false,
default: [] default: ''
}) })
user_fields: [] log_saved_days: number
}
}
\ No newline at end of file \ No newline at end of file
import { IsString, IsNumber, IsNotEmpty, MaxLength, IsMobilePhone, IsOptional, isNotEmpty } from 'class-validator' import { IsString, IsNumber, IsNotEmpty, MaxLength, IsMobilePhone, IsOptional, isNotEmpty } from 'class-validator'
import { ApiProperty } from '@nestjs/swagger' import { ApiProperty } from '@nestjs/swagger'
import { BaseDto } from './base.dto' import { BaseDto } from './base.dto'
import { LogConfigUpdateDto } from './config.dto'
export class UserBaseDto {
@ApiProperty({
type: String,
description: '设备用户',
default: ''
})
user?: string
@IsMobilePhone('zh-CN', {}, { message: '手机号格式不正确' })
@IsOptional()
@ApiProperty({
type: String,
description: '使用者手机号',
default: ''
})
mobile?: string
@ApiProperty({
type: String,
description: '使用者商户名称',
default: ''
})
merchant_name?: string
}
export class DeviceQueryDto extends BaseDto { export class DeviceQueryDto extends BaseDto {
@ApiProperty({ @ApiProperty({
...@@ -19,6 +45,8 @@ export class DeviceQueryDto extends BaseDto { ...@@ -19,6 +45,8 @@ export class DeviceQueryDto extends BaseDto {
}) })
user?: string user?: string
@IsMobilePhone('zh-CN', {}, { message: '手机号格式不正确' })
@IsOptional()
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: '使用者手机号', description: '使用者手机号',
...@@ -26,6 +54,13 @@ export class DeviceQueryDto extends BaseDto { ...@@ -26,6 +54,13 @@ export class DeviceQueryDto extends BaseDto {
default: '' default: ''
}) })
mobile?: string mobile?: string
@ApiProperty({
type: Number,
description: '在线状态 1:在线,2:离线,0:弃用',
required: false
})
status?: number
} }
export class DeviceFindOneDto { export class DeviceFindOneDto {
...@@ -48,7 +83,7 @@ export class DeviceFindOneDto { ...@@ -48,7 +83,7 @@ export class DeviceFindOneDto {
mobile: string mobile: string
} }
export class AddDeviceDto { export class AddDeviceDto extends UserBaseDto {
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: '设备SN', description: '设备SN',
...@@ -59,28 +94,47 @@ export class AddDeviceDto { ...@@ -59,28 +94,47 @@ export class AddDeviceDto {
@IsNotEmpty({ message: '设备SN不能为空' }) @IsNotEmpty({ message: '设备SN不能为空' })
sn: string sn: string
} }
/**
* model device_info { export class AddBaseDto{
id Int @id @default(autoincrement())
device_id Int @unique(map: "device_id") @default(0)
user String? @db.VarChar(20)
status Int? @db.TinyInt
last_log_upload_time String? @db.VarChar(30)
last_log_remove_time String? @db.VarChar(30)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
mobile String? @db.VarChar(20)
merchant_name String? @db.VarChar(50)
log_config log_config?
} }
*/
export class AddDeviceInfoDto { export class AddDeviceInfoDto {
@ApiProperty({ @ApiProperty({
description: 'SN 设备表的SN'
})
sn?: string
@ApiProperty({
description: '设备信息 包括 user mobile merchant_name'
})
device_info?: UserBaseDto
@ApiProperty({
description: '设备配置信息 包括 log_saved_days'
})
log_config?: LogConfigUpdateDto
@ApiProperty({
description: '设备对应的日志字段集合 '
})
user_fields?: Array<Number>
@ApiProperty({
type: Number, type: Number,
description: '设备信息ID', description: '创建时间',
default: 0 default: ''
}) })
id: number created_at: Date
@ApiProperty({
type: Date,
description: '更新时间',
default: ''
})
updated_at: Date
}
export class UpdateDeviceInfoDto {
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: '设备ID', description: '设备ID',
...@@ -91,32 +145,23 @@ export class AddDeviceInfoDto { ...@@ -91,32 +145,23 @@ export class AddDeviceInfoDto {
device_id: number device_id: number
@ApiProperty({ @ApiProperty({
type: String, description: 'SN 设备表的SN'
description: '设备用户',
default: ''
}) })
user: string sn?: string
@ApiProperty({ @ApiProperty({
type: Number, description: '设备信息 包括 user mobile merchant_name'
description: '设备状态',
default: 0
}) })
status: number device_info?: UserBaseDto
@ApiProperty({ @ApiProperty({
type: String, description: '设备配置信息 包括 log_saved_days'
description: '最后一次上传日志的时间',
default: ''
}) })
last_log_upload_time: string log_config?: LogConfigUpdateDto
@ApiProperty({ @ApiProperty({
type: String, description: '设备对应的日志字段集合 '
description: '最后一次移除日志的时间',
default: ''
}) })
last_log_remove_time: string user_fields?: Array<Number>
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
...@@ -131,27 +176,5 @@ export class AddDeviceInfoDto { ...@@ -131,27 +176,5 @@ export class AddDeviceInfoDto {
default: '' default: ''
}) })
updated_at: Date updated_at: Date
@IsMobilePhone('zh-CN', {}, { message: '手机号格式不正确' })
@IsOptional()
@ApiProperty({
type: String,
description: '使用者手机号',
default: ''
})
mobile: string
@ApiProperty({
type: String,
description: '使用者商户名称',
default: ''
})
merchant_name: string
@ApiProperty({
type: Object,
description: '日志配置',
default: {}
})
log_config: {}
} }
...@@ -5,26 +5,44 @@ export class DeviceStatusDto { ...@@ -5,26 +5,44 @@ export class DeviceStatusDto {
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: '设备ID', description: '设备ID',
default: 0 required: true,
}) })
@IsNumber({}, { message: '设备ID必须是数字' }) @IsNumber({}, { message: '设备ID必须是数字' })
@IsNotEmpty({ message: '设备ID不能为空' }) @IsNotEmpty({ message: '设备ID不能为空' })
device_id: number device_id: number
@IsNumber({}, { message: '设备状态必须是数字' })
@IsNotEmpty({ message: '设备状态不能为空' })
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: '设备状态', description: '设备状态',
default: 0 required: false,
}) })
status: number status?: number
@IsNotEmpty({ message: 'SocketID不能为空' })
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'SocketID', description: '最后一次上传日志的时间',
default: '' required: false,
}) })
socket_id: string last_log_upload_time?: string
@ApiProperty({
type: String,
description: '最后一次移除日志的时间',
required: false,
})
last_log_remove_time?: string
@ApiProperty({
type: String,
description: '最后一次登录时间',
required: false,
})
last_login_time?: string
@ApiProperty({
type: String,
description: '最后一次离线时间',
required: false,
})
last_offline_time?: string
} }
...@@ -17,8 +17,9 @@ export class BroadcastService { ...@@ -17,8 +17,9 @@ export class BroadcastService {
} }
// // 广播消息 // // 广播消息
async onMessage(param: any): Promise<CommonTypes.IResData> { async onMessage(param: any): Promise<CommonTypes.IResData> {
if (param?.code === RESPONSE_CODE.SUCCESS && param?.data?.command === Command.RemoveLog) { if (param?.code == RESPONSE_CODE.SUCCESS && param?.data?.command === Command.RemoveLog) {
this.eventEmitter.emit(Events.OnLogFileRemoved, { device_id: param.device_id, last_log_remove_time: new Date() }) const statusInfo: DeviceStatus.IDeviceStatus = { device_id: param.device_id, last_log_remove_time: new Date() }
this.eventEmitter.emit(Events.OnLogFileRemoved, statusInfo)
return return
} }
const res: AxiosResponse<any, any> = await this.httpService const res: AxiosResponse<any, any> = await this.httpService
......
...@@ -16,12 +16,12 @@ export class ConfigController { ...@@ -16,12 +16,12 @@ export class ConfigController {
@UsePipes(new PagesPipe()) @UsePipes(new PagesPipe())
@UsePipes(new ParseDeviceIdPipe()) @UsePipes(new ParseDeviceIdPipe())
@ApiOperation({ summary: '根据设备号获取配置' }) @ApiOperation({ summary: '根据设备号获取配置' })
async findAll(@Query() params: LogConfigDto): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResponse[]>> { async findAll(@Query() params: LogConfigDto): Promise<CommonTypes.IResData<ConfigTypes.LogConfigResult[]>> {
return this.configService.findAll(params) return this.configService.findAll(params)
} }
@Post('/add') @Post('/add')
@ApiOperation({ summary: '新增设备配置' }) @ApiOperation({ summary: '新增或更新设备配置,de' })
addConfig(@Body() param: LogConfigDto): Promise<CommonTypes.IResData> { upsertConfig(@Body() param: LogConfigDto): Promise<CommonTypes.IResData> {
return this.configService.addConfig(param) return this.configService.upsertConfig(param)
} }
} }
...@@ -27,7 +27,7 @@ export class ConfigService { ...@@ -27,7 +27,7 @@ export class ConfigService {
return resBody return resBody
} }
async addConfig(config: ConfigTypes.ILogConfig): Promise<CommonTypes.IResData> { async upsertConfig(config: ConfigTypes.ILogConfig): Promise<CommonTypes.IResData> {
const now = new Date() const now = new Date()
await this.prisma.log_config.upsert({ where: { device_id: config.device_id }, update: { ...config, updated_at: now }, create: { ...config, created_at: now, updated_at: now } }) await this.prisma.log_config.upsert({ where: { device_id: config.device_id }, update: { ...config, updated_at: now }, create: { ...config, created_at: now, updated_at: now } })
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' } return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
......
import { Controller, Get, Post, Body, UseInterceptors, Query, UsePipes, Inject } from '@nestjs/common' import { Controller, Get, Post, Body, UseInterceptors, Query, UsePipes, Inject } from '@nestjs/common'
import { DeviceService } from './device.service' import { DeviceService } from './device.service'
import { TransformInterceptor } from '../../common/interceptors' import { TransformInterceptor } from '../../common/interceptors'
import { AddDeviceDto, AddDeviceInfoDto, DeviceFindOneDto, DeviceQueryDto, DeviceStatusDto } from '../../dto' import { AddDeviceDto, AddDeviceInfoDto, DeviceFindOneDto, DeviceQueryDto, DeviceStatusDto, UpdateDeviceInfoDto } from '../../dto'
import { PagesPipe, ValidationPipe } from '../../common/pipes' import { PagesPipe, ValidationPipe } from '../../common/pipes'
import { OnEvent, EventEmitter2 } from '@nestjs/event-emitter' import { OnEvent, EventEmitter2 } from '@nestjs/event-emitter'
import { WsAccess, Events, WsMessageType, Command, RESPONSE_CODE } from '../../common/enums' import { WsAccess, Events, WsMessageType, Command, RESPONSE_CODE } from '../../common/enums'
...@@ -49,7 +49,7 @@ export class DeviceController { ...@@ -49,7 +49,7 @@ export class DeviceController {
*/ */
@Post('/add') @Post('/add')
@ApiOperation({ summary: '添加设备' }) @ApiOperation({ summary: '添加设备' })
async addDevice(@Body() param: AddDeviceDto): Promise<CommonTypes.IResponseBase> { async addDevice(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResponseBase> {
// console.log(param) // console.log(param)
return await this.deviceService.addDevice(param) return await this.deviceService.addDevice(param)
} }
...@@ -61,7 +61,7 @@ export class DeviceController { ...@@ -61,7 +61,7 @@ export class DeviceController {
*/ */
@Post('/addInfo') @Post('/addInfo')
@ApiOperation({ summary: '添加设备信息' }) @ApiOperation({ summary: '添加设备信息' })
async addDeviceInfo(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResponseBase> { async addDeviceInfo(@Body() param: UpdateDeviceInfoDto): Promise<CommonTypes.IResData> {
// console.log(param) // console.log(param)
return await this.deviceService.addDeviceInfo(param) return await this.deviceService.addDeviceInfo(param)
} }
...@@ -74,8 +74,7 @@ export class DeviceController { ...@@ -74,8 +74,7 @@ export class DeviceController {
*/ */
@Post('/updateInfo') @Post('/updateInfo')
@ApiOperation({ summary: '修改设备信息' }) @ApiOperation({ summary: '修改设备信息' })
@OnEvent(Events.OnLogFileRemoved) async updateDeviceInfo(@Body() param: UpdateDeviceInfoDto): Promise<CommonTypes.IResData> {
async updateDeviceInfo(@Body() param: AddDeviceInfoDto): Promise<CommonTypes.IResponseBase> {
return await this.deviceService.updateDeviceInfo(param) return await this.deviceService.updateDeviceInfo(param)
} }
...@@ -86,9 +85,10 @@ export class DeviceController { ...@@ -86,9 +85,10 @@ export class DeviceController {
* @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象 * @returns 一个Promise,成功时解析为包含CommonTypes.IResponseBase接口的CommonTypes.IResData对象
*/ */
@OnEvent(Events.OnConnected) @OnEvent(Events.OnConnected)
@OnEvent(Events.OnLogFileRemoved)
@Post('/upsertStatus') @Post('/upsertStatus')
@ApiOperation({ summary: '更新设备状态' }) @ApiOperation({ summary: '更新设备状态' })
async upsertDeviceStatus(@Body() param: DeviceStatusDto): Promise<void | CommonTypes.IResponseBase> { async upsertDeviceStatus(@Body() param: DeviceStatusDto): Promise<void | CommonTypes.IResData> {
return await this.deviceService.upsertDeviceStatus(param).catch(error => { return await this.deviceService.upsertDeviceStatus(param).catch(error => {
const out: WsTypes.WsConnError = { message: WsAccess.ConnFailure, device_id: param.device_id } const out: WsTypes.WsConnError = { message: WsAccess.ConnFailure, device_id: param.device_id }
this.eventEmitter.emit(Events.OnConnectError, out) this.eventEmitter.emit(Events.OnConnectError, out)
...@@ -104,7 +104,7 @@ export class DeviceController { ...@@ -104,7 +104,7 @@ export class DeviceController {
@Post('/offlineAll') @Post('/offlineAll')
@OnEvent(Events.OnOfflineAll) @OnEvent(Events.OnOfflineAll)
@ApiOperation({ summary: '修改所有设备状态为离线' }) @ApiOperation({ summary: '修改所有设备状态为离线' })
async resetAllDeviceStatus(): Promise<void | CommonTypes.IResponseBase> { async resetAllDeviceStatus(): Promise<void | CommonTypes.IResData> {
return await this.deviceService.resetAllDeviceStatus() return await this.deviceService.resetAllDeviceStatus()
} }
...@@ -116,7 +116,14 @@ export class DeviceController { ...@@ -116,7 +116,14 @@ export class DeviceController {
} }
@Get('/addAll') @Get('/addAll')
@ApiOperation({ summary: '批量导入设备,用于初始化数据' }) @ApiOperation({ summary: '批量导入设备,用于初始化数据' })
async addAll(devices: Array<any>): Promise<void | CommonTypes.IResponseBase> { async addAll(devices: Array<any>): Promise<void | CommonTypes.IResData> {
// return this.deviceService.addAll(devices) // return this.deviceService.addAll(devices)
} }
@Get('/upsertFields')
@ApiOperation({ summary: '添加设备关联的日志字段' })
upsertFields() {
}
} }
...@@ -18,7 +18,7 @@ export class DeviceService implements OnModuleInit { ...@@ -18,7 +18,7 @@ export class DeviceService implements OnModuleInit {
async onModuleInit() { async onModuleInit() {
this.resetAllDeviceStatus() this.resetAllDeviceStatus()
} }
async findAll({ user, mobile, sn, skip, take }: DeviceTypes.IQueryDevices): Promise<CommonTypes.IResData<DeviceTypes.TDevice[]>> { async findAll({ user, mobile, sn, skip, take, status }: DeviceTypes.IQueryDevices): Promise<CommonTypes.IResData<DeviceTypes.IDevice[]>> {
const where = { const where = {
sn: { sn: {
contains: sn contains: sn
...@@ -30,6 +30,9 @@ export class DeviceService implements OnModuleInit { ...@@ -30,6 +30,9 @@ export class DeviceService implements OnModuleInit {
user: { user: {
contains: user contains: user
} }
},
device_status: {
status: status || status == 0 ? +status : undefined
} }
} }
const result: DeviceTypes.IDeviceResult[] = await this.prisma.device.findMany({ const result: DeviceTypes.IDeviceResult[] = await this.prisma.device.findMany({
...@@ -64,12 +67,13 @@ export class DeviceService implements OnModuleInit { ...@@ -64,12 +67,13 @@ export class DeviceService implements OnModuleInit {
select: { status: true, last_log_remove_time: true, last_log_upload_time: true, last_login_time: true, last_offline_time: true } select: { status: true, last_log_remove_time: true, last_log_upload_time: true, last_login_time: true, last_offline_time: true }
} }
}, },
where where,
orderBy: { created_at: 'desc' }
}) })
const total: number = await this.prisma.device.count({ const total: number = await this.prisma.device.count({
where where
}) })
const data: DeviceTypes.TDevice[] = result.reduce((pre: DeviceTypes.TDevice[], cur: DeviceTypes.IDeviceResult) => { const data: DeviceTypes.IDevice[] = result.reduce((pre: DeviceTypes.IDevice[], cur: DeviceTypes.IDeviceResult) => {
pre.push({ pre.push({
id: cur.id, id: cur.id,
sn: cur.sn, sn: cur.sn,
...@@ -86,7 +90,7 @@ export class DeviceService implements OnModuleInit { ...@@ -86,7 +90,7 @@ export class DeviceService implements OnModuleInit {
}) })
return pre return pre
}, []) }, [])
const resBody: CommonTypes.IResData<DeviceTypes.TDevice[]> = { total, data } const resBody: CommonTypes.IResData<DeviceTypes.IDevice[]> = { total, data }
return resBody return resBody
} }
...@@ -97,55 +101,97 @@ export class DeviceService implements OnModuleInit { ...@@ -97,55 +101,97 @@ export class DeviceService implements OnModuleInit {
return { code: RESPONSE_CODE.SUCCESS, data: deviceInfo } return { code: RESPONSE_CODE.SUCCESS, data: deviceInfo }
} }
async addDevice(device: CommonTypes.ISn): Promise<CommonTypes.IResData> { async addDevice(device: Omit<DeviceTypes.IDeviceSaves, 'device_id'>): Promise<CommonTypes.IResData> {
const { device_info, log_config, user_fields, sn } = device
await this.prisma.$transaction(async prisma => { await this.prisma.$transaction(async prisma => {
const { id } = await prisma.device.create({ data: device, select: { id: true } }) const now = new Date()
// await this.addDeviceInfo({device_id:id}) const { id } = await prisma.device.create({ data: { sn, created_at: now }, select: { id: true } })
await prisma.device_info.create({ data: { device_id: id, created_at: new Date(), updated_at: new Date() } }) const device_id = id
if (device_info) {
await prisma.device_info.create({ data: { device_id, user: device_info.user, mobile: device_info.mobile, merchant_name: device_info.merchant_name, updated_at: now, created_at: now } })
}
if (log_config) {
await prisma.log_config.create({ data: { log_saved_days: log_config.log_saved_days, device_id, created_at: now, updated_at: now } })
}
if (user_fields) {
await prisma.field_relation.deleteMany({ where: { device_id } })
await prisma.field_relation.createMany({
data: user_fields.map((item: number) => ({ device_id, field_id: item }))
})
}
await prisma.device_status.create({ data: { device_id: id, status: WsStatus.Offline } }) await prisma.device_status.create({ data: { device_id: id, status: WsStatus.Offline } })
}) })
return { code: RESPONSE_CODE.SUCCESS, message: '添加设备成功' } return { code: RESPONSE_CODE.SUCCESS, message: '添加设备成功' }
} }
async addDeviceInfo(deviceInfo: DeviceTypes.TOneDeviceInfo): Promise<CommonTypes.IResData> { async addDeviceInfo(deviceInfo: DeviceTypes.IDeviceSaves): Promise<CommonTypes.IResData> {
deviceInfo.created_at = new Date() const now = new Date()
deviceInfo.updated_at = new Date() const { device_id, ...data } = deviceInfo
const { device_info, log_config, user_fields, sn } = data
await this.prisma.$transaction(async prisma => { await this.prisma.$transaction(async prisma => {
await prisma.device_info.create({ data: deviceInfo }) if (sn) {
await prisma.device.update({ where: { id: device_id }, data: { sn } })
}
if (device_info) {
await prisma.device_info.create({ data: { device_id, user: device_info.user, mobile: device_info.mobile, merchant_name: device_info.merchant_name, updated_at: now, created_at: now } })
}
if (log_config) {
await prisma.log_config.create({ data: { log_saved_days: log_config.log_saved_days, device_id, created_at: now, updated_at: now } })
}
if (user_fields) {
await prisma.field_relation.deleteMany({ where: { device_id } })
await prisma.field_relation.createMany({
data: user_fields.map((item: number) => ({ device_id, field_id: item }))
})
}
await prisma.device_status.create({ data: { device_id: deviceInfo.device_id, status: WsStatus.Offline } }) await prisma.device_status.create({ data: { device_id: deviceInfo.device_id, status: WsStatus.Offline } })
}) })
return { code: RESPONSE_CODE.SUCCESS, message: '添加设备信息成功' } return { code: RESPONSE_CODE.SUCCESS, message: '添加设备信息成功' }
} }
async updateDeviceInfo(deviceInfo: DeviceTypes.TOneDeviceInfo): Promise<CommonTypes.IResData> { async updateDeviceInfo(deviceInfo: DeviceTypes.IDeviceSaves): Promise<CommonTypes.IResData> {
const { device_id, ...data } = deviceInfo const { device_id, ...data } = deviceInfo
data.updated_at = new Date() const where = { device_id }
await this.prisma.device_info.update({ await this.prisma.$transaction(async prisma => {
where: { const now = new Date()
device_id: deviceInfo.device_id const { device_info, log_config, user_fields, sn } = data
}, if (sn) {
data await prisma.device.update({ where: { id: device_id }, data: { sn } })
}
if (device_info) {
device_info.updated_at = now
await prisma.device_info.update({
where,
data: { user: device_info.user, mobile: device_info.mobile, merchant_name: device_info.merchant_name, updated_at: now }
})
}
if (log_config) {
await prisma.log_config.update({
where,
data: { log_saved_days: log_config.log_saved_days, updated_at: now }
})
}
if (user_fields) {
await prisma.field_relation.deleteMany({ where })
await prisma.field_relation.createMany({
data: user_fields.map((item: number) => ({ device_id, field_id: item }))
})
}
}) })
return { code: RESPONSE_CODE.SUCCESS, message: '设备信息更新成功' } return { code: RESPONSE_CODE.SUCCESS, message: '设备信息更新成功' }
} }
async upsertDeviceStatus(data: DeviceStatus.IDeviceStatus): Promise<CommonTypes.IResData> { async upsertDeviceStatus(data: DeviceStatus.IDeviceStatus): Promise<CommonTypes.IResData> {
await this.prisma.device_status.upsert({ await this.prisma.device_status.upsert({
where: { where: { device_id: data.device_id },
device_id: data.device_id create: { device_id: data.device_id, status: WsStatus.Offline },
}, update: { status: data.status, last_login_time: data.status === WsStatus.Online ? new Date() : undefined, last_offline_time: data.status === WsStatus.Offline ? new Date() : undefined, last_log_remove_time: data.last_log_remove_time, last_log_upload_time: data.last_log_upload_time }
create: data,
update: {
status: data.status
}
}) })
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' } return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
} }
async resetAllDeviceStatus(): Promise<CommonTypes.IResData> { async resetAllDeviceStatus(): Promise<CommonTypes.IResData> {
Logger.warn('========重置所有设备状态========') Logger.warn('========重置所有设备状态========')
await this.prisma.device_status.updateMany({ await this.prisma.device_status.updateMany({
data: { data: { status: WsStatus.Offline }
status: WsStatus.Offline
}
}) })
return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' } return { code: RESPONSE_CODE.SUCCESS, message: '设备状态更新成功' }
} }
......
...@@ -25,7 +25,8 @@ export class FieldsService { ...@@ -25,7 +25,8 @@ export class FieldsService {
}, },
type type
} }
const result: FieldTypes.IFiled[] = await this.prismaService.field.findMany({ skip, take, where }) const result: FieldTypes.IFiled[] = await this.prismaService.field.findMany({ skip, take, where, orderBy: { created_at: 'desc' } })
const total = await this.prismaService.field.count({ where }) const total = await this.prismaService.field.count({ where })
return { code: RESPONSE_CODE.SUCCESS, message: '查询成功', total, data: result } return { code: RESPONSE_CODE.SUCCESS, message: '查询成功', total, data: result }
......
...@@ -37,7 +37,8 @@ export class FileService { ...@@ -37,7 +37,8 @@ export class FileService {
contains: filename contains: filename
} }
} }
const files: FileTypes.IFile<DocTypes | string>[] = await this.prisma.file.findMany({ skip, take, where }) const files: FileTypes.IFile<DocTypes | string>[] = await this.prisma.file.findMany({ skip, take, where, orderBy: { created_at: 'desc' } })
const total: number = await this.prisma.file.count({ const total: number = await this.prisma.file.count({
where where
}) })
......
declare namespace DeviceTypes { declare namespace DeviceTypes {
/** type IQueryDevices = Partial<CommonTypes.IQueryBase & CommonTypes.ISn & CommonTypes.IUser & Pick<DeviceStatus.Status,'status'>>
* 查询设备信息的查询对象接口
*
* @param user - 用户
* @param mobile - 手机号
* @param sn - 设备号
* @param skip - 可选,跳过的记录数量
* @param take - 可选,获取的记录数量
*/
type IQueryDevices = Partial<CommonTypes.IQueryBase & CommonTypes.ISn & CommonTypes.IUser>
type IDeviceInfo = CommonTypes.ITime & CommonTypes.IUser type TDeviceInfo = CommonTypes.ITime & Partial<CommonTypes.IUser>
type TDeviceInfoResult = Omit<IDeviceInfo, 'created_at' | 'updated_at' | 'device_id'> type TOneDeviceInfo = TDeviceInfo & CommonTypes.IDeviceId
/** interface IDevice extends CommonTypes.IId, CommonTypes.ISn, DeviceStatus.Status, Partial<TDeviceInfo>, Partial<ConfigTypes.ILogConfig> {
* model device_info {
id Int @id @default(autoincrement())
device_id Int @unique(map: "device_id") @default(0)
user String? @db.VarChar(20)
status Int? @db.TinyInt
last_log_upload_time String? @db.VarChar(30)
last_log_remove_time String? @db.VarChar(30)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
mobile String? @db.VarChar(20)
merchant_name String? @db.VarChar(50)
log_config log_config?
}*/
type TOneDeviceInfo = IDeviceInfo & CommonTypes.IDeviceId
/**
* 表示设备结果的接口
*/
type TDevice= {
fields: FieldTypes.TFieldRequird[] fields: FieldTypes.TFieldRequird[]
} & CommonTypes.IId& CommonTypes.IUser & DeviceStatus.Status &Partial<IDeviceInfo> & Partial<ConfigTypes.ILogConfig> & CommonTypes.ISn }
type IDeviceResult = { interface IDeviceResult extends CommonTypes.IId, CommonTypes.ISn, Partial<Pick<CommonTypes.ITime, 'created_at'>> {
device_info: Partial<IDeviceInfo> device_info: Partial<TDeviceInfo>
log_config: Partial<ConfigTypes.ILogConfig> log_config: Partial<ConfigTypes.ILogConfig>
device_status: DeviceStatus.Status device_status: DeviceStatus.Status
fields: IFields[] fields: IFields[]
}
} & CommonTypes.IId & CommonTypes.ISn & Partial<Pick<CommonTypes.ITime, 'created_at'>> interface IDeviceSaves extends CommonTypes.IDeviceId, Partial<CommonTypes.ISn>{
device_info?: Partial<TDeviceInfo>,
log_config?: Partial<ConfigTypes.ILogConfig>,
/** user_fields?: Array<Number>
* 表示日志用户字段的接口 }
*/
interface IFields { interface IFields {
/**
* 日志用户字段的详细信息
*/
field?: FieldTypes.TFieldRequird field?: FieldTypes.TFieldRequird
} }
} }
declare namespace DeviceStatus { declare namespace DeviceStatus {
interface IDeviceStatus extends CommonTypes.IDeviceId{ interface IDeviceStatus extends CommonTypes.IDeviceId{
status: number, status?: number,
last_log_upload_time?: string | Date last_log_upload_time?: string | Date
last_log_remove_time?: string | Date last_log_remove_time?: string | Date
last_login_time?: string | Date last_login_time?: string | Date
......
...@@ -2,5 +2,4 @@ declare namespace RelationsTypes { ...@@ -2,5 +2,4 @@ declare namespace RelationsTypes {
interface IRelation extends CommonTypes.IId, CommonTypes.IDeviceId { interface IRelation extends CommonTypes.IId, CommonTypes.IDeviceId {
field_id: number field_id: number
} }
type LogConfigUserFieldsRel = Omit<IRelation, 'id'>
} }
declare namespace UserFieldTypes {
interface ILogUserFields extends CommonTypes.IId {
name: string
}
}
...@@ -18,7 +18,7 @@ declare namespace WsTypes { ...@@ -18,7 +18,7 @@ declare namespace WsTypes {
status: T status: T
message: U message: U
} }
type LoginValidate<T> = { isValidate: boolean; errMsg: T,errorCode: number } type LoginValidate<T> = { isValidate: boolean; errMsg: T; errorCode: number }
type MessageData<T> = { type MessageData<T> = {
command: T command: T
......
# http://localhost:3000/device?pageIndex=1&pageSize=5 # http://localhost:3000/device?status=1
# http://localhost:3000/device/addAll # http://localhost:3000/device/addAll
# http://localhost:3000/device/task # http://localhost:3000/device/task
...@@ -39,9 +39,10 @@ POST http://localhost:3000/broadcast/cmd HTTP/1.1 ...@@ -39,9 +39,10 @@ POST http://localhost:3000/broadcast/cmd HTTP/1.1
{ {
"event":"private", "event":"private",
"device_id":"1000020", "device_id":"1000069",
"data":{ "data":{
"command":"stopPolling", "command":"getLog",
"days":7,
"interval":1000, "interval":1000,
"force":true "force":true
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!