-
Notifications
You must be signed in to change notification settings - Fork 0
[2b] User and department management #30
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
andrmaz
wants to merge
6
commits into
develop
Choose a base branch
from
cursor/user-department-management-70bf
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
3c7f271
feat(api,web): department CRUD, user assignment, and session enrichment
cursoragent b4eb800
📝 CodeRabbit Chat: Generate Unit Tests for PR Changes
coderabbitai[bot] 201ce29
fix(web): address PR review comments on admin users flow
cursoragent 51282e7
fix: apply CodeRabbit auto-fixes
coderabbitai[bot] 71b70ae
fix: address PR review comments on admin auth and validation
cursoragent 197ed26
fix(web): wire OAuth callback to set admin session cookie
cursoragent File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| export interface CreateDepartmentDto { | ||
| name: string; | ||
| } | ||
|
|
||
| export interface DepartmentResponseDto { | ||
| id: string; | ||
| name: string; | ||
| organizationId: string; | ||
| createdAt: string; | ||
| updatedAt: string; | ||
| } |
123 changes: 123 additions & 0 deletions
123
apps/api/src/admin/departments/department.service.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| import { Test, type TestingModule } from "@nestjs/testing"; | ||
| import { ConflictException, NotFoundException } from "@nestjs/common"; | ||
| import { DepartmentService } from "./department.service"; | ||
| import { PrismaService } from "../../prisma/prisma.service"; | ||
|
|
||
| const now = new Date("2024-01-01T00:00:00Z"); | ||
|
|
||
| const mockOrg = { id: "org-1", name: "acme.com" }; | ||
|
|
||
| const mockDept = { | ||
| id: "dept-1", | ||
| name: "Engineering", | ||
| organizationId: "org-1", | ||
| createdAt: now, | ||
| updatedAt: now, | ||
| }; | ||
|
|
||
| const mockPrisma = { | ||
| organization: { | ||
| findUnique: jest.fn(), | ||
| }, | ||
| department: { | ||
| findMany: jest.fn(), | ||
| create: jest.fn(), | ||
| }, | ||
| }; | ||
|
|
||
| describe("DepartmentService", () => { | ||
| let service: DepartmentService; | ||
|
|
||
| beforeEach(async () => { | ||
| jest.clearAllMocks(); | ||
|
|
||
| const module: TestingModule = await Test.createTestingModule({ | ||
| providers: [ | ||
| DepartmentService, | ||
| { provide: PrismaService, useValue: mockPrisma }, | ||
| ], | ||
| }).compile(); | ||
|
|
||
| service = module.get<DepartmentService>(DepartmentService); | ||
| }); | ||
|
|
||
| describe("findAllByOrganization", () => { | ||
| it("returns departments scoped to the organization, ordered by createdAt desc", async () => { | ||
| mockPrisma.organization.findUnique.mockResolvedValue(mockOrg); | ||
| mockPrisma.department.findMany.mockResolvedValue([mockDept]); | ||
|
|
||
| const result = await service.findAllByOrganization("org-1"); | ||
|
|
||
| expect(result).toEqual([mockDept]); | ||
| expect(mockPrisma.department.findMany).toHaveBeenCalledWith({ | ||
| where: { organizationId: "org-1" }, | ||
| orderBy: { createdAt: "desc" }, | ||
| }); | ||
| }); | ||
|
|
||
| it("returns an empty array when the organization has no departments", async () => { | ||
| mockPrisma.organization.findUnique.mockResolvedValue(mockOrg); | ||
| mockPrisma.department.findMany.mockResolvedValue([]); | ||
|
|
||
| const result = await service.findAllByOrganization("org-1"); | ||
|
|
||
| expect(result).toEqual([]); | ||
| }); | ||
|
|
||
| it("throws NotFoundException when the organization does not exist", async () => { | ||
| mockPrisma.organization.findUnique.mockResolvedValue(null); | ||
|
|
||
| await expect( | ||
| service.findAllByOrganization("missing-org"), | ||
| ).rejects.toThrow(NotFoundException); | ||
| expect(mockPrisma.department.findMany).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("create", () => { | ||
| it("creates and returns the department scoped to the organization", async () => { | ||
| mockPrisma.organization.findUnique.mockResolvedValue(mockOrg); | ||
| mockPrisma.department.create.mockResolvedValue(mockDept); | ||
|
|
||
| const result = await service.create("org-1", { name: "Engineering" }); | ||
|
|
||
| expect(result).toEqual(mockDept); | ||
| expect(mockPrisma.department.create).toHaveBeenCalledWith({ | ||
| data: { name: "Engineering", organizationId: "org-1" }, | ||
| }); | ||
| }); | ||
|
|
||
| it("throws NotFoundException when the organization does not exist", async () => { | ||
| mockPrisma.organization.findUnique.mockResolvedValue(null); | ||
|
|
||
| await expect( | ||
| service.create("missing-org", { name: "Engineering" }), | ||
| ).rejects.toThrow(NotFoundException); | ||
| expect(mockPrisma.department.create).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("throws ConflictException on P2002 unique constraint violation", async () => { | ||
| mockPrisma.organization.findUnique.mockResolvedValue(mockOrg); | ||
| const p2002 = Object.assign(new Error("Unique constraint failed"), { | ||
| code: "P2002", | ||
| }); | ||
| mockPrisma.department.create.mockRejectedValue(p2002); | ||
|
|
||
| await expect( | ||
| service.create("org-1", { name: "Engineering" }), | ||
| ).rejects.toThrow(ConflictException); | ||
| }); | ||
|
|
||
| it("re-throws non-P2002 database errors", async () => { | ||
| mockPrisma.organization.findUnique.mockResolvedValue(mockOrg); | ||
| const dbError = Object.assign(new Error("Connection refused"), { | ||
| code: "P1001", | ||
| }); | ||
| mockPrisma.department.create.mockRejectedValue(dbError); | ||
|
|
||
| await expect( | ||
| service.create("org-1", { name: "Engineering" }), | ||
| ).rejects.toThrow("Connection refused"); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import { | ||
| Injectable, | ||
| ConflictException, | ||
| NotFoundException, | ||
| } from "@nestjs/common"; | ||
| import { PrismaService } from "../../prisma/prisma.service"; | ||
| import type { Department } from "db/client"; | ||
| import type { CreateDepartmentDto } from "./department.dto"; | ||
| import { isPrismaUniqueConstraintError } from "../../common/prisma-errors"; | ||
|
|
||
| @Injectable() | ||
| export class DepartmentService { | ||
| constructor(private readonly prisma: PrismaService) {} | ||
|
|
||
| /** | ||
| * Lists departments scoped to a single Organization. | ||
| * Throws NotFoundException up front so callers get a clear 404 instead | ||
| * of a silently empty list when the organizationId is bogus. | ||
| */ | ||
| async findAllByOrganization(organizationId: string): Promise<Department[]> { | ||
| await this.ensureOrganizationExists(organizationId); | ||
| return this.prisma.department.findMany({ | ||
| where: { organizationId }, | ||
| orderBy: { createdAt: "desc" }, | ||
| }); | ||
| } | ||
|
|
||
| async create( | ||
| organizationId: string, | ||
| dto: CreateDepartmentDto, | ||
| ): Promise<Department> { | ||
| await this.ensureOrganizationExists(organizationId); | ||
|
|
||
| try { | ||
| return await this.prisma.department.create({ | ||
| data: { name: dto.name, organizationId }, | ||
| }); | ||
| } catch (err) { | ||
| if (isPrismaUniqueConstraintError(err)) { | ||
| throw new ConflictException( | ||
| `Department with name "${dto.name}" already exists in this organization`, | ||
| ); | ||
| } | ||
| throw err; | ||
| } | ||
| } | ||
|
|
||
| private async ensureOrganizationExists( | ||
| organizationId: string, | ||
| ): Promise<void> { | ||
| const org = await this.prisma.organization.findUnique({ | ||
| where: { id: organizationId }, | ||
| }); | ||
| if (!org) { | ||
| throw new NotFoundException( | ||
| `Organization with id "${organizationId}" not found`, | ||
| ); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| import { | ||
| Controller, | ||
| Get, | ||
| Post, | ||
| Param, | ||
| Body, | ||
| Req, | ||
| UseGuards, | ||
| HttpCode, | ||
| HttpStatus, | ||
| BadRequestException, | ||
| } from "@nestjs/common"; | ||
| import { AdminRoleGuard } from "../guards/admin-role.guard"; | ||
| import { assertAdminOrganizationAccess } from "../guards/assert-admin-organization"; | ||
| import { DepartmentService } from "./department.service"; | ||
| import type { | ||
| CreateDepartmentDto, | ||
| DepartmentResponseDto, | ||
| } from "./department.dto"; | ||
| import type { Department } from "db/client"; | ||
| import type { AuthenticatedUser } from "../../auth/auth.types"; | ||
|
|
||
| interface RequestWithUser { | ||
| user: AuthenticatedUser; | ||
| } | ||
|
|
||
| function toResponseDto(dept: Department): DepartmentResponseDto { | ||
| return { | ||
| id: dept.id, | ||
| name: dept.name, | ||
| organizationId: dept.organizationId, | ||
| createdAt: dept.createdAt.toISOString(), | ||
| updatedAt: dept.updatedAt.toISOString(), | ||
| }; | ||
| } | ||
|
|
||
| @Controller("api/admin/organizations/:organizationId/departments") | ||
| @UseGuards(AdminRoleGuard) | ||
| export class DepartmentsController { | ||
| constructor(private readonly departmentService: DepartmentService) {} | ||
|
|
||
| @Get() | ||
| @HttpCode(HttpStatus.OK) | ||
| async findAll( | ||
| @Req() req: RequestWithUser, | ||
| @Param("organizationId") organizationId: string, | ||
| ): Promise<DepartmentResponseDto[]> { | ||
| assertAdminOrganizationAccess(req.user.organizationId, organizationId); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed: |
||
| const departments = | ||
| await this.departmentService.findAllByOrganization(organizationId); | ||
| return departments.map(toResponseDto); | ||
| } | ||
|
|
||
| @Post() | ||
| @HttpCode(HttpStatus.CREATED) | ||
| async create( | ||
| @Req() req: RequestWithUser, | ||
| @Param("organizationId") organizationId: string, | ||
| @Body() body: CreateDepartmentDto, | ||
| ): Promise<DepartmentResponseDto> { | ||
| assertAdminOrganizationAccess(req.user.organizationId, organizationId); | ||
| if (!body.name || typeof body.name !== "string" || !body.name.trim()) { | ||
| throw new BadRequestException("name is required and must be a string"); | ||
| } | ||
| const dept = await this.departmentService.create(organizationId, { | ||
| name: body.name.trim(), | ||
| }); | ||
| return toResponseDto(dept); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.