8000 Eng 420 introduce patient cohorts into our api by RamilGaripov · Pull Request #3962 · metriport/metriport · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Eng 420 introduce patient cohorts into our api #3962

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jun 20, 2025

Conversation

RamilGaripov
Copy link
Contributor
@RamilGaripov RamilGaripov commented Jun 5, 2025

Issues:

Dependencies

Description

  • Added a migration to create two new tables: cohort and patient_cohort
  • Added an interface for the sequelize models to create / access data from those tables
  • Added the sequelize models for both tables

Testing

  • Local
    • Start the API and check if migration is a success
    • Check the DB tables on DBeaver
      • cohort table is good
      • patient_cohort table is good
      • constraints are as expected
      • more tests - link
  • Staging
    • Check if migration is a success
    • Check the DB tables on DBeaver
      • cohort table is good
      • patient_cohort table is good
      • constraints are as expected
      • more tests - link
  • Production
    • TBA

Release Plan

  • ⚠️ This contains a DB migration
  • Merge this

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced support for managing medical cohorts, including creation of cohorts and assignment of patients to cohorts.
    • Added the ability to specify and store monitoring settings for each cohort.
  • Database Changes

    • Added new database tables for cohorts and patient-cohort associations to support cohort management functionality.

Part of ENG-420

Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-420

Signed-off-by: Ramil Garipov <ramil@metriport.com>
Copy link
linear bot commented Jun 5, 2025

Copy link
coderabbitai bot commented Jun 5, 2025

Walkthrough

This update introduces new domain types and Sequelize model classes for managing medical cohorts and their patient associations. It adds corresponding database migration scripts to create the necessary tables ("cohort" and "patient_cohort") and updates the model initialization logic to include the new models for Sequelize setup.

Changes

File(s) Change Summary
packages/core/src/domain/cohort.ts Added domain types and interfaces for cohorts and patient-cohort relationships.
packages/api/src/models/medical/cohort.ts Added CohortModel Sequelize ORM class representing the "cohort" table.
packages/api/src/models/medical/patient-cohort.ts Added PatientCohortModel Sequelize ORM class representing the "patient_cohort" join table.
packages/api/src/models/db.ts Updated imports and included CohortModel.setup and PatientCohortModel.setup in the Sequelize models array.
packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort.ts Added migration to create and drop the "cohort" table with columns for id, cxId, name, and monitoring, including versioning.
packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts Added migration to create and drop the "patient_cohort" join table with foreign keys, unique constraint, and index on cohort_id.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant CohortModel
    participant PatientCohortModel
    participant Database

    Client->>API: Request to create cohort
    API->>CohortModel: Call setup/init
    CohortModel->>Database: Create cohort record

    Client->>API: Assign patient to cohort
    API->>PatientCohortModel: Call setup/init
    PatientCohortModel->>Database: Create patient_cohort association
Loading

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error code ERR_SSL_WRONG_VERSION_NUMBER
npm error errno ERR_SSL_WRONG_VERSION_NUMBER
npm error request to https://10.0.0.28:4873/punycode/-/punycode-2.3.1.tgz failed, reason: C00C6540257F0000:error:0A00010B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:354:
npm error
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-20T15_46_37_942Z-debug-0.log


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d90706f and f5f5ec0.

📒 Files selected for processing (1)
  • packages/api/src/models/db.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/api/src/models/db.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

Part of ENG-420

Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-420

Signed-off-by: Ramil Garipov <ramil@metriport.com>
@RamilGaripov RamilGaripov marked this pull request as ready for review June 17, 2025 15:22
coderabbitai[bot]
Copy link
@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

🧹 Nitpick comments (4)
packages/core/src/domain/cohort.ts (1)

7-12: Consider renaming cxId for clarity

cxId is an internal abbreviation that may not be obvious to new contributors. customerId (or similar) would be self-explanatory and still map cleanly to the cx_id DB column.

packages/api/src/models/medical/cohort.ts (3)

13-31: Avoid duplicating attributes & address linter warning

You build the attribute map twice (in attributes() and again in setup()) and use super inside a static context, which Biome flags. Prefer a single source of truth and explicit class names:

-  static override attributes() {
-    return {
-      ...super.attributes(),
+  static override attributes() {
+    return {
+      ...BaseModel.attributes(),

Then inside setup() simply call CohortModel.attributes() instead of rebuilding the object.


52-55: Use explicit class name for clarity

this.NAME inside a static method is valid but fails the noThisInStatic lint rule. Swap to the class identifier:

-        tableName: this.NAME,
+        tableName: CohortModel.NAME,

96-101: Same lint issue applies here – replace this.NAME with CohortAssignmentModel.NAME (and super with BaseModelNoId) to silence the warning.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 255246c and dcb50e8.

📒 Files selected for processing (4)
  • packages/api/src/models/db.ts (3 hunks)
  • packages/api/src/models/medical/cohort.ts (1 hunks)
  • packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts (1 hunks)
  • packages/core/src/domain/cohort.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.ts`: - Use the Onion Pattern to organize a package's code in layers - Try to use immutable code and avoid sharing state across different functions, objects, and systems - Try...

**/*.ts: - Use the Onion Pattern to organize a package's code in layers

  • Try to use immutable code and avoid sharing state across different functions, objects, and systems
  • Try to build code that's idempotent whenever possible
  • Prefer functional programming style functions: small, deterministic, 1 input, 1 output
  • Minimize coupling / dependencies
  • Avoid modifying objects received as parameter
  • Only add comments to code to explain why something was done, not how it works
  • Naming
    • classes, enums: PascalCase
    • constants, variables, functions: camelCase
    • file names: kebab-case
    • table and column names: snake_case
    • Use meaningful names, so whoever is reading the code understands what it means
    • Don’t use negative names, like notEnabled, prefer isDisabled
    • For numeric values, if the type doesn’t convey the unit, add the unit to the name
  • Typescript
    • Use types
    • Prefer const instead of let
    • Avoid any and casting from any to other types
    • Type predicates: only applicable to narrow down the type, not to force a complete type conversion
    • Prefer deconstructing parameters for functions instead of multiple parameters that might be of
      the same type
    • Don’t use null inside the app, only on code interacting with external interfaces/services,
      like DB and HTTP; convert to undefined before sending inwards into the code
    • Use async/await instead of .then()
    • Use the strict equality operator ===, don’t use abstract equality operator ==
    • When calling a Promise-returning function asynchronously (i.e., not awaiting), use .catch() to
      handle errors (see processAsyncError and emptyFunction depending on the case)
    • Date and Time
      • Always use buildDayjs() to create dayjs instances
      • Prefer dayjs.duration(...) to create duration consts and keep them as duration
  • Prefer Nullish Coalesce (??) than the OR operator (||) to provide a default value
  • Avoid creating arrow functions
  • Use truthy syntax instead of in - i.e., if (data.link) not if ('link' in data)
  • Error handling
    • Pass the original error as the new one’s cause so the stack trace is persisted
    • Error messages should have a static message - add dynamic data to MetriportError's additionalInfo prop
    • Avoid sending multiple events to Sentry for a single error
  • Global constants and variables
    • Move literals to constants declared after imports when possible (avoid magic numbers)
    • Avoid shared, global objects
  • Avoid using console.log and console.error in packages other than utils, infra and shared,
    and try to use out().log instead
  • Avoid multi-line logs
    • don't send objects as a second parameter to console.log() or out().log()
    • don't create multi-line strings when using JSON.stringify()
  • Use eslint to enforce code style
  • Use prettier to format code
  • max column length is 100 chars
  • multi-line comments use /** */
  • scripts: top-level comments go after the import
  • packages/api/src/models/db.ts
  • packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts
  • packages/core/src/domain/cohort.ts
  • packages/api/src/models/medical/cohort.ts
🧬 Code Graph Analysis (3)
packages/api/src/models/db.ts (1)
packages/api/src/models/medical/cohort.ts (2)
  • CohortModel (5-57)
  • CohortAssignmentModel (59-109)
packages/core/src/domain/cohort.ts (1)
packages/shared/src/domain/base-domain.ts (3)
  • BaseDomainCreate (1-3)
  • BaseDomain (10-12)
  • BaseDomainNoId (5-8)
packages/api/src/models/medical/cohort.ts (2)
packages/core/src/domain/cohort.ts (3)
  • Cohort (14-14)
  • MonitoringSettings (3-5)
  • CohortAssignment (25-25)
packages/api/src/models/_default.ts (1)
  • ModelSetup (17-17)
🪛 Biome (1.9.4)
packages/api/src/models/medical/cohort.ts

[error] 15-15: Using super in a static context can be confusing.

super refers to a parent class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 98-98: Using super in a static context can be confusing.

super refers to a parent class.

(lint/complexity/noThisInStatic)


[error] 99-99: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (4)
packages/core/src/domain/cohort.ts (1)

1-26: Domain layer looks solid

New cohort-related domain types are well-structured, immutable and follow the existing BaseDomain* hierarchy. No correctness issues spotted.

packages/api/src/models/db.ts (2)

32-33: Model imports wired correctly

CohortModel and CohortAssignmentModel are imported next to their peers – good job keeping the registry centralised.


75-77: Verify FK source model initialisation order

CohortAssignmentModel references both patient and cohort tables.
PatientModel.setup and CohortModel.setup already appear earlier in the array, so Sequelize should resolve all FKs, but please run a quick migration + sync locally just in case.

packages/api/src/models/medical/cohort.ts (1)

70-83: Confirm patientId datatype alignment

The model sets patientId as UUID; ensure the patient table column is also uuid (and update the migration as noted). A mismatch will surface only at runtime.

Part of ENG-420

Signed-off-by: Ramil Garipov <ramil@metriport.com>
Copy link
@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: 3

♻️ Duplicate comments (1)
packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort.ts (1)

18-22: Add NOT-NULL in model or relax DB – cx_id mismatch

DB enforces NOT NULL on cx_id. Current CohortModel.setup() allows null values.
Once the model fix in cohort.ts is applied (see earlier comment) this will be aligned; otherwise inserts will fail.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dcb50e8 and a2a9c44.

📒 Files selected for processing (5)
  • packages/api/src/models/db.ts (3 hunks)
  • packages/api/src/models/medical/cohort.ts (1 hunks)
  • packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort.ts (1 hunks)
  • packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts (1 hunks)
  • packages/core/src/domain/cohort.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/api/src/models/db.ts
  • packages/core/src/domain/cohort.ts
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.ts`: - Use the Onion Pattern to organize a package's code in layers - Try to use immutable code and avoid sharing state across different functions, objects, and systems - Try...

**/*.ts: - Use the Onion Pattern to organize a package's code in layers

  • Try to use immutable code and avoid sharing state across different functions, objects, and systems
  • Try to build code that's idempotent whenever possible
  • Prefer functional programming style functions: small, deterministic, 1 input, 1 output
  • Minimize coupling / dependencies
  • Avoid modifying objects received as parameter
  • Only add comments to code to explain why something was done, not how it works
  • Naming
    • class 8000 es, enums: PascalCase
    • constants, variables, functions: camelCase
    • file names: kebab-case
    • table and column names: snake_case
    • Use meaningful names, so whoever is reading the code understands what it means
    • Don’t use negative names, like notEnabled, prefer isDisabled
    • For numeric values, if the type doesn’t convey the unit, add the unit to the name
  • Typescript
    • Use types
    • Prefer const instead of let
    • Avoid any and casting from any to other types
    • Type predicates: only applicable to narrow down the type, not to force a complete type conversion
    • Prefer deconstructing parameters for functions instead of multiple parameters that might be of
      the same type
    • Don’t use null inside the app, only on code interacting with external interfaces/services,
      like DB and HTTP; convert to undefined before sending inwards into the code
    • Use async/await instead of .then()
    • Use the strict equality operator ===, don’t use abstract equality operator ==
    • When calling a Promise-returning function asynchronously (i.e., not awaiting), use .catch() to
      handle errors (see processAsyncError and emptyFunction depending on the case)
    • Date and Time
      • Always use buildDayjs() to create dayjs instances
      • Prefer dayjs.duration(...) to create duration consts and keep them as duration
  • Prefer Nullish Coalesce (??) than the OR operator (||) to provide a default value
  • Avoid creating arrow functions
  • Use truthy syntax instead of in - i.e., if (data.link) not if ('link' in data)
  • Error handling
    • Pass the original error as the new one’s cause so the stack trace is persisted
    • Error messages should have a static message - add dynamic data to MetriportError's additionalInfo prop
    • Avoid sending multiple events to Sentry for a single error
  • Global constants and variables
    • Move literals to constants declared after imports when possible (avoid magic numbers)
    • Avoid shared, global objects
  • Avoid using console.log and console.error in packages other than utils, infra and shared,
    and try to use out().log instead
  • Avoid multi-line logs
    • don't send objects as a second parameter to console.log() or out().log()
    • don't create multi-line strings when using JSON.stringify()
  • Use eslint to enforce code style
  • Use prettier to format code
  • max column length is 100 chars
  • multi-line comments use /** */
  • scripts: top-level comments go after the import
  • packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort.ts
  • packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts
  • packages/api/src/models/medical/cohort.ts
🪛 Biome (1.9.4)
packages/api/src/models/medical/cohort.ts

[error] 14-14: Using super in a static context can be confusing.

super refers to a parent class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 88-88: Using super in a static context can be confusing.

super refers to a parent class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 89-89: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
packages/api/src/models/medical/cohort.ts (1)

70-80: Model expects ON DELETE CASCADE; migration does not add it

Both patientId & cohortId specify onDelete: "CASCADE", but the join-table migration omits onDelete.
Either drop the option here or extend the migration with onDelete: "CASCADE" for both FKs to match expectations.

packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts (2)

39-45: Composite PK already created; setting primaryKey: true on each column in model is fine

Good job naming the constraint explicitly; this avoids random names in different environments.


16-32: Datatype / FK options inconsistent with model

  1. patient_id is declared STRING, model uses UUID.
  2. No onDelete: "CASCADE" is provided, yet the model expects it.

Please update to keep ORM ↔ DB in sync:

-        patient_id: {
-          type: DataTypes.STRING,
+        patient_id: {
+          type: DataTypes.UUID,
           allowNull: false,
           references: {
             model: patientTableName,
             key: "id",
           },
+          onDelete: "CASCADE",
         },

…and apply the same to cohort_id.

⛔ Skipped due to learnings
Learnt from: RamilGaripov
PR: metriport/metriport#3962
File: packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts:50-56
Timestamp: 2025-06-17T20:03:18.904Z
Learning: In the Metriport codebase, the patient table ID is defined as DataTypes.STRING in the database schema, not UUID. Foreign key references to patient.id should use DataTypes.STRING to maintain consistency.

Part of ENG-420

Signed-off-by: Ramil Garipov <ramil@metriport.com>
Copy link
@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: 1

🧹 Nitpick comments (1)
packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts (1)

11-13: Remove dead code or put it to use

patientCohortIndex is commented-out and never referenced. Either delete it or wire it up; leaving commented constants behind clutters migrations and invites drift.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a2a9c44 and 6cb9671.

📒 Files selected for processing (1)
  • packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.ts`: - Use the Onion Pattern to organize a package's code in layers - Try to use immutable code and avoid sharing state across different functions, objects, and systems - Try...

**/*.ts: - Use the Onion Pattern to organize a package's code in layers

  • Try to use immutable code and avoid sharing state across different functions, objects, and systems
  • Try to build code that's idempotent whenever possible
  • Prefer functional programming style functions: small, deterministic, 1 input, 1 output
  • Minimize coupling / dependencies
  • Avoid modifying objects received as parameter
  • Only add comments to code to explain why something was done, not how it works
  • Naming
    • classes, enums: PascalCase
    • constants, variables, functions: camelCase
    • file names: kebab-case
    • table and column names: snake_case
    • Use meaningful names, so whoever is reading the code understands what it means
    • Don’t use negative names, like notEnabled, prefer isDisabled
    • For numeric values, if the type doesn’t convey the unit, add the unit to the name
  • Typescript
    • Use types
    • Prefer const instead of let
    • Avoid any and casting from any to other types
    • Type predicates: only applicable to narrow down the type, not to force a complete type conversion
    • Prefer deconstructing parameters for functions instead of multiple parameters that might be of
      the same type
    • Don’t use null inside the app, only on code interacting with external interfaces/services,
      like DB and HTTP; convert to undefined before sending inwards into the code
    • Use async/await instead of .then()
    • Use the strict equality operator ===, don’t use abstract equality operator ==
    • When calling a Promise-returning function asynchronously (i.e., not awaiting), use .catch() to
      handle errors (see processAsyncError and emptyFunction depending on the case)
    • Date and Time
      • Always use buildDayjs() to create dayjs instances
      • Prefer dayjs.duration(...) to create duration consts and keep them as duration
  • Prefer Nullish Coalesce (??) than the OR operator (||) to provide a default value
  • Avoid creating arrow functions
  • Use truthy syntax instead of in - i.e., if (data.link) not if ('link' in data)
  • Error handling
    • Pass the original error as the new one’s cause so the stack trace is persisted
    • Error messages should have a static message - add dynamic data to MetriportError's additionalInfo prop
    • Avoid sending multiple events to Sentry for a single error
  • Global constants and variables
    • Move literals to constants declared after imports when possible (avoid magic numbers)
    • Avoid shared, global objects
  • Avoid using console.log and console.error in packages other than utils, infra and shared,
    and try to use out().log instead
  • Avoid multi-line logs
    • don't send objects as a second parameter to console.log() or out().log()
    • don't create multi-line strings when using JSON.stringify()
  • Use eslint to enforce code style
  • Use prettier to format code
  • max column length is 100 chars
  • multi-line comments use /** */
  • scripts: top-level comments go after the import
  • packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts (1)

25-44: ```shell
#!/bin/bash

List migration files to identify patient table creation migration

ls packages/api/src/sequelize/migrations


</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Part of ENG-420

Signed-off-by: Ramil Garipov <ramil@metriport.com>
Copy link
@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: 1

♻️ Duplicate comments (3)
packages/api/src/models/medical/cohort.ts (3)

15-18: cxId is missing the field: "cx_id" mapping (repeat issue)

Without the explicit mapping, Sequelize looks for a cxId column that doesn’t exist (migration creates cx_id).

       cxId: {
         type: DataTypes.UUID,
         allowNull: false,
+        field: "cx_id",
       },

29-43: setup() re-declares attributes and drifts from attributes() (repeat issue)

The block duplicates the attribute bag, omits allowNull: false on cxId, and will inevitably diverge from the canonical attributes() definition.

-    CohortModel.init(
-      {
-        ...BaseModel.attributes(),
-        cxId: {
-          type: DataTypes.UUID,
-        },
-        name: {
-          type: DataTypes.STRING,
-          allowNull: false,
-        },
-        monitoring: {
-          type: DataTypes.JSONB,
-        },
-      },
+    CohortModel.init(
+      CohortModel.attributes(),
       {
         ...BaseModel.modelOptions(sequelize),
-        tableName: this.NAME,
+        tableName: CohortModel.NAME,
       }
     );

60-70: patientId datatype diverges from migration – runtime cast errors ahead

Migration defines patient_id as STRING; the model sets UUID.
Align the types and re-enable cascading delete to keep behaviour consistent with the migration.

-      patientId: {
-        type: DataTypes.UUID,
+      patientId: {
+        type: DataTypes.STRING,
         allowNull: false,
         field: "patient_id",
         primaryKey: true,
         references: {
           model: "patient",
           key: "id",
         },
-        // onDelete: "CASCADE",
+        onDelete: "CASCADE",
       },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6cb9671 and f71da77.

📒 Files selected for processing (3)
  • packages/api/src/models/medical/cohort.ts (1 hunks)
  • packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts (1 hunks)
  • packages/core/src/domain/cohort.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts
  • packages/core/src/domain/cohort.ts
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.ts`: - Use the Onion Pattern to organize a package's code in layers - Try to use immutable code and avoid sharing state across different functions, objects, and systems - Try...

**/*.ts: - Use the Onion Pattern to organize a package's code in layers

  • Try to use immutable code and avoid sharing state across different functions, objects, and systems
  • Try to build code that's idempotent whenever possible
  • Prefer functional programming style functions: small, deterministic, 1 input, 1 output
  • Minimize coupling / dependencies
  • Avoid modifying objects received as parameter
  • Only add comments to code to explain why something was done, not how it works
  • Naming
    • classes, enums: PascalCase
    • constants, variables, functions: camelCase
    • file names: kebab-case
    • table and column names: snake_case
    • Use meaningful names, so whoever is reading the code understands what it means
    • Don’t use negative names, like notEnabled, prefer isDisabled
    • For numeric values, if the type doesn’t convey the unit, add the unit to the name
  • Typescript
    • Use types
    • Prefer const instead of let
    • Avoid any and casting from any to other types
    • Type predicates: only applicable to narrow down the type, not to force a complete type conversion
    • Prefer deconstructing parameters for functions instead of multiple parameters that might be of
      the same type
    • Don’t use null inside the app, only on code interacting with external interfaces/services,
      like DB and HTTP; convert to undefined before sending inwards into the code
    • Use async/await instead of .then()
    • Use the strict equality operator ===, don’t use abstract equality operator ==
    • When calling a Promise-returning function asynchronously (i.e., not awaiting), use .catch() to
      handle errors (see processAsyncError and emptyFunction depending on the case)
    • Date and Time
      • Always use buildDayjs() to create dayjs instances
      • Prefer dayjs.duration(...) to create duration consts and keep them as duration
  • Prefer Nullish Coalesce (??) than the OR operator (||) to provide a default value
  • Avoid creating arrow functions
  • Use truthy syntax instead of in - i.e., if (data.link) not if ('link' in data)
  • Error handling
    • Pass the original error as the new one’s cause so the stack trace is persisted
    • Error messages should have a static message - add dynamic data to MetriportError's additionalInfo prop
    • Avoid sending multiple events to Sentry for a single error
  • Global constants and variables
    • Move literals to constants declared after imports when possible (avoid magic numbers)
    • Avoid shared, global objects
  • Avoid using console.log and console.error in packages other than utils, infra and shared,
    and try to use out().log instead
  • Avoid multi-line logs
    • don't send objects as a second parameter to console.log() or out().log()
    • don't create multi-line strings when using JSON.stringify()
  • Use eslint to enforce code style
  • Use prettier to format code
  • max column length is 100 chars
  • multi-line comments use /** */
  • scripts: top-level comments go after the import
  • packages/api/src/models/medical/cohort.ts
🧠 Learnings (1)
packages/api/src/models/m A93C edical/cohort.ts (1)
Learnt from: RamilGaripov
PR: metriport/metriport#3962
File: packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts:50-56
Timestamp: 2025-06-17T20:03:18.904Z
Learning: In the Metriport codebase, the patient table ID is defined as DataTypes.STRING in the database schema, not UUID. Foreign key references to patient.id should use DataTypes.STRING to maintain consistency.
🪛 Biome (1.9.4)
packages/api/src/models/medical/cohort.ts

[error] 14-14: Using super in a static context can be confusing.

super refers to a parent class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 60-60: Using super in a static context can be confusing.

super refers to a parent class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 89-89: Using super in a static context can be confusing.

super refers to a parent class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 90-90: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)

Part of ENG-420

Signed-off-by: Ramil Garipov <ramil@metriport.com>
Copy link
@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: 0

♻️ Duplicate comments (3)
packages/api/src/models/medical/cohort.ts (3)

61-70: patientId datatype should be STRING, not UUID
See migration 2025-06-17_01_create-patient-cohort.ts and earlier learning that patient.id is STRING. Misaligned types will throw cast errors on insert / join.


71-80: Uncomment onDelete: "CASCADE" on cohortId for symmetric cleanup
Keeps join table tidy when a cohort is deleted and mirrors the (likely) cascade on patientId.


15-18: Add explicit field: "cx_id" mapping to avoid runtime column mismatch

The migration creates the column as cx_id, but the model currently leaves the default (cxId). Without an explicit field mapping, Sequelize will generate SELECT "cxId" … and fail at runtime.

       cxId: {
         type: DataTypes.UUID,
         allowNull: false,
+        field: "cx_id",
       },
🧹 Nitpick comments (1)
packages/api/src/models/medical/cohort.ts (1)

87-88: Minor: use the class name instead of this in static context

Static code is clearer and avoids Biome warnings:

-      tableName: this.NAME,
+      tableName: PatientCohortModel.NAME,
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f71da77 and 6b042a1.

📒 Files selected for processing (1)
  • packages/api/src/models/medical/cohort.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.ts`: - Use the Onion Pattern to organize a package's code in layers - Try to use immutable code and avoid sharing state across different functions, objects, and systems - Try...

**/*.ts: - Use the Onion Pattern to organize a package's code in layers

  • Try to use immutable code and avoid sharing state across different functions, objects, and systems
  • Try to build code that's idempotent whenever possible
  • Prefer functional programming style functions: small, deterministic, 1 input, 1 output
  • Minimize coupling / dependencies
  • Avoid modifying objects received as parameter
  • Only add comments to code to explain why something was done, not how it works
  • Naming
    • classes, enums: PascalCase
    • constants, variables, functions: camelCase
    • file names: kebab-case
    • table and column names: snake_case
    • Use meaningful names, so whoever is reading the code understands what it means
    • Don’t use negative names, like notEnabled, prefer isDisabled
    • For numeric values, if the type doesn’t convey the unit, add the unit to the name
  • Typescript
    • Use types
    • Prefer const instead of let
    • Avoid any and casting from any to other types
    • Type predicates: only applicable to narrow down the type, not to force a complete type conversion
    • Prefer deconstructing parameters for functions instead of multiple parameters that might be of
      the same type
    • Don’t use null inside the app, only on code interacting with external interfaces/services,
      like DB and HTTP; convert to undefined before sending inwards into the code
    • Use async/await instead of .then()
    • Use the strict equality operator ===, don’t use abstract equality operator ==
    • When calling a Promise-returning function asynchronously (i.e., not awaiting), use .catch() to
      handle errors (see processAsyncError and emptyFunction depending on the case)
    • Date and Time
      • Always use buildDayjs() to create dayjs instances
      • Prefer dayjs.duration(...) to create duration consts and keep them as duration
  • Prefer Nullish Coalesce (??) than the OR operator (||) to provide a default value
  • Avoid creating arrow functions
  • Use truthy syntax instead of in - i.e., if (data.link) not if ('link' in data)
  • Error handling
    • Pass the original error as the new one’s cause so the stack trace is persisted
    • Error messages should have a static message - add dynamic data to MetriportError's additionalInfo prop
    • Avoid sending multiple events to Sentry for a single error
  • Global constants and variables
    • Move literals to constants declared after imports when possible (avoid magic numbers)
    • Avoid shared, global objects
  • Avoid using console.log and console.error in packages other than utils, infra and shared,
    and try to use out().log instead
  • Avoid multi-line logs
    • don't send objects as a second parameter to console.log() or out().log()
    • don't create multi-line strings when using JSON.stringify()
  • Use eslint to enforce code style
  • Use prettier to format code
  • max column length is 100 chars
  • multi-line comments use /** */
  • scripts: top-level comments go after the import
  • packages/api/src/models/medical/cohort.ts
🧠 Learnings (1)
packages/api/src/models/medical/cohort.ts (1)
Learnt from: RamilGaripov
PR: metriport/metriport#3962
File: packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts:50-56
Timestamp: 2025-06-17T20:03:18.904Z
Learning: In the Metriport codebase, the patient table ID is defined as DataTypes.STRING in the database schema, not UUID. Foreign key references to patient.id should use DataTypes.STRING to maintain consistency.
🪛 Biome (1.9.4)
packages/api/src/models/medical/cohort.ts

[error] 14-14: Using super in a static context can be confusing.

super refers to a parent class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 60-60: Using super in a static context can be confusing.

super refers to a parent class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 87-87: Using super in a static context can be confusing.

super refers to a parent class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 88-88: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
packages/api/src/models/medical/cohort.ts (1)

29-43: Stop duplicating attribute definitions; reuse CohortModel.attributes()

setup() re-declares the attributes, silently dropping allowNull: false on cxId.
This creates drift between the model and DB schema and violates DRY.

-    CohortModel.init(
-      {
-        ...BaseModel.attributes(),
-        cxId: {
-          type: DataTypes.UUID,
-        },
-        name: {
-          type: DataTypes.STRING,
-          allowNull: false,
-        },
-        monitoring: {
-          type: DataTypes.JSONB,
-        },
-      },
+    CohortModel.init(
+      CohortModel.attributes(),
       {
-        ...BaseModel.modelOptions(sequelize),
-        tableName: this.NAME,
+        ...BaseModel.modelOptions(sequelize),
+        tableName: CohortModel.NAME,
       }
     );

This keeps a single source of truth and preserves the NOT-NULL constraint.
[ suggest_essential_refactor ]

@RamilGaripov RamilGaripov requested a review from leite08 June 18, 2025 07:42
Part of ENG-420

Signed-off-by: Ramil Garipov <ramil@metriport.com>
Copy link
@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

🧹 Nitpick comments (2)
packages/api/src/models/medical/patient-cohort.ts (2)

6-6: Rename NAME to comply with repo naming conventions

Coding-guidelines specify that constants/variables use camelCase; upper-snake is reserved neither for constants nor for classes.
Consider renaming to tableName (or similar) to stay consistent with the rest of the codebase.

-  static NAME = "patient_cohort";
+  static tableName = "patient_cohort";

11-13: Expose associate() to define belongsTo relations

Without associations, eager-loading or cascade deletes will not work.
Consider exporting an associate(models) method that adds:

PatientCohortModel.belongsTo(models.PatientModel, { foreignKey: "patientId" });
PatientCohortModel.belongsTo(models.CohortModel,  { foreignKey: "cohortId"  });

This keeps the relationship explicit and discoverable.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6b042a1 and d90706f.

📒 Files selected for processing (4)
  • packages/api/src/models/db.ts (3 hunks)
  • packages/api/src/models/medical/cohort.ts (1 hunks)
  • packages/api/src/models/medical/patient-cohort.ts (1 hunks)
  • packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/api/src/models/medical/cohort.ts
  • packages/api/src/models/db.ts
  • packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.ts`: - Use the Onion Pattern to organize a package's code in layers - Try to use immutable code and avoid sharing state across different functions, objects, and systems - Try...

**/*.ts: - Use the Onion Pattern to organize a package's code in layers

  • Try to use immutable code and avoid sharing state across different functions, objects, and systems
  • Try to build code that's idempotent whenever possible
  • Prefer functional programming style functions: small, deterministic, 1 input, 1 output
  • Minimize coupling / dependencies
  • Avoid modifying objects received as parameter
  • Only add comments to code to explain why something was done, not how it works
  • Naming
    • classes, enums: PascalCase
    • constants, variables, functions: camelCase
    • file names: kebab-case
    • table and column names: snake_case
    • Use meaningful names, so whoever is reading the code understands what it means
    • Don’t use negative names, like notEnabled, prefer isDisabled
    • For numeric values, if the type doesn’t convey the unit, add the unit to the name
  • Typescript
    • Use types
    • Prefer const instead of let
    • Avoid any and casting from any to other types
    • Type predicates: only applicable to narrow down the type, not to force a complete type conversion
    • Prefer deconstructing parameters for functions instead of multiple parameters that might be of
      the same type
    • Don’t use null inside the app, only on code interacting with external interfaces/services,
      like DB and HTTP; convert to undefined before sending inwards into the code
    • Use async/await instead of .then()
    • Use the strict equality operator ===, don’t use abstract equality operator ==
    • When calling a Promise-returning function asynchronously (i.e., not awaiting), use .catch() to
      handle errors (see processAsyncError and emptyFunction depending on the case)
    • Date and Time
      • Always use buildDayjs() to create dayjs instances
      • Prefer dayjs.duration(...) to create duration consts and keep them as duration
  • Prefer Nullish Coalesce (??) than the OR operator (||) to provide a default value
  • Avoid creating arrow functions
  • Use truthy syntax instead of in - i.e., if (data.link) not if ('link' in data)
  • Error handling
    • Pass the original error as the new one’s cause so the stack trace is persisted
    • Error messages should have a static message - add dynamic data to MetriportError's additionalInfo prop
    • Avoid sending multiple events to Sentry for a single error
  • Global constants and variables
    • Move literals to constants declared after imports when possible (avoid magic numbers)
    • Avoid shared, global objects
  • Avoid using console.log and console.error in packages other than utils, infra and shared,
    and try to use out().log instead
  • Avoid multi-line logs
    • don't send objects as a second parameter to console.log() or out().log()
    • don't create multi-line strings when using JSON.stringify()
  • Use eslint to enforce code style
  • Use prettier to format code
  • max column length is 100 chars
  • multi-line comments use /** */
  • scripts: top-level comments go after the import
  • packages/api/src/models/medical/patient-cohort.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)

Part of ENG-420

Signed-off-by: Ramil Garipov <ramil@metriport.com>
@RamilGaripov RamilGaripov added this pull request to the merge queue Jun 20, 2025
Merged via the queue into develop with commit 25a34b3 Jun 20, 2025
16 checks passed
@RamilGaripov RamilGaripov deleted the eng-420-introduce-patient-cohorts-into-our-api branch June 20, 2025 16:57
@coderabbitai coderabbitai bot mentioned this pull request Jun 20, 2025
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants
0