Skip to content

Feat/sales channel retrieve#2

Open
DhirenMhatre wants to merge 9 commits into
developfrom
feat/sales-channel-retrieve
Open

Feat/sales channel retrieve#2
DhirenMhatre wants to merge 9 commits into
developfrom
feat/sales-channel-retrieve

Conversation

@DhirenMhatre
Copy link
Copy Markdown

Summary

What — What changes are introduced in this PR?

Please provide answer here

Why — Why are these changes relevant or necessary?

Please provide answer here

How — How have these changes been implemented?

Please provide answer here

Testing — How have these changes been tested, or how can the reviewer test the feature?

Please provide answer here


Examples

Provide examples or code snippets that demonstrate how this feature works, or how it can be used in practice.
This helps with documentation and ensures maintainers can quickly understand and verify the change.

// Example usage

Checklist

Please ensure the following before requesting a review:

  • I have added a changeset for this PR
    • Every non-breaking change should be marked as a patch
    • To add a changeset, run yarn changeset and follow the prompts
  • The changes are covered by relevant tests
  • I have verified the code works as intended locally
  • I have linked the related issue(s) if applicable

Additional Context

Add any additional context, related issues, or references that might help the reviewer understand this PR.

@chay2199
Copy link
Copy Markdown

chay2199 commented Jun 6, 2026

@codity review

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

PR Summary

What Changed

  • Implemented GET /admin/sales-channels/:id endpoint to retrieve a single sales channel by ID with optional relations
  • Added repository methods for efficient relation loading and middleware to attach sales channel to request context
  • Fixed type name typo AdminSalesChanenlResAdminSalesChannelRes

Key Changes by Area

API: Added GET /admin/sales-channels/:id route with getRequestedSalesChannel middleware for request context injection

Service Layer: Implemented SalesChannelService.retrieve() with transaction safety via atomicPhase_ and proper error handling for missing records

Repository: Extended SalesChannelRepository with findWithRelations() and findOneWithRelations() for relation loading

Types: Added SalesChannelRequest type extending Express Request for middleware type safety

Files Changed

File Changes Summary
integration-tests/api/tests/admin/snapshots/sales-channels.js.snap Added snapshot for integration test
integration-tests/api/tests/admin/sales-channels.js Added integration test for retrieve endpoint
integration-tests/api/helpers/sales-channels-seeder.js Added seeder for test data setup
packages/medusa/src/api/middlewares/index.ts Exported sales channel middleware
packages/medusa/src/api/middlewares/sales-channel/get-requested-sales-channel.ts New middleware to fetch and attach sales channel to request
packages/medusa/src/api/routes/admin/index.js Registered sales channel routes
packages/medusa/src/api/routes/admin/sales-channels/tests/get-sales-channel.js Added unit tests for GET endpoint
packages/medusa/src/api/routes/admin/sales-channels/get-sales-channels.ts Added route handler for retrieve endpoint
packages/medusa/src/api/routes/admin/sales-channels/index.ts Fixed typo in response type name
packages/medusa/src/repositories/sales-channel.ts Added relation loading methods
packages/medusa/src/services/mocks/sales-channel.js Added mock for service tests
packages/medusa/src/services/tests/batch-job.ts Unrelated test file changes
packages/medusa/src/services/tests/sales-channel.ts Added unit tests for retrieve method
packages/medusa/src/services/sales-channel.ts Implemented retrieve method with transaction wrapper
packages/medusa/src/types/sales-channels.ts Added request type for middleware

Review Focus Areas

  • Error message typo "Sale channel" at sales-channel.ts:65 affects API consumer experience
  • Dead import FindWithoutRelationsOptions from product module creates unnecessary coupling
  • Dead mock in service tests gives false coverage impression

Architecture

Design Decisions: Used atomicPhase_ wrapper for transaction safety even on read operations. This follows existing Medusa patterns but adds minimal overhead. Middleware pattern for entity loading matches existing admin API conventions.

Risks:

  • Intentional: Typo in error message is exposed to API consumers (acceptable to fix in follow-up)
  • Unintentional: Unused import from product module creates cross-module coupling that should be removed

Merge Status

NOT MERGEABLE — PR Score 59/100, below threshold (50)

  • [H3] 4 high-risk (strong copyleft) licenses detected
  • [H5] 1 CRITICAL inline review finding need resolution

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

Workflow Diagrams

Automatically generated sequence diagrams showing the workflows in this PR

1. Sales Channel Retrieval API Flow

Medium complexity • Components: SalesChannelService, SalesChannelRepository, getRequestedSalesChannel middleware

sequenceDiagram
    title Sales Channel Retrieve API Endpoint

    participant Client as Client
    participant API as Admin API Route
    participant Middleware as getRequestedSalesChannel Middleware
    participant Service as SalesChannelService
    participant Repo as SalesChannelRepository
    participant DB as Database

    Client->>API: GET /admin/sales-channels/:id

    API->>Middleware: Route with middleware

    Middleware->>Service: retrieve(salesChannelId, config)

    Service->>Service: atomicPhase_ (transaction wrapper)

    Service->>Repo: getCustomRepository()

    Service->>Repo: findOneWithRelations(relations, query)

    Repo->>DB: SELECT with WHERE id = salesChannelId

    DB-->>Repo: SalesChannel entity

    Repo-->>Service: SalesChannel or undefined

    alt SalesChannel not found
        Service-->>Middleware: throw MedusaError NOT_FOUND
        Middleware-->>API: Error propagated
        API-->>Client: 404 Not Found
    else SalesChannel found
        Service-->>Middleware: Return SalesChannel
        Middleware->>Middleware: Attach to req.sales_channel
        Middleware-->>API: next()
        API-->>Client: 200 OK with {sales_channel: {...}}
    end

    Note over Client,DB: Integration test flow uses sales-channels-seeder.js to seed test data before each test
Loading

Note: Diagrams show detected patterns only. Complex workflows may require manual review.

Comment on lines +1 to +3
import { SalesChannel } from "@medusajs/medusa/dist/models/sales-channel"

module.exports = async (connection, data = {}) => {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Functional Critical

The seeder mixes ES module import syntax with CommonJS module.exports, causing a runtime SyntaxError when the test infrastructure uses require() to load it. All other seeders in the codebase use pure CommonJS with const X = require(...), and the integration test environment has no Babel transform configured. This breaks the GET /admin/sales-channels/:id test suite.

Suggested fix
const { SalesChannel } = require("@medusajs/medusa/dist/models/sales-channel")

module.exports = async (connection, data = {}) => {
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: integration-tests/api/helpers/sales-channels-seeder.js
Lines: 1-3
Issue Type: functional-critical
Severity: critical

Issue Description:
The seeder mixes ES module `import` syntax with CommonJS `module.exports`, causing a runtime `SyntaxError` when the test infrastructure uses `require()` to load it. All other seeders in the codebase use pure CommonJS with `const X = require(...)`, and the integration test environment has no Babel transform configured. This breaks the GET /admin/sales-channels/:id test suite.

Current Code:
import { SalesChannel } from "@medusajs/medusa/dist/models/sales-channel"

module.exports = async (connection, data = {}) => {

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue

import EventBusService from "./event-bus"
import { buildQuery } from "../utils"
import { FindWithoutRelationsOptions } from "../repositories/product"
import { MedusaError } from "medusa-core-utils/dist"
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Robustness High

The import statement on line 13 imports MedusaError from the internal dist directory rather than the package's public entry point. This bypasses the package's intended API contract and creates a fragile dependency that will break silently if the maintainers reorganize the internal file structure. The correct approach is to import from the public entry point medusa-core-utils.

Suggested change
import { MedusaError } from "medusa-core-utils/dist"
import { MedusaError } from "medusa-core-utils"
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: packages/medusa/src/services/sales-channel.ts
Lines: 13-13
Issue Type: robustness-high
Severity: high

Issue Description:
The import statement on line 13 imports `MedusaError` from the internal `dist` directory rather than the package's public entry point. This bypasses the package's intended API contract and creates a fragile dependency that will break silently if the maintainers reorganize the internal file structure. The correct approach is to import from the public entry point `medusa-core-utils`.

Current Code:
import { MedusaError } from "medusa-core-utils/dist"

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue

eventBusService: eventBusServiceMock,
batchJobRepository: batchJobRepositoryMock
})
} as any)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Maintainability Low

The as any cast on line 25 violates the project's AGENTS.md prohibition against type-unsafe casts. This mask a type mismatch between the mock object and the actual BatchJobService constructor parameter type, making it impossible to catch real type errors during development. Removing the cast requires properly typing the mock object to match the expected service dependencies interface, ensuring type safety and maintainability.

Suggested change
} as any)
} as BatchJobService['constructor']['prototype']['constructor'])
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: packages/medusa/src/services/__tests__/batch-job.ts
Lines: 25-25
Issue Type: maintainability-low
Severity: low

Issue Description:
The `as any` cast on line 25 violates the project's AGENTS.md prohibition against type-unsafe casts. This mask a type mismatch between the mock object and the actual `BatchJobService` constructor parameter type, making it impossible to catch real type errors during development. Removing the cast requires properly typing the mock object to match the expected service dependencies interface, ensuring type safety and maintainability.

Current Code:
  } as any)

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

Nitpicks (Low Priority)

Found 3 low-priority suggestions for code improvement

Click to expand nitpicks

packages/medusa/src/services/sales-channel.ts (line 65)

Readability Low

The error message on line 65 contains a typo: "Sale channel" should be "Sales channel" (plural). This misleading error message is exposed to API consumers and appears in logs, creating confusion about the actual entity type being referenced and reducing professional quality of error reporting.

Code Suggestion or Comments
`Sales channel with id ${salesChannelId} was not found`
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: packages/medusa/src/services/sales-channel.ts
Lines: 65-65
Issue Type: readability-low
Severity: low

Issue Description:
The error message on line 65 contains a typo: "Sale channel" should be "Sales channel" (plural). This misleading error message is exposed to API consumers and appears in logs, creating confusion about the actual entity type being referenced and reducing professional quality of error reporting.

Current Code:
          `Sale channel with id ${salesChannelId} was not found`

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---



packages/medusa/src/services/__tests__/sales-channel.ts (lines 18-23)

Maintainability Low

The retrieve mock on salesChannelRepositoryMock is dead code that will never be called by the test. SalesChannelService.retrieve internally calls findOneWithRelations instead of Repository.retrieve, making this mock redundant. Removing it eliminates false coverage and reduces test maintenance burden by removing misleading mock implementations.

Code Suggestion or Comments
const salesChannelRepositoryMock = MockRepository({
    create: jest.fn().mockImplementation((data) => {
      return Object.assign(new SalesChannel(), data)
    }),
    findOneWithRelations: jest.fn().mockImplementation(
      (relations: string[], config): Promise<SalesChannel | void> => {
        if (config?.where?.id === IdMap.getId("sales_channel_1")) {
          return Promise.resolve(salesChannel1 as SalesChannel)
        }
        return Promise.resolve()
      }
    ),
  })
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: packages/medusa/src/services/__tests__/sales-channel.ts
Lines: 18-23
Issue Type: maintainability-low
Severity: low

Issue Description:
The `retrieve` mock on `salesChannelRepositoryMock` is dead code that will never be called by the test. SalesChannelService.retrieve internally calls `findOneWithRelations` instead of `Repository.retrieve`, making this mock redundant. Removing it eliminates false coverage and reduces test maintenance burden by removing misleading mock implementations.

Current Code:
  retrieve: jest.fn().mockImplementation((id: string): any => {
    if (id === IdMap.getId("sales_channel_1")) {
      return Promise.resolve(salesChannel1)
    }
    return Promise.resolve()
  }),

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---



packages/medusa/src/services/sales-channel.ts (line 12)

Maintainability Low

The import of FindWithoutRelationsOptions from the unrelated product repository module is unused in this file, creating unnecessary coupling between SalesChannelService and the product module. Removing this dead import reduces module interdependencies, improves maintainability, and makes the dependency graph clearer. This type of accidental cross-module coupling can lead to circular dependencies or unexpected breakage when the product module changes.

Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: packages/medusa/src/services/sales-channel.ts
Lines: 12-12
Issue Type: maintainability-low
Severity: low

Issue Description:
The import of `FindWithoutRelationsOptions` from the unrelated product repository module is unused in this file, creating unnecessary coupling between SalesChannelService and the product module. Removing this dead import reduces module interdependencies, improves maintainability, and makes the dependency graph clearer. This type of accidental cross-module coupling can lead to circular dependencies or unexpected breakage when the product module changes.

Current Code:
import { FindWithoutRelationsOptions } from "../repositories/product"

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---



Like Dislike

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

Security Scan Summary

Metric Value
Vulnerabilities Critical: 0
Overall Risk Clean
Files Scanned 15

No critical security issues detected

Scan completed in 36.4s

Security scan powered by Codity.ai

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

License Compliance Scan

Metric Value
Packages Scanned 6953
High Risk (Strong Copyleft) 4
Medium Risk (Weak Copyleft) 4
Low Risk (Permissive) 5211
Unknown License 1734

Strong copyleft licenses detected - review before merging

Weak copyleft licenses found - verify compatibility

Some packages have unknown licenses - manual review required

High Risk Licenses - 4 packages

(BSD-3-Clause OR GPL-2.0) (1 packages):

  • node-forge 1.2.1

AGPL-3.0-or-later (2 packages):

  • medusa-core-utils 0.1.39
  • medusa-core-utils 0.1.27

GPL-2.0-only (1 packages):

  • breakword 1.0.5
Medium Risk Licenses - 4 packages

(MPL-2.0 OR Apache-2.0) (2 packages):

  • dompurify 2.3.4
  • dompurify 2.2.6

MPL-2.0 (2 packages):

  • axe-core 4.3.5
  • client-sessions 0.8.0
Unknown Licenses - 1734 packages
  • @apidevtools/json-schema-ref-parser 0.0.0-dev
  • @babel/cli@^7.12.1", "@babel/cli@^7.13.0", "@babel/cli@^7.14.3", "@babel/cli@^7.15.4", "@babel/cli@^7.16.0", "@babel/cli 7.16.7
  • @babel/code-frame@7.10.4", "@babel/code-frame 7.10.4
  • @babel/code-frame@^7.12.13", "@babel/code-frame@^7.14.0", "@babel/code-frame@^7.16.7", "@babel/code-frame@^7.5.5", "@babel/code-frame 7.16.7
  • @babel/code-frame@^7.10.4", "@babel/code-frame@^7.14.5", "@babel/code-frame 7.16.0
  • @babel/compat-data@^7.13.11", "@babel/compat-data 7.14.7
  • @babel/compat-data@^7.15.0", "@babel/compat-data 7.16.0
  • @babel/core@^7.1.0", "@babel/core@^7.12.3", "@babel/core@^7.12.7", "@babel/core 7.15.0
  • @babel/generator@^7.10.5", "@babel/generator@^7.12.11", "@babel/generator@^7.16.7", "@babel/generator 7.16.7
  • @babel/core@^7.13.8", "@babel/core@^7.14.3", "@babel/core@^7.15.5", "@babel/core@^7.16.0", "@babel/core@^7.4.4", "@babel/core@^7.7.2", "@babel/core 7.16.7
  • @babel/generator@^7.14.5", "@babel/generator@^7.15.0", "@babel/generator@^7.15.4", "@babel/generator 7.16.0
  • @babel/helper-annotate-as-pure@^7.10.4", "@babel/helper-annotate-as-pure@^7.14.5", "@babel/helper-annotate-as-pure 7.16.0
  • @babel/helper-builder-binary-assignment-operator-visitor@^7.14.5", "@babel/helper-builder-binary-assignment-operator-visitor 7.16.0
  • @babel/helper-create-class-features-plugin@^7.10.4", "@babel/helper-create-class-features-plugin@^7.12.1", "@babel/helper-create-class-features-plugin 7.15.4
  • @babel/helper-create-class-features-plugin@^7.14.5", "@babel/helper-create-class-features-plugin 7.16.0
  • @babel/helper-create-regexp-features-plugin@^7.14.5", "@babel/helper-create-regexp-features-plugin 7.16.0
  • @babel/helper-function-name@^7.10.4", "@babel/helper-function-name@^7.14.5", "@babel/helper-function-name@^7.15.4", "@babel/helper-function-name 7.16.0
  • @babel/helper-get-function-arity@^7.10.4", "@babel/helper-get-function-arity 7.16.0
  • @babel/helper-hoist-variables@^7.14.5", "@babel/helper-hoist-variables@^7.15.4", "@babel/helper-hoist-variables 7.16.0
  • @babel/helper-member-expression-to-functions@^7.15.4", "@babel/helper-member-expression-to-functions 7.16.0

...and 1714 more

Powered by Codity.ai · Docs

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

Code Quality Report — test-org-codity/medusa · PR #2

Scanned: 2026-06-06 17:24 UTC | Score: 62/100 | Provider: github

Executive Summary

Severity Count
Critical 0
High 1
Medium 3
Low 3
Top Findings

[CQ-LLM-002] integration-tests/api/__tests__/admin/sales-channels.js:30 (Error_Handling · HIGH)

Issue: Swallowed exceptions in the beforeEach function without proper logging or handling.
Suggestion: Implement proper error handling or rethrow the error after logging.

console.error(e)

[CQ-LLM-001] integration-tests/api/__tests__/admin/sales-channels.js:23 (Complexity · MEDIUM)

Issue: The beforeEach function has multiple async calls which increases cyclomatic complexity.
Suggestion: Consider breaking down the beforeEach function into smaller functions to reduce complexity.

await adminSeeder(dbConnection)
await salesChannelsSeeder(dbConnection)

[CQ-LLM-003] packages/medusa/src/api/middlewares/sales-channel/get-requested-sales-channel.ts:1 (Documentation · MEDIUM)

Issue: Missing JSDoc for the getRequestedSalesChannel function.
Suggestion: Add JSDoc comments to describe the function's purpose, parameters, and return type.

export async function getRequestedSalesChannel(req: Request, res: Response, next: NextFunction): Promise<void> {

[CQ-LLM-004] packages/medusa/src/api/routes/admin/sales-channels/get-sales-channels.ts:1 (Testability · MEDIUM)

Issue: Directly using Response from express without dependency injection makes testing harder.
Suggestion: Consider using dependency injection for the Response object to improve testability.

export default async (req: SalesChannelRequest, res: Response): Promise<void> => {

[CQ-008] integration-tests/api/__tests__/admin/sales-channels.js:72 (Maintainability · LOW)

Issue: Magic number 200 in code
Suggestion: Extract to a named constant

expect(response.status).toEqual(200)

[CQ-008] packages/medusa/src/api/routes/admin/sales-channels/get-sales-channels.ts:8 (Maintainability · LOW)

Issue: Magic number 200 in code
Suggestion: Extract to a named constant

res.status(200).json({ sales_channel: req.sales_channel })

[CQ-LLM-005] packages/medusa/src/api/routes/admin/sales-channels/index.ts:39 (Maintainability · LOW)

Issue: The type AdminSalesChanenlRes has a typo in its name.
Suggestion: Rename AdminSalesChanenlRes to AdminSalesChannelRes to correct the typo.

export type AdminSalesChanenlRes = {

Per-File Breakdown

File Critical High Medium Low Total
integration-tests/api/__tests__/admin/sales-channels.js 0 1 1 1 3
packages/medusa/src/api/middlewares/sales-channel/get-requested-sales-channel.ts 0 0 1 0 1
packages/medusa/src/api/routes/admin/sales-channels/get-sales-channels.ts 0 0 1 1 2
packages/medusa/src/api/routes/admin/sales-channels/index.ts 0 0 0 1 1

Recommendations

  1. Resolve High severity issues, especially error handling gaps and performance bottlenecks.
  • Run automated tests after applying fixes to verify no regressions.

@chay2199
Copy link
Copy Markdown

chay2199 commented Jun 6, 2026

@codity review

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

PR Summary

What Changed

  • Added GET /admin/sales-channels/:id endpoint to retrieve a single sales channel by ID with optional relations support.
  • Introduced middleware to pre-fetch and inject sales channel into request context, keeping route handlers thin.
  • Extended repository with findWithRelations() and findOneWithRelations() methods for flexible data loading.

Key Changes by Area

API Routes: New endpoint with nested router pattern and getRequestedSalesChannel middleware in packages/medusa/src/api/routes/admin/sales-channels/index.ts:12-18.

Service Layer: SalesChannelService.retrieve() uses atomicPhase_ wrapper, buildQuery utility, and repository methods with error handling for missing records.

Repository: Added relation-aware query methods to SalesChannelRepository for consistent data loading patterns.

Types: Added SalesChannelRequest type extending Express Request to type the injected sales channel entity.

Testing: Unit tests for service and route handler, plus integration tests with snapshot validation.

Files Changed

File Changes Summary
integration-tests/api/tests/admin/snapshots/sales-channels.js.snap Snapshot tests for API responses
integration-tests/api/tests/admin/sales-channels.js Integration tests for retrieve endpoint
integration-tests/api/helpers/sales-channels-seeder.js Test data seeding helper
packages/medusa/src/api/middlewares/index.ts Exported new middleware
packages/medusa/src/api/middlewares/sales-channel/get-requested-sales-channel.ts New middleware to fetch and attach sales channel
packages/medusa/src/api/routes/admin/index.js Wired up sales channels router
packages/medusa/src/api/routes/admin/sales-channels/tests/get-sales-channel.js Unit tests for route handler
packages/medusa/src/api/routes/admin/sales-channels/get-sales-channels.ts New route handler for retrieve
packages/medusa/src/api/routes/admin/sales-channels/index.ts Router setup with middleware chain
packages/medusa/src/repositories/sales-channel.ts Added findWithRelations and findOneWithRelations methods
packages/medusa/src/services/mocks/sales-channel.js Mock updates for testing
packages/medusa/src/services/tests/batch-job.ts Unrelated test file (no material changes)
packages/medusa/src/services/tests/sales-channel.ts Updated tests for retrieve method
packages/medusa/src/services/sales-channel.ts Implemented retrieve with transaction wrapper
packages/medusa/src/types/sales-channels.ts Added SalesChannelRequest type

Review Focus Areas

  • Error message typo at packages/medusa/src/services/sales-channel.ts:65: "Sale channel" should be "Sales channel". This appears in production API responses.
  • Middleware error handling: verify getRequestedSalesChannel properly distinguishes 404 vs 500 cases.
  • Repository method consistency: confirm findOneWithRelations parameter handling matches test expectations.

Architecture

Design Decisions: The nested router pattern with middleware pre-fetching keeps handlers thin and reusable. The atomicPhase_ wrapper ensures transaction safety even for simple reads, following existing Medusa patterns.

Risks: The typo in the error message is unintentional and should be fixed before merge. It affects client-visible error responses.

Merge Status

NOT MERGEABLE — PR Score 50/100, below threshold (50)

  • [H3] 4 high-risk (strong copyleft) licenses detected
  • [H5] 1 CRITICAL inline review finding need resolution

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

Workflow Diagrams

Automatically generated sequence diagrams showing the workflows in this PR

1. Sales Channel Retrieval API Flow

Medium complexity • Components: SalesChannelService, SalesChannelRepository, getRequestedSalesChannel middleware

sequenceDiagram
    title Sales Channel Retrieve API Workflow

    participant Client as HTTP Client
    participant API as Admin API Route
    participant Middleware as getRequestedSalesChannel Middleware
    participant Service as SalesChannelService
    participant Repo as SalesChannelRepository
    participant DB as Database

    Client->>API: GET /admin/sales-channels/:id
    API->>Middleware: Invoke middleware with id param

    Middleware->>Service: retrieve(salesChannelId, config)
    note over Middleware,Service: Extracts ID from request params

    Service->>Service: atomicPhase_ (transaction wrapper)
    Service->>Repo: getCustomRepository(SalesChannelRepository)

    Service->>Repo: findOneWithRelations(relations, query)
    note over Service,Repo: Builds query with buildQuery utility

    Repo->>DB: SELECT with optional relations
    DB-->>Repo: SalesChannel entity or null

    Repo-->>Service: saleChannel or undefined

    alt Sales channel not found
        Service->>Service: throw MedusaError NOT_FOUND
        Service-->>Middleware: Error propagated
        Middleware-->>API: Error propagated
        API-->>Client: 404 Not Found
    else Sales channel found
        Service-->>Middleware: Return SalesChannel entity
        Middleware->>Middleware: Attach to req.salesChannel
        Middleware-->>API: next()

        API->>API: Format response
        API-->>Client: 200 OK with sales_channel data
    end

    note over Client,DB: Integration Test Flow
    participant Test as Integration Test
    participant Seeder as salesChannelsSeeder

    Test->>Seeder: Seed test data
    Seeder->>DB: INSERT sales_channel_1
    Test->>API: GET /admin/sales-channels/sales_channel_1
    API-->>Test: 200 with matching snapshot
Loading

Note: Diagrams show detected patterns only. Complex workflows may require manual review.

Comment on lines +1 to +3
import { SalesChannel } from "@medusajs/medusa/dist/models/sales-channel"

module.exports = async (connection, data = {}) => {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Functional Critical

The file uses ES module import syntax on line 1 but exports using CommonJS module.exports on line 3. Since the file is .js without "type": "module" in package.json, Node.js treats it as CommonJS, causing a syntax error when the file is parsed. This breaks the integration test suite when salesChannelsSeeder is required.

Suggested fix
const { SalesChannel } = require("@medusajs/medusa/dist/models/sales-channel")

module.exports = async (connection, data = {}) => {
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: integration-tests/api/helpers/sales-channels-seeder.js
Lines: 1-3
Issue Type: functional-critical
Severity: critical

Issue Description:
The file uses ES module `import` syntax on line 1 but exports using CommonJS `module.exports` on line 3. Since the file is `.js` without `"type": "module"` in `package.json`, Node.js treats it as CommonJS, causing a syntax error when the file is parsed. This breaks the integration test suite when `salesChannelsSeeder` is required.

Current Code:
import { SalesChannel } from "@medusajs/medusa/dist/models/sales-channel"

module.exports = async (connection, data = {}) => {

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue

import EventBusService from "./event-bus"
import { buildQuery } from "../utils"
import { FindWithoutRelationsOptions } from "../repositories/product"
import { MedusaError } from "medusa-core-utils/dist"
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Maintainability High

MedusaError is imported from the internal dist subdirectory instead of the public package entry point. This breaks the established pattern used across 50+ other files in the codebase and violates the package's public API contract, risking silent failures if the package reorganizes its compiled output.

Suggested change
import { MedusaError } from "medusa-core-utils/dist"
import { MedusaError } from "medusa-core-utils"
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: packages/medusa/src/services/sales-channel.ts
Lines: 13-13
Issue Type: maintainability-high
Severity: high

Issue Description:
MedusaError is imported from the internal dist subdirectory instead of the public package entry point. This breaks the established pattern used across 50+ other files in the codebase and violates the package's public API contract, risking silent failures if the package reorganizes its compiled output.

Current Code:
import { MedusaError } from "medusa-core-utils/dist"

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue

beforeAll(async () => {
const cwd = path.resolve(path.join(__dirname, "..", ".."))
const [process, connection] = await startServerWithEnvironment({
process.env.MEDUSA_FF_SALES_CHANNELS = true
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Functional Medium

Line 26 assigns a boolean true to process.env.MEDUSA_FF_SALES_CHANNELS, but environment variables are always strings in Node.js. This causes the value to coerce to the string "true", which will fail strict equality checks (=== true) elsewhere in the code. Additionally, this direct mutation of process.env is redundant since the env object passed to startServerWithEnvironment on line 29 already handles the subprocess environment configuration.

Suggested change
process.env.MEDUSA_FF_SALES_CHANNELS = true
// Remove line 26 entirely; the env object on line 29 already handles the subprocess
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: integration-tests/api/__tests__/admin/sales-channels.js
Lines: 26-26
Issue Type: functional-medium
Severity: medium

Issue Description:
Line 26 assigns a boolean `true` to `process.env.MEDUSA_FF_SALES_CHANNELS`, but environment variables are always strings in Node.js. This causes the value to coerce to the string `"true"`, which will fail strict equality checks (`=== true`) elsewhere in the code. Additionally, this direct mutation of `process.env` is redundant since the `env` object passed to `startServerWithEnvironment` on line 29 already handles the subprocess environment configuration.

Current Code:
    process.env.MEDUSA_FF_SALES_CHANNELS = true

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue

Comment on lines +51 to +57
beforeEach(async() => {
try {
await adminSeeder(dbConnection)
await salesChannelsSeeder(dbConnection)
} catch (e) {
console.error(e)
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Robustness Low

The beforeEach block catches and silently logs seeder errors with console.error, allowing tests to continue without required fixture data. When seeding fails (e.g., due to import/export issues), subsequent tests fail with cryptic errors unrelated to the actual setup failure, making CI triage difficult.

Suggested fix
    beforeEach(async() => {
          await adminSeeder(dbConnection)
          await salesChannelsSeeder(dbConnection)
        })
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: integration-tests/api/__tests__/admin/sales-channels.js
Lines: 51-57
Issue Type: robustness-low
Severity: low

Issue Description:
The `beforeEach` block catches and silently logs seeder errors with `console.error`, allowing tests to continue without required fixture data. When seeding fails (e.g., due to import/export issues), subsequent tests fail with cryptic errors unrelated to the actual setup failure, making CI triage difficult.

Current Code:
    beforeEach(async() => {
      try {
        await adminSeeder(dbConnection)
        await salesChannelsSeeder(dbConnection)
      } catch (e) {
        console.error(e)
      }
    })

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

Nitpicks (Low Priority)

Found 1 low-priority suggestions for code improvement

Click to expand nitpicks

packages/medusa/src/services/sales-channel.ts (line 65)

Readability Low

The error message on line 65 contains a typo: "Sale channel" should be "Sales channel". This misspelling appears in API error responses and logs visible to clients and operators in production.

Code Suggestion or Comments
`Sales channel with id ${salesChannelId} was not found`
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: packages/medusa/src/services/sales-channel.ts
Lines: 65-65
Issue Type: readability-low
Severity: low

Issue Description:
The error message on line 65 contains a typo: `"Sale channel"` should be `"Sales channel"`. This misspelling appears in API error responses and logs visible to clients and operators in production.

Current Code:
          `Sale channel with id ${salesChannelId} was not found`

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---



Like Dislike

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

Security Scan Summary

Metric Value
Vulnerabilities Critical: 0
Overall Risk Clean
Files Scanned 15

No critical security issues detected

Scan completed in 21.2s

Security scan powered by Codity.ai

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

License Compliance Scan

Metric Value
Packages Scanned 6953
High Risk (Strong Copyleft) 4
Medium Risk (Weak Copyleft) 4
Low Risk (Permissive) 5211
Unknown License 1734

Strong copyleft licenses detected - review before merging

Weak copyleft licenses found - verify compatibility

Some packages have unknown licenses - manual review required

High Risk Licenses - 4 packages

(BSD-3-Clause OR GPL-2.0) (1 packages):

  • node-forge 1.2.1

AGPL-3.0-or-later (2 packages):

  • medusa-core-utils 0.1.39
  • medusa-core-utils 0.1.27

GPL-2.0-only (1 packages):

  • breakword 1.0.5
Medium Risk Licenses - 4 packages

(MPL-2.0 OR Apache-2.0) (2 packages):

  • dompurify 2.3.4
  • dompurify 2.2.6

MPL-2.0 (2 packages):

  • axe-core 4.3.5
  • client-sessions 0.8.0
Unknown Licenses - 1734 packages
  • @apidevtools/json-schema-ref-parser 0.0.0-dev
  • @babel/cli@^7.12.1", "@babel/cli@^7.13.0", "@babel/cli@^7.14.3", "@babel/cli@^7.15.4", "@babel/cli@^7.16.0", "@babel/cli 7.16.7
  • @babel/code-frame@7.10.4", "@babel/code-frame 7.10.4
  • @babel/compat-data@^7.13.11", "@babel/compat-data 7.14.7
  • @babel/code-frame@^7.12.13", "@babel/code-frame@^7.14.0", "@babel/code-frame@^7.16.7", "@babel/code-frame@^7.5.5", "@babel/code-frame 7.16.7
  • @babel/code-frame@^7.10.4", "@babel/code-frame@^7.14.5", "@babel/code-frame 7.16.0
  • @babel/compat-data@^7.15.0", "@babel/compat-data 7.16.0
  • @babel/core@^7.1.0", "@babel/core@^7.12.3", "@babel/core@^7.12.7", "@babel/core 7.15.0
  • @babel/generator@^7.14.5", "@babel/generator@^7.15.0", "@babel/generator@^7.15.4", "@babel/generator 7.16.0
  • @babel/core@^7.13.8", "@babel/core@^7.14.3", "@babel/core@^7.15.5", "@babel/core@^7.16.0", "@babel/core@^7.4.4", "@babel/core@^7.7.2", "@babel/core 7.16.7
  • @babel/generator@^7.10.5", "@babel/generator@^7.12.11", "@babel/generator@^7.16.7", "@babel/generator 7.16.7
  • @babel/helper-annotate-as-pure@^7.10.4", "@babel/helper-annotate-as-pure@^7.14.5", "@babel/helper-annotate-as-pure 7.16.0
  • @babel/helper-builder-binary-assignment-operator-visitor@^7.14.5", "@babel/helper-builder-binary-assignment-operator-visitor 7.16.0
  • @babel/helper-create-class-features-plugin@^7.14.5", "@babel/helper-create-class-features-plugin 7.16.0
  • @babel/helper-create-class-features-plugin@^7.10.4", "@babel/helper-create-class-features-plugin@^7.12.1", "@babel/helper-create-class-features-plugin 7.15.4
  • @babel/helper-create-regexp-features-plugin@^7.14.5", "@babel/helper-create-regexp-features-plugin 7.16.0
  • @babel/helper-function-name@^7.10.4", "@babel/helper-function-name@^7.14.5", "@babel/helper-function-name@^7.15.4", "@babel/helper-function-name 7.16.0
  • @babel/helper-get-function-arity@^7.10.4", "@babel/helper-get-function-arity 7.16.0
  • @babel/helper-module-imports@^7.0.0", "@babel/helper-module-imports@^7.0.0-beta.49", "@babel/helper-module-imports 7.16.7
  • @babel/helper-hoist-variables@^7.14.5", "@babel/helper-hoist-variables@^7.15.4", "@babel/helper-hoist-variables 7.16.0

...and 1714 more

Powered by Codity.ai · Docs

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

Code Quality Report — test-org-codity/medusa · PR #2

Scanned: 2026-06-06 18:06 UTC | Score: 62/100 | Provider: github

Executive Summary

Severity Count
Critical 0
High 1
Medium 3
Low 3
Top Findings

[CQ-LLM-002] integration-tests/api/__tests__/admin/sales-channels.js:30 (Error_Handling · HIGH)

Issue: Swallowed exceptions in the beforeEach block without proper logging or handling.
Suggestion: Implement proper error handling or rethrow the error after logging.

console.error(e)

[CQ-LLM-001] integration-tests/api/__tests__/admin/sales-channels.js:23 (Complexity · MEDIUM)

Issue: The beforeEach function has multiple async calls which increases cyclomatic complexity.
Suggestion: Consider breaking down the async calls into separate functions to reduce complexity.

await adminSeeder(dbConnection)
await salesChannelsSeeder(dbConnection)

[CQ-LLM-003] packages/medusa/src/api/middlewares/sales-channel/get-requested-sales-channel.ts:1 (Documentation · MEDIUM)

Issue: Missing JSDoc for the public API function getRequestedSalesChannel.
Suggestion: Add JSDoc comments to describe the function's purpose, parameters, and return type.

export async function getRequestedSalesChannel(req: Request, res: Response, next: NextFunction): Promise<void> {

[CQ-LLM-004] packages/medusa/src/api/routes/admin/sales-channels/get-sales-channels.ts:5 (Testability · MEDIUM)

Issue: Directly using req.sales_channel without checking if it exists may lead to runtime errors.
Suggestion: Add a check to ensure req.sales_channel is defined before using it.

res.status(200).json({ sales_channel: req.sales_channel })

[CQ-008] integration-tests/api/__tests__/admin/sales-channels.js:72 (Maintainability · LOW)

Issue: Magic number 200 in code
Suggestion: Extract to a named constant

expect(response.status).toEqual(200)

[CQ-008] packages/medusa/src/api/routes/admin/sales-channels/get-sales-channels.ts:8 (Maintainability · LOW)

Issue: Magic number 200 in code
Suggestion: Extract to a named constant

res.status(200).json({ sales_channel: req.sales_channel })

[CQ-LLM-005] packages/medusa/src/api/routes/admin/sales-channels/index.ts:1 (Maintainability · LOW)

Issue: The comment disabling eslint rules is unnecessary and can lead to confusion.
Suggestion: Remove the eslint-disable comment or address the underlying issue.

/* eslint-disable @typescript-eslint/no-empty-function */

Per-File Breakdown

File Critical High Medium Low Total
integration-tests/api/__tests__/admin/sales-channels.js 0 1 1 1 3
packages/medusa/src/api/middlewares/sales-channel/get-requested-sales-channel.ts 0 0 1 0 1
packages/medusa/src/api/routes/admin/sales-channels/get-sales-channels.ts 0 0 1 1 2
packages/medusa/src/api/routes/admin/sales-channels/index.ts 0 0 0 1 1

Recommendations

  1. Resolve High severity issues, especially error handling gaps and performance bottlenecks.
  • Run automated tests after applying fixes to verify no regressions.

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.

4 participants