-
Notifications
You must be signed in to change notification settings - Fork 280
test: add test for the application create flow #2536
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
test: add test for the application create flow #2536
Conversation
|
Important Review skippedAuto incremental reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the WalkthroughThe changes refactor application creation from direct model usage to a service-driven architecture with conflict detection for already-reviewed applications. New constants, types, validation rules, and comprehensive test coverage support the expanded functionality, including role-based validation and social link handling. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Controller
participant Service
participant Model
participant Database
Client->>Controller: POST /applications (userId, payload)
Controller->>Service: createApplicationService(userId, payload)
Service->>Model: getUserApplications(userId)
Model->>Database: Query existing applications
Database-->>Model: Return applications array
Model-->>Service: applications
alt Existing app after review cycle date
Service->>Service: Check createdAt > REVIEW_CYCLE_START_DATE
Service-->>Controller: Throw Conflict error
Controller-->>Client: 409 Conflict response
else No conflict
Service->>Service: transformPayloadToApplication(payload)
Service->>Service: Enrich with score, status, createdAt, isNew
Service->>Model: addApplication(applicationData)
Model->>Database: Insert new application
Database-->>Model: Return applicationId
Model-->>Service: applicationId
Service-->>Controller: { applicationId, isNew: true }
Controller-->>Client: 201 Created with APPLICATION_CREATED_SUCCESS
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…reation logic - Updated APPLICATION_STATUS_TYPES to use an object for better clarity and added CHANGES_REQUESTED status. - Introduced APPLICATION_ROLES for role management. - Added new API response messages for application creation and updates. - Refactored addApplication controller to utilize createApplicationService for improved application handling. - Implemented validation for application roles in the application validator. - Added getApplicationByUserId method in the applications model to retrieve applications by user ID. - Created applicationService to encapsulate application creation logic and handle conflicts. - Updated application types to include role and social link structures.
…tests - Updated integration test to include imageUrl in application creation request. - Modified unit tests for application validator to include imageUrl in rawData for validation scenarios.
…tion creation logic - Implemented tests for various scenarios including successful application creation, conflict errors, and boundary cases based on application creation dates. - Verified correct transformation of payload fields and handling of optional fields. - Ensured error handling and logging for different error scenarios.
dd46666 to
96d8594
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
middlewares/validators/application.ts (1)
93-95: Update error message for consistency.Line 67 was updated to say "application data" but line 94 still references "recruiter data". Update for consistency.
✏️ Proposed fix
} catch (error) { - logger.error(`Error in validating recruiter data: ${error}`); + logger.error(`Error in validating application update data: ${error}`); res.boom.badRequest(error.details[0].message); }test/unit/middlewares/application-validator.test.ts (1)
68-88: Consider adding test for invalid imageUrl format.The tests cover
imageUrlbeing present but don't validate what happens when an invalid URL format is provided. SinceimageUrlis typed as URI in the validator, a test for invalid URL format would improve coverage.Example test case
it("should not call the next function if imageUrl is not a valid URI", async function () { const rawData = { ...applicationsData[6], imageUrl: "not-a-valid-url", }; const req = { body: rawData }; const res = { boom: { badRequest: () => {} } }; const nextSpy = Sinon.spy(); await applicationValidator.validateApplicationData(req, res, nextSpy); expect(nextSpy.callCount).to.equal(0); });
🤖 Fix all issues with AI agents
In @middlewares/validators/application.ts:
- Around line 55-60: The imageUrl field in the application validator is marked
as required but the Application and applicationPayload types define it as
optional and applicationService checks it with if (payload.imageUrl); update the
imageUrl joi schema in the application validator (the imageUrl validator entry)
to remove .required() and use .optional() or replace with .allow(null, '') /
.allow('') so the validator matches the types and service logic.
In @services/applicationService.ts:
- Around line 79-85: existingApplication.createdAt may be null/undefined so
creating a Date from it can yield epoch and produce incorrect comparisons; in
the block around existingApplication check (where you construct
existingCreatedAt and compare to APPLICATION_REVIEW_CYCLE_START_DATE and throw
Conflict with APPLICATION_ERROR_MESSAGES.APPLICATION_ALREADY_REVIEWED), first
validate that existingApplication.createdAt is a present, valid date (e.g.,
non-null/undefined and produces a valid Date) and if not, either skip the
review-cycle comparison or treat it as not reviewed (or throw a specific error),
ensuring you do not call new Date(...) on null/undefined before performing the
comparison.
In @test/fixtures/applications/applications.ts:
- Line 23: Fixtures in applications.ts currently set role: "developer" for
multiple entries; update the role property on each fixture object (the entries
that currently contain role: "developer") to use varied values like "designer",
"product_manager", "qa", etc., so tests exercise role-specific logic; locate the
fixture array or const that defines these application objects and change the
role string for the entries at the indicated spots (the objects containing the
role field around the repeated occurrences) to different realistic roles while
keeping object structure intact.
In @test/integration/application.test.ts:
- Line 15: Remove the unused import getUserApplicationObject from the test file
or add tests that exercise it; specifically, either delete the require statement
that imports getUserApplicationObject or write a new test case that calls
getUserApplicationObject (and asserts its expected output) so the import is used
and lint errors are resolved.
In @test/unit/services/applicationService.test.ts:
- Around line 199-201: The test's guard if (mockPayload.socialLink) never runs
because mockPayload is built from applicationsData[6] which lacks socialLink;
update the test to explicitly include a socialLink when constructing mockPayload
(or otherwise set mockPayload.socialLink = '<expected value>') so the
expectation
expect(applicationData.socialLink).to.deep.equal(mockPayload.socialLink)
actually executes and validates the field mapping for socialLink.
In @types/application.d.ts:
- Around line 14-19: Feedback.status currently uses hard-coded string literals;
update it to derive its type from the existing APPLICATION_STATUS_TYPES constant
(e.g., use a union from keys or values of APPLICATION_STATUS_TYPES) so Feedback
and application.status align; if "pending" should remain excluded from feedback,
explicitly filter out or omit that value when deriving the Feedback status type
and add a brief comment near the Feedback type explaining the exclusion.
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (10)
constants/application.tscontrollers/applications.tsmiddlewares/validators/application.tsmodels/applications.tsservices/applicationService.tstest/fixtures/applications/applications.tstest/integration/application.test.tstest/unit/middlewares/application-validator.test.tstest/unit/services/applicationService.test.tstypes/application.d.ts
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: AnujChhikara
Repo: RealDevSquad/website-backend PR: 2534
File: services/applicationService.ts:79-85
Timestamp: 2026-01-13T05:25:38.636Z
Learning: In the application creation flow (services/applicationService.ts), users with applications created before January 1, 2026 are intentionally allowed to create new applications regardless of whether their old application status was ACCEPTED, REJECTED, or PENDING. Only applications created after the cutoff date should prevent duplicate submissions by throwing a Conflict error.
📚 Learning: 2026-01-13T05:25:38.636Z
Learnt from: AnujChhikara
Repo: RealDevSquad/website-backend PR: 2534
File: services/applicationService.ts:79-85
Timestamp: 2026-01-13T05:25:38.636Z
Learning: In services/applicationService.ts, implement a date-based rule for duplicate submissions: users with applications created before 2026-01-01 may create new applications regardless of their previous application's status (ACCEPTED, REJECTED, or PENDING). For applications created on or after 2026-01-01, block duplicate submissions by throwing a Conflict error when attempting to create a new application if a prior submission already exists. This should be implemented as a hard check in the application creation flow, scoped to this file, and should reference the cutoff date and the Conflict error consistently.
Applied to files:
services/applicationService.ts
📚 Learning: 2026-01-13T05:25:38.636Z
Learnt from: AnujChhikara
Repo: RealDevSquad/website-backend PR: 2534
File: services/applicationService.ts:79-85
Timestamp: 2026-01-13T05:25:38.636Z
Learning: In the application creation flow (services/applicationService.ts), users with applications created before January 1, 2026 are intentionally allowed to create new applications regardless of whether their old application status was ACCEPTED, REJECTED, or PENDING. Only applications created after the cutoff date should prevent duplicate submissions by throwing a Conflict error.
Applied to files:
constants/application.tstest/unit/services/applicationService.test.tscontrollers/applications.ts
🧬 Code graph analysis (5)
services/applicationService.ts (2)
test/integration/discordactions.test.js (1)
ApplicationModel(11-11)types/application.d.ts (2)
applicationPayload(57-74)application(21-55)
test/unit/services/applicationService.test.ts (2)
test/integration/discordactions.test.js (1)
ApplicationModel(11-11)types/application.d.ts (1)
applicationPayload(57-74)
controllers/applications.ts (1)
services/applicationService.ts (1)
createApplicationService(70-111)
test/unit/middlewares/application-validator.test.ts (1)
controllers/users.js (1)
rawData(846-846)
middlewares/validators/application.ts (2)
types/global.d.ts (2)
CustomRequest(45-45)CustomResponse(44-44)constants/subscription-validator.ts (1)
phoneNumberRegex(2-2)
🔇 Additional comments (15)
models/applications.ts (1)
100-103: LGTM! Query optimized for service layer requirements.The
.orderBy("createdAt", "desc").limit(1)change ensuresgetUserApplicationsreturns only the most recent application, which aligns with the conflict detection logic increateApplicationServicethat checks if the latest application was created after the review cycle start date.controllers/applications.ts (1)
67-100: LGTM! Clean service-driven refactoring with proper error handling.The controller properly delegates to
createApplicationService, handles theConflicterror for 409 responses, and includesapplicationIdin the success response. The logging captures relevant context includingisNewstatus.services/applicationService.ts (1)
21-57: LGTM! Clean payload transformation with proper optional field handling.The transformation correctly maps the flat payload structure to the nested
applicationtype, and conditionally includesimageUrlandsocialLinkonly when present in the payload.constants/application.ts (1)
1-15: LGTM! Well-structured constants with proper documentation.The refactoring from array to object format for
APPLICATION_STATUS_TYPESimproves usability, and the newAPPLICATION_ROLESconstant aligns with theApplicationRoletype definition. TheCHANGES_REQUESTEDstatus addition supports the feedback workflow.types/application.d.ts (1)
57-74: LGTM! Payload type correctly defines required and optional fields.The
applicationPayloadtype properly marksroleas required andimageUrl/socialLinkas optional, matching the validation schema in the middleware.middlewares/validators/application.ts (1)
14-25: LGTM! Well-structured socialLink validation schema.The schema correctly validates optional social platform fields with minimum length constraints and applies regex validation to phoneNo. The
.optional()on the entire object allows applications without social links.test/integration/application.test.ts (1)
336-355: Test correctly validates new response format, but consider adding conflict scenario coverage.The test properly verifies the success case with the new response structure (
applicationIdproperty and updated message). However, integration tests for the conflict scenario (when a user already has an application created after Jan 1, 2026) are missing. This scenario is covered in unit tests but having an integration test would provide end-to-end validation.Consider adding an integration test that:
- Creates an application for a user with a
createdAtdate after Jan 1, 2026- Attempts to create another application for the same user
- Expects a 409 Conflict response
test/unit/middlewares/application-validator.test.ts (1)
9-22: Test updates correctly reflect new validation requirements.The addition of
imageUrlto test payloads aligns with the updated validator that now requires this field. The test structure is consistent and properly validates the success case.test/unit/services/applicationService.test.ts (7)
1-14: Well-structured test file with comprehensive imports.The imports are appropriate for the test suite. Good use of constants from the application module to ensure tests stay in sync with production code.
130-168: Thorough verification of default field values.The tests comprehensively verify that
isNew,score,status, andnudgeCountare correctly set regardless of whether an existing application exists (before the cutoff date).
204-226: Good coverage for optional field handling.This test properly validates that
undefinedoptional fields are omitted from the persisted data rather than being stored asundefinedvalues. This is important for clean database records.
228-247: Timestamp bounds verification is appropriate.The before/after capture approach is a reasonable way to verify timestamp creation without being overly strict. The test correctly validates that
createdAtis a string and falls within the expected time window.
250-313: Comprehensive error handling tests.The error handling suite properly covers:
- Conflict errors being propagated without modification
- Non-Conflict errors being logged before re-throwing
- Errors from
addApplicationbeing properly handledGood use of
sinon.stubfor the logger to verify error logging behavior without side effects.
24-26: Proper test cleanup with sinon.restore().Good practice using
afterEachwithsinon.restore()to ensure all stubs are cleaned up between tests, preventing test pollution.
85-108: Boundary case test correctly reflects service implementation.The test at lines 85-108 correctly expects that an application created exactly at
APPLICATION_REVIEW_CYCLE_START_DATE(Jan 1, 2026 00:00:00.000Z) should allow a new application to be created. The service implementation uses a strictly-greater-than comparison (existingCreatedAt > APPLICATION_REVIEW_CYCLE_START_DATEon line 82), which means applications created at the exact boundary are not considered "after" the cutoff and thus permit new submissions. This aligns with the learnings that applications created before January 1, 2026 (including the exact moment) are intentionally allowed to create new applications.
…logic - Removed conditional check for imageUrl and directly assigned it to the transformed object. - This change streamlines the transformation process for application payloads.
…dling - Modified the test to specifically check the handling of the optional field socialLink when not provided. - Ensured that imageUrl is correctly assigned from the mock payload during application creation.
0e9af59
* refactor: restructure application constants and enhance application creation logic - Updated APPLICATION_STATUS_TYPES to use an object for better clarity and added CHANGES_REQUESTED status. - Introduced APPLICATION_ROLES for role management. - Added new API response messages for application creation and updates. - Refactored addApplication controller to utilize createApplicationService for improved application handling. - Implemented validation for application roles in the application validator. - Added getApplicationByUserId method in the applications model to retrieve applications by user ID. - Created applicationService to encapsulate application creation logic and handle conflicts. - Updated application types to include role and social link structures. * test: add imageUrl to application data in integration and validation tests - Updated integration test to include imageUrl in application creation request. - Modified unit tests for application validator to include imageUrl in rawData for validation scenarios. * refactor: enhance application constants and update application retrieval logic * feat: add new API response message for successful application retrieval * test: add unit tests for createApplicationService to validate application creation logic - Implemented tests for various scenarios including successful application creation, conflict errors, and boundary cases based on application creation dates. - Verified correct transformation of payload fields and handling of optional fields. - Ensured error handling and logging for different error scenarios. * refactor: simplify imageUrl assignment in application transformation logic - Removed conditional check for imageUrl and directly assigned it to the transformed object. - This change streamlines the transformation process for application payloads. * test: update createApplicationService test to focus on socialLink handling - Modified the test to specifically check the handling of the optional field socialLink when not provided. - Ensured that imageUrl is correctly assigned from the mock payload during application creation.
* feat: add migration functionality for applications (#2537) * feat: add migration functionality for applications - Implemented `migrateApplications` controller to handle application migrations based on specified actions. - Added `addIsNewField` method in the model to update applications with a new `isNew` field. - Updated routes to include a new endpoint for triggering migrations. * fix: improve batch update logic in addIsNewField method * refactor: rename migration function and update route for adding 'isNew' field - Renamed `migrateApplications` to `addIsNewFieldMigration` for clarity. - Updated the route to directly call the new migration function without action parameters. * style: format route definition for addIsNewFieldMigration - Reformatted the route definition for better readability by aligning parameters in a multi-line format. * refactor: update addIsNewField logic and improve readability * refactor: streamline addIsNewField logic and enhance batch update process - Removed unnecessary tracking of skipped applications. - Simplified document processing by directly updating all documents in the snapshot. - Improved error handling by mapping document IDs for failed updates. * feat: Implement Create Application Flow for User Onboarding (#2534) * refactor: restructure application constants and enhance application creation logic - Updated APPLICATION_STATUS_TYPES to use an object for better clarity and added CHANGES_REQUESTED status. - Introduced APPLICATION_ROLES for role management. - Added new API response messages for application creation and updates. - Refactored addApplication controller to utilize createApplicationService for improved application handling. - Implemented validation for application roles in the application validator. - Added getApplicationByUserId method in the applications model to retrieve applications by user ID. - Created applicationService to encapsulate application creation logic and handle conflicts. - Updated application types to include role and social link structures. * test: add imageUrl to application data in integration and validation tests - Updated integration test to include imageUrl in application creation request. - Modified unit tests for application validator to include imageUrl in rawData for validation scenarios. * refactor: enhance application constants and update application retrieval logic * feat: add new API response message for successful application retrieval * test: add test for the application create flow (#2536) * refactor: restructure application constants and enhance application creation logic - Updated APPLICATION_STATUS_TYPES to use an object for better clarity and added CHANGES_REQUESTED status. - Introduced APPLICATION_ROLES for role management. - Added new API response messages for application creation and updates. - Refactored addApplication controller to utilize createApplicationService for improved application handling. - Implemented validation for application roles in the application validator. - Added getApplicationByUserId method in the applications model to retrieve applications by user ID. - Created applicationService to encapsulate application creation logic and handle conflicts. - Updated application types to include role and social link structures. * test: add imageUrl to application data in integration and validation tests - Updated integration test to include imageUrl in application creation request. - Modified unit tests for application validator to include imageUrl in rawData for validation scenarios. * refactor: enhance application constants and update application retrieval logic * feat: add new API response message for successful application retrieval * test: add unit tests for createApplicationService to validate application creation logic - Implemented tests for various scenarios including successful application creation, conflict errors, and boundary cases based on application creation dates. - Verified correct transformation of payload fields and handling of optional fields. - Ensured error handling and logging for different error scenarios. * refactor: simplify imageUrl assignment in application transformation logic - Removed conditional check for imageUrl and directly assigned it to the transformed object. - This change streamlines the transformation process for application payloads. * test: update createApplicationService test to focus on socialLink handling - Modified the test to specifically check the handling of the optional field socialLink when not provided. - Ensured that imageUrl is correctly assigned from the mock payload during application creation.
* refactor: restructure application constants and enhance application creation logic - Updated APPLICATION_STATUS_TYPES to use an object for better clarity and added CHANGES_REQUESTED status. - Introduced APPLICATION_ROLES for role management. - Added new API response messages for application creation and updates. - Refactored addApplication controller to utilize createApplicationService for improved application handling. - Implemented validation for application roles in the application validator. - Added getApplicationByUserId method in the applications model to retrieve applications by user ID. - Created applicationService to encapsulate application creation logic and handle conflicts. - Updated application types to include role and social link structures. * test: add imageUrl to application data in integration and validation tests - Updated integration test to include imageUrl in application creation request. - Modified unit tests for application validator to include imageUrl in rawData for validation scenarios. * refactor: enhance application constants and update application retrieval logic * feat: add new API response message for successful application retrieval * test: add unit tests for createApplicationService to validate application creation logic - Implemented tests for various scenarios including successful application creation, conflict errors, and boundary cases based on application creation dates. - Verified correct transformation of payload fields and handling of optional fields. - Ensured error handling and logging for different error scenarios. * refactor: simplify imageUrl assignment in application transformation logic - Removed conditional check for imageUrl and directly assigned it to the transformed object. - This change streamlines the transformation process for application payloads. * test: update createApplicationService test to focus on socialLink handling - Modified the test to specifically check the handling of the optional field socialLink when not provided. - Ensured that imageUrl is correctly assigned from the mock payload during application creation.
Date: 11 Jan 2026
Developer Name: @AnujChhikara
Issue Ticket Number
Tech Doc Link
Business Doc Link
Description
Documentation Updated?
Under Feature Flag
Database Changes
Breaking Changes
Development Tested?
Screenshots
Screenshot 1
Test Coverage
Screenshot 1
Additional Notes