OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M6-001): user + organization modules into core (incl. delete.service + cron delete fragment)
ralph3c25cef24c31
diff --git a/apps/worker/src/jobs/cron.delete.ts b/apps/worker/src/jobs/cron.delete.tsindex 9ec608338..18e04797f 100644--- a/apps/worker/src/jobs/cron.delete.ts+++ b/apps/worker/src/jobs/cron.delete.ts@@ -1,61 +1,14 @@-import {- db,- deleteFromClickhouse,- deleteOrganization,- deleteProjects,-} from '@openpanel/db';+// Dissolved into @openpanel/core's organization module (M6-001): the+// deletion sweep itself, plus packages/db/src/services/delete.service.ts,+// moved to+// packages/core/src/modules/organization/organization.service.ts#runDeleteCron.+// This file stays (DELEGATE PATTERN) — it is the `cron.ts` dispatcher's+// `delete` case, a thin wrapper around the core function, same shape as+// gsc.ts's `gscSyncAllJob` (M5-002).+import { runDeleteCron } from '@openpanel/core';import { logger } from '@/utils/logger';export async function jobDelete() {- const now = new Date();-- // Find orphaned organizations (no admin member)- // or organizations that are scheduled for deletion- const organizations = await db.organization.findMany({- where: {- OR: [- { deleteAt: { lte: now } },- { members: { none: { role: 'org:admin' } } },- ],- },- include: { projects: { select: { id: true } } },- });-- // Skip paying organizations- const deletableOrganizations = organizations.filter(- (organization) =>- !(organization.hasSubscription && !organization.isWillBeCanceled)- );-- // Find projects that are scheduled for deletion- const scheduledProjects = await db.project.findMany({- where: { deleteAt: { lte: now } },- select: { id: true },- });-- const projectIds = [- ...new Set([- ...deletableOrganizations.flatMap((organization) =>- organization.projects.map((project) => project.id)- ),- ...scheduledProjects.map((project) => project.id),- ]),- ];-- if (projectIds.length > 0) {- await deleteFromClickhouse(projectIds);- await deleteProjects(projectIds);- }-- for (const organization of deletableOrganizations) {- await deleteOrganization(organization.id);- }-- logger.info(- {- organizations: deletableOrganizations.length,- projects: projectIds.length,- },- 'Delete cron complete'- );+ const result = await runDeleteCron();+ logger.info(result, 'Delete cron complete');}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex aec48dc0c..c4b80f175 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -274,6 +274,67 @@ export {selectGscSite,syncGscData,} from './modules/gsc/gsc.service';+// Dissolved from @openpanel/db's services/organization.service.ts ++// services/delete.service.ts (M6-001, folded together per the module map) —+// packages/trpc's organization router, apps/worker's delete cron job and+// packages/db's own engine/analytics services (`getSettingsForProject`) call+// these directly, the same way V1 reaches every other dissolved service here.+// packages/db/src/services/organization.service.ts stays a re-export shim+// (unlike delete.service.ts, which packages/db loses entirely — nothing but+// the worker's cron job reached it through @openpanel/db's barrel).+export type {+ DeleteCronResult,+ InviteUserResult,+ IServiceInvite,+ IServiceMember,+ IServiceOrganization,+ IServiceProjectAccess,+ OrganizationService,+} from './modules/organization/organization.service';+export {+ cancelOrganizationDeletion,+ connectUserToOrganization,+ createOrganizationService,+ deleteFromClickhouse,+ deleteOrganization,+ deleteProjects,+ getInviteById,+ getInviteOrThrow,+ getInvites,+ getMember,+ getMembers,+ getOrganizationBillingEventsCount,+ getOrganizationBillingEventsCountSerie,+ getOrganizationBillingEventsCountSerieCached,+ getOrganizationById,+ getOrganizationByProjectId,+ getOrganizationByProjectIdCached,+ getOrganizationEventsCount,+ getOrganizationEventsCountSince,+ getOrganizationSubscriptionChartEndDate,+ getOrganizations,+ getSettingsForOrganization,+ getSettingsForProject,+ inviteUserToOrganization,+ removeOrganizationMember,+ revokeInvite,+ runDeleteCron,+ scheduleOrganizationDeletion,+ updateOrganization,+ updateOrganizationMemberAccess,+} from './modules/organization/organization.service';+// Dissolved from @openpanel/db's services/user.service.ts (M6-001) —+// packages/trpc's auth/onboarding routers still call `getUserById`/+// `getUserAccount` directly through @openpanel/db's re-export shim, the same+// way they reach every other dissolved service here.+export type { IServiceUser } from './modules/user/user.service';+export {+ deleteUserAccount,+ getUserAccount,+ getUserById,+ listUserDeletionBlockers,+ updateUserProfile,+} from './modules/user/user.service';// packages/mcp absorbed whole (M5-007) — apps/api's mcp.router.ts is the one// external caller, delegating the streamable-HTTP POST protocol herediff --git a/packages/core/src/jobs.registry.test.ts b/packages/core/src/jobs.registry.test.tsindex 4b154cbf2..dca70afda 100644--- a/packages/core/src/jobs.registry.test.ts+++ b/packages/core/src/jobs.registry.test.ts@@ -84,6 +84,7 @@ test('the cron queue carries the insight module cron fragment', () => {expect(Object.keys(queues.cron.jobs).sort()).toEqual(['cohortRefresh',+ 'delete','gscSync','insightCleanup','insightsDaily',@@ -136,6 +137,15 @@ test('the cron queue carries the cohort module cron fragment', () => {});});+// M6-001: the organization module's `delete` cron fragment (folded in from+// packages/db/src/services/delete.service.ts).+test('the cron queue carries the organization module cron fragment', () => {+ expect(queues.cron.jobs.delete).toMatchObject({+ queue: 'cron',+ name: 'delete',+ });+});+// M5-004: the import module's own job. No cron fragment — imports are always// user-triggered (import.rpc.ts's create/retry), unlike gsc/cohort/insight.// legacyCompat.import already discriminates on this exact namediff --git a/packages/core/src/jobs.registry.ts b/packages/core/src/jobs.registry.tsindex f5f8905d0..2ffd6a909 100644--- a/packages/core/src/jobs.registry.ts+++ b/packages/core/src/jobs.registry.ts@@ -21,6 +21,7 @@ import {insightCronJobs,insightQueueJobs,} from './modules/insight/insight.jobs';+import { organizationCronJobs } from './modules/organization/organization.jobs';const HOUR_IN_SECONDS = 3600;const DAY_IN_SECONDS = 86_400;@@ -58,6 +59,7 @@ const cron = defineQueue('cron', {...insightCronJobs,...gscCronJobs,...cohortCronJobs,+ ...organizationCronJobs,},});diff --git a/packages/core/src/jobs/schedulers.ts b/packages/core/src/jobs/schedulers.tsindex 21353ca8d..62e5f3831 100644--- a/packages/core/src/jobs/schedulers.ts+++ b/packages/core/src/jobs/schedulers.ts@@ -8,6 +8,7 @@ import type { Logger } from '../logger';import { cohortCronSchedules } from '../modules/cohort/cohort.jobs';import { gscCronSchedules } from '../modules/gsc/gsc.jobs';import { insightCronSchedules } from '../modules/insight/insight.jobs';+import { organizationCronSchedules } from '../modules/organization/organization.jobs';import { wrap } from './envelope';export type RepeatSchedule = { pattern: string } | { every: number };@@ -57,7 +58,9 @@ const MINUTE_MS = 60_000;// see `PING_SCHEDULE` and `startSchedulers`.export const CRON_SCHEDULES: readonly SchedulerDefinition[] = [{ id: 'salt', schedule: { pattern: '0 0 * * *' } },- { id: 'delete', schedule: { pattern: '0 * * * *' } },+ // delete — owned by the organization module, declared next to its jobs+ // (modules/organization/organization.jobs.ts).+ ...organizationCronSchedules,{ id: 'flushEvents', schedule: { every: 10_000 } },{ id: 'flushProfiles', schedule: { every: 10_000 } },{ id: 'flushSessions', schedule: { every: 10_000 } },diff --git a/packages/core/src/modules/cohort/cohort.jobs.test.ts b/packages/core/src/modules/cohort/cohort.jobs.test.tsindex 3db8fc483..221282fc3 100644--- a/packages/core/src/modules/cohort/cohort.jobs.test.ts+++ b/packages/core/src/modules/cohort/cohort.jobs.test.ts@@ -35,6 +35,7 @@ function stubJobCtx(cohort: Partial<CohortService>, jobName = 'test'): JobCtx {gsc: {} as Services['gsc'],import: {} as Services['import'],cohort: cohort as CohortService,+ organization: {} as Services['organization'],};return {db: {},diff --git a/packages/core/src/modules/gsc/gsc.jobs.test.ts b/packages/core/src/modules/gsc/gsc.jobs.test.tsindex 8a6fefd86..8caa10557 100644--- a/packages/core/src/modules/gsc/gsc.jobs.test.ts+++ b/packages/core/src/modules/gsc/gsc.jobs.test.ts@@ -31,6 +31,7 @@ function stubJobCtx(gsc: Partial<GscService>, jobName = 'test'): JobCtx {cohort: {} as Services['cohort'],import: {} as Services['import'],gsc: gsc as GscService,+ organization: {} as Services['organization'],};return {db: {},@@ -128,6 +129,7 @@ test('gscSync fans out one gscProjectSync enqueue per connected project', async{ projectId: 'p2' },],} as GscService,+ organization: {} as Services['organization'],},requestId: 'req_1',job: { id: 'job_1', attempt: 0, queue: 'cron', name: 'gscSync' },diff --git a/packages/core/src/modules/gsc/gsc.service.test.ts b/packages/core/src/modules/gsc/gsc.service.test.tsindex 46fe6a767..c6d3ad1aa 100644--- a/packages/core/src/modules/gsc/gsc.service.test.ts+++ b/packages/core/src/modules/gsc/gsc.service.test.ts@@ -157,7 +157,15 @@ const validateAuthorizationCode = mock(async () => ({refreshToken: () => 'google-refresh-token',accessTokenExpiresAt: () => new Date('2026-09-04T00:00:00.000Z'),}));+// Spread the real module — see the clickhouse/client mock above for why a+// partial factory here is a process-wide hazard, not a local one. Surfaced+// by M6-001: @openpanel/db's organization.service.ts shim (imported below)+// now re-exports from @openpanel/core's full barrel, which reaches this+// same auth.service.ts for createAuthService — a partial replacement here+// used to be invisible because nothing else in this file's chain needed it.+const actualAuthService = await import('../auth/auth.service');mock.module('../auth/auth.service', () => ({+ ...actualAuthService,googleGsc: { validateAuthorizationCode },}));diff --git a/packages/core/src/modules/import/import.jobs.test.ts b/packages/core/src/modules/import/import.jobs.test.tsindex 209c4d1a2..11677d559 100644--- a/packages/core/src/modules/import/import.jobs.test.ts+++ b/packages/core/src/modules/import/import.jobs.test.ts@@ -31,6 +31,7 @@ function stubJobCtx(importService: Partial<ImportService>): JobCtx {cohort: {} as Services['cohort'],gsc: {} as Services['gsc'],import: importService as ImportService,+ organization: {} as Services['organization'],};return {db: {},diff --git a/packages/core/src/modules/insight/insight.jobs.test.ts b/packages/core/src/modules/insight/insight.jobs.test.tsindex 37c52bf5a..b8ee4d589 100644--- a/packages/core/src/modules/insight/insight.jobs.test.ts+++ b/packages/core/src/modules/insight/insight.jobs.test.ts@@ -42,6 +42,7 @@ function stubJobCtx(gsc: {} as Services['gsc'],cohort: {} as Services['cohort'],import: {} as Services['import'],+ organization: {} as Services['organization'],};return {db: {},@@ -122,6 +123,7 @@ test('insightsDaily fans out one insightsProject enqueue per candidate, jobId degsc: {} as Services['gsc'],cohort: {} as Services['cohort'],import: {} as Services['import'],+ organization: {} as Services['organization'],},requestId: 'req_1',job: { id: 'job_1', attempt: 0, queue: 'cron', name: 'insightsDaily' },diff --git a/packages/core/src/modules/organization/organization.jobs.test.ts b/packages/core/src/modules/organization/organization.jobs.test.tsnew file mode 100644index 000000000..52b382436--- /dev/null+++ b/packages/core/src/modules/organization/organization.jobs.test.ts@@ -0,0 +1,87 @@+// Job/cron-fragment wiring — no ClickHouse/Postgres touched. The service+// method itself is exercised in organization.service.test.ts.++import { expect, test } from 'bun:test';+import type { JobCtx } from '../../context';+import { createRecordingProducers } from '../../jobs/testing';+import { queues } from '../../jobs.registry';+import type { Logger } from '../../logger';+import type { Services } from '../../services';+import {+ organizationCronJobs,+ organizationCronSchedules,+} from './organization.jobs';+import type { OrganizationService } from './organization.service';++function stubLogger(): Logger {+ const noop = () => undefined;+ const logger: Logger = {+ fatal: noop,+ error: noop,+ warn: noop,+ info: noop,+ debug: noop,+ trace: noop,+ child: () => logger,+ };+ return logger;+}++function stubJobCtx(+ organization: Partial<OrganizationService>,+ jobName = 'test'+): JobCtx {+ const services: Services = {+ auth: {} as Services['auth'],+ insight: {} as Services['insight'],+ gsc: {} as Services['gsc'],+ import: {} as Services['import'],+ cohort: {} as Services['cohort'],+ organization: organization as OrganizationService,+ };+ return {+ db: {},+ ch: {},+ redis: {},+ clients: {},+ buffers: {},+ logger: stubLogger(),+ queues: createRecordingProducers(queues).queues,+ services,+ requestId: 'req_1',+ job: { id: 'job_1', attempt: 0, queue: 'cron', name: jobName },+ };+}++test('the cron queue declares delete on the cron queue', () => {+ expect(queues.cron.jobs.delete).toMatchObject({+ queue: 'cron',+ name: 'delete',+ });+});++test('the organization cron fragment is spread into the cron queue', () => {+ expect(queues.cron.jobs.delete).toBeDefined();+});++test('delete delegates to runDeleteCron', async () => {+ let called = false;+ const ctx = stubJobCtx({+ runDeleteCron: async () => {+ called = true;+ return { organizations: 1, projects: 2 };+ },+ });++ await organizationCronJobs.delete.handler({ payload: null, ctx });++ expect(called).toBe(true);+});++// Byte-identity with the id/cadence schedulers.test.ts's golden snapshot pins+// (apps/worker/src/boot-cron.ts).+test('the organization cron fragment carries V1 id and cadence unchanged', () => {+ expect(organizationCronSchedules).toEqual([+ { id: 'delete', schedule: { pattern: '0 * * * *' } },+ ]);+});diff --git a/packages/core/src/modules/organization/organization.jobs.ts b/packages/core/src/modules/organization/organization.jobs.tsnew file mode 100644index 000000000..6b84c53cf--- /dev/null+++ b/packages/core/src/modules/organization/organization.jobs.ts@@ -0,0 +1,27 @@+// Ported from apps/worker/src/jobs/cron.delete.ts + boot-cron.ts's `delete`+// schedule (M6-001).+//+// `delete` is this module's fragment of the ONE `cron` queue's jobs:+// declared here, spread into jobs.registry.ts and into `CRON_SCHEDULES` by+// jobs/schedulers.ts. Scheduler id and cadence are V1's, unchanged+// (apps/worker/src/boot-cron.ts).++import { z } from 'zod';+import { defineJob } from '../../jobs/define';+import type { SchedulerDefinition } from '../../jobs/schedulers';++/** This module's fragment of the `cron` queue's jobs. */+export const organizationCronJobs = {+ delete: defineJob({+ payload: z.null(),+ handler: async ({ ctx }) => {+ const result = await ctx.services.organization.runDeleteCron();+ ctx.logger.info({ ...result }, 'Delete cron complete');+ },+ }),+};++/** This module's fragment of `CRON_SCHEDULES` — id and cadence unchanged. */+export const organizationCronSchedules: readonly SchedulerDefinition[] = [+ { id: 'delete', schedule: { pattern: '0 * * * *' } },+];diff --git a/packages/core/src/modules/organization/organization.rpc.test.ts b/packages/core/src/modules/organization/organization.rpc.test.tsnew file mode 100644index 000000000..8e3229ded--- /dev/null+++ b/packages/core/src/modules/organization/organization.rpc.test.ts@@ -0,0 +1,101 @@+// Only the "is anyone logged in" boundary is exercised here — no database.+// The admin-access-check + mutation bodies ride on @openpanel/db (lazy-loaded+// through ./src/access and organization.service.ts); wiring this router+// end-to-end against a real Postgres is P6's (protectedProcedure) job, not+// this one's — see organization.rpc.ts's header.++import { expect, test } from 'bun:test';+import { stubHttpCtx } from '../../../test/rpc-fixtures';+import { makeTrpcContext } from '../../rpc/base';+import type { CookieOptions } from '../../shared/cookie';+import { organizationRouter } from './organization.rpc';++const COOKIE_OPTIONS: CookieOptions = {+ domain: '.openpanel.dev',+ secure: true,+ sameSite: 'lax',+ httpOnly: true,+ path: '/',+};++// EMPTY_SESSION's shape (packages/db/src/services/auth-session.service.ts) —+// `TrpcContext.session` is never literally `null`, only its `userId` is.+const EMPTY_SESSION = { session: null, user: null, userId: null };++async function anonCaller() {+ const { ctx } = stubHttpCtx({}, EMPTY_SESSION);+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {+ cookieOptions: COOKIE_OPTIONS,+ });+ return organizationRouter.createCaller(trpcCtx);+}++test('get rejects an unauthenticated caller before reading an organization', async () => {+ const caller = await anonCaller();+ await expect(caller.get({ organizationId: 'org_1' })).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+});++test('list rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(caller.list()).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('myAccess rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(+ caller.myAccess({ organizationId: 'org_1' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('update rejects an unauthenticated caller before touching an organization', async () => {+ const caller = await anonCaller();+ await expect(+ caller.update({ id: 'org_1', name: 'Acme', timezone: 'UTC' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('delete rejects an unauthenticated caller before scheduling deletion', async () => {+ const caller = await anonCaller();+ await expect(+ caller.delete({ organizationId: 'org_1' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('inviteUser rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(+ caller.inviteUser({+ organizationId: 'org_1',+ email: '[email protected]',+ role: 'org:member',+ access: [],+ })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('removeMember rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(+ caller.removeMember({+ organizationId: 'org_1',+ userId: 'user_2',+ id: 'member_1',+ })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('members rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(+ caller.members({ organizationId: 'org_1' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('getInvite requires an inviteId', async () => {+ const caller = await anonCaller();+ await expect(caller.getInvite({})).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+});diff --git a/packages/core/src/modules/organization/organization.rpc.ts b/packages/core/src/modules/organization/organization.rpc.tsnew file mode 100644index 000000000..6bb263603--- /dev/null+++ b/packages/core/src/modules/organization/organization.rpc.ts@@ -0,0 +1,187 @@+// Ported from packages/trpc/src/routers/organization.ts (M6-001).+//+// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware+// stack — lands in core with auth (rpc/base.ts: "those need the resolved+// Session shape and the access rules, so they land with auth (P6)"). Until+// then this router does its own minimal "is anyone logged in" check inline,+// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route+// through packages/trpc's own `protectedProcedure` (full stack included) and+// delegates its handler bodies to `ctx.services.organization` (DELEGATE+// PATTERN), so nothing here is a live regression.+//+// The organization-admin ladder itself IS shared: `./src/access.ts` binds+// core's shared/access.ts ladder to @openpanel/db's real lookups, the same+// way packages/trpc/src/access.ts does for V1.+//+// `getInvite` drops V1's rate limiting (packages/trpc's `rateLimitMiddleware`+// lands with auth, same as `protectedProcedure` above) — V1 keeps enforcing+// it on the live route through its own copy of this router.++import {+ zEditOrganization,+ zInviteUser,+ zUpdateMemberAccess,+} from '@openpanel/validation';+import { z } from 'zod';+import { createTRPCRouter, procedure } from '../../rpc/base';+import {+ TRPCAccessError,+ TRPCBadRequestError,+ TRPCForbiddenError,+} from '../../rpc/errors';++function loadAccessChecks() {+ return import('./src/access');+}++function requireLogin(userId: string | null | undefined): string {+ if (!userId) {+ throw new TRPCAccessError('Not authenticated');+ }+ return userId;+}++async function requireOrgAdmin(userId: string, organizationId: string) {+ const { requireOrganizationAdmin } = await loadAccessChecks();+ await requireOrganizationAdmin({ userId, organizationId });+}++export const organizationRouter = createTRPCRouter({+ get: procedure+ .input(z.object({ organizationId: z.string() }))+ .query(async ({ input, ctx }) => {+ requireLogin(ctx.session.userId);+ return ctx.services.organization.get(input.organizationId);+ }),++ list: procedure.query(async ({ ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ return ctx.services.organization.list(userId);+ }),++ // Membership-exempt on purpose: any logged-in user may ask whether they have+ // access to a given org. Returns null when they're not a member (instead of+ // throwing), which the org-layout guard uses to render a not-found page.+ myAccess: procedure+ .input(z.object({ organizationId: z.string() }))+ .query(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ const { getOrganizationAccess } = await loadAccessChecks();+ const access = await getOrganizationAccess({+ userId,+ organizationId: input.organizationId,+ });+ if (!access) {+ return null;+ }+ return { role: access.role };+ }),++ update: procedure+ .input(zEditOrganization)+ .mutation(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ await requireOrgAdmin(userId, input.id);+ return ctx.services.organization.update(input);+ }),++ delete: procedure+ .input(z.object({ organizationId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ await requireOrgAdmin(userId, input.organizationId);+ await ctx.services.organization.scheduleDeletion(input.organizationId);+ return true;+ }),++ cancelDeletion: procedure+ .input(z.object({ organizationId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ await requireOrgAdmin(userId, input.organizationId);+ await ctx.services.organization.cancelDeletion(input.organizationId);+ return true;+ }),++ inviteUser: procedure.input(zInviteUser).mutation(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ await requireOrgAdmin(userId, input.organizationId);+ return ctx.services.organization.inviteUser({+ organizationId: input.organizationId,+ email: input.email,+ role: input.role,+ access: input.access,+ invitedById: userId,+ });+ }),++ revokeInvite: procedure+ .input(z.object({ inviteId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ const invite = await ctx.services.organization.getInviteOrThrow(+ input.inviteId+ );+ await requireOrgAdmin(userId, invite.organizationId);+ return ctx.services.organization.revokeInvite(input.inviteId);+ }),++ removeMember: procedure+ .input(+ z.object({+ organizationId: z.string(),+ userId: z.string(),+ id: z.string(),+ })+ )+ .mutation(async ({ input, ctx }) => {+ const requestedByUserId = requireLogin(ctx.session.userId);+ await requireOrgAdmin(requestedByUserId, input.organizationId);+ await ctx.services.organization.removeMember({+ organizationId: input.organizationId,+ memberId: input.id,+ targetUserId: input.userId,+ requestedByUserId,+ });+ }),++ updateMemberAccess: procedure+ .input(zUpdateMemberAccess)+ .mutation(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ if (input.userId === userId) {+ throw new TRPCForbiddenError('You cannot update your own access');+ }+ await requireOrgAdmin(userId, input.organizationId);+ return ctx.services.organization.updateMemberAccess({+ organizationId: input.organizationId,+ targetUserId: input.userId,+ access: input.access,+ });+ }),++ members: procedure+ .input(z.object({ organizationId: z.string() }))+ .query(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ await requireOrgAdmin(userId, input.organizationId);+ return ctx.services.organization.members(input.organizationId);+ }),++ invitations: procedure+ .input(z.object({ organizationId: z.string() }))+ .query(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ await requireOrgAdmin(userId, input.organizationId);+ return ctx.services.organization.invitations(input.organizationId);+ }),++ getInvite: procedure+ .input(z.object({ inviteId: z.string().optional() }))+ .query(async ({ input, ctx }) => {+ if (!input.inviteId) {+ throw new TRPCBadRequestError('Invite ID is required');+ }+ return ctx.services.organization.getInvite(input.inviteId);+ }),+});diff --git a/packages/core/src/modules/organization/organization.service.test.ts b/packages/core/src/modules/organization/organization.service.test.tsnew file mode 100644index 000000000..21c2cbd71--- /dev/null+++ b/packages/core/src/modules/organization/organization.service.test.ts@@ -0,0 +1,784 @@+// organization.service.ts's db/ch access is lazy (`await import(...)` inside+// each function — see the file's header), which is exactly what makes+// `mock.module` work here with no import-time side effects to race: every+// mock below is registered before the subject's first call, not before its+// (side-effect-free) import.++import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';++interface FakeOrganization {+ id: string;+ name: string;+ timezone: string | null;+ createdByUserId: string | null;+ deleteAt: Date | null;+ subscriptionStatus: string | null;+ subscriptionCurrentPeriodStart: Date | null;+ subscriptionCurrentPeriodEnd: Date | null;+ subscriptionEndsAt: Date | null;+ subscriptionChartEndDate: Date | null;+ createdAt: Date;+ // Prisma $extends computed fields — set directly on the fixture rather+ // than derived, since the mock never touches the real extension.+ hasSubscription: boolean;+ isWillBeCanceled: boolean;+}++interface FakeProject {+ id: string;+ organizationId: string;+ deleteAt: Date | null;+}++interface FakeMember {+ id: string;+ organizationId: string;+ userId: string | null;+ role: string;+ email: string;+}++interface FakeInvite {+ id: string;+ email: string;+ organizationId: string;+ role: string;+ createdById: string;+ projectAccess: { projectId: string; level: 'read' | 'write' }[];+ expiresAt: Date;+ createdAt: Date;+}++interface FakeUser {+ id: string;+ email: string;+}++const EPOCH = new Date('2026-09-03T00:00:00.000Z');++function makeOrganization(+ overrides: Partial<FakeOrganization> & { id: string }+): FakeOrganization {+ return {+ name: 'Acme',+ timezone: null,+ createdByUserId: null,+ deleteAt: null,+ subscriptionStatus: null,+ subscriptionCurrentPeriodStart: null,+ subscriptionCurrentPeriodEnd: null,+ subscriptionEndsAt: null,+ subscriptionChartEndDate: null,+ createdAt: EPOCH,+ hasSubscription: false,+ isWillBeCanceled: false,+ ...overrides,+ };+}++const organizationStore = new Map<string, FakeOrganization>();+const projectStore = new Map<string, FakeProject>();+const memberStore = new Map<string, FakeMember>();+const inviteStore = new Map<string, FakeInvite>();+const userStore = new Map<string, FakeUser>();+const projectAccessStore = new Map<+ string,+ {+ id: string;+ userId: string;+ organizationId: string;+ projectId: string;+ level: string;+ }+>();++function resetStores() {+ organizationStore.clear();+ projectStore.clear();+ memberStore.clear();+ inviteStore.clear();+ userStore.clear();+ projectAccessStore.clear();+}++const organization = {+ findMany: mock(+ async ({+ where,+ }: {+ where?: {+ members?: { some: { userId: string } };+ OR?: unknown[];+ deleteAt?: { lte: Date };+ };+ } = {}) => {+ let rows = [...organizationStore.values()];+ if (where?.members) {+ const userId = where.members.some.userId;+ rows = rows.filter((org) =>+ [...memberStore.values()].some(+ (m) => m.organizationId === org.id && m.userId === userId+ )+ );+ }+ if (where?.OR) {+ rows = rows.filter((org) => {+ const scheduledForDeletion =+ org.deleteAt && org.deleteAt <= new Date();+ const noAdmin = ![...memberStore.values()].some(+ (m) => m.organizationId === org.id && m.role === 'org:admin'+ );+ return scheduledForDeletion || noAdmin;+ });+ }+ return rows.map((org) => ({+ ...org,+ projects: [...projectStore.values()].filter(+ (p) => p.organizationId === org.id+ ),+ }));+ }+ ),+ findUniqueOrThrow: mock(+ async ({ where: { id } }: { where: { id: string } }) => {+ const org = organizationStore.get(id);+ if (!org) {+ throw new Error(`organization ${id} not found`);+ }+ return org;+ }+ ),+ update: mock(+ async ({+ where: { id },+ data,+ }: {+ where: { id: string };+ data: Partial<FakeOrganization>;+ }) => {+ const existing = organizationStore.get(id);+ if (!existing) {+ throw new Error(`organization ${id} not found`);+ }+ const next = { ...existing, ...data };+ organizationStore.set(id, next);+ return next;+ }+ ),+ delete: mock(async ({ where: { id } }: { where: { id: string } }) => {+ organizationStore.delete(id);+ }),+};++const project = {+ findMany: mock(+ async ({+ where,+ }: {+ where?: { id?: { in: string[] }; deleteAt?: { lte: Date } };+ } = {}) => {+ let rows = [...projectStore.values()];+ if (where?.id) {+ rows = rows.filter((p) => where.id?.in.includes(p.id));+ }+ if (where?.deleteAt) {+ rows = rows.filter((p) => p.deleteAt && p.deleteAt <= new Date());+ }+ return rows;+ }+ ),+ delete: mock(async ({ where: { id } }: { where: { id: string } }) => {+ projectStore.delete(id);+ }),+ updateMany: mock(+ async ({+ where: { organizationId },+ data,+ }: {+ where: { organizationId: string };+ data: Partial<FakeProject>;+ }) => {+ let count = 0;+ for (const p of projectStore.values()) {+ if (p.organizationId === organizationId) {+ Object.assign(p, data);+ count++;+ }+ }+ return { count };+ }+ ),+};++const member = {+ count: mock(+ async ({ where }: { where: { userId: string; organizationId: string } }) =>+ [...memberStore.values()].filter(+ (m) =>+ m.userId === where.userId && m.organizationId === where.organizationId+ ).length+ ),+ findFirst: mock(+ async ({ where }: { where: { userId?: string; organizationId: string } }) =>+ [...memberStore.values()].find(+ (m) =>+ m.organizationId === where.organizationId &&+ (where.userId === undefined || m.userId === where.userId)+ ) ?? null+ ),+ findMany: mock(+ async ({+ where,+ }: {+ where: { organizationId: string; userId?: unknown };+ }) =>+ [...memberStore.values()]+ .filter((m) => m.organizationId === where.organizationId && m.userId)+ .map((m) => ({ ...m, user: userStore.get(m.userId as string) }))+ ),+ delete: mock(+ async ({+ where,+ }: {+ where: { id: string; userId: string; organizationId: string };+ }) => {+ const existing = memberStore.get(where.id);+ if (!existing || existing.userId !== where.userId) {+ throw new Error('member not found');+ }+ memberStore.delete(where.id);+ return existing;+ }+ ),+ upsert: mock(+ async ({+ where,+ update,+ create,+ }: {+ where: {+ organizationId_userId: { organizationId: string; userId: string };+ };+ update: Partial<FakeMember>;+ create: Omit<FakeMember, 'id'>;+ }) => {+ const existing = [...memberStore.values()].find(+ (m) =>+ m.organizationId === where.organizationId_userId.organizationId &&+ m.userId === where.organizationId_userId.userId+ );+ if (existing) {+ Object.assign(existing, update);+ return existing;+ }+ const id = `member_${memberStore.size + 1}`;+ const row = { id, ...create };+ memberStore.set(id, row);+ return row;+ }+ ),+};++const invite = {+ findFirst: mock(+ async ({ where }: { where: { email: string; organizationId: string } }) =>+ [...inviteStore.values()].find(+ (i) =>+ i.email === where.email && i.organizationId === where.organizationId+ ) ?? null+ ),+ findMany: mock(async ({ where }: { where: { organizationId: string } }) =>+ [...inviteStore.values()]+ .filter((i) => i.organizationId === where.organizationId)+ .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())+ ),+ findUnique: mock(async ({ where: { id } }: { where: { id: string } }) => {+ const found = inviteStore.get(id);+ if (!found) {+ return null;+ }+ return {+ ...found,+ organization: { id: found.organizationId, name: 'Acme' },+ };+ }),+ findUniqueOrThrow: mock(+ async ({ where: { id } }: { where: { id: string } }) => {+ const found = inviteStore.get(id);+ if (!found) {+ throw new Error(`invite ${id} not found`);+ }+ return found;+ }+ ),+ create: mock(async ({ data }: { data: FakeInvite }) => {+ inviteStore.set(data.id, { ...data, createdAt: EPOCH });+ return { ...data, organization: { name: 'Acme' } };+ }),+ delete: mock(async ({ where: { id } }: { where: { id: string } }) => {+ const found = inviteStore.get(id);+ inviteStore.delete(id);+ return found;+ }),+};++const user = {+ findFirst: mock(+ async ({ where }: { where: { email: { equals: string } } }) =>+ [...userStore.values()].find((u) => u.email === where.email.equals) ??+ null+ ),+};++const projectAccess = {+ findMany: mock(async ({ where }: { where: { organizationId: string } }) =>+ [...projectAccessStore.values()].filter(+ (a) => a.organizationId === where.organizationId+ )+ ),+ create: mock(+ async ({+ data,+ }: {+ data: {+ projectId: string;+ userId: string;+ organizationId: string;+ level: string;+ };+ }) => {+ const id = `access_${projectAccessStore.size + 1}`;+ const row = { id, ...data };+ projectAccessStore.set(id, row);+ return row;+ }+ ),+ createMany: mock(+ async ({+ data,+ }: {+ data: {+ projectId: string;+ userId: string;+ organizationId: string;+ level: string;+ }[];+ }) => {+ for (const grant of data) {+ const id = `access_${projectAccessStore.size + 1}`;+ projectAccessStore.set(id, { id, ...grant });+ }+ return { count: data.length };+ }+ ),+ deleteMany: mock(+ async ({+ where,+ }: {+ where: { userId: string; organizationId: string };+ }) => {+ let count = 0;+ for (const [id, row] of projectAccessStore.entries()) {+ if (+ row.userId === where.userId &&+ row.organizationId === where.organizationId+ ) {+ projectAccessStore.delete(id);+ count++;+ }+ }+ return { count };+ }+ ),+};++const $transaction = mock(async (ops: Promise<unknown>[]) => Promise.all(ops));++const actualPrismaClient = await import('@openpanel/db/src/prisma-client');+mock.module('@openpanel/db/src/prisma-client', () => ({+ ...actualPrismaClient,+ db: {+ organization,+ project,+ member,+ invite,+ user,+ projectAccess,+ $transaction,+ },+}));++// Spread the real module rather than hand-listing every export — see+// gsc.service.test.ts's header for why a partial factory here is a+// process-wide hazard, not a local one (bun shares one module registry+// across files without `--isolate`).+const actualClickhouseClient = await import(+ '@openpanel/db/src/clickhouse/client'+);+const realClickhouseClient = { ...actualClickhouseClient };+const chCommand = mock(async () => undefined);+mock.module('@openpanel/db/src/clickhouse/client', () => ({+ ...realClickhouseClient,+ ch: { command: chCommand },+}));++afterAll(() => {+ mock.module(+ '@openpanel/db/src/clickhouse/client',+ () => realClickhouseClient+ );+});++// Bypasses the Redis cache-aside entirely — this module's own logic is+// exercised directly, caching is @openpanel/redis's concern. `access.service.ts`+// (reached via connectUserToOrganization's dynamic import) calls `.clear()` on+// its cacheable-wrapped lookups, so the stand-in needs that method too, not+// just the bare passthrough gsc.service.test.ts's identical mock gets away with.+// Real `cacheable` overloads on `(fn, ttl)` OR `(name, fn, ttl)` — this+// module uses the first form, access.service.ts (reached via+// connectUserToOrganization) the second.+function cacheableStub(+ fnOrName: ((...args: unknown[]) => unknown) | string,+ fnOrTtl: ((...args: unknown[]) => unknown) | number+) {+ const fn =+ typeof fnOrName === 'function'+ ? fnOrName+ : (fnOrTtl as (...args: unknown[]) => unknown);+ return Object.assign(fn, {+ getKey: () => '',+ clear: async () => 0,+ set: () => async () => 'OK' as const,+ });+}+mock.module('@openpanel/redis', () => ({+ cacheable: cacheableStub,+ getRedisCache: () => ({+ get: async () => null,+ setex: async () => undefined,+ del: async () => undefined,+ }),+}));++// Mocks core's own clients/email.ts wrapper, not @openpanel/email itself:+// that package statically imports @openpanel/db's full barrel (Resend/SMTP+// setup aside), which is exactly the eager side-effecting chain+// organization.service.ts's own lazy `load*` helpers exist to avoid — see+// this file's header. mcp.service.test.ts mocks the same relative depth for+// the same reason.+const sentEmails: { templateKey: string; to: string; data: unknown }[] = [];+mock.module('../../clients/email', () => ({+ sendEmail: async (+ templateKey: string,+ options: { to: string; data: unknown }+ ) => {+ sentEmails.push({ templateKey, to: options.to, data: options.data });+ },+}));++let subject: typeof import('./organization.service');+beforeAll(async () => {+ subject = await import('./organization.service');+});++beforeEach(() => {+ resetStores();+ sentEmails.length = 0;+});++test('scheduleOrganizationDeletion sets deleteAt on the org and its projects', async () => {+ organizationStore.set('org_1', makeOrganization({ id: 'org_1' }));+ projectStore.set('proj_1', {+ id: 'proj_1',+ organizationId: 'org_1',+ deleteAt: null,+ });++ await subject.scheduleOrganizationDeletion('org_1');++ expect(organizationStore.get('org_1')?.deleteAt).toBeInstanceOf(Date);+ expect(projectStore.get('proj_1')?.deleteAt).toBeInstanceOf(Date);+});++test('scheduleOrganizationDeletion refuses a live, uncancelled subscription', async () => {+ organizationStore.set(+ 'org_1',+ makeOrganization({+ id: 'org_1',+ hasSubscription: true,+ isWillBeCanceled: false,+ })+ );++ await expect(subject.scheduleOrganizationDeletion('org_1')).rejects.toThrow(+ /cancel your subscription/+ );+});++test('scheduleOrganizationDeletion allows a subscription already scheduled to cancel', async () => {+ organizationStore.set(+ 'org_1',+ makeOrganization({+ id: 'org_1',+ hasSubscription: true,+ isWillBeCanceled: true,+ })+ );++ await subject.scheduleOrganizationDeletion('org_1');+ expect(organizationStore.get('org_1')?.deleteAt).toBeInstanceOf(Date);+});++test('cancelOrganizationDeletion clears deleteAt on the org and its projects', async () => {+ organizationStore.set(+ 'org_1',+ makeOrganization({ id: 'org_1', deleteAt: new Date() })+ );+ projectStore.set('proj_1', {+ id: 'proj_1',+ organizationId: 'org_1',+ deleteAt: new Date(),+ });++ await subject.cancelOrganizationDeletion('org_1');++ expect(organizationStore.get('org_1')?.deleteAt).toBeNull();+ expect(projectStore.get('proj_1')?.deleteAt).toBeNull();+});++test('updateOrganization updates name and timezone', async () => {+ organizationStore.set('org_1', makeOrganization({ id: 'org_1' }));+ const result = await subject.updateOrganization({+ id: 'org_1',+ name: 'New name',+ timezone: 'Europe/Stockholm',+ });+ expect(result).toMatchObject({+ name: 'New name',+ timezone: 'Europe/Stockholm',+ });+});++test('removeOrganizationMember refuses a user removing themself as the last member', async () => {+ memberStore.set('member_1', {+ id: 'member_1',+ organizationId: 'org_1',+ userId: 'user_1',+ role: 'org:admin',+ email: '[email protected]',+ });++ await expect(+ subject.removeOrganizationMember({+ organizationId: 'org_1',+ memberId: 'member_1',+ targetUserId: 'user_1',+ requestedByUserId: 'user_1',+ })+ ).rejects.toThrow(/cannot remove yourself/);+ expect(memberStore.has('member_1')).toBe(true);+});++test('removeOrganizationMember deletes the member and their project access', async () => {+ memberStore.set('member_1', {+ id: 'member_1',+ organizationId: 'org_1',+ userId: 'user_1',+ role: 'org:member',+ email: '[email protected]',+ });+ projectAccessStore.set('access_1', {+ id: 'access_1',+ userId: 'user_1',+ organizationId: 'org_1',+ projectId: 'proj_1',+ level: 'write',+ });++ await subject.removeOrganizationMember({+ organizationId: 'org_1',+ memberId: 'member_1',+ targetUserId: 'user_1',+ requestedByUserId: 'user_admin',+ });++ expect(memberStore.has('member_1')).toBe(false);+ expect(projectAccessStore.has('access_1')).toBe(false);+});++test('updateOrganizationMemberAccess replaces project access with the given grants', async () => {+ projectAccessStore.set('access_old', {+ id: 'access_old',+ userId: 'user_1',+ organizationId: 'org_1',+ projectId: 'proj_old',+ level: 'read',+ });++ await subject.updateOrganizationMemberAccess({+ organizationId: 'org_1',+ targetUserId: 'user_1',+ access: [{ projectId: 'proj_new', level: 'write' }],+ });++ const remaining = [...projectAccessStore.values()];+ expect(remaining).toHaveLength(1);+ expect(remaining[0]).toMatchObject({ projectId: 'proj_new', level: 'write' });+});++test('inviteUserToOrganization refuses when the email is already a member', async () => {+ userStore.set('user_1', { id: 'user_1', email: '[email protected]' });+ memberStore.set('member_1', {+ id: 'member_1',+ organizationId: 'org_1',+ userId: 'user_1',+ role: 'org:member',+ email: '[email protected]',+ });++ await expect(+ subject.inviteUserToOrganization({+ organizationId: 'org_1',+ email: '[email protected]',+ role: 'org:member',+ access: [],+ invitedById: 'user_admin',+ })+ ).rejects.toThrow(/already a member/);+});++test('inviteUserToOrganization refuses a duplicate pending invite', async () => {+ inviteStore.set('invite_1', {+ id: 'invite_1',+ email: '[email protected]',+ organizationId: 'org_1',+ role: 'org:member',+ createdById: 'user_admin',+ projectAccess: [],+ expiresAt: new Date(Date.now() + 1000),+ createdAt: EPOCH,+ });++ await expect(+ subject.inviteUserToOrganization({+ organizationId: 'org_1',+ email: '[email protected]',+ role: 'org:member',+ access: [],+ invitedById: 'user_admin',+ })+ ).rejects.toThrow(/already invited/);+});++test('inviteUserToOrganization connects an existing user immediately, with no email sent', async () => {+ userStore.set('user_2', { id: 'user_2', email: '[email protected]' });++ const result = await subject.inviteUserToOrganization({+ organizationId: 'org_1',+ email: '[email protected]',+ role: 'org:member',+ access: [],+ invitedById: 'user_admin',+ });++ expect(result.type).toBe('is_member');+ expect(sentEmails).toHaveLength(0);+});++test('inviteUserToOrganization emails a new user and leaves the invite pending', async () => {+ const result = await subject.inviteUserToOrganization({+ organizationId: 'org_1',+ email: '[email protected]',+ role: 'org:member',+ access: [],+ invitedById: 'user_admin',+ });++ expect(result.type).toBe('is_invited');+ expect(sentEmails).toHaveLength(1);+ expect(sentEmails[0]).toMatchObject({+ templateKey: 'invite',+ to: '[email protected]',+ });+});++test('revokeInvite deletes the invite row', async () => {+ inviteStore.set('invite_1', {+ id: 'invite_1',+ email: '[email protected]',+ organizationId: 'org_1',+ role: 'org:member',+ createdById: 'user_admin',+ projectAccess: [],+ expiresAt: new Date(Date.now() + 1000),+ createdAt: EPOCH,+ });++ await subject.revokeInvite('invite_1');+ expect(inviteStore.has('invite_1')).toBe(false);+});++test('runDeleteCron sweeps orphaned and scheduled-for-deletion organizations and projects', async () => {+ organizationStore.set(+ 'org_orphaned',+ makeOrganization({ id: 'org_orphaned' })+ );+ organizationStore.set(+ 'org_paying',+ makeOrganization({+ id: 'org_paying',+ hasSubscription: true,+ isWillBeCanceled: false,+ })+ );+ memberStore.set('member_paying_admin', {+ id: 'member_paying_admin',+ organizationId: 'org_paying',+ userId: 'user_1',+ role: 'org:admin',+ email: '[email protected]',+ });+ projectStore.set('proj_orphaned', {+ id: 'proj_orphaned',+ organizationId: 'org_orphaned',+ deleteAt: null,+ });+ projectStore.set('proj_scheduled', {+ id: 'proj_scheduled',+ organizationId: 'org_paying',+ deleteAt: new Date(Date.now() - 1000),+ });++ const result = await subject.runDeleteCron();++ expect(result).toEqual({ organizations: 1, projects: 2 });+ expect(organizationStore.has('org_orphaned')).toBe(false);+ expect(organizationStore.has('org_paying')).toBe(true);+ expect(projectStore.has('proj_orphaned')).toBe(false);+ expect(projectStore.has('proj_scheduled')).toBe(false);+ expect(chCommand).toHaveBeenCalled();+});++test('runDeleteCron is a no-op when nothing is due', async () => {+ organizationStore.set('org_healthy', makeOrganization({ id: 'org_healthy' }));+ memberStore.set('member_1', {+ id: 'member_1',+ organizationId: 'org_healthy',+ userId: 'user_1',+ role: 'org:admin',+ email: '[email protected]',+ });++ const result = await subject.runDeleteCron();+ expect(result).toEqual({ organizations: 0, projects: 0 });+ expect(organizationStore.has('org_healthy')).toBe(true);+});++test('getSettingsForOrganization falls back to UTC when the organization has no timezone', async () => {+ organizationStore.set(+ 'org_1',+ makeOrganization({ id: 'org_1', timezone: null })+ );+ const result = await subject.getSettingsForOrganization('org_1');+ expect(result).toEqual({ timezone: 'UTC' });+});diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.tsnew file mode 100644index 000000000..963e5d240--- /dev/null+++ b/packages/core/src/modules/organization/organization.service.ts@@ -0,0 +1,892 @@+// Moved from packages/db/src/services/organization.service.ts ++// packages/db/src/services/delete.service.ts (M6-001, folded together per the+// module map: "delete.service in organization"). The mutation bodies inline+// in packages/trpc/src/routers/organization.ts (update/delete/cancelDeletion/+// inviteUser/revokeInvite/removeMember/updateMemberAccess) move here too, so+// V1's router and core's own organization.rpc.ts share one implementation+// (DELEGATE PATTERN). packages/db keeps a re-export shim for+// organization.service.ts: its own engine + several analytics services+// (`getSettingsForProject`) still reach it directly. packages/db loses+// delete.service.ts entirely — nothing outside apps/worker's cron job+// (now delegating here) reached it through @openpanel/db's barrel.+//+// db/ch access is LAZY (`load*` below), not a static top-level import — see+// insight.service.ts's header for the full reasoning (jobs.registry.ts and+// services.ts pull this module into the eager barrel chain nearly every core+// test file reaches, and constructing @openpanel/db's clients at import time+// would spawn a pino-pretty transport worker thread per test file).+//+// ClickHouse queries here still go through raw sqlstring-escaped strings and+// the (still-live, pre-ADR-013) `createSqlBuilder`, not the `sql` tag:+// ADR-013 converts the analytics read path one query per P7 task, and this+// module's queries haven't been converted yet.++import { DateTime } from '@openpanel/common';+import type {+ Invite,+ Prisma,+ ProjectAccess,+ User,+} from '@openpanel/db/src/prisma-client';+import { cacheable } from '@openpanel/redis';+import sqlstring from 'sqlstring';+import { sendEmail } from '../../clients/email';+import { TRPCBadRequestError } from '../../rpc/errors';+import type { ServiceDeps } from '../../services';+import { generateSecureId } from '../../shared/id';++export type IServiceOrganization = Awaited<+ ReturnType<typeof getOrganizationById>+>;+export type IServiceInvite = Invite;+export type IServiceMember = Prisma.MemberGetPayload<{+ include: { user: true };+}> & { access: ProjectAccess[] };+export type IServiceProjectAccess = ProjectAccess;++const DEFAULT_TIMEZONE = 'UTC';+// Grace period between a scheduled deletion and the `delete` cron sweeping it+// up — matches V1's `addHours(new Date(), 24)`.+const DELETE_GRACE_PERIOD_MS = 24 * 60 * 60 * 1000;+// Invite link lifetime — matches V1's `addDays(new Date(), 3)`.+const INVITE_EXPIRY_MS = 3 * 24 * 60 * 60 * 1000;++function loadDb() {+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);+}++function loadChClient() {+ return import('@openpanel/db/src/clickhouse/client');+}++function loadSqlBuilder() {+ return import('@openpanel/db/src/sql-builder').then(+ (m) => m.createSqlBuilder+ );+}++export async function getOrganizations(userId: string | null) {+ if (!userId) {+ return [];+ }++ const db = await loadDb();+ return db.organization.findMany({+ where: {+ members: {+ some: {+ userId,+ },+ },+ },+ orderBy: {+ createdAt: 'desc',+ },+ });+}++export async function getOrganizationById(organizationId: string) {+ const db = await loadDb();+ return db.organization.findUniqueOrThrow({+ where: {+ id: organizationId,+ },+ });+}++export async function getOrganizationByProjectId(projectId: string) {+ const db = await loadDb();+ const project = await db.project.findUniqueOrThrow({+ where: {+ id: projectId,+ },+ include: {+ organization: true,+ },+ });++ if (!project.organization) {+ return null;+ }++ return project.organization;+}++const ORGANIZATION_BY_PROJECT_CACHE_TTL_SEC = 60 * 5;+export const getOrganizationByProjectIdCached = cacheable(+ getOrganizationByProjectId,+ ORGANIZATION_BY_PROJECT_CACHE_TTL_SEC+);++export async function getInvites(organizationId: string): Promise<Invite[]> {+ const db = await loadDb();+ return db.invite.findMany({+ where: {+ organizationId,+ },+ orderBy: {+ createdAt: 'desc',+ },+ });+}++export async function getInviteById(inviteId: string) {+ const db = await loadDb();+ const res = await db.invite.findUnique({+ where: {+ id: inviteId,+ },+ include: {+ organization: {+ select: {+ id: true,+ name: true,+ },+ },+ },+ });++ return {+ ...res,+ isExpired: res?.expiresAt && res.expiresAt < new Date(),+ };+}++export async function getMembers(+ organizationId: string+): Promise<IServiceMember[]> {+ const db = await loadDb();+ const [members, access] = await Promise.all([+ db.member.findMany({+ where: {+ organizationId,+ userId: {+ not: null,+ },+ },+ include: {+ user: true,+ },+ }),+ db.projectAccess.findMany({+ where: {+ organizationId,+ },+ }),+ ]);++ return members.map((member) => ({+ ...member,+ access: access.filter((a) => a.userId === member.userId),+ })) as IServiceMember[];+}++export async function getMember(organizationId: string, userId: string) {+ const db = await loadDb();+ return db.member.findFirst({+ where: {+ organizationId,+ userId,+ },+ });+}++export async function connectUserToOrganization({+ user,+ inviteId,+}: {+ user: User;+ inviteId: string;+}) {+ const db = await loadDb();+ const { getOrganizationAccess, getProjectAccess } = await import(+ '@openpanel/db/src/services/access.service'+ );++ // Use primary since before this we might have just created the invite+ // If we use replica it might not find the invite+ const invite = await db.invite.findUnique({+ where: {+ id: inviteId,+ },+ });++ if (!invite) {+ throw new Error('Invite not found');+ }++ if (process.env.ALLOW_INVITATION === 'false') {+ throw new Error('Invitations are not allowed');+ }++ if (invite.expiresAt < new Date()) {+ throw new Error('Invite expired');+ }++ // The invite might be consumed by a user who is already a member of the+ // organization (e.g. accepting it a second time). Upsert atomically against+ // the (organizationId, userId) unique constraint so concurrent consumption+ // cannot create duplicate membership rows; an existing membership is reused+ // unchanged and the invite is still consumed below.+ const member = await db.member.upsert({+ where: {+ organizationId_userId: {+ organizationId: invite.organizationId,+ userId: user.id,+ },+ },+ update: {},+ create: {+ organizationId: invite.organizationId,+ userId: user.id,+ role: invite.role,+ email: user.email,+ invitedById: invite.createdById,+ },+ });++ await getOrganizationAccess.clear({+ userId: user.id,+ organizationId: invite.organizationId,+ });++ if (invite.projectAccess.length > 0) {+ for (const grant of invite.projectAccess) {+ await getProjectAccess.clear({+ userId: user.id,+ projectId: grant.projectId,+ });+ await db.projectAccess.create({+ data: {+ projectId: grant.projectId,+ userId: user.id,+ organizationId: invite.organizationId,+ // The level the inviting admin chose, not a hardcoded default.+ level: grant.level,+ },+ });+ }+ }++ await db.invite.delete({+ where: {+ id: inviteId,+ },+ });++ return member;+}++/**+ * Get the total number of events during the+ * current subscription period for an organization+ */+export async function getOrganizationBillingEventsCount(+ organization: IServiceOrganization & { projects: { id: string }[] }+): Promise<number | undefined> {+ // Trials have no Polar billing period; fall back to the trial window+ // (creation → trial end). Status stays 'trialing' even once expired.+ const isTrialStatus = organization.subscriptionStatus === 'trialing';+ const periodStart =+ organization.subscriptionCurrentPeriodStart ??+ (isTrialStatus ? organization.createdAt : null);+ const periodEnd =+ organization.subscriptionCurrentPeriodEnd ??+ (isTrialStatus ? organization.subscriptionEndsAt : null);++ if (!(periodStart && periodEnd) || organization.projects.length === 0) {+ return 0;+ }++ const { chQuery, formatClickhouseDate } = await loadChClient();+ const createSqlBuilder = await loadSqlBuilder();+ const { sb, getSql } = createSqlBuilder();++ sb.select.count = 'COUNT(*) AS count';+ sb.where.projectIds = `project_id IN (${organization.projects.map((project) => sqlstring.escape(project.id)).join(',')})`;+ sb.where.createdAt = `created_at BETWEEN ${sqlstring.escape(formatClickhouseDate(periodStart))} AND ${sqlstring.escape(formatClickhouseDate(periodEnd))}`;+ sb.where.names = `name NOT IN ('session_start', 'session_end')`;++ const res = await chQuery<{ count: number }>(getSql());+ return res[0]?.count;+}++// Lifetime event count for a set of projects (excluding session bookkeeping+// events). The onboarding emails use this instead of subscriptionPeriodEventsCount,+// which only refreshes when sessions end.+export async function getOrganizationEventsCount(+ projectIds: string[]+): Promise<number> {+ if (projectIds.length === 0) {+ return 0;+ }++ const { chQuery } = await loadChClient();+ const createSqlBuilder = await loadSqlBuilder();+ const { sb, getSql } = createSqlBuilder();++ sb.select.count = 'COUNT(*) AS count';+ sb.where.projectIds = `project_id IN (${projectIds.map((id) => sqlstring.escape(id)).join(',')})`;+ sb.where.names = `name NOT IN ('session_start', 'session_end')`;++ const res = await chQuery<{ count: number }>(getSql());+ return res[0]?.count ?? 0;+}++// Events in a recent window, for organizations whose trial lapsed but whose+// SDKs never stopped. The lifetime count above says "you once used this"; this+// one says "you are using this right now", which is the only number that+// actually argues for a subscription.+export async function getOrganizationEventsCountSince(+ projectIds: string[],+ since: Date+): Promise<number> {+ if (projectIds.length === 0) {+ return 0;+ }++ const { chQuery, formatClickhouseDate } = await loadChClient();+ const createSqlBuilder = await loadSqlBuilder();+ const { sb, getSql } = createSqlBuilder();++ sb.select.count = 'COUNT(*) AS count';+ sb.where.projectIds = `project_id IN (${projectIds.map((id) => sqlstring.escape(id)).join(',')})`;+ sb.where.names = `name NOT IN ('session_start', 'session_end')`;+ sb.where.createdAt = `created_at >= ${sqlstring.escape(formatClickhouseDate(since, true))}`;++ const res = await chQuery<{ count: number }>(getSql());+ return res[0]?.count ?? 0;+}++export async function getOrganizationBillingEventsCountSerie(+ organization: IServiceOrganization & { projects: { id: string }[] },+ {+ startDate,+ endDate,+ }: {+ startDate: Date;+ endDate: Date;+ }+): Promise<{ count: number; day: string }[]> {+ const interval = 'day';+ const { chQuery, formatClickhouseDate } = await loadChClient();+ const createSqlBuilder = await loadSqlBuilder();+ const { sb, getSql } = createSqlBuilder();++ sb.select.count = 'COUNT(*) AS count';+ sb.select.day = `toDate(toStartOf${interval.slice(0, 1).toUpperCase() + interval.slice(1)}(created_at)) AS ${interval}`;+ sb.groupBy.day = interval;+ sb.orderBy.day = `${interval} WITH FILL FROM toDate(${sqlstring.escape(formatClickhouseDate(startDate, true))}) TO toDate(${sqlstring.escape(formatClickhouseDate(endDate, true))}) STEP INTERVAL 1 ${interval.toUpperCase()}`;+ sb.where.projectIds = `project_id IN (${organization.projects.map((project) => sqlstring.escape(project.id)).join(',')})`;+ sb.where.createdAt = `${interval} BETWEEN ${sqlstring.escape(formatClickhouseDate(startDate, true))} AND ${sqlstring.escape(formatClickhouseDate(endDate, true))}`;+ sb.where.names = `name NOT IN ('session_start', 'session_end')`;++ return chQuery<{ count: number; day: string }>(getSql());+}++const BILLING_EVENTS_SERIE_CACHE_TTL_SEC = 60 * 10;+export const getOrganizationBillingEventsCountSerieCached = cacheable(+ getOrganizationBillingEventsCountSerie,+ BILLING_EVENTS_SERIE_CACHE_TTL_SEC+);++export async function getOrganizationSubscriptionChartEndDate(+ projectId: string,+ endDate: string+): Promise<string | null> {+ const organization = await getOrganizationByProjectIdCached(projectId);+ if (!organization) {+ return null;+ }+ // If the current period end date is after the subscription chart end date, we need to use the subscription chart end date+ if (+ organization.subscriptionChartEndDate &&+ new Date(endDate) > organization.subscriptionChartEndDate+ ) {+ return DateTime.fromJSDate(organization.subscriptionChartEndDate)+ .setZone(organization.timezone || DEFAULT_TIMEZONE)+ .toFormat('yyyy-MM-dd HH:mm:ss');+ }++ return endDate;+}++export async function getSettingsForOrganization(+ organizationId: string+): Promise<{ timezone: string }> {+ const db = await loadDb();+ const organization = await db.organization.findUniqueOrThrow({+ where: {+ id: organizationId,+ },+ });++ return {+ timezone: organization.timezone || DEFAULT_TIMEZONE,+ };+}++export async function getSettingsForProject(+ projectId: string+): Promise<{ timezone: string }> {+ const db = await loadDb();+ const project = await db.project.findUniqueOrThrow({+ where: {+ id: projectId,+ },+ include: {+ organization: true,+ },+ });++ return {+ timezone: project.organization.timezone || DEFAULT_TIMEZONE,+ };+}++// --- Moved from packages/db/src/services/delete.service.ts ---++export async function deleteOrganization(organizationId: string) {+ const db = await loadDb();+ return db.organization.delete({+ where: {+ id: organizationId,+ },+ });+}++export async function deleteProjects(projectIds: string[]) {+ const db = await loadDb();+ const projects = await db.project.findMany({+ where: {+ id: {+ in: projectIds,+ },+ },+ });++ if (projects.length === 0) {+ return;+ }++ for (const project of projects) {+ await db.project.delete({+ where: {+ id: project.id,+ },+ });+ }++ return projects;+}++export async function deleteFromClickhouse(projectIds: string[]) {+ const { TABLE_NAMES, ch, getReplicatedTableName } = await loadChClient();+ const where = `project_id IN (${projectIds.map((projectId) => sqlstring.escape(projectId)).join(',')})`;+ const tables = [+ TABLE_NAMES.events,+ TABLE_NAMES.profiles,+ TABLE_NAMES.events_bots,+ TABLE_NAMES.sessions,+ TABLE_NAMES.cohort_events_mv,+ TABLE_NAMES.dau_mv,+ TABLE_NAMES.event_names_mv,+ TABLE_NAMES.event_property_values_mv,+ TABLE_NAMES.cohort_members,+ TABLE_NAMES.cohort_metadata,+ TABLE_NAMES.profile_event_summary_mv,+ TABLE_NAMES.profile_event_property_summary_mv,+ TABLE_NAMES.event_profile_summary_mv,+ TABLE_NAMES.event_property_profile_summary_mv,+ ];++ for (const table of tables) {+ // If materialized view, use ALTER TABLE since DELETE is not supported+ const query = table.endsWith('_mv')+ ? `ALTER TABLE ${getReplicatedTableName(table)} DELETE WHERE ${where};`+ : `DELETE FROM ${getReplicatedTableName(table)} WHERE ${where};`;++ await ch.command({+ query,+ clickhouse_settings: {+ lightweight_deletes_sync: '0',+ },+ });+ }+}++export interface DeleteCronResult {+ organizations: number;+ projects: number;+}++/**+ * The `delete` cron fragment's body — moved from+ * apps/worker/src/jobs/cron.delete.ts's `jobDelete` (M6-001). Finds+ * organizations scheduled for deletion or orphaned (no admin member), and+ * projects individually scheduled for deletion, then sweeps both out of+ * ClickHouse and Postgres in one pass.+ */+export async function runDeleteCron(): Promise<DeleteCronResult> {+ const db = await loadDb();+ const now = new Date();++ // Find orphaned organizations (no admin member)+ // or organizations that are scheduled for deletion+ const organizations = await db.organization.findMany({+ where: {+ OR: [+ { deleteAt: { lte: now } },+ { members: { none: { role: 'org:admin' } } },+ ],+ },+ include: { projects: { select: { id: true } } },+ });++ // Skip paying organizations+ const deletableOrganizations = organizations.filter(+ (organization) =>+ !(organization.hasSubscription && !organization.isWillBeCanceled)+ );++ // Find projects that are scheduled for deletion+ const scheduledProjects = await db.project.findMany({+ where: { deleteAt: { lte: now } },+ select: { id: true },+ });++ const projectIds = [+ ...new Set([+ ...deletableOrganizations.flatMap((organization) =>+ organization.projects.map((project) => project.id)+ ),+ ...scheduledProjects.map((project) => project.id),+ ]),+ ];++ if (projectIds.length > 0) {+ await deleteFromClickhouse(projectIds);+ await deleteProjects(projectIds);+ }++ for (const organization of deletableOrganizations) {+ await deleteOrganization(organization.id);+ }++ return {+ organizations: deletableOrganizations.length,+ projects: projectIds.length,+ };+}++// --- Moved from packages/trpc/src/routers/organization.ts's inline bodies ---++export async function updateOrganization(input: {+ id: string;+ name: string;+ timezone: string;+}) {+ const db = await loadDb();+ return db.organization.update({+ where: {+ id: input.id,+ },+ data: {+ name: input.name,+ timezone: input.timezone,+ },+ });+}++/**+ * Schedule the organization and all of its projects for deletion in 24+ * hours (cancelable until then). The hourly `delete` cron removes the+ * projects (and their ClickHouse events) and the organization in a single+ * pass once their `deleteAt` has passed.+ */+export async function scheduleOrganizationDeletion(+ organizationId: string+): Promise<void> {+ const db = await loadDb();+ const organization = await getOrganizationById(organizationId);++ // Require billing to be cancelled first. We don't want to delete an+ // organization that still has a live paid subscription. Once the user has+ // cancelled (the subscription is scheduled to end), deletion is allowed.+ if (organization.hasSubscription && !organization.isWillBeCanceled) {+ throw new TRPCBadRequestError(+ 'Please cancel your subscription before deleting this organization.'+ );+ }++ const deleteAt = new Date(Date.now() + DELETE_GRACE_PERIOD_MS);+ await db.$transaction([+ db.project.updateMany({+ where: {+ organizationId,+ },+ data: {+ deleteAt,+ },+ }),+ db.organization.update({+ where: {+ id: organizationId,+ },+ data: {+ deleteAt,+ },+ }),+ ]);+}++export async function cancelOrganizationDeletion(+ organizationId: string+): Promise<void> {+ const db = await loadDb();+ await db.$transaction([+ db.project.updateMany({+ where: {+ organizationId,+ },+ data: {+ deleteAt: null,+ },+ }),+ db.organization.update({+ where: {+ id: organizationId,+ },+ data: {+ deleteAt: null,+ },+ }),+ ]);+}++export type InviteUserResult =+ | {+ type: 'is_member';+ member: Awaited<ReturnType<typeof connectUserToOrganization>>;+ }+ | {+ type: 'is_invited';+ invite: Invite & { organization: { name: string } };+ };++export async function inviteUserToOrganization(input: {+ organizationId: string;+ email: string;+ role: 'org:admin' | 'org:member';+ access: { projectId: string; level: 'read' | 'write' }[];+ invitedById: string;+}): Promise<InviteUserResult> {+ const db = await loadDb();+ const email = input.email.toLowerCase();+ const userExists = await db.user.findFirst({+ where: {+ email: {+ equals: email,+ mode: 'insensitive',+ },+ },+ });++ const alreadyMember = await db.member.findFirst({+ where: {+ userId: userExists?.id,+ organizationId: input.organizationId,+ },+ });++ if (alreadyMember && userExists) {+ throw new TRPCBadRequestError(+ 'User is already a member of the organization'+ );+ }++ const alreadyInvited = await db.invite.findFirst({+ where: {+ email,+ organizationId: input.organizationId,+ },+ });++ if (alreadyInvited) {+ throw new TRPCBadRequestError(+ 'User is already invited to the organization'+ );+ }++ const invite = await db.invite.create({+ data: {+ id: generateSecureId('invite'),+ email,+ organizationId: input.organizationId,+ role: input.role,+ createdById: input.invitedById,+ projectAccess: input.access ?? [],+ expiresAt: new Date(Date.now() + INVITE_EXPIRY_MS),+ },+ include: {+ organization: {+ select: {+ name: true,+ },+ },+ },+ });++ if (userExists) {+ const member = await connectUserToOrganization({+ user: userExists,+ inviteId: invite.id,+ });++ return {+ type: 'is_member',+ member,+ };+ }++ await sendEmail('invite', {+ to: email,+ data: {+ url: `${process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL}/onboarding?inviteId=${invite.id}`,+ organizationName: invite.organization.name,+ },+ });++ return {+ type: 'is_invited',+ invite,+ };+}++export async function getInviteOrThrow(inviteId: string): Promise<Invite> {+ const db = await loadDb();+ return db.invite.findUniqueOrThrow({+ where: {+ id: inviteId,+ },+ });+}++export async function revokeInvite(inviteId: string): Promise<Invite> {+ const db = await loadDb();+ return db.invite.delete({+ where: {+ id: inviteId,+ },+ });+}++export async function removeOrganizationMember(input: {+ organizationId: string;+ memberId: string;+ targetUserId: string;+ requestedByUserId: string;+}): Promise<void> {+ const db = await loadDb();+ const exists = await db.member.count({+ where: {+ userId: input.targetUserId,+ organizationId: input.organizationId,+ },+ });++ if (input.requestedByUserId === input.targetUserId && exists === 1) {+ throw new Error('You cannot remove yourself from the organization');+ }++ await db.$transaction([+ db.member.delete({+ where: {+ id: input.memberId,+ userId: input.targetUserId,+ organizationId: input.organizationId,+ },+ }),+ db.projectAccess.deleteMany({+ where: {+ userId: input.targetUserId,+ organizationId: input.organizationId,+ },+ }),+ ]);+}++export async function updateOrganizationMemberAccess(input: {+ organizationId: string;+ targetUserId: string;+ access: { projectId: string; level: 'read' | 'write' }[];+}) {+ const db = await loadDb();+ return db.$transaction([+ db.projectAccess.deleteMany({+ where: {+ userId: input.targetUserId,+ organizationId: input.organizationId,+ },+ }),+ db.projectAccess.createMany({+ // The level comes from the admin's choice. This used to be hardcoded+ // to 'read', which was harmless only because nothing enforced the+ // level (GHSA-f9rx-pxgw-c6rg).+ data: input.access.map((grant) => ({+ userId: input.targetUserId,+ organizationId: input.organizationId,+ projectId: grant.projectId,+ level: grant.level,+ })),+ }),+ ]);+}++export interface OrganizationService {+ get(organizationId: string): ReturnType<typeof getOrganizationById>;+ list(userId: string | null): ReturnType<typeof getOrganizations>;+ update(input: {+ id: string;+ name: string;+ timezone: string;+ }): ReturnType<typeof updateOrganization>;+ scheduleDeletion(organizationId: string): Promise<void>;+ cancelDeletion(organizationId: string): Promise<void>;+ inviteUser(+ input: Parameters<typeof inviteUserToOrganization>[0]+ ): Promise<InviteUserResult>;+ getInviteOrThrow(inviteId: string): Promise<Invite>;+ revokeInvite(inviteId: string): Promise<Invite>;+ removeMember(+ input: Parameters<typeof removeOrganizationMember>[0]+ ): Promise<void>;+ updateMemberAccess(+ input: Parameters<typeof updateOrganizationMemberAccess>[0]+ ): ReturnType<typeof updateOrganizationMemberAccess>;+ members(organizationId: string): Promise<IServiceMember[]>;+ invitations(organizationId: string): Promise<Invite[]>;+ getInvite(inviteId: string): ReturnType<typeof getInviteById>;+ runDeleteCron(): Promise<DeleteCronResult>;+}++export function createOrganizationService(+ _deps: ServiceDeps+): OrganizationService {+ return {+ get: getOrganizationById,+ list: getOrganizations,+ update: updateOrganization,+ scheduleDeletion: scheduleOrganizationDeletion,+ cancelDeletion: cancelOrganizationDeletion,+ inviteUser: inviteUserToOrganization,+ getInviteOrThrow,+ revokeInvite,+ removeMember: removeOrganizationMember,+ updateMemberAccess: updateOrganizationMemberAccess,+ members: getMembers,+ invitations: getInvites,+ getInvite: getInviteById,+ runDeleteCron,+ };+}diff --git a/packages/core/src/modules/organization/src/access.ts b/packages/core/src/modules/organization/src/access.tsnew file mode 100644index 000000000..600ad06bd--- /dev/null+++ b/packages/core/src/modules/organization/src/access.ts@@ -0,0 +1,24 @@+// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for+// this module's own router — the same binding packages/trpc/src/access.ts+// does for V1, self-contained here because the general core -> db binding+// itself moves with auth (P6), not this wave. Same shape as+// conversation/src/access.ts and gsc/src/access.ts.++import {+ canWriteProject,+ getOrganizationAccess,+ getProjectAccess,+} from '@openpanel/db/src/services/access.service';+import { getProjectById } from '@openpanel/db/src/services/project.service';+import { createAccessChecks } from '../../../shared/access';++export { getOrganizationAccess } from '@openpanel/db/src/services/access.service';++const checks = createAccessChecks({+ getProjectAccess,+ canWriteProject,+ getOrganizationAccess,+ getProjectById,+});++export const requireOrganizationAdmin = checks.requireOrganizationAdmin;diff --git a/packages/core/src/modules/user/user.rpc.test.ts b/packages/core/src/modules/user/user.rpc.test.tsnew file mode 100644index 000000000..8a8e8a3b8--- /dev/null+++ b/packages/core/src/modules/user/user.rpc.test.ts@@ -0,0 +1,59 @@+// Only the "is anyone logged in" boundary is exercised here — no database.+// The mutation bodies ride on @openpanel/db (lazy-loaded, see+// user.service.ts's header); wiring this router end-to-end against a real+// Postgres is P6's (protectedProcedure) job, not this one's — see+// user.rpc.ts's header.++import { expect, test } from 'bun:test';+import { stubHttpCtx } from '../../../test/rpc-fixtures';+import { makeTrpcContext } from '../../rpc/base';+import type { CookieOptions } from '../../shared/cookie';+import { userRouter } from './user.rpc';++const COOKIE_OPTIONS: CookieOptions = {+ domain: '.openpanel.dev',+ secure: true,+ sameSite: 'lax',+ httpOnly: true,+ path: '/',+};++// EMPTY_SESSION's shape (packages/db/src/services/auth-session.service.ts) —+// `TrpcContext.session` is never literally `null`, only its `userId` is.+const EMPTY_SESSION = { session: null, user: null, userId: null };++async function anonCaller() {+ const { ctx } = stubHttpCtx({}, EMPTY_SESSION);+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {+ cookieOptions: COOKIE_OPTIONS,+ });+ return userRouter.createCaller(trpcCtx);+}++test('deletionBlockers rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(caller.deletionBlockers()).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+});++test('delete rejects an unauthenticated caller before touching the account', async () => {+ const caller = await anonCaller();+ await expect(caller.delete()).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+});++test('update rejects an unauthenticated caller before touching the profile', async () => {+ const caller = await anonCaller();+ await expect(+ caller.update({ firstName: 'Ralph', lastName: 'Wiggum' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('debugPostCookie rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(+ caller.debugPostCookie({ sameSite: 'lax', domain: '.openpanel.dev' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});diff --git a/packages/core/src/modules/user/user.rpc.ts b/packages/core/src/modules/user/user.rpc.tsnew file mode 100644index 000000000..6f111b447--- /dev/null+++ b/packages/core/src/modules/user/user.rpc.ts@@ -0,0 +1,90 @@+// Ported from packages/trpc/src/routers/user.ts (M6-001).+//+// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware+// stack — lands in core with auth (rpc/base.ts: "those need the resolved+// Session shape and the access rules, so they land with auth (P6)"). Until+// then this router does its own minimal "is anyone logged in" check inline,+// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route+// through packages/trpc's own `protectedProcedure` (full stack included) and+// delegates its handler bodies to core's user functions (DELEGATE PATTERN) —+// this module has no queue/cron of its own, so there is no+// `ctx.services.user`, same as `conversation`.++import { z } from 'zod';+import { createTRPCRouter, procedure } from '../../rpc/base';+import { TRPCAccessError } from '../../rpc/errors';+import { deleteSessionTokenCookie } from '../auth/auth.service';+import {+ deleteUserAccount,+ listUserDeletionBlockers,+ updateUserProfile,+} from './user.service';++function requireLogin(userId: string | null | undefined): string {+ if (!userId) {+ throw new TRPCAccessError('Not authenticated');+ }+ return userId;+}++export const userRouter = createTRPCRouter({+ deletionBlockers: procedure.query(async ({ ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ return listUserDeletionBlockers(userId);+ }),++ delete: procedure.mutation(async ({ ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ await deleteUserAccount(userId);+ deleteSessionTokenCookie(ctx.setCookie);+ return true;+ }),++ update: procedure+ .input(+ z.object({+ firstName: z.string(),+ lastName: z.string(),+ })+ )+ .mutation(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ return updateUserProfile({ userId, ...input });+ }),++ debugPostCookie: procedure+ .input(+ z.object({+ sameSite: z.enum(['lax', 'strict', 'none']),+ domain: z.string(),+ })+ )+ .mutation(async ({ ctx, input }) => {+ requireLogin(ctx.session.userId);+ ctx.setCookie('debugCookie', new Date().toISOString(), {+ domain: input.domain,+ sameSite: input.sameSite,+ httpOnly: true,+ secure: true,+ path: '/',+ });+ }),++ debugGetCookie: procedure+ .input(+ z.object({+ sameSite: z.enum(['lax', 'strict', 'none']),+ domain: z.string(),+ })+ )+ .query(async ({ ctx, input }) => {+ requireLogin(ctx.session.userId);+ ctx.setCookie('debugCookie', new Date().toISOString(), {+ domain: input.domain,+ sameSite: input.sameSite,+ httpOnly: true,+ secure: true,+ path: '/',+ });+ }),+});diff --git a/packages/core/src/modules/user/user.service.test.ts b/packages/core/src/modules/user/user.service.test.tsnew file mode 100644index 000000000..c268504b1--- /dev/null+++ b/packages/core/src/modules/user/user.service.test.ts@@ -0,0 +1,182 @@+// user.service.ts's db access is lazy (`await import(...)` inside each+// function — see the file's header), which is exactly what makes+// `mock.module` work here with no import-time side effects to race: every+// mock below is registered before the subject's first call, not before its+// (side-effect-free) import.++import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';++interface FakeUser {+ id: string;+ email: string;+ firstName: string | null;+ lastName: string | null;+}++interface FakeOrganization {+ id: string;+ name: string;+ createdByUserId: string | null;+ hasSubscription: boolean;+ isWillBeCanceled: boolean;+}++const userStore = new Map<string, FakeUser>();+const organizationStore = new Map<string, FakeOrganization>();++function makeUser(overrides: Partial<FakeUser> & { id: string }): FakeUser {+ return {+ email: '[email protected]',+ firstName: null,+ lastName: null,+ ...overrides,+ };+}++const user = {+ findUniqueOrThrow: mock(+ async ({ where: { id } }: { where: { id: string } }) => {+ const found = userStore.get(id);+ if (!found) {+ throw new Error(`user ${id} not found`);+ }+ return found;+ }+ ),+ findFirst: mock(+ async ({+ where,+ include,+ }: {+ where: { email: { equals: string } };+ include?: { accounts?: { where: { provider: string } } };+ }) => {+ const found = [...userStore.values()].find(+ (u) => u.email === where.email.equals+ );+ if (!found) {+ return null;+ }+ return include?.accounts ? { ...found, accounts: [] } : found;+ }+ ),+ update: mock(+ async ({+ where: { id },+ data,+ }: {+ where: { id: string };+ data: Partial<FakeUser>;+ }) => {+ const existing = userStore.get(id);+ if (!existing) {+ throw new Error(`user ${id} not found`);+ }+ const next = { ...existing, ...data };+ userStore.set(id, next);+ return next;+ }+ ),+ delete: mock(async ({ where: { id } }: { where: { id: string } }) => {+ userStore.delete(id);+ }),+};++const organization = {+ findMany: mock(async ({ where }: { where: { createdByUserId: string } }) =>+ [...organizationStore.values()].filter(+ (o) => o.createdByUserId === where.createdByUserId+ )+ ),+};++const actualPrismaClient = await import('@openpanel/db/src/prisma-client');+mock.module('@openpanel/db/src/prisma-client', () => ({+ ...actualPrismaClient,+ db: { user, organization },+}));++let subject: typeof import('./user.service');+beforeAll(async () => {+ subject = await import('./user.service');+});++beforeEach(() => {+ userStore.clear();+ organizationStore.clear();+});++test('getUserById returns the row', async () => {+ userStore.set('user_1', makeUser({ id: 'user_1' }));+ const result = await subject.getUserById('user_1');+ expect(result).toMatchObject({ id: 'user_1' });+});++test('getUserAccount returns null when the matching provider account is missing', async () => {+ userStore.set('user_1', makeUser({ id: 'user_1' }));+ const result = await subject.getUserAccount({+ email: '[email protected]',+ provider: 'google',+ });+ expect(result).toBeNull();+});++test('updateUserProfile updates first and last name', async () => {+ userStore.set('user_1', makeUser({ id: 'user_1' }));+ const result = await subject.updateUserProfile({+ userId: 'user_1',+ firstName: 'Ralph',+ lastName: 'Wiggum',+ });+ expect(result).toMatchObject({ firstName: 'Ralph', lastName: 'Wiggum' });+});++test('listUserDeletionBlockers only returns orgs with a live, uncancelled subscription', async () => {+ organizationStore.set('org_paying', {+ id: 'org_paying',+ name: 'Paying Co',+ createdByUserId: 'user_1',+ hasSubscription: true,+ isWillBeCanceled: false,+ });+ organizationStore.set('org_canceling', {+ id: 'org_canceling',+ name: 'Canceling Co',+ createdByUserId: 'user_1',+ hasSubscription: true,+ isWillBeCanceled: true,+ });+ organizationStore.set('org_free', {+ id: 'org_free',+ name: 'Free Co',+ createdByUserId: 'user_1',+ hasSubscription: false,+ isWillBeCanceled: false,+ });++ const blockers = await subject.listUserDeletionBlockers('user_1');+ expect(blockers).toEqual([{ id: 'org_paying', name: 'Paying Co' }]);+});++test('deleteUserAccount refuses while a blocking subscription exists', async () => {+ userStore.set('user_1', makeUser({ id: 'user_1' }));+ organizationStore.set('org_paying', {+ id: 'org_paying',+ name: 'Paying Co',+ createdByUserId: 'user_1',+ hasSubscription: true,+ isWillBeCanceled: false,+ });++ await expect(subject.deleteUserAccount('user_1')).rejects.toThrow(+ /Paying Co/+ );+ expect(userStore.has('user_1')).toBe(true);+});++test('deleteUserAccount deletes the row once no blocker remains', async () => {+ userStore.set('user_1', makeUser({ id: 'user_1' }));++ await subject.deleteUserAccount('user_1');+ expect(userStore.has('user_1')).toBe(false);+});diff --git a/packages/core/src/modules/user/user.service.ts b/packages/core/src/modules/user/user.service.tsnew file mode 100644index 000000000..ad785da28--- /dev/null+++ b/packages/core/src/modules/user/user.service.ts@@ -0,0 +1,136 @@+// Moved from packages/db/src/services/user.service.ts (M6-001). packages/db+// keeps a re-export shim — packages/trpc's auth/onboarding routers (not yet+// ported) still reach `getUserById`/`getUserAccount`/`IServiceUser` through+// @openpanel/db's barrel, same shape as packages/db/src/gsc.ts since M5-002.+//+// db access is LAZY, not a static top-level import — see insight.service.ts's+// header for the full reasoning (jobs.registry.ts and services.ts pull this+// module into the eager barrel chain nearly every core test file reaches, and+// constructing @openpanel/db's clients at import time would spawn a+// pino-pretty transport worker thread per test file).+//+// No `UserService` / `createUserService` here: this module has no queue or+// cron of its own (module map: user is R,S only), so there is nothing that+// needs a Ctx-bound container — same shape as conversation.service.ts.++import { TRPCBadRequestError } from '../../rpc/errors';++export type IServiceUser = Awaited<ReturnType<typeof getUserById>>;++function loadDb() {+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);+}++export async function getUserById(id: string) {+ const db = await loadDb();+ return db.user.findUniqueOrThrow({+ where: {+ id,+ },+ });+}++export async function getUserAccount({+ email,+ provider,+ providerId,+}: {+ email: string;+ provider: string;+ providerId?: string;+}) {+ const db = await loadDb();+ const res = await db.user.findFirst({+ where: {+ email: {+ equals: email,+ mode: 'insensitive',+ },+ },+ include: {+ accounts: {+ where: {+ provider,+ providerId: providerId ? String(providerId) : undefined,+ },+ take: 1,+ },+ },+ });++ if (!res?.accounts[0]) {+ return null;+ }++ return {+ ...res,+ account: res?.accounts[0],+ };+}++export interface UserDeletionBlocker {+ id: string;+ name: string;+}++/**+ * Organizations the user created that still have a blocking subscription+ * (active and not scheduled to cancel). The account cannot be deleted while+ * any of these exist.+ */+export async function listUserDeletionBlockers(+ userId: string+): Promise<UserDeletionBlocker[]> {+ const db = await loadDb();+ const organizations = await db.organization.findMany({+ where: { createdByUserId: userId },+ });+ return organizations+ .filter(+ (organization) =>+ organization.hasSubscription && !organization.isWillBeCanceled+ )+ .map((organization) => ({+ id: organization.id,+ name: organization.name,+ }));+}++/**+ * Hard delete the user. Cascades clean up sessions, accounts, totp,+ * twoFactorChallenges, members, projectAccess, invites and conversations.+ * Organizations the user created have `createdByUserId`/`subscriptionCreatedByUserId`+ * set to null (SetNull); any org left without an org:admin member is then+ * removed by the organization module's `delete` cron.+ */+export async function deleteUserAccount(userId: string): Promise<void> {+ const blockers = await listUserDeletionBlockers(userId);++ if (blockers.length > 0) {+ throw new TRPCBadRequestError(+ `Please cancel the subscription for ${blockers+ .map((blocker) => blocker.name)+ .join(', ')} before deleting your account.`+ );+ }++ const db = await loadDb();+ await db.user.delete({ where: { id: userId } });+}++export async function updateUserProfile(input: {+ userId: string;+ firstName: string;+ lastName: string;+}) {+ const db = await loadDb();+ return db.user.update({+ where: {+ id: input.userId,+ },+ data: {+ firstName: input.firstName,+ lastName: input.lastName,+ },+ });+}diff --git a/packages/core/src/rpc.router.ts b/packages/core/src/rpc.router.tsindex 7f50649da..fe43acd68 100644--- a/packages/core/src/rpc.router.ts+++ b/packages/core/src/rpc.router.ts@@ -11,6 +11,8 @@ import { gscRouter } from './modules/gsc/gsc.rpc';import { healthRouter } from './modules/health/health.rpc';import { importRouter } from './modules/import/import.rpc';import { insightRouter } from './modules/insight/insight.rpc';+import { organizationRouter } from './modules/organization/organization.rpc';+import { userRouter } from './modules/user/user.rpc';import { createTRPCRouter } from './rpc/base';export const appRouter = createTRPCRouter({@@ -21,6 +23,8 @@ export const appRouter = createTRPCRouter({import: importRouter,chat: chatRouter,conversation: conversationRouter,+ organization: organizationRouter,+ user: userRouter,});export type AppRouter = typeof appRouter;diff --git a/packages/core/src/services.ts b/packages/core/src/services.tsindex 64a22c33d..b2139abd9 100644--- a/packages/core/src/services.ts+++ b/packages/core/src/services.ts@@ -20,6 +20,10 @@ import {createInsightService,type InsightService,} from './modules/insight/insight.service';+import {+ createOrganizationService,+ type OrganizationService,+} from './modules/organization/organization.service';/** What every service factory receives — derived from Ctx, so it cannot drift. */export type ServiceDeps = Pick<@@ -42,6 +46,7 @@ export interface Services {gsc: GscService;cohort: CohortService;import: ImportService;+ organization: OrganizationService;}export function createServices(deps: ServiceDeps): Services {@@ -54,5 +59,6 @@ export function createServices(deps: ServiceDeps): Services {gsc: createGscService(deps),cohort: createCohortService(deps),import: createImportService(deps),+ organization: createOrganizationService(deps),};}diff --git a/packages/db/index.ts b/packages/db/index.tsindex 300617dcd..b7b9471d5 100644--- a/packages/db/index.ts+++ b/packages/db/index.ts@@ -15,7 +15,6 @@ export * from './src/services/conversation.service';export * from './src/services/conversion.service';export * from './src/services/dashboard.service';export * from './src/services/date.service';-export * from './src/services/delete.service';export * from './src/services/event.service';export * from './src/services/filter-where.service';export * from './src/services/funnel.service';diff --git a/packages/db/src/services/delete.service.ts b/packages/db/src/services/delete.service.tsdeleted file mode 100644index 7dace2640..000000000--- a/packages/db/src/services/delete.service.ts+++ /dev/null@@ -1,72 +0,0 @@-import { TABLE_NAMES, ch, getReplicatedTableName } from '../clickhouse/client';-import { logger } from '../logger';-import { db } from '../prisma-client';--import sqlstring from 'sqlstring';--export async function deleteOrganization(organizationId: string) {- return await db.organization.delete({- where: {- id: organizationId,- },- });-}--export async function deleteProjects(projectIds: string[]) {- const projects = await db.project.findMany({- where: {- id: {- in: projectIds,- },- },- });-- if (projects.length === 0) {- return;- }-- for (const project of projects) {- await db.project.delete({- where: {- id: project.id,- },- });- }-- return projects;-}--export async function deleteFromClickhouse(projectIds: string[]) {- const where = `project_id IN (${projectIds.map((projectId) => sqlstring.escape(projectId)).join(',')})`;- const tables = [- TABLE_NAMES.events,- TABLE_NAMES.profiles,- TABLE_NAMES.events_bots,- TABLE_NAMES.sessions,- TABLE_NAMES.cohort_events_mv,- TABLE_NAMES.dau_mv,- TABLE_NAMES.event_names_mv,- TABLE_NAMES.event_property_values_mv,- TABLE_NAMES.cohort_members,- TABLE_NAMES.cohort_metadata,- TABLE_NAMES.profile_event_summary_mv,- TABLE_NAMES.profile_event_property_summary_mv,- TABLE_NAMES.event_profile_summary_mv,- TABLE_NAMES.event_property_profile_summary_mv,- ];-- for (const table of tables) {- // If materialized view, use ALTER TABLE since DELETE is not supported- const query = table.endsWith('_mv')- ? `ALTER TABLE ${getReplicatedTableName(table)} DELETE WHERE ${where};`- : `DELETE FROM ${getReplicatedTableName(table)} WHERE ${where};`;-- logger.info({ query }, 'Deleting from ClickHouse table:');- await ch.command({- query,- clickhouse_settings: {- lightweight_deletes_sync: '0',- },- });- }-}diff --git a/packages/db/src/services/organization.service.ts b/packages/db/src/services/organization.service.tsindex 707761790..753a4eb66 100644--- a/packages/db/src/services/organization.service.ts+++ b/packages/db/src/services/organization.service.ts@@ -1,369 +1,42 @@-import { DateTime } from '@openpanel/common';-import { cacheable } from '@openpanel/redis';-import sqlstring from 'sqlstring';-import { chQuery, formatClickhouseDate } from '../clickhouse/client';-import type { Invite, Prisma, ProjectAccess, User } from '../prisma-client';-import { db } from '../prisma-client';-import { createSqlBuilder } from '../sql-builder';-import { getOrganizationAccess, getProjectAccess } from './access.service';-import type { IServiceProject } from './project.service';-export type IServiceOrganization = Awaited<- ReturnType<typeof db.organization.findUniqueOrThrow>->;-export type IServiceInvite = Invite;-export type IServiceMember = Prisma.MemberGetPayload<{- include: { user: true };-}> & { access: ProjectAccess[] };-export type IServiceProjectAccess = ProjectAccess;--export async function getOrganizations(userId: string | null) {- if (!userId) {- return [];- }-- const organizations = await db.organization.findMany({- where: {- members: {- some: {- userId,- },- },- },- orderBy: {- createdAt: 'desc',- },- });-- return organizations;-}--export function getOrganizationById(slug: string) {- return db.organization.findUniqueOrThrow({- where: {- id: slug,- },- });-}--export async function getOrganizationByProjectId(projectId: string) {- const project = await db.project.findUniqueOrThrow({- where: {- id: projectId,- },- include: {- organization: true,- },- });-- if (!project.organization) {- return null;- }-- return project.organization;-}--export const getOrganizationByProjectIdCached = cacheable(- getOrganizationByProjectId,- 60 * 5-);--export async function getInvites(organizationId: string) {- return db.invite.findMany({- where: {- organizationId,- },- orderBy: {- createdAt: 'desc',- },- });-}--export async function getInviteById(inviteId: string) {- const res = await db.invite.findUnique({- where: {- id: inviteId,- },- include: {- organization: {- select: {- id: true,- name: true,- },- },- },- });-- return {- ...res,- isExpired: res?.expiresAt && res.expiresAt < new Date(),- };-}--export async function getMembers(organizationId: string) {- const [members, access] = await Promise.all([- db.member.findMany({- where: {- organizationId,- userId: {- not: null,- },- },- include: {- user: true,- },- }),- db.projectAccess.findMany({- where: {- organizationId,- },- }),- ]);-- return members.map((member) => ({- ...member,- access: access.filter((a) => a.userId === member.userId),- }));-}--export async function getMember(organizationId: string, userId: string) {- return db.member.findFirst({- where: {- organizationId,- userId,- },- });-}--export async function connectUserToOrganization({- user,- inviteId,-}: {- user: User;- inviteId: string;-}) {- // Use primary since before this we might have just created the invite- // If we use replica it might not find the invite- const invite = await db.invite.findUnique({- where: {- id: inviteId,- },- });-- if (!invite) {- throw new Error('Invite not found');- }-- if (process.env.ALLOW_INVITATION === 'false') {- throw new Error('Invitations are not allowed');- }-- if (invite.expiresAt < new Date()) {- throw new Error('Invite expired');- }-- // The invite might be consumed by a user who is already a member of the- // organization (e.g. accepting it a second time). Upsert atomically against- // the (organizationId, userId) unique constraint so concurrent consumption- // cannot create duplicate membership rows; an existing membership is reused- // unchanged and the invite is still consumed below.- const member = await db.member.upsert({- where: {- organizationId_userId: {- organizationId: invite.organizationId,- userId: user.id,- },- },- update: {},- create: {- organizationId: invite.organizationId,- userId: user.id,- role: invite.role,- email: user.email,- invitedById: invite.createdById,- },- });-- await getOrganizationAccess.clear({- userId: user.id,- organizationId: invite.organizationId,- });-- if (invite.projectAccess.length > 0) {- for (const grant of invite.projectAccess) {- await getProjectAccess.clear({- userId: user.id,- projectId: grant.projectId,- });- await db.projectAccess.create({- data: {- projectId: grant.projectId,- userId: user.id,- organizationId: invite.organizationId,- // The level the inviting admin chose, not a hardcoded default.- level: grant.level,- },- });- }- }-- await db.invite.delete({- where: {- id: inviteId,- },- });-- return member;-}--/**- * Get the total number of events during the- * current subscription period for an organization- */-export async function getOrganizationBillingEventsCount(- organization: IServiceOrganization & { projects: IServiceProject[] }-) {- // Trials have no Polar billing period; fall back to the trial window- // (creation → trial end). Status stays 'trialing' even once expired.- const isTrialStatus = organization.subscriptionStatus === 'trialing';- const periodStart =- organization.subscriptionCurrentPeriodStart ??- (isTrialStatus ? organization.createdAt : null);- const periodEnd =- organization.subscriptionCurrentPeriodEnd ??- (isTrialStatus ? organization.subscriptionEndsAt : null);-- if (!(periodStart && periodEnd) || organization.projects.length === 0) {- return 0;- }-- const { sb, getSql } = createSqlBuilder();-- sb.select.count = 'COUNT(*) AS count';- sb.where.projectIds = `project_id IN (${organization.projects.map((project) => sqlstring.escape(project.id)).join(',')})`;- sb.where.createdAt = `created_at BETWEEN ${sqlstring.escape(formatClickhouseDate(periodStart))} AND ${sqlstring.escape(formatClickhouseDate(periodEnd))}`;- sb.where.names = `name NOT IN ('session_start', 'session_end')`;-- const res = await chQuery<{ count: number }>(getSql());- return res[0]?.count;-}--// Lifetime event count for a set of projects (excluding session bookkeeping-// events). The onboarding emails use this instead of subscriptionPeriodEventsCount,-// which only refreshes when sessions end.-export async function getOrganizationEventsCount(projectIds: string[]) {- if (projectIds.length === 0) {- return 0;- }-- const { sb, getSql } = createSqlBuilder();-- sb.select.count = 'COUNT(*) AS count';- sb.where.projectIds = `project_id IN (${projectIds.map((id) => sqlstring.escape(id)).join(',')})`;- sb.where.names = `name NOT IN ('session_start', 'session_end')`;-- const res = await chQuery<{ count: number }>(getSql());- return res[0]?.count ?? 0;-}--// Events in a recent window, for organizations whose trial lapsed but whose-// SDKs never stopped. The lifetime count above says "you once used this"; this-// one says "you are using this right now", which is the only number that-// actually argues for a subscription.-export async function getOrganizationEventsCountSince(- projectIds: string[],- since: Date-) {- if (projectIds.length === 0) {- return 0;- }-- const { sb, getSql } = createSqlBuilder();-- sb.select.count = 'COUNT(*) AS count';- sb.where.projectIds = `project_id IN (${projectIds.map((id) => sqlstring.escape(id)).join(',')})`;- sb.where.names = `name NOT IN ('session_start', 'session_end')`;- sb.where.createdAt = `created_at >= ${sqlstring.escape(formatClickhouseDate(since, true))}`;-- const res = await chQuery<{ count: number }>(getSql());- return res[0]?.count ?? 0;-}--export async function getOrganizationBillingEventsCountSerie(- organization: IServiceOrganization & { projects: { id: string }[] },- {- startDate,- endDate,- }: {- startDate: Date;- endDate: Date;- }-) {- const interval = 'day';- const { sb, getSql } = createSqlBuilder();-- sb.select.count = 'COUNT(*) AS count';- sb.select.day = `toDate(toStartOf${interval.slice(0, 1).toUpperCase() + interval.slice(1)}(created_at)) AS ${interval}`;- sb.groupBy.day = interval;- sb.orderBy.day = `${interval} WITH FILL FROM toDate(${sqlstring.escape(formatClickhouseDate(startDate, true))}) TO toDate(${sqlstring.escape(formatClickhouseDate(endDate, true))}) STEP INTERVAL 1 ${interval.toUpperCase()}`;- sb.where.projectIds = `project_id IN (${organization.projects.map((project) => sqlstring.escape(project.id)).join(',')})`;- sb.where.createdAt = `${interval} BETWEEN ${sqlstring.escape(formatClickhouseDate(startDate, true))} AND ${sqlstring.escape(formatClickhouseDate(endDate, true))}`;- sb.where.names = `name NOT IN ('session_start', 'session_end')`;-- const res = await chQuery<{ count: number; day: string }>(getSql());- return res;-}--export const getOrganizationBillingEventsCountSerieCached = cacheable(+// The organization service — plus packages/db/src/services/delete.service.ts,+// folded in with it — lives in @openpanel/core now (M6-001). Re-exported here+// for existing `@openpanel/db` importers (packages/db's own engine ++// analytics services reading `getSettingsForProject`, packages/trpc's+// organization router, apps/worker's delete cron job) — same shape as+// packages/db/src/gsc.ts since M5-002.+export type {+ IServiceInvite,+ IServiceMember,+ IServiceOrganization,+ IServiceProjectAccess,+} from '@openpanel/core';+export {+ cancelOrganizationDeletion,+ connectUserToOrganization,+ deleteFromClickhouse,+ deleteOrganization,+ deleteProjects,+ getInviteById,+ getInvites,+ getMember,+ getMembers,+ getOrganizationBillingEventsCount,getOrganizationBillingEventsCountSerie,- 60 * 10-);--export async function getOrganizationSubscriptionChartEndDate(- projectId: string,- endDate: string-) {- const organization = await getOrganizationByProjectIdCached(projectId);- if (!organization) {- return null;- }- // If the current period end date is after the subscription chart end date, we need to use the subscription chart end date- if (- organization.subscriptionChartEndDate &&- new Date(endDate) > organization.subscriptionChartEndDate- ) {- return DateTime.fromJSDate(organization.subscriptionChartEndDate)- .setZone(organization.timezone || DEFAULT_TIMEZONE)- .toFormat('yyyy-MM-dd HH:mm:ss');- }-- return endDate;-}--const DEFAULT_TIMEZONE = 'UTC';--export async function getSettingsForOrganization(organizationId: string) {- const organization = await db.organization.findUniqueOrThrow({- where: {- id: organizationId,- },- });-- return {- timezone: organization.timezone || DEFAULT_TIMEZONE,- };-}--export async function getSettingsForProject(projectId: string) {- const project = await db.project.findUniqueOrThrow({- where: {- id: projectId,- },- include: {- organization: true,- },- });-- return {- timezone: project.organization.timezone || DEFAULT_TIMEZONE,- };-}+ getOrganizationBillingEventsCountSerieCached,+ getOrganizationById,+ getOrganizationByProjectId,+ getOrganizationByProjectIdCached,+ getOrganizationEventsCount,+ getOrganizationEventsCountSince,+ getOrganizationSubscriptionChartEndDate,+ getOrganizations,+ getSettingsForOrganization,+ getSettingsForProject,+ inviteUserToOrganization,+ removeOrganizationMember,+ revokeInvite,+ runDeleteCron,+ scheduleOrganizationDeletion,+ updateOrganization,+ updateOrganizationMemberAccess,+} from '@openpanel/core';diff --git a/packages/db/src/services/user.service.ts b/packages/db/src/services/user.service.tsindex 197bca542..6b07f8123 100644--- a/packages/db/src/services/user.service.ts+++ b/packages/db/src/services/user.service.ts@@ -1,44 +1,6 @@-import { db } from '../prisma-client';--export type IServiceUser = Awaited<ReturnType<typeof getUserById>>;--export async function getUserById(id: string) {- return db.user.findUniqueOrThrow({- where: {- id,- },- });-}--export async function getUserAccount({- email,- provider,- providerId,-}: { email: string; provider: string; providerId?: string }) {- const res = await db.user.findFirst({- where: {- email: {- equals: email,- mode: 'insensitive',- },- },- include: {- accounts: {- where: {- provider,- providerId: providerId ? String(providerId) : undefined,- },- take: 1,- },- },- });-- if (!res?.accounts[0]) {- return null;- }-- return {- ...res,- account: res?.accounts[0],- };-}+// The user service lives in @openpanel/core now (M6-001). Re-exported here+// for existing `@openpanel/db` importers (packages/trpc's auth/onboarding+// routers, not yet ported) — same shape as packages/db/src/gsc.ts since+// M5-002.+export type { IServiceUser } from '@openpanel/core';+export { getUserAccount, getUserById } from '@openpanel/core';diff --git a/packages/trpc/src/routers/organization.ts b/packages/trpc/src/routers/organization.tsindex 2183cb6cd..6b0c8a5d7 100644--- a/packages/trpc/src/routers/organization.ts+++ b/packages/trpc/src/routers/organization.ts@@ -1,20 +1,30 @@-import { generateSecureId } from '@openpanel/core';+// Dissolved into @openpanel/core's organization module (M6-001): the CRUD+// and mutation bodies moved to+// packages/core/src/modules/organization/organization.service.ts (delete.service.ts+// folded in with it). This router stays (DELEGATE PATTERN) — it keeps V1's+// protectedProcedure stack (session/access/logger/rate-limit middleware) and+// delegates every handler body to core's organization functions, same as+// conversation's router does (M5-006).import {- connectUserToOrganization,- db,+ cancelOrganizationDeletion,getInviteById,- getInvites,+ getInviteOrThrow,getMembers,getOrganizationById,getOrganizations,-} from '@openpanel/db';-import { sendEmail } from '@openpanel/email';+ inviteUserToOrganization,+ getInvites as loadInvites,+ removeOrganizationMember,+ revokeInvite as revokeInviteById,+ scheduleOrganizationDeletion,+ updateOrganization,+ updateOrganizationMemberAccess,+} from '@openpanel/core';import {zEditOrganization,zInviteUser,zUpdateMemberAccess,} from '@openpanel/validation';-import { addDays, addHours } from 'date-fns';import { z } from 'zod';import { getOrganizationAccess } from '../access';import { TRPCBadRequestError, TRPCForbiddenError } from '../errors';@@ -65,15 +75,7 @@ export const organizationRouter = createTRPCRouter({throw new TRPCForbiddenError('You do not have access to this project');}- return db.organization.update({- where: {- id: input.id,- },- data: {- name: input.name,- timezone: input.timezone,- },- });+ return updateOrganization(input);}),delete: protectedProcedure@@ -90,40 +92,12 @@ export const organizationRouter = createTRPCRouter({);}- const organization = await getOrganizationById(input.organizationId);-- // Require billing to be cancelled first. We don't want to delete an- // organization that still has a live paid subscription. Once the user has- // cancelled (the subscription is scheduled to end), deletion is allowed.- if (organization.hasSubscription && !organization.isWillBeCanceled) {- throw new TRPCBadRequestError(- 'Please cancel your subscription before deleting this organization.'- );- }-- // Schedule the organization and all of its projects for deletion in 24- // hours (cancelable until then). The hourly `delete` cron removes the- // projects (and their ClickHouse events) and the organization in a single- // pass once their `deleteAt` has passed.- const deleteAt = addHours(new Date(), 24);- await db.$transaction([- db.project.updateMany({- where: {- organizationId: input.organizationId,- },- data: {- deleteAt,- },- }),- db.organization.update({- where: {- id: input.organizationId,- },- data: {- deleteAt,- },- }),- ]);+ // Schedules the organization and all of its projects for deletion in 24+ // hours (cancelable until then); throws if a live paid subscription+ // hasn't been cancelled yet. The hourly `delete` cron removes the+ // projects (and their ClickHouse events) and the organization in a+ // single pass once their `deleteAt` has passed.+ await scheduleOrganizationDeletion(input.organizationId);return true;}),@@ -142,24 +116,7 @@ export const organizationRouter = createTRPCRouter({);}- await db.$transaction([- db.project.updateMany({- where: {- organizationId: input.organizationId,- },- data: {- deleteAt: null,- },- }),- db.organization.update({- where: {- id: input.organizationId,- },- data: {- deleteAt: null,- },- }),- ]);+ await cancelOrganizationDeletion(input.organizationId);return true;}),@@ -176,85 +133,13 @@ export const organizationRouter = createTRPCRouter({throw new TRPCForbiddenError('You do not have access to this project');}- const email = input.email.toLowerCase();- const userExists = await db.user.findFirst({- where: {- email: {- equals: email,- mode: 'insensitive',- },- },- });-- const alreadyMember = await db.member.findFirst({- where: {- userId: userExists?.id,- organizationId: input.organizationId,- },- });-- if (alreadyMember && userExists) {- throw new TRPCBadRequestError(- 'User is already a member of the organization'- );- }-- const alreadyInvited = await db.invite.findFirst({- where: {- email,- organizationId: input.organizationId,- },- });-- if (alreadyInvited) {- throw new TRPCBadRequestError(- 'User is already invited to the organization'- );- }-- const invite = await db.invite.create({- data: {- id: generateSecureId('invite'),- email,- organizationId: input.organizationId,- role: input.role,- createdById: ctx.session.userId,- projectAccess: input.access ?? [],- expiresAt: addDays(new Date(), 3),- },- include: {- organization: {- select: {- name: true,- },- },- },- });-- if (userExists) {- const member = await connectUserToOrganization({- user: userExists,- inviteId: invite.id,- });-- return {- type: 'is_member',- member,- };- }-- await sendEmail('invite', {- to: email,- data: {- url: `${process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL}/onboarding?inviteId=${invite.id}`,- organizationName: invite.organization.name,- },+ return inviteUserToOrganization({+ organizationId: input.organizationId,+ email: input.email,+ role: input.role,+ access: input.access ?? [],+ invitedById: ctx.session.userId,});-- return {- type: 'is_invited',- invite,- };}),revokeInvite: protectedProcedure.input(@@ -263,11 +148,7 @@ export const organizationRouter = createTRPCRouter({})).mutation(async ({ input, ctx }) => {- const invite = await db.invite.findUniqueOrThrow({- where: {- id: input.inviteId,- },- });+ const invite = await getInviteOrThrow(input.inviteId);const access = await getOrganizationAccess({userId: ctx.session.userId,@@ -278,11 +159,7 @@ export const organizationRouter = createTRPCRouter({throw new TRPCForbiddenError('You do not have access to this project');}- return db.invite.delete({- where: {- id: input.inviteId,- },- });+ return revokeInviteById(input.inviteId);}),removeMember: protectedProcedure@@ -294,17 +171,6 @@ export const organizationRouter = createTRPCRouter({})).mutation(async ({ input, ctx }) => {- const exists = await db.member.count({- where: {- userId: input.userId,- organizationId: input.organizationId,- },- });-- if (ctx.session.userId === input.userId && exists === 1) {- throw new Error('You cannot remove yourself from the organization');- }-const access = await getOrganizationAccess({userId: ctx.session.userId,organizationId: input.organizationId,@@ -314,21 +180,12 @@ export const organizationRouter = createTRPCRouter({throw new TRPCForbiddenError('You do not have access to this project');}- await db.$transaction([- db.member.delete({- where: {- id: input.id,- userId: input.userId,- organizationId: input.organizationId,- },- }),- db.projectAccess.deleteMany({- where: {- userId: input.userId,- organizationId: input.organizationId,- },- }),- ]);+ await removeOrganizationMember({+ organizationId: input.organizationId,+ memberId: input.id,+ targetUserId: input.userId,+ requestedByUserId: ctx.session.userId,+ });}),updateMemberAccess: protectedProcedure@@ -347,25 +204,11 @@ export const organizationRouter = createTRPCRouter({throw new TRPCForbiddenError('You do not have access to this project');}- return db.$transaction([- db.projectAccess.deleteMany({- where: {- userId: input.userId,- organizationId: input.organizationId,- },- }),- db.projectAccess.createMany({- // The level comes from the admin's choice. This used to be hardcoded- // to 'read', which was harmless only because nothing enforced the- // level (GHSA-f9rx-pxgw-c6rg).- data: input.access.map((grant) => ({- userId: input.userId,- organizationId: input.organizationId,- projectId: grant.projectId,- level: grant.level,- })),- }),- ]);+ return updateOrganizationMemberAccess({+ organizationId: input.organizationId,+ targetUserId: input.userId,+ access: input.access,+ });}),members: protectedProcedure@@ -391,7 +234,7 @@ export const organizationRouter = createTRPCRouter({if (access?.role !== 'org:admin') {throw new TRPCForbiddenError('You do not have access to this project');}- return getInvites(input.organizationId);+ return loadInvites(input.organizationId);}),getInvite: publicProcedurediff --git a/packages/trpc/src/routers/user.ts b/packages/trpc/src/routers/user.tsindex bbac16286..cdb16dd1a 100644--- a/packages/trpc/src/routers/user.ts+++ b/packages/trpc/src/routers/user.ts@@ -1,7 +1,16 @@-import { deleteSessionTokenCookie } from '@openpanel/core';-import { db } from '@openpanel/db';+// Dissolved into @openpanel/core's user module (M6-001): the CRUD itself+// moved to packages/core/src/modules/user/user.service.ts. This router+// stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack+// (session/access/logger/rate-limit middleware) and delegates every handler+// body to core's user functions, same as conversation's router does+// (M5-006).+import {+ deleteSessionTokenCookie,+ deleteUserAccount,+ listUserDeletionBlockers,+ updateUserProfile,+} from '@openpanel/core';import { z } from 'zod';-import { TRPCBadRequestError } from '../errors';import { createTRPCRouter, protectedProcedure } from '../trpc';export const userRouter = createTRPCRouter({@@ -9,43 +18,11 @@ export const userRouter = createTRPCRouter({// (active and not scheduled to cancel). The account cannot be deleted while// any of these exist.deletionBlockers: protectedProcedure.query(async ({ ctx }) => {- const organizations = await db.organization.findMany({- where: { createdByUserId: ctx.session.userId },- });- return organizations- .filter(- (organization) =>- organization.hasSubscription && !organization.isWillBeCanceled- )- .map((organization) => ({- id: organization.id,- name: organization.name,- }));+ return listUserDeletionBlockers(ctx.session.userId);}),delete: protectedProcedure.mutation(async ({ ctx }) => {- const organizations = await db.organization.findMany({- where: { createdByUserId: ctx.session.userId },- });- const blocking = organizations.filter(- (organization) =>- organization.hasSubscription && !organization.isWillBeCanceled- );-- if (blocking.length > 0) {- throw new TRPCBadRequestError(- `Please cancel the subscription for ${blocking- .map((organization) => organization.name)- .join(', ')} before deleting your account.`- );- }-- // Hard delete the user. Cascades clean up sessions, accounts, totp,- // twoFactorChallenges, members, projectAccess, invites and conversations.- // Organizations the user created have `createdByUserId`/`subscriptionCreatedByUserId`- // set to null (SetNull); any org left without an org:admin member is then- // removed by the `delete` cron.- await db.user.delete({ where: { id: ctx.session.userId } });+ await deleteUserAccount(ctx.session.userId);deleteSessionTokenCookie(ctx.setCookie);return true;@@ -59,15 +36,7 @@ export const userRouter = createTRPCRouter({})).mutation(async ({ input, ctx }) => {- return db.user.update({- where: {- id: ctx.session.userId,- },- data: {- firstName: input.firstName,- lastName: input.lastName,- },- });+ return updateUserProfile({ userId: ctx.session.userId, ...input });}),debugPostCookie: protectedProcedure.input(