Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions e2e/invitations.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { type Browser } from '@playwright/test';
import { expect, test } from 'e2e/utils';
import { ADMIN_FILE, INVITED_EMAIL, INVITED_FILE } from 'e2e/utils/constants';
import {
ADMIN_FILE,
INVITED_EMAIL,
INVITED_FILE,
ORG_SLUG,
} from 'e2e/utils/constants';

type Invitation = { id: string; email: string; status: string };
type Member = { user: { email: string } };
Expand All @@ -18,7 +23,7 @@ async function ensureInvitation(browser: Browser): Promise<string> {
try {
// 1. Get current org state
const orgResp = await adminContext.request.get(
'/api/rest/organizations/active'
`/api/rest/organizations/active?slug=${ORG_SLUG}`
);
const org = await orgResp.json();

Expand Down Expand Up @@ -50,7 +55,7 @@ async function ensureInvitation(browser: Browser): Promise<string> {

// 5. Get the new invitation ID
const orgResp2 = await adminContext.request.get(
'/api/rest/organizations/active'
`/api/rest/organizations/active?slug=${ORG_SLUG}`
);
const org2 = await orgResp2.json();
const invitation = (org2.invitations as Invitation[] | undefined)?.find(
Expand Down
7 changes: 6 additions & 1 deletion src/features/organization/manager/org-settings-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';

import { Route } from '@/routes/manager/$orgSlug/route';

const zFormFields = z.object({
name: z.string().min(1).max(100),
});
Expand All @@ -26,9 +28,12 @@ type FormFields = z.infer<typeof zFormFields>;
export const OrgSettingsCard = () => {
const { t } = useTranslation(['organization']);
const queryClient = useQueryClient();
const { orgSlug } = Route.useParams();

const orgQuery = useQuery(
orpc.organization.getActiveOrganization.queryOptions()
orpc.organization.getActiveOrganization.queryOptions({
input: { slug: orgSlug },
})
);

const form = useForm<FormFields>({
Expand Down
6 changes: 5 additions & 1 deletion src/features/organization/manager/page-organization.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,17 @@ import {
PageLayoutTopBar,
PageLayoutTopBarTitle,
} from '@/layout/manager/page-layout';
import { Route } from '@/routes/manager/$orgSlug/route';

export const PageOrganization = () => {
const { t } = useTranslation(['organization', 'common']);
const navigate = useNavigate();
const { orgSlug } = Route.useParams();

const orgQuery = useQuery(
orpc.organization.getActiveOrganization.queryOptions()
orpc.organization.getActiveOrganization.queryOptions({
input: { slug: orgSlug },
})
);

const deleteOrganization = useMutation(
Expand Down
11 changes: 7 additions & 4 deletions src/features/stats/manager/page-stats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,22 @@ import {
PageLayoutTopBar,
PageLayoutTopBarTitle,
} from '@/layout/manager/page-layout';
import { Route } from '@/routes/manager/$orgSlug/route';

export const PageStats = () => {
const { t } = useTranslation(['stats']);

const [from, setFrom] = useState<Date | null>(null);
const [to, setTo] = useState<Date | null>(null);
const { orgSlug } = Route.useParams();

const statsQuery = useQuery(
orpc.stats.getAll.queryOptions({
input:
from || to
? { from: from ?? undefined, to: to ?? undefined }
: undefined,
input: {
orgSlug,
from: from ?? undefined,
to: to ?? undefined,
},
})
);

Expand Down
7 changes: 0 additions & 7 deletions src/routes/manager/$orgSlug/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
import { createFileRoute } from '@tanstack/react-router';

import { orpc } from '@/lib/orpc/client';

import { PageOrganization } from '@/features/organization/manager/page-organization';

export const Route = createFileRoute('/manager/$orgSlug/')({
loader: ({ context }) => {
context.queryClient.prefetchQuery(
orpc.organization.getActiveOrganization.queryOptions()
);
},
component: RouteComponent,
});

Expand Down
9 changes: 9 additions & 0 deletions src/routes/manager/$orgSlug/route.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import { createFileRoute, Outlet } from '@tanstack/react-router';

import { orpc } from '@/lib/orpc/client';

import { GuardOrganization } from '@/features/organization/guard-organization';
import { Layout } from '@/layout/manager/layout';

export const Route = createFileRoute('/manager/$orgSlug')({
loader: ({ context, params }) => {
context.queryClient.prefetchQuery(
orpc.organization.getActiveOrganization.queryOptions({
input: { slug: params.orgSlug },
})
);
},
component: RouteComponent,
});

Expand Down
6 changes: 4 additions & 2 deletions src/routes/manager/$orgSlug/stats.index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ import { orpc } from '@/lib/orpc/client';
import { PageStats } from '@/features/stats/manager/page-stats';

export const Route = createFileRoute('/manager/$orgSlug/stats/')({
loader: ({ context }) => {
loader: ({ context, params }) => {
context.queryClient.prefetchQuery(
orpc.stats.getAll.queryOptions({ input: undefined })
orpc.stats.getAll.queryOptions({
input: { orgSlug: params.orgSlug },
})
);
},
component: RouteComponent,
Expand Down
21 changes: 21 additions & 0 deletions src/server/repositories/organization.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,27 @@ export const createOrganizationRepository = (db: AppDB) => ({
orderBy: { email: 'asc' },
}),

findBySlugWithDetails: (slug: string) =>
db.organization.findUnique({
where: { slug },
include: {
members: {
include: {
user: { select: userCardSelect },
},
},
invitations: {
where: { status: 'pending' },
select: {
id: true,
email: true,
role: true,
status: true,
expiresAt: true,
},
},
},
}),
findById: (id: string) => db.organization.findUnique({ where: { id } }),

findSlugById: (id: string) =>
Expand Down
7 changes: 3 additions & 4 deletions src/server/routers/organization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ export default {

getActiveOrganization: orgProcedure()
.route({ method: 'GET', path: '/organizations/active', tags })
.input(z.object({ slug: z.string() }))
.output(
z.object({
id: z.string(),
Expand Down Expand Up @@ -154,10 +155,8 @@ export default {
),
})
)
.handler(async ({ context }) => {
const org = await context.organizations.findByIdWithDetails(
context.organizationId
);
.handler(async ({ context, input }) => {
const org = await context.organizations.findBySlugWithDetails(input.slug);

if (!org) {
throw new ORPCError('NOT_FOUND');
Expand Down
34 changes: 24 additions & 10 deletions src/server/routers/stats.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,53 @@
import { ORPCError } from '@orpc/client';
import { z } from 'zod';

import { zStatsUser } from '@/features/stats/schema';
import {
organizationProcedure,
type OrganizationProcedureArgs,
} from '@/server/orpc';
import { createOrganizationRepository } from '@/server/repositories/organization.repository';
import { createStatsRepository } from '@/server/repositories/stats.repository';

const tags = ['stats'];

const procedure = (args: OrganizationProcedureArgs = {}) =>
organizationProcedure(args).use(({ context, next }) =>
next({ context: { stats: createStatsRepository(context.db) } })
next({
context: {
stats: createStatsRepository(context.db),
organizations: createOrganizationRepository(context.db),
},
})
);

export default {
getAll: procedure()
.route({ method: 'GET', path: '/stats', tags })
.input(
z
.object({
from: z.coerce.date().optional(),
to: z.coerce.date().optional(),
})
.optional()
z.object({
orgSlug: z.string(),
from: z.coerce.date().optional(),
to: z.coerce.date().optional(),
})
)
.output(z.object({ users: z.array(zStatsUser()) }))
.handler(async ({ context, input }) => {
context.logger.info('Getting stats from database');

const dateRange = input?.from || input?.to ? input : undefined;
const org = await context.organizations.findBySlugWithDetails(
input.orgSlug
);
if (!org) throw new ORPCError('NOT_FOUND');

const isMember = org.members.some((m) => m.user.id === context.user.id);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the isMember verification must also be added to the getActiveOrganization endpoint

if (!isMember) throw new ORPCError('FORBIDDEN');

const dateRange = input.from || input.to ? input : undefined;

const [membersWithCounts, commutesWithStops] = await Promise.all([
context.stats.getMembersWithCounts(context.organizationId, dateRange),
context.stats.getCommuteStopCounts(context.organizationId, dateRange),
context.stats.getMembersWithCounts(org.id, dateRange),
context.stats.getCommuteStopCounts(org.id, dateRange),
]);

const stopCountByMember = new Map<string, number>();
Expand Down
43 changes: 34 additions & 9 deletions src/server/routers/stats.unit.spec.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,28 @@
import { call } from '@orpc/server';
import { describe, expect, it } from 'vitest';
import { beforeEach, describe, expect, it } from 'vitest';

import statsRouter from '@/server/routers/stats';
import {
mockDb,
mockGetSession,
mockMemberId,
mockOrganizationId,
mockUser,
setupAuthenticatedUser,
} from '@/server/routers/test-utils';

const mockOrg = {
id: mockOrganizationId,
slug: 'org-1',
name: 'Test Org',
members: [
{
user: { id: mockUser.id },
},
],
invitations: [],
};

const mockMemberFromDb = {
id: mockMemberId,
user: {
Expand All @@ -25,12 +39,19 @@ const mockMemberFromDb = {
};

describe('stats router', () => {
beforeEach(() => {
setupAuthenticatedUser();
mockDb.organization.findUnique.mockResolvedValue(mockOrg);
});

describe('getAll', () => {
it('should return user stats', async () => {
mockDb.member.findMany.mockResolvedValue([mockMemberFromDb]);
mockDb.commute.findMany.mockResolvedValue([]);

const result = await call(statsRouter.getAll, undefined);
const result = await call(statsRouter.getAll, {
orgSlug: mockOrganizationId,
});

expect(result.users).toEqual([
{
Expand All @@ -50,7 +71,7 @@ describe('stats router', () => {
mockDb.member.findMany.mockResolvedValue([]);
mockDb.commute.findMany.mockResolvedValue([]);

await call(statsRouter.getAll, undefined);
await call(statsRouter.getAll, { orgSlug: mockOrganizationId });

expect(mockDb.member.findMany).toHaveBeenCalledWith(
expect.objectContaining({
Expand All @@ -66,7 +87,7 @@ describe('stats router', () => {
const from = new Date('2025-01-01');
const to = new Date('2025-12-31');

await call(statsRouter.getAll, { from, to });
await call(statsRouter.getAll, { orgSlug: mockOrganizationId, from, to });

expect(mockDb.commute.findMany).toHaveBeenCalledWith(
expect.objectContaining({
Expand All @@ -81,7 +102,7 @@ describe('stats router', () => {
mockDb.member.findMany.mockResolvedValue([]);
mockDb.commute.findMany.mockResolvedValue([]);

await call(statsRouter.getAll, undefined);
await call(statsRouter.getAll, { orgSlug: mockOrganizationId });

expect(mockDb.commute.findMany).toHaveBeenCalledWith(
expect.objectContaining({
Expand All @@ -94,7 +115,7 @@ describe('stats router', () => {
mockDb.member.findMany.mockResolvedValue([]);
mockDb.commute.findMany.mockResolvedValue([]);

await call(statsRouter.getAll, undefined);
await call(statsRouter.getAll, { orgSlug: mockOrganizationId });

expect(mockDb.member.findMany).toHaveBeenCalledWith(
expect.objectContaining({
Expand Down Expand Up @@ -123,7 +144,7 @@ describe('stats router', () => {
mockDb.member.findMany.mockResolvedValue([]);
mockDb.commute.findMany.mockResolvedValue([]);

await call(statsRouter.getAll, undefined);
await call(statsRouter.getAll, { orgSlug: mockOrganizationId });

expect(mockDb.commute.findMany).toHaveBeenCalledWith(
expect.objectContaining({
Expand All @@ -139,15 +160,19 @@ describe('stats router', () => {
{ driverMemberId: mockMemberId, _count: { stops: 2 } },
]);

const result = await call(statsRouter.getAll, undefined);
const result = await call(statsRouter.getAll, {
orgSlug: mockOrganizationId,
});

expect(result.users[0]!.stopCount).toBe(5);
});

it('should throw UNAUTHORIZED when user is not authenticated', async () => {
mockGetSession.mockResolvedValue(null);

await expect(call(statsRouter.getAll, undefined)).rejects.toMatchObject({
await expect(
call(statsRouter.getAll, { orgSlug: mockOrganizationId })
).rejects.toMatchObject({
code: 'UNAUTHORIZED',
});
});
Expand Down
Loading