Compare commits
7 Commits
9c45bf11e4
...
7cb5ff487d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7cb5ff487d
|
||
|
|
0cef694f2b
|
||
|
|
5c4badb837
|
||
|
|
b53c51b825
|
||
|
|
76de69fc64
|
||
|
|
ec8eb8d43a
|
||
|
|
514bd354bf
|
@@ -4,11 +4,12 @@ import { CryptoModule } from "../crypto/crypto.module";
|
|||||||
import { DatabaseModule } from "../database/database.module";
|
import { DatabaseModule } from "../database/database.module";
|
||||||
import { ApiKeysController } from "./api-keys.controller";
|
import { ApiKeysController } from "./api-keys.controller";
|
||||||
import { ApiKeysService } from "./api-keys.service";
|
import { ApiKeysService } from "./api-keys.service";
|
||||||
|
import { ApiKeysRepository } from "./repositories/api-keys.repository";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DatabaseModule, AuthModule, CryptoModule],
|
imports: [DatabaseModule, AuthModule, CryptoModule],
|
||||||
controllers: [ApiKeysController],
|
controllers: [ApiKeysController],
|
||||||
providers: [ApiKeysService],
|
providers: [ApiKeysService, ApiKeysRepository],
|
||||||
exports: [ApiKeysService],
|
exports: [ApiKeysService],
|
||||||
})
|
})
|
||||||
export class ApiKeysModule {}
|
export class ApiKeysModule {}
|
||||||
|
|||||||
@@ -1,58 +1,43 @@
|
|||||||
import { createHash } from "node:crypto";
|
|
||||||
import { Test, TestingModule } from "@nestjs/testing";
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
import { DatabaseService } from "../database/database.service";
|
import { HashingService } from "../crypto/services/hashing.service";
|
||||||
import { apiKeys } from "../database/schemas";
|
|
||||||
import { ApiKeysService } from "./api-keys.service";
|
import { ApiKeysService } from "./api-keys.service";
|
||||||
|
import { ApiKeysRepository } from "./repositories/api-keys.repository";
|
||||||
|
|
||||||
describe("ApiKeysService", () => {
|
describe("ApiKeysService", () => {
|
||||||
let service: ApiKeysService;
|
let service: ApiKeysService;
|
||||||
|
let repository: ApiKeysRepository;
|
||||||
|
|
||||||
const mockDb = {
|
const mockApiKeysRepository = {
|
||||||
insert: jest.fn(),
|
create: jest.fn(),
|
||||||
values: jest.fn(),
|
findAll: jest.fn(),
|
||||||
select: jest.fn(),
|
revoke: jest.fn(),
|
||||||
from: jest.fn(),
|
findActiveByKeyHash: jest.fn(),
|
||||||
where: jest.fn(),
|
updateLastUsed: jest.fn(),
|
||||||
limit: jest.fn(),
|
};
|
||||||
update: jest.fn(),
|
|
||||||
set: jest.fn(),
|
const mockHashingService = {
|
||||||
returning: jest.fn(),
|
hashSha256: jest.fn().mockResolvedValue("hashed-key"),
|
||||||
};
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
|
|
||||||
mockDb.insert.mockReturnThis();
|
|
||||||
mockDb.values.mockResolvedValue(undefined);
|
|
||||||
mockDb.select.mockReturnThis();
|
|
||||||
mockDb.from.mockReturnThis();
|
|
||||||
mockDb.where.mockReturnThis();
|
|
||||||
mockDb.limit.mockReturnThis();
|
|
||||||
mockDb.update.mockReturnThis();
|
|
||||||
mockDb.set.mockReturnThis();
|
|
||||||
mockDb.returning.mockResolvedValue([]);
|
|
||||||
|
|
||||||
// Default for findAll which is awaited on where()
|
|
||||||
mockDb.where.mockImplementation(() => {
|
|
||||||
const chain = {
|
|
||||||
returning: jest.fn().mockResolvedValue([]),
|
|
||||||
};
|
|
||||||
return Object.assign(Promise.resolve([]), chain);
|
|
||||||
});
|
|
||||||
|
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
ApiKeysService,
|
ApiKeysService,
|
||||||
{
|
{
|
||||||
provide: DatabaseService,
|
provide: ApiKeysRepository,
|
||||||
useValue: {
|
useValue: mockApiKeysRepository,
|
||||||
db: mockDb,
|
},
|
||||||
},
|
{
|
||||||
|
provide: HashingService,
|
||||||
|
useValue: mockHashingService,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
service = module.get<ApiKeysService>(ApiKeysService);
|
service = module.get<ApiKeysService>(ApiKeysService);
|
||||||
|
repository = module.get<ApiKeysRepository>(ApiKeysRepository);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should be defined", () => {
|
it("should be defined", () => {
|
||||||
@@ -67,8 +52,7 @@ describe("ApiKeysService", () => {
|
|||||||
|
|
||||||
const result = await service.create(userId, name, expiresAt);
|
const result = await service.create(userId, name, expiresAt);
|
||||||
|
|
||||||
expect(mockDb.insert).toHaveBeenCalledWith(apiKeys);
|
expect(repository.create).toHaveBeenCalledWith(
|
||||||
expect(mockDb.values).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
userId,
|
userId,
|
||||||
name,
|
name,
|
||||||
@@ -87,12 +71,11 @@ describe("ApiKeysService", () => {
|
|||||||
it("should find all API keys for a user", async () => {
|
it("should find all API keys for a user", async () => {
|
||||||
const userId = "user-id";
|
const userId = "user-id";
|
||||||
const expectedKeys = [{ id: "1", name: "Key 1" }];
|
const expectedKeys = [{ id: "1", name: "Key 1" }];
|
||||||
(mockDb.where as jest.Mock).mockResolvedValue(expectedKeys);
|
mockApiKeysRepository.findAll.mockResolvedValue(expectedKeys);
|
||||||
|
|
||||||
const result = await service.findAll(userId);
|
const result = await service.findAll(userId);
|
||||||
|
|
||||||
expect(mockDb.select).toHaveBeenCalled();
|
expect(repository.findAll).toHaveBeenCalledWith(userId);
|
||||||
expect(mockDb.from).toHaveBeenCalledWith(apiKeys);
|
|
||||||
expect(result).toEqual(expectedKeys);
|
expect(result).toEqual(expectedKeys);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -102,17 +85,11 @@ describe("ApiKeysService", () => {
|
|||||||
const userId = "user-id";
|
const userId = "user-id";
|
||||||
const keyId = "key-id";
|
const keyId = "key-id";
|
||||||
const expectedResult = [{ id: keyId, isActive: false }];
|
const expectedResult = [{ id: keyId, isActive: false }];
|
||||||
|
mockApiKeysRepository.revoke.mockResolvedValue(expectedResult);
|
||||||
mockDb.where.mockReturnValue({
|
|
||||||
returning: jest.fn().mockResolvedValue(expectedResult),
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await service.revoke(userId, keyId);
|
const result = await service.revoke(userId, keyId);
|
||||||
|
|
||||||
expect(mockDb.update).toHaveBeenCalledWith(apiKeys);
|
expect(repository.revoke).toHaveBeenCalledWith(userId, keyId);
|
||||||
expect(mockDb.set).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({ isActive: false }),
|
|
||||||
);
|
|
||||||
expect(result).toEqual(expectedResult);
|
expect(result).toEqual(expectedResult);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -120,42 +97,19 @@ describe("ApiKeysService", () => {
|
|||||||
describe("validateKey", () => {
|
describe("validateKey", () => {
|
||||||
it("should validate a valid API key", async () => {
|
it("should validate a valid API key", async () => {
|
||||||
const key = "mg_live_testkey";
|
const key = "mg_live_testkey";
|
||||||
const keyHash = createHash("sha256").update(key).digest("hex");
|
const apiKey = { id: "1", isActive: true, expiresAt: null };
|
||||||
const apiKey = { id: "1", keyHash, isActive: true, expiresAt: null };
|
mockApiKeysRepository.findActiveByKeyHash.mockResolvedValue(apiKey);
|
||||||
|
|
||||||
(mockDb.limit as jest.Mock).mockResolvedValue([apiKey]);
|
|
||||||
(mockDb.where as jest.Mock).mockResolvedValue([apiKey]); // For the update later if needed, but here it's for select
|
|
||||||
|
|
||||||
// We need to be careful with chaining mockDb.where is used in both select and update
|
|
||||||
const mockSelect = {
|
|
||||||
from: jest.fn().mockReturnThis(),
|
|
||||||
where: jest.fn().mockReturnThis(),
|
|
||||||
limit: jest.fn().mockResolvedValue([apiKey]),
|
|
||||||
};
|
|
||||||
const mockUpdate = {
|
|
||||||
set: jest.fn().mockReturnThis(),
|
|
||||||
where: jest.fn().mockResolvedValue(undefined),
|
|
||||||
};
|
|
||||||
|
|
||||||
(mockDb.select as jest.Mock).mockReturnValue(mockSelect);
|
|
||||||
(mockDb.update as jest.Mock).mockReturnValue(mockUpdate);
|
|
||||||
|
|
||||||
const result = await service.validateKey(key);
|
const result = await service.validateKey(key);
|
||||||
|
|
||||||
expect(result).toEqual(apiKey);
|
expect(result).toEqual(apiKey);
|
||||||
expect(mockDb.select).toHaveBeenCalled();
|
expect(repository.findActiveByKeyHash).toHaveBeenCalled();
|
||||||
expect(mockDb.update).toHaveBeenCalledWith(apiKeys);
|
expect(repository.updateLastUsed).toHaveBeenCalledWith(apiKey.id);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return null for invalid API key", async () => {
|
it("should return null for invalid API key", async () => {
|
||||||
(mockDb.select as jest.Mock).mockReturnValue({
|
mockApiKeysRepository.findActiveByKeyHash.mockResolvedValue(null);
|
||||||
from: jest.fn().mockReturnThis(),
|
|
||||||
where: jest.fn().mockReturnThis(),
|
|
||||||
limit: jest.fn().mockResolvedValue([]),
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await service.validateKey("invalid-key");
|
const result = await service.validateKey("invalid-key");
|
||||||
|
|
||||||
expect(result).toBeNull();
|
expect(result).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -164,12 +118,7 @@ describe("ApiKeysService", () => {
|
|||||||
const expiredDate = new Date();
|
const expiredDate = new Date();
|
||||||
expiredDate.setFullYear(expiredDate.getFullYear() - 1);
|
expiredDate.setFullYear(expiredDate.getFullYear() - 1);
|
||||||
const apiKey = { id: "1", isActive: true, expiresAt: expiredDate };
|
const apiKey = { id: "1", isActive: true, expiresAt: expiredDate };
|
||||||
|
mockApiKeysRepository.findActiveByKeyHash.mockResolvedValue(apiKey);
|
||||||
(mockDb.select as jest.Mock).mockReturnValue({
|
|
||||||
from: jest.fn().mockReturnThis(),
|
|
||||||
where: jest.fn().mockReturnThis(),
|
|
||||||
limit: jest.fn().mockResolvedValue([apiKey]),
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await service.validateKey(key);
|
const result = await service.validateKey(key);
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
import { createHash, randomBytes } from "node:crypto";
|
import { randomBytes } from "node:crypto";
|
||||||
import { Injectable, Logger } from "@nestjs/common";
|
import { Injectable, Logger } from "@nestjs/common";
|
||||||
import { and, eq } from "drizzle-orm";
|
import { HashingService } from "../crypto/services/hashing.service";
|
||||||
import { DatabaseService } from "../database/database.service";
|
import { ApiKeysRepository } from "./repositories/api-keys.repository";
|
||||||
import { apiKeys } from "../database/schemas";
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ApiKeysService {
|
export class ApiKeysService {
|
||||||
private readonly logger = new Logger(ApiKeysService.name);
|
private readonly logger = new Logger(ApiKeysService.name);
|
||||||
|
|
||||||
constructor(private readonly databaseService: DatabaseService) {}
|
constructor(
|
||||||
|
private readonly apiKeysRepository: ApiKeysRepository,
|
||||||
|
private readonly hashingService: HashingService,
|
||||||
|
) {}
|
||||||
|
|
||||||
async create(userId: string, name: string, expiresAt?: Date) {
|
async create(userId: string, name: string, expiresAt?: Date) {
|
||||||
this.logger.log(`Creating API key for user ${userId}: ${name}`);
|
this.logger.log(`Creating API key for user ${userId}: ${name}`);
|
||||||
@@ -16,9 +18,9 @@ export class ApiKeysService {
|
|||||||
const randomPart = randomBytes(24).toString("hex");
|
const randomPart = randomBytes(24).toString("hex");
|
||||||
const key = `${prefix}${randomPart}`;
|
const key = `${prefix}${randomPart}`;
|
||||||
|
|
||||||
const keyHash = createHash("sha256").update(key).digest("hex");
|
const keyHash = await this.hashingService.hashSha256(key);
|
||||||
|
|
||||||
await this.databaseService.db.insert(apiKeys).values({
|
await this.apiKeysRepository.create({
|
||||||
userId,
|
userId,
|
||||||
name,
|
name,
|
||||||
prefix: prefix.substring(0, 8),
|
prefix: prefix.substring(0, 8),
|
||||||
@@ -34,37 +36,18 @@ export class ApiKeysService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async findAll(userId: string) {
|
async findAll(userId: string) {
|
||||||
return await this.databaseService.db
|
return await this.apiKeysRepository.findAll(userId);
|
||||||
.select({
|
|
||||||
id: apiKeys.id,
|
|
||||||
name: apiKeys.name,
|
|
||||||
prefix: apiKeys.prefix,
|
|
||||||
isActive: apiKeys.isActive,
|
|
||||||
lastUsedAt: apiKeys.lastUsedAt,
|
|
||||||
expiresAt: apiKeys.expiresAt,
|
|
||||||
createdAt: apiKeys.createdAt,
|
|
||||||
})
|
|
||||||
.from(apiKeys)
|
|
||||||
.where(eq(apiKeys.userId, userId));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async revoke(userId: string, keyId: string) {
|
async revoke(userId: string, keyId: string) {
|
||||||
this.logger.log(`Revoking API key ${keyId} for user ${userId}`);
|
this.logger.log(`Revoking API key ${keyId} for user ${userId}`);
|
||||||
return await this.databaseService.db
|
return await this.apiKeysRepository.revoke(userId, keyId);
|
||||||
.update(apiKeys)
|
|
||||||
.set({ isActive: false, updatedAt: new Date() })
|
|
||||||
.where(and(eq(apiKeys.id, keyId), eq(apiKeys.userId, userId)))
|
|
||||||
.returning();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async validateKey(key: string) {
|
async validateKey(key: string) {
|
||||||
const keyHash = createHash("sha256").update(key).digest("hex");
|
const keyHash = await this.hashingService.hashSha256(key);
|
||||||
|
|
||||||
const [apiKey] = await this.databaseService.db
|
const apiKey = await this.apiKeysRepository.findActiveByKeyHash(keyHash);
|
||||||
.select()
|
|
||||||
.from(apiKeys)
|
|
||||||
.where(and(eq(apiKeys.keyHash, keyHash), eq(apiKeys.isActive, true)))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (!apiKey) return null;
|
if (!apiKey) return null;
|
||||||
|
|
||||||
@@ -73,10 +56,7 @@ export class ApiKeysService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update last used at
|
// Update last used at
|
||||||
await this.databaseService.db
|
await this.apiKeysRepository.updateLastUsed(apiKey.id);
|
||||||
.update(apiKeys)
|
|
||||||
.set({ lastUsedAt: new Date() })
|
|
||||||
.where(eq(apiKeys.id, apiKey.id));
|
|
||||||
|
|
||||||
return apiKey;
|
return apiKey;
|
||||||
}
|
}
|
||||||
|
|||||||
58
backend/src/api-keys/repositories/api-keys.repository.ts
Normal file
58
backend/src/api-keys/repositories/api-keys.repository.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { and, eq } from "drizzle-orm";
|
||||||
|
import { DatabaseService } from "../../database/database.service";
|
||||||
|
import { apiKeys } from "../../database/schemas";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ApiKeysRepository {
|
||||||
|
constructor(private readonly databaseService: DatabaseService) {}
|
||||||
|
|
||||||
|
async create(data: {
|
||||||
|
userId: string;
|
||||||
|
name: string;
|
||||||
|
prefix: string;
|
||||||
|
keyHash: string;
|
||||||
|
expiresAt?: Date;
|
||||||
|
}) {
|
||||||
|
return await this.databaseService.db.insert(apiKeys).values(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAll(userId: string) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.select({
|
||||||
|
id: apiKeys.id,
|
||||||
|
name: apiKeys.name,
|
||||||
|
prefix: apiKeys.prefix,
|
||||||
|
isActive: apiKeys.isActive,
|
||||||
|
lastUsedAt: apiKeys.lastUsedAt,
|
||||||
|
expiresAt: apiKeys.expiresAt,
|
||||||
|
createdAt: apiKeys.createdAt,
|
||||||
|
})
|
||||||
|
.from(apiKeys)
|
||||||
|
.where(eq(apiKeys.userId, userId));
|
||||||
|
}
|
||||||
|
|
||||||
|
async revoke(userId: string, keyId: string) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.update(apiKeys)
|
||||||
|
.set({ isActive: false, updatedAt: new Date() })
|
||||||
|
.where(and(eq(apiKeys.id, keyId), eq(apiKeys.userId, userId)))
|
||||||
|
.returning();
|
||||||
|
}
|
||||||
|
|
||||||
|
async findActiveByKeyHash(keyHash: string) {
|
||||||
|
const result = await this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(apiKeys)
|
||||||
|
.where(and(eq(apiKeys.keyHash, keyHash), eq(apiKeys.isActive, true)))
|
||||||
|
.limit(1);
|
||||||
|
return result[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateLastUsed(id: string) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.update(apiKeys)
|
||||||
|
.set({ lastUsedAt: new Date() })
|
||||||
|
.where(eq(apiKeys.id, id));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,11 +6,12 @@ import { UsersModule } from "../users/users.module";
|
|||||||
import { AuthController } from "./auth.controller";
|
import { AuthController } from "./auth.controller";
|
||||||
import { AuthService } from "./auth.service";
|
import { AuthService } from "./auth.service";
|
||||||
import { RbacService } from "./rbac.service";
|
import { RbacService } from "./rbac.service";
|
||||||
|
import { RbacRepository } from "./repositories/rbac.repository";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [UsersModule, CryptoModule, SessionsModule, DatabaseModule],
|
imports: [UsersModule, CryptoModule, SessionsModule, DatabaseModule],
|
||||||
controllers: [AuthController],
|
controllers: [AuthController],
|
||||||
providers: [AuthService, RbacService],
|
providers: [AuthService, RbacService, RbacRepository],
|
||||||
exports: [AuthService, RbacService],
|
exports: [AuthService, RbacService],
|
||||||
})
|
})
|
||||||
export class AuthModule {}
|
export class AuthModule {}
|
||||||
|
|||||||
@@ -17,14 +17,14 @@ import { BadRequestException, UnauthorizedException } from "@nestjs/common";
|
|||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import { authenticator } from "otplib";
|
import { authenticator } from "otplib";
|
||||||
import * as qrcode from "qrcode";
|
import * as qrcode from "qrcode";
|
||||||
import { CryptoService } from "../crypto/crypto.service";
|
import { HashingService } from "../crypto/services/hashing.service";
|
||||||
|
import { JwtService } from "../crypto/services/jwt.service";
|
||||||
import { SessionsService } from "../sessions/sessions.service";
|
import { SessionsService } from "../sessions/sessions.service";
|
||||||
import { UsersService } from "../users/users.service";
|
import { UsersService } from "../users/users.service";
|
||||||
import { AuthService } from "./auth.service";
|
import { AuthService } from "./auth.service";
|
||||||
|
|
||||||
jest.mock("otplib");
|
jest.mock("otplib");
|
||||||
jest.mock("qrcode");
|
jest.mock("qrcode");
|
||||||
jest.mock("../crypto/crypto.service");
|
|
||||||
jest.mock("../users/users.service");
|
jest.mock("../users/users.service");
|
||||||
jest.mock("../sessions/sessions.service");
|
jest.mock("../sessions/sessions.service");
|
||||||
|
|
||||||
@@ -41,10 +41,13 @@ describe("AuthService", () => {
|
|||||||
findOneWithPrivateData: jest.fn(),
|
findOneWithPrivateData: jest.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const mockCryptoService = {
|
const mockHashingService = {
|
||||||
hashPassword: jest.fn(),
|
hashPassword: jest.fn(),
|
||||||
hashEmail: jest.fn(),
|
hashEmail: jest.fn(),
|
||||||
verifyPassword: jest.fn(),
|
verifyPassword: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockJwtService = {
|
||||||
generateJwt: jest.fn(),
|
generateJwt: jest.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -62,7 +65,8 @@ describe("AuthService", () => {
|
|||||||
providers: [
|
providers: [
|
||||||
AuthService,
|
AuthService,
|
||||||
{ provide: UsersService, useValue: mockUsersService },
|
{ provide: UsersService, useValue: mockUsersService },
|
||||||
{ provide: CryptoService, useValue: mockCryptoService },
|
{ provide: HashingService, useValue: mockHashingService },
|
||||||
|
{ provide: JwtService, useValue: mockJwtService },
|
||||||
{ provide: SessionsService, useValue: mockSessionsService },
|
{ provide: SessionsService, useValue: mockSessionsService },
|
||||||
{ provide: ConfigService, useValue: mockConfigService },
|
{ provide: ConfigService, useValue: mockConfigService },
|
||||||
],
|
],
|
||||||
@@ -142,8 +146,8 @@ describe("AuthService", () => {
|
|||||||
email: "test@example.com",
|
email: "test@example.com",
|
||||||
password: "password",
|
password: "password",
|
||||||
};
|
};
|
||||||
mockCryptoService.hashPassword.mockResolvedValue("hashed-password");
|
mockHashingService.hashPassword.mockResolvedValue("hashed-password");
|
||||||
mockCryptoService.hashEmail.mockResolvedValue("hashed-email");
|
mockHashingService.hashEmail.mockResolvedValue("hashed-email");
|
||||||
mockUsersService.create.mockResolvedValue({ uuid: "new-user-id" });
|
mockUsersService.create.mockResolvedValue({ uuid: "new-user-id" });
|
||||||
|
|
||||||
const result = await service.register(dto);
|
const result = await service.register(dto);
|
||||||
@@ -164,10 +168,10 @@ describe("AuthService", () => {
|
|||||||
passwordHash: "hash",
|
passwordHash: "hash",
|
||||||
isTwoFactorEnabled: false,
|
isTwoFactorEnabled: false,
|
||||||
};
|
};
|
||||||
mockCryptoService.hashEmail.mockResolvedValue("hashed-email");
|
mockHashingService.hashEmail.mockResolvedValue("hashed-email");
|
||||||
mockUsersService.findByEmailHash.mockResolvedValue(user);
|
mockUsersService.findByEmailHash.mockResolvedValue(user);
|
||||||
mockCryptoService.verifyPassword.mockResolvedValue(true);
|
mockHashingService.verifyPassword.mockResolvedValue(true);
|
||||||
mockCryptoService.generateJwt.mockResolvedValue("access-token");
|
mockJwtService.generateJwt.mockResolvedValue("access-token");
|
||||||
mockSessionsService.createSession.mockResolvedValue({
|
mockSessionsService.createSession.mockResolvedValue({
|
||||||
refreshToken: "refresh-token",
|
refreshToken: "refresh-token",
|
||||||
});
|
});
|
||||||
@@ -189,9 +193,9 @@ describe("AuthService", () => {
|
|||||||
passwordHash: "hash",
|
passwordHash: "hash",
|
||||||
isTwoFactorEnabled: true,
|
isTwoFactorEnabled: true,
|
||||||
};
|
};
|
||||||
mockCryptoService.hashEmail.mockResolvedValue("hashed-email");
|
mockHashingService.hashEmail.mockResolvedValue("hashed-email");
|
||||||
mockUsersService.findByEmailHash.mockResolvedValue(user);
|
mockUsersService.findByEmailHash.mockResolvedValue(user);
|
||||||
mockCryptoService.verifyPassword.mockResolvedValue(true);
|
mockHashingService.verifyPassword.mockResolvedValue(true);
|
||||||
|
|
||||||
const result = await service.login(dto);
|
const result = await service.login(dto);
|
||||||
|
|
||||||
@@ -218,7 +222,7 @@ describe("AuthService", () => {
|
|||||||
mockUsersService.findOneWithPrivateData.mockResolvedValue(user);
|
mockUsersService.findOneWithPrivateData.mockResolvedValue(user);
|
||||||
mockUsersService.getTwoFactorSecret.mockResolvedValue("secret");
|
mockUsersService.getTwoFactorSecret.mockResolvedValue("secret");
|
||||||
(authenticator.verify as jest.Mock).mockReturnValue(true);
|
(authenticator.verify as jest.Mock).mockReturnValue(true);
|
||||||
mockCryptoService.generateJwt.mockResolvedValue("access-token");
|
mockJwtService.generateJwt.mockResolvedValue("access-token");
|
||||||
mockSessionsService.createSession.mockResolvedValue({
|
mockSessionsService.createSession.mockResolvedValue({
|
||||||
refreshToken: "refresh-token",
|
refreshToken: "refresh-token",
|
||||||
});
|
});
|
||||||
@@ -240,7 +244,7 @@ describe("AuthService", () => {
|
|||||||
const user = { uuid: "user-id", username: "test" };
|
const user = { uuid: "user-id", username: "test" };
|
||||||
mockSessionsService.refreshSession.mockResolvedValue(session);
|
mockSessionsService.refreshSession.mockResolvedValue(session);
|
||||||
mockUsersService.findOne.mockResolvedValue(user);
|
mockUsersService.findOne.mockResolvedValue(user);
|
||||||
mockCryptoService.generateJwt.mockResolvedValue("new-access");
|
mockJwtService.generateJwt.mockResolvedValue("new-access");
|
||||||
|
|
||||||
const result = await service.refresh(refreshToken);
|
const result = await service.refresh(refreshToken);
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ import {
|
|||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import { authenticator } from "otplib";
|
import { authenticator } from "otplib";
|
||||||
import { toDataURL } from "qrcode";
|
import { toDataURL } from "qrcode";
|
||||||
import { CryptoService } from "../crypto/crypto.service";
|
import { HashingService } from "../crypto/services/hashing.service";
|
||||||
|
import { JwtService } from "../crypto/services/jwt.service";
|
||||||
import { SessionsService } from "../sessions/sessions.service";
|
import { SessionsService } from "../sessions/sessions.service";
|
||||||
import { UsersService } from "../users/users.service";
|
import { UsersService } from "../users/users.service";
|
||||||
import { LoginDto } from "./dto/login.dto";
|
import { LoginDto } from "./dto/login.dto";
|
||||||
@@ -19,7 +20,8 @@ export class AuthService {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly usersService: UsersService,
|
private readonly usersService: UsersService,
|
||||||
private readonly cryptoService: CryptoService,
|
private readonly hashingService: HashingService,
|
||||||
|
private readonly jwtService: JwtService,
|
||||||
private readonly sessionsService: SessionsService,
|
private readonly sessionsService: SessionsService,
|
||||||
private readonly configService: ConfigService,
|
private readonly configService: ConfigService,
|
||||||
) {}
|
) {}
|
||||||
@@ -81,8 +83,8 @@ export class AuthService {
|
|||||||
this.logger.log(`Registering new user: ${dto.username}`);
|
this.logger.log(`Registering new user: ${dto.username}`);
|
||||||
const { username, email, password } = dto;
|
const { username, email, password } = dto;
|
||||||
|
|
||||||
const passwordHash = await this.cryptoService.hashPassword(password);
|
const passwordHash = await this.hashingService.hashPassword(password);
|
||||||
const emailHash = await this.cryptoService.hashEmail(email);
|
const emailHash = await this.hashingService.hashEmail(email);
|
||||||
|
|
||||||
const user = await this.usersService.create({
|
const user = await this.usersService.create({
|
||||||
username,
|
username,
|
||||||
@@ -101,14 +103,14 @@ export class AuthService {
|
|||||||
this.logger.log(`Login attempt for email: ${dto.email}`);
|
this.logger.log(`Login attempt for email: ${dto.email}`);
|
||||||
const { email, password } = dto;
|
const { email, password } = dto;
|
||||||
|
|
||||||
const emailHash = await this.cryptoService.hashEmail(email);
|
const emailHash = await this.hashingService.hashEmail(email);
|
||||||
const user = await this.usersService.findByEmailHash(emailHash);
|
const user = await this.usersService.findByEmailHash(emailHash);
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw new UnauthorizedException("Invalid credentials");
|
throw new UnauthorizedException("Invalid credentials");
|
||||||
}
|
}
|
||||||
|
|
||||||
const isPasswordValid = await this.cryptoService.verifyPassword(
|
const isPasswordValid = await this.hashingService.verifyPassword(
|
||||||
password,
|
password,
|
||||||
user.passwordHash,
|
user.passwordHash,
|
||||||
);
|
);
|
||||||
@@ -125,7 +127,7 @@ export class AuthService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const accessToken = await this.cryptoService.generateJwt({
|
const accessToken = await this.jwtService.generateJwt({
|
||||||
sub: user.uuid,
|
sub: user.uuid,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
});
|
});
|
||||||
@@ -163,7 +165,7 @@ export class AuthService {
|
|||||||
throw new UnauthorizedException("Invalid 2FA token");
|
throw new UnauthorizedException("Invalid 2FA token");
|
||||||
}
|
}
|
||||||
|
|
||||||
const accessToken = await this.cryptoService.generateJwt({
|
const accessToken = await this.jwtService.generateJwt({
|
||||||
sub: user.uuid,
|
sub: user.uuid,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
});
|
});
|
||||||
@@ -189,7 +191,7 @@ export class AuthService {
|
|||||||
throw new UnauthorizedException("User not found");
|
throw new UnauthorizedException("User not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const accessToken = await this.cryptoService.generateJwt({
|
const accessToken = await this.jwtService.generateJwt({
|
||||||
sub: user.uuid,
|
sub: user.uuid,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,13 +6,13 @@ import {
|
|||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import { getIronSession } from "iron-session";
|
import { getIronSession } from "iron-session";
|
||||||
import { CryptoService } from "../../crypto/crypto.service";
|
import { JwtService } from "../../crypto/services/jwt.service";
|
||||||
import { getSessionOptions, SessionData } from "../session.config";
|
import { getSessionOptions, SessionData } from "../session.config";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthGuard implements CanActivate {
|
export class AuthGuard implements CanActivate {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly cryptoService: CryptoService,
|
private readonly jwtService: JwtService,
|
||||||
private readonly configService: ConfigService,
|
private readonly configService: ConfigService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@@ -33,7 +33,7 @@ export class AuthGuard implements CanActivate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const payload = await this.cryptoService.verifyJwt(token);
|
const payload = await this.jwtService.verifyJwt(token);
|
||||||
request.user = payload;
|
request.user = payload;
|
||||||
} catch {
|
} catch {
|
||||||
throw new UnauthorizedException();
|
throw new UnauthorizedException();
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
import { Test, TestingModule } from "@nestjs/testing";
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
import { DatabaseService } from "../database/database.service";
|
|
||||||
import { RbacService } from "./rbac.service";
|
import { RbacService } from "./rbac.service";
|
||||||
|
import { RbacRepository } from "./repositories/rbac.repository";
|
||||||
|
|
||||||
describe("RbacService", () => {
|
describe("RbacService", () => {
|
||||||
let service: RbacService;
|
let service: RbacService;
|
||||||
|
let repository: RbacRepository;
|
||||||
|
|
||||||
const mockDb = {
|
const mockRbacRepository = {
|
||||||
select: jest.fn().mockReturnThis(),
|
findRolesByUserId: jest.fn(),
|
||||||
from: jest.fn().mockReturnThis(),
|
findPermissionsByUserId: jest.fn(),
|
||||||
innerJoin: jest.fn().mockReturnThis(),
|
|
||||||
where: jest.fn(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
@@ -18,15 +17,14 @@ describe("RbacService", () => {
|
|||||||
providers: [
|
providers: [
|
||||||
RbacService,
|
RbacService,
|
||||||
{
|
{
|
||||||
provide: DatabaseService,
|
provide: RbacRepository,
|
||||||
useValue: {
|
useValue: mockRbacRepository,
|
||||||
db: mockDb,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
service = module.get<RbacService>(RbacService);
|
service = module.get<RbacService>(RbacService);
|
||||||
|
repository = module.get<RbacRepository>(RbacRepository);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should be defined", () => {
|
it("should be defined", () => {
|
||||||
@@ -36,34 +34,26 @@ describe("RbacService", () => {
|
|||||||
describe("getUserRoles", () => {
|
describe("getUserRoles", () => {
|
||||||
it("should return user roles", async () => {
|
it("should return user roles", async () => {
|
||||||
const userId = "user-id";
|
const userId = "user-id";
|
||||||
const mockRoles = [{ slug: "admin" }, { slug: "user" }];
|
const mockRoles = ["admin", "user"];
|
||||||
mockDb.where.mockResolvedValue(mockRoles);
|
mockRbacRepository.findRolesByUserId.mockResolvedValue(mockRoles);
|
||||||
|
|
||||||
const result = await service.getUserRoles(userId);
|
const result = await service.getUserRoles(userId);
|
||||||
|
|
||||||
expect(result).toEqual(["admin", "user"]);
|
expect(result).toEqual(mockRoles);
|
||||||
expect(mockDb.select).toHaveBeenCalled();
|
expect(repository.findRolesByUserId).toHaveBeenCalledWith(userId);
|
||||||
expect(mockDb.from).toHaveBeenCalled();
|
|
||||||
expect(mockDb.innerJoin).toHaveBeenCalled();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("getUserPermissions", () => {
|
describe("getUserPermissions", () => {
|
||||||
it("should return unique user permissions", async () => {
|
it("should return user permissions", async () => {
|
||||||
const userId = "user-id";
|
const userId = "user-id";
|
||||||
const mockPermissions = [
|
const mockPermissions = ["read", "write"];
|
||||||
{ slug: "read" },
|
mockRbacRepository.findPermissionsByUserId.mockResolvedValue(mockPermissions);
|
||||||
{ slug: "write" },
|
|
||||||
{ slug: "read" }, // Duplicate
|
|
||||||
];
|
|
||||||
mockDb.where.mockResolvedValue(mockPermissions);
|
|
||||||
|
|
||||||
const result = await service.getUserPermissions(userId);
|
const result = await service.getUserPermissions(userId);
|
||||||
|
|
||||||
expect(result).toEqual(["read", "write"]);
|
expect(result).toEqual(mockPermissions);
|
||||||
expect(mockDb.select).toHaveBeenCalled();
|
expect(repository.findPermissionsByUserId).toHaveBeenCalledWith(userId);
|
||||||
expect(mockDb.from).toHaveBeenCalled();
|
|
||||||
expect(mockDb.innerJoin).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,42 +1,15 @@
|
|||||||
import { Injectable } from "@nestjs/common";
|
import { Injectable } from "@nestjs/common";
|
||||||
import { eq } from "drizzle-orm";
|
import { RbacRepository } from "./repositories/rbac.repository";
|
||||||
import { DatabaseService } from "../database/database.service";
|
|
||||||
import {
|
|
||||||
permissions,
|
|
||||||
roles,
|
|
||||||
rolesToPermissions,
|
|
||||||
usersToRoles,
|
|
||||||
} from "../database/schemas";
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class RbacService {
|
export class RbacService {
|
||||||
constructor(private readonly databaseService: DatabaseService) {}
|
constructor(private readonly rbacRepository: RbacRepository) {}
|
||||||
|
|
||||||
async getUserRoles(userId: string) {
|
async getUserRoles(userId: string) {
|
||||||
const result = await this.databaseService.db
|
return this.rbacRepository.findRolesByUserId(userId);
|
||||||
.select({
|
|
||||||
slug: roles.slug,
|
|
||||||
})
|
|
||||||
.from(usersToRoles)
|
|
||||||
.innerJoin(roles, eq(usersToRoles.roleId, roles.id))
|
|
||||||
.where(eq(usersToRoles.userId, userId));
|
|
||||||
|
|
||||||
return result.map((r) => r.slug);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async getUserPermissions(userId: string) {
|
async getUserPermissions(userId: string) {
|
||||||
const result = await this.databaseService.db
|
return this.rbacRepository.findPermissionsByUserId(userId);
|
||||||
.select({
|
|
||||||
slug: permissions.slug,
|
|
||||||
})
|
|
||||||
.from(usersToRoles)
|
|
||||||
.innerJoin(
|
|
||||||
rolesToPermissions,
|
|
||||||
eq(usersToRoles.roleId, rolesToPermissions.roleId),
|
|
||||||
)
|
|
||||||
.innerJoin(permissions, eq(rolesToPermissions.permissionId, permissions.id))
|
|
||||||
.where(eq(usersToRoles.userId, userId));
|
|
||||||
|
|
||||||
return Array.from(new Set(result.map((p) => p.slug)));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
42
backend/src/auth/repositories/rbac.repository.ts
Normal file
42
backend/src/auth/repositories/rbac.repository.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import { DatabaseService } from "../../database/database.service";
|
||||||
|
import {
|
||||||
|
permissions,
|
||||||
|
roles,
|
||||||
|
rolesToPermissions,
|
||||||
|
usersToRoles,
|
||||||
|
} from "../../database/schemas";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class RbacRepository {
|
||||||
|
constructor(private readonly databaseService: DatabaseService) {}
|
||||||
|
|
||||||
|
async findRolesByUserId(userId: string) {
|
||||||
|
const result = await this.databaseService.db
|
||||||
|
.select({
|
||||||
|
slug: roles.slug,
|
||||||
|
})
|
||||||
|
.from(usersToRoles)
|
||||||
|
.innerJoin(roles, eq(usersToRoles.roleId, roles.id))
|
||||||
|
.where(eq(usersToRoles.userId, userId));
|
||||||
|
|
||||||
|
return result.map((r) => r.slug);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findPermissionsByUserId(userId: string) {
|
||||||
|
const result = await this.databaseService.db
|
||||||
|
.select({
|
||||||
|
slug: permissions.slug,
|
||||||
|
})
|
||||||
|
.from(usersToRoles)
|
||||||
|
.innerJoin(
|
||||||
|
rolesToPermissions,
|
||||||
|
eq(usersToRoles.roleId, rolesToPermissions.roleId),
|
||||||
|
)
|
||||||
|
.innerJoin(permissions, eq(rolesToPermissions.permissionId, permissions.id))
|
||||||
|
.where(eq(usersToRoles.userId, userId));
|
||||||
|
|
||||||
|
return Array.from(new Set(result.map((p) => p.slug)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,11 +2,12 @@ import { Module } from "@nestjs/common";
|
|||||||
import { DatabaseModule } from "../database/database.module";
|
import { DatabaseModule } from "../database/database.module";
|
||||||
import { CategoriesController } from "./categories.controller";
|
import { CategoriesController } from "./categories.controller";
|
||||||
import { CategoriesService } from "./categories.service";
|
import { CategoriesService } from "./categories.service";
|
||||||
|
import { CategoriesRepository } from "./repositories/categories.repository";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DatabaseModule],
|
imports: [DatabaseModule],
|
||||||
controllers: [CategoriesController],
|
controllers: [CategoriesController],
|
||||||
providers: [CategoriesService],
|
providers: [CategoriesService, CategoriesRepository],
|
||||||
exports: [CategoriesService],
|
exports: [CategoriesService],
|
||||||
})
|
})
|
||||||
export class CategoriesModule {}
|
export class CategoriesModule {}
|
||||||
|
|||||||
@@ -1,25 +1,24 @@
|
|||||||
import { Test, TestingModule } from "@nestjs/testing";
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
import { DatabaseService } from "../database/database.service";
|
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
||||||
import { categories } from "../database/schemas";
|
|
||||||
import { CategoriesService } from "./categories.service";
|
import { CategoriesService } from "./categories.service";
|
||||||
|
import { CategoriesRepository } from "./repositories/categories.repository";
|
||||||
import { CreateCategoryDto } from "./dto/create-category.dto";
|
import { CreateCategoryDto } from "./dto/create-category.dto";
|
||||||
import { UpdateCategoryDto } from "./dto/update-category.dto";
|
import { UpdateCategoryDto } from "./dto/update-category.dto";
|
||||||
|
|
||||||
describe("CategoriesService", () => {
|
describe("CategoriesService", () => {
|
||||||
let service: CategoriesService;
|
let service: CategoriesService;
|
||||||
|
let repository: CategoriesRepository;
|
||||||
|
|
||||||
const mockDb = {
|
const mockCategoriesRepository = {
|
||||||
select: jest.fn().mockReturnThis(),
|
findAll: jest.fn(),
|
||||||
from: jest.fn().mockReturnThis(),
|
findOne: jest.fn(),
|
||||||
where: jest.fn().mockReturnThis(),
|
create: jest.fn(),
|
||||||
limit: jest.fn().mockResolvedValue([]),
|
update: jest.fn(),
|
||||||
orderBy: jest.fn().mockResolvedValue([]),
|
remove: jest.fn(),
|
||||||
insert: jest.fn().mockReturnThis(),
|
};
|
||||||
values: jest.fn().mockReturnThis(),
|
|
||||||
update: jest.fn().mockReturnThis(),
|
const mockCacheManager = {
|
||||||
set: jest.fn().mockReturnThis(),
|
del: jest.fn(),
|
||||||
delete: jest.fn().mockReturnThis(),
|
|
||||||
returning: jest.fn().mockResolvedValue([]),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
@@ -28,15 +27,15 @@ describe("CategoriesService", () => {
|
|||||||
providers: [
|
providers: [
|
||||||
CategoriesService,
|
CategoriesService,
|
||||||
{
|
{
|
||||||
provide: DatabaseService,
|
provide: CategoriesRepository,
|
||||||
useValue: {
|
useValue: mockCategoriesRepository,
|
||||||
db: mockDb,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
|
{ provide: CACHE_MANAGER, useValue: mockCacheManager },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
service = module.get<CategoriesService>(CategoriesService);
|
service = module.get<CategoriesService>(CategoriesService);
|
||||||
|
repository = module.get<CategoriesRepository>(CategoriesRepository);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should be defined", () => {
|
it("should be defined", () => {
|
||||||
@@ -46,28 +45,28 @@ describe("CategoriesService", () => {
|
|||||||
describe("findAll", () => {
|
describe("findAll", () => {
|
||||||
it("should return all categories ordered by name", async () => {
|
it("should return all categories ordered by name", async () => {
|
||||||
const mockCategories = [{ name: "A" }, { name: "B" }];
|
const mockCategories = [{ name: "A" }, { name: "B" }];
|
||||||
mockDb.orderBy.mockResolvedValue(mockCategories);
|
mockCategoriesRepository.findAll.mockResolvedValue(mockCategories);
|
||||||
|
|
||||||
const result = await service.findAll();
|
const result = await service.findAll();
|
||||||
|
|
||||||
expect(result).toEqual(mockCategories);
|
expect(result).toEqual(mockCategories);
|
||||||
expect(mockDb.select).toHaveBeenCalled();
|
expect(repository.findAll).toHaveBeenCalled();
|
||||||
expect(mockDb.from).toHaveBeenCalledWith(categories);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("findOne", () => {
|
describe("findOne", () => {
|
||||||
it("should return a category by id", async () => {
|
it("should return a category by id", async () => {
|
||||||
const mockCategory = { id: "1", name: "Cat" };
|
const mockCategory = { id: "1", name: "Cat" };
|
||||||
mockDb.limit.mockResolvedValue([mockCategory]);
|
mockCategoriesRepository.findOne.mockResolvedValue(mockCategory);
|
||||||
|
|
||||||
const result = await service.findOne("1");
|
const result = await service.findOne("1");
|
||||||
|
|
||||||
expect(result).toEqual(mockCategory);
|
expect(result).toEqual(mockCategory);
|
||||||
|
expect(repository.findOne).toHaveBeenCalledWith("1");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return null if category not found", async () => {
|
it("should return null if category not found", async () => {
|
||||||
mockDb.limit.mockResolvedValue([]);
|
mockCategoriesRepository.findOne.mockResolvedValue(null);
|
||||||
const result = await service.findOne("999");
|
const result = await service.findOne("999");
|
||||||
expect(result).toBeNull();
|
expect(result).toBeNull();
|
||||||
});
|
});
|
||||||
@@ -76,12 +75,11 @@ describe("CategoriesService", () => {
|
|||||||
describe("create", () => {
|
describe("create", () => {
|
||||||
it("should create a category and generate slug", async () => {
|
it("should create a category and generate slug", async () => {
|
||||||
const dto: CreateCategoryDto = { name: "Test Category" };
|
const dto: CreateCategoryDto = { name: "Test Category" };
|
||||||
mockDb.returning.mockResolvedValue([{ ...dto, slug: "test-category" }]);
|
mockCategoriesRepository.create.mockResolvedValue([{ ...dto, slug: "test-category" }]);
|
||||||
|
|
||||||
const result = await service.create(dto);
|
const result = await service.create(dto);
|
||||||
|
|
||||||
expect(mockDb.insert).toHaveBeenCalledWith(categories);
|
expect(repository.create).toHaveBeenCalledWith({
|
||||||
expect(mockDb.values).toHaveBeenCalledWith({
|
|
||||||
name: "Test Category",
|
name: "Test Category",
|
||||||
slug: "test-category",
|
slug: "test-category",
|
||||||
});
|
});
|
||||||
@@ -93,12 +91,12 @@ describe("CategoriesService", () => {
|
|||||||
it("should update a category and regenerate slug", async () => {
|
it("should update a category and regenerate slug", async () => {
|
||||||
const id = "1";
|
const id = "1";
|
||||||
const dto: UpdateCategoryDto = { name: "New Name" };
|
const dto: UpdateCategoryDto = { name: "New Name" };
|
||||||
mockDb.returning.mockResolvedValue([{ id, ...dto, slug: "new-name" }]);
|
mockCategoriesRepository.update.mockResolvedValue([{ id, ...dto, slug: "new-name" }]);
|
||||||
|
|
||||||
const result = await service.update(id, dto);
|
const result = await service.update(id, dto);
|
||||||
|
|
||||||
expect(mockDb.update).toHaveBeenCalledWith(categories);
|
expect(repository.update).toHaveBeenCalledWith(
|
||||||
expect(mockDb.set).toHaveBeenCalledWith(
|
id,
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
name: "New Name",
|
name: "New Name",
|
||||||
slug: "new-name",
|
slug: "new-name",
|
||||||
@@ -111,11 +109,11 @@ describe("CategoriesService", () => {
|
|||||||
describe("remove", () => {
|
describe("remove", () => {
|
||||||
it("should remove a category", async () => {
|
it("should remove a category", async () => {
|
||||||
const id = "1";
|
const id = "1";
|
||||||
mockDb.returning.mockResolvedValue([{ id }]);
|
mockCategoriesRepository.remove.mockResolvedValue([{ id }]);
|
||||||
|
|
||||||
const result = await service.remove(id);
|
const result = await service.remove(id);
|
||||||
|
|
||||||
expect(mockDb.delete).toHaveBeenCalledWith(categories);
|
expect(repository.remove).toHaveBeenCalledWith(id);
|
||||||
expect(result).toEqual([{ id }]);
|
expect(result).toEqual([{ id }]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import { Injectable, Logger, Inject } from "@nestjs/common";
|
import { Injectable, Logger, Inject } from "@nestjs/common";
|
||||||
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
||||||
import { Cache } from "cache-manager";
|
import { Cache } from "cache-manager";
|
||||||
import { eq } from "drizzle-orm";
|
import { CategoriesRepository } from "./repositories/categories.repository";
|
||||||
import { DatabaseService } from "../database/database.service";
|
|
||||||
import { categories } from "../database/schemas";
|
|
||||||
import { CreateCategoryDto } from "./dto/create-category.dto";
|
import { CreateCategoryDto } from "./dto/create-category.dto";
|
||||||
import { UpdateCategoryDto } from "./dto/update-category.dto";
|
import { UpdateCategoryDto } from "./dto/update-category.dto";
|
||||||
|
|
||||||
@@ -12,7 +10,7 @@ export class CategoriesService {
|
|||||||
private readonly logger = new Logger(CategoriesService.name);
|
private readonly logger = new Logger(CategoriesService.name);
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly databaseService: DatabaseService,
|
private readonly categoriesRepository: CategoriesRepository,
|
||||||
@Inject(CACHE_MANAGER) private cacheManager: Cache,
|
@Inject(CACHE_MANAGER) private cacheManager: Cache,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@@ -22,20 +20,11 @@ export class CategoriesService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async findAll() {
|
async findAll() {
|
||||||
return await this.databaseService.db
|
return await this.categoriesRepository.findAll();
|
||||||
.select()
|
|
||||||
.from(categories)
|
|
||||||
.orderBy(categories.name);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async findOne(id: string) {
|
async findOne(id: string) {
|
||||||
const result = await this.databaseService.db
|
return await this.categoriesRepository.findOne(id);
|
||||||
.select()
|
|
||||||
.from(categories)
|
|
||||||
.where(eq(categories.id, id))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
return result[0] || null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async create(data: CreateCategoryDto) {
|
async create(data: CreateCategoryDto) {
|
||||||
@@ -44,10 +33,7 @@ export class CategoriesService {
|
|||||||
.toLowerCase()
|
.toLowerCase()
|
||||||
.replace(/ /g, "-")
|
.replace(/ /g, "-")
|
||||||
.replace(/[^\w-]/g, "");
|
.replace(/[^\w-]/g, "");
|
||||||
const result = await this.databaseService.db
|
const result = await this.categoriesRepository.create({ ...data, slug });
|
||||||
.insert(categories)
|
|
||||||
.values({ ...data, slug })
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
await this.clearCategoriesCache();
|
await this.clearCategoriesCache();
|
||||||
return result;
|
return result;
|
||||||
@@ -65,11 +51,7 @@ export class CategoriesService {
|
|||||||
.replace(/[^\w-]/g, "")
|
.replace(/[^\w-]/g, "")
|
||||||
: undefined,
|
: undefined,
|
||||||
};
|
};
|
||||||
const result = await this.databaseService.db
|
const result = await this.categoriesRepository.update(id, updateData);
|
||||||
.update(categories)
|
|
||||||
.set(updateData)
|
|
||||||
.where(eq(categories.id, id))
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
await this.clearCategoriesCache();
|
await this.clearCategoriesCache();
|
||||||
return result;
|
return result;
|
||||||
@@ -77,10 +59,7 @@ export class CategoriesService {
|
|||||||
|
|
||||||
async remove(id: string) {
|
async remove(id: string) {
|
||||||
this.logger.log(`Removing category: ${id}`);
|
this.logger.log(`Removing category: ${id}`);
|
||||||
const result = await this.databaseService.db
|
const result = await this.categoriesRepository.remove(id);
|
||||||
.delete(categories)
|
|
||||||
.where(eq(categories.id, id))
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
await this.clearCategoriesCache();
|
await this.clearCategoriesCache();
|
||||||
return result;
|
return result;
|
||||||
|
|||||||
50
backend/src/categories/repositories/categories.repository.ts
Normal file
50
backend/src/categories/repositories/categories.repository.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import { DatabaseService } from "../../database/database.service";
|
||||||
|
import { categories } from "../../database/schemas";
|
||||||
|
import type { CreateCategoryDto } from "../dto/create-category.dto";
|
||||||
|
import type { UpdateCategoryDto } from "../dto/update-category.dto";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CategoriesRepository {
|
||||||
|
constructor(private readonly databaseService: DatabaseService) {}
|
||||||
|
|
||||||
|
async findAll() {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(categories)
|
||||||
|
.orderBy(categories.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(id: string) {
|
||||||
|
const result = await this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(categories)
|
||||||
|
.where(eq(categories.id, id))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
return result[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(data: CreateCategoryDto & { slug: string }) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.insert(categories)
|
||||||
|
.values(data)
|
||||||
|
.returning();
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(id: string, data: UpdateCategoryDto & { slug?: string; updatedAt: Date }) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.update(categories)
|
||||||
|
.set(data)
|
||||||
|
.where(eq(categories.id, id))
|
||||||
|
.returning();
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(id: string) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.delete(categories)
|
||||||
|
.where(eq(categories.id, id))
|
||||||
|
.returning();
|
||||||
|
}
|
||||||
|
}
|
||||||
4
backend/src/common/interfaces/mail.interface.ts
Normal file
4
backend/src/common/interfaces/mail.interface.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export interface IMailService {
|
||||||
|
sendEmailValidation(email: string, token: string): Promise<void>;
|
||||||
|
sendPasswordReset(email: string, token: string): Promise<void>;
|
||||||
|
}
|
||||||
25
backend/src/common/interfaces/media.interface.ts
Normal file
25
backend/src/common/interfaces/media.interface.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
export interface MediaProcessingResult {
|
||||||
|
buffer: Buffer;
|
||||||
|
mimeType: string;
|
||||||
|
extension: string;
|
||||||
|
width?: number;
|
||||||
|
height?: number;
|
||||||
|
size: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ScanResult {
|
||||||
|
isInfected: boolean;
|
||||||
|
virusName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IMediaService {
|
||||||
|
scanFile(buffer: Buffer, filename: string): Promise<ScanResult>;
|
||||||
|
processImage(
|
||||||
|
buffer: Buffer,
|
||||||
|
format?: "webp" | "avif",
|
||||||
|
): Promise<MediaProcessingResult>;
|
||||||
|
processVideo(
|
||||||
|
buffer: Buffer,
|
||||||
|
format?: "webm" | "av1",
|
||||||
|
): Promise<MediaProcessingResult>;
|
||||||
|
}
|
||||||
39
backend/src/common/interfaces/storage.interface.ts
Normal file
39
backend/src/common/interfaces/storage.interface.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import type { Readable } from "node:stream";
|
||||||
|
|
||||||
|
export interface IStorageService {
|
||||||
|
uploadFile(
|
||||||
|
fileName: string,
|
||||||
|
file: Buffer,
|
||||||
|
mimeType: string,
|
||||||
|
metaData?: Record<string, string>,
|
||||||
|
bucketName?: string,
|
||||||
|
): Promise<string>;
|
||||||
|
|
||||||
|
getFile(
|
||||||
|
fileName: string,
|
||||||
|
bucketName?: string,
|
||||||
|
): Promise<Readable>;
|
||||||
|
|
||||||
|
getFileUrl(
|
||||||
|
fileName: string,
|
||||||
|
expiry?: number,
|
||||||
|
bucketName?: string,
|
||||||
|
): Promise<string>;
|
||||||
|
|
||||||
|
getUploadUrl(
|
||||||
|
fileName: string,
|
||||||
|
expiry?: number,
|
||||||
|
bucketName?: string,
|
||||||
|
): Promise<string>;
|
||||||
|
|
||||||
|
deleteFile(fileName: string, bucketName?: string): Promise<void>;
|
||||||
|
|
||||||
|
getFileInfo(fileName: string, bucketName?: string): Promise<any>;
|
||||||
|
|
||||||
|
moveFile(
|
||||||
|
sourceFileName: string,
|
||||||
|
destinationFileName: string,
|
||||||
|
sourceBucketName?: string,
|
||||||
|
destinationBucketName?: string,
|
||||||
|
): Promise<string>;
|
||||||
|
}
|
||||||
@@ -1,38 +1,31 @@
|
|||||||
import { Logger } from "@nestjs/common";
|
import { Logger } from "@nestjs/common";
|
||||||
import { Test, TestingModule } from "@nestjs/testing";
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
import { DatabaseService } from "../../database/database.service";
|
import { ContentsRepository } from "../../contents/repositories/contents.repository";
|
||||||
|
import { ReportsRepository } from "../../reports/repositories/reports.repository";
|
||||||
|
import { SessionsRepository } from "../../sessions/repositories/sessions.repository";
|
||||||
|
import { UsersRepository } from "../../users/repositories/users.repository";
|
||||||
import { PurgeService } from "./purge.service";
|
import { PurgeService } from "./purge.service";
|
||||||
|
|
||||||
describe("PurgeService", () => {
|
describe("PurgeService", () => {
|
||||||
let service: PurgeService;
|
let service: PurgeService;
|
||||||
|
|
||||||
const mockDb = {
|
const mockSessionsRepository = { purgeExpired: jest.fn().mockResolvedValue([]) };
|
||||||
delete: jest.fn(),
|
const mockReportsRepository = { purgeObsolete: jest.fn().mockResolvedValue([]) };
|
||||||
where: jest.fn(),
|
const mockUsersRepository = { purgeDeleted: jest.fn().mockResolvedValue([]) };
|
||||||
returning: jest.fn(),
|
const mockContentsRepository = { purgeSoftDeleted: jest.fn().mockResolvedValue([]) };
|
||||||
};
|
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
jest.spyOn(Logger.prototype, "error").mockImplementation(() => {});
|
jest.spyOn(Logger.prototype, "error").mockImplementation(() => {});
|
||||||
jest.spyOn(Logger.prototype, "log").mockImplementation(() => {});
|
jest.spyOn(Logger.prototype, "log").mockImplementation(() => {});
|
||||||
|
|
||||||
const chain = {
|
|
||||||
delete: jest.fn().mockReturnThis(),
|
|
||||||
where: jest.fn().mockReturnThis(),
|
|
||||||
returning: jest.fn().mockResolvedValue([]),
|
|
||||||
};
|
|
||||||
|
|
||||||
const mockImplementation = () => Object.assign(Promise.resolve([]), chain);
|
|
||||||
for (const mock of Object.values(chain)) {
|
|
||||||
mock.mockImplementation(mockImplementation);
|
|
||||||
}
|
|
||||||
Object.assign(mockDb, chain);
|
|
||||||
|
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
PurgeService,
|
PurgeService,
|
||||||
{ provide: DatabaseService, useValue: { db: mockDb } },
|
{ provide: SessionsRepository, useValue: mockSessionsRepository },
|
||||||
|
{ provide: ReportsRepository, useValue: mockReportsRepository },
|
||||||
|
{ provide: UsersRepository, useValue: mockUsersRepository },
|
||||||
|
{ provide: ContentsRepository, useValue: mockContentsRepository },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
@@ -44,23 +37,22 @@ describe("PurgeService", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("purgeExpiredData", () => {
|
describe("purgeExpiredData", () => {
|
||||||
it("should purge data", async () => {
|
it("should purge data using repositories", async () => {
|
||||||
mockDb.returning
|
mockSessionsRepository.purgeExpired.mockResolvedValue([{ id: "s1" }]);
|
||||||
.mockResolvedValueOnce([{ id: "s1" }]) // sessions
|
mockReportsRepository.purgeObsolete.mockResolvedValue([{ id: "r1" }]);
|
||||||
.mockResolvedValueOnce([{ id: "r1" }]) // reports
|
mockUsersRepository.purgeDeleted.mockResolvedValue([{ id: "u1" }]);
|
||||||
.mockResolvedValueOnce([{ id: "u1" }]) // users
|
mockContentsRepository.purgeSoftDeleted.mockResolvedValue([{ id: "c1" }]);
|
||||||
.mockResolvedValueOnce([{ id: "c1" }]); // contents
|
|
||||||
|
|
||||||
await service.purgeExpiredData();
|
await service.purgeExpiredData();
|
||||||
|
|
||||||
expect(mockDb.delete).toHaveBeenCalledTimes(4);
|
expect(mockSessionsRepository.purgeExpired).toHaveBeenCalled();
|
||||||
expect(mockDb.returning).toHaveBeenCalledTimes(4);
|
expect(mockReportsRepository.purgeObsolete).toHaveBeenCalled();
|
||||||
|
expect(mockUsersRepository.purgeDeleted).toHaveBeenCalled();
|
||||||
|
expect(mockContentsRepository.purgeSoftDeleted).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should handle errors", async () => {
|
it("should handle errors", async () => {
|
||||||
mockDb.delete.mockImplementation(() => {
|
mockSessionsRepository.purgeExpired.mockRejectedValue(new Error("Db error"));
|
||||||
throw new Error("Db error");
|
|
||||||
});
|
|
||||||
await expect(service.purgeExpiredData()).resolves.not.toThrow();
|
await expect(service.purgeExpiredData()).resolves.not.toThrow();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,14 +1,20 @@
|
|||||||
import { Injectable, Logger } from "@nestjs/common";
|
import { Injectable, Logger } from "@nestjs/common";
|
||||||
import { Cron, CronExpression } from "@nestjs/schedule";
|
import { Cron, CronExpression } from "@nestjs/schedule";
|
||||||
import { and, eq, isNotNull, lte } from "drizzle-orm";
|
import { ContentsRepository } from "../../contents/repositories/contents.repository";
|
||||||
import { DatabaseService } from "../../database/database.service";
|
import { ReportsRepository } from "../../reports/repositories/reports.repository";
|
||||||
import { contents, reports, sessions, users } from "../../database/schemas";
|
import { SessionsRepository } from "../../sessions/repositories/sessions.repository";
|
||||||
|
import { UsersRepository } from "../../users/repositories/users.repository";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class PurgeService {
|
export class PurgeService {
|
||||||
private readonly logger = new Logger(PurgeService.name);
|
private readonly logger = new Logger(PurgeService.name);
|
||||||
|
|
||||||
constructor(private readonly databaseService: DatabaseService) {}
|
constructor(
|
||||||
|
private readonly sessionsRepository: SessionsRepository,
|
||||||
|
private readonly reportsRepository: ReportsRepository,
|
||||||
|
private readonly usersRepository: UsersRepository,
|
||||||
|
private readonly contentsRepository: ContentsRepository,
|
||||||
|
) {}
|
||||||
|
|
||||||
// Toutes les nuits à minuit
|
// Toutes les nuits à minuit
|
||||||
@Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
|
@Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
|
||||||
@@ -19,40 +25,26 @@ export class PurgeService {
|
|||||||
const now = new Date();
|
const now = new Date();
|
||||||
|
|
||||||
// 1. Purge des sessions expirées
|
// 1. Purge des sessions expirées
|
||||||
const deletedSessions = await this.databaseService.db
|
const deletedSessions = await this.sessionsRepository.purgeExpired(now);
|
||||||
.delete(sessions)
|
|
||||||
.where(lte(sessions.expiresAt, now))
|
|
||||||
.returning();
|
|
||||||
this.logger.log(`Purged ${deletedSessions.length} expired sessions.`);
|
this.logger.log(`Purged ${deletedSessions.length} expired sessions.`);
|
||||||
|
|
||||||
// 2. Purge des signalements obsolètes
|
// 2. Purge des signalements obsolètes
|
||||||
const deletedReports = await this.databaseService.db
|
const deletedReports = await this.reportsRepository.purgeObsolete(now);
|
||||||
.delete(reports)
|
|
||||||
.where(lte(reports.expiresAt, now))
|
|
||||||
.returning();
|
|
||||||
this.logger.log(`Purged ${deletedReports.length} obsolete reports.`);
|
this.logger.log(`Purged ${deletedReports.length} obsolete reports.`);
|
||||||
|
|
||||||
// 3. Purge des utilisateurs supprimés (Soft Delete > 30 jours)
|
// 3. Purge des utilisateurs supprimés (Soft Delete > 30 jours)
|
||||||
const thirtyDaysAgo = new Date();
|
const thirtyDaysAgo = new Date();
|
||||||
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
||||||
|
|
||||||
const deletedUsers = await this.databaseService.db
|
const deletedUsers = await this.usersRepository.purgeDeleted(thirtyDaysAgo);
|
||||||
.delete(users)
|
|
||||||
.where(
|
|
||||||
and(eq(users.status, "deleted"), lte(users.deletedAt, thirtyDaysAgo)),
|
|
||||||
)
|
|
||||||
.returning();
|
|
||||||
this.logger.log(
|
this.logger.log(
|
||||||
`Purged ${deletedUsers.length} users marked for deletion more than 30 days ago.`,
|
`Purged ${deletedUsers.length} users marked for deletion more than 30 days ago.`,
|
||||||
);
|
);
|
||||||
|
|
||||||
// 4. Purge des contenus supprimés (Soft Delete > 30 jours)
|
// 4. Purge des contenus supprimés (Soft Delete > 30 jours)
|
||||||
const deletedContents = await this.databaseService.db
|
const deletedContents = await this.contentsRepository.purgeSoftDeleted(
|
||||||
.delete(contents)
|
thirtyDaysAgo,
|
||||||
.where(
|
);
|
||||||
and(isNotNull(contents.deletedAt), lte(contents.deletedAt, thirtyDaysAgo)),
|
|
||||||
)
|
|
||||||
.returning();
|
|
||||||
this.logger.log(
|
this.logger.log(
|
||||||
`Purged ${deletedContents.length} contents marked for deletion more than 30 days ago.`,
|
`Purged ${deletedContents.length} contents marked for deletion more than 30 days ago.`,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -136,25 +136,7 @@ export class ContentsController {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (isBot) {
|
if (isBot) {
|
||||||
const imageUrl = this.contentsService.getFileUrl(content.storageKey);
|
const html = this.contentsService.generateBotHtml(content);
|
||||||
const html = `<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
|
||||||
<title>${content.title}</title>
|
|
||||||
<meta property="og:title" content="${content.title}" />
|
|
||||||
<meta property="og:type" content="website" />
|
|
||||||
<meta property="og:image" content="${imageUrl}" />
|
|
||||||
<meta property="og:description" content="Découvrez ce meme sur Memegoat" />
|
|
||||||
<meta name="twitter:card" content="summary_large_image" />
|
|
||||||
<meta name="twitter:title" content="${content.title}" />
|
|
||||||
<meta name="twitter:image" content="${imageUrl}" />
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h1>${content.title}</h1>
|
|
||||||
<img src="${imageUrl}" alt="${content.title}" />
|
|
||||||
</body>
|
|
||||||
</html>`;
|
|
||||||
return res.send(html);
|
return res.send(html);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,10 +6,11 @@ import { MediaModule } from "../media/media.module";
|
|||||||
import { S3Module } from "../s3/s3.module";
|
import { S3Module } from "../s3/s3.module";
|
||||||
import { ContentsController } from "./contents.controller";
|
import { ContentsController } from "./contents.controller";
|
||||||
import { ContentsService } from "./contents.service";
|
import { ContentsService } from "./contents.service";
|
||||||
|
import { ContentsRepository } from "./repositories/contents.repository";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DatabaseModule, S3Module, AuthModule, CryptoModule, MediaModule],
|
imports: [DatabaseModule, S3Module, AuthModule, CryptoModule, MediaModule],
|
||||||
controllers: [ContentsController],
|
controllers: [ContentsController],
|
||||||
providers: [ContentsService],
|
providers: [ContentsService, ContentsRepository],
|
||||||
})
|
})
|
||||||
export class ContentsModule {}
|
export class ContentsModule {}
|
||||||
|
|||||||
@@ -4,33 +4,28 @@ jest.mock("uuid", () => ({
|
|||||||
|
|
||||||
import { BadRequestException } from "@nestjs/common";
|
import { BadRequestException } from "@nestjs/common";
|
||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
|
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
||||||
import { Test, TestingModule } from "@nestjs/testing";
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
import { DatabaseService } from "../database/database.service";
|
import { DatabaseService } from "../database/database.service";
|
||||||
import { MediaService } from "../media/media.service";
|
import { MediaService } from "../media/media.service";
|
||||||
import { S3Service } from "../s3/s3.service";
|
import { S3Service } from "../s3/s3.service";
|
||||||
import { ContentsService } from "./contents.service";
|
import { ContentsService } from "./contents.service";
|
||||||
|
import { ContentsRepository } from "./repositories/contents.repository";
|
||||||
|
|
||||||
describe("ContentsService", () => {
|
describe("ContentsService", () => {
|
||||||
let service: ContentsService;
|
let service: ContentsService;
|
||||||
let s3Service: S3Service;
|
let s3Service: S3Service;
|
||||||
let mediaService: MediaService;
|
let mediaService: MediaService;
|
||||||
|
|
||||||
const mockDb = {
|
const mockContentsRepository = {
|
||||||
select: jest.fn().mockReturnThis(),
|
findAll: jest.fn(),
|
||||||
from: jest.fn().mockReturnThis(),
|
count: jest.fn(),
|
||||||
where: jest.fn().mockReturnThis(),
|
create: jest.fn(),
|
||||||
limit: jest.fn().mockReturnThis(),
|
incrementViews: jest.fn(),
|
||||||
offset: jest.fn().mockReturnThis(),
|
incrementUsage: jest.fn(),
|
||||||
orderBy: jest.fn().mockReturnThis(),
|
softDelete: jest.fn(),
|
||||||
innerJoin: jest.fn().mockReturnThis(),
|
findOne: jest.fn(),
|
||||||
insert: jest.fn().mockReturnThis(),
|
findBySlug: jest.fn(),
|
||||||
values: jest.fn().mockReturnThis(),
|
|
||||||
update: jest.fn().mockReturnThis(),
|
|
||||||
set: jest.fn().mockReturnThis(),
|
|
||||||
returning: jest.fn().mockResolvedValue([]),
|
|
||||||
onConflictDoNothing: jest.fn().mockReturnThis(),
|
|
||||||
transaction: jest.fn().mockImplementation((cb) => cb(mockDb)),
|
|
||||||
execute: jest.fn().mockResolvedValue([]),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const mockS3Service = {
|
const mockS3Service = {
|
||||||
@@ -48,46 +43,24 @@ describe("ContentsService", () => {
|
|||||||
get: jest.fn(),
|
get: jest.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const mockCacheManager = {
|
||||||
|
store: {
|
||||||
|
keys: jest.fn().mockResolvedValue([]),
|
||||||
|
},
|
||||||
|
del: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
|
|
||||||
const chain = {
|
|
||||||
select: jest.fn().mockReturnThis(),
|
|
||||||
from: jest.fn().mockReturnThis(),
|
|
||||||
where: jest.fn().mockReturnThis(),
|
|
||||||
orderBy: jest.fn().mockReturnThis(),
|
|
||||||
limit: jest.fn().mockReturnThis(),
|
|
||||||
offset: jest.fn().mockReturnThis(),
|
|
||||||
innerJoin: jest.fn().mockReturnThis(),
|
|
||||||
insert: jest.fn().mockReturnThis(),
|
|
||||||
values: jest.fn().mockReturnThis(),
|
|
||||||
update: jest.fn().mockReturnThis(),
|
|
||||||
set: jest.fn().mockReturnThis(),
|
|
||||||
returning: jest.fn().mockReturnThis(),
|
|
||||||
onConflictDoNothing: jest.fn().mockReturnThis(),
|
|
||||||
};
|
|
||||||
|
|
||||||
const mockImplementation = () => {
|
|
||||||
return Object.assign(Promise.resolve([]), chain);
|
|
||||||
};
|
|
||||||
|
|
||||||
for (const mock of Object.values(chain)) {
|
|
||||||
|
|
||||||
//TODO Fix : TS2774: This condition will always return true since this function is always defined. Did you mean to call it instead?
|
|
||||||
if (mock.mockReturnValue) {
|
|
||||||
mock.mockImplementation(mockImplementation);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Object.assign(mockDb, chain);
|
|
||||||
|
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
ContentsService,
|
ContentsService,
|
||||||
{ provide: DatabaseService, useValue: { db: mockDb } },
|
{ provide: ContentsRepository, useValue: mockContentsRepository },
|
||||||
{ provide: S3Service, useValue: mockS3Service },
|
{ provide: S3Service, useValue: mockS3Service },
|
||||||
{ provide: MediaService, useValue: mockMediaService },
|
{ provide: MediaService, useValue: mockMediaService },
|
||||||
{ provide: ConfigService, useValue: mockConfigService },
|
{ provide: ConfigService, useValue: mockConfigService },
|
||||||
|
{ provide: CACHE_MANAGER, useValue: mockCacheManager },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
@@ -127,7 +100,8 @@ describe("ContentsService", () => {
|
|||||||
mimeType: "image/webp",
|
mimeType: "image/webp",
|
||||||
size: 500,
|
size: 500,
|
||||||
});
|
});
|
||||||
mockDb.returning.mockResolvedValue([{ id: "content-id" }]);
|
mockContentsRepository.findBySlug.mockResolvedValue(null);
|
||||||
|
mockContentsRepository.create.mockResolvedValue({ id: "content-id" });
|
||||||
|
|
||||||
const result = await service.uploadAndProcess("user1", file, {
|
const result = await service.uploadAndProcess("user1", file, {
|
||||||
title: "Meme",
|
title: "Meme",
|
||||||
@@ -155,8 +129,8 @@ describe("ContentsService", () => {
|
|||||||
|
|
||||||
describe("findAll", () => {
|
describe("findAll", () => {
|
||||||
it("should return contents and total count", async () => {
|
it("should return contents and total count", async () => {
|
||||||
mockDb.where.mockResolvedValueOnce([{ count: 10 }]); // for count
|
mockContentsRepository.count.mockResolvedValue(10);
|
||||||
mockDb.offset.mockResolvedValueOnce([{ id: "1" }]); // for data
|
mockContentsRepository.findAll.mockResolvedValue([{ id: "1" }]);
|
||||||
|
|
||||||
const result = await service.findAll({ limit: 10, offset: 0 });
|
const result = await service.findAll({ limit: 10, offset: 0 });
|
||||||
|
|
||||||
@@ -167,9 +141,9 @@ describe("ContentsService", () => {
|
|||||||
|
|
||||||
describe("incrementViews", () => {
|
describe("incrementViews", () => {
|
||||||
it("should increment views", async () => {
|
it("should increment views", async () => {
|
||||||
mockDb.returning.mockResolvedValue([{ id: "1", views: 1 }]);
|
mockContentsRepository.incrementViews.mockResolvedValue([{ id: "1", views: 1 }]);
|
||||||
const result = await service.incrementViews("1");
|
const result = await service.incrementViews("1");
|
||||||
expect(mockDb.update).toHaveBeenCalled();
|
expect(mockContentsRepository.incrementViews).toHaveBeenCalledWith("1");
|
||||||
expect(result[0].views).toBe(1);
|
expect(result[0].views).toBe(1);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,39 +3,21 @@ import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
|||||||
import { Cache } from "cache-manager";
|
import { Cache } from "cache-manager";
|
||||||
import { Inject } from "@nestjs/common";
|
import { Inject } from "@nestjs/common";
|
||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import {
|
|
||||||
and,
|
|
||||||
desc,
|
|
||||||
eq,
|
|
||||||
exists,
|
|
||||||
ilike,
|
|
||||||
isNull,
|
|
||||||
type SQL,
|
|
||||||
sql,
|
|
||||||
} from "drizzle-orm";
|
|
||||||
import { v4 as uuidv4 } from "uuid";
|
import { v4 as uuidv4 } from "uuid";
|
||||||
import { DatabaseService } from "../database/database.service";
|
import type { IMediaService } from "../common/interfaces/media.interface";
|
||||||
import {
|
import type { IStorageService } from "../common/interfaces/storage.interface";
|
||||||
categories,
|
|
||||||
contents,
|
|
||||||
contentsToTags,
|
|
||||||
favorites,
|
|
||||||
tags,
|
|
||||||
users,
|
|
||||||
} from "../database/schemas";
|
|
||||||
import type { MediaProcessingResult } from "../media/interfaces/media.interface";
|
|
||||||
import { MediaService } from "../media/media.service";
|
import { MediaService } from "../media/media.service";
|
||||||
import { S3Service } from "../s3/s3.service";
|
import { S3Service } from "../s3/s3.service";
|
||||||
import { CreateContentDto } from "./dto/create-content.dto";
|
import { ContentsRepository } from "./repositories/contents.repository";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ContentsService {
|
export class ContentsService {
|
||||||
private readonly logger = new Logger(ContentsService.name);
|
private readonly logger = new Logger(ContentsService.name);
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly databaseService: DatabaseService,
|
private readonly contentsRepository: ContentsRepository,
|
||||||
private readonly s3Service: S3Service,
|
@Inject(S3Service) private readonly s3Service: IStorageService,
|
||||||
private readonly mediaService: MediaService,
|
@Inject(MediaService) private readonly mediaService: IMediaService,
|
||||||
private readonly configService: ConfigService,
|
private readonly configService: ConfigService,
|
||||||
@Inject(CACHE_MANAGER) private cacheManager: Cache,
|
@Inject(CACHE_MANAGER) private cacheManager: Cache,
|
||||||
) {}
|
) {}
|
||||||
@@ -104,7 +86,7 @@ export class ContentsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 2. Transcodage
|
// 2. Transcodage
|
||||||
let processed: MediaProcessingResult;
|
let processed;
|
||||||
if (file.mimetype.startsWith("image/")) {
|
if (file.mimetype.startsWith("image/")) {
|
||||||
// Image ou GIF -> WebP (format moderne, bien supporté)
|
// Image ou GIF -> WebP (format moderne, bien supporté)
|
||||||
processed = await this.mediaService.processImage(file.buffer, "webp");
|
processed = await this.mediaService.processImage(file.buffer, "webp");
|
||||||
@@ -139,195 +121,71 @@ export class ContentsService {
|
|||||||
favoritesOnly?: boolean;
|
favoritesOnly?: boolean;
|
||||||
userId?: string; // Nécessaire si favoritesOnly est vrai
|
userId?: string; // Nécessaire si favoritesOnly est vrai
|
||||||
}) {
|
}) {
|
||||||
const {
|
const [data, totalCount] = await Promise.all([
|
||||||
limit,
|
this.contentsRepository.findAll(options),
|
||||||
offset,
|
this.contentsRepository.count(options),
|
||||||
sortBy,
|
]);
|
||||||
tag,
|
|
||||||
category,
|
|
||||||
author,
|
|
||||||
query,
|
|
||||||
favoritesOnly,
|
|
||||||
userId,
|
|
||||||
} = options;
|
|
||||||
|
|
||||||
let whereClause: SQL | undefined = isNull(contents.deletedAt);
|
|
||||||
|
|
||||||
if (tag) {
|
|
||||||
whereClause = and(
|
|
||||||
whereClause,
|
|
||||||
exists(
|
|
||||||
this.databaseService.db
|
|
||||||
.select()
|
|
||||||
.from(contentsToTags)
|
|
||||||
.innerJoin(tags, eq(contentsToTags.tagId, tags.id))
|
|
||||||
.where(
|
|
||||||
and(eq(contentsToTags.contentId, contents.id), eq(tags.name, tag)),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (author) {
|
|
||||||
whereClause = and(
|
|
||||||
whereClause,
|
|
||||||
exists(
|
|
||||||
this.databaseService.db
|
|
||||||
.select()
|
|
||||||
.from(users)
|
|
||||||
.where(and(eq(users.uuid, contents.userId), eq(users.username, author))),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (category) {
|
|
||||||
whereClause = and(
|
|
||||||
whereClause,
|
|
||||||
exists(
|
|
||||||
this.databaseService.db
|
|
||||||
.select()
|
|
||||||
.from(categories)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(categories.id, contents.categoryId),
|
|
||||||
sql`(${categories.slug} = ${category} OR ${categories.id}::text = ${category})`,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (query) {
|
|
||||||
whereClause = and(whereClause, ilike(contents.title, `%${query}%`));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (favoritesOnly && userId) {
|
|
||||||
whereClause = and(
|
|
||||||
whereClause,
|
|
||||||
exists(
|
|
||||||
this.databaseService.db
|
|
||||||
.select()
|
|
||||||
.from(favorites)
|
|
||||||
.where(
|
|
||||||
and(eq(favorites.contentId, contents.id), eq(favorites.userId, userId)),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pagination Total Count
|
|
||||||
const totalCountResult = await this.databaseService.db
|
|
||||||
.select({ count: sql<number>`count(*)` })
|
|
||||||
.from(contents)
|
|
||||||
.where(whereClause);
|
|
||||||
|
|
||||||
const totalCount = Number(totalCountResult[0].count);
|
|
||||||
|
|
||||||
// Sorting
|
|
||||||
let orderBy: SQL = desc(contents.createdAt);
|
|
||||||
if (sortBy === "trend") {
|
|
||||||
orderBy = desc(sql`${contents.views} + ${contents.usageCount}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await this.databaseService.db
|
|
||||||
.select()
|
|
||||||
.from(contents)
|
|
||||||
.where(whereClause)
|
|
||||||
.orderBy(orderBy)
|
|
||||||
.limit(limit)
|
|
||||||
.offset(offset);
|
|
||||||
|
|
||||||
return { data, totalCount };
|
return { data, totalCount };
|
||||||
}
|
}
|
||||||
|
|
||||||
async create(userId: string, data: CreateContentDto) {
|
async create(userId: string, data: any) {
|
||||||
this.logger.log(`Creating content for user ${userId}: ${data.title}`);
|
this.logger.log(`Creating content for user ${userId}: ${data.title}`);
|
||||||
const { tags: tagNames, ...contentData } = data;
|
const { tags: tagNames, ...contentData } = data;
|
||||||
|
|
||||||
const slug = await this.ensureUniqueSlug(contentData.title);
|
const slug = await this.ensureUniqueSlug(contentData.title);
|
||||||
|
|
||||||
return await this.databaseService.db.transaction(async (tx) => {
|
const newContent = await this.contentsRepository.create(
|
||||||
const [newContent] = await tx
|
{ ...contentData, userId, slug },
|
||||||
.insert(contents)
|
tagNames,
|
||||||
.values({ ...contentData, userId, slug })
|
);
|
||||||
.returning();
|
|
||||||
|
|
||||||
if (tagNames && tagNames.length > 0) {
|
await this.clearContentsCache();
|
||||||
for (const tagName of tagNames) {
|
return newContent;
|
||||||
const slug = tagName
|
|
||||||
.toLowerCase()
|
|
||||||
.replace(/ /g, "-")
|
|
||||||
.replace(/[^\w-]/g, "");
|
|
||||||
|
|
||||||
// Trouver ou créer le tag
|
|
||||||
let [tag] = await tx
|
|
||||||
.select()
|
|
||||||
.from(tags)
|
|
||||||
.where(eq(tags.slug, slug))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (!tag) {
|
|
||||||
[tag] = await tx
|
|
||||||
.insert(tags)
|
|
||||||
.values({ name: tagName, slug, userId })
|
|
||||||
.returning();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lier le tag au contenu
|
|
||||||
await tx
|
|
||||||
.insert(contentsToTags)
|
|
||||||
.values({ contentId: newContent.id, tagId: tag.id })
|
|
||||||
.onConflictDoNothing();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.clearContentsCache();
|
|
||||||
return newContent;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async incrementViews(id: string) {
|
async incrementViews(id: string) {
|
||||||
return await this.databaseService.db
|
return await this.contentsRepository.incrementViews(id);
|
||||||
.update(contents)
|
|
||||||
.set({ views: sql`${contents.views} + 1` })
|
|
||||||
.where(eq(contents.id, id))
|
|
||||||
.returning();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async incrementUsage(id: string) {
|
async incrementUsage(id: string) {
|
||||||
return await this.databaseService.db
|
return await this.contentsRepository.incrementUsage(id);
|
||||||
.update(contents)
|
|
||||||
.set({ usageCount: sql`${contents.usageCount} + 1` })
|
|
||||||
.where(eq(contents.id, id))
|
|
||||||
.returning();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async remove(id: string, userId: string) {
|
async remove(id: string, userId: string) {
|
||||||
this.logger.log(`Removing content ${id} for user ${userId}`);
|
this.logger.log(`Removing content ${id} for user ${userId}`);
|
||||||
const result = await this.databaseService.db
|
const deleted = await this.contentsRepository.softDelete(id, userId);
|
||||||
.update(contents)
|
|
||||||
.set({ deletedAt: new Date() })
|
|
||||||
.where(and(eq(contents.id, id), eq(contents.userId, userId)))
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
if (result.length > 0) {
|
if (deleted) {
|
||||||
await this.clearContentsCache();
|
await this.clearContentsCache();
|
||||||
}
|
}
|
||||||
return result;
|
return deleted;
|
||||||
}
|
}
|
||||||
|
|
||||||
async findOne(idOrSlug: string) {
|
async findOne(idOrSlug: string) {
|
||||||
const [content] = await this.databaseService.db
|
return this.contentsRepository.findOne(idOrSlug);
|
||||||
.select()
|
}
|
||||||
.from(contents)
|
|
||||||
.where(
|
generateBotHtml(content: any): string {
|
||||||
and(
|
const imageUrl = this.getFileUrl(content.storageKey);
|
||||||
isNull(contents.deletedAt),
|
return `<!DOCTYPE html>
|
||||||
sql`(${contents.id}::text = ${idOrSlug} OR ${contents.slug} = ${idOrSlug})`,
|
<html>
|
||||||
),
|
<head>
|
||||||
)
|
<meta charset="UTF-8">
|
||||||
.limit(1);
|
<title>${content.title}</title>
|
||||||
return content;
|
<meta property="og:title" content="${content.title}" />
|
||||||
|
<meta property="og:type" content="website" />
|
||||||
|
<meta property="og:image" content="${imageUrl}" />
|
||||||
|
<meta property="og:description" content="Découvrez ce meme sur Memegoat" />
|
||||||
|
<meta name="twitter:card" content="summary_large_image" />
|
||||||
|
<meta name="twitter:title" content="${content.title}" />
|
||||||
|
<meta name="twitter:image" content="${imageUrl}" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>${content.title}</h1>
|
||||||
|
<img src="${imageUrl}" alt="${content.title}" />
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
getFileUrl(storageKey: string): string {
|
getFileUrl(storageKey: string): string {
|
||||||
@@ -359,11 +217,7 @@ export class ContentsService {
|
|||||||
let counter = 1;
|
let counter = 1;
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
const [existing] = await this.databaseService.db
|
const existing = await this.contentsRepository.findBySlug(slug);
|
||||||
.select()
|
|
||||||
.from(contents)
|
|
||||||
.where(eq(contents.slug, slug))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (!existing) break;
|
if (!existing) break;
|
||||||
slug = `${baseSlug}-${counter++}`;
|
slug = `${baseSlug}-${counter++}`;
|
||||||
|
|||||||
383
backend/src/contents/repositories/contents.repository.ts
Normal file
383
backend/src/contents/repositories/contents.repository.ts
Normal file
@@ -0,0 +1,383 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import {
|
||||||
|
and,
|
||||||
|
desc,
|
||||||
|
eq,
|
||||||
|
exists,
|
||||||
|
ilike,
|
||||||
|
isNull,
|
||||||
|
sql,
|
||||||
|
lte,
|
||||||
|
type SQL,
|
||||||
|
} from "drizzle-orm";
|
||||||
|
import { DatabaseService } from "../../database/database.service";
|
||||||
|
import {
|
||||||
|
categories,
|
||||||
|
contents,
|
||||||
|
contentsToTags,
|
||||||
|
favorites,
|
||||||
|
tags,
|
||||||
|
users,
|
||||||
|
} from "../../database/schemas";
|
||||||
|
import type { NewContentInDb } from "../../database/schemas/content";
|
||||||
|
|
||||||
|
export interface FindAllOptions {
|
||||||
|
limit: number;
|
||||||
|
offset: number;
|
||||||
|
sortBy?: "trend" | "recent";
|
||||||
|
tag?: string;
|
||||||
|
category?: string;
|
||||||
|
author?: string;
|
||||||
|
query?: string;
|
||||||
|
favoritesOnly?: boolean;
|
||||||
|
userId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ContentsRepository {
|
||||||
|
constructor(private readonly databaseService: DatabaseService) {}
|
||||||
|
|
||||||
|
async findAll(options: FindAllOptions) {
|
||||||
|
const {
|
||||||
|
limit,
|
||||||
|
offset,
|
||||||
|
sortBy,
|
||||||
|
tag,
|
||||||
|
category,
|
||||||
|
author,
|
||||||
|
query,
|
||||||
|
favoritesOnly,
|
||||||
|
userId,
|
||||||
|
} = options;
|
||||||
|
|
||||||
|
let whereClause: SQL | undefined = isNull(contents.deletedAt);
|
||||||
|
|
||||||
|
if (tag) {
|
||||||
|
whereClause = and(
|
||||||
|
whereClause,
|
||||||
|
exists(
|
||||||
|
this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(contentsToTags)
|
||||||
|
.innerJoin(tags, eq(contentsToTags.tagId, tags.id))
|
||||||
|
.where(
|
||||||
|
and(eq(contentsToTags.contentId, contents.id), eq(tags.name, tag)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (category) {
|
||||||
|
whereClause = and(
|
||||||
|
whereClause,
|
||||||
|
exists(
|
||||||
|
this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(categories)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(contents.categoryId, categories.id),
|
||||||
|
sql`(${categories.id}::text = ${category} OR ${categories.slug} = ${category})`,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (author) {
|
||||||
|
whereClause = and(
|
||||||
|
whereClause,
|
||||||
|
exists(
|
||||||
|
this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(users)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(contents.userId, users.uuid),
|
||||||
|
sql`(${users.uuid}::text = ${author} OR ${users.username} = ${author})`,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (query) {
|
||||||
|
whereClause = and(whereClause, ilike(contents.title, `%${query}%`));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (favoritesOnly && userId) {
|
||||||
|
whereClause = and(
|
||||||
|
whereClause,
|
||||||
|
exists(
|
||||||
|
this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(favorites)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(favorites.contentId, contents.id),
|
||||||
|
eq(favorites.userId, userId),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let orderBy = desc(contents.createdAt);
|
||||||
|
if (sortBy === "trend") {
|
||||||
|
orderBy = desc(sql`${contents.views} + ${contents.usageCount} * 2`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = await this.databaseService.db
|
||||||
|
.select({
|
||||||
|
id: contents.id,
|
||||||
|
title: contents.title,
|
||||||
|
slug: contents.slug,
|
||||||
|
type: contents.type,
|
||||||
|
storageKey: contents.storageKey,
|
||||||
|
mimeType: contents.mimeType,
|
||||||
|
fileSize: contents.fileSize,
|
||||||
|
views: contents.views,
|
||||||
|
usageCount: contents.usageCount,
|
||||||
|
createdAt: contents.createdAt,
|
||||||
|
updatedAt: contents.updatedAt,
|
||||||
|
author: {
|
||||||
|
id: users.uuid,
|
||||||
|
username: users.username,
|
||||||
|
avatarUrl: users.avatarUrl,
|
||||||
|
},
|
||||||
|
category: {
|
||||||
|
id: categories.id,
|
||||||
|
name: categories.name,
|
||||||
|
slug: categories.slug,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.from(contents)
|
||||||
|
.leftJoin(users, eq(contents.userId, users.uuid))
|
||||||
|
.leftJoin(categories, eq(contents.categoryId, categories.id))
|
||||||
|
.where(whereClause)
|
||||||
|
.orderBy(orderBy)
|
||||||
|
.limit(limit)
|
||||||
|
.offset(offset);
|
||||||
|
|
||||||
|
const contentIds = results.map((r) => r.id);
|
||||||
|
const tagsForContents = contentIds.length
|
||||||
|
? await this.databaseService.db
|
||||||
|
.select({
|
||||||
|
contentId: contentsToTags.contentId,
|
||||||
|
name: tags.name,
|
||||||
|
})
|
||||||
|
.from(contentsToTags)
|
||||||
|
.innerJoin(tags, eq(contentsToTags.tagId, tags.id))
|
||||||
|
.where(sql`${contentsToTags.contentId} IN ${contentIds}`)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return results.map((r) => ({
|
||||||
|
...r,
|
||||||
|
tags: tagsForContents
|
||||||
|
.filter((t) => t.contentId === r.id)
|
||||||
|
.map((t) => t.name),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(data: NewContentInDb & { userId: string }, tagNames?: string[]) {
|
||||||
|
return await this.databaseService.db.transaction(async (tx) => {
|
||||||
|
const [newContent] = await tx
|
||||||
|
.insert(contents)
|
||||||
|
.values(data)
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
if (tagNames && tagNames.length > 0) {
|
||||||
|
for (const tagName of tagNames) {
|
||||||
|
const slug = tagName
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/ /g, "-")
|
||||||
|
.replace(/[^\w-]/g, "");
|
||||||
|
|
||||||
|
let [tag] = await tx
|
||||||
|
.select()
|
||||||
|
.from(tags)
|
||||||
|
.where(eq(tags.slug, slug))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (!tag) {
|
||||||
|
[tag] = await tx
|
||||||
|
.insert(tags)
|
||||||
|
.values({
|
||||||
|
name: tagName,
|
||||||
|
slug,
|
||||||
|
userId: data.userId,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
}
|
||||||
|
|
||||||
|
await tx
|
||||||
|
.insert(contentsToTags)
|
||||||
|
.values({
|
||||||
|
contentId: newContent.id,
|
||||||
|
tagId: tag.id,
|
||||||
|
})
|
||||||
|
.onConflictDoNothing();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return newContent;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(idOrSlug: string) {
|
||||||
|
const [result] = await this.databaseService.db
|
||||||
|
.select({
|
||||||
|
id: contents.id,
|
||||||
|
title: contents.title,
|
||||||
|
slug: contents.slug,
|
||||||
|
type: contents.type,
|
||||||
|
storageKey: contents.storageKey,
|
||||||
|
mimeType: contents.mimeType,
|
||||||
|
fileSize: contents.fileSize,
|
||||||
|
views: contents.views,
|
||||||
|
usageCount: contents.usageCount,
|
||||||
|
createdAt: contents.createdAt,
|
||||||
|
updatedAt: contents.updatedAt,
|
||||||
|
userId: contents.userId,
|
||||||
|
})
|
||||||
|
.from(contents)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
isNull(contents.deletedAt),
|
||||||
|
sql`(${contents.id}::text = ${idOrSlug} OR ${contents.slug} = ${idOrSlug})`,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async count(options: {
|
||||||
|
tag?: string;
|
||||||
|
category?: string;
|
||||||
|
author?: string;
|
||||||
|
query?: string;
|
||||||
|
favoritesOnly?: boolean;
|
||||||
|
userId?: string;
|
||||||
|
}) {
|
||||||
|
const { tag, category, author, query, favoritesOnly, userId } = options;
|
||||||
|
|
||||||
|
let whereClause: SQL | undefined = isNull(contents.deletedAt);
|
||||||
|
|
||||||
|
if (tag) {
|
||||||
|
whereClause = and(
|
||||||
|
whereClause,
|
||||||
|
exists(
|
||||||
|
this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(contentsToTags)
|
||||||
|
.innerJoin(tags, eq(contentsToTags.tagId, tags.id))
|
||||||
|
.where(
|
||||||
|
and(eq(contentsToTags.contentId, contents.id), eq(tags.name, tag)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (category) {
|
||||||
|
whereClause = and(
|
||||||
|
whereClause,
|
||||||
|
exists(
|
||||||
|
this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(categories)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(contents.categoryId, categories.id),
|
||||||
|
sql`(${categories.id}::text = ${category} OR ${categories.slug} = ${category})`,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (author) {
|
||||||
|
whereClause = and(
|
||||||
|
whereClause,
|
||||||
|
exists(
|
||||||
|
this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(users)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(contents.userId, users.uuid),
|
||||||
|
sql`(${users.uuid}::text = ${author} OR ${users.username} = ${author})`,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (query) {
|
||||||
|
whereClause = and(whereClause, ilike(contents.title, `%${query}%`));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (favoritesOnly && userId) {
|
||||||
|
whereClause = and(
|
||||||
|
whereClause,
|
||||||
|
exists(
|
||||||
|
this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(favorites)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(favorites.contentId, contents.id),
|
||||||
|
eq(favorites.userId, userId),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const [result] = await this.databaseService.db
|
||||||
|
.select({ count: sql<number>`count(*)` })
|
||||||
|
.from(contents)
|
||||||
|
.where(whereClause);
|
||||||
|
|
||||||
|
return Number(result.count);
|
||||||
|
}
|
||||||
|
|
||||||
|
async incrementViews(id: string) {
|
||||||
|
await this.databaseService.db
|
||||||
|
.update(contents)
|
||||||
|
.set({ views: sql`${contents.views} + 1` })
|
||||||
|
.where(eq(contents.id, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
async incrementUsage(id: string) {
|
||||||
|
await this.databaseService.db
|
||||||
|
.update(contents)
|
||||||
|
.set({ usageCount: sql`${contents.usageCount} + 1` })
|
||||||
|
.where(eq(contents.id, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
async softDelete(id: string, userId: string) {
|
||||||
|
const [deleted] = await this.databaseService.db
|
||||||
|
.update(contents)
|
||||||
|
.set({ deletedAt: new Date() })
|
||||||
|
.where(and(eq(contents.id, id), eq(contents.userId, userId)))
|
||||||
|
.returning();
|
||||||
|
return deleted;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findBySlug(slug: string) {
|
||||||
|
const [result] = await this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(contents)
|
||||||
|
.where(eq(contents.slug, slug))
|
||||||
|
.limit(1);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async purgeSoftDeleted(before: Date) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.delete(contents)
|
||||||
|
.where(and(sql`${contents.deletedAt} IS NOT NULL`, lte(contents.deletedAt, before)))
|
||||||
|
.returning();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,24 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { CryptoService } from "./crypto.service";
|
import { CryptoService } from "./crypto.service";
|
||||||
|
import { HashingService } from "./services/hashing.service";
|
||||||
|
import { JwtService } from "./services/jwt.service";
|
||||||
|
import { EncryptionService } from "./services/encryption.service";
|
||||||
|
import { PostQuantumService } from "./services/post-quantum.service";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
providers: [CryptoService],
|
providers: [
|
||||||
exports: [CryptoService],
|
CryptoService,
|
||||||
|
HashingService,
|
||||||
|
JwtService,
|
||||||
|
EncryptionService,
|
||||||
|
PostQuantumService,
|
||||||
|
],
|
||||||
|
exports: [
|
||||||
|
CryptoService,
|
||||||
|
HashingService,
|
||||||
|
JwtService,
|
||||||
|
EncryptionService,
|
||||||
|
PostQuantumService,
|
||||||
|
],
|
||||||
})
|
})
|
||||||
export class CryptoModule {}
|
export class CryptoModule {}
|
||||||
|
|||||||
@@ -64,6 +64,10 @@ jest.mock("jose", () => ({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
import { CryptoService } from "./crypto.service";
|
import { CryptoService } from "./crypto.service";
|
||||||
|
import { HashingService } from "./services/hashing.service";
|
||||||
|
import { JwtService } from "./services/jwt.service";
|
||||||
|
import { EncryptionService } from "./services/encryption.service";
|
||||||
|
import { PostQuantumService } from "./services/post-quantum.service";
|
||||||
|
|
||||||
describe("CryptoService", () => {
|
describe("CryptoService", () => {
|
||||||
let service: CryptoService;
|
let service: CryptoService;
|
||||||
@@ -72,6 +76,10 @@ describe("CryptoService", () => {
|
|||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
CryptoService,
|
CryptoService,
|
||||||
|
HashingService,
|
||||||
|
JwtService,
|
||||||
|
EncryptionService,
|
||||||
|
PostQuantumService,
|
||||||
{
|
{
|
||||||
provide: ConfigService,
|
provide: ConfigService,
|
||||||
useValue: {
|
useValue: {
|
||||||
|
|||||||
@@ -1,151 +1,79 @@
|
|||||||
import { Injectable, Logger } from "@nestjs/common";
|
import { Injectable } from "@nestjs/common";
|
||||||
import { ConfigService } from "@nestjs/config";
|
import type * as jose from "jose";
|
||||||
import { ml_kem768 } from "@noble/post-quantum/ml-kem.js";
|
import { EncryptionService } from "./services/encryption.service";
|
||||||
import { hash, verify } from "@node-rs/argon2";
|
import { HashingService } from "./services/hashing.service";
|
||||||
import * as jose from "jose";
|
import { JwtService } from "./services/jwt.service";
|
||||||
|
import { PostQuantumService } from "./services/post-quantum.service";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Use HashingService, JwtService, EncryptionService or PostQuantumService directly.
|
||||||
|
* This service acts as a Facade for backward compatibility.
|
||||||
|
*/
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CryptoService {
|
export class CryptoService {
|
||||||
private readonly logger = new Logger(CryptoService.name);
|
constructor(
|
||||||
private readonly jwtSecret: Uint8Array;
|
private readonly hashingService: HashingService,
|
||||||
private readonly encryptionKey: Uint8Array;
|
private readonly jwtService: JwtService,
|
||||||
|
private readonly encryptionService: EncryptionService,
|
||||||
constructor(private configService: ConfigService) {
|
private readonly postQuantumService: PostQuantumService,
|
||||||
const secret = this.configService.get<string>("JWT_SECRET");
|
) {}
|
||||||
if (!secret) {
|
|
||||||
this.logger.warn(
|
|
||||||
"JWT_SECRET is not defined, using a default insecure secret for development",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
this.jwtSecret = new TextEncoder().encode(
|
|
||||||
secret || "default-secret-change-me-in-production",
|
|
||||||
);
|
|
||||||
|
|
||||||
const encKey = this.configService.get<string>("ENCRYPTION_KEY");
|
|
||||||
if (!encKey) {
|
|
||||||
this.logger.warn(
|
|
||||||
"ENCRYPTION_KEY is not defined, using a default insecure key for development",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// Pour AES-GCM 256, on a besoin de 32 octets (256 bits)
|
|
||||||
const rawKey = encKey || "default-encryption-key-32-chars-";
|
|
||||||
this.encryptionKey = new TextEncoder().encode(
|
|
||||||
rawKey.padEnd(32, "0").substring(0, 32),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Blind Indexing (for search on encrypted data) ---
|
|
||||||
|
|
||||||
async hashEmail(email: string): Promise<string> {
|
async hashEmail(email: string): Promise<string> {
|
||||||
const normalizedEmail = email.toLowerCase().trim();
|
return this.hashingService.hashEmail(email);
|
||||||
const data = new TextEncoder().encode(normalizedEmail);
|
|
||||||
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
||||||
return Array.from(new Uint8Array(hashBuffer))
|
|
||||||
.map((b) => b.toString(16).padStart(2, "0"))
|
|
||||||
.join("");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async hashIp(ip: string): Promise<string> {
|
async hashIp(ip: string): Promise<string> {
|
||||||
const data = new TextEncoder().encode(ip);
|
return this.hashingService.hashIp(ip);
|
||||||
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
||||||
return Array.from(new Uint8Array(hashBuffer))
|
|
||||||
.map((b) => b.toString(16).padStart(2, "0"))
|
|
||||||
.join("");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getPgpEncryptionKey(): string {
|
getPgpEncryptionKey(): string {
|
||||||
return (
|
return this.encryptionService.getPgpEncryptionKey();
|
||||||
this.configService.get<string>("PGP_ENCRYPTION_KEY") || "default-pgp-key"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Argon2 Hashing ---
|
|
||||||
|
|
||||||
async hashPassword(password: string): Promise<string> {
|
async hashPassword(password: string): Promise<string> {
|
||||||
return hash(password, {
|
return this.hashingService.hashPassword(password);
|
||||||
algorithm: 2,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async verifyPassword(password: string, hash: string): Promise<boolean> {
|
async verifyPassword(password: string, hash: string): Promise<boolean> {
|
||||||
return verify(hash, password);
|
return this.hashingService.verifyPassword(password, hash);
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- JWT Operations via jose ---
|
|
||||||
|
|
||||||
async generateJwt(
|
async generateJwt(
|
||||||
payload: jose.JWTPayload,
|
payload: jose.JWTPayload,
|
||||||
expiresIn = "2h",
|
expiresIn = "2h",
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
return new jose.SignJWT(payload)
|
return this.jwtService.generateJwt(payload, expiresIn);
|
||||||
.setProtectedHeader({ alg: "HS256" })
|
|
||||||
.setIssuedAt()
|
|
||||||
.setExpirationTime(expiresIn)
|
|
||||||
.sign(this.jwtSecret);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async verifyJwt<T extends jose.JWTPayload>(token: string): Promise<T> {
|
async verifyJwt<T extends jose.JWTPayload>(token: string): Promise<T> {
|
||||||
const { payload } = await jose.jwtVerify(token, this.jwtSecret);
|
return this.jwtService.verifyJwt<T>(token);
|
||||||
return payload as T;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Encryption & Decryption (JWE) ---
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Chiffre un contenu textuel en utilisant JWE (Compact Serialization)
|
|
||||||
* Algorithme: A256GCMKW pour la gestion des clés, A256GCM pour le chiffrement de contenu
|
|
||||||
*/
|
|
||||||
async encryptContent(content: string): Promise<string> {
|
async encryptContent(content: string): Promise<string> {
|
||||||
const data = new TextEncoder().encode(content);
|
return this.encryptionService.encryptContent(content);
|
||||||
return new jose.CompactEncrypt(data)
|
|
||||||
.setProtectedHeader({ alg: "dir", enc: "A256GCM" })
|
|
||||||
.encrypt(this.encryptionKey);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Déchiffre un contenu JWE
|
|
||||||
*/
|
|
||||||
async decryptContent(jwe: string): Promise<string> {
|
async decryptContent(jwe: string): Promise<string> {
|
||||||
const { plaintext } = await jose.compactDecrypt(jwe, this.encryptionKey);
|
return this.encryptionService.decryptContent(jwe);
|
||||||
return new TextDecoder().decode(plaintext);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Signature & Verification (JWS) ---
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Signe un contenu textuel en utilisant JWS (Compact Serialization)
|
|
||||||
* Algorithme: HS256 (HMAC-SHA256)
|
|
||||||
*/
|
|
||||||
async signContent(content: string): Promise<string> {
|
async signContent(content: string): Promise<string> {
|
||||||
const data = new TextEncoder().encode(content);
|
return this.encryptionService.signContent(content);
|
||||||
return new jose.CompactSign(data)
|
|
||||||
.setProtectedHeader({ alg: "HS256" })
|
|
||||||
.sign(this.jwtSecret);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Vérifie la signature JWS d'un contenu
|
|
||||||
*/
|
|
||||||
async verifyContentSignature(jws: string): Promise<string> {
|
async verifyContentSignature(jws: string): Promise<string> {
|
||||||
const { payload } = await jose.compactVerify(jws, this.jwtSecret);
|
return this.encryptionService.verifyContentSignature(jws);
|
||||||
return new TextDecoder().decode(payload);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Post-Quantum Cryptography via @noble/post-quantum ---
|
|
||||||
// Example: Kyber (ML-KEM) key encapsulation
|
|
||||||
|
|
||||||
generatePostQuantumKeyPair() {
|
generatePostQuantumKeyPair() {
|
||||||
const seed = new Uint8Array(64);
|
return this.postQuantumService.generatePostQuantumKeyPair();
|
||||||
crypto.getRandomValues(seed);
|
|
||||||
const { publicKey, secretKey } = ml_kem768.keygen(seed);
|
|
||||||
return { publicKey, secretKey };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
encapsulate(publicKey: Uint8Array) {
|
encapsulate(publicKey: Uint8Array) {
|
||||||
return ml_kem768.encapsulate(publicKey);
|
return this.postQuantumService.encapsulate(publicKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
decapsulate(cipherText: Uint8Array, secretKey: Uint8Array) {
|
decapsulate(cipherText: Uint8Array, secretKey: Uint8Array) {
|
||||||
return ml_kem768.decapsulate(cipherText, secretKey);
|
return this.postQuantumService.decapsulate(cipherText, secretKey);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
58
backend/src/crypto/services/encryption.service.ts
Normal file
58
backend/src/crypto/services/encryption.service.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import { Injectable, Logger } from "@nestjs/common";
|
||||||
|
import { ConfigService } from "@nestjs/config";
|
||||||
|
import * as jose from "jose";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class EncryptionService {
|
||||||
|
private readonly logger = new Logger(EncryptionService.name);
|
||||||
|
private readonly jwtSecret: Uint8Array;
|
||||||
|
private readonly encryptionKey: Uint8Array;
|
||||||
|
|
||||||
|
constructor(private configService: ConfigService) {
|
||||||
|
const secret = this.configService.get<string>("JWT_SECRET");
|
||||||
|
this.jwtSecret = new TextEncoder().encode(
|
||||||
|
secret || "default-secret-change-me-in-production",
|
||||||
|
);
|
||||||
|
|
||||||
|
const encKey = this.configService.get<string>("ENCRYPTION_KEY");
|
||||||
|
if (!encKey) {
|
||||||
|
this.logger.warn(
|
||||||
|
"ENCRYPTION_KEY is not defined, using a default insecure key for development",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const rawKey = encKey || "default-encryption-key-32-chars-";
|
||||||
|
this.encryptionKey = new TextEncoder().encode(
|
||||||
|
rawKey.padEnd(32, "0").substring(0, 32),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async encryptContent(content: string): Promise<string> {
|
||||||
|
const data = new TextEncoder().encode(content);
|
||||||
|
return new jose.CompactEncrypt(data)
|
||||||
|
.setProtectedHeader({ alg: "dir", enc: "A256GCM" })
|
||||||
|
.encrypt(this.encryptionKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
async decryptContent(jwe: string): Promise<string> {
|
||||||
|
const { plaintext } = await jose.compactDecrypt(jwe, this.encryptionKey);
|
||||||
|
return new TextDecoder().decode(plaintext);
|
||||||
|
}
|
||||||
|
|
||||||
|
async signContent(content: string): Promise<string> {
|
||||||
|
const data = new TextEncoder().encode(content);
|
||||||
|
return new jose.CompactSign(data)
|
||||||
|
.setProtectedHeader({ alg: "HS256" })
|
||||||
|
.sign(this.jwtSecret);
|
||||||
|
}
|
||||||
|
|
||||||
|
async verifyContentSignature(jws: string): Promise<string> {
|
||||||
|
const { payload } = await jose.compactVerify(jws, this.jwtSecret);
|
||||||
|
return new TextDecoder().decode(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
getPgpEncryptionKey(): string {
|
||||||
|
return (
|
||||||
|
this.configService.get<string>("PGP_ENCRYPTION_KEY") || "default-pgp-key"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
32
backend/src/crypto/services/hashing.service.ts
Normal file
32
backend/src/crypto/services/hashing.service.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { hash, verify } from "@node-rs/argon2";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class HashingService {
|
||||||
|
async hashEmail(email: string): Promise<string> {
|
||||||
|
const normalizedEmail = email.toLowerCase().trim();
|
||||||
|
return this.hashSha256(normalizedEmail);
|
||||||
|
}
|
||||||
|
|
||||||
|
async hashIp(ip: string): Promise<string> {
|
||||||
|
return this.hashSha256(ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
async hashSha256(text: string): Promise<string> {
|
||||||
|
const data = new TextEncoder().encode(text);
|
||||||
|
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
||||||
|
return Array.from(new Uint8Array(hashBuffer))
|
||||||
|
.map((b) => b.toString(16).padStart(2, "0"))
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
async hashPassword(password: string): Promise<string> {
|
||||||
|
return hash(password, {
|
||||||
|
algorithm: 2,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async verifyPassword(password: string, hash: string): Promise<boolean> {
|
||||||
|
return verify(hash, password);
|
||||||
|
}
|
||||||
|
}
|
||||||
37
backend/src/crypto/services/jwt.service.ts
Normal file
37
backend/src/crypto/services/jwt.service.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { Injectable, Logger } from "@nestjs/common";
|
||||||
|
import { ConfigService } from "@nestjs/config";
|
||||||
|
import * as jose from "jose";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class JwtService {
|
||||||
|
private readonly logger = new Logger(JwtService.name);
|
||||||
|
private readonly jwtSecret: Uint8Array;
|
||||||
|
|
||||||
|
constructor(private configService: ConfigService) {
|
||||||
|
const secret = this.configService.get<string>("JWT_SECRET");
|
||||||
|
if (!secret) {
|
||||||
|
this.logger.warn(
|
||||||
|
"JWT_SECRET is not defined, using a default insecure secret for development",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.jwtSecret = new TextEncoder().encode(
|
||||||
|
secret || "default-secret-change-me-in-production",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async generateJwt(
|
||||||
|
payload: jose.JWTPayload,
|
||||||
|
expiresIn = "2h",
|
||||||
|
): Promise<string> {
|
||||||
|
return new jose.SignJWT(payload)
|
||||||
|
.setProtectedHeader({ alg: "HS256" })
|
||||||
|
.setIssuedAt()
|
||||||
|
.setExpirationTime(expiresIn)
|
||||||
|
.sign(this.jwtSecret);
|
||||||
|
}
|
||||||
|
|
||||||
|
async verifyJwt<T extends jose.JWTPayload>(token: string): Promise<T> {
|
||||||
|
const { payload } = await jose.jwtVerify(token, this.jwtSecret);
|
||||||
|
return payload as T;
|
||||||
|
}
|
||||||
|
}
|
||||||
20
backend/src/crypto/services/post-quantum.service.ts
Normal file
20
backend/src/crypto/services/post-quantum.service.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { ml_kem768 } from "@noble/post-quantum/ml-kem.js";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PostQuantumService {
|
||||||
|
generatePostQuantumKeyPair() {
|
||||||
|
const seed = new Uint8Array(64);
|
||||||
|
crypto.getRandomValues(seed);
|
||||||
|
const { publicKey, secretKey } = ml_kem768.keygen(seed);
|
||||||
|
return { publicKey, secretKey };
|
||||||
|
}
|
||||||
|
|
||||||
|
encapsulate(publicKey: Uint8Array) {
|
||||||
|
return ml_kem768.encapsulate(publicKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
decapsulate(cipherText: Uint8Array, secretKey: Uint8Array) {
|
||||||
|
return ml_kem768.decapsulate(cipherText, secretKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,11 +2,12 @@ import { Module } from "@nestjs/common";
|
|||||||
import { DatabaseModule } from "../database/database.module";
|
import { DatabaseModule } from "../database/database.module";
|
||||||
import { FavoritesController } from "./favorites.controller";
|
import { FavoritesController } from "./favorites.controller";
|
||||||
import { FavoritesService } from "./favorites.service";
|
import { FavoritesService } from "./favorites.service";
|
||||||
|
import { FavoritesRepository } from "./repositories/favorites.repository";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DatabaseModule],
|
imports: [DatabaseModule],
|
||||||
controllers: [FavoritesController],
|
controllers: [FavoritesController],
|
||||||
providers: [FavoritesService],
|
providers: [FavoritesService, FavoritesRepository],
|
||||||
exports: [FavoritesService],
|
exports: [FavoritesService],
|
||||||
})
|
})
|
||||||
export class FavoritesModule {}
|
export class FavoritesModule {}
|
||||||
|
|||||||
@@ -1,54 +1,31 @@
|
|||||||
import { ConflictException, NotFoundException } from "@nestjs/common";
|
import { ConflictException, NotFoundException } from "@nestjs/common";
|
||||||
import { Test, TestingModule } from "@nestjs/testing";
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
import { DatabaseService } from "../database/database.service";
|
|
||||||
import { FavoritesService } from "./favorites.service";
|
import { FavoritesService } from "./favorites.service";
|
||||||
|
import { FavoritesRepository } from "./repositories/favorites.repository";
|
||||||
|
|
||||||
describe("FavoritesService", () => {
|
describe("FavoritesService", () => {
|
||||||
let service: FavoritesService;
|
let service: FavoritesService;
|
||||||
|
let repository: FavoritesRepository;
|
||||||
|
|
||||||
const mockDb = {
|
const mockFavoritesRepository = {
|
||||||
select: jest.fn(),
|
findContentById: jest.fn(),
|
||||||
from: jest.fn(),
|
add: jest.fn(),
|
||||||
where: jest.fn(),
|
remove: jest.fn(),
|
||||||
limit: jest.fn(),
|
findByUserId: jest.fn(),
|
||||||
offset: jest.fn(),
|
|
||||||
innerJoin: jest.fn(),
|
|
||||||
insert: jest.fn(),
|
|
||||||
values: jest.fn(),
|
|
||||||
delete: jest.fn(),
|
|
||||||
returning: jest.fn(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
|
|
||||||
const chain = {
|
|
||||||
select: jest.fn().mockReturnThis(),
|
|
||||||
from: jest.fn().mockReturnThis(),
|
|
||||||
where: jest.fn().mockReturnThis(),
|
|
||||||
limit: jest.fn().mockReturnThis(),
|
|
||||||
offset: jest.fn().mockReturnThis(),
|
|
||||||
innerJoin: jest.fn().mockReturnThis(),
|
|
||||||
insert: jest.fn().mockReturnThis(),
|
|
||||||
values: jest.fn().mockReturnThis(),
|
|
||||||
delete: jest.fn().mockReturnThis(),
|
|
||||||
returning: jest.fn().mockReturnThis(),
|
|
||||||
};
|
|
||||||
|
|
||||||
const mockImplementation = () => Object.assign(Promise.resolve([]), chain);
|
|
||||||
for (const mock of Object.values(chain)) {
|
|
||||||
mock.mockImplementation(mockImplementation);
|
|
||||||
}
|
|
||||||
Object.assign(mockDb, chain);
|
|
||||||
|
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
FavoritesService,
|
FavoritesService,
|
||||||
{ provide: DatabaseService, useValue: { db: mockDb } },
|
{ provide: FavoritesRepository, useValue: mockFavoritesRepository },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
service = module.get<FavoritesService>(FavoritesService);
|
service = module.get<FavoritesService>(FavoritesService);
|
||||||
|
repository = module.get<FavoritesRepository>(FavoritesRepository);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should be defined", () => {
|
it("should be defined", () => {
|
||||||
@@ -57,26 +34,27 @@ describe("FavoritesService", () => {
|
|||||||
|
|
||||||
describe("addFavorite", () => {
|
describe("addFavorite", () => {
|
||||||
it("should add a favorite", async () => {
|
it("should add a favorite", async () => {
|
||||||
mockDb.limit.mockResolvedValue([{ id: "content1" }]);
|
mockFavoritesRepository.findContentById.mockResolvedValue({ id: "content1" });
|
||||||
mockDb.returning.mockResolvedValue([
|
mockFavoritesRepository.add.mockResolvedValue([
|
||||||
{ userId: "u1", contentId: "content1" },
|
{ userId: "u1", contentId: "content1" },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const result = await service.addFavorite("u1", "content1");
|
const result = await service.addFavorite("u1", "content1");
|
||||||
|
|
||||||
expect(result).toEqual([{ userId: "u1", contentId: "content1" }]);
|
expect(result).toEqual([{ userId: "u1", contentId: "content1" }]);
|
||||||
|
expect(repository.add).toHaveBeenCalledWith("u1", "content1");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should throw NotFoundException if content does not exist", async () => {
|
it("should throw NotFoundException if content does not exist", async () => {
|
||||||
mockDb.limit.mockResolvedValue([]);
|
mockFavoritesRepository.findContentById.mockResolvedValue(null);
|
||||||
await expect(service.addFavorite("u1", "invalid")).rejects.toThrow(
|
await expect(service.addFavorite("u1", "invalid")).rejects.toThrow(
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should throw ConflictException on duplicate favorite", async () => {
|
it("should throw ConflictException on duplicate favorite", async () => {
|
||||||
mockDb.limit.mockResolvedValue([{ id: "content1" }]);
|
mockFavoritesRepository.findContentById.mockResolvedValue({ id: "content1" });
|
||||||
mockDb.returning.mockRejectedValue(new Error("Duplicate"));
|
mockFavoritesRepository.add.mockRejectedValue(new Error("Duplicate"));
|
||||||
await expect(service.addFavorite("u1", "content1")).rejects.toThrow(
|
await expect(service.addFavorite("u1", "content1")).rejects.toThrow(
|
||||||
ConflictException,
|
ConflictException,
|
||||||
);
|
);
|
||||||
@@ -85,13 +63,14 @@ describe("FavoritesService", () => {
|
|||||||
|
|
||||||
describe("removeFavorite", () => {
|
describe("removeFavorite", () => {
|
||||||
it("should remove a favorite", async () => {
|
it("should remove a favorite", async () => {
|
||||||
mockDb.returning.mockResolvedValue([{ userId: "u1", contentId: "c1" }]);
|
mockFavoritesRepository.remove.mockResolvedValue([{ userId: "u1", contentId: "c1" }]);
|
||||||
const result = await service.removeFavorite("u1", "c1");
|
const result = await service.removeFavorite("u1", "c1");
|
||||||
expect(result).toEqual({ userId: "u1", contentId: "c1" });
|
expect(result).toEqual({ userId: "u1", contentId: "c1" });
|
||||||
|
expect(repository.remove).toHaveBeenCalledWith("u1", "c1");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should throw NotFoundException if favorite not found", async () => {
|
it("should throw NotFoundException if favorite not found", async () => {
|
||||||
mockDb.returning.mockResolvedValue([]);
|
mockFavoritesRepository.remove.mockResolvedValue([]);
|
||||||
await expect(service.removeFavorite("u1", "c1")).rejects.toThrow(
|
await expect(service.removeFavorite("u1", "c1")).rejects.toThrow(
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,46 +4,32 @@ import {
|
|||||||
Logger,
|
Logger,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
import { and, eq } from "drizzle-orm";
|
import { FavoritesRepository } from "./repositories/favorites.repository";
|
||||||
import { DatabaseService } from "../database/database.service";
|
|
||||||
import { contents, favorites } from "../database/schemas";
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class FavoritesService {
|
export class FavoritesService {
|
||||||
private readonly logger = new Logger(FavoritesService.name);
|
private readonly logger = new Logger(FavoritesService.name);
|
||||||
|
|
||||||
constructor(private readonly databaseService: DatabaseService) {}
|
constructor(private readonly favoritesRepository: FavoritesRepository) {}
|
||||||
|
|
||||||
async addFavorite(userId: string, contentId: string) {
|
async addFavorite(userId: string, contentId: string) {
|
||||||
this.logger.log(`Adding favorite: user ${userId}, content ${contentId}`);
|
this.logger.log(`Adding favorite: user ${userId}, content ${contentId}`);
|
||||||
// Vérifier si le contenu existe
|
|
||||||
const content = await this.databaseService.db
|
|
||||||
.select()
|
|
||||||
.from(contents)
|
|
||||||
.where(eq(contents.id, contentId))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (content.length === 0) {
|
const content = await this.favoritesRepository.findContentById(contentId);
|
||||||
|
if (!content) {
|
||||||
throw new NotFoundException("Content not found");
|
throw new NotFoundException("Content not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return await this.databaseService.db
|
return await this.favoritesRepository.add(userId, contentId);
|
||||||
.insert(favorites)
|
|
||||||
.values({ userId, contentId })
|
|
||||||
.returning();
|
|
||||||
} catch (_error) {
|
} catch (_error) {
|
||||||
// Probablement une violation de clé primaire (déjà en favori)
|
|
||||||
throw new ConflictException("Content already in favorites");
|
throw new ConflictException("Content already in favorites");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async removeFavorite(userId: string, contentId: string) {
|
async removeFavorite(userId: string, contentId: string) {
|
||||||
this.logger.log(`Removing favorite: user ${userId}, content ${contentId}`);
|
this.logger.log(`Removing favorite: user ${userId}, content ${contentId}`);
|
||||||
const result = await this.databaseService.db
|
const result = await this.favoritesRepository.remove(userId, contentId);
|
||||||
.delete(favorites)
|
|
||||||
.where(and(eq(favorites.userId, userId), eq(favorites.contentId, contentId)))
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
if (result.length === 0) {
|
if (result.length === 0) {
|
||||||
throw new NotFoundException("Favorite not found");
|
throw new NotFoundException("Favorite not found");
|
||||||
@@ -53,16 +39,6 @@ export class FavoritesService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getUserFavorites(userId: string, limit: number, offset: number) {
|
async getUserFavorites(userId: string, limit: number, offset: number) {
|
||||||
const data = await this.databaseService.db
|
return await this.favoritesRepository.findByUserId(userId, limit, offset);
|
||||||
.select({
|
|
||||||
content: contents,
|
|
||||||
})
|
|
||||||
.from(favorites)
|
|
||||||
.innerJoin(contents, eq(favorites.contentId, contents.id))
|
|
||||||
.where(eq(favorites.userId, userId))
|
|
||||||
.limit(limit)
|
|
||||||
.offset(offset);
|
|
||||||
|
|
||||||
return data.map((item) => item.content);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
46
backend/src/favorites/repositories/favorites.repository.ts
Normal file
46
backend/src/favorites/repositories/favorites.repository.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { and, eq } from "drizzle-orm";
|
||||||
|
import { DatabaseService } from "../../database/database.service";
|
||||||
|
import { contents, favorites } from "../../database/schemas";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class FavoritesRepository {
|
||||||
|
constructor(private readonly databaseService: DatabaseService) {}
|
||||||
|
|
||||||
|
async findContentById(contentId: string) {
|
||||||
|
const result = await this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(contents)
|
||||||
|
.where(eq(contents.id, contentId))
|
||||||
|
.limit(1);
|
||||||
|
return result[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async add(userId: string, contentId: string) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.insert(favorites)
|
||||||
|
.values({ userId, contentId })
|
||||||
|
.returning();
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(userId: string, contentId: string) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.delete(favorites)
|
||||||
|
.where(and(eq(favorites.userId, userId), eq(favorites.contentId, contentId)))
|
||||||
|
.returning();
|
||||||
|
}
|
||||||
|
|
||||||
|
async findByUserId(userId: string, limit: number, offset: number) {
|
||||||
|
const data = await this.databaseService.db
|
||||||
|
.select({
|
||||||
|
content: contents,
|
||||||
|
})
|
||||||
|
.from(favorites)
|
||||||
|
.innerJoin(contents, eq(favorites.contentId, contents.id))
|
||||||
|
.where(eq(favorites.userId, userId))
|
||||||
|
.limit(limit)
|
||||||
|
.offset(offset);
|
||||||
|
|
||||||
|
return data.map((item) => item.content);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
import { Injectable, Logger } from "@nestjs/common";
|
import { Injectable, Logger } from "@nestjs/common";
|
||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import { MailerService } from "@nestjs-modules/mailer";
|
import { MailerService } from "@nestjs-modules/mailer";
|
||||||
|
import type { IMailService } from "../common/interfaces/mail.interface";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class MailService {
|
export class MailService implements IMailService {
|
||||||
private readonly logger = new Logger(MailService.name);
|
private readonly logger = new Logger(MailService.name);
|
||||||
private readonly domain: string;
|
private readonly domain: string;
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { MediaService } from "./media.service";
|
import { MediaService } from "./media.service";
|
||||||
|
import { ImageProcessorStrategy } from "./strategies/image-processor.strategy";
|
||||||
|
import { VideoProcessorStrategy } from "./strategies/video-processor.strategy";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
providers: [MediaService],
|
providers: [MediaService, ImageProcessorStrategy, VideoProcessorStrategy],
|
||||||
exports: [MediaService],
|
exports: [MediaService],
|
||||||
})
|
})
|
||||||
export class MediaModule {}
|
export class MediaModule {}
|
||||||
|
|||||||
@@ -6,6 +6,9 @@ import ffmpeg from "fluent-ffmpeg";
|
|||||||
import sharp from "sharp";
|
import sharp from "sharp";
|
||||||
import { MediaService } from "./media.service";
|
import { MediaService } from "./media.service";
|
||||||
|
|
||||||
|
import { ImageProcessorStrategy } from "./strategies/image-processor.strategy";
|
||||||
|
import { VideoProcessorStrategy } from "./strategies/video-processor.strategy";
|
||||||
|
|
||||||
jest.mock("sharp");
|
jest.mock("sharp");
|
||||||
jest.mock("fluent-ffmpeg");
|
jest.mock("fluent-ffmpeg");
|
||||||
jest.mock("node:fs/promises");
|
jest.mock("node:fs/promises");
|
||||||
@@ -29,6 +32,8 @@ describe("MediaService", () => {
|
|||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
MediaService,
|
MediaService,
|
||||||
|
ImageProcessorStrategy,
|
||||||
|
VideoProcessorStrategy,
|
||||||
{
|
{
|
||||||
provide: ConfigService,
|
provide: ConfigService,
|
||||||
useValue: {
|
useValue: {
|
||||||
|
|||||||
@@ -1,22 +1,18 @@
|
|||||||
import { readFile, unlink, writeFile } from "node:fs/promises";
|
|
||||||
import { tmpdir } from "node:os";
|
|
||||||
import { join } from "node:path";
|
|
||||||
import { Readable } from "node:stream";
|
import { Readable } from "node:stream";
|
||||||
import {
|
import {
|
||||||
BadRequestException,
|
|
||||||
Injectable,
|
Injectable,
|
||||||
InternalServerErrorException,
|
InternalServerErrorException,
|
||||||
Logger,
|
Logger,
|
||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import * as NodeClam from "clamscan";
|
import * as NodeClam from "clamscan";
|
||||||
import ffmpeg from "fluent-ffmpeg";
|
|
||||||
import sharp from "sharp";
|
|
||||||
import { v4 as uuidv4 } from "uuid";
|
|
||||||
import type {
|
import type {
|
||||||
|
IMediaService,
|
||||||
MediaProcessingResult,
|
MediaProcessingResult,
|
||||||
ScanResult,
|
ScanResult,
|
||||||
} from "./interfaces/media.interface";
|
} from "../common/interfaces/media.interface";
|
||||||
|
import { ImageProcessorStrategy } from "./strategies/image-processor.strategy";
|
||||||
|
import { VideoProcessorStrategy } from "./strategies/video-processor.strategy";
|
||||||
|
|
||||||
interface ClamScanner {
|
interface ClamScanner {
|
||||||
scanStream(
|
scanStream(
|
||||||
@@ -25,12 +21,16 @@ interface ClamScanner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class MediaService {
|
export class MediaService implements IMediaService {
|
||||||
private readonly logger = new Logger(MediaService.name);
|
private readonly logger = new Logger(MediaService.name);
|
||||||
private clamscan: ClamScanner | null = null;
|
private clamscan: ClamScanner | null = null;
|
||||||
private isClamAvInitialized = false;
|
private isClamAvInitialized = false;
|
||||||
|
|
||||||
constructor(private readonly configService: ConfigService) {
|
constructor(
|
||||||
|
private readonly configService: ConfigService,
|
||||||
|
private readonly imageProcessor: ImageProcessorStrategy,
|
||||||
|
private readonly videoProcessor: VideoProcessorStrategy,
|
||||||
|
) {
|
||||||
this.initClamScan();
|
this.initClamScan();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,82 +84,13 @@ export class MediaService {
|
|||||||
buffer: Buffer,
|
buffer: Buffer,
|
||||||
format: "webp" | "avif" = "webp",
|
format: "webp" | "avif" = "webp",
|
||||||
): Promise<MediaProcessingResult> {
|
): Promise<MediaProcessingResult> {
|
||||||
try {
|
return this.imageProcessor.process(buffer, { format });
|
||||||
let pipeline = sharp(buffer);
|
|
||||||
const metadata = await pipeline.metadata();
|
|
||||||
|
|
||||||
if (format === "webp") {
|
|
||||||
pipeline = pipeline.webp({ quality: 80, effort: 6 });
|
|
||||||
} else {
|
|
||||||
pipeline = pipeline.avif({ quality: 65, effort: 6 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const processedBuffer = await pipeline.toBuffer();
|
|
||||||
|
|
||||||
return {
|
|
||||||
buffer: processedBuffer,
|
|
||||||
mimeType: `image/${format}`,
|
|
||||||
extension: format,
|
|
||||||
width: metadata.width,
|
|
||||||
height: metadata.height,
|
|
||||||
size: processedBuffer.length,
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
this.logger.error(`Error processing image: ${error.message}`);
|
|
||||||
throw new BadRequestException("Failed to process image");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async processVideo(
|
async processVideo(
|
||||||
buffer: Buffer,
|
buffer: Buffer,
|
||||||
format: "webm" | "av1" = "webm",
|
format: "webm" | "av1" = "webm",
|
||||||
): Promise<MediaProcessingResult> {
|
): Promise<MediaProcessingResult> {
|
||||||
const tempInput = join(tmpdir(), `${uuidv4()}.tmp`);
|
return this.videoProcessor.process(buffer, { format });
|
||||||
const tempOutput = join(
|
|
||||||
tmpdir(),
|
|
||||||
`${uuidv4()}.${format === "av1" ? "mp4" : "webm"}`,
|
|
||||||
);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await writeFile(tempInput, buffer);
|
|
||||||
|
|
||||||
await new Promise<void>((resolve, reject) => {
|
|
||||||
let command = ffmpeg(tempInput);
|
|
||||||
|
|
||||||
if (format === "webm") {
|
|
||||||
command = command
|
|
||||||
.toFormat("webm")
|
|
||||||
.videoCodec("libvpx-vp9")
|
|
||||||
.audioCodec("libopus")
|
|
||||||
.outputOptions("-crf 30", "-b:v 0");
|
|
||||||
} else {
|
|
||||||
command = command
|
|
||||||
.toFormat("mp4")
|
|
||||||
.videoCodec("libaom-av1")
|
|
||||||
.audioCodec("libopus")
|
|
||||||
.outputOptions("-crf 34", "-b:v 0", "-strict experimental");
|
|
||||||
}
|
|
||||||
|
|
||||||
command
|
|
||||||
.on("end", () => resolve())
|
|
||||||
.on("error", (err) => reject(err))
|
|
||||||
.save(tempOutput);
|
|
||||||
});
|
|
||||||
|
|
||||||
const processedBuffer = await readFile(tempOutput);
|
|
||||||
|
|
||||||
return {
|
|
||||||
buffer: processedBuffer,
|
|
||||||
mimeType: format === "av1" ? "video/mp4" : "video/webm",
|
|
||||||
extension: format === "av1" ? "mp4" : "webm",
|
|
||||||
size: processedBuffer.length,
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
this.logger.error(`Error processing video: ${error.message}`);
|
|
||||||
throw new BadRequestException("Failed to process video");
|
|
||||||
} finally {
|
|
||||||
await unlink(tempInput).catch(() => {});
|
|
||||||
await unlink(tempOutput).catch(() => {});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
44
backend/src/media/strategies/image-processor.strategy.ts
Normal file
44
backend/src/media/strategies/image-processor.strategy.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { BadRequestException, Injectable, Logger } from "@nestjs/common";
|
||||||
|
import sharp from "sharp";
|
||||||
|
import type { MediaProcessingResult } from "../../common/interfaces/media.interface";
|
||||||
|
import type { IMediaProcessorStrategy } from "./media-processor.strategy";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ImageProcessorStrategy implements IMediaProcessorStrategy {
|
||||||
|
private readonly logger = new Logger(ImageProcessorStrategy.name);
|
||||||
|
|
||||||
|
canHandle(mimeType: string): boolean {
|
||||||
|
return mimeType.startsWith("image/");
|
||||||
|
}
|
||||||
|
|
||||||
|
async process(
|
||||||
|
buffer: Buffer,
|
||||||
|
options: { format: "webp" | "avif" } = { format: "webp" },
|
||||||
|
): Promise<MediaProcessingResult> {
|
||||||
|
try {
|
||||||
|
const { format } = options;
|
||||||
|
let pipeline = sharp(buffer);
|
||||||
|
const metadata = await pipeline.metadata();
|
||||||
|
|
||||||
|
if (format === "webp") {
|
||||||
|
pipeline = pipeline.webp({ quality: 80, effort: 6 });
|
||||||
|
} else {
|
||||||
|
pipeline = pipeline.avif({ quality: 65, effort: 6 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const processedBuffer = await pipeline.toBuffer();
|
||||||
|
|
||||||
|
return {
|
||||||
|
buffer: processedBuffer,
|
||||||
|
mimeType: `image/${format}`,
|
||||||
|
extension: format,
|
||||||
|
width: metadata.width,
|
||||||
|
height: metadata.height,
|
||||||
|
size: processedBuffer.length,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(`Error processing image: ${error.message}`);
|
||||||
|
throw new BadRequestException("Failed to process image");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
6
backend/src/media/strategies/media-processor.strategy.ts
Normal file
6
backend/src/media/strategies/media-processor.strategy.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import type { MediaProcessingResult } from "../../common/interfaces/media.interface";
|
||||||
|
|
||||||
|
export interface IMediaProcessorStrategy {
|
||||||
|
canHandle(mimeType: string): boolean;
|
||||||
|
process(buffer: Buffer, options?: any): Promise<MediaProcessingResult>;
|
||||||
|
}
|
||||||
71
backend/src/media/strategies/video-processor.strategy.ts
Normal file
71
backend/src/media/strategies/video-processor.strategy.ts
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import { readFile, unlink, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { BadRequestException, Injectable, Logger } from "@nestjs/common";
|
||||||
|
import ffmpeg from "fluent-ffmpeg";
|
||||||
|
import { v4 as uuidv4 } from "uuid";
|
||||||
|
import type { MediaProcessingResult } from "../../common/interfaces/media.interface";
|
||||||
|
import type { IMediaProcessorStrategy } from "./media-processor.strategy";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class VideoProcessorStrategy implements IMediaProcessorStrategy {
|
||||||
|
private readonly logger = new Logger(VideoProcessorStrategy.name);
|
||||||
|
|
||||||
|
canHandle(mimeType: string): boolean {
|
||||||
|
return mimeType.startsWith("video/");
|
||||||
|
}
|
||||||
|
|
||||||
|
async process(
|
||||||
|
buffer: Buffer,
|
||||||
|
options: { format: "webm" | "av1" } = { format: "webm" },
|
||||||
|
): Promise<MediaProcessingResult> {
|
||||||
|
const { format } = options;
|
||||||
|
const tempInput = join(tmpdir(), `${uuidv4()}.tmp`);
|
||||||
|
const tempOutput = join(
|
||||||
|
tmpdir(),
|
||||||
|
`${uuidv4()}.${format === "av1" ? "mp4" : "webm"}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await writeFile(tempInput, buffer);
|
||||||
|
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
let command = ffmpeg(tempInput);
|
||||||
|
|
||||||
|
if (format === "webm") {
|
||||||
|
command = command
|
||||||
|
.toFormat("webm")
|
||||||
|
.videoCodec("libvpx-vp9")
|
||||||
|
.audioCodec("libopus")
|
||||||
|
.outputOptions("-crf 30", "-b:v 0");
|
||||||
|
} else {
|
||||||
|
command = command
|
||||||
|
.toFormat("mp4")
|
||||||
|
.videoCodec("libaom-av1")
|
||||||
|
.audioCodec("libopus")
|
||||||
|
.outputOptions("-crf 34", "-b:v 0", "-strict experimental");
|
||||||
|
}
|
||||||
|
|
||||||
|
command
|
||||||
|
.on("end", () => resolve())
|
||||||
|
.on("error", (err) => reject(err))
|
||||||
|
.save(tempOutput);
|
||||||
|
});
|
||||||
|
|
||||||
|
const processedBuffer = await readFile(tempOutput);
|
||||||
|
|
||||||
|
return {
|
||||||
|
buffer: processedBuffer,
|
||||||
|
mimeType: format === "av1" ? "video/mp4" : "video/webm",
|
||||||
|
extension: format === "av1" ? "mp4" : "webm",
|
||||||
|
size: processedBuffer.length,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(`Error processing video: ${error.message}`);
|
||||||
|
throw new BadRequestException("Failed to process video");
|
||||||
|
} finally {
|
||||||
|
await unlink(tempInput).catch(() => {});
|
||||||
|
await unlink(tempOutput).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,10 +4,11 @@ import { CryptoModule } from "../crypto/crypto.module";
|
|||||||
import { DatabaseModule } from "../database/database.module";
|
import { DatabaseModule } from "../database/database.module";
|
||||||
import { ReportsController } from "./reports.controller";
|
import { ReportsController } from "./reports.controller";
|
||||||
import { ReportsService } from "./reports.service";
|
import { ReportsService } from "./reports.service";
|
||||||
|
import { ReportsRepository } from "./repositories/reports.repository";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DatabaseModule, AuthModule, CryptoModule],
|
imports: [DatabaseModule, AuthModule, CryptoModule],
|
||||||
controllers: [ReportsController],
|
controllers: [ReportsController],
|
||||||
providers: [ReportsService],
|
providers: [ReportsService, ReportsRepository],
|
||||||
})
|
})
|
||||||
export class ReportsModule {}
|
export class ReportsModule {}
|
||||||
|
|||||||
@@ -1,56 +1,29 @@
|
|||||||
import { Test, TestingModule } from "@nestjs/testing";
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
import { DatabaseService } from "../database/database.service";
|
|
||||||
import { CreateReportDto } from "./dto/create-report.dto";
|
|
||||||
import { ReportsService } from "./reports.service";
|
import { ReportsService } from "./reports.service";
|
||||||
|
import { ReportsRepository } from "./repositories/reports.repository";
|
||||||
|
|
||||||
describe("ReportsService", () => {
|
describe("ReportsService", () => {
|
||||||
let service: ReportsService;
|
let service: ReportsService;
|
||||||
|
let repository: ReportsRepository;
|
||||||
|
|
||||||
const mockDb = {
|
const mockReportsRepository = {
|
||||||
insert: jest.fn(),
|
create: jest.fn(),
|
||||||
values: jest.fn(),
|
findAll: jest.fn(),
|
||||||
returning: jest.fn(),
|
updateStatus: jest.fn(),
|
||||||
select: jest.fn(),
|
|
||||||
from: jest.fn(),
|
|
||||||
orderBy: jest.fn(),
|
|
||||||
limit: jest.fn(),
|
|
||||||
offset: jest.fn(),
|
|
||||||
update: jest.fn(),
|
|
||||||
set: jest.fn(),
|
|
||||||
where: jest.fn(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
|
|
||||||
const chain = {
|
|
||||||
insert: jest.fn().mockReturnThis(),
|
|
||||||
values: jest.fn().mockReturnThis(),
|
|
||||||
returning: jest.fn().mockReturnThis(),
|
|
||||||
select: jest.fn().mockReturnThis(),
|
|
||||||
from: jest.fn().mockReturnThis(),
|
|
||||||
orderBy: jest.fn().mockReturnThis(),
|
|
||||||
limit: jest.fn().mockReturnThis(),
|
|
||||||
offset: jest.fn().mockReturnThis(),
|
|
||||||
update: jest.fn().mockReturnThis(),
|
|
||||||
set: jest.fn().mockReturnThis(),
|
|
||||||
where: jest.fn().mockReturnThis(),
|
|
||||||
};
|
|
||||||
|
|
||||||
const mockImplementation = () => Object.assign(Promise.resolve([]), chain);
|
|
||||||
for (const mock of Object.values(chain)) {
|
|
||||||
mock.mockImplementation(mockImplementation);
|
|
||||||
}
|
|
||||||
Object.assign(mockDb, chain);
|
|
||||||
|
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
ReportsService,
|
ReportsService,
|
||||||
{ provide: DatabaseService, useValue: { db: mockDb } },
|
{ provide: ReportsRepository, useValue: mockReportsRepository },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
service = module.get<ReportsService>(ReportsService);
|
service = module.get<ReportsService>(ReportsService);
|
||||||
|
repository = module.get<ReportsRepository>(ReportsRepository);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should be defined", () => {
|
it("should be defined", () => {
|
||||||
@@ -60,29 +33,31 @@ describe("ReportsService", () => {
|
|||||||
describe("create", () => {
|
describe("create", () => {
|
||||||
it("should create a report", async () => {
|
it("should create a report", async () => {
|
||||||
const reporterId = "u1";
|
const reporterId = "u1";
|
||||||
const data: CreateReportDto = { contentId: "c1", reason: "spam" };
|
const data = { contentId: "c1", reason: "spam" };
|
||||||
mockDb.returning.mockResolvedValue([{ id: "r1", ...data, reporterId }]);
|
mockReportsRepository.create.mockResolvedValue({ id: "r1", ...data, reporterId });
|
||||||
|
|
||||||
const result = await service.create(reporterId, data);
|
const result = await service.create(reporterId, data);
|
||||||
|
|
||||||
expect(result.id).toBe("r1");
|
expect(result.id).toBe("r1");
|
||||||
expect(mockDb.insert).toHaveBeenCalled();
|
expect(repository.create).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("findAll", () => {
|
describe("findAll", () => {
|
||||||
it("should return reports", async () => {
|
it("should return reports", async () => {
|
||||||
mockDb.offset.mockResolvedValue([{ id: "r1" }]);
|
mockReportsRepository.findAll.mockResolvedValue([{ id: "r1" }]);
|
||||||
const result = await service.findAll(10, 0);
|
const result = await service.findAll(10, 0);
|
||||||
expect(result).toHaveLength(1);
|
expect(result).toHaveLength(1);
|
||||||
|
expect(repository.findAll).toHaveBeenCalledWith(10, 0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("updateStatus", () => {
|
describe("updateStatus", () => {
|
||||||
it("should update report status", async () => {
|
it("should update report status", async () => {
|
||||||
mockDb.returning.mockResolvedValue([{ id: "r1", status: "resolved" }]);
|
mockReportsRepository.updateStatus.mockResolvedValue([{ id: "r1", status: "resolved" }]);
|
||||||
const result = await service.updateStatus("r1", "resolved");
|
const result = await service.updateStatus("r1", "resolved");
|
||||||
expect(result[0].status).toBe("resolved");
|
expect(result[0].status).toBe("resolved");
|
||||||
|
expect(repository.updateStatus).toHaveBeenCalledWith("r1", "resolved");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,37 +1,26 @@
|
|||||||
import { Injectable, Logger } from "@nestjs/common";
|
import { Injectable, Logger } from "@nestjs/common";
|
||||||
import { desc, eq } from "drizzle-orm";
|
import { ReportsRepository } from "./repositories/reports.repository";
|
||||||
import { DatabaseService } from "../database/database.service";
|
|
||||||
import { reports } from "../database/schemas";
|
|
||||||
import { CreateReportDto } from "./dto/create-report.dto";
|
import { CreateReportDto } from "./dto/create-report.dto";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ReportsService {
|
export class ReportsService {
|
||||||
private readonly logger = new Logger(ReportsService.name);
|
private readonly logger = new Logger(ReportsService.name);
|
||||||
|
|
||||||
constructor(private readonly databaseService: DatabaseService) {}
|
constructor(private readonly reportsRepository: ReportsRepository) {}
|
||||||
|
|
||||||
async create(reporterId: string, data: CreateReportDto) {
|
async create(reporterId: string, data: CreateReportDto) {
|
||||||
this.logger.log(`Creating report from user ${reporterId}`);
|
this.logger.log(`Creating report from user ${reporterId}`);
|
||||||
const [newReport] = await this.databaseService.db
|
return await this.reportsRepository.create({
|
||||||
.insert(reports)
|
reporterId,
|
||||||
.values({
|
contentId: data.contentId,
|
||||||
reporterId,
|
tagId: data.tagId,
|
||||||
contentId: data.contentId,
|
reason: data.reason,
|
||||||
tagId: data.tagId,
|
description: data.description,
|
||||||
reason: data.reason,
|
});
|
||||||
description: data.description,
|
|
||||||
})
|
|
||||||
.returning();
|
|
||||||
return newReport;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async findAll(limit: number, offset: number) {
|
async findAll(limit: number, offset: number) {
|
||||||
return await this.databaseService.db
|
return await this.reportsRepository.findAll(limit, offset);
|
||||||
.select()
|
|
||||||
.from(reports)
|
|
||||||
.orderBy(desc(reports.createdAt))
|
|
||||||
.limit(limit)
|
|
||||||
.offset(offset);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateStatus(
|
async updateStatus(
|
||||||
@@ -39,10 +28,6 @@ export class ReportsService {
|
|||||||
status: "pending" | "reviewed" | "resolved" | "dismissed",
|
status: "pending" | "reviewed" | "resolved" | "dismissed",
|
||||||
) {
|
) {
|
||||||
this.logger.log(`Updating report ${id} status to ${status}`);
|
this.logger.log(`Updating report ${id} status to ${status}`);
|
||||||
return await this.databaseService.db
|
return await this.reportsRepository.updateStatus(id, status);
|
||||||
.update(reports)
|
|
||||||
.set({ status, updatedAt: new Date() })
|
|
||||||
.where(eq(reports.id, id))
|
|
||||||
.returning();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
50
backend/src/reports/repositories/reports.repository.ts
Normal file
50
backend/src/reports/repositories/reports.repository.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { desc, eq, lte } from "drizzle-orm";
|
||||||
|
import { DatabaseService } from "../../database/database.service";
|
||||||
|
import { reports } from "../../database/schemas";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ReportsRepository {
|
||||||
|
constructor(private readonly databaseService: DatabaseService) {}
|
||||||
|
|
||||||
|
async create(data: {
|
||||||
|
reporterId: string;
|
||||||
|
contentId?: string;
|
||||||
|
tagId?: string;
|
||||||
|
reason: string;
|
||||||
|
description?: string;
|
||||||
|
}) {
|
||||||
|
const [newReport] = await this.databaseService.db
|
||||||
|
.insert(reports)
|
||||||
|
.values(data)
|
||||||
|
.returning();
|
||||||
|
return newReport;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAll(limit: number, offset: number) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(reports)
|
||||||
|
.orderBy(desc(reports.createdAt))
|
||||||
|
.limit(limit)
|
||||||
|
.offset(offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateStatus(
|
||||||
|
id: string,
|
||||||
|
status: "pending" | "reviewed" | "resolved" | "dismissed",
|
||||||
|
) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.update(reports)
|
||||||
|
.set({ status, updatedAt: new Date() })
|
||||||
|
.where(eq(reports.id, id))
|
||||||
|
.returning();
|
||||||
|
}
|
||||||
|
|
||||||
|
async purgeObsolete(now: Date) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.delete(reports)
|
||||||
|
.where(lte(reports.expiresAt, now))
|
||||||
|
.returning();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
import { Injectable, Logger, OnModuleInit } from "@nestjs/common";
|
import { Injectable, Logger, OnModuleInit } from "@nestjs/common";
|
||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import * as Minio from "minio";
|
import * as Minio from "minio";
|
||||||
|
import type { IStorageService } from "../common/interfaces/storage.interface";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class S3Service implements OnModuleInit {
|
export class S3Service implements OnModuleInit, IStorageService {
|
||||||
private readonly logger = new Logger(S3Service.name);
|
private readonly logger = new Logger(S3Service.name);
|
||||||
private minioClient: Minio.Client;
|
private minioClient: Minio.Client;
|
||||||
private readonly bucketName: string;
|
private readonly bucketName: string;
|
||||||
|
|||||||
64
backend/src/sessions/repositories/sessions.repository.ts
Normal file
64
backend/src/sessions/repositories/sessions.repository.ts
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { and, eq, lte } from "drizzle-orm";
|
||||||
|
import { DatabaseService } from "../../database/database.service";
|
||||||
|
import { sessions } from "../../database/schemas";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SessionsRepository {
|
||||||
|
constructor(private readonly databaseService: DatabaseService) {}
|
||||||
|
|
||||||
|
async create(data: {
|
||||||
|
userId: string;
|
||||||
|
refreshToken: string;
|
||||||
|
userAgent?: string;
|
||||||
|
ipHash?: string | null;
|
||||||
|
expiresAt: Date;
|
||||||
|
}) {
|
||||||
|
const [session] = await this.databaseService.db
|
||||||
|
.insert(sessions)
|
||||||
|
.values(data)
|
||||||
|
.returning();
|
||||||
|
return session;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findValidByRefreshToken(refreshToken: string) {
|
||||||
|
const result = await this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(sessions)
|
||||||
|
.where(
|
||||||
|
and(eq(sessions.refreshToken, refreshToken), eq(sessions.isValid, true)),
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
return result[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(sessionId: string, data: any) {
|
||||||
|
const [updatedSession] = await this.databaseService.db
|
||||||
|
.update(sessions)
|
||||||
|
.set({ ...data, updatedAt: new Date() })
|
||||||
|
.where(eq(sessions.id, sessionId))
|
||||||
|
.returning();
|
||||||
|
return updatedSession;
|
||||||
|
}
|
||||||
|
|
||||||
|
async revoke(sessionId: string) {
|
||||||
|
await this.databaseService.db
|
||||||
|
.update(sessions)
|
||||||
|
.set({ isValid: false, updatedAt: new Date() })
|
||||||
|
.where(eq(sessions.id, sessionId));
|
||||||
|
}
|
||||||
|
|
||||||
|
async revokeAllByUserId(userId: string) {
|
||||||
|
await this.databaseService.db
|
||||||
|
.update(sessions)
|
||||||
|
.set({ isValid: false, updatedAt: new Date() })
|
||||||
|
.where(eq(sessions.userId, userId));
|
||||||
|
}
|
||||||
|
|
||||||
|
async purgeExpired(now: Date) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.delete(sessions)
|
||||||
|
.where(lte(sessions.expiresAt, now))
|
||||||
|
.returning();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,10 +2,11 @@ import { Module } from "@nestjs/common";
|
|||||||
import { CryptoModule } from "../crypto/crypto.module";
|
import { CryptoModule } from "../crypto/crypto.module";
|
||||||
import { DatabaseModule } from "../database/database.module";
|
import { DatabaseModule } from "../database/database.module";
|
||||||
import { SessionsService } from "./sessions.service";
|
import { SessionsService } from "./sessions.service";
|
||||||
|
import { SessionsRepository } from "./repositories/sessions.repository";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DatabaseModule, CryptoModule],
|
imports: [DatabaseModule, CryptoModule],
|
||||||
providers: [SessionsService],
|
providers: [SessionsService, SessionsRepository],
|
||||||
exports: [SessionsService],
|
exports: [SessionsService],
|
||||||
})
|
})
|
||||||
export class SessionsModule {}
|
export class SessionsModule {}
|
||||||
|
|||||||
@@ -13,60 +13,45 @@ jest.mock("jose", () => ({
|
|||||||
|
|
||||||
import { UnauthorizedException } from "@nestjs/common";
|
import { UnauthorizedException } from "@nestjs/common";
|
||||||
import { Test, TestingModule } from "@nestjs/testing";
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
import { CryptoService } from "../crypto/crypto.service";
|
import { HashingService } from "../crypto/services/hashing.service";
|
||||||
import { DatabaseService } from "../database/database.service";
|
import { JwtService } from "../crypto/services/jwt.service";
|
||||||
import { SessionsService } from "./sessions.service";
|
import { SessionsService } from "./sessions.service";
|
||||||
|
import { SessionsRepository } from "./repositories/sessions.repository";
|
||||||
|
|
||||||
describe("SessionsService", () => {
|
describe("SessionsService", () => {
|
||||||
let service: SessionsService;
|
let service: SessionsService;
|
||||||
|
let repository: SessionsRepository;
|
||||||
|
|
||||||
const mockDb = {
|
const mockSessionsRepository = {
|
||||||
insert: jest.fn(),
|
create: jest.fn(),
|
||||||
select: jest.fn(),
|
findValidByRefreshToken: jest.fn(),
|
||||||
update: jest.fn(),
|
update: jest.fn(),
|
||||||
|
revoke: jest.fn(),
|
||||||
|
revokeAllByUserId: jest.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const mockCryptoService = {
|
const mockHashingService = {
|
||||||
generateJwt: jest.fn().mockResolvedValue("mock-jwt"),
|
hashIp: jest.fn().mockResolvedValue("hashed-ip"),
|
||||||
hashIp: jest.fn().mockResolvedValue("mock-ip-hash"),
|
};
|
||||||
|
|
||||||
|
const mockJwtService = {
|
||||||
|
generateJwt: jest.fn().mockResolvedValue("new-token"),
|
||||||
};
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
|
|
||||||
const chain = {
|
|
||||||
insert: jest.fn().mockReturnThis(),
|
|
||||||
values: jest.fn().mockReturnThis(),
|
|
||||||
returning: jest.fn().mockReturnThis(),
|
|
||||||
select: jest.fn().mockReturnThis(),
|
|
||||||
from: jest.fn().mockReturnThis(),
|
|
||||||
where: jest.fn().mockReturnThis(),
|
|
||||||
limit: jest.fn().mockReturnThis(),
|
|
||||||
update: jest.fn().mockReturnThis(),
|
|
||||||
set: jest.fn().mockReturnThis(),
|
|
||||||
// biome-ignore lint/suspicious/noThenProperty: Fine for testing purposes
|
|
||||||
then: jest.fn().mockImplementation(function (cb) {
|
|
||||||
return Promise.resolve(this).then(cb);
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
|
|
||||||
const mockImplementation = () => Object.assign(Promise.resolve([]), chain);
|
|
||||||
for (const mock of Object.values(chain)) {
|
|
||||||
if (mock !== chain.then) {
|
|
||||||
mock.mockImplementation(mockImplementation);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Object.assign(mockDb, chain);
|
|
||||||
|
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
SessionsService,
|
SessionsService,
|
||||||
{ provide: DatabaseService, useValue: { db: mockDb } },
|
{ provide: SessionsRepository, useValue: mockSessionsRepository },
|
||||||
{ provide: CryptoService, useValue: mockCryptoService },
|
{ provide: HashingService, useValue: mockHashingService },
|
||||||
|
{ provide: JwtService, useValue: mockJwtService },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
service = module.get<SessionsService>(SessionsService);
|
service = module.get<SessionsService>(SessionsService);
|
||||||
|
repository = module.get<SessionsRepository>(SessionsRepository);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should be defined", () => {
|
it("should be defined", () => {
|
||||||
@@ -75,13 +60,10 @@ describe("SessionsService", () => {
|
|||||||
|
|
||||||
describe("createSession", () => {
|
describe("createSession", () => {
|
||||||
it("should create a session", async () => {
|
it("should create a session", async () => {
|
||||||
mockDb.returning.mockResolvedValue([{ id: "s1", refreshToken: "mock-jwt" }]);
|
mockSessionsRepository.create.mockResolvedValue({ id: "s1" });
|
||||||
const result = await service.createSession("u1", "agent", "1.2.3.4");
|
const result = await service.createSession("u1", "agent", "1.2.3.4");
|
||||||
expect(result.id).toBe("s1");
|
expect(result).toEqual({ id: "s1" });
|
||||||
expect(mockCryptoService.generateJwt).toHaveBeenCalledWith(
|
expect(repository.create).toHaveBeenCalled();
|
||||||
{ sub: "u1", type: "refresh" },
|
|
||||||
"7d",
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -89,36 +71,46 @@ describe("SessionsService", () => {
|
|||||||
it("should refresh a valid session", async () => {
|
it("should refresh a valid session", async () => {
|
||||||
const expiresAt = new Date();
|
const expiresAt = new Date();
|
||||||
expiresAt.setDate(expiresAt.getDate() + 1);
|
expiresAt.setDate(expiresAt.getDate() + 1);
|
||||||
const session = { id: "s1", userId: "u1", expiresAt, isValid: true };
|
mockSessionsRepository.findValidByRefreshToken.mockResolvedValue({
|
||||||
|
id: "s1",
|
||||||
mockDb.where.mockImplementation(() => {
|
userId: "u1",
|
||||||
const chain = {
|
expiresAt,
|
||||||
limit: jest.fn().mockReturnThis(),
|
|
||||||
returning: jest
|
|
||||||
.fn()
|
|
||||||
.mockResolvedValue([{ ...session, refreshToken: "new-jwt" }]),
|
|
||||||
// biome-ignore lint/suspicious/noThenProperty: Fine for testing purposes
|
|
||||||
then: jest.fn().mockResolvedValue(session),
|
|
||||||
};
|
|
||||||
return Object.assign(Promise.resolve([session]), chain);
|
|
||||||
});
|
});
|
||||||
|
mockSessionsRepository.update.mockResolvedValue({ id: "s1", refreshToken: "new-token" });
|
||||||
|
|
||||||
const result = await service.refreshSession("old-jwt");
|
const result = await service.refreshSession("old-token");
|
||||||
expect(result.refreshToken).toBe("new-jwt");
|
|
||||||
|
expect(result.refreshToken).toBe("new-token");
|
||||||
|
expect(repository.update).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should throw UnauthorizedException if session not found", async () => {
|
it("should throw if session not found", async () => {
|
||||||
mockDb.where.mockImplementation(() => {
|
mockSessionsRepository.findValidByRefreshToken.mockResolvedValue(null);
|
||||||
const chain = {
|
|
||||||
limit: jest.fn().mockReturnThis(),
|
|
||||||
// biome-ignore lint/suspicious/noThenProperty: Fine for testing purposes
|
|
||||||
then: jest.fn().mockResolvedValue(null),
|
|
||||||
};
|
|
||||||
return Object.assign(Promise.resolve([]), chain);
|
|
||||||
});
|
|
||||||
await expect(service.refreshSession("invalid")).rejects.toThrow(
|
await expect(service.refreshSession("invalid")).rejects.toThrow(
|
||||||
UnauthorizedException,
|
UnauthorizedException,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("should throw and revoke if session expired", async () => {
|
||||||
|
const expiresAt = new Date();
|
||||||
|
expiresAt.setDate(expiresAt.getDate() - 1);
|
||||||
|
mockSessionsRepository.findValidByRefreshToken.mockResolvedValue({
|
||||||
|
id: "s1",
|
||||||
|
userId: "u1",
|
||||||
|
expiresAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(service.refreshSession("expired")).rejects.toThrow(
|
||||||
|
UnauthorizedException,
|
||||||
|
);
|
||||||
|
expect(repository.revoke).toHaveBeenCalledWith("s1");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("revokeSession", () => {
|
||||||
|
it("should revoke a session", async () => {
|
||||||
|
await service.revokeSession("s1");
|
||||||
|
expect(repository.revoke).toHaveBeenCalledWith("s1");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,48 +1,36 @@
|
|||||||
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
||||||
import { and, eq } from "drizzle-orm";
|
import { HashingService } from "../crypto/services/hashing.service";
|
||||||
import { CryptoService } from "../crypto/crypto.service";
|
import { JwtService } from "../crypto/services/jwt.service";
|
||||||
import { DatabaseService } from "../database/database.service";
|
import { SessionsRepository } from "./repositories/sessions.repository";
|
||||||
import { sessions } from "../database/schemas";
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SessionsService {
|
export class SessionsService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly databaseService: DatabaseService,
|
private readonly sessionsRepository: SessionsRepository,
|
||||||
private readonly cryptoService: CryptoService,
|
private readonly hashingService: HashingService,
|
||||||
|
private readonly jwtService: JwtService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async createSession(userId: string, userAgent?: string, ip?: string) {
|
async createSession(userId: string, userAgent?: string, ip?: string) {
|
||||||
const refreshToken = await this.cryptoService.generateJwt(
|
const refreshToken = await this.jwtService.generateJwt(
|
||||||
{ sub: userId, type: "refresh" },
|
{ sub: userId, type: "refresh" },
|
||||||
"7d",
|
"7d",
|
||||||
);
|
);
|
||||||
const ipHash = ip ? await this.cryptoService.hashIp(ip) : null;
|
const ipHash = ip ? await this.hashingService.hashIp(ip) : null;
|
||||||
const expiresAt = new Date();
|
const expiresAt = new Date();
|
||||||
expiresAt.setDate(expiresAt.getDate() + 7);
|
expiresAt.setDate(expiresAt.getDate() + 7);
|
||||||
|
|
||||||
const [session] = await this.databaseService.db
|
return await this.sessionsRepository.create({
|
||||||
.insert(sessions)
|
userId,
|
||||||
.values({
|
refreshToken,
|
||||||
userId,
|
userAgent,
|
||||||
refreshToken,
|
ipHash,
|
||||||
userAgent,
|
expiresAt,
|
||||||
ipHash,
|
});
|
||||||
expiresAt,
|
|
||||||
})
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
return session;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async refreshSession(oldRefreshToken: string) {
|
async refreshSession(oldRefreshToken: string) {
|
||||||
const session = await this.databaseService.db
|
const session = await this.sessionsRepository.findValidByRefreshToken(oldRefreshToken);
|
||||||
.select()
|
|
||||||
.from(sessions)
|
|
||||||
.where(
|
|
||||||
and(eq(sessions.refreshToken, oldRefreshToken), eq(sessions.isValid, true)),
|
|
||||||
)
|
|
||||||
.limit(1)
|
|
||||||
.then((res) => res[0]);
|
|
||||||
|
|
||||||
if (!session || session.expiresAt < new Date()) {
|
if (!session || session.expiresAt < new Date()) {
|
||||||
if (session) {
|
if (session) {
|
||||||
@@ -52,37 +40,24 @@ export class SessionsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Rotation du refresh token
|
// Rotation du refresh token
|
||||||
const newRefreshToken = await this.cryptoService.generateJwt(
|
const newRefreshToken = await this.jwtService.generateJwt(
|
||||||
{ sub: session.userId, type: "refresh" },
|
{ sub: session.userId, type: "refresh" },
|
||||||
"7d",
|
"7d",
|
||||||
);
|
);
|
||||||
const expiresAt = new Date();
|
const expiresAt = new Date();
|
||||||
expiresAt.setDate(expiresAt.getDate() + 7);
|
expiresAt.setDate(expiresAt.getDate() + 7);
|
||||||
|
|
||||||
const [updatedSession] = await this.databaseService.db
|
return await this.sessionsRepository.update(session.id, {
|
||||||
.update(sessions)
|
refreshToken: newRefreshToken,
|
||||||
.set({
|
expiresAt,
|
||||||
refreshToken: newRefreshToken,
|
});
|
||||||
expiresAt,
|
|
||||||
updatedAt: new Date(),
|
|
||||||
})
|
|
||||||
.where(eq(sessions.id, session.id))
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
return updatedSession;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async revokeSession(sessionId: string) {
|
async revokeSession(sessionId: string) {
|
||||||
await this.databaseService.db
|
await this.sessionsRepository.revoke(sessionId);
|
||||||
.update(sessions)
|
|
||||||
.set({ isValid: false, updatedAt: new Date() })
|
|
||||||
.where(eq(sessions.id, sessionId));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async revokeAllUserSessions(userId: string) {
|
async revokeAllUserSessions(userId: string) {
|
||||||
await this.databaseService.db
|
await this.sessionsRepository.revokeAllByUserId(userId);
|
||||||
.update(sessions)
|
|
||||||
.set({ isValid: false, updatedAt: new Date() })
|
|
||||||
.where(eq(sessions.userId, userId));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
48
backend/src/tags/repositories/tags.repository.ts
Normal file
48
backend/src/tags/repositories/tags.repository.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { desc, eq, ilike, sql } from "drizzle-orm";
|
||||||
|
import { DatabaseService } from "../../database/database.service";
|
||||||
|
import { contentsToTags, tags } from "../../database/schemas";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TagsRepository {
|
||||||
|
constructor(private readonly databaseService: DatabaseService) {}
|
||||||
|
|
||||||
|
async findAll(options: {
|
||||||
|
limit: number;
|
||||||
|
offset: number;
|
||||||
|
query?: string;
|
||||||
|
sortBy?: "popular" | "recent";
|
||||||
|
}) {
|
||||||
|
const { limit, offset, query, sortBy } = options;
|
||||||
|
|
||||||
|
let whereClause = sql`1=1`;
|
||||||
|
if (query) {
|
||||||
|
whereClause = ilike(tags.name, `%${query}%`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sortBy === "popular") {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.select({
|
||||||
|
id: tags.id,
|
||||||
|
name: tags.name,
|
||||||
|
slug: tags.slug,
|
||||||
|
count: sql<number>`count(${contentsToTags.contentId})`.as("usage_count"),
|
||||||
|
})
|
||||||
|
.from(tags)
|
||||||
|
.leftJoin(contentsToTags, eq(tags.id, contentsToTags.tagId))
|
||||||
|
.where(whereClause)
|
||||||
|
.groupBy(tags.id)
|
||||||
|
.orderBy(desc(sql`usage_count`))
|
||||||
|
.limit(limit)
|
||||||
|
.offset(offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(tags)
|
||||||
|
.where(whereClause)
|
||||||
|
.orderBy(sortBy === "recent" ? desc(tags.createdAt) : desc(tags.name))
|
||||||
|
.limit(limit)
|
||||||
|
.offset(offset);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,11 +2,12 @@ import { Module } from "@nestjs/common";
|
|||||||
import { DatabaseModule } from "../database/database.module";
|
import { DatabaseModule } from "../database/database.module";
|
||||||
import { TagsController } from "./tags.controller";
|
import { TagsController } from "./tags.controller";
|
||||||
import { TagsService } from "./tags.service";
|
import { TagsService } from "./tags.service";
|
||||||
|
import { TagsRepository } from "./repositories/tags.repository";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DatabaseModule],
|
imports: [DatabaseModule],
|
||||||
controllers: [TagsController],
|
controllers: [TagsController],
|
||||||
providers: [TagsService],
|
providers: [TagsService, TagsRepository],
|
||||||
exports: [TagsService],
|
exports: [TagsService],
|
||||||
})
|
})
|
||||||
export class TagsModule {}
|
export class TagsModule {}
|
||||||
|
|||||||
@@ -1,49 +1,27 @@
|
|||||||
import { Test, TestingModule } from "@nestjs/testing";
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
import { DatabaseService } from "../database/database.service";
|
|
||||||
import { TagsService } from "./tags.service";
|
import { TagsService } from "./tags.service";
|
||||||
|
import { TagsRepository } from "./repositories/tags.repository";
|
||||||
|
|
||||||
describe("TagsService", () => {
|
describe("TagsService", () => {
|
||||||
let service: TagsService;
|
let service: TagsService;
|
||||||
|
let repository: TagsRepository;
|
||||||
|
|
||||||
const mockDb = {
|
const mockTagsRepository = {
|
||||||
select: jest.fn(),
|
findAll: jest.fn(),
|
||||||
from: jest.fn(),
|
|
||||||
leftJoin: jest.fn(),
|
|
||||||
where: jest.fn(),
|
|
||||||
groupBy: jest.fn(),
|
|
||||||
orderBy: jest.fn(),
|
|
||||||
limit: jest.fn(),
|
|
||||||
offset: jest.fn(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
|
|
||||||
const chain = {
|
|
||||||
select: jest.fn().mockReturnThis(),
|
|
||||||
from: jest.fn().mockReturnThis(),
|
|
||||||
leftJoin: jest.fn().mockReturnThis(),
|
|
||||||
where: jest.fn().mockReturnThis(),
|
|
||||||
groupBy: jest.fn().mockReturnThis(),
|
|
||||||
orderBy: jest.fn().mockReturnThis(),
|
|
||||||
limit: jest.fn().mockReturnThis(),
|
|
||||||
offset: jest.fn().mockReturnThis(),
|
|
||||||
};
|
|
||||||
|
|
||||||
const mockImplementation = () => Object.assign(Promise.resolve([]), chain);
|
|
||||||
for (const mock of Object.values(chain)) {
|
|
||||||
mock.mockImplementation(mockImplementation);
|
|
||||||
}
|
|
||||||
Object.assign(mockDb, chain);
|
|
||||||
|
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
TagsService,
|
TagsService,
|
||||||
{ provide: DatabaseService, useValue: { db: mockDb } },
|
{ provide: TagsRepository, useValue: mockTagsRepository },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
service = module.get<TagsService>(TagsService);
|
service = module.get<TagsService>(TagsService);
|
||||||
|
repository = module.get<TagsRepository>(TagsRepository);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should be defined", () => {
|
it("should be defined", () => {
|
||||||
@@ -53,24 +31,12 @@ describe("TagsService", () => {
|
|||||||
describe("findAll", () => {
|
describe("findAll", () => {
|
||||||
it("should return tags", async () => {
|
it("should return tags", async () => {
|
||||||
const mockTags = [{ id: "1", name: "tag1" }];
|
const mockTags = [{ id: "1", name: "tag1" }];
|
||||||
mockDb.offset.mockResolvedValue(mockTags);
|
mockTagsRepository.findAll.mockResolvedValue(mockTags);
|
||||||
|
|
||||||
const result = await service.findAll({ limit: 10, offset: 0 });
|
const result = await service.findAll({ limit: 10, offset: 0 });
|
||||||
|
|
||||||
expect(result).toEqual(mockTags);
|
expect(result).toEqual(mockTags);
|
||||||
expect(mockDb.select).toHaveBeenCalled();
|
expect(repository.findAll).toHaveBeenCalledWith({ limit: 10, offset: 0 });
|
||||||
});
|
|
||||||
|
|
||||||
it("should handle popular sort", async () => {
|
|
||||||
mockDb.offset.mockResolvedValue([{ id: "1", name: "tag1", count: 5 }]);
|
|
||||||
const result = await service.findAll({
|
|
||||||
limit: 10,
|
|
||||||
offset: 0,
|
|
||||||
sortBy: "popular",
|
|
||||||
});
|
|
||||||
expect(result[0].count).toBe(5);
|
|
||||||
expect(mockDb.leftJoin).toHaveBeenCalled();
|
|
||||||
expect(mockDb.groupBy).toHaveBeenCalled();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,13 +1,11 @@
|
|||||||
import { Injectable, Logger } from "@nestjs/common";
|
import { Injectable, Logger } from "@nestjs/common";
|
||||||
import { desc, eq, ilike, sql } from "drizzle-orm";
|
import { TagsRepository } from "./repositories/tags.repository";
|
||||||
import { DatabaseService } from "../database/database.service";
|
|
||||||
import { contentsToTags, tags } from "../database/schemas";
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TagsService {
|
export class TagsService {
|
||||||
private readonly logger = new Logger(TagsService.name);
|
private readonly logger = new Logger(TagsService.name);
|
||||||
|
|
||||||
constructor(private readonly databaseService: DatabaseService) {}
|
constructor(private readonly tagsRepository: TagsRepository) {}
|
||||||
|
|
||||||
async findAll(options: {
|
async findAll(options: {
|
||||||
limit: number;
|
limit: number;
|
||||||
@@ -16,41 +14,6 @@ export class TagsService {
|
|||||||
sortBy?: "popular" | "recent";
|
sortBy?: "popular" | "recent";
|
||||||
}) {
|
}) {
|
||||||
this.logger.log(`Fetching tags with options: ${JSON.stringify(options)}`);
|
this.logger.log(`Fetching tags with options: ${JSON.stringify(options)}`);
|
||||||
const { limit, offset, query, sortBy } = options;
|
return await this.tagsRepository.findAll(options);
|
||||||
|
|
||||||
let whereClause = sql`1=1`;
|
|
||||||
if (query) {
|
|
||||||
whereClause = ilike(tags.name, `%${query}%`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pour la popularité, on compte le nombre d'associations dans contentsToTags
|
|
||||||
if (sortBy === "popular") {
|
|
||||||
const data = await this.databaseService.db
|
|
||||||
.select({
|
|
||||||
id: tags.id,
|
|
||||||
name: tags.name,
|
|
||||||
slug: tags.slug,
|
|
||||||
count: sql<number>`count(${contentsToTags.contentId})`.as("usage_count"),
|
|
||||||
})
|
|
||||||
.from(tags)
|
|
||||||
.leftJoin(contentsToTags, eq(tags.id, contentsToTags.tagId))
|
|
||||||
.where(whereClause)
|
|
||||||
.groupBy(tags.id)
|
|
||||||
.orderBy(desc(sql`usage_count`))
|
|
||||||
.limit(limit)
|
|
||||||
.offset(offset);
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await this.databaseService.db
|
|
||||||
.select()
|
|
||||||
.from(tags)
|
|
||||||
.where(whereClause)
|
|
||||||
.orderBy(sortBy === "recent" ? desc(tags.createdAt) : desc(tags.name))
|
|
||||||
.limit(limit)
|
|
||||||
.offset(offset);
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
158
backend/src/users/repositories/users.repository.ts
Normal file
158
backend/src/users/repositories/users.repository.ts
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { and, eq, lte, sql } from "drizzle-orm";
|
||||||
|
import { DatabaseService } from "../../database/database.service";
|
||||||
|
import { users, contents, favorites } from "../../database/schemas";
|
||||||
|
import type { UpdateUserDto } from "../dto/update-user.dto";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class UsersRepository {
|
||||||
|
constructor(private readonly databaseService: DatabaseService) {}
|
||||||
|
|
||||||
|
async create(data: {
|
||||||
|
username: string;
|
||||||
|
email: string;
|
||||||
|
passwordHash: string;
|
||||||
|
emailHash: string;
|
||||||
|
}) {
|
||||||
|
const [newUser] = await this.databaseService.db
|
||||||
|
.insert(users)
|
||||||
|
.values(data)
|
||||||
|
.returning();
|
||||||
|
return newUser;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findByEmailHash(emailHash: string) {
|
||||||
|
const result = await this.databaseService.db
|
||||||
|
.select({
|
||||||
|
uuid: users.uuid,
|
||||||
|
username: users.username,
|
||||||
|
email: users.email,
|
||||||
|
passwordHash: users.passwordHash,
|
||||||
|
status: users.status,
|
||||||
|
isTwoFactorEnabled: users.isTwoFactorEnabled,
|
||||||
|
})
|
||||||
|
.from(users)
|
||||||
|
.where(eq(users.emailHash, emailHash))
|
||||||
|
.limit(1);
|
||||||
|
return result[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOneWithPrivateData(uuid: string) {
|
||||||
|
const result = await this.databaseService.db
|
||||||
|
.select({
|
||||||
|
uuid: users.uuid,
|
||||||
|
username: users.username,
|
||||||
|
email: users.email,
|
||||||
|
displayName: users.displayName,
|
||||||
|
status: users.status,
|
||||||
|
isTwoFactorEnabled: users.isTwoFactorEnabled,
|
||||||
|
createdAt: users.createdAt,
|
||||||
|
updatedAt: users.updatedAt,
|
||||||
|
})
|
||||||
|
.from(users)
|
||||||
|
.where(eq(users.uuid, uuid))
|
||||||
|
.limit(1);
|
||||||
|
return result[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async countAll() {
|
||||||
|
const result = await this.databaseService.db
|
||||||
|
.select({ count: sql<number>`count(*)` })
|
||||||
|
.from(users);
|
||||||
|
return Number(result[0].count);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAll(limit: number, offset: number) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.select({
|
||||||
|
uuid: users.uuid,
|
||||||
|
username: users.username,
|
||||||
|
displayName: users.displayName,
|
||||||
|
status: users.status,
|
||||||
|
createdAt: users.createdAt,
|
||||||
|
})
|
||||||
|
.from(users)
|
||||||
|
.limit(limit)
|
||||||
|
.offset(offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findByUsername(username: string) {
|
||||||
|
const result = await this.databaseService.db
|
||||||
|
.select({
|
||||||
|
uuid: users.uuid,
|
||||||
|
username: users.username,
|
||||||
|
displayName: users.displayName,
|
||||||
|
createdAt: users.createdAt,
|
||||||
|
})
|
||||||
|
.from(users)
|
||||||
|
.where(eq(users.username, username))
|
||||||
|
.limit(1);
|
||||||
|
return result[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(uuid: string) {
|
||||||
|
const result = await this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(users)
|
||||||
|
.where(eq(users.uuid, uuid))
|
||||||
|
.limit(1);
|
||||||
|
return result[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(uuid: string, data: any) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.update(users)
|
||||||
|
.set({ ...data, updatedAt: new Date() })
|
||||||
|
.where(eq(users.uuid, uuid))
|
||||||
|
.returning();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getTwoFactorSecret(uuid: string) {
|
||||||
|
const result = await this.databaseService.db
|
||||||
|
.select({
|
||||||
|
secret: users.twoFactorSecret,
|
||||||
|
})
|
||||||
|
.from(users)
|
||||||
|
.where(eq(users.uuid, uuid))
|
||||||
|
.limit(1);
|
||||||
|
return result[0]?.secret || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getUserContents(uuid: string) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(contents)
|
||||||
|
.where(eq(contents.userId, uuid));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getUserFavorites(uuid: string) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(favorites)
|
||||||
|
.where(eq(favorites.userId, uuid));
|
||||||
|
}
|
||||||
|
|
||||||
|
async softDeleteUserAndContents(uuid: string) {
|
||||||
|
return await this.databaseService.db.transaction(async (tx) => {
|
||||||
|
const userResult = await tx
|
||||||
|
.update(users)
|
||||||
|
.set({ status: "deleted", deletedAt: new Date() })
|
||||||
|
.where(eq(users.uuid, uuid))
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
await tx
|
||||||
|
.update(contents)
|
||||||
|
.set({ deletedAt: new Date() })
|
||||||
|
.where(eq(contents.userId, uuid));
|
||||||
|
|
||||||
|
return userResult;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async purgeDeleted(before: Date) {
|
||||||
|
return await this.databaseService.db
|
||||||
|
.delete(users)
|
||||||
|
.where(and(eq(users.status, "deleted"), lte(users.deletedAt, before)))
|
||||||
|
.returning();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,11 +4,12 @@ import { CryptoModule } from "../crypto/crypto.module";
|
|||||||
import { DatabaseModule } from "../database/database.module";
|
import { DatabaseModule } from "../database/database.module";
|
||||||
import { UsersController } from "./users.controller";
|
import { UsersController } from "./users.controller";
|
||||||
import { UsersService } from "./users.service";
|
import { UsersService } from "./users.service";
|
||||||
|
import { UsersRepository } from "./repositories/users.repository";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DatabaseModule, CryptoModule, AuthModule],
|
imports: [DatabaseModule, CryptoModule, AuthModule],
|
||||||
controllers: [UsersController],
|
controllers: [UsersController],
|
||||||
providers: [UsersService],
|
providers: [UsersService, UsersRepository],
|
||||||
exports: [UsersService],
|
exports: [UsersService],
|
||||||
})
|
})
|
||||||
export class UsersModule {}
|
export class UsersModule {}
|
||||||
|
|||||||
@@ -12,61 +12,46 @@ jest.mock("jose", () => ({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
import { Test, TestingModule } from "@nestjs/testing";
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
import { CryptoService } from "../crypto/crypto.service";
|
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
||||||
import { DatabaseService } from "../database/database.service";
|
|
||||||
import { UsersService } from "./users.service";
|
import { UsersService } from "./users.service";
|
||||||
|
import { UsersRepository } from "./repositories/users.repository";
|
||||||
|
|
||||||
describe("UsersService", () => {
|
describe("UsersService", () => {
|
||||||
let service: UsersService;
|
let service: UsersService;
|
||||||
|
let repository: UsersRepository;
|
||||||
|
|
||||||
const mockDb = {
|
const mockUsersRepository = {
|
||||||
insert: jest.fn(),
|
create: jest.fn(),
|
||||||
select: jest.fn(),
|
findOne: jest.fn(),
|
||||||
|
findByEmailHash: jest.fn(),
|
||||||
|
findOneWithPrivateData: jest.fn(),
|
||||||
|
countAll: jest.fn(),
|
||||||
|
findAll: jest.fn(),
|
||||||
|
findByUsername: jest.fn(),
|
||||||
update: jest.fn(),
|
update: jest.fn(),
|
||||||
transaction: jest.fn().mockImplementation((cb) => cb(mockDb)),
|
getTwoFactorSecret: jest.fn(),
|
||||||
|
getUserContents: jest.fn(),
|
||||||
|
getUserFavorites: jest.fn(),
|
||||||
|
softDeleteUserAndContents: jest.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const mockCryptoService = {
|
const mockCacheManager = {
|
||||||
getPgpEncryptionKey: jest.fn().mockReturnValue("mock-pgp-key"),
|
del: jest.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
|
|
||||||
const chain = {
|
|
||||||
insert: jest.fn().mockReturnThis(),
|
|
||||||
values: jest.fn().mockReturnThis(),
|
|
||||||
returning: jest.fn().mockReturnThis(),
|
|
||||||
select: jest.fn().mockReturnThis(),
|
|
||||||
from: jest.fn().mockReturnThis(),
|
|
||||||
where: jest.fn().mockReturnThis(),
|
|
||||||
limit: jest.fn().mockReturnThis(),
|
|
||||||
offset: jest.fn().mockReturnThis(),
|
|
||||||
update: jest.fn().mockReturnThis(),
|
|
||||||
set: jest.fn().mockReturnThis(),
|
|
||||||
// biome-ignore lint/suspicious/noThenProperty: Fine for testing purposes
|
|
||||||
then: jest.fn().mockImplementation(function (cb) {
|
|
||||||
return Promise.resolve(this).then(cb);
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
|
|
||||||
const mockImplementation = () => Object.assign(Promise.resolve([]), chain);
|
|
||||||
for (const mock of Object.values(chain)) {
|
|
||||||
if (mock !== chain.then) {
|
|
||||||
mock.mockImplementation(mockImplementation);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Object.assign(mockDb, chain);
|
|
||||||
|
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
UsersService,
|
UsersService,
|
||||||
{ provide: DatabaseService, useValue: { db: mockDb } },
|
{ provide: UsersRepository, useValue: mockUsersRepository },
|
||||||
{ provide: CryptoService, useValue: mockCryptoService },
|
{ provide: CACHE_MANAGER, useValue: mockCacheManager },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
service = module.get<UsersService>(UsersService);
|
service = module.get<UsersService>(UsersService);
|
||||||
|
repository = module.get<UsersRepository>(UsersRepository);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should be defined", () => {
|
it("should be defined", () => {
|
||||||
@@ -81,24 +66,24 @@ describe("UsersService", () => {
|
|||||||
passwordHash: "p1",
|
passwordHash: "p1",
|
||||||
emailHash: "eh1",
|
emailHash: "eh1",
|
||||||
};
|
};
|
||||||
mockDb.returning.mockResolvedValue([{ uuid: "uuid1", ...data }]);
|
mockUsersRepository.create.mockResolvedValue({ uuid: "uuid1", ...data });
|
||||||
|
|
||||||
const result = await service.create(data);
|
const result = await service.create(data);
|
||||||
|
|
||||||
expect(result.uuid).toBe("uuid1");
|
expect(result.uuid).toBe("uuid1");
|
||||||
expect(mockDb.insert).toHaveBeenCalled();
|
expect(repository.create).toHaveBeenCalledWith(data);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("findOne", () => {
|
describe("findOne", () => {
|
||||||
it("should find a user", async () => {
|
it("should find a user", async () => {
|
||||||
mockDb.limit.mockResolvedValue([{ uuid: "uuid1" }]);
|
mockUsersRepository.findOne.mockResolvedValue({ uuid: "uuid1" });
|
||||||
const result = await service.findOne("uuid1");
|
const result = await service.findOne("uuid1");
|
||||||
expect(result.uuid).toBe("uuid1");
|
expect(result.uuid).toBe("uuid1");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return null if not found", async () => {
|
it("should return null if not found", async () => {
|
||||||
mockDb.limit.mockResolvedValue([]);
|
mockUsersRepository.findOne.mockResolvedValue(null);
|
||||||
const result = await service.findOne("uuid1");
|
const result = await service.findOne("uuid1");
|
||||||
expect(result).toBeNull();
|
expect(result).toBeNull();
|
||||||
});
|
});
|
||||||
@@ -106,7 +91,7 @@ describe("UsersService", () => {
|
|||||||
|
|
||||||
describe("update", () => {
|
describe("update", () => {
|
||||||
it("should update a user", async () => {
|
it("should update a user", async () => {
|
||||||
mockDb.returning.mockResolvedValue([{ uuid: "uuid1", displayName: "New" }]);
|
mockUsersRepository.update.mockResolvedValue([{ uuid: "uuid1", displayName: "New" }]);
|
||||||
const result = await service.update("uuid1", { displayName: "New" });
|
const result = await service.update("uuid1", { displayName: "New" });
|
||||||
expect(result[0].displayName).toBe("New");
|
expect(result[0].displayName).toBe("New");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,14 +1,7 @@
|
|||||||
import { Injectable, Logger, Inject } from "@nestjs/common";
|
import { Injectable, Logger, Inject } from "@nestjs/common";
|
||||||
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
||||||
import { Cache } from "cache-manager";
|
import { Cache } from "cache-manager";
|
||||||
import { eq, sql } from "drizzle-orm";
|
import { UsersRepository } from "./repositories/users.repository";
|
||||||
import { CryptoService } from "../crypto/crypto.service";
|
|
||||||
import { DatabaseService } from "../database/database.service";
|
|
||||||
import {
|
|
||||||
contents,
|
|
||||||
favorites,
|
|
||||||
users,
|
|
||||||
} from "../database/schemas";
|
|
||||||
import { UpdateUserDto } from "./dto/update-user.dto";
|
import { UpdateUserDto } from "./dto/update-user.dto";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -16,8 +9,7 @@ export class UsersService {
|
|||||||
private readonly logger = new Logger(UsersService.name);
|
private readonly logger = new Logger(UsersService.name);
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly databaseService: DatabaseService,
|
private readonly usersRepository: UsersRepository,
|
||||||
private readonly cryptoService: CryptoService,
|
|
||||||
@Inject(CACHE_MANAGER) private cacheManager: Cache,
|
@Inject(CACHE_MANAGER) private cacheManager: Cache,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@@ -33,109 +25,37 @@ export class UsersService {
|
|||||||
passwordHash: string;
|
passwordHash: string;
|
||||||
emailHash: string;
|
emailHash: string;
|
||||||
}) {
|
}) {
|
||||||
const [newUser] = await this.databaseService.db
|
return await this.usersRepository.create(data);
|
||||||
.insert(users)
|
|
||||||
.values({
|
|
||||||
username: data.username,
|
|
||||||
email: data.email,
|
|
||||||
emailHash: data.emailHash,
|
|
||||||
passwordHash: data.passwordHash,
|
|
||||||
})
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
return newUser;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async findByEmailHash(emailHash: string) {
|
async findByEmailHash(emailHash: string) {
|
||||||
const result = await this.databaseService.db
|
return await this.usersRepository.findByEmailHash(emailHash);
|
||||||
.select({
|
|
||||||
uuid: users.uuid,
|
|
||||||
username: users.username,
|
|
||||||
email: users.email,
|
|
||||||
passwordHash: users.passwordHash,
|
|
||||||
status: users.status,
|
|
||||||
isTwoFactorEnabled: users.isTwoFactorEnabled,
|
|
||||||
})
|
|
||||||
.from(users)
|
|
||||||
.where(eq(users.emailHash, emailHash))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
return result[0] || null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async findOneWithPrivateData(uuid: string) {
|
async findOneWithPrivateData(uuid: string) {
|
||||||
const result = await this.databaseService.db
|
return await this.usersRepository.findOneWithPrivateData(uuid);
|
||||||
.select({
|
|
||||||
uuid: users.uuid,
|
|
||||||
username: users.username,
|
|
||||||
email: users.email,
|
|
||||||
displayName: users.displayName,
|
|
||||||
status: users.status,
|
|
||||||
isTwoFactorEnabled: users.isTwoFactorEnabled,
|
|
||||||
createdAt: users.createdAt,
|
|
||||||
updatedAt: users.updatedAt,
|
|
||||||
})
|
|
||||||
.from(users)
|
|
||||||
.where(eq(users.uuid, uuid))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
return result[0] || null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async findAll(limit: number, offset: number) {
|
async findAll(limit: number, offset: number) {
|
||||||
const totalCountResult = await this.databaseService.db
|
const [data, totalCount] = await Promise.all([
|
||||||
.select({ count: sql<number>`count(*)` })
|
this.usersRepository.findAll(limit, offset),
|
||||||
.from(users);
|
this.usersRepository.countAll(),
|
||||||
|
]);
|
||||||
const totalCount = Number(totalCountResult[0].count);
|
|
||||||
|
|
||||||
const data = await this.databaseService.db
|
|
||||||
.select({
|
|
||||||
uuid: users.uuid,
|
|
||||||
username: users.username,
|
|
||||||
displayName: users.displayName,
|
|
||||||
status: users.status,
|
|
||||||
createdAt: users.createdAt,
|
|
||||||
})
|
|
||||||
.from(users)
|
|
||||||
.limit(limit)
|
|
||||||
.offset(offset);
|
|
||||||
|
|
||||||
return { data, totalCount };
|
return { data, totalCount };
|
||||||
}
|
}
|
||||||
|
|
||||||
async findPublicProfile(username: string) {
|
async findPublicProfile(username: string) {
|
||||||
const result = await this.databaseService.db
|
return await this.usersRepository.findByUsername(username);
|
||||||
.select({
|
|
||||||
uuid: users.uuid,
|
|
||||||
username: users.username,
|
|
||||||
displayName: users.displayName,
|
|
||||||
createdAt: users.createdAt,
|
|
||||||
})
|
|
||||||
.from(users)
|
|
||||||
.where(eq(users.username, username))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
return result[0] || null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async findOne(uuid: string) {
|
async findOne(uuid: string) {
|
||||||
const result = await this.databaseService.db
|
return await this.usersRepository.findOne(uuid);
|
||||||
.select()
|
|
||||||
.from(users)
|
|
||||||
.where(eq(users.uuid, uuid))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
return result[0] || null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async update(uuid: string, data: UpdateUserDto) {
|
async update(uuid: string, data: UpdateUserDto) {
|
||||||
this.logger.log(`Updating user profile for ${uuid}`);
|
this.logger.log(`Updating user profile for ${uuid}`);
|
||||||
const result = await this.databaseService.db
|
const result = await this.usersRepository.update(uuid, data);
|
||||||
.update(users)
|
|
||||||
.set({ ...data, updatedAt: new Date() })
|
|
||||||
.where(eq(users.uuid, uuid))
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
if (result[0]) {
|
if (result[0]) {
|
||||||
await this.clearUserCache(result[0].username);
|
await this.clearUserCache(result[0].username);
|
||||||
@@ -148,65 +68,37 @@ export class UsersService {
|
|||||||
termsVersion: string,
|
termsVersion: string,
|
||||||
privacyVersion: string,
|
privacyVersion: string,
|
||||||
) {
|
) {
|
||||||
return await this.databaseService.db
|
return await this.usersRepository.update(uuid, {
|
||||||
.update(users)
|
termsVersion,
|
||||||
.set({
|
privacyVersion,
|
||||||
termsVersion,
|
gdprAcceptedAt: new Date(),
|
||||||
privacyVersion,
|
});
|
||||||
gdprAcceptedAt: new Date(),
|
|
||||||
updatedAt: new Date(),
|
|
||||||
})
|
|
||||||
.where(eq(users.uuid, uuid))
|
|
||||||
.returning();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async setTwoFactorSecret(uuid: string, secret: string) {
|
async setTwoFactorSecret(uuid: string, secret: string) {
|
||||||
return await this.databaseService.db
|
return await this.usersRepository.update(uuid, {
|
||||||
.update(users)
|
twoFactorSecret: secret,
|
||||||
.set({
|
});
|
||||||
twoFactorSecret: secret,
|
|
||||||
updatedAt: new Date(),
|
|
||||||
})
|
|
||||||
.where(eq(users.uuid, uuid))
|
|
||||||
.returning();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async toggleTwoFactor(uuid: string, enabled: boolean) {
|
async toggleTwoFactor(uuid: string, enabled: boolean) {
|
||||||
return await this.databaseService.db
|
return await this.usersRepository.update(uuid, {
|
||||||
.update(users)
|
isTwoFactorEnabled: enabled,
|
||||||
.set({
|
});
|
||||||
isTwoFactorEnabled: enabled,
|
|
||||||
updatedAt: new Date(),
|
|
||||||
})
|
|
||||||
.where(eq(users.uuid, uuid))
|
|
||||||
.returning();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async getTwoFactorSecret(uuid: string): Promise<string | null> {
|
async getTwoFactorSecret(uuid: string): Promise<string | null> {
|
||||||
const result = await this.databaseService.db
|
return await this.usersRepository.getTwoFactorSecret(uuid);
|
||||||
.select({
|
|
||||||
secret: users.twoFactorSecret,
|
|
||||||
})
|
|
||||||
.from(users)
|
|
||||||
.where(eq(users.uuid, uuid))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
return result[0]?.secret || null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async exportUserData(uuid: string) {
|
async exportUserData(uuid: string) {
|
||||||
const user = await this.findOneWithPrivateData(uuid);
|
const user = await this.findOneWithPrivateData(uuid);
|
||||||
if (!user) return null;
|
if (!user) return null;
|
||||||
|
|
||||||
const userContents = await this.databaseService.db
|
const [userContents, userFavorites] = await Promise.all([
|
||||||
.select()
|
this.usersRepository.getUserContents(uuid),
|
||||||
.from(contents)
|
this.usersRepository.getUserFavorites(uuid),
|
||||||
.where(eq(contents.userId, uuid));
|
]);
|
||||||
|
|
||||||
const userFavorites = await this.databaseService.db
|
|
||||||
.select()
|
|
||||||
.from(favorites)
|
|
||||||
.where(eq(favorites.userId, uuid));
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
profile: user,
|
profile: user,
|
||||||
@@ -217,21 +109,6 @@ export class UsersService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async remove(uuid: string) {
|
async remove(uuid: string) {
|
||||||
return await this.databaseService.db.transaction(async (tx) => {
|
return await this.usersRepository.softDeleteUserAndContents(uuid);
|
||||||
// Soft delete de l'utilisateur
|
|
||||||
const userResult = await tx
|
|
||||||
.update(users)
|
|
||||||
.set({ status: "deleted", deletedAt: new Date() })
|
|
||||||
.where(eq(users.uuid, uuid))
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
// Soft delete de tous ses contenus
|
|
||||||
await tx
|
|
||||||
.update(contents)
|
|
||||||
.set({ deletedAt: new Date() })
|
|
||||||
.where(eq(contents.userId, uuid));
|
|
||||||
|
|
||||||
return userResult;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
3
backend/test/__mocks__/cuid2.js
Normal file
3
backend/test/__mocks__/cuid2.js
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module.exports = {
|
||||||
|
createCuid: () => () => 'mocked-cuid',
|
||||||
|
};
|
||||||
13
backend/test/__mocks__/jose.js
Normal file
13
backend/test/__mocks__/jose.js
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
module.exports = {
|
||||||
|
SignJWT: class {
|
||||||
|
constructor() { return this; }
|
||||||
|
setProtectedHeader() { return this; }
|
||||||
|
setIssuedAt() { return this; }
|
||||||
|
setExpirationTime() { return this; }
|
||||||
|
sign() { return Promise.resolve('mocked-token'); }
|
||||||
|
},
|
||||||
|
jwtVerify: () => Promise.resolve({ payload: { sub: 'mocked-user' } }),
|
||||||
|
importJWK: () => Promise.resolve({}),
|
||||||
|
exportJWK: () => Promise.resolve({}),
|
||||||
|
generateKeyPair: () => Promise.resolve({ publicKey: {}, privateKey: {} }),
|
||||||
|
};
|
||||||
7
backend/test/__mocks__/ml-kem.js
Normal file
7
backend/test/__mocks__/ml-kem.js
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
module.exports = {
|
||||||
|
ml_kem768: {
|
||||||
|
keygen: () => ({ publicKey: Buffer.alloc(1184), secretKey: Buffer.alloc(2400) }),
|
||||||
|
encapsulate: () => ({ cipherText: Buffer.alloc(1088), sharedSecret: Buffer.alloc(32) }),
|
||||||
|
decapsulate: () => Buffer.alloc(32),
|
||||||
|
}
|
||||||
|
};
|
||||||
5
backend/test/__mocks__/sha3.js
Normal file
5
backend/test/__mocks__/sha3.js
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
module.exports = {
|
||||||
|
sha3_256: () => ({ update: () => ({ digest: () => Buffer.alloc(32) }) }),
|
||||||
|
sha3_512: () => ({ update: () => ({ digest: () => Buffer.alloc(64) }) }),
|
||||||
|
shake256: () => ({ update: () => ({ digest: () => Buffer.alloc(32) }) }),
|
||||||
|
};
|
||||||
22
frontend/components.json
Normal file
22
frontend/components.json
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://ui.shadcn.com/schema.json",
|
||||||
|
"style": "new-york",
|
||||||
|
"rsc": true,
|
||||||
|
"tsx": true,
|
||||||
|
"tailwind": {
|
||||||
|
"config": "",
|
||||||
|
"css": "src/app/globals.css",
|
||||||
|
"baseColor": "stone",
|
||||||
|
"cssVariables": true,
|
||||||
|
"prefix": ""
|
||||||
|
},
|
||||||
|
"iconLibrary": "lucide",
|
||||||
|
"aliases": {
|
||||||
|
"components": "@/components",
|
||||||
|
"utils": "@/lib/utils",
|
||||||
|
"ui": "@/components/ui",
|
||||||
|
"lib": "@/lib",
|
||||||
|
"hooks": "@/hooks"
|
||||||
|
},
|
||||||
|
"registries": {}
|
||||||
|
}
|
||||||
@@ -10,9 +10,52 @@
|
|||||||
"format": "biome format --write"
|
"format": "biome format --write"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@hookform/resolvers": "^5.2.2",
|
||||||
|
"@radix-ui/react-accordion": "^1.2.12",
|
||||||
|
"@radix-ui/react-alert-dialog": "^1.1.15",
|
||||||
|
"@radix-ui/react-aspect-ratio": "^1.1.8",
|
||||||
|
"@radix-ui/react-avatar": "^1.1.11",
|
||||||
|
"@radix-ui/react-checkbox": "^1.3.3",
|
||||||
|
"@radix-ui/react-collapsible": "^1.1.12",
|
||||||
|
"@radix-ui/react-context-menu": "^2.2.16",
|
||||||
|
"@radix-ui/react-dialog": "^1.1.15",
|
||||||
|
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||||
|
"@radix-ui/react-hover-card": "^1.1.15",
|
||||||
|
"@radix-ui/react-label": "^2.1.8",
|
||||||
|
"@radix-ui/react-menubar": "^1.1.16",
|
||||||
|
"@radix-ui/react-navigation-menu": "^1.2.14",
|
||||||
|
"@radix-ui/react-popover": "^1.1.15",
|
||||||
|
"@radix-ui/react-progress": "^1.1.8",
|
||||||
|
"@radix-ui/react-radio-group": "^1.3.8",
|
||||||
|
"@radix-ui/react-scroll-area": "^1.2.10",
|
||||||
|
"@radix-ui/react-select": "^2.2.6",
|
||||||
|
"@radix-ui/react-separator": "^1.1.8",
|
||||||
|
"@radix-ui/react-slider": "^1.3.6",
|
||||||
|
"@radix-ui/react-slot": "^1.2.4",
|
||||||
|
"@radix-ui/react-switch": "^1.2.6",
|
||||||
|
"@radix-ui/react-tabs": "^1.1.13",
|
||||||
|
"@radix-ui/react-toggle": "^1.1.10",
|
||||||
|
"@radix-ui/react-toggle-group": "^1.1.11",
|
||||||
|
"@radix-ui/react-tooltip": "^1.2.8",
|
||||||
|
"class-variance-authority": "^0.7.1",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
|
"cmdk": "^1.1.1",
|
||||||
|
"date-fns": "^4.1.0",
|
||||||
|
"embla-carousel-react": "^8.6.0",
|
||||||
|
"input-otp": "^1.4.2",
|
||||||
|
"lucide-react": "^0.562.0",
|
||||||
"next": "16.1.1",
|
"next": "16.1.1",
|
||||||
|
"next-themes": "^0.4.6",
|
||||||
"react": "19.2.3",
|
"react": "19.2.3",
|
||||||
"react-dom": "19.2.3"
|
"react-day-picker": "^9.13.0",
|
||||||
|
"react-dom": "19.2.3",
|
||||||
|
"react-hook-form": "^7.71.1",
|
||||||
|
"react-resizable-panels": "^4.4.1",
|
||||||
|
"recharts": "2.15.4",
|
||||||
|
"sonner": "^2.0.7",
|
||||||
|
"tailwind-merge": "^3.4.0",
|
||||||
|
"vaul": "^1.1.2",
|
||||||
|
"zod": "^4.3.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@biomejs/biome": "2.3.11",
|
"@biomejs/biome": "2.3.11",
|
||||||
@@ -22,6 +65,7 @@
|
|||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
"babel-plugin-react-compiler": "1.0.0",
|
"babel-plugin-react-compiler": "1.0.0",
|
||||||
"tailwindcss": "^4",
|
"tailwindcss": "^4",
|
||||||
|
"tw-animate-css": "^1.4.0",
|
||||||
"typescript": "^5"
|
"typescript": "^5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,26 +1,193 @@
|
|||||||
@import "tailwindcss";
|
@import "tailwindcss";
|
||||||
|
@import "tw-animate-css";
|
||||||
|
|
||||||
:root {
|
@custom-variant dark (&:is(.dark *));
|
||||||
--background: #ffffff;
|
|
||||||
--foreground: #171717;
|
|
||||||
}
|
|
||||||
|
|
||||||
@theme inline {
|
@theme inline {
|
||||||
--color-background: var(--background);
|
--color-background: var(--background);
|
||||||
--color-foreground: var(--foreground);
|
--color-foreground: var(--foreground);
|
||||||
--font-sans: var(--font-geist-sans);
|
--font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
|
||||||
--font-mono: var(--font-geist-mono);
|
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||||
|
--color-sidebar-ring: var(--sidebar-ring);
|
||||||
|
--color-sidebar-border: var(--sidebar-border);
|
||||||
|
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||||
|
--color-sidebar-accent: var(--sidebar-accent);
|
||||||
|
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||||
|
--color-sidebar-primary: var(--sidebar-primary);
|
||||||
|
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||||
|
--color-sidebar: var(--sidebar);
|
||||||
|
--color-chart-5: var(--chart-5);
|
||||||
|
--color-chart-4: var(--chart-4);
|
||||||
|
--color-chart-3: var(--chart-3);
|
||||||
|
--color-chart-2: var(--chart-2);
|
||||||
|
--color-chart-1: var(--chart-1);
|
||||||
|
--color-ring: var(--ring);
|
||||||
|
--color-input: var(--input);
|
||||||
|
--color-border: var(--border);
|
||||||
|
--color-destructive: var(--destructive);
|
||||||
|
--color-accent-foreground: var(--accent-foreground);
|
||||||
|
--color-accent: var(--accent);
|
||||||
|
--color-muted-foreground: var(--muted-foreground);
|
||||||
|
--color-muted: var(--muted);
|
||||||
|
--color-secondary-foreground: var(--secondary-foreground);
|
||||||
|
--color-secondary: var(--secondary);
|
||||||
|
--color-primary-foreground: var(--primary-foreground);
|
||||||
|
--color-primary: var(--primary);
|
||||||
|
--color-popover-foreground: var(--popover-foreground);
|
||||||
|
--color-popover: var(--popover);
|
||||||
|
--color-card-foreground: var(--card-foreground);
|
||||||
|
--color-card: var(--card);
|
||||||
|
--radius-sm: calc(var(--radius) - 4px);
|
||||||
|
--radius-md: calc(var(--radius) - 2px);
|
||||||
|
--radius-lg: var(--radius);
|
||||||
|
--radius-xl: calc(var(--radius) + 4px);
|
||||||
|
--radius-2xl: calc(var(--radius) + 8px);
|
||||||
|
--radius-3xl: calc(var(--radius) + 12px);
|
||||||
|
--radius-4xl: calc(var(--radius) + 16px);
|
||||||
|
--font-serif: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;
|
||||||
|
--radius: 0.5rem;
|
||||||
|
--tracking-tighter: calc(var(--tracking-normal) - 0.05em);
|
||||||
|
--tracking-tight: calc(var(--tracking-normal) - 0.025em);
|
||||||
|
--tracking-wide: calc(var(--tracking-normal) + 0.025em);
|
||||||
|
--tracking-wider: calc(var(--tracking-normal) + 0.05em);
|
||||||
|
--tracking-widest: calc(var(--tracking-normal) + 0.1em);
|
||||||
|
--tracking-normal: var(--tracking-normal);
|
||||||
|
--shadow-2xl: var(--shadow-2xl);
|
||||||
|
--shadow-xl: var(--shadow-xl);
|
||||||
|
--shadow-lg: var(--shadow-lg);
|
||||||
|
--shadow-md: var(--shadow-md);
|
||||||
|
--shadow: var(--shadow);
|
||||||
|
--shadow-sm: var(--shadow-sm);
|
||||||
|
--shadow-xs: var(--shadow-xs);
|
||||||
|
--shadow-2xs: var(--shadow-2xs);
|
||||||
|
--spacing: var(--spacing);
|
||||||
|
--letter-spacing: var(--letter-spacing);
|
||||||
|
--shadow-offset-y: var(--shadow-offset-y);
|
||||||
|
--shadow-offset-x: var(--shadow-offset-x);
|
||||||
|
--shadow-spread: var(--shadow-spread);
|
||||||
|
--shadow-blur: var(--shadow-blur);
|
||||||
|
--shadow-opacity: var(--shadow-opacity);
|
||||||
|
--color-shadow-color: var(--shadow-color);
|
||||||
|
--color-destructive-foreground: var(--destructive-foreground);
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
:root {
|
||||||
:root {
|
--radius: 0.5rem;
|
||||||
--background: #0a0a0a;
|
--background: oklch(0.9821 0 0);
|
||||||
--foreground: #ededed;
|
--foreground: oklch(0.2435 0 0);
|
||||||
|
--card: oklch(0.9911 0 0);
|
||||||
|
--card-foreground: oklch(0.2435 0 0);
|
||||||
|
--popover: oklch(0.9911 0 0);
|
||||||
|
--popover-foreground: oklch(0.2435 0 0);
|
||||||
|
--primary: oklch(0.4341 0.0392 41.9938);
|
||||||
|
--primary-foreground: oklch(1.0000 0 0);
|
||||||
|
--secondary: oklch(0.9200 0.0651 74.3695);
|
||||||
|
--secondary-foreground: oklch(0.3499 0.0685 40.8288);
|
||||||
|
--muted: oklch(0.9521 0 0);
|
||||||
|
--muted-foreground: oklch(0.5032 0 0);
|
||||||
|
--accent: oklch(0.9310 0 0);
|
||||||
|
--accent-foreground: oklch(0.2435 0 0);
|
||||||
|
--destructive: oklch(0.6271 0.1936 33.3390);
|
||||||
|
--border: oklch(0.8822 0 0);
|
||||||
|
--input: oklch(0.8822 0 0);
|
||||||
|
--ring: oklch(0.4341 0.0392 41.9938);
|
||||||
|
--chart-1: oklch(0.4341 0.0392 41.9938);
|
||||||
|
--chart-2: oklch(0.9200 0.0651 74.3695);
|
||||||
|
--chart-3: oklch(0.9310 0 0);
|
||||||
|
--chart-4: oklch(0.9367 0.0523 75.5009);
|
||||||
|
--chart-5: oklch(0.4338 0.0437 41.6746);
|
||||||
|
--sidebar: oklch(0.9881 0 0);
|
||||||
|
--sidebar-foreground: oklch(0.2645 0 0);
|
||||||
|
--sidebar-primary: oklch(0.3250 0 0);
|
||||||
|
--sidebar-primary-foreground: oklch(0.9881 0 0);
|
||||||
|
--sidebar-accent: oklch(0.9761 0 0);
|
||||||
|
--sidebar-accent-foreground: oklch(0.3250 0 0);
|
||||||
|
--sidebar-border: oklch(0.9401 0 0);
|
||||||
|
--sidebar-ring: oklch(0.7731 0 0);
|
||||||
|
--destructive-foreground: oklch(1.0000 0 0);
|
||||||
|
--font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
|
||||||
|
--font-serif: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;
|
||||||
|
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||||
|
--shadow-color: oklch(0 0 0);
|
||||||
|
--shadow-opacity: 0.09;
|
||||||
|
--shadow-blur: 5.5px;
|
||||||
|
--shadow-spread: 0.5px;
|
||||||
|
--shadow-offset-x: 2.5px;
|
||||||
|
--shadow-offset-y: 3.5px;
|
||||||
|
--letter-spacing: 0em;
|
||||||
|
--spacing: 0.2rem;
|
||||||
|
--shadow-2xs: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.04);
|
||||||
|
--shadow-xs: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.04);
|
||||||
|
--shadow-sm: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.09), 2.5px 1px 2px -0.5px hsl(0 0% 0% / 0.09);
|
||||||
|
--shadow: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.09), 2.5px 1px 2px -0.5px hsl(0 0% 0% / 0.09);
|
||||||
|
--shadow-md: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.09), 2.5px 2px 4px -0.5px hsl(0 0% 0% / 0.09);
|
||||||
|
--shadow-lg: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.09), 2.5px 4px 6px -0.5px hsl(0 0% 0% / 0.09);
|
||||||
|
--shadow-xl: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.09), 2.5px 8px 10px -0.5px hsl(0 0% 0% / 0.09);
|
||||||
|
--shadow-2xl: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.22);
|
||||||
|
--tracking-normal: 0em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark {
|
||||||
|
--background: oklch(0.1776 0 0);
|
||||||
|
--foreground: oklch(0.9491 0 0);
|
||||||
|
--card: oklch(0.2134 0 0);
|
||||||
|
--card-foreground: oklch(0.9491 0 0);
|
||||||
|
--popover: oklch(0.2134 0 0);
|
||||||
|
--popover-foreground: oklch(0.9491 0 0);
|
||||||
|
--primary: oklch(0.9247 0.0524 66.1732);
|
||||||
|
--primary-foreground: oklch(0.2490 0.0317 198.7326);
|
||||||
|
--secondary: oklch(0.3163 0.0190 63.6992);
|
||||||
|
--secondary-foreground: oklch(0.9247 0.0524 66.1732);
|
||||||
|
--muted: oklch(0.2520 0 0);
|
||||||
|
--muted-foreground: oklch(0.7699 0 0);
|
||||||
|
--accent: oklch(0.2850 0 0);
|
||||||
|
--accent-foreground: oklch(0.9491 0 0);
|
||||||
|
--destructive: oklch(0.6271 0.1936 33.3390);
|
||||||
|
--border: oklch(0.2351 0.0115 91.7467);
|
||||||
|
--input: oklch(0.4017 0 0);
|
||||||
|
--ring: oklch(0.9247 0.0524 66.1732);
|
||||||
|
--chart-1: oklch(0.9247 0.0524 66.1732);
|
||||||
|
--chart-2: oklch(0.3163 0.0190 63.6992);
|
||||||
|
--chart-3: oklch(0.2850 0 0);
|
||||||
|
--chart-4: oklch(0.3481 0.0219 67.0001);
|
||||||
|
--chart-5: oklch(0.9245 0.0533 67.0855);
|
||||||
|
--sidebar: oklch(0.2103 0.0059 285.8852);
|
||||||
|
--sidebar-foreground: oklch(0.9674 0.0013 286.3752);
|
||||||
|
--sidebar-primary: oklch(0.4882 0.2172 264.3763);
|
||||||
|
--sidebar-primary-foreground: oklch(1.0000 0 0);
|
||||||
|
--sidebar-accent: oklch(0.2739 0.0055 286.0326);
|
||||||
|
--sidebar-accent-foreground: oklch(0.9674 0.0013 286.3752);
|
||||||
|
--sidebar-border: oklch(0.2739 0.0055 286.0326);
|
||||||
|
--sidebar-ring: oklch(0.8711 0.0055 286.2860);
|
||||||
|
--destructive-foreground: oklch(1.0000 0 0);
|
||||||
|
--radius: 0.5rem;
|
||||||
|
--font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
|
||||||
|
--font-serif: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;
|
||||||
|
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||||
|
--shadow-color: oklch(0 0 0);
|
||||||
|
--shadow-opacity: 0.09;
|
||||||
|
--shadow-blur: 5.5px;
|
||||||
|
--shadow-spread: 0.5px;
|
||||||
|
--shadow-offset-x: 2.5px;
|
||||||
|
--shadow-offset-y: 3.5px;
|
||||||
|
--letter-spacing: 0em;
|
||||||
|
--spacing: 0.2rem;
|
||||||
|
--shadow-2xs: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.04);
|
||||||
|
--shadow-xs: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.04);
|
||||||
|
--shadow-sm: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.09), 2.5px 1px 2px -0.5px hsl(0 0% 0% / 0.09);
|
||||||
|
--shadow: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.09), 2.5px 1px 2px -0.5px hsl(0 0% 0% / 0.09);
|
||||||
|
--shadow-md: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.09), 2.5px 2px 4px -0.5px hsl(0 0% 0% / 0.09);
|
||||||
|
--shadow-lg: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.09), 2.5px 4px 6px -0.5px hsl(0 0% 0% / 0.09);
|
||||||
|
--shadow-xl: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.09), 2.5px 8px 10px -0.5px hsl(0 0% 0% / 0.09);
|
||||||
|
--shadow-2xl: 2.5px 3.5px 5.5px 0.5px hsl(0 0% 0% / 0.22);
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer base {
|
||||||
|
* {
|
||||||
|
@apply border-border outline-ring/50;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
@apply bg-background text-foreground;
|
||||||
|
letter-spacing: var(--tracking-normal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
|
||||||
background: var(--background);
|
|
||||||
color: var(--foreground);
|
|
||||||
font-family: Arial, Helvetica, sans-serif;
|
|
||||||
}
|
|
||||||
|
|||||||
66
frontend/src/components/ui/accordion.tsx
Normal file
66
frontend/src/components/ui/accordion.tsx
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as AccordionPrimitive from "@radix-ui/react-accordion"
|
||||||
|
import { ChevronDownIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Accordion({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
|
||||||
|
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccordionItem({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
|
||||||
|
return (
|
||||||
|
<AccordionPrimitive.Item
|
||||||
|
data-slot="accordion-item"
|
||||||
|
className={cn("border-b last:border-b-0", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccordionTrigger({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<AccordionPrimitive.Header className="flex">
|
||||||
|
<AccordionPrimitive.Trigger
|
||||||
|
data-slot="accordion-trigger"
|
||||||
|
className={cn(
|
||||||
|
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
|
||||||
|
</AccordionPrimitive.Trigger>
|
||||||
|
</AccordionPrimitive.Header>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccordionContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<AccordionPrimitive.Content
|
||||||
|
data-slot="accordion-content"
|
||||||
|
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className={cn("pt-0 pb-4", className)}>{children}</div>
|
||||||
|
</AccordionPrimitive.Content>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
|
||||||
157
frontend/src/components/ui/alert-dialog.tsx
Normal file
157
frontend/src/components/ui/alert-dialog.tsx
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { buttonVariants } from "@/components/ui/button"
|
||||||
|
|
||||||
|
function AlertDialog({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
|
||||||
|
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogOverlay({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Overlay
|
||||||
|
data-slot="alert-dialog-overlay"
|
||||||
|
className={cn(
|
||||||
|
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPortal>
|
||||||
|
<AlertDialogOverlay />
|
||||||
|
<AlertDialogPrimitive.Content
|
||||||
|
data-slot="alert-dialog-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</AlertDialogPortal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogHeader({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-dialog-header"
|
||||||
|
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogFooter({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-dialog-footer"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogTitle({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Title
|
||||||
|
data-slot="alert-dialog-title"
|
||||||
|
className={cn("text-lg font-semibold", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Description
|
||||||
|
data-slot="alert-dialog-description"
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogAction({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Action
|
||||||
|
className={cn(buttonVariants(), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogCancel({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Cancel
|
||||||
|
className={cn(buttonVariants({ variant: "outline" }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogPortal,
|
||||||
|
AlertDialogOverlay,
|
||||||
|
AlertDialogTrigger,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogTitle,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
}
|
||||||
66
frontend/src/components/ui/alert.tsx
Normal file
66
frontend/src/components/ui/alert.tsx
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const alertVariants = cva(
|
||||||
|
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-card text-card-foreground",
|
||||||
|
destructive:
|
||||||
|
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Alert({
|
||||||
|
className,
|
||||||
|
variant,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert"
|
||||||
|
role="alert"
|
||||||
|
className={cn(alertVariants({ variant }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-title"
|
||||||
|
className={cn(
|
||||||
|
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-description"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Alert, AlertTitle, AlertDescription }
|
||||||
11
frontend/src/components/ui/aspect-ratio.tsx
Normal file
11
frontend/src/components/ui/aspect-ratio.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"
|
||||||
|
|
||||||
|
function AspectRatio({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
|
||||||
|
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
export { AspectRatio }
|
||||||
53
frontend/src/components/ui/avatar.tsx
Normal file
53
frontend/src/components/ui/avatar.tsx
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as AvatarPrimitive from "@radix-ui/react-avatar"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Avatar({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Root
|
||||||
|
data-slot="avatar"
|
||||||
|
className={cn(
|
||||||
|
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AvatarImage({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Image
|
||||||
|
data-slot="avatar-image"
|
||||||
|
className={cn("aspect-square size-full", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AvatarFallback({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Fallback
|
||||||
|
data-slot="avatar-fallback"
|
||||||
|
className={cn(
|
||||||
|
"bg-muted flex size-full items-center justify-center rounded-full",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Avatar, AvatarImage, AvatarFallback }
|
||||||
46
frontend/src/components/ui/badge.tsx
Normal file
46
frontend/src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const badgeVariants = cva(
|
||||||
|
"inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default:
|
||||||
|
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||||
|
secondary:
|
||||||
|
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||||
|
destructive:
|
||||||
|
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||||
|
outline:
|
||||||
|
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Badge({
|
||||||
|
className,
|
||||||
|
variant,
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span"> &
|
||||||
|
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||||
|
const Comp = asChild ? Slot : "span"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="badge"
|
||||||
|
className={cn(badgeVariants({ variant }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Badge, badgeVariants }
|
||||||
109
frontend/src/components/ui/breadcrumb.tsx
Normal file
109
frontend/src/components/ui/breadcrumb.tsx
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
|
import { ChevronRight, MoreHorizontal } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
|
||||||
|
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
|
||||||
|
return (
|
||||||
|
<ol
|
||||||
|
data-slot="breadcrumb-list"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||||
|
return (
|
||||||
|
<li
|
||||||
|
data-slot="breadcrumb-item"
|
||||||
|
className={cn("inline-flex items-center gap-1.5", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function BreadcrumbLink({
|
||||||
|
asChild,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"a"> & {
|
||||||
|
asChild?: boolean
|
||||||
|
}) {
|
||||||
|
const Comp = asChild ? Slot : "a"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="breadcrumb-link"
|
||||||
|
className={cn("hover:text-foreground transition-colors", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="breadcrumb-page"
|
||||||
|
role="link"
|
||||||
|
aria-disabled="true"
|
||||||
|
aria-current="page"
|
||||||
|
className={cn("text-foreground font-normal", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function BreadcrumbSeparator({
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"li">) {
|
||||||
|
return (
|
||||||
|
<li
|
||||||
|
data-slot="breadcrumb-separator"
|
||||||
|
role="presentation"
|
||||||
|
aria-hidden="true"
|
||||||
|
className={cn("[&>svg]:size-3.5", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children ?? <ChevronRight />}
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function BreadcrumbEllipsis({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="breadcrumb-ellipsis"
|
||||||
|
role="presentation"
|
||||||
|
aria-hidden="true"
|
||||||
|
className={cn("flex size-9 items-center justify-center", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<MoreHorizontal className="size-4" />
|
||||||
|
<span className="sr-only">More</span>
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Breadcrumb,
|
||||||
|
BreadcrumbList,
|
||||||
|
BreadcrumbItem,
|
||||||
|
BreadcrumbLink,
|
||||||
|
BreadcrumbPage,
|
||||||
|
BreadcrumbSeparator,
|
||||||
|
BreadcrumbEllipsis,
|
||||||
|
}
|
||||||
83
frontend/src/components/ui/button-group.tsx
Normal file
83
frontend/src/components/ui/button-group.tsx
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Separator } from "@/components/ui/separator"
|
||||||
|
|
||||||
|
const buttonGroupVariants = cva(
|
||||||
|
"flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
orientation: {
|
||||||
|
horizontal:
|
||||||
|
"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",
|
||||||
|
vertical:
|
||||||
|
"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
orientation: "horizontal",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function ButtonGroup({
|
||||||
|
className,
|
||||||
|
orientation,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="group"
|
||||||
|
data-slot="button-group"
|
||||||
|
data-orientation={orientation}
|
||||||
|
className={cn(buttonGroupVariants({ orientation }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ButtonGroupText({
|
||||||
|
className,
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
asChild?: boolean
|
||||||
|
}) {
|
||||||
|
const Comp = asChild ? Slot : "div"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
className={cn(
|
||||||
|
"bg-muted flex items-center gap-2 rounded-md border px-4 text-sm font-medium shadow-xs [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ButtonGroupSeparator({
|
||||||
|
className,
|
||||||
|
orientation = "vertical",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof Separator>) {
|
||||||
|
return (
|
||||||
|
<Separator
|
||||||
|
data-slot="button-group-separator"
|
||||||
|
orientation={orientation}
|
||||||
|
className={cn(
|
||||||
|
"bg-input relative !m-0 self-stretch data-[orientation=vertical]:h-auto",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
ButtonGroup,
|
||||||
|
ButtonGroupSeparator,
|
||||||
|
ButtonGroupText,
|
||||||
|
buttonGroupVariants,
|
||||||
|
}
|
||||||
62
frontend/src/components/ui/button.tsx
Normal file
62
frontend/src/components/ui/button.tsx
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const buttonVariants = cva(
|
||||||
|
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||||
|
destructive:
|
||||||
|
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||||
|
outline:
|
||||||
|
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||||
|
secondary:
|
||||||
|
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||||
|
ghost:
|
||||||
|
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||||
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||||
|
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||||
|
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||||
|
icon: "size-9",
|
||||||
|
"icon-sm": "size-8",
|
||||||
|
"icon-lg": "size-10",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Button({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
size = "default",
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"button"> &
|
||||||
|
VariantProps<typeof buttonVariants> & {
|
||||||
|
asChild?: boolean
|
||||||
|
}) {
|
||||||
|
const Comp = asChild ? Slot : "button"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="button"
|
||||||
|
data-variant={variant}
|
||||||
|
data-size={size}
|
||||||
|
className={cn(buttonVariants({ variant, size, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Button, buttonVariants }
|
||||||
220
frontend/src/components/ui/calendar.tsx
Normal file
220
frontend/src/components/ui/calendar.tsx
Normal file
@@ -0,0 +1,220 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import {
|
||||||
|
ChevronDownIcon,
|
||||||
|
ChevronLeftIcon,
|
||||||
|
ChevronRightIcon,
|
||||||
|
} from "lucide-react"
|
||||||
|
import {
|
||||||
|
DayPicker,
|
||||||
|
getDefaultClassNames,
|
||||||
|
type DayButton,
|
||||||
|
} from "react-day-picker"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Button, buttonVariants } from "@/components/ui/button"
|
||||||
|
|
||||||
|
function Calendar({
|
||||||
|
className,
|
||||||
|
classNames,
|
||||||
|
showOutsideDays = true,
|
||||||
|
captionLayout = "label",
|
||||||
|
buttonVariant = "ghost",
|
||||||
|
formatters,
|
||||||
|
components,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DayPicker> & {
|
||||||
|
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||||
|
}) {
|
||||||
|
const defaultClassNames = getDefaultClassNames()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DayPicker
|
||||||
|
showOutsideDays={showOutsideDays}
|
||||||
|
className={cn(
|
||||||
|
"bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
|
||||||
|
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||||
|
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
captionLayout={captionLayout}
|
||||||
|
formatters={{
|
||||||
|
formatMonthDropdown: (date) =>
|
||||||
|
date.toLocaleString("default", { month: "short" }),
|
||||||
|
...formatters,
|
||||||
|
}}
|
||||||
|
classNames={{
|
||||||
|
root: cn("w-fit", defaultClassNames.root),
|
||||||
|
months: cn(
|
||||||
|
"flex gap-4 flex-col md:flex-row relative",
|
||||||
|
defaultClassNames.months
|
||||||
|
),
|
||||||
|
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
|
||||||
|
nav: cn(
|
||||||
|
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
|
||||||
|
defaultClassNames.nav
|
||||||
|
),
|
||||||
|
button_previous: cn(
|
||||||
|
buttonVariants({ variant: buttonVariant }),
|
||||||
|
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||||
|
defaultClassNames.button_previous
|
||||||
|
),
|
||||||
|
button_next: cn(
|
||||||
|
buttonVariants({ variant: buttonVariant }),
|
||||||
|
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||||
|
defaultClassNames.button_next
|
||||||
|
),
|
||||||
|
month_caption: cn(
|
||||||
|
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
|
||||||
|
defaultClassNames.month_caption
|
||||||
|
),
|
||||||
|
dropdowns: cn(
|
||||||
|
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
|
||||||
|
defaultClassNames.dropdowns
|
||||||
|
),
|
||||||
|
dropdown_root: cn(
|
||||||
|
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
|
||||||
|
defaultClassNames.dropdown_root
|
||||||
|
),
|
||||||
|
dropdown: cn(
|
||||||
|
"absolute bg-popover inset-0 opacity-0",
|
||||||
|
defaultClassNames.dropdown
|
||||||
|
),
|
||||||
|
caption_label: cn(
|
||||||
|
"select-none font-medium",
|
||||||
|
captionLayout === "label"
|
||||||
|
? "text-sm"
|
||||||
|
: "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
|
||||||
|
defaultClassNames.caption_label
|
||||||
|
),
|
||||||
|
table: "w-full border-collapse",
|
||||||
|
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||||
|
weekday: cn(
|
||||||
|
"text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",
|
||||||
|
defaultClassNames.weekday
|
||||||
|
),
|
||||||
|
week: cn("flex w-full mt-2", defaultClassNames.week),
|
||||||
|
week_number_header: cn(
|
||||||
|
"select-none w-(--cell-size)",
|
||||||
|
defaultClassNames.week_number_header
|
||||||
|
),
|
||||||
|
week_number: cn(
|
||||||
|
"text-[0.8rem] select-none text-muted-foreground",
|
||||||
|
defaultClassNames.week_number
|
||||||
|
),
|
||||||
|
day: cn(
|
||||||
|
"relative w-full h-full p-0 text-center [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
|
||||||
|
props.showWeekNumber
|
||||||
|
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-md"
|
||||||
|
: "[&:first-child[data-selected=true]_button]:rounded-l-md",
|
||||||
|
defaultClassNames.day
|
||||||
|
),
|
||||||
|
range_start: cn(
|
||||||
|
"rounded-l-md bg-accent",
|
||||||
|
defaultClassNames.range_start
|
||||||
|
),
|
||||||
|
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||||
|
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
|
||||||
|
today: cn(
|
||||||
|
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
|
||||||
|
defaultClassNames.today
|
||||||
|
),
|
||||||
|
outside: cn(
|
||||||
|
"text-muted-foreground aria-selected:text-muted-foreground",
|
||||||
|
defaultClassNames.outside
|
||||||
|
),
|
||||||
|
disabled: cn(
|
||||||
|
"text-muted-foreground opacity-50",
|
||||||
|
defaultClassNames.disabled
|
||||||
|
),
|
||||||
|
hidden: cn("invisible", defaultClassNames.hidden),
|
||||||
|
...classNames,
|
||||||
|
}}
|
||||||
|
components={{
|
||||||
|
Root: ({ className, rootRef, ...props }) => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="calendar"
|
||||||
|
ref={rootRef}
|
||||||
|
className={cn(className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
Chevron: ({ className, orientation, ...props }) => {
|
||||||
|
if (orientation === "left") {
|
||||||
|
return (
|
||||||
|
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (orientation === "right") {
|
||||||
|
return (
|
||||||
|
<ChevronRightIcon
|
||||||
|
className={cn("size-4", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||||
|
)
|
||||||
|
},
|
||||||
|
DayButton: CalendarDayButton,
|
||||||
|
WeekNumber: ({ children, ...props }) => {
|
||||||
|
return (
|
||||||
|
<td {...props}>
|
||||||
|
<div className="flex size-(--cell-size) items-center justify-center text-center">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
...components,
|
||||||
|
}}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CalendarDayButton({
|
||||||
|
className,
|
||||||
|
day,
|
||||||
|
modifiers,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DayButton>) {
|
||||||
|
const defaultClassNames = getDefaultClassNames()
|
||||||
|
|
||||||
|
const ref = React.useRef<HTMLButtonElement>(null)
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (modifiers.focused) ref.current?.focus()
|
||||||
|
}, [modifiers.focused])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
ref={ref}
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
data-day={day.date.toLocaleDateString()}
|
||||||
|
data-selected-single={
|
||||||
|
modifiers.selected &&
|
||||||
|
!modifiers.range_start &&
|
||||||
|
!modifiers.range_end &&
|
||||||
|
!modifiers.range_middle
|
||||||
|
}
|
||||||
|
data-range-start={modifiers.range_start}
|
||||||
|
data-range-end={modifiers.range_end}
|
||||||
|
data-range-middle={modifiers.range_middle}
|
||||||
|
className={cn(
|
||||||
|
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
|
||||||
|
defaultClassNames.day,
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Calendar, CalendarDayButton }
|
||||||
92
frontend/src/components/ui/card.tsx
Normal file
92
frontend/src/components/ui/card.tsx
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card"
|
||||||
|
className={cn(
|
||||||
|
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-header"
|
||||||
|
className={cn(
|
||||||
|
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-title"
|
||||||
|
className={cn("leading-none font-semibold", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-description"
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-action"
|
||||||
|
className={cn(
|
||||||
|
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-content"
|
||||||
|
className={cn("px-6", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-footer"
|
||||||
|
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Card,
|
||||||
|
CardHeader,
|
||||||
|
CardFooter,
|
||||||
|
CardTitle,
|
||||||
|
CardAction,
|
||||||
|
CardDescription,
|
||||||
|
CardContent,
|
||||||
|
}
|
||||||
241
frontend/src/components/ui/carousel.tsx
Normal file
241
frontend/src/components/ui/carousel.tsx
Normal file
@@ -0,0 +1,241 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import useEmblaCarousel, {
|
||||||
|
type UseEmblaCarouselType,
|
||||||
|
} from "embla-carousel-react"
|
||||||
|
import { ArrowLeft, ArrowRight } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
|
||||||
|
type CarouselApi = UseEmblaCarouselType[1]
|
||||||
|
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
|
||||||
|
type CarouselOptions = UseCarouselParameters[0]
|
||||||
|
type CarouselPlugin = UseCarouselParameters[1]
|
||||||
|
|
||||||
|
type CarouselProps = {
|
||||||
|
opts?: CarouselOptions
|
||||||
|
plugins?: CarouselPlugin
|
||||||
|
orientation?: "horizontal" | "vertical"
|
||||||
|
setApi?: (api: CarouselApi) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
type CarouselContextProps = {
|
||||||
|
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
|
||||||
|
api: ReturnType<typeof useEmblaCarousel>[1]
|
||||||
|
scrollPrev: () => void
|
||||||
|
scrollNext: () => void
|
||||||
|
canScrollPrev: boolean
|
||||||
|
canScrollNext: boolean
|
||||||
|
} & CarouselProps
|
||||||
|
|
||||||
|
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
|
||||||
|
|
||||||
|
function useCarousel() {
|
||||||
|
const context = React.useContext(CarouselContext)
|
||||||
|
|
||||||
|
if (!context) {
|
||||||
|
throw new Error("useCarousel must be used within a <Carousel />")
|
||||||
|
}
|
||||||
|
|
||||||
|
return context
|
||||||
|
}
|
||||||
|
|
||||||
|
function Carousel({
|
||||||
|
orientation = "horizontal",
|
||||||
|
opts,
|
||||||
|
setApi,
|
||||||
|
plugins,
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & CarouselProps) {
|
||||||
|
const [carouselRef, api] = useEmblaCarousel(
|
||||||
|
{
|
||||||
|
...opts,
|
||||||
|
axis: orientation === "horizontal" ? "x" : "y",
|
||||||
|
},
|
||||||
|
plugins
|
||||||
|
)
|
||||||
|
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
|
||||||
|
const [canScrollNext, setCanScrollNext] = React.useState(false)
|
||||||
|
|
||||||
|
const onSelect = React.useCallback((api: CarouselApi) => {
|
||||||
|
if (!api) return
|
||||||
|
setCanScrollPrev(api.canScrollPrev())
|
||||||
|
setCanScrollNext(api.canScrollNext())
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const scrollPrev = React.useCallback(() => {
|
||||||
|
api?.scrollPrev()
|
||||||
|
}, [api])
|
||||||
|
|
||||||
|
const scrollNext = React.useCallback(() => {
|
||||||
|
api?.scrollNext()
|
||||||
|
}, [api])
|
||||||
|
|
||||||
|
const handleKeyDown = React.useCallback(
|
||||||
|
(event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||||
|
if (event.key === "ArrowLeft") {
|
||||||
|
event.preventDefault()
|
||||||
|
scrollPrev()
|
||||||
|
} else if (event.key === "ArrowRight") {
|
||||||
|
event.preventDefault()
|
||||||
|
scrollNext()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[scrollPrev, scrollNext]
|
||||||
|
)
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (!api || !setApi) return
|
||||||
|
setApi(api)
|
||||||
|
}, [api, setApi])
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (!api) return
|
||||||
|
onSelect(api)
|
||||||
|
api.on("reInit", onSelect)
|
||||||
|
api.on("select", onSelect)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
api?.off("select", onSelect)
|
||||||
|
}
|
||||||
|
}, [api, onSelect])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<CarouselContext.Provider
|
||||||
|
value={{
|
||||||
|
carouselRef,
|
||||||
|
api: api,
|
||||||
|
opts,
|
||||||
|
orientation:
|
||||||
|
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
|
||||||
|
scrollPrev,
|
||||||
|
scrollNext,
|
||||||
|
canScrollPrev,
|
||||||
|
canScrollNext,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
onKeyDownCapture={handleKeyDown}
|
||||||
|
className={cn("relative", className)}
|
||||||
|
role="region"
|
||||||
|
aria-roledescription="carousel"
|
||||||
|
data-slot="carousel"
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</CarouselContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
const { carouselRef, orientation } = useCarousel()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={carouselRef}
|
||||||
|
className="overflow-hidden"
|
||||||
|
data-slot="carousel-content"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex",
|
||||||
|
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
const { orientation } = useCarousel()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="group"
|
||||||
|
aria-roledescription="slide"
|
||||||
|
data-slot="carousel-item"
|
||||||
|
className={cn(
|
||||||
|
"min-w-0 shrink-0 grow-0 basis-full",
|
||||||
|
orientation === "horizontal" ? "pl-4" : "pt-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CarouselPrevious({
|
||||||
|
className,
|
||||||
|
variant = "outline",
|
||||||
|
size = "icon",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof Button>) {
|
||||||
|
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
data-slot="carousel-previous"
|
||||||
|
variant={variant}
|
||||||
|
size={size}
|
||||||
|
className={cn(
|
||||||
|
"absolute size-8 rounded-full",
|
||||||
|
orientation === "horizontal"
|
||||||
|
? "top-1/2 -left-12 -translate-y-1/2"
|
||||||
|
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
disabled={!canScrollPrev}
|
||||||
|
onClick={scrollPrev}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ArrowLeft />
|
||||||
|
<span className="sr-only">Previous slide</span>
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CarouselNext({
|
||||||
|
className,
|
||||||
|
variant = "outline",
|
||||||
|
size = "icon",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof Button>) {
|
||||||
|
const { orientation, scrollNext, canScrollNext } = useCarousel()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
data-slot="carousel-next"
|
||||||
|
variant={variant}
|
||||||
|
size={size}
|
||||||
|
className={cn(
|
||||||
|
"absolute size-8 rounded-full",
|
||||||
|
orientation === "horizontal"
|
||||||
|
? "top-1/2 -right-12 -translate-y-1/2"
|
||||||
|
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
disabled={!canScrollNext}
|
||||||
|
onClick={scrollNext}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ArrowRight />
|
||||||
|
<span className="sr-only">Next slide</span>
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
type CarouselApi,
|
||||||
|
Carousel,
|
||||||
|
CarouselContent,
|
||||||
|
CarouselItem,
|
||||||
|
CarouselPrevious,
|
||||||
|
CarouselNext,
|
||||||
|
}
|
||||||
357
frontend/src/components/ui/chart.tsx
Normal file
357
frontend/src/components/ui/chart.tsx
Normal file
@@ -0,0 +1,357 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as RechartsPrimitive from "recharts"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
// Format: { THEME_NAME: CSS_SELECTOR }
|
||||||
|
const THEMES = { light: "", dark: ".dark" } as const
|
||||||
|
|
||||||
|
export type ChartConfig = {
|
||||||
|
[k in string]: {
|
||||||
|
label?: React.ReactNode
|
||||||
|
icon?: React.ComponentType
|
||||||
|
} & (
|
||||||
|
| { color?: string; theme?: never }
|
||||||
|
| { color?: never; theme: Record<keyof typeof THEMES, string> }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
type ChartContextProps = {
|
||||||
|
config: ChartConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
const ChartContext = React.createContext<ChartContextProps | null>(null)
|
||||||
|
|
||||||
|
function useChart() {
|
||||||
|
const context = React.useContext(ChartContext)
|
||||||
|
|
||||||
|
if (!context) {
|
||||||
|
throw new Error("useChart must be used within a <ChartContainer />")
|
||||||
|
}
|
||||||
|
|
||||||
|
return context
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChartContainer({
|
||||||
|
id,
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
config,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
config: ChartConfig
|
||||||
|
children: React.ComponentProps<
|
||||||
|
typeof RechartsPrimitive.ResponsiveContainer
|
||||||
|
>["children"]
|
||||||
|
}) {
|
||||||
|
const uniqueId = React.useId()
|
||||||
|
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ChartContext.Provider value={{ config }}>
|
||||||
|
<div
|
||||||
|
data-slot="chart"
|
||||||
|
data-chart={chartId}
|
||||||
|
className={cn(
|
||||||
|
"[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ChartStyle id={chartId} config={config} />
|
||||||
|
<RechartsPrimitive.ResponsiveContainer>
|
||||||
|
{children}
|
||||||
|
</RechartsPrimitive.ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
</ChartContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
|
||||||
|
const colorConfig = Object.entries(config).filter(
|
||||||
|
([, config]) => config.theme || config.color
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!colorConfig.length) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<style
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: Object.entries(THEMES)
|
||||||
|
.map(
|
||||||
|
([theme, prefix]) => `
|
||||||
|
${prefix} [data-chart=${id}] {
|
||||||
|
${colorConfig
|
||||||
|
.map(([key, itemConfig]) => {
|
||||||
|
const color =
|
||||||
|
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
|
||||||
|
itemConfig.color
|
||||||
|
return color ? ` --color-${key}: ${color};` : null
|
||||||
|
})
|
||||||
|
.join("\n")}
|
||||||
|
}
|
||||||
|
`
|
||||||
|
)
|
||||||
|
.join("\n"),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const ChartTooltip = RechartsPrimitive.Tooltip
|
||||||
|
|
||||||
|
function ChartTooltipContent({
|
||||||
|
active,
|
||||||
|
payload,
|
||||||
|
className,
|
||||||
|
indicator = "dot",
|
||||||
|
hideLabel = false,
|
||||||
|
hideIndicator = false,
|
||||||
|
label,
|
||||||
|
labelFormatter,
|
||||||
|
labelClassName,
|
||||||
|
formatter,
|
||||||
|
color,
|
||||||
|
nameKey,
|
||||||
|
labelKey,
|
||||||
|
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
|
||||||
|
React.ComponentProps<"div"> & {
|
||||||
|
hideLabel?: boolean
|
||||||
|
hideIndicator?: boolean
|
||||||
|
indicator?: "line" | "dot" | "dashed"
|
||||||
|
nameKey?: string
|
||||||
|
labelKey?: string
|
||||||
|
}) {
|
||||||
|
const { config } = useChart()
|
||||||
|
|
||||||
|
const tooltipLabel = React.useMemo(() => {
|
||||||
|
if (hideLabel || !payload?.length) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const [item] = payload
|
||||||
|
const key = `${labelKey || item?.dataKey || item?.name || "value"}`
|
||||||
|
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||||
|
const value =
|
||||||
|
!labelKey && typeof label === "string"
|
||||||
|
? config[label as keyof typeof config]?.label || label
|
||||||
|
: itemConfig?.label
|
||||||
|
|
||||||
|
if (labelFormatter) {
|
||||||
|
return (
|
||||||
|
<div className={cn("font-medium", labelClassName)}>
|
||||||
|
{labelFormatter(value, payload)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!value) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return <div className={cn("font-medium", labelClassName)}>{value}</div>
|
||||||
|
}, [
|
||||||
|
label,
|
||||||
|
labelFormatter,
|
||||||
|
payload,
|
||||||
|
hideLabel,
|
||||||
|
labelClassName,
|
||||||
|
config,
|
||||||
|
labelKey,
|
||||||
|
])
|
||||||
|
|
||||||
|
if (!active || !payload?.length) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const nestLabel = payload.length === 1 && indicator !== "dot"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{!nestLabel ? tooltipLabel : null}
|
||||||
|
<div className="grid gap-1.5">
|
||||||
|
{payload
|
||||||
|
.filter((item) => item.type !== "none")
|
||||||
|
.map((item, index) => {
|
||||||
|
const key = `${nameKey || item.name || item.dataKey || "value"}`
|
||||||
|
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||||
|
const indicatorColor = color || item.payload.fill || item.color
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={item.dataKey}
|
||||||
|
className={cn(
|
||||||
|
"[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",
|
||||||
|
indicator === "dot" && "items-center"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{formatter && item?.value !== undefined && item.name ? (
|
||||||
|
formatter(item.value, item.name, item, index, item.payload)
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{itemConfig?.icon ? (
|
||||||
|
<itemConfig.icon />
|
||||||
|
) : (
|
||||||
|
!hideIndicator && (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",
|
||||||
|
{
|
||||||
|
"h-2.5 w-2.5": indicator === "dot",
|
||||||
|
"w-1": indicator === "line",
|
||||||
|
"w-0 border-[1.5px] border-dashed bg-transparent":
|
||||||
|
indicator === "dashed",
|
||||||
|
"my-0.5": nestLabel && indicator === "dashed",
|
||||||
|
}
|
||||||
|
)}
|
||||||
|
style={
|
||||||
|
{
|
||||||
|
"--color-bg": indicatorColor,
|
||||||
|
"--color-border": indicatorColor,
|
||||||
|
} as React.CSSProperties
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex flex-1 justify-between leading-none",
|
||||||
|
nestLabel ? "items-end" : "items-center"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="grid gap-1.5">
|
||||||
|
{nestLabel ? tooltipLabel : null}
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
{itemConfig?.label || item.name}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{item.value && (
|
||||||
|
<span className="text-foreground font-mono font-medium tabular-nums">
|
||||||
|
{item.value.toLocaleString()}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const ChartLegend = RechartsPrimitive.Legend
|
||||||
|
|
||||||
|
function ChartLegendContent({
|
||||||
|
className,
|
||||||
|
hideIcon = false,
|
||||||
|
payload,
|
||||||
|
verticalAlign = "bottom",
|
||||||
|
nameKey,
|
||||||
|
}: React.ComponentProps<"div"> &
|
||||||
|
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
|
||||||
|
hideIcon?: boolean
|
||||||
|
nameKey?: string
|
||||||
|
}) {
|
||||||
|
const { config } = useChart()
|
||||||
|
|
||||||
|
if (!payload?.length) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex items-center justify-center gap-4",
|
||||||
|
verticalAlign === "top" ? "pb-3" : "pt-3",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{payload
|
||||||
|
.filter((item) => item.type !== "none")
|
||||||
|
.map((item) => {
|
||||||
|
const key = `${nameKey || item.dataKey || "value"}`
|
||||||
|
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={item.value}
|
||||||
|
className={cn(
|
||||||
|
"[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{itemConfig?.icon && !hideIcon ? (
|
||||||
|
<itemConfig.icon />
|
||||||
|
) : (
|
||||||
|
<div
|
||||||
|
className="h-2 w-2 shrink-0 rounded-[2px]"
|
||||||
|
style={{
|
||||||
|
backgroundColor: item.color,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{itemConfig?.label}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper to extract item config from a payload.
|
||||||
|
function getPayloadConfigFromPayload(
|
||||||
|
config: ChartConfig,
|
||||||
|
payload: unknown,
|
||||||
|
key: string
|
||||||
|
) {
|
||||||
|
if (typeof payload !== "object" || payload === null) {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
const payloadPayload =
|
||||||
|
"payload" in payload &&
|
||||||
|
typeof payload.payload === "object" &&
|
||||||
|
payload.payload !== null
|
||||||
|
? payload.payload
|
||||||
|
: undefined
|
||||||
|
|
||||||
|
let configLabelKey: string = key
|
||||||
|
|
||||||
|
if (
|
||||||
|
key in payload &&
|
||||||
|
typeof payload[key as keyof typeof payload] === "string"
|
||||||
|
) {
|
||||||
|
configLabelKey = payload[key as keyof typeof payload] as string
|
||||||
|
} else if (
|
||||||
|
payloadPayload &&
|
||||||
|
key in payloadPayload &&
|
||||||
|
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
|
||||||
|
) {
|
||||||
|
configLabelKey = payloadPayload[
|
||||||
|
key as keyof typeof payloadPayload
|
||||||
|
] as string
|
||||||
|
}
|
||||||
|
|
||||||
|
return configLabelKey in config
|
||||||
|
? config[configLabelKey]
|
||||||
|
: config[key as keyof typeof config]
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
ChartContainer,
|
||||||
|
ChartTooltip,
|
||||||
|
ChartTooltipContent,
|
||||||
|
ChartLegend,
|
||||||
|
ChartLegendContent,
|
||||||
|
ChartStyle,
|
||||||
|
}
|
||||||
32
frontend/src/components/ui/checkbox.tsx
Normal file
32
frontend/src/components/ui/checkbox.tsx
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||||
|
import { CheckIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Checkbox({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<CheckboxPrimitive.Root
|
||||||
|
data-slot="checkbox"
|
||||||
|
className={cn(
|
||||||
|
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<CheckboxPrimitive.Indicator
|
||||||
|
data-slot="checkbox-indicator"
|
||||||
|
className="grid place-content-center text-current transition-none"
|
||||||
|
>
|
||||||
|
<CheckIcon className="size-3.5" />
|
||||||
|
</CheckboxPrimitive.Indicator>
|
||||||
|
</CheckboxPrimitive.Root>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Checkbox }
|
||||||
33
frontend/src/components/ui/collapsible.tsx
Normal file
33
frontend/src/components/ui/collapsible.tsx
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
|
||||||
|
|
||||||
|
function Collapsible({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
||||||
|
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function CollapsibleTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
|
||||||
|
return (
|
||||||
|
<CollapsiblePrimitive.CollapsibleTrigger
|
||||||
|
data-slot="collapsible-trigger"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CollapsibleContent({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
||||||
|
return (
|
||||||
|
<CollapsiblePrimitive.CollapsibleContent
|
||||||
|
data-slot="collapsible-content"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
|
||||||
184
frontend/src/components/ui/command.tsx
Normal file
184
frontend/src/components/ui/command.tsx
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Command as CommandPrimitive } from "cmdk"
|
||||||
|
import { SearchIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog"
|
||||||
|
|
||||||
|
function Command({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CommandPrimitive>) {
|
||||||
|
return (
|
||||||
|
<CommandPrimitive
|
||||||
|
data-slot="command"
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandDialog({
|
||||||
|
title = "Command Palette",
|
||||||
|
description = "Search for a command to run...",
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
showCloseButton = true,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof Dialog> & {
|
||||||
|
title?: string
|
||||||
|
description?: string
|
||||||
|
className?: string
|
||||||
|
showCloseButton?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<Dialog {...props}>
|
||||||
|
<DialogHeader className="sr-only">
|
||||||
|
<DialogTitle>{title}</DialogTitle>
|
||||||
|
<DialogDescription>{description}</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogContent
|
||||||
|
className={cn("overflow-hidden p-0", className)}
|
||||||
|
showCloseButton={showCloseButton}
|
||||||
|
>
|
||||||
|
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||||
|
{children}
|
||||||
|
</Command>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandInput({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="command-input-wrapper"
|
||||||
|
className="flex h-9 items-center gap-2 border-b px-3"
|
||||||
|
>
|
||||||
|
<SearchIcon className="size-4 shrink-0 opacity-50" />
|
||||||
|
<CommandPrimitive.Input
|
||||||
|
data-slot="command-input"
|
||||||
|
className={cn(
|
||||||
|
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandList({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CommandPrimitive.List>) {
|
||||||
|
return (
|
||||||
|
<CommandPrimitive.List
|
||||||
|
data-slot="command-list"
|
||||||
|
className={cn(
|
||||||
|
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandEmpty({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
|
||||||
|
return (
|
||||||
|
<CommandPrimitive.Empty
|
||||||
|
data-slot="command-empty"
|
||||||
|
className="py-6 text-center text-sm"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandGroup({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
|
||||||
|
return (
|
||||||
|
<CommandPrimitive.Group
|
||||||
|
data-slot="command-group"
|
||||||
|
className={cn(
|
||||||
|
"text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
|
||||||
|
return (
|
||||||
|
<CommandPrimitive.Separator
|
||||||
|
data-slot="command-separator"
|
||||||
|
className={cn("bg-border -mx-1 h-px", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandItem({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
|
||||||
|
return (
|
||||||
|
<CommandPrimitive.Item
|
||||||
|
data-slot="command-item"
|
||||||
|
className={cn(
|
||||||
|
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandShortcut({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="command-shortcut"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Command,
|
||||||
|
CommandDialog,
|
||||||
|
CommandInput,
|
||||||
|
CommandList,
|
||||||
|
CommandEmpty,
|
||||||
|
CommandGroup,
|
||||||
|
CommandItem,
|
||||||
|
CommandShortcut,
|
||||||
|
CommandSeparator,
|
||||||
|
}
|
||||||
252
frontend/src/components/ui/context-menu.tsx
Normal file
252
frontend/src/components/ui/context-menu.tsx
Normal file
@@ -0,0 +1,252 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
|
||||||
|
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function ContextMenu({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||||
|
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuSub({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||||
|
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuRadioGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.RadioGroup
|
||||||
|
data-slot="context-menu-radio-group"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuSubTrigger({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.SubTrigger
|
||||||
|
data-slot="context-menu-sub-trigger"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronRightIcon className="ml-auto" />
|
||||||
|
</ContextMenuPrimitive.SubTrigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuSubContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.SubContent
|
||||||
|
data-slot="context-menu-sub-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Portal>
|
||||||
|
<ContextMenuPrimitive.Content
|
||||||
|
data-slot="context-menu-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</ContextMenuPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuItem({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||||
|
inset?: boolean
|
||||||
|
variant?: "default" | "destructive"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Item
|
||||||
|
data-slot="context-menu-item"
|
||||||
|
data-inset={inset}
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuCheckboxItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
checked,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.CheckboxItem
|
||||||
|
data-slot="context-menu-checkbox-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
checked={checked}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<ContextMenuPrimitive.ItemIndicator>
|
||||||
|
<CheckIcon className="size-4" />
|
||||||
|
</ContextMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</ContextMenuPrimitive.CheckboxItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuRadioItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.RadioItem
|
||||||
|
data-slot="context-menu-radio-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<ContextMenuPrimitive.ItemIndicator>
|
||||||
|
<CircleIcon className="size-2 fill-current" />
|
||||||
|
</ContextMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</ContextMenuPrimitive.RadioItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuLabel({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Label
|
||||||
|
data-slot="context-menu-label"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||||
|
return (
|
||||||
|
<ContextMenuPrimitive.Separator
|
||||||
|
data-slot="context-menu-separator"
|
||||||
|
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContextMenuShortcut({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="context-menu-shortcut"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
ContextMenu,
|
||||||
|
ContextMenuTrigger,
|
||||||
|
ContextMenuContent,
|
||||||
|
ContextMenuItem,
|
||||||
|
ContextMenuCheckboxItem,
|
||||||
|
ContextMenuRadioItem,
|
||||||
|
ContextMenuLabel,
|
||||||
|
ContextMenuSeparator,
|
||||||
|
ContextMenuShortcut,
|
||||||
|
ContextMenuGroup,
|
||||||
|
ContextMenuPortal,
|
||||||
|
ContextMenuSub,
|
||||||
|
ContextMenuSubContent,
|
||||||
|
ContextMenuSubTrigger,
|
||||||
|
ContextMenuRadioGroup,
|
||||||
|
}
|
||||||
143
frontend/src/components/ui/dialog.tsx
Normal file
143
frontend/src/components/ui/dialog.tsx
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||||
|
import { XIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Dialog({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||||
|
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||||
|
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||||
|
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogClose({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||||
|
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogOverlay({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Overlay
|
||||||
|
data-slot="dialog-overlay"
|
||||||
|
className={cn(
|
||||||
|
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
showCloseButton = true,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||||
|
showCloseButton?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DialogPortal data-slot="dialog-portal">
|
||||||
|
<DialogOverlay />
|
||||||
|
<DialogPrimitive.Content
|
||||||
|
data-slot="dialog-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
{showCloseButton && (
|
||||||
|
<DialogPrimitive.Close
|
||||||
|
data-slot="dialog-close"
|
||||||
|
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||||
|
>
|
||||||
|
<XIcon />
|
||||||
|
<span className="sr-only">Close</span>
|
||||||
|
</DialogPrimitive.Close>
|
||||||
|
)}
|
||||||
|
</DialogPrimitive.Content>
|
||||||
|
</DialogPortal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="dialog-header"
|
||||||
|
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="dialog-footer"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogTitle({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Title
|
||||||
|
data-slot="dialog-title"
|
||||||
|
className={cn("text-lg leading-none font-semibold", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Description
|
||||||
|
data-slot="dialog-description"
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Dialog,
|
||||||
|
DialogClose,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogOverlay,
|
||||||
|
DialogPortal,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
}
|
||||||
135
frontend/src/components/ui/drawer.tsx
Normal file
135
frontend/src/components/ui/drawer.tsx
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Drawer as DrawerPrimitive } from "vaul"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Drawer({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
|
||||||
|
return <DrawerPrimitive.Root data-slot="drawer" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
|
||||||
|
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
|
||||||
|
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerClose({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
|
||||||
|
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerOverlay({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
|
||||||
|
return (
|
||||||
|
<DrawerPrimitive.Overlay
|
||||||
|
data-slot="drawer-overlay"
|
||||||
|
className={cn(
|
||||||
|
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<DrawerPortal data-slot="drawer-portal">
|
||||||
|
<DrawerOverlay />
|
||||||
|
<DrawerPrimitive.Content
|
||||||
|
data-slot="drawer-content"
|
||||||
|
className={cn(
|
||||||
|
"group/drawer-content bg-background fixed z-50 flex h-auto flex-col",
|
||||||
|
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
|
||||||
|
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
|
||||||
|
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
|
||||||
|
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className="bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
|
||||||
|
{children}
|
||||||
|
</DrawerPrimitive.Content>
|
||||||
|
</DrawerPortal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="drawer-header"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="drawer-footer"
|
||||||
|
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerTitle({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
|
||||||
|
return (
|
||||||
|
<DrawerPrimitive.Title
|
||||||
|
data-slot="drawer-title"
|
||||||
|
className={cn("text-foreground font-semibold", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
|
||||||
|
return (
|
||||||
|
<DrawerPrimitive.Description
|
||||||
|
data-slot="drawer-description"
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Drawer,
|
||||||
|
DrawerPortal,
|
||||||
|
DrawerOverlay,
|
||||||
|
DrawerTrigger,
|
||||||
|
DrawerClose,
|
||||||
|
DrawerContent,
|
||||||
|
DrawerHeader,
|
||||||
|
DrawerFooter,
|
||||||
|
DrawerTitle,
|
||||||
|
DrawerDescription,
|
||||||
|
}
|
||||||
257
frontend/src/components/ui/dropdown-menu.tsx
Normal file
257
frontend/src/components/ui/dropdown-menu.tsx
Normal file
@@ -0,0 +1,257 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||||
|
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function DropdownMenu({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||||
|
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Trigger
|
||||||
|
data-slot="dropdown-menu-trigger"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuContent({
|
||||||
|
className,
|
||||||
|
sideOffset = 4,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Portal>
|
||||||
|
<DropdownMenuPrimitive.Content
|
||||||
|
data-slot="dropdown-menu-content"
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</DropdownMenuPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuItem({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||||
|
inset?: boolean
|
||||||
|
variant?: "default" | "destructive"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Item
|
||||||
|
data-slot="dropdown-menu-item"
|
||||||
|
data-inset={inset}
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuCheckboxItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
checked,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.CheckboxItem
|
||||||
|
data-slot="dropdown-menu-checkbox-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
checked={checked}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
<CheckIcon className="size-4" />
|
||||||
|
</DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</DropdownMenuPrimitive.CheckboxItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuRadioGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.RadioGroup
|
||||||
|
data-slot="dropdown-menu-radio-group"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuRadioItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.RadioItem
|
||||||
|
data-slot="dropdown-menu-radio-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
<CircleIcon className="size-2 fill-current" />
|
||||||
|
</DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</DropdownMenuPrimitive.RadioItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuLabel({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Label
|
||||||
|
data-slot="dropdown-menu-label"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Separator
|
||||||
|
data-slot="dropdown-menu-separator"
|
||||||
|
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuShortcut({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="dropdown-menu-shortcut"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSub({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||||
|
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSubTrigger({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.SubTrigger
|
||||||
|
data-slot="dropdown-menu-sub-trigger"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronRightIcon className="ml-auto size-4" />
|
||||||
|
</DropdownMenuPrimitive.SubTrigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSubContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.SubContent
|
||||||
|
data-slot="dropdown-menu-sub-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuPortal,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuGroup,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuCheckboxItem,
|
||||||
|
DropdownMenuRadioGroup,
|
||||||
|
DropdownMenuRadioItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuShortcut,
|
||||||
|
DropdownMenuSub,
|
||||||
|
DropdownMenuSubTrigger,
|
||||||
|
DropdownMenuSubContent,
|
||||||
|
}
|
||||||
104
frontend/src/components/ui/empty.tsx
Normal file
104
frontend/src/components/ui/empty.tsx
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Empty({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="empty"
|
||||||
|
className={cn(
|
||||||
|
"flex min-w-0 flex-1 flex-col items-center justify-center gap-6 rounded-lg border-dashed p-6 text-center text-balance md:p-12",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="empty-header"
|
||||||
|
className={cn(
|
||||||
|
"flex max-w-sm flex-col items-center gap-2 text-center",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const emptyMediaVariants = cva(
|
||||||
|
"flex shrink-0 items-center justify-center mb-2 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-transparent",
|
||||||
|
icon: "bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*='size-'])]:size-6",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function EmptyMedia({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof emptyMediaVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="empty-icon"
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(emptyMediaVariants({ variant, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="empty-title"
|
||||||
|
className={cn("text-lg font-medium tracking-tight", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="empty-description"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground [&>a:hover]:text-primary text-sm/relaxed [&>a]:underline [&>a]:underline-offset-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="empty-content"
|
||||||
|
className={cn(
|
||||||
|
"flex w-full max-w-sm min-w-0 flex-col items-center gap-4 text-sm text-balance",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Empty,
|
||||||
|
EmptyHeader,
|
||||||
|
EmptyTitle,
|
||||||
|
EmptyDescription,
|
||||||
|
EmptyContent,
|
||||||
|
EmptyMedia,
|
||||||
|
}
|
||||||
248
frontend/src/components/ui/field.tsx
Normal file
248
frontend/src/components/ui/field.tsx
Normal file
@@ -0,0 +1,248 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useMemo } from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Label } from "@/components/ui/label"
|
||||||
|
import { Separator } from "@/components/ui/separator"
|
||||||
|
|
||||||
|
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
|
||||||
|
return (
|
||||||
|
<fieldset
|
||||||
|
data-slot="field-set"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col gap-6",
|
||||||
|
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldLegend({
|
||||||
|
className,
|
||||||
|
variant = "legend",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
|
||||||
|
return (
|
||||||
|
<legend
|
||||||
|
data-slot="field-legend"
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"mb-3 font-medium",
|
||||||
|
"data-[variant=legend]:text-base",
|
||||||
|
"data-[variant=label]:text-sm",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="field-group"
|
||||||
|
className={cn(
|
||||||
|
"group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const fieldVariants = cva(
|
||||||
|
"group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
orientation: {
|
||||||
|
vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"],
|
||||||
|
horizontal: [
|
||||||
|
"flex-row items-center",
|
||||||
|
"[&>[data-slot=field-label]]:flex-auto",
|
||||||
|
"has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
||||||
|
],
|
||||||
|
responsive: [
|
||||||
|
"flex-col [&>*]:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto",
|
||||||
|
"@md/field-group:[&>[data-slot=field-label]]:flex-auto",
|
||||||
|
"@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
orientation: "vertical",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Field({
|
||||||
|
className,
|
||||||
|
orientation = "vertical",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="group"
|
||||||
|
data-slot="field"
|
||||||
|
data-orientation={orientation}
|
||||||
|
className={cn(fieldVariants({ orientation }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="field-content"
|
||||||
|
className={cn(
|
||||||
|
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldLabel({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof Label>) {
|
||||||
|
return (
|
||||||
|
<Label
|
||||||
|
data-slot="field-label"
|
||||||
|
className={cn(
|
||||||
|
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
|
||||||
|
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4",
|
||||||
|
"has-data-[state=checked]:bg-primary/5 has-data-[state=checked]:border-primary dark:has-data-[state=checked]:bg-primary/10",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="field-label"
|
||||||
|
className={cn(
|
||||||
|
"flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-slot="field-description"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground text-sm leading-normal font-normal group-has-[[data-orientation=horizontal]]/field:text-balance",
|
||||||
|
"last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
|
||||||
|
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldSeparator({
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
children?: React.ReactNode
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="field-separator"
|
||||||
|
data-content={!!children}
|
||||||
|
className={cn(
|
||||||
|
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<Separator className="absolute inset-0 top-1/2" />
|
||||||
|
{children && (
|
||||||
|
<span
|
||||||
|
className="bg-background text-muted-foreground relative mx-auto block w-fit px-2"
|
||||||
|
data-slot="field-separator-content"
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldError({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
errors,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
errors?: Array<{ message?: string } | undefined>
|
||||||
|
}) {
|
||||||
|
const content = useMemo(() => {
|
||||||
|
if (children) {
|
||||||
|
return children
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!errors?.length) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const uniqueErrors = [
|
||||||
|
...new Map(errors.map((error) => [error?.message, error])).values(),
|
||||||
|
]
|
||||||
|
|
||||||
|
if (uniqueErrors?.length == 1) {
|
||||||
|
return uniqueErrors[0]?.message
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ul className="ml-4 flex list-disc flex-col gap-1">
|
||||||
|
{uniqueErrors.map(
|
||||||
|
(error, index) =>
|
||||||
|
error?.message && <li key={index}>{error.message}</li>
|
||||||
|
)}
|
||||||
|
</ul>
|
||||||
|
)
|
||||||
|
}, [children, errors])
|
||||||
|
|
||||||
|
if (!content) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="alert"
|
||||||
|
data-slot="field-error"
|
||||||
|
className={cn("text-destructive text-sm font-normal", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{content}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Field,
|
||||||
|
FieldLabel,
|
||||||
|
FieldDescription,
|
||||||
|
FieldError,
|
||||||
|
FieldGroup,
|
||||||
|
FieldLegend,
|
||||||
|
FieldSeparator,
|
||||||
|
FieldSet,
|
||||||
|
FieldContent,
|
||||||
|
FieldTitle,
|
||||||
|
}
|
||||||
167
frontend/src/components/ui/form.tsx
Normal file
167
frontend/src/components/ui/form.tsx
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import type * as LabelPrimitive from "@radix-ui/react-label"
|
||||||
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
FormProvider,
|
||||||
|
useFormContext,
|
||||||
|
useFormState,
|
||||||
|
type ControllerProps,
|
||||||
|
type FieldPath,
|
||||||
|
type FieldValues,
|
||||||
|
} from "react-hook-form"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Label } from "@/components/ui/label"
|
||||||
|
|
||||||
|
const Form = FormProvider
|
||||||
|
|
||||||
|
type FormFieldContextValue<
|
||||||
|
TFieldValues extends FieldValues = FieldValues,
|
||||||
|
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||||
|
> = {
|
||||||
|
name: TName
|
||||||
|
}
|
||||||
|
|
||||||
|
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||||
|
{} as FormFieldContextValue
|
||||||
|
)
|
||||||
|
|
||||||
|
const FormField = <
|
||||||
|
TFieldValues extends FieldValues = FieldValues,
|
||||||
|
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||||
|
>({
|
||||||
|
...props
|
||||||
|
}: ControllerProps<TFieldValues, TName>) => {
|
||||||
|
return (
|
||||||
|
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||||
|
<Controller {...props} />
|
||||||
|
</FormFieldContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const useFormField = () => {
|
||||||
|
const fieldContext = React.useContext(FormFieldContext)
|
||||||
|
const itemContext = React.useContext(FormItemContext)
|
||||||
|
const { getFieldState } = useFormContext()
|
||||||
|
const formState = useFormState({ name: fieldContext.name })
|
||||||
|
const fieldState = getFieldState(fieldContext.name, formState)
|
||||||
|
|
||||||
|
if (!fieldContext) {
|
||||||
|
throw new Error("useFormField should be used within <FormField>")
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id } = itemContext
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name: fieldContext.name,
|
||||||
|
formItemId: `${id}-form-item`,
|
||||||
|
formDescriptionId: `${id}-form-item-description`,
|
||||||
|
formMessageId: `${id}-form-item-message`,
|
||||||
|
...fieldState,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type FormItemContextValue = {
|
||||||
|
id: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||||
|
{} as FormItemContextValue
|
||||||
|
)
|
||||||
|
|
||||||
|
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
const id = React.useId()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FormItemContext.Provider value={{ id }}>
|
||||||
|
<div
|
||||||
|
data-slot="form-item"
|
||||||
|
className={cn("grid gap-2", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</FormItemContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FormLabel({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||||
|
const { error, formItemId } = useFormField()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Label
|
||||||
|
data-slot="form-label"
|
||||||
|
data-error={!!error}
|
||||||
|
className={cn("data-[error=true]:text-destructive", className)}
|
||||||
|
htmlFor={formItemId}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
||||||
|
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Slot
|
||||||
|
data-slot="form-control"
|
||||||
|
id={formItemId}
|
||||||
|
aria-describedby={
|
||||||
|
!error
|
||||||
|
? `${formDescriptionId}`
|
||||||
|
: `${formDescriptionId} ${formMessageId}`
|
||||||
|
}
|
||||||
|
aria-invalid={!!error}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
|
const { formDescriptionId } = useFormField()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-slot="form-description"
|
||||||
|
id={formDescriptionId}
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
|
const { error, formMessageId } = useFormField()
|
||||||
|
const body = error ? String(error?.message ?? "") : props.children
|
||||||
|
|
||||||
|
if (!body) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-slot="form-message"
|
||||||
|
id={formMessageId}
|
||||||
|
className={cn("text-destructive text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{body}
|
||||||
|
</p>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
useFormField,
|
||||||
|
Form,
|
||||||
|
FormItem,
|
||||||
|
FormLabel,
|
||||||
|
FormControl,
|
||||||
|
FormDescription,
|
||||||
|
FormMessage,
|
||||||
|
FormField,
|
||||||
|
}
|
||||||
44
frontend/src/components/ui/hover-card.tsx
Normal file
44
frontend/src/components/ui/hover-card.tsx
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function HoverCard({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
|
||||||
|
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function HoverCardTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function HoverCardContent({
|
||||||
|
className,
|
||||||
|
align = "center",
|
||||||
|
sideOffset = 4,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<HoverCardPrimitive.Portal data-slot="hover-card-portal">
|
||||||
|
<HoverCardPrimitive.Content
|
||||||
|
data-slot="hover-card-content"
|
||||||
|
align={align}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</HoverCardPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { HoverCard, HoverCardTrigger, HoverCardContent }
|
||||||
170
frontend/src/components/ui/input-group.tsx
Normal file
170
frontend/src/components/ui/input-group.tsx
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Input } from "@/components/ui/input"
|
||||||
|
import { Textarea } from "@/components/ui/textarea"
|
||||||
|
|
||||||
|
function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="input-group"
|
||||||
|
role="group"
|
||||||
|
className={cn(
|
||||||
|
"group/input-group border-input dark:bg-input/30 relative flex w-full items-center rounded-md border shadow-xs transition-[color,box-shadow] outline-none",
|
||||||
|
"h-9 min-w-0 has-[>textarea]:h-auto",
|
||||||
|
|
||||||
|
// Variants based on alignment.
|
||||||
|
"has-[>[data-align=inline-start]]:[&>input]:pl-2",
|
||||||
|
"has-[>[data-align=inline-end]]:[&>input]:pr-2",
|
||||||
|
"has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3",
|
||||||
|
"has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3",
|
||||||
|
|
||||||
|
// Focus state.
|
||||||
|
"has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot=input-group-control]:focus-visible]:ring-[3px]",
|
||||||
|
|
||||||
|
// Error state.
|
||||||
|
"has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40",
|
||||||
|
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const inputGroupAddonVariants = cva(
|
||||||
|
"text-muted-foreground flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium select-none [&>svg:not([class*='size-'])]:size-4 [&>kbd]:rounded-[calc(var(--radius)-5px)] group-data-[disabled=true]/input-group:opacity-50",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
align: {
|
||||||
|
"inline-start":
|
||||||
|
"order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]",
|
||||||
|
"inline-end":
|
||||||
|
"order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]",
|
||||||
|
"block-start":
|
||||||
|
"order-first w-full justify-start px-3 pt-3 [.border-b]:pb-3 group-has-[>input]/input-group:pt-2.5",
|
||||||
|
"block-end":
|
||||||
|
"order-last w-full justify-start px-3 pb-3 [.border-t]:pt-3 group-has-[>input]/input-group:pb-2.5",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
align: "inline-start",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function InputGroupAddon({
|
||||||
|
className,
|
||||||
|
align = "inline-start",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="group"
|
||||||
|
data-slot="input-group-addon"
|
||||||
|
data-align={align}
|
||||||
|
className={cn(inputGroupAddonVariants({ align }), className)}
|
||||||
|
onClick={(e) => {
|
||||||
|
if ((e.target as HTMLElement).closest("button")) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
e.currentTarget.parentElement?.querySelector("input")?.focus()
|
||||||
|
}}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const inputGroupButtonVariants = cva(
|
||||||
|
"text-sm shadow-none flex gap-2 items-center",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
size: {
|
||||||
|
xs: "h-6 gap-1 px-2 rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-3.5 has-[>svg]:px-2",
|
||||||
|
sm: "h-8 px-2.5 gap-1.5 rounded-md has-[>svg]:px-2.5",
|
||||||
|
"icon-xs":
|
||||||
|
"size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0",
|
||||||
|
"icon-sm": "size-8 p-0 has-[>svg]:p-0",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
size: "xs",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function InputGroupButton({
|
||||||
|
className,
|
||||||
|
type = "button",
|
||||||
|
variant = "ghost",
|
||||||
|
size = "xs",
|
||||||
|
...props
|
||||||
|
}: Omit<React.ComponentProps<typeof Button>, "size"> &
|
||||||
|
VariantProps<typeof inputGroupButtonVariants>) {
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
type={type}
|
||||||
|
data-size={size}
|
||||||
|
variant={variant}
|
||||||
|
className={cn(inputGroupButtonVariants({ size }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground flex items-center gap-2 text-sm [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function InputGroupInput({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"input">) {
|
||||||
|
return (
|
||||||
|
<Input
|
||||||
|
data-slot="input-group-control"
|
||||||
|
className={cn(
|
||||||
|
"flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function InputGroupTextarea({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"textarea">) {
|
||||||
|
return (
|
||||||
|
<Textarea
|
||||||
|
data-slot="input-group-control"
|
||||||
|
className={cn(
|
||||||
|
"flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
InputGroup,
|
||||||
|
InputGroupAddon,
|
||||||
|
InputGroupButton,
|
||||||
|
InputGroupText,
|
||||||
|
InputGroupInput,
|
||||||
|
InputGroupTextarea,
|
||||||
|
}
|
||||||
77
frontend/src/components/ui/input-otp.tsx
Normal file
77
frontend/src/components/ui/input-otp.tsx
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { OTPInput, OTPInputContext } from "input-otp"
|
||||||
|
import { MinusIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function InputOTP({
|
||||||
|
className,
|
||||||
|
containerClassName,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof OTPInput> & {
|
||||||
|
containerClassName?: string
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<OTPInput
|
||||||
|
data-slot="input-otp"
|
||||||
|
containerClassName={cn(
|
||||||
|
"flex items-center gap-2 has-disabled:opacity-50",
|
||||||
|
containerClassName
|
||||||
|
)}
|
||||||
|
className={cn("disabled:cursor-not-allowed", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="input-otp-group"
|
||||||
|
className={cn("flex items-center", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function InputOTPSlot({
|
||||||
|
index,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
index: number
|
||||||
|
}) {
|
||||||
|
const inputOTPContext = React.useContext(OTPInputContext)
|
||||||
|
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="input-otp-slot"
|
||||||
|
data-active={isActive}
|
||||||
|
className={cn(
|
||||||
|
"data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{char}
|
||||||
|
{hasFakeCaret && (
|
||||||
|
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
|
||||||
|
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div data-slot="input-otp-separator" role="separator" {...props}>
|
||||||
|
<MinusIcon />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }
|
||||||
21
frontend/src/components/ui/input.tsx
Normal file
21
frontend/src/components/ui/input.tsx
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
type={type}
|
||||||
|
data-slot="input"
|
||||||
|
className={cn(
|
||||||
|
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||||
|
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||||
|
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Input }
|
||||||
193
frontend/src/components/ui/item.tsx
Normal file
193
frontend/src/components/ui/item.tsx
Normal file
@@ -0,0 +1,193 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Separator } from "@/components/ui/separator"
|
||||||
|
|
||||||
|
function ItemGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="list"
|
||||||
|
data-slot="item-group"
|
||||||
|
className={cn("group/item-group flex flex-col", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof Separator>) {
|
||||||
|
return (
|
||||||
|
<Separator
|
||||||
|
data-slot="item-separator"
|
||||||
|
orientation="horizontal"
|
||||||
|
className={cn("my-0", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemVariants = cva(
|
||||||
|
"group/item flex items-center border border-transparent text-sm rounded-md transition-colors [a]:hover:bg-accent/50 [a]:transition-colors duration-100 flex-wrap outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-transparent",
|
||||||
|
outline: "border-border",
|
||||||
|
muted: "bg-muted/50",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default: "p-4 gap-4 ",
|
||||||
|
sm: "py-3 px-4 gap-2.5",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Item({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
size = "default",
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> &
|
||||||
|
VariantProps<typeof itemVariants> & { asChild?: boolean }) {
|
||||||
|
const Comp = asChild ? Slot : "div"
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="item"
|
||||||
|
data-variant={variant}
|
||||||
|
data-size={size}
|
||||||
|
className={cn(itemVariants({ variant, size, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemMediaVariants = cva(
|
||||||
|
"flex shrink-0 items-center justify-center gap-2 group-has-[[data-slot=item-description]]/item:self-start [&_svg]:pointer-events-none group-has-[[data-slot=item-description]]/item:translate-y-0.5",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-transparent",
|
||||||
|
icon: "size-8 border rounded-sm bg-muted [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
image:
|
||||||
|
"size-10 rounded-sm overflow-hidden [&_img]:size-full [&_img]:object-cover",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function ItemMedia({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof itemMediaVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-media"
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(itemMediaVariants({ variant, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-content"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-1 flex-col gap-1 [&+[data-slot=item-content]]:flex-none",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-title"
|
||||||
|
className={cn(
|
||||||
|
"flex w-fit items-center gap-2 text-sm leading-snug font-medium",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-slot="item-description"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground line-clamp-2 text-sm leading-normal font-normal text-balance",
|
||||||
|
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemActions({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-actions"
|
||||||
|
className={cn("flex items-center gap-2", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-header"
|
||||||
|
className={cn(
|
||||||
|
"flex basis-full items-center justify-between gap-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-footer"
|
||||||
|
className={cn(
|
||||||
|
"flex basis-full items-center justify-between gap-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Item,
|
||||||
|
ItemMedia,
|
||||||
|
ItemContent,
|
||||||
|
ItemActions,
|
||||||
|
ItemGroup,
|
||||||
|
ItemSeparator,
|
||||||
|
ItemTitle,
|
||||||
|
ItemDescription,
|
||||||
|
ItemHeader,
|
||||||
|
ItemFooter,
|
||||||
|
}
|
||||||
28
frontend/src/components/ui/kbd.tsx
Normal file
28
frontend/src/components/ui/kbd.tsx
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
|
||||||
|
return (
|
||||||
|
<kbd
|
||||||
|
data-slot="kbd"
|
||||||
|
className={cn(
|
||||||
|
"bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none",
|
||||||
|
"[&_svg:not([class*='size-'])]:size-3",
|
||||||
|
"[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function KbdGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<kbd
|
||||||
|
data-slot="kbd-group"
|
||||||
|
className={cn("inline-flex items-center gap-1", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Kbd, KbdGroup }
|
||||||
24
frontend/src/components/ui/label.tsx
Normal file
24
frontend/src/components/ui/label.tsx
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Label({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<LabelPrimitive.Root
|
||||||
|
data-slot="label"
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Label }
|
||||||
276
frontend/src/components/ui/menubar.tsx
Normal file
276
frontend/src/components/ui/menubar.tsx
Normal file
@@ -0,0 +1,276 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as MenubarPrimitive from "@radix-ui/react-menubar"
|
||||||
|
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Menubar({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.Root
|
||||||
|
data-slot="menubar"
|
||||||
|
className={cn(
|
||||||
|
"bg-background flex h-9 items-center gap-1 rounded-md border p-1 shadow-xs",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarMenu({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
|
||||||
|
return <MenubarPrimitive.Menu data-slot="menubar-menu" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
|
||||||
|
return <MenubarPrimitive.Group data-slot="menubar-group" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
|
||||||
|
return <MenubarPrimitive.Portal data-slot="menubar-portal" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarRadioGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.RadioGroup data-slot="menubar-radio-group" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarTrigger({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.Trigger
|
||||||
|
data-slot="menubar-trigger"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex items-center rounded-sm px-2 py-1 text-sm font-medium outline-hidden select-none",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarContent({
|
||||||
|
className,
|
||||||
|
align = "start",
|
||||||
|
alignOffset = -4,
|
||||||
|
sideOffset = 8,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<MenubarPortal>
|
||||||
|
<MenubarPrimitive.Content
|
||||||
|
data-slot="menubar-content"
|
||||||
|
align={align}
|
||||||
|
alignOffset={alignOffset}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[12rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-md",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</MenubarPortal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarItem({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Item> & {
|
||||||
|
inset?: boolean
|
||||||
|
variant?: "default" | "destructive"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.Item
|
||||||
|
data-slot="menubar-item"
|
||||||
|
data-inset={inset}
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarCheckboxItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
checked,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.CheckboxItem>) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.CheckboxItem
|
||||||
|
data-slot="menubar-checkbox-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
checked={checked}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<MenubarPrimitive.ItemIndicator>
|
||||||
|
<CheckIcon className="size-4" />
|
||||||
|
</MenubarPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</MenubarPrimitive.CheckboxItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarRadioItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.RadioItem>) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.RadioItem
|
||||||
|
data-slot="menubar-radio-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<MenubarPrimitive.ItemIndicator>
|
||||||
|
<CircleIcon className="size-2 fill-current" />
|
||||||
|
</MenubarPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</MenubarPrimitive.RadioItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarLabel({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Label> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.Label
|
||||||
|
data-slot="menubar-label"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Separator>) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.Separator
|
||||||
|
data-slot="menubar-separator"
|
||||||
|
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarShortcut({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="menubar-shortcut"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarSub({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
|
||||||
|
return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarSubTrigger({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.SubTrigger> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.SubTrigger
|
||||||
|
data-slot="menubar-sub-trigger"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[inset]:pl-8",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronRightIcon className="ml-auto h-4 w-4" />
|
||||||
|
</MenubarPrimitive.SubTrigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenubarSubContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof MenubarPrimitive.SubContent>) {
|
||||||
|
return (
|
||||||
|
<MenubarPrimitive.SubContent
|
||||||
|
data-slot="menubar-sub-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Menubar,
|
||||||
|
MenubarPortal,
|
||||||
|
MenubarMenu,
|
||||||
|
MenubarTrigger,
|
||||||
|
MenubarContent,
|
||||||
|
MenubarGroup,
|
||||||
|
MenubarSeparator,
|
||||||
|
MenubarLabel,
|
||||||
|
MenubarItem,
|
||||||
|
MenubarShortcut,
|
||||||
|
MenubarCheckboxItem,
|
||||||
|
MenubarRadioGroup,
|
||||||
|
MenubarRadioItem,
|
||||||
|
MenubarSub,
|
||||||
|
MenubarSubTrigger,
|
||||||
|
MenubarSubContent,
|
||||||
|
}
|
||||||
168
frontend/src/components/ui/navigation-menu.tsx
Normal file
168
frontend/src/components/ui/navigation-menu.tsx
Normal file
@@ -0,0 +1,168 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
|
||||||
|
import { cva } from "class-variance-authority"
|
||||||
|
import { ChevronDownIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function NavigationMenu({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
viewport = true,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.Root> & {
|
||||||
|
viewport?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<NavigationMenuPrimitive.Root
|
||||||
|
data-slot="navigation-menu"
|
||||||
|
data-viewport={viewport}
|
||||||
|
className={cn(
|
||||||
|
"group/navigation-menu relative flex max-w-max flex-1 items-center justify-center",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
{viewport && <NavigationMenuViewport />}
|
||||||
|
</NavigationMenuPrimitive.Root>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NavigationMenuList({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.List>) {
|
||||||
|
return (
|
||||||
|
<NavigationMenuPrimitive.List
|
||||||
|
data-slot="navigation-menu-list"
|
||||||
|
className={cn(
|
||||||
|
"group flex flex-1 list-none items-center justify-center gap-1",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NavigationMenuItem({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.Item>) {
|
||||||
|
return (
|
||||||
|
<NavigationMenuPrimitive.Item
|
||||||
|
data-slot="navigation-menu-item"
|
||||||
|
className={cn("relative", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const navigationMenuTriggerStyle = cva(
|
||||||
|
"group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:hover:bg-accent data-[state=open]:text-accent-foreground data-[state=open]:focus:bg-accent data-[state=open]:bg-accent/50 focus-visible:ring-ring/50 outline-none transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1"
|
||||||
|
)
|
||||||
|
|
||||||
|
function NavigationMenuTrigger({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<NavigationMenuPrimitive.Trigger
|
||||||
|
data-slot="navigation-menu-trigger"
|
||||||
|
className={cn(navigationMenuTriggerStyle(), "group", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}{" "}
|
||||||
|
<ChevronDownIcon
|
||||||
|
className="relative top-[1px] ml-1 size-3 transition duration-300 group-data-[state=open]:rotate-180"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
</NavigationMenuPrimitive.Trigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NavigationMenuContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<NavigationMenuPrimitive.Content
|
||||||
|
data-slot="navigation-menu-content"
|
||||||
|
className={cn(
|
||||||
|
"data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 top-0 left-0 w-full p-2 pr-2.5 md:absolute md:w-auto",
|
||||||
|
"group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-md group-data-[viewport=false]/navigation-menu:border group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:duration-200 **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NavigationMenuViewport({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.Viewport>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"absolute top-full left-0 isolate z-50 flex justify-center"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<NavigationMenuPrimitive.Viewport
|
||||||
|
data-slot="navigation-menu-viewport"
|
||||||
|
className={cn(
|
||||||
|
"origin-top-center bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border shadow md:w-[var(--radix-navigation-menu-viewport-width)]",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NavigationMenuLink({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.Link>) {
|
||||||
|
return (
|
||||||
|
<NavigationMenuPrimitive.Link
|
||||||
|
data-slot="navigation-menu-link"
|
||||||
|
className={cn(
|
||||||
|
"data-[active=true]:focus:bg-accent data-[active=true]:hover:bg-accent data-[active=true]:bg-accent/50 data-[active=true]:text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus-visible:ring-ring/50 [&_svg:not([class*='text-'])]:text-muted-foreground flex flex-col gap-1 rounded-sm p-2 text-sm transition-all outline-none focus-visible:ring-[3px] focus-visible:outline-1 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NavigationMenuIndicator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NavigationMenuPrimitive.Indicator>) {
|
||||||
|
return (
|
||||||
|
<NavigationMenuPrimitive.Indicator
|
||||||
|
data-slot="navigation-menu-indicator"
|
||||||
|
className={cn(
|
||||||
|
"data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className="bg-border relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm shadow-md" />
|
||||||
|
</NavigationMenuPrimitive.Indicator>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
NavigationMenu,
|
||||||
|
NavigationMenuList,
|
||||||
|
NavigationMenuItem,
|
||||||
|
NavigationMenuContent,
|
||||||
|
NavigationMenuTrigger,
|
||||||
|
NavigationMenuLink,
|
||||||
|
NavigationMenuIndicator,
|
||||||
|
NavigationMenuViewport,
|
||||||
|
navigationMenuTriggerStyle,
|
||||||
|
}
|
||||||
127
frontend/src/components/ui/pagination.tsx
Normal file
127
frontend/src/components/ui/pagination.tsx
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import {
|
||||||
|
ChevronLeftIcon,
|
||||||
|
ChevronRightIcon,
|
||||||
|
MoreHorizontalIcon,
|
||||||
|
} from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { buttonVariants, type Button } from "@/components/ui/button"
|
||||||
|
|
||||||
|
function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
|
||||||
|
return (
|
||||||
|
<nav
|
||||||
|
role="navigation"
|
||||||
|
aria-label="pagination"
|
||||||
|
data-slot="pagination"
|
||||||
|
className={cn("mx-auto flex w-full justify-center", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PaginationContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"ul">) {
|
||||||
|
return (
|
||||||
|
<ul
|
||||||
|
data-slot="pagination-content"
|
||||||
|
className={cn("flex flex-row items-center gap-1", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PaginationItem({ ...props }: React.ComponentProps<"li">) {
|
||||||
|
return <li data-slot="pagination-item" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
type PaginationLinkProps = {
|
||||||
|
isActive?: boolean
|
||||||
|
} & Pick<React.ComponentProps<typeof Button>, "size"> &
|
||||||
|
React.ComponentProps<"a">
|
||||||
|
|
||||||
|
function PaginationLink({
|
||||||
|
className,
|
||||||
|
isActive,
|
||||||
|
size = "icon",
|
||||||
|
...props
|
||||||
|
}: PaginationLinkProps) {
|
||||||
|
return (
|
||||||
|
<a
|
||||||
|
aria-current={isActive ? "page" : undefined}
|
||||||
|
data-slot="pagination-link"
|
||||||
|
data-active={isActive}
|
||||||
|
className={cn(
|
||||||
|
buttonVariants({
|
||||||
|
variant: isActive ? "outline" : "ghost",
|
||||||
|
size,
|
||||||
|
}),
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PaginationPrevious({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof PaginationLink>) {
|
||||||
|
return (
|
||||||
|
<PaginationLink
|
||||||
|
aria-label="Go to previous page"
|
||||||
|
size="default"
|
||||||
|
className={cn("gap-1 px-2.5 sm:pl-2.5", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ChevronLeftIcon />
|
||||||
|
<span className="hidden sm:block">Previous</span>
|
||||||
|
</PaginationLink>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PaginationNext({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof PaginationLink>) {
|
||||||
|
return (
|
||||||
|
<PaginationLink
|
||||||
|
aria-label="Go to next page"
|
||||||
|
size="default"
|
||||||
|
className={cn("gap-1 px-2.5 sm:pr-2.5", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="hidden sm:block">Next</span>
|
||||||
|
<ChevronRightIcon />
|
||||||
|
</PaginationLink>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PaginationEllipsis({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
aria-hidden
|
||||||
|
data-slot="pagination-ellipsis"
|
||||||
|
className={cn("flex size-9 items-center justify-center", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<MoreHorizontalIcon className="size-4" />
|
||||||
|
<span className="sr-only">More pages</span>
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Pagination,
|
||||||
|
PaginationContent,
|
||||||
|
PaginationLink,
|
||||||
|
PaginationItem,
|
||||||
|
PaginationPrevious,
|
||||||
|
PaginationNext,
|
||||||
|
PaginationEllipsis,
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user