Skip to content

Conversation

RamilGaripov
Copy link
Contributor

@RamilGaripov RamilGaripov commented Aug 12, 2025

Part of ENG-836

Issues:

Description

  • The docs marked for redownload was getting filtered out. This fixes it

Testing

  • Staging
    • Make sure the staging pt with test docs on CW redownloads them successfully
  • Production
    • Confirm in prod

Release Plan

  • Merge this

Summary by CodeRabbit

  • Improvements
    • Forced re-download now refreshes rendered document views (HTML/PDF) consistently for up-to-date content.
  • Bug Fixes
    • Ensures all stored documents are included during a forced download, preventing missed or skipped files.

Part of ENG-836

Signed-off-by: Ramil Garipov <ramil@metriport.com>
Copy link

linear bot commented Aug 12, 2025

Copy link

coderabbitai bot commented Aug 12, 2025

Walkthrough

Expands force-download behavior in document-query to include storage-only documents and always delete existing render artifacts during forced downloads. Public APIs remain unchanged.

Changes

Cohort / File(s) Summary of changes
CommonWell Document Download/Upsert
packages/api/src/external/commonwell/document/document-query.ts
- When forceDownload is true, include remainingFoundOnStorage docs not already in filesToDownload.
- On forced downloads, always delete existing render outputs (HTML/PDF) before upsert, regardless of file size comparison.
- No exported/public signature changes.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant DocumentQuery
  participant Storage
  participant Renderer

  Caller->>DocumentQuery: downloadDocsAndUpsertFHIR({ forceDownload })
  alt forceDownload = true
    DocumentQuery->>Storage: list existing docs on storage
    DocumentQuery->>DocumentQuery: add remaining storage-only docs to filesToDownload
    loop for each doc in filesToDownload
      DocumentQuery->>Renderer: delete existing HTML/PDF renders
      DocumentQuery->>Storage: download doc
      DocumentQuery->>DocumentQuery: upsert FHIR resources
    end
  else forceDownload = false
    loop for each doc needing download
      DocumentQuery->>Storage: conditional download (size/need based)
      DocumentQuery->>DocumentQuery: upsert FHIR resources
    end
  end
  DocumentQuery-->>Caller: result
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch eng-836-fix

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

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

🧹 Nitpick comments (1)
packages/api/src/external/commonwell/document/document-query.ts (1)

535-539: Force re-download now correctly includes storage-only docs; consider Set for O(1) dedupe

Solid fix to ensure storage-only docs aren't skipped when forceDownload is true. Minor perf/readability nit: use a Set for constant-time membership checks.

Apply this diff:

-    const alreadyIncluded = filesToDownload.map(f => f.docId);
-    const remainingFoundOnStorage = foundOnStorage.filter(f => !alreadyIncluded.includes(f.docId));
+    const alreadyIncluded = new Set(filesToDownload.map(f => f.docId));
+    const remainingFoundOnStorage = foundOnStorage.filter(f => !alreadyIncluded.has(f.docId));
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d13ee7b and dd92a5b.

📒 Files selected for processing (1)
  • packages/api/src/external/commonwell/document/document-query.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursorrules)

**/*.{js,jsx,ts,tsx}: 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 const whenever possible
Use async/await instead of .then()
Naming: classes, enums: PascalCase
Naming: constants, variables, functions: camelCase
Naming: file names: kebab-case
Naming: Don’t use negative names, like notEnabled, prefer isDisabled
If possible, use decomposing objects for function parameters
Prefer Nullish Coalesce (??) than the OR operator (||) when you want 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)
While handling errors, keep the stack trace around: if you create a new Error (e.g., MetriportError), make sure to pass the original error as the new one’s cause so the stack trace is available upstream.
max column length is 100 chars
multi-line comments use /** */
top-level comments go after the import (save pre-import to basic file header, like license)
move literals to constants declared after imports when possible

Files:

  • packages/api/src/external/commonwell/document/document-query.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursorrules)

Use types whenever possible

Files:

  • packages/api/src/external/commonwell/document/document-query.ts
**/*.ts

⚙️ CodeRabbit Configuration File

**/*.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
  • U...

Files:

  • packages/api/src/external/commonwell/document/document-query.ts
🧠 Learnings (1)
📓 Common learnings
Learnt from: RamilGaripov
PR: metriport/metriport#4176
File: packages/fhir-converter/src/lib/handlebars-converter/handlebars-helpers.js:296-320
Timestamp: 2025-07-17T21:24:37.077Z
Learning: RamilGaripov prefers to maintain consistency with existing patterns in a file rather than making isolated fixes to coding guideline violations like var vs const declarations, when the pattern is already established throughout the codebase.
⏰ 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). (2)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
packages/api/src/external/commonwell/document/document-query.ts (1)

588-595: Always delete renders on forceDownload — avoids stale artifacts and matches redownload intent

Broadening the condition to delete renders whenever forceDownload is true makes the behavior predictable and prevents serving outdated HTML/PDF after a forced re-download. LGTM.

@RamilGaripov RamilGaripov added this pull request to the merge queue Aug 12, 2025
Merged via the queue into develop with commit 1b7bf0e Aug 12, 2025
14 checks passed
@RamilGaripov RamilGaripov deleted the eng-836-fix branch August 12, 2025 00:56
@coderabbitai coderabbitai bot mentioned this pull request Aug 12, 2025
1 task
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.

2 participants