Skip to content

Conversation

@ThyMinimalDev
Copy link
Contributor

@ThyMinimalDev ThyMinimalDev commented Aug 19, 2025

What does this PR do?

Refactor repositories to be able to dependency inject prisma client instead of using static methods

Mandatory Tasks (DO NOT REMOVE)

  • I have self-reviewed the code (A decent size PR without self-review might be rejected).
  • N/A I have updated the developer docs in /docs if this PR makes changes that would require a documentation change. If N/A, write N/A here and check the checkbox.
  • I confirm automated tests are in place that prove my fix is effective or that my feature works.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 19, 2025

Walkthrough

This change refactors repository usage to depend on injected PrismaClient instances instead of module-scoped clients and static methods. PrismaAttributeRepository and HostRepository now require construction with a PrismaClient and expose instance methods. All call sites in web pages, services, TRPC handlers, and tests are updated to instantiate repositories and call instance methods. Attribute-related fetches (including options) and host schedule updates are routed through these repositories. The TRPC availability util removes the exported updateHostsWithNewDefaultSchedule function, with handlers/tests using HostRepository directly. No exported/public signatures change at call sites; repository classes add constructors and non-static method signatures.

Possibly related PRs

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor-prisma-host-repository

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@keithwillcode keithwillcode added core area: core, team members only foundation platform Anything related to our platform plan labels Aug 19, 2025
@ThyMinimalDev ThyMinimalDev changed the title refactor: replace static methods of HostRepository and PrismaAttribut… refactor: static methods of HostRepository & PrismaAttributeRepository Aug 19, 2025
@graphite-app graphite-app bot requested a review from a team August 19, 2025 07:23
Comment on lines -58 to -64
export const updateHostsWithNewDefaultSchedule = async (
userId: number,
defaultScheduleId: number,
scheduleId: number
) => {
return await HostRepository.updateHostsSchedule(userId, defaultScheduleId, scheduleId);
};
Copy link
Contributor Author

Choose a reason for hiding this comment

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

not useful method, just calling repository, deleted it

@graphite-app
Copy link

graphite-app bot commented Aug 19, 2025

Graphite Automations

"Add platform team as reviewer" took an action on this PR • (08/19/25)

1 reviewer was added to this PR based on Keith Williams's automation.

const result = await hostRepo.updateHostsSchedule(userId, oldScheduleId, newScheduleId);

expect(prisma.host.updateMany).toHaveBeenCalledWith({
where: {
Copy link
Contributor Author

@ThyMinimalDev ThyMinimalDev Aug 19, 2025

Choose a reason for hiding this comment

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

tempted to fully remove those tests, basically these tests are just testing that a method calling prisma is calling prisma, no real value added

Copy link
Contributor

Choose a reason for hiding this comment

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

Yeah would be better as integration tests

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/lib/server/repository/PrismaAttributeRepository.ts (3)

13-27: Blocker: replace include with select per Prisma query guidelines

We should never use include. Replace it with select and explicitly select only the necessary fields.

-    return this.prismaClient.attribute.findMany({
-      where: {
-        name: { in: attributeNames, mode: "insensitive" },
-        teamId: orgId,
-      },
-      include: {
-        options: {
-          select: {
-            id: true,
-            value: true,
-            slug: true,
-          },
-        },
-      },
-    });
+    return this.prismaClient.attribute.findMany({
+      where: {
+        name: { in: attributeNames, mode: "insensitive" },
+        teamId: orgId,
+      },
+      select: {
+        id: true,
+        name: true,
+        type: true,
+        slug: true,
+        options: {
+          select: {
+            id: true,
+            value: true,
+            slug: true,
+          },
+        },
+      },
+    });

32-43: Limit nested selection to only required option fields

Avoid options: true; select the fields we actually use. This also keeps payloads smaller.

       select: {
         id: true,
         name: true,
         type: true,
         slug: true,
-        options: true,
+        options: {
+          select: {
+            id: true,
+            value: true,
+            slug: true,
+          },
+        },
       },

If other call sites need more fields, we can expand this, but default to least privilege. I can run a repository-wide usage search if needed.


48-57: Blocker: replace include with select per Prisma query guidelines

Same here, switch to select and fetch only required fields. Also drop redundant await.

-  async findAllByOrgIdWithOptions({ orgId }: { orgId: number }) {
-    return await this.prismaClient.attribute.findMany({
-      where: {
-        teamId: orgId,
-      },
-      include: {
-        options: true,
-      },
-    });
-  }
+  async findAllByOrgIdWithOptions({ orgId }: { orgId: number }) {
+    return this.prismaClient.attribute.findMany({
+      where: { teamId: orgId },
+      select: {
+        id: true,
+        name: true,
+        type: true,
+        slug: true,
+        options: {
+          select: {
+            id: true,
+            value: true,
+            slug: true,
+          },
+        },
+      },
+    });
+  }
🧹 Nitpick comments (11)
packages/lib/server/repository/host.ts (2)

6-15: Drop redundant await in return

No need to await a value you immediately return; it adds overhead without benefit here.

-    return await this.prismaClient.host.updateMany({
+    return this.prismaClient.host.updateMany({
       where: {
         userId,
         scheduleId: oldScheduleId,
       },
       data: {
         scheduleId: newScheduleId,
       },
     });

1-4: Repository file/class naming not aligned with guidelines

Per our repository naming guideline, prefer technology-prefixed class and filename, e.g., PrismaHostRepository in PrismaHostRepository.ts. Current filename is host.ts and class HostRepository.

If you’d like, I can prep a follow-up patch to:

  • Rename file to packages/lib/server/repository/PrismaHostRepository.ts
  • Rename class to PrismaHostRepository
  • Update imports in call sites (e.g., delete.handler.ts, util.test.ts)
packages/trpc/server/routers/viewer/availability/schedule/delete.handler.ts (2)

16-69: Make schedule reassignment and deletion atomic with a transaction

The three-step sequence (update hosts, update user default, delete schedule) can leave the system inconsistent if an intermediate step fails. Wrap these in a single transaction and use the transaction client for repository ops.

 export const deleteHandler = async ({ input, ctx }: DeleteOptions) => {
   const { user } = ctx;
-  const hostRepo = new HostRepository(prisma);
+  const hostRepo = new HostRepository(prisma);
@@
-  if (user.defaultScheduleId === input.scheduleId) {
-    // set a new default or unset default if no other schedule
-    const scheduleToSetAsDefault = await prisma.schedule.findFirst({
-      where: {
-        userId: user.id,
-        NOT: {
-          id: input.scheduleId,
-        },
-      },
-      select: {
-        id: true,
-      },
-    });
-
-    // to throw the error if there arent any other schedules
-    if (!scheduleToSetAsDefault) throw new TRPCError({ code: "BAD_REQUEST" });
-
-    await hostRepo.updateHostsSchedule(user.id, input.scheduleId, scheduleToSetAsDefault.id);
-
-    await prisma.user.update({
-      where: {
-        id: user.id,
-      },
-      data: {
-        defaultScheduleId: scheduleToSetAsDefault?.id || null,
-      },
-    });
-  } else if (user.defaultScheduleId) {
-    await hostRepo.updateHostsSchedule(user.id, input.scheduleId, user.defaultScheduleId);
-  }
-
-  await prisma.schedule.delete({
-    where: {
-      id: input.scheduleId,
-    },
-  });
+  await prisma.$transaction(async (tx) => {
+    const txHostRepo = new HostRepository(tx as any); // tx is a Prisma transaction client
+
+    if (user.defaultScheduleId === input.scheduleId) {
+      const scheduleToSetAsDefault = await tx.schedule.findFirst({
+        where: {
+          userId: user.id,
+          NOT: { id: input.scheduleId },
+        },
+        select: { id: true },
+      });
+      if (!scheduleToSetAsDefault) throw new TRPCError({ code: "BAD_REQUEST" });
+
+      await txHostRepo.updateHostsSchedule(user.id, input.scheduleId, scheduleToSetAsDefault.id);
+      await tx.user.update({
+        where: { id: user.id },
+        data: { defaultScheduleId: scheduleToSetAsDefault.id },
+      });
+    } else if (user.defaultScheduleId) {
+      await txHostRepo.updateHostsSchedule(user.id, input.scheduleId, user.defaultScheduleId);
+    }
+
+    await tx.schedule.delete({ where: { id: input.scheduleId } });
+  });

29-30: Differentiate NOT_FOUND vs UNAUTHORIZED

If the schedule doesn’t exist, return NOT_FOUND; if it exists but belongs to another user, return UNAUTHORIZED. Current check conflates both.

-  if (scheduleToDelete?.userId !== user.id) throw new TRPCError({ code: "UNAUTHORIZED" });
+  if (!scheduleToDelete) throw new TRPCError({ code: "NOT_FOUND" });
+  if (scheduleToDelete.userId !== user.id) throw new TRPCError({ code: "UNAUTHORIZED" });
packages/trpc/server/routers/viewer/availability/util.test.ts (1)

150-171: Rename the describe block for clarity

The test suite label still references the removed util name. Update it to reflect HostRepository.updateHostsSchedule.

-  describe("updateHostsWithNewDefaultSchedule", () => {
+  describe("HostRepository.updateHostsSchedule", () => {
     it("should update hosts with new scheduleId", async () => {
apps/web/app/(use-page-wrapper)/settings/organizations/(org-user-only)/members/page.tsx (1)

50-56: Consider narrowing selected fields upstream

UI only uses option.value here. Ensure the repository method returns just what’s needed (id, name, slug, options.value) to minimize payload and GC pressure.

packages/lib/service/attribute/server/getAttributes.ts (1)

219-224: Good DI step; consider threading a transaction-scoped Prisma and narrowing selected fields

Constructing PrismaAttributeRepository with the injected Prisma client is aligned with the PR’s objective. Two optional follow-ups:

  • If _queryAllData is ever called within a transaction, consider accepting a PrismaClient/TxClient param and passing that into the repo to avoid cross-connection reads.
  • The repo method findManyByOrgId currently selects options: true, which returns all option fields. Given this file only needs { id, value, slug } of options for tranformContains, trim to those fields to reduce payload.

Outside-changes support snippet (in packages/lib/server/repository/PrismaAttributeRepository.ts):

async findManyByOrgId({ orgId }: { orgId: number }) {
  return this.prismaClient.attribute.findMany({
    where: { teamId: orgId },
    select: {
      id: true,
      name: true,
      type: true,
      slug: true,
      options: {
        select: {
          id: true,
          value: true,
          slug: true,
        },
      },
    },
  });
}
packages/trpc/server/routers/viewer/attributes/list.handler.ts (1)

18-21: Nit: “apart” → “a part” in user-facing error message

Minor grammar fix for clarity: “You need to be a part of an organization…”

-      message: "You need to be apart of an organization to use this feature",
+      message: "You need to be a part of an organization to use this feature",
apps/web/app/(use-page-wrapper)/settings/(settings-layout)/teams/[id]/members/page.tsx (2)

40-44: LGTM on DI and usage; trim repo select fields to reduce payload

Using new PrismaAttributeRepository(prisma) inside the cache-builder is fine and keeps the API consistent. Ensure findAllByOrgIdWithOptions is updated to use select (not include) and only return the fields this page uses: attribute { id, name } and option { id, value, slug }. This will lower response size and adhere to the guideline.

Outside-changes support snippet (in packages/lib/server/repository/PrismaAttributeRepository.ts):

async findAllByOrgIdWithOptions({ orgId }: { orgId: number }) {
  return this.prismaClient.attribute.findMany({
    where: { teamId: orgId },
    select: {
      id: true,
      name: true,
      slug: true,
      type: true,
      options: {
        select: {
          id: true,
          value: true,
          slug: true,
          // add if truly needed by consumers:
          // isGroup: true,
          // contains: true,
        },
      },
    },
  });
}

60-62: Localize user-facing string

This is a TSX file; prefer t() for UI strings. Consider localizing the error text.

-  if (!team) {
-    throw new Error("Team not found");
-  }
+  if (!team) {
+    throw new Error(t("team_not_found"));
+  }
packages/lib/service/attribute/server/assignValueToUser.ts (1)

40-42: Nice DI refactor; update repo method to use select instead of include

Instantiation with prisma is aligned with the new pattern. The called method findManyByNamesAndOrgIdIncludeOptions currently uses include and the name encodes that. To meet our guideline, switch to select and (optionally) rename to reflect the behavior, e.g., findManyByNamesAndOrgIdWithOptions.

Outside-changes support snippet (in packages/lib/server/repository/PrismaAttributeRepository.ts):

async findManyByNamesAndOrgIdIncludeOptions({
  attributeNames,
  orgId,
}: {
  attributeNames: string[];
  orgId: number;
}) {
  return this.prismaClient.attribute.findMany({
    where: {
      name: { in: attributeNames, mode: "insensitive" },
      teamId: orgId,
    },
    select: {
      id: true,
      name: true,
      slug: true,
      type: true,
      options: {
        select: {
          id: true,
          value: true,
          slug: true,
        },
      },
    },
  });
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a91561f and cd0a236.

📒 Files selected for processing (10)
  • apps/web/app/(use-page-wrapper)/settings/(settings-layout)/teams/[id]/members/page.tsx (2 hunks)
  • apps/web/app/(use-page-wrapper)/settings/organizations/(org-user-only)/members/page.tsx (2 hunks)
  • packages/lib/server/repository/PrismaAttributeRepository.ts (3 hunks)
  • packages/lib/server/repository/host.ts (1 hunks)
  • packages/lib/service/attribute/server/assignValueToUser.ts (1 hunks)
  • packages/lib/service/attribute/server/getAttributes.ts (1 hunks)
  • packages/trpc/server/routers/viewer/attributes/list.handler.ts (2 hunks)
  • packages/trpc/server/routers/viewer/availability/schedule/delete.handler.ts (4 hunks)
  • packages/trpc/server/routers/viewer/availability/util.test.ts (4 hunks)
  • packages/trpc/server/routers/viewer/availability/util.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • packages/trpc/server/routers/viewer/availability/util.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

**/*.ts: For Prisma queries, only select data you need; never use include, always use select
Ensure the credential.key field is never returned from tRPC endpoints or APIs

Files:

  • packages/lib/service/attribute/server/getAttributes.ts
  • packages/lib/service/attribute/server/assignValueToUser.ts
  • packages/trpc/server/routers/viewer/attributes/list.handler.ts
  • packages/lib/server/repository/host.ts
  • packages/lib/server/repository/PrismaAttributeRepository.ts
  • packages/trpc/server/routers/viewer/availability/schedule/delete.handler.ts
  • packages/trpc/server/routers/viewer/availability/util.test.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Flag excessive Day.js use in performance-critical code; prefer native Date or Day.js .utc() in hot paths like loops

Files:

  • packages/lib/service/attribute/server/getAttributes.ts
  • packages/lib/service/attribute/server/assignValueToUser.ts
  • packages/trpc/server/routers/viewer/attributes/list.handler.ts
  • apps/web/app/(use-page-wrapper)/settings/organizations/(org-user-only)/members/page.tsx
  • packages/lib/server/repository/host.ts
  • apps/web/app/(use-page-wrapper)/settings/(settings-layout)/teams/[id]/members/page.tsx
  • packages/lib/server/repository/PrismaAttributeRepository.ts
  • packages/trpc/server/routers/viewer/availability/schedule/delete.handler.ts
  • packages/trpc/server/routers/viewer/availability/util.test.ts
**/*.tsx

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Always use t() for text localization in frontend code; direct text embedding should trigger a warning

Files:

  • apps/web/app/(use-page-wrapper)/settings/organizations/(org-user-only)/members/page.tsx
  • apps/web/app/(use-page-wrapper)/settings/(settings-layout)/teams/[id]/members/page.tsx
**/*Repository.ts

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Repository files must include Repository suffix, prefix with technology if applicable (e.g., PrismaAppRepository.ts), and use PascalCase matching the exported class

Files:

  • packages/lib/server/repository/PrismaAttributeRepository.ts
🧬 Code Graph Analysis (9)
packages/lib/service/attribute/server/getAttributes.ts (1)
packages/lib/server/repository/PrismaAttributeRepository.ts (1)
  • PrismaAttributeRepository (3-58)
packages/lib/service/attribute/server/assignValueToUser.ts (1)
packages/lib/server/repository/PrismaAttributeRepository.ts (1)
  • PrismaAttributeRepository (3-58)
packages/trpc/server/routers/viewer/attributes/list.handler.ts (2)
packages/lib/server/repository/PrismaAttributeRepository.ts (1)
  • PrismaAttributeRepository (3-58)
scripts/prepare-local-for-delegation-credentials-testing.js (1)
  • org (42-44)
apps/web/app/(use-page-wrapper)/settings/organizations/(org-user-only)/members/page.tsx (1)
packages/lib/server/repository/PrismaAttributeRepository.ts (1)
  • PrismaAttributeRepository (3-58)
packages/lib/server/repository/host.ts (1)
packages/prisma/index.ts (1)
  • PrismaClient (83-83)
apps/web/app/(use-page-wrapper)/settings/(settings-layout)/teams/[id]/members/page.tsx (1)
packages/lib/server/repository/PrismaAttributeRepository.ts (1)
  • PrismaAttributeRepository (3-58)
packages/lib/server/repository/PrismaAttributeRepository.ts (1)
packages/prisma/index.ts (1)
  • PrismaClient (83-83)
packages/trpc/server/routers/viewer/availability/schedule/delete.handler.ts (1)
packages/lib/server/repository/host.ts (1)
  • HostRepository (3-17)
packages/trpc/server/routers/viewer/availability/util.test.ts (1)
packages/lib/server/repository/host.ts (1)
  • HostRepository (3-17)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Install dependencies / Yarn install & cache
🔇 Additional comments (9)
packages/lib/server/repository/host.ts (1)

6-15: DI refactor looks good

Constructor injection of PrismaClient and moving to an instance method improves testability and decouples from module-scoped clients.

packages/trpc/server/routers/viewer/availability/schedule/delete.handler.ts (2)

50-50: Repository call replacement looks correct

Switch to hostRepo.updateHostsSchedule maintains previous behavior with the new DI pattern.


61-61: Repository call replacement looks correct

Second call site also correctly uses the repository instance.

packages/trpc/server/routers/viewer/availability/util.test.ts (3)

30-35: Good move to DI with a repository instance

Instantiating HostRepository with the mocked Prisma client improves isolation and keeps tests focused.


159-169: Assertion shape and call path look correct

The test validates the correct Prisma updateMany call via the repository.


181-193: Covers the no-op case

Good coverage for the zero-updates path.

packages/lib/server/repository/PrismaAttributeRepository.ts (1)

1-5: DI conversion looks good

Type-only import of PrismaClient and constructor injection are aligned with our patterns and keep runtime bundles light.

apps/web/app/(use-page-wrapper)/settings/organizations/(org-user-only)/members/page.tsx (2)

21-26: Repository instantiation in cache lambda is fine

Creating the repository with the shared prisma instance here is appropriate. Once the repository switches to select (not include) for options, this path will comply with our Prisma query guideline.


7-7: Import style consistency with prisma

This file uses import prisma from "@calcom/prisma", whereas delete.handler.ts uses a named import. Let’s standardize to one import style across the codebase.

You can reuse the audit script from the handler review to decide which style to adopt repo-wide.

Comment on lines +23 to 26
const attributeRepo = new PrismaAttributeRepository(prisma);

return await PrismaAttributeRepository.findAllByOrgIdWithOptions({ orgId: org.id });
return await attributeRepo.findAllByOrgIdWithOptions({ orgId: org.id });
};
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Instance-based repository usage looks good; ensure downstream repo query uses select not include

The switch to new PrismaAttributeRepository(prisma) is on point. However, findAllByOrgIdWithOptions in the repo uses include: { options: true }. Our guideline is “only select data you need; never use include”. Please update the repo method to use select and return only the necessary fields (id, name, slug, type, options[id,value,slug,(isGroup?),(contains?)]).

Run this script to (a) ensure no static uses of PrismaAttributeRepository remain and (b) locate include: usage inside the repository:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Checking for static method calls on PrismaAttributeRepository..."
rg -nP --type=ts --type=tsx -C2 '\bPrismaAttributeRepository\.\w+\s*\(' || true

echo
echo "Checking for 'include:' usage within PrismaAttributeRepository..."
rg -nP -C3 '(?s)class\s+PrismaAttributeRepository\b.*?\binclude\s*:' || true

Length of output: 500


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Locating the PrismaAttributeRepository implementation file..."
rg -l "class\s\+PrismaAttributeRepository" --type=ts --type=js

echo
echo "Inspecting 'include:' usage inside PrismaAttributeRepository..."
for repo_file in $(rg -l "class\s\+PrismaAttributeRepository" --type=ts --type=js); do
  echo "---- $repo_file ----"
  rg -n "include\s*:" "$repo_file" || echo "No 'include:' found in $repo_file"
done

Length of output: 217


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Locating the repository method definition..."
repo_file=$(rg -l "findAllByOrgIdWithOptions" -g "*.ts" -g "*.js" | head -n1)
if [[ -z "$repo_file" ]]; then
  echo "Error: Method definition not found."
  exit 1
fi
echo "Found in: $repo_file"

echo
echo "Checking for 'include:' vs 'select:' usage in $repo_file..."
rg -n -C2 "include\s*:" "$repo_file" || echo "No 'include:' usage found in $repo_file"
rg -n -C2 "select\s*:" "$repo_file" || echo "No 'select:' usage found in $repo_file"

Length of output: 1319


Refactor findAllByOrgIdWithOptions to use select instead of include

The method in packages/lib/server/repository/PrismaAttributeRepository.ts still uses:

// …  
include: {
  options: true,
},
// …

Please replace it with a select block that returns only the fields you need, for example:

- include: {
-   options: true,
- },
+ select: {
+   id: true,
+   name: true,
+   slug: true,
+   type: true,
+   options: {
+     select: {
+       id: true,
+       value: true,
+       slug: true,
+       isGroup: true,
+       contains: true,
+     },
+   },
+ },

This ensures we “only select data you need; never use include.”

🤖 Prompt for AI Agents
In packages/trpc/server/routers/viewer/attributes/list.handler.ts around lines
23 to 26, the call to attributeRepo.findAllByOrgIdWithOptions triggers a
repository method that uses Prisma's include: { options: true }; change that
repository method in packages/lib/server/repository/PrismaAttributeRepository.ts
to use a select block instead of include, selecting only the attribute fields
and the specific option fields you actually need (e.g., id, value, sortOrder,
etc.), update the return type accordingly, and ensure any callers (including
this handler) still receive the expected shape.

Comment on lines +1 to 3
import { HostRepository } from "@calcom/lib/server/repository/host";
import { prisma } from "@calcom/prisma";

Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Import style consistency for prisma

This file uses a named import import { prisma } from "@calcom/prisma"; while other files (e.g., the Next.js page) use a default import import prisma from "@calcom/prisma". Ensure we standardize on one style to avoid confusion.

Run this to audit usage:


🏁 Script executed:

#!/bin/bash
rg -n --type=ts -C1 -e $'^import\\s+\\{\\s*prisma\\s*\\}\\s+from\\s+"@calcom/prisma"' -e $'^import\\s+prisma\\s+from\\s+"@calcom/prisma"'

Length of output: 203787


Standardize prisma import style
Update this file to use the default export from @calcom/prisma instead of a named import:

--- packages/trpc/server/routers/viewer/availability/schedule/delete.handler.ts
@@
-import { prisma } from "@calcom/prisma";
+import prisma from "@calcom/prisma";

• Only one import style should be used across the codebase—prefer the default import (import prisma from "@calcom/prisma").
• Consider adding an ESLint rule or codemod to enforce this consistently.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { HostRepository } from "@calcom/lib/server/repository/host";
import { prisma } from "@calcom/prisma";
import { HostRepository } from "@calcom/lib/server/repository/host";
import prisma from "@calcom/prisma";
🤖 Prompt for AI Agents
In packages/trpc/server/routers/viewer/availability/schedule/delete.handler.ts
around lines 1 to 3, the file imports prisma as a named import but our codebase
standard is to use the default export; change the import to use the default
export from "@calcom/prisma" (import prisma from "@calcom/prisma") and update
any usages if necessary to match the default-imported identifier; ensure no
other named imports are required from that module and run TypeScript/ESLint to
verify, and consider adding an ESLint rule or codemod separately to enforce this
style across the repo.

@keithwillcode keithwillcode enabled auto-merge (squash) August 19, 2025 07:57
@keithwillcode keithwillcode merged commit 9e9f815 into main Aug 19, 2025
133 of 142 checks passed
@keithwillcode keithwillcode deleted the refactor-prisma-host-repository branch August 19, 2025 07:59
@github-actions
Copy link
Contributor

E2E results are ready!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core area: core, team members only foundation platform Anything related to our platform plan ready-for-e2e 💻 refactor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants