fix: restore accidentally deleted organizations schema tables#784
fix: restore accidentally deleted organizations schema tables#784anshul23102 wants to merge 1 commit into
Conversation
|
@anshul23102 is attempting to deploy a commit to the Karan Mani Tripathi 's projects Team on Vercel. A member of the Team first needs to authorize it. |
|
CodeAnt AI is reviewing your PR. |
Thanks for using CodeAnt! 🎉We're free for open-source projects. if you're enjoying it, help us grow by sharing. Share on X · |
WalkthroughRestores multi-tenant organization schema definitions in ChangesOrganizations Schema Restoration
Estimated code review effort: 2 (Simple) | ~10 minutes Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
|
@coderabbitai review |
| userEmailFk: foreignKey({ | ||
| columns: [table.userEmail], | ||
| foreignColumns: [usersTable.email], | ||
| }).onDelete("cascade"), |
There was a problem hiding this comment.
Suggestion: organizationMembershipsTable references usersTable.email before usersTable is declared in the module, which can trigger a temporal-dead-zone initialization failure when schema metadata is built. Move usersTable above this table definition (or defer the FK target lookup in a way that is guaranteed to execute after initialization) so module load does not fail. [incorrect variable usage]
Severity Level: Critical 🚨
- ❌ All modules importing configs/schema crash at load.
- ❌ Cover letter API endpoint fails on first request.
- ❌ Classroom invite API endpoint fails due to schema error.
- ❌ Reply vote API endpoint fails importing repliesTable schema.
- ⚠️ Test suites importing schema cannot run in CI.
- ⚠️ Future org membership features unusable until fixed.Steps of Reproduction ✅
1. Note module configuration in `tsconfig.json` at lines 2-16: target is "ES2017" and
module is "esnext", meaning TypeScript emits ES modules with `const` semantics and
temporal dead zone behavior.
2. Inspect `src/configs/schema.ts` where `organizationMembershipsTable` is defined at
lines 18-34. Its FK callback contains `userEmailFk` at lines 29-32, which builds
`foreignColumns: [usersTable.email]` while `usersTable` itself is only declared later at
lines 40-68 in the same file.
3. Observe that any import of `@/configs/schema` causes this file to be evaluated
top-to-bottom. For example, `src/lib/auth-utils.ts` at lines 1-2 imports `{ usersTable }`
from "@/configs/schema", and `src/app/api/cover-letter/route.ts` at lines 3-5 imports `{
coverLettersTable }` from "@/configs/schema", both forcing `schema.ts` to load when those
API routes are hit.
4. When the module `src/configs/schema.ts` is evaluated, the initializer for
`organizationMembershipsTable` at line 18 executes before `usersTable` is initialized at
line 40. The array literal `[usersTable.email]` in line 31 reads `usersTable` in its
temporal dead zone, causing a runtime `ReferenceError: Cannot access 'usersTable' before
initialization`, and the importing routes (e.g. `/api/cover-letter`) fail at startup or on
first request due to schema initialization crashing.(Use Cmd/Ctrl + Click for best experience)
Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** src/configs/schema.ts
**Line:** 29:32
**Comment:**
*Incorrect Variable Usage: `organizationMembershipsTable` references `usersTable.email` before `usersTable` is declared in the module, which can trigger a temporal-dead-zone initialization failure when schema metadata is built. Move `usersTable` above this table definition (or defer the FK target lookup in a way that is guaranteed to execute after initialization) so module load does not fail.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix|
CodeAnt AI finished reviewing your PR. |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/configs/schema.ts (1)
10-16: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winConsider a FK for
ownerEmail.
organizationMembershipsTable.userEmail(Line 30-32) has an explicit FK tousersTable.email, butorganizationsTable.ownerEmail(Line 14) does not referenceusersTableat all, so orphaned/invalid owner emails aren't prevented at the DB level. Since this restores previously-deleted code, this may be pre-existing behavior rather than a regression introduced here.♻️ Optional fix
export const organizationsTable = pgTable("organizations", { id: integer().primaryKey().generatedAlwaysAsIdentity(), name: varchar({ length: 255 }).notNull(), slug: varchar({ length: 255 }).notNull().unique(), ownerEmail: varchar("owner_email", { length: 255 }).notNull(), createdAt: timestamp("created_at").defaultNow().notNull(), -}); +}, (table) => ({ + ownerEmailFk: foreignKey({ + columns: [table.ownerEmail], + foreignColumns: [usersTable.email], + }), +}));🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/configs/schema.ts` around lines 10 - 16, Add a foreign key constraint for organizationsTable.ownerEmail so it references usersTable.email, matching the pattern already used by organizationMembershipsTable.userEmail. Update the organizations table definition in schema.ts to declare the relationship using the existing table symbols (organizationsTable and usersTable) so invalid owner emails are rejected at the database level.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@src/configs/schema.ts`:
- Around line 10-16: Add a foreign key constraint for
organizationsTable.ownerEmail so it references usersTable.email, matching the
pattern already used by organizationMembershipsTable.userEmail. Update the
organizations table definition in schema.ts to declare the relationship using
the existing table symbols (organizationsTable and usersTable) so invalid owner
emails are rejected at the database level.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 07e35df3-1aed-4de4-9c4d-4f7cb936008b
📒 Files selected for processing (1)
src/configs/schema.ts
…sage wording
- ask-ai.test.ts: the 'generate AI solution' test predates this PR's
mandatory-classroomId requirement; add a classroomId plus membership/
block-check mocks so it exercises the real (now-required) code path
instead of being rejected with 422 before reaching the AI call.
- ask-ai.test.ts: update the malformed-classroomId assertion to match the
route's actual message ('classroomId is required and must be a valid
integer.') instead of a stale placeholder string.
- teacher-insights.test.ts: same stale-message fix as other PRs in this
batch (400 case distinguishes missing vs malformed IDs; 403 case uses
'Access denied to this classroom').
- digest-functions.test.ts: invoke the Inngest function's .fn handler
directly and fix the sendDigestEmail mock contract, matching the fix
already applied in knoxiboy#784/knoxiboy#785.
Verified locally: tsc clean, eslint clean, npm run build succeeds, 211/211
tests pass across 41 suites.
…loses knoxiboy#735) The scaffolded endpoints in this PR returned hardcoded success responses without ever touching the database — POST /api/doubts/flag never recorded a flag, the auto-hide threshold check was commented out, and GET always returned an empty queue regardless of what was flagged. This finishes the implementation so the feature actually does what the PR description claims. Schema: - Add contentFlagsTable (doubt_id, reporter_email, reason, status, created_at) with a unique constraint on (doubt_id, reporter_email) so a student can't flag the same doubt twice, and cascading FKs to doubts/users. - Add isHidden boolean to doubtsTable for the auto-hide/re-show state. src/app/api/doubts/flag/route.ts: - POST inserts a real flag row, returns 409 on a duplicate flag from the same reporter, counts open flags on that doubt within the last 10 minutes, and auto-hides the doubt once the count reaches 3 (matching issue knoxiboy#735's 'distinct sessions within 10 minutes' threshold). - GET now requires the caller to be a teacher of the target classroom (via requireTeacher) and returns the real flagged-doubt queue grouped by doubt with a live flag count, instead of an empty array. - New PATCH handler gives teachers the 'dismiss' and 're-show' actions the issue calls for: dismiss resolves the open flags without touching visibility; re-show resolves the flags and clears isHidden. src/app/api/doubts/route.ts: - Exclude isHidden doubts from the student-facing feed (the poster can still see their own hidden doubt; teachers already see everything via the existing isTeacher branch), since hiding was previously a no-op — the column existed nowhere and nothing read it. Added src/__tests__/api/doubts-flag.test.ts covering auth, validation, duplicate-flag conflict, auto-hide threshold, teacher-only queue access, and both PATCH actions (12 new tests). Also includes the repo-wide CI fixes from knoxiboy#784 (this branch predates them) and the drizzle migration for the new table/column. Verified locally: tsc clean, eslint clean, npm run build succeeds, 223/223 tests pass across 42 suites, drizzle-kit generate reports no schema changes.
Restores multi-tenant organization support accidentally deleted in PR knoxiboy#731: - Restores orgRoleEnum, organizationsTable, organizationMembershipsTable - Adds organizationId column to classroomsTable with FK constraint - Ensures consumers (organizations/route.ts, rooms/route.ts) compile without errors Also fixes pre-existing test failures and TypeScript errors: - teacher-insights test: update error message assertions to match endpoint returns - digest-functions test: add inngest client mock, fix email result mock - migration integrity: remove orphan migration files with duplicate prefixes - TypeScript: fix implicit-any and readonly-property errors in route handlers Fixes knoxiboy#777 Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
7222d0e to
720ac4c
Compare
|
CodeAnt AI is running Incremental review |
Thanks for using CodeAnt! 🎉We're free for open-source projects. if you're enjoying it, help us grow by sharing. Share on X · |
|
CodeAnt AI Incremental review completed. |
|
Ready for review. Clean build, all tests passing. Quick labels when you get a sec:
Thanks! 🙏 |
|
This pull request has been closed because the requested features or bug fixes are already implemented in the repository. |
…loses knoxiboy#735) The scaffolded endpoints in this PR returned hardcoded success responses without ever touching the database — POST /api/doubts/flag never recorded a flag, the auto-hide threshold check was commented out, and GET always returned an empty queue regardless of what was flagged. This finishes the implementation so the feature actually does what the PR description claims. Schema: - Add contentFlagsTable (doubt_id, reporter_email, reason, status, created_at) with a unique constraint on (doubt_id, reporter_email) so a student can't flag the same doubt twice, and cascading FKs to doubts/users. - Add isHidden boolean to doubtsTable for the auto-hide/re-show state. src/app/api/doubts/flag/route.ts: - POST inserts a real flag row, returns 409 on a duplicate flag from the same reporter, counts open flags on that doubt within the last 10 minutes, and auto-hides the doubt once the count reaches 3 (matching issue knoxiboy#735's 'distinct sessions within 10 minutes' threshold). - GET now requires the caller to be a teacher of the target classroom (via requireTeacher) and returns the real flagged-doubt queue grouped by doubt with a live flag count, instead of an empty array. - New PATCH handler gives teachers the 'dismiss' and 're-show' actions the issue calls for: dismiss resolves the open flags without touching visibility; re-show resolves the flags and clears isHidden. src/app/api/doubts/route.ts: - Exclude isHidden doubts from the student-facing feed (the poster can still see their own hidden doubt; teachers already see everything via the existing isTeacher branch), since hiding was previously a no-op — the column existed nowhere and nothing read it. Added src/__tests__/api/doubts-flag.test.ts covering auth, validation, duplicate-flag conflict, auto-hide threshold, teacher-only queue access, and both PATCH actions (12 new tests). Also includes the repo-wide CI fixes from knoxiboy#784 (this branch predates them) and the drizzle migration for the new table/column. Verified locally: tsc clean, eslint clean, npm run build succeeds, 223/223 tests pass across 42 suites, drizzle-kit generate reports no schema changes.
|
Hey @knoxiboy! 👋 Ready for review on #784: Resolve all CI failures blocking downstream PRs (mega PR). This is the foundational fix that unblocks 5+ stalled PRs: eliminated 100+ implicit-any TS errors across 30+ files, fixed stale test assertions, resolved drizzle migration state, and wired up the CI test suite. Every downstream PR depends on this landing first. Suggested GSSoC labels (to help with contribution scoring):
Infrastructure improvements that enable other PRs are high-impact! ⚙️ |
User description
Restores the multi-tenant organizations schema tables that were accidentally deleted in PR #731.
Changes
Closes #777
Summary by CodeRabbit
CodeAnt-AI Description
Fix route errors and keep the test suite aligned with current responses
What Changed
Impact
✅ Fewer failing test runs✅ Clearer teacher insights error messages✅ Fewer build-time type errors💡 Usage Guide
Checking Your Pull Request
Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.
Talking to CodeAnt AI
Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:
This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.
Example
Preserve Org Learnings with CodeAnt
You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:
This helps CodeAnt AI learn and adapt to your team's coding style and standards.
Example
Retrigger review
Ask CodeAnt AI to review the PR again, by typing:
Check Your Repository Health
To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.