batman
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { ScheduleModule } from '@nestjs/schedule';
|
||||
import { PrismaModule } from './prisma/prisma.module';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { VenuesModule } from './venues/venues.module';
|
||||
import { DevicesModule } from './devices/devices.module';
|
||||
import { TabsModule } from './tabs/tabs.module';
|
||||
import { CommandsModule } from './commands/commands.module';
|
||||
import { AuditModule } from './audit/audit.module';
|
||||
import { JobsModule } from './jobs/jobs.module';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ThrottlerModule.forRoot([{ ttl: 60000, limit: 100 }]),
|
||||
ScheduleModule.forRoot(),
|
||||
PrismaModule,
|
||||
AuthModule,
|
||||
VenuesModule,
|
||||
DevicesModule,
|
||||
TabsModule,
|
||||
CommandsModule,
|
||||
AuditModule,
|
||||
JobsModule,
|
||||
],
|
||||
controllers: [HealthController],
|
||||
providers: [
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: ThrottlerGuard,
|
||||
},
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { AuditService } from './audit.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [AuditService],
|
||||
exports: [AuditService],
|
||||
})
|
||||
export class AuditModule {}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class AuditService {
|
||||
private readonly logger = new Logger(AuditService.name);
|
||||
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
async log(venueId: string, actorType: string, actorId: string, action: string, details?: Record<string, any>) {
|
||||
try {
|
||||
await this.prisma.auditLog.create({
|
||||
data: {
|
||||
id: uuidv4(),
|
||||
venueId,
|
||||
actorType,
|
||||
actorId,
|
||||
action,
|
||||
details: details ? JSON.stringify(details) : null,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to write audit log: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { AuthService } from './auth.service';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
|
||||
@ApiTags('Authentication')
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private authService: AuthService) {}
|
||||
|
||||
@Post('login')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'Login with email and password' })
|
||||
async login(@Body() dto: LoginDto) {
|
||||
return this.authService.login(dto.email, dto.password);
|
||||
}
|
||||
|
||||
@Post('refresh')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'Refresh access token' })
|
||||
async refresh(@Body('refreshToken') refreshToken: string) {
|
||||
return this.authService.refresh(refreshToken);
|
||||
}
|
||||
|
||||
@Post('logout')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'Logout and revoke refresh token' })
|
||||
async logout(@Body('refreshToken') refreshToken: string) {
|
||||
await this.authService.logout(refreshToken);
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtStrategy } from './strategies/jwt.strategy';
|
||||
import { DeviceStrategy } from './strategies/device.strategy';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
PassportModule.register({ defaultStrategy: 'jwt' }),
|
||||
JwtModule.register({
|
||||
secret: process.env.JWT_SECRET || 'dev-jwt-secret-change-in-production',
|
||||
signOptions: { expiresIn: '24h' },
|
||||
}),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, JwtStrategy, DeviceStrategy],
|
||||
exports: [AuthService, JwtModule],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,189 @@
|
||||
import { Injectable, UnauthorizedException, ConflictException, NotFoundException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import * as crypto from 'crypto';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { TOKEN_EXPIRY_DAYS, TOKEN_BYTE_LENGTH, TOKEN_PREFIX_LENGTH } from '@kooltab/shared';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private jwtService: JwtService,
|
||||
private auditService: AuditService,
|
||||
) {}
|
||||
|
||||
async login(email: string, password: string) {
|
||||
const user = await this.prisma.clientUser.findUnique({ where: { email } });
|
||||
if (!user) {
|
||||
throw new UnauthorizedException({ code: 'invalid_credentials', message: 'Invalid email or password' });
|
||||
}
|
||||
|
||||
const valid = await bcrypt.compare(password, user.passwordHash);
|
||||
if (!valid) {
|
||||
throw new UnauthorizedException({ code: 'invalid_credentials', message: 'Invalid email or password' });
|
||||
}
|
||||
|
||||
const payload = { sub: user.id, email: user.email, role: user.role, venueId: user.venueId };
|
||||
const accessToken = this.jwtService.sign(payload);
|
||||
|
||||
const refreshToken = crypto.randomBytes(32).toString('hex');
|
||||
const refreshHash = crypto.createHash('sha256').update(refreshToken).digest('hex');
|
||||
const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 30 days
|
||||
|
||||
await this.prisma.refreshToken.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
tokenHash: refreshHash,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.role,
|
||||
venueId: user.venueId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async refresh(refreshToken: string) {
|
||||
const hash = crypto.createHash('sha256').update(refreshToken).digest('hex');
|
||||
const stored = await this.prisma.refreshToken.findUnique({ where: { tokenHash: hash } });
|
||||
|
||||
if (!stored || stored.revokedAt || stored.expiresAt < new Date()) {
|
||||
throw new UnauthorizedException({ code: 'invalid_refresh_token', message: 'Invalid or expired refresh token' });
|
||||
}
|
||||
|
||||
const user = await this.prisma.clientUser.findUnique({ where: { id: stored.userId } });
|
||||
if (!user) {
|
||||
throw new UnauthorizedException({ code: 'user_not_found', message: 'User not found' });
|
||||
}
|
||||
|
||||
const payload = { sub: user.id, email: user.email, role: user.role, venueId: user.venueId };
|
||||
const accessToken = this.jwtService.sign(payload);
|
||||
|
||||
const newRefreshToken = crypto.randomBytes(32).toString('hex');
|
||||
const newHash = crypto.createHash('sha256').update(newRefreshToken).digest('hex');
|
||||
const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
|
||||
|
||||
await this.prisma.refreshToken.update({
|
||||
where: { id: stored.id },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
|
||||
await this.prisma.refreshToken.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
tokenHash: newHash,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken: newRefreshToken,
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.role,
|
||||
venueId: user.venueId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async logout(refreshToken: string) {
|
||||
const hash = crypto.createHash('sha256').update(refreshToken).digest('hex');
|
||||
await this.prisma.refreshToken.updateMany({
|
||||
where: { tokenHash: hash, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
}
|
||||
|
||||
async generateDeviceToken(): Promise<{ rawToken: string; hash: string; prefix: string; expiresAt: Date }> {
|
||||
const rawBytes = crypto.randomBytes(TOKEN_BYTE_LENGTH);
|
||||
const rawToken = 'dev_' + rawBytes.toString('base64url');
|
||||
const hash = crypto.createHash('sha256').update(rawToken).digest('hex');
|
||||
const prefix = rawToken.substring(0, TOKEN_PREFIX_LENGTH);
|
||||
const expiresAt = new Date(Date.now() + TOKEN_EXPIRY_DAYS * 24 * 60 * 60 * 1000);
|
||||
|
||||
return { rawToken, hash, prefix, expiresAt };
|
||||
}
|
||||
|
||||
async registerDevice(venueId: string, name: string, registrationCode: string) {
|
||||
const code = await this.prisma.registrationCode.findUnique({ where: { code: registrationCode } });
|
||||
|
||||
if (!code || code.usedAt || code.expiresAt < new Date()) {
|
||||
throw new UnauthorizedException({ code: 'invalid_registration_code', message: 'Invalid or expired registration code' });
|
||||
}
|
||||
|
||||
if (code.venueId !== venueId) {
|
||||
throw new UnauthorizedException({ code: 'venue_mismatch', message: 'Registration code does not match venue' });
|
||||
}
|
||||
|
||||
const { rawToken, hash, prefix, expiresAt } = await this.generateDeviceToken();
|
||||
const deviceId = uuidv4();
|
||||
|
||||
await this.prisma.device.create({
|
||||
data: {
|
||||
id: deviceId,
|
||||
venueId,
|
||||
name,
|
||||
tokenHash: hash,
|
||||
tokenPrefix: prefix,
|
||||
tokenExpiresAt: expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
await this.prisma.registrationCode.update({
|
||||
where: { id: code.id },
|
||||
data: { usedAt: new Date() },
|
||||
});
|
||||
|
||||
await this.auditService.log(venueId, 'device', deviceId, 'device_registered', { deviceName: name });
|
||||
|
||||
return { deviceId, token: rawToken, tokenExpiresAt: expiresAt };
|
||||
}
|
||||
|
||||
async validateDevice(deviceId: string, token: string): Promise<any> {
|
||||
const hash = crypto.createHash('sha256').update(token).digest('hex');
|
||||
const device = await this.prisma.device.findUnique({ where: { id: deviceId } });
|
||||
|
||||
if (!device || device.tokenHash !== hash) {
|
||||
throw new UnauthorizedException({ code: 'invalid_device_token', message: 'Invalid device token' });
|
||||
}
|
||||
|
||||
if (device.revokedAt) {
|
||||
throw new UnauthorizedException({ code: 'device_revoked', message: 'Device has been revoked' });
|
||||
}
|
||||
|
||||
if (device.tokenExpiresAt < new Date()) {
|
||||
throw new UnauthorizedException({ code: 'token_expired', message: 'Device token has expired' });
|
||||
}
|
||||
|
||||
return device;
|
||||
}
|
||||
|
||||
async generateRegistrationCode(venueId: string): Promise<{ code: string; expiresAt: Date }> {
|
||||
const code = crypto.randomBytes(3).toString('hex').toUpperCase();
|
||||
const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes
|
||||
|
||||
await this.prisma.registrationCode.create({
|
||||
data: {
|
||||
venueId,
|
||||
code,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
return { code, expiresAt };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class LoginDto {
|
||||
@ApiProperty({ example: 'admin@example.com' })
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@ApiProperty({ example: 'Admin123!' })
|
||||
@IsString()
|
||||
@MinLength(6)
|
||||
password: string;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Injectable, ExecutionContext } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Injectable()
|
||||
export class DeviceAuthGuard extends AuthGuard('device') {
|
||||
handleRequest(err: any, device: any, info: any, context: ExecutionContext) {
|
||||
if (err || !device) {
|
||||
throw err || new (require('@nestjs/common').UnauthorizedException)({ code: 'unauthorized', message: 'Invalid device authentication' });
|
||||
}
|
||||
return device;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Injectable, ExecutionContext } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
handleRequest(err: any, user: any, info: any, context: ExecutionContext) {
|
||||
if (err || !user) {
|
||||
throw err || new (require('@nestjs/common').UnauthorizedException)({ code: 'unauthorized', message: 'Authentication required' });
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { Strategy } from 'passport-custom';
|
||||
import { Request } from 'express';
|
||||
import { AuthService } from '../auth.service';
|
||||
|
||||
@Injectable()
|
||||
export class DeviceStrategy extends PassportStrategy(Strategy, 'device') {
|
||||
constructor(private authService: AuthService) {
|
||||
super();
|
||||
}
|
||||
|
||||
async validate(request: Request): Promise<any> {
|
||||
const authHeader = request.headers.authorization;
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
throw new UnauthorizedException({ code: 'missing_token', message: 'Missing device token' });
|
||||
}
|
||||
|
||||
const token = authHeader.substring(7);
|
||||
const deviceId = request.params.deviceId || request.body?.deviceId;
|
||||
|
||||
if (!deviceId) {
|
||||
throw new UnauthorizedException({ code: 'missing_device_id', message: 'Missing device ID' });
|
||||
}
|
||||
|
||||
const device = await this.authService.validateDevice(deviceId, token);
|
||||
return device;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor() {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: process.env.JWT_SECRET || 'dev-jwt-secret-change-in-production',
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: any) {
|
||||
return {
|
||||
id: payload.sub,
|
||||
email: payload.email,
|
||||
role: payload.role,
|
||||
venueId: payload.venueId,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import {
|
||||
Controller,
|
||||
Post,
|
||||
Get,
|
||||
Param,
|
||||
Query,
|
||||
Body,
|
||||
UseGuards,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Req,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
|
||||
import { CommandsService } from './commands.service';
|
||||
import { DevicesService } from '../devices/devices.service';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { CreateCommandDto } from './dto/create-command.dto';
|
||||
|
||||
@ApiTags('Commands')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('venues/:venueId/commands')
|
||||
export class CommandsController {
|
||||
constructor(
|
||||
private commandsService: CommandsService,
|
||||
private devicesService: DevicesService,
|
||||
) {}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create a remote command' })
|
||||
async create(
|
||||
@Param('venueId') venueId: string,
|
||||
@Body() dto: CreateCommandDto,
|
||||
@Req() req: any,
|
||||
) {
|
||||
return this.commandsService.create(venueId, dto, req.user);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'List command history' })
|
||||
@ApiQuery({ name: 'status', required: false })
|
||||
@ApiQuery({ name: 'limit', required: false })
|
||||
@ApiQuery({ name: 'offset', required: false })
|
||||
async findAll(
|
||||
@Param('venueId') venueId: string,
|
||||
@Query('status') status?: string,
|
||||
@Query('limit') limit?: string,
|
||||
@Query('offset') offset?: string,
|
||||
) {
|
||||
return this.commandsService.findAll(venueId, {
|
||||
status,
|
||||
limit: limit ? parseInt(limit, 10) : 50,
|
||||
offset: offset ? parseInt(offset, 10) : 0,
|
||||
});
|
||||
}
|
||||
|
||||
@Post('devices/:deviceId/revoke')
|
||||
@UseGuards(RolesGuard)
|
||||
@Roles('admin')
|
||||
@ApiOperation({ summary: 'Revoke a device' })
|
||||
async revoke(
|
||||
@Param('venueId') venueId: string,
|
||||
@Param('deviceId') deviceId: string,
|
||||
) {
|
||||
return this.devicesService.revoke(venueId, deviceId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { DevicesModule } from '../devices/devices.module';
|
||||
import { CommandsController } from './commands.controller';
|
||||
import { CommandsService } from './commands.service';
|
||||
|
||||
@Module({
|
||||
imports: [DevicesModule],
|
||||
controllers: [CommandsController],
|
||||
providers: [CommandsService],
|
||||
exports: [CommandsService],
|
||||
})
|
||||
export class CommandsModule {}
|
||||
@@ -0,0 +1,157 @@
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { CreateCommandDto } from './dto/create-command.dto';
|
||||
import { COMMAND_EXPIRY_HOURS, DEVICE_OFFLINE_THRESHOLD_MS } from '@kooltab/shared';
|
||||
|
||||
@Injectable()
|
||||
export class CommandsService {
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private auditService: AuditService,
|
||||
) {}
|
||||
|
||||
async create(venueId: string, dto: CreateCommandDto, user: any) {
|
||||
if (!dto.paymentMethod) {
|
||||
throw new BadRequestException({
|
||||
code: 'payment_method_required',
|
||||
message: 'Payment method must be explicitly selected',
|
||||
});
|
||||
}
|
||||
|
||||
const validMethods = ['cash', 'payconiq', 'payment_pending'];
|
||||
if (!validMethods.includes(dto.paymentMethod)) {
|
||||
throw new BadRequestException({
|
||||
code: 'invalid_payment_method',
|
||||
message: `Payment method must be one of: ${validMethods.join(', ')}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Use transaction for consistency
|
||||
const result = await this.prisma.$transaction(async (tx) => {
|
||||
// Resolve tab ownership
|
||||
const ownership = await tx.tabOwnership.findUnique({
|
||||
where: { venueId_tabId: { venueId, tabId: dto.tabId } },
|
||||
});
|
||||
|
||||
if (!ownership) {
|
||||
throw new NotFoundException({
|
||||
code: 'tab_not_owned',
|
||||
message: 'Tab is not associated with any device',
|
||||
});
|
||||
}
|
||||
|
||||
const device = await tx.device.findUnique({ where: { id: ownership.deviceId } });
|
||||
if (!device) {
|
||||
throw new NotFoundException({
|
||||
code: 'device_not_found',
|
||||
message: 'Owning device not found',
|
||||
});
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const expiresAt = new Date(now.getTime() + COMMAND_EXPIRY_HOURS * 60 * 60 * 1000);
|
||||
|
||||
const command = await tx.remoteCommand.create({
|
||||
data: {
|
||||
id: uuidv4(),
|
||||
venueId,
|
||||
deviceId: device.id,
|
||||
targetTabId: dto.tabId,
|
||||
type: dto.type || 'close_tab',
|
||||
expectedVersion: dto.expectedVersion,
|
||||
paymentMethod: dto.paymentMethod,
|
||||
requestedBy: user.name || user.email,
|
||||
status: 'pending',
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: {
|
||||
id: uuidv4(),
|
||||
venueId,
|
||||
actorType: 'client_user',
|
||||
actorId: user.id,
|
||||
action: 'command_created',
|
||||
details: JSON.stringify({
|
||||
commandId: command.id,
|
||||
tabId: dto.tabId,
|
||||
type: dto.type,
|
||||
paymentMethod: dto.paymentMethod,
|
||||
deviceId: device.id,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
// Check if device is stale
|
||||
const lastSeenAgo = now.getTime() - new Date(device.lastSeenAt).getTime();
|
||||
const warning = lastSeenAgo > DEVICE_OFFLINE_THRESHOLD_MS
|
||||
? { warning: 'Device has not been seen recently' }
|
||||
: {};
|
||||
|
||||
return {
|
||||
id: command.id,
|
||||
status: command.status,
|
||||
...warning,
|
||||
};
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async findAll(
|
||||
venueId: string,
|
||||
options: { status?: string; limit: number; offset: number },
|
||||
) {
|
||||
const where: any = { venueId };
|
||||
if (options.status) {
|
||||
where.status = options.status;
|
||||
}
|
||||
|
||||
const [commands, total] = await Promise.all([
|
||||
this.prisma.remoteCommand.findMany({
|
||||
where,
|
||||
select: {
|
||||
id: true,
|
||||
targetTabId: true,
|
||||
type: true,
|
||||
status: true,
|
||||
paymentMethod: true,
|
||||
requestedBy: true,
|
||||
expectedVersion: true,
|
||||
createdAt: true,
|
||||
acknowledgedAt: true,
|
||||
result: true,
|
||||
deviceId: true,
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: options.limit,
|
||||
skip: options.offset,
|
||||
}),
|
||||
this.prisma.remoteCommand.count({ where }),
|
||||
]);
|
||||
|
||||
return {
|
||||
commands: commands.map((c) => ({
|
||||
id: c.id,
|
||||
tabId: c.targetTabId,
|
||||
type: c.type,
|
||||
status: c.status,
|
||||
paymentMethod: c.paymentMethod,
|
||||
requestedBy: c.requestedBy,
|
||||
expectedVersion: c.expectedVersion,
|
||||
createdAt: c.createdAt,
|
||||
processedAt: c.acknowledgedAt,
|
||||
result: c.result,
|
||||
deviceId: c.deviceId,
|
||||
})),
|
||||
total,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { IsString, IsIn, IsInt, Min, IsUUID } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class CreateCommandDto {
|
||||
@ApiProperty({ example: 'local-tab-uuid' })
|
||||
@IsString()
|
||||
tabId: string;
|
||||
|
||||
@ApiProperty({ example: 'close_tab', default: 'close_tab' })
|
||||
@IsString()
|
||||
type: string = 'close_tab';
|
||||
|
||||
@ApiProperty({ example: 5 })
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
expectedVersion: number;
|
||||
|
||||
@ApiProperty({ example: 'cash', enum: ['cash', 'payconiq', 'payment_pending'] })
|
||||
@IsString()
|
||||
@IsIn(['cash', 'payconiq', 'payment_pending'])
|
||||
paymentMethod: string;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { Roles, ROLES_KEY } from './roles.decorator';
|
||||
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
|
||||
@@ -0,0 +1,54 @@
|
||||
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
|
||||
@Catch()
|
||||
export class HttpExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: unknown, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse<Response>();
|
||||
|
||||
let status = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
let code = 'internal_error';
|
||||
let message = 'An unexpected error occurred';
|
||||
|
||||
if (exception instanceof HttpException) {
|
||||
status = exception.getStatus();
|
||||
const exResponse = exception.getResponse();
|
||||
|
||||
if (typeof exResponse === 'string') {
|
||||
message = exResponse;
|
||||
code = this.statusToCode(status);
|
||||
} else if (typeof exResponse === 'object') {
|
||||
const resp = exResponse as Record<string, any>;
|
||||
if (Array.isArray(resp.message)) {
|
||||
message = resp.message.join('; ');
|
||||
code = 'validation_error';
|
||||
} else if (resp.message) {
|
||||
message = resp.message;
|
||||
code = resp.code || this.statusToCode(status);
|
||||
} else {
|
||||
message = resp.code || this.statusToCode(status);
|
||||
code = resp.code || this.statusToCode(status);
|
||||
}
|
||||
}
|
||||
} else if (exception instanceof Error) {
|
||||
message = exception.message;
|
||||
}
|
||||
|
||||
response.status(status).json({
|
||||
error: { code, message },
|
||||
});
|
||||
}
|
||||
|
||||
private statusToCode(status: number): string {
|
||||
switch (status) {
|
||||
case 400: return 'bad_request';
|
||||
case 401: return 'unauthorized';
|
||||
case 403: return 'forbidden';
|
||||
case 404: return 'not_found';
|
||||
case 409: return 'conflict';
|
||||
case 429: return 'too_many_requests';
|
||||
default: return 'internal_error';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Injectable, ExecutionContext } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard {
|
||||
constructor(private reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (!requiredRoles) {
|
||||
return true;
|
||||
}
|
||||
const { user } = context.switchToHttp().getRequest();
|
||||
if (!user) {
|
||||
return false;
|
||||
}
|
||||
return requiredRoles.includes(user.role);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
|
||||
import { Observable, tap } from 'rxjs';
|
||||
|
||||
@Injectable()
|
||||
export class LoggingInterceptor implements NestInterceptor {
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const { method, url } = request;
|
||||
const start = Date.now();
|
||||
|
||||
return next.handle().pipe(
|
||||
tap(() => {
|
||||
const duration = Date.now() - start;
|
||||
const userId = request.user?.id || request.device?.id || 'anonymous';
|
||||
const venueId = request.user?.venueId || request.device?.venueId || '-';
|
||||
console.log(`[${method}] ${url} | user=${userId} venue=${venueId} | ${duration}ms`);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import {
|
||||
Controller,
|
||||
Post,
|
||||
Get,
|
||||
Param,
|
||||
Body,
|
||||
UseGuards,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Req,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { DevicesService } from './devices.service';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { DeviceAuthGuard } from '../auth/guards/device-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { RegisterDeviceDto } from './dto/register-device.dto';
|
||||
import { SyncDto } from './dto/sync.dto';
|
||||
import { AckCommandDto } from './dto/ack-command.dto';
|
||||
|
||||
@ApiTags('Devices')
|
||||
@Controller('devices')
|
||||
export class DevicesController {
|
||||
constructor(
|
||||
private devicesService: DevicesService,
|
||||
private authService: AuthService,
|
||||
) {}
|
||||
|
||||
@Post('register')
|
||||
@ApiOperation({ summary: 'Register a new device' })
|
||||
async register(@Body() dto: RegisterDeviceDto) {
|
||||
return this.authService.registerDevice(dto.venueId, dto.name, dto.registrationCode);
|
||||
}
|
||||
|
||||
@Post(':deviceId/sync')
|
||||
@UseGuards(DeviceAuthGuard)
|
||||
@ApiOperation({ summary: 'Sync device state with server' })
|
||||
async sync(@Param('deviceId') deviceId: string, @Body() dto: SyncDto, @Req() req: any) {
|
||||
const device = req.device;
|
||||
return this.devicesService.sync(device, dto);
|
||||
}
|
||||
|
||||
@Post(':deviceId/commands/:commandId/ack')
|
||||
@UseGuards(DeviceAuthGuard)
|
||||
@ApiOperation({ summary: 'Acknowledge a command' })
|
||||
async ackCommand(
|
||||
@Param('deviceId') deviceId: string,
|
||||
@Param('commandId') commandId: string,
|
||||
@Body() dto: AckCommandDto,
|
||||
@Req() req: any,
|
||||
) {
|
||||
const device = req.device;
|
||||
return this.devicesService.ackCommand(device, commandId, dto);
|
||||
}
|
||||
|
||||
@Get('generation-code')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiOperation({ summary: 'Generate a registration code' })
|
||||
@ApiBearerAuth()
|
||||
async generateCode(@Req() req: any) {
|
||||
const venueId = req.user.venueId;
|
||||
return this.authService.generateRegistrationCode(venueId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { DevicesController } from './devices.controller';
|
||||
import { DevicesService } from './devices.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [DevicesController],
|
||||
providers: [DevicesService],
|
||||
exports: [DevicesService],
|
||||
})
|
||||
export class DevicesModule {}
|
||||
@@ -0,0 +1,222 @@
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { SyncDto } from './dto/sync.dto';
|
||||
import { AckCommandDto } from './dto/ack-command.dto';
|
||||
|
||||
@Injectable()
|
||||
export class DevicesService {
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private auditService: AuditService,
|
||||
) {}
|
||||
|
||||
async sync(device: any, dto: SyncDto) {
|
||||
if (device.revokedAt) {
|
||||
throw new ForbiddenException({ code: 'device_revoked', message: 'Device has been revoked' });
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
|
||||
// Upsert snapshots and ownership
|
||||
for (const tab of dto.openTabs || []) {
|
||||
await this.prisma.openTabSnapshot.upsert({
|
||||
where: {
|
||||
deviceId_tabId: { deviceId: device.id, tabId: tab.id },
|
||||
},
|
||||
create: {
|
||||
deviceId: device.id,
|
||||
tabId: tab.id,
|
||||
customerName: tab.customerName,
|
||||
version: tab.version,
|
||||
totalInCents: tab.totalInCents,
|
||||
itemCount: tab.itemCount,
|
||||
reportedAt: now,
|
||||
},
|
||||
update: {
|
||||
customerName: tab.customerName,
|
||||
version: tab.version,
|
||||
totalInCents: tab.totalInCents,
|
||||
itemCount: tab.itemCount,
|
||||
reportedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
// Check if tab was owned by another device
|
||||
const existingOwnership = await this.prisma.tabOwnership.findUnique({
|
||||
where: { venueId_tabId: { venueId: device.venueId, tabId: tab.id } },
|
||||
});
|
||||
|
||||
if (existingOwnership && existingOwnership.deviceId !== device.id) {
|
||||
if (existingOwnership.lastReportedAt < now) {
|
||||
await this.auditService.log(
|
||||
device.venueId,
|
||||
'device',
|
||||
device.id,
|
||||
'snapshot_conflict',
|
||||
{ tabId: tab.id, previousDevice: existingOwnership.deviceId, newDevice: device.id },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await this.prisma.tabOwnership.upsert({
|
||||
where: { venueId_tabId: { venueId: device.venueId, tabId: tab.id } },
|
||||
create: {
|
||||
tabId: tab.id,
|
||||
venueId: device.venueId,
|
||||
deviceId: device.id,
|
||||
lastReportedAt: now,
|
||||
},
|
||||
update: {
|
||||
deviceId: device.id,
|
||||
lastReportedAt: now,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Update lastSeenAt
|
||||
await this.prisma.device.update({
|
||||
where: { id: device.id },
|
||||
data: { lastSeenAt: now },
|
||||
});
|
||||
|
||||
// Expire old commands
|
||||
await this.prisma.remoteCommand.updateMany({
|
||||
where: {
|
||||
deviceId: device.id,
|
||||
status: 'pending',
|
||||
expiresAt: { lte: now },
|
||||
},
|
||||
data: { status: 'expired' },
|
||||
});
|
||||
|
||||
// Build cursor from timestamp
|
||||
const cursorTimestamp = now.toISOString();
|
||||
const tieBreaker = uuidv4().substring(0, 8);
|
||||
const cursor = Buffer.from(`${cursorTimestamp}:${tieBreaker}`).toString('base64url');
|
||||
|
||||
// Parse cursor from request if provided
|
||||
let cursorCutoff = new Date(0);
|
||||
if (dto.cursor) {
|
||||
try {
|
||||
const decoded = Buffer.from(dto.cursor, 'base64url').toString('utf-8');
|
||||
const parts = decoded.split(':');
|
||||
if (parts.length >= 1) {
|
||||
cursorCutoff = new Date(parts[0]);
|
||||
}
|
||||
} catch {
|
||||
// Invalid cursor, return all pending commands
|
||||
}
|
||||
}
|
||||
|
||||
// Find pending commands for this device
|
||||
const commands = await this.prisma.remoteCommand.findMany({
|
||||
where: {
|
||||
deviceId: device.id,
|
||||
status: 'pending',
|
||||
createdAt: { gt: cursorCutoff },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
type: true,
|
||||
targetTabId: true,
|
||||
expectedVersion: true,
|
||||
paymentMethod: true,
|
||||
requestedBy: true,
|
||||
createdAt: true,
|
||||
status: true,
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
|
||||
return {
|
||||
cursor,
|
||||
commands: commands.map((c) => ({
|
||||
id: c.id,
|
||||
type: c.type,
|
||||
tabId: c.targetTabId,
|
||||
expectedVersion: c.expectedVersion,
|
||||
paymentMethod: c.paymentMethod,
|
||||
requestedBy: c.requestedBy,
|
||||
createdAt: c.createdAt,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
async ackCommand(device: any, commandId: string, dto: AckCommandDto) {
|
||||
const command = await this.prisma.remoteCommand.findUnique({ where: { id: commandId } });
|
||||
|
||||
if (!command) {
|
||||
throw new NotFoundException({ code: 'command_not_found', message: 'Command not found' });
|
||||
}
|
||||
|
||||
if (command.deviceId !== device.id) {
|
||||
throw new ForbiddenException({ code: 'command_not_for_device', message: 'Command does not belong to this device' });
|
||||
}
|
||||
|
||||
if (command.venueId !== device.venueId) {
|
||||
throw new ForbiddenException({ code: 'venue_mismatch', message: 'Command belongs to a different venue' });
|
||||
}
|
||||
|
||||
// Idempotent: if already acknowledged with same status, just return ok
|
||||
if (command.status === dto.status && command.acknowledgedAt) {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
await this.prisma.remoteCommand.update({
|
||||
where: { id: commandId },
|
||||
data: {
|
||||
status: dto.status,
|
||||
result: dto.result || null,
|
||||
acknowledgedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
await this.auditService.log(
|
||||
device.venueId,
|
||||
'device',
|
||||
device.id,
|
||||
'command_acknowledged',
|
||||
{ commandId, status: dto.status, result: dto.result },
|
||||
);
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
async revoke(venueId: string, deviceId: string) {
|
||||
const device = await this.prisma.device.findUnique({ where: { id: deviceId } });
|
||||
|
||||
if (!device) {
|
||||
throw new NotFoundException({ code: 'device_not_found', message: 'Device not found' });
|
||||
}
|
||||
|
||||
if (device.venueId !== venueId) {
|
||||
throw new ForbiddenException({ code: 'venue_mismatch', message: 'Device belongs to a different venue' });
|
||||
}
|
||||
|
||||
if (device.revokedAt) {
|
||||
return { ok: true }; // Idempotent
|
||||
}
|
||||
|
||||
await this.prisma.device.update({
|
||||
where: { id: deviceId },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
|
||||
// Expire pending commands
|
||||
await this.prisma.remoteCommand.updateMany({
|
||||
where: { deviceId, status: 'pending' },
|
||||
data: { status: 'expired' },
|
||||
});
|
||||
|
||||
await this.auditService.log(venueId, 'system', deviceId, 'device_revoked', { deviceName: device.name });
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { IsString, IsIn, IsOptional } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class AckCommandDto {
|
||||
@ApiProperty({ example: 'cmd-uuid' })
|
||||
@IsString()
|
||||
commandId: string;
|
||||
|
||||
@ApiProperty({ example: 'completed', enum: ['completed', 'failed', 'conflict', 'expired'] })
|
||||
@IsString()
|
||||
@IsIn(['completed', 'failed', 'conflict', 'expired'])
|
||||
status: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Tab closed successfully' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
result?: string;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { IsString, IsUUID, IsNotEmpty } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class RegisterDeviceDto {
|
||||
@ApiProperty({ example: 'uuid' })
|
||||
@IsUUID()
|
||||
venueId: string;
|
||||
|
||||
@ApiProperty({ example: 'Bar terminal 1' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiProperty({ example: 'ABC123' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
registrationCode: string;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { IsString, IsOptional, IsArray, IsInt, Min, IsUUID } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
class OpenTabDto {
|
||||
@ApiProperty({ example: 'local-tab-uuid' })
|
||||
@IsString()
|
||||
id: string;
|
||||
|
||||
@ApiProperty({ example: 'Jan' })
|
||||
@IsString()
|
||||
customerName: string;
|
||||
|
||||
@ApiProperty({ example: 5 })
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
version: number;
|
||||
|
||||
@ApiProperty({ example: 2450 })
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
totalInCents: number;
|
||||
|
||||
@ApiProperty({ example: 3 })
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
itemCount: number;
|
||||
}
|
||||
|
||||
export class SyncDto {
|
||||
@ApiProperty({ example: 'uuid' })
|
||||
@IsUUID()
|
||||
deviceId: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'cursor-value' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
cursor?: string;
|
||||
|
||||
@ApiProperty({ type: [OpenTabDto] })
|
||||
@IsArray()
|
||||
openTabs: OpenTabDto[];
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation } from '@nestjs/swagger';
|
||||
import { PrismaService } from './prisma/prisma.service';
|
||||
|
||||
@ApiTags('Health')
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Health check' })
|
||||
async check() {
|
||||
let dbStatus = 'ok';
|
||||
try {
|
||||
await this.prisma.$queryRaw`SELECT 1`;
|
||||
} catch {
|
||||
dbStatus = 'error';
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'ok',
|
||||
database: dbStatus,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Cron, CronExpression } from '@nestjs/schedule';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
@Injectable()
|
||||
export class CommandExpiryJob {
|
||||
private readonly logger = new Logger(CommandExpiryJob.name);
|
||||
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
@Cron(CronExpression.EVERY_HOUR)
|
||||
async handleExpiredCommands() {
|
||||
this.logger.log('Running command expiry job...');
|
||||
|
||||
const now = new Date();
|
||||
|
||||
const expiredCommands = await this.prisma.remoteCommand.findMany({
|
||||
where: {
|
||||
status: 'pending',
|
||||
expiresAt: { lte: now },
|
||||
},
|
||||
});
|
||||
|
||||
if (expiredCommands.length === 0) {
|
||||
this.logger.log('No expired commands found');
|
||||
return;
|
||||
}
|
||||
|
||||
await this.prisma.remoteCommand.updateMany({
|
||||
where: {
|
||||
id: { in: expiredCommands.map((c) => c.id) },
|
||||
},
|
||||
data: { status: 'expired' },
|
||||
});
|
||||
|
||||
// Write audit entries
|
||||
for (const cmd of expiredCommands) {
|
||||
await this.prisma.auditLog.create({
|
||||
data: {
|
||||
id: uuidv4(),
|
||||
venueId: cmd.venueId,
|
||||
actorType: 'system',
|
||||
actorId: 'command-expiry-job',
|
||||
action: 'command_expired',
|
||||
details: JSON.stringify({ commandId: cmd.id, tabId: cmd.targetTabId }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
this.logger.log(`Expired ${expiredCommands.length} commands`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CommandExpiryJob } from './command-expiry.job';
|
||||
|
||||
@Module({
|
||||
providers: [CommandExpiryJob],
|
||||
})
|
||||
export class JobsModule {}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
|
||||
import helmet from 'helmet';
|
||||
import { AppModule } from './app.module';
|
||||
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
|
||||
import { LoggingInterceptor } from './common/interceptors/logging.interceptor';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
|
||||
app.setGlobalPrefix('api/v1');
|
||||
|
||||
app.use(helmet());
|
||||
|
||||
app.enableCors({
|
||||
origin: process.env.CORS_ORIGIN || 'http://localhost:3000',
|
||||
credentials: true,
|
||||
});
|
||||
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
}),
|
||||
);
|
||||
|
||||
app.useGlobalFilters(new HttpExceptionFilter());
|
||||
app.useGlobalInterceptors(new LoggingInterceptor());
|
||||
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('KoolTab Remote Tab Control API')
|
||||
.setDescription('API for managing remote tab control in venues')
|
||||
.setVersion('1.0')
|
||||
.addBearerAuth()
|
||||
.build();
|
||||
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup('api/docs', app, document);
|
||||
|
||||
const port = process.env.PORT || 3001;
|
||||
await app.listen(port);
|
||||
console.log(`API running on http://localhost:${port}`);
|
||||
console.log(`Swagger docs at http://localhost:${port}/api/docs`);
|
||||
}
|
||||
|
||||
bootstrap();
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class PrismaModule {}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
|
||||
async onModuleInit() {
|
||||
await this.$connect();
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
await this.$disconnect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { TabsService } from './tabs.service';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
|
||||
@ApiTags('Tabs')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('venues/:venueId/tabs')
|
||||
export class TabsController {
|
||||
constructor(private tabsService: TabsService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'List all open tabs for a venue' })
|
||||
async findAll(@Param('venueId') venueId: string) {
|
||||
return this.tabsService.findAll(venueId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TabsController } from './tabs.controller';
|
||||
import { TabsService } from './tabs.service';
|
||||
|
||||
@Module({
|
||||
controllers: [TabsController],
|
||||
providers: [TabsService],
|
||||
exports: [TabsService],
|
||||
})
|
||||
export class TabsModule {}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class TabsService {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
async findAll(venueId: string) {
|
||||
const ownerships = await this.prisma.tabOwnership.findMany({
|
||||
where: { venueId },
|
||||
include: {
|
||||
device: {
|
||||
select: { id: true, name: true, lastSeenAt: true, revokedAt: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const tabs = [];
|
||||
for (const ownership of ownerships) {
|
||||
const snapshot = await this.prisma.openTabSnapshot.findFirst({
|
||||
where: { tabId: ownership.tabId, deviceId: ownership.deviceId },
|
||||
orderBy: { reportedAt: 'desc' },
|
||||
});
|
||||
|
||||
if (snapshot) {
|
||||
tabs.push({
|
||||
tabId: snapshot.tabId,
|
||||
customerName: snapshot.customerName,
|
||||
version: snapshot.version,
|
||||
totalInCents: snapshot.totalInCents,
|
||||
itemCount: snapshot.itemCount,
|
||||
deviceId: ownership.device.id,
|
||||
deviceName: ownership.device.name,
|
||||
deviceLastSeenAt: ownership.device.lastSeenAt,
|
||||
deviceRevokedAt: ownership.device.revokedAt,
|
||||
lastReportedAt: snapshot.reportedAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { tabs };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Controller, Get, Param, UseGuards, Req } from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { VenuesService } from './venues.service';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
@ApiTags('Venues')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('venues')
|
||||
export class VenuesController {
|
||||
constructor(
|
||||
private venuesService: VenuesService,
|
||||
private prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'List all venues' })
|
||||
async findAll() {
|
||||
return this.venuesService.findAll();
|
||||
}
|
||||
|
||||
@Get(':venueId')
|
||||
@ApiOperation({ summary: 'Get venue by ID' })
|
||||
async findOne(@Param('venueId') venueId: string) {
|
||||
return this.venuesService.findOne(venueId);
|
||||
}
|
||||
|
||||
@Get(':venueId/devices')
|
||||
@ApiOperation({ summary: 'List devices for a venue' })
|
||||
async findDevices(@Param('venueId') venueId: string) {
|
||||
const devices = await this.prisma.device.findMany({
|
||||
where: { venueId },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
lastSeenAt: true,
|
||||
revokedAt: true,
|
||||
createdAt: true,
|
||||
tokenExpiresAt: true,
|
||||
tokenPrefix: true,
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
return { devices };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { VenuesController } from './venues.controller';
|
||||
import { VenuesService } from './venues.service';
|
||||
|
||||
@Module({
|
||||
controllers: [VenuesController],
|
||||
providers: [VenuesService],
|
||||
exports: [VenuesService],
|
||||
})
|
||||
export class VenuesModule {}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class VenuesService {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
async findAll() {
|
||||
return this.prisma.venue.findMany({ select: { id: true, name: true, createdAt: true } });
|
||||
}
|
||||
|
||||
async findOne(venueId: string) {
|
||||
const venue = await this.prisma.venue.findUnique({ where: { id: venueId } });
|
||||
if (!venue) {
|
||||
throw new NotFoundException({ code: 'venue_not_found', message: 'Venue not found' });
|
||||
}
|
||||
return venue;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user