feat: Implement Create Application Flow for User Onboarding#2534
Conversation
WalkthroughThis PR extends the application system with role-based applications, social link support, and image URLs. A new service layer handles application creation and updates, distinguishing between new applications and migrated ones through status codes and response messages. Changes
Sequence DiagramsequenceDiagram
participant Client
participant Controller
participant Service
participant Model
participant Database
Client->>Controller: POST /applications (with role, imageUrl, socialLink)
Controller->>Service: createApplicationService({userId, payload})
Service->>Model: getApplicationByUserId(userId)
Model->>Database: Query ApplicationsModel by userId
Database-->>Model: Return existing app or null
Model-->>Service: Application record or null
alt Existing application after 2026-01-01
Service-->>Controller: Throw Conflict (ALREADY_REVIEWED)
else Existing PENDING application (before 2026-01-01)
Service->>Database: Update application with transformed payload
Database-->>Service: Updated record
Service-->>Controller: {applicationId, isNew: true, migratedAt}
Controller->>Controller: Log with applicationId and isNew
Controller-->>Client: 200 APPLICATION_UPDATED_SUCCESS
else No existing application
Service->>Database: Create new application (status: PENDING)
Database-->>Service: New application record
Service-->>Controller: {applicationId, isNew: true}
Controller->>Controller: Log with applicationId and isNew
Controller-->>Client: 201 APPLICATION_CREATED_SUCCESS
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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 |
There was a problem hiding this comment.
Actionable comments posted: 10
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
test/fixtures/applications/applications.ts (1)
1-162: LGTM!The
role: "developer"field is correctly added to all fixture objects, aligning with the new required field in the application schema.Consider using varied roles across fixtures (e.g., "designer", "product_manager") to improve test coverage for role-specific behaviors.
🤖 Fix all issues with AI agents
In @constants/application.ts:
- Around line 21-25: The duplicate key APPLICATION_ALREADY_REVIEWED appears in
API_RESPONSE_MESSAGES and APPLICATION_ERROR_MESSAGES with different text;
consolidate by keeping a single canonical message or renaming one key to make
intent explicit (e.g., APPLICATION_ALREADY_REVIEWED_ERROR or
APPLICATION_ALREADY_REVIEWED_RESPONSE), update all usages to reference the
chosen symbol, or remove the API_RESPONSE_MESSAGES entry if it’s unused; ensure
you only change the key or value in API_RESPONSE_MESSAGES /
APPLICATION_ERROR_MESSAGES and update any references to those constants
accordingly.
In @middlewares/validators/application.ts:
- Around line 9-20: The socialLinkSchema object has a typo: the field "dribble"
should be "dribbble"; update the schema definition inside socialLinkSchema to
rename the key from dribble to dribbble (preserving
joi.string().uri().optional()) so incoming payloads for Dribbble are validated
correctly.
- Line 11: The phoneNo schema currently allows any string (phoneNo:
joi.string().optional()); tighten validation by adding either a regex pattern
for E.164 (e.g., /^\+?[1-9]\d{1,14}$/) or by applying length constraints via
.min()/.max(), and update the joi rule for the phoneNo field in the validator so
invalid phone numbers are rejected and valid formats are enforced.
In @models/applications.ts:
- Around line 119-136: getApplicationByUserId returns the first arbitrary
document because it lacks an ordering; modify the query on ApplicationsModel
(the call inside getApplicationByUserId) to order by "createdAt" descending and
limit the result to 1 (same behavior as getUserApplications) so you consistently
return the latest application for a user; update the
ApplicationsModel.where(...).get() call to include orderBy("createdAt", "desc")
and limit(1) before .get().
In @services/applicationService.ts:
- Around line 76-80: The code compares ISO strings which is brittle; convert the
sentinel "2026-01-01T00:00:00.000Z" to a Date and ensure
existingApplication.createdAt is compared as a Date/number (e.g., new
Date(januaryFirst2026) and existingApplication.createdAt instanceof Date ?
existingApplication.createdAt.getTime() : new
Date(existingApplication.createdAt).getTime()), then compare timestamps before
throwing Conflict(APPLICATION_ERROR_MESSAGES.APPLICATION_ALREADY_REVIEWED);
update the januaryFirst2026 symbol to hold a Date (or a numeric timestamp) and
use createdAt parsing/validation to avoid string comparisons.
- Around line 75-103: The current branch allows creating a new application when
an existing application was created before the 2026 cutoff but has a final
status (e.g., ACCEPTED/REJECTED), causing duplicates; update the logic in the
existingApplication handling (the block using existingApplication,
APPLICATION_STATUS_TYPES, and
APPLICATION_ERROR_MESSAGES.APPLICATION_ALREADY_REVIEWED) to explicitly block
creating a new application for non-PENDING statuses—after the createdAt check,
add a guard that if existingApplication.status !==
APPLICATION_STATUS_TYPES.PENDING (or is in [ACCEPTED, REJECTED]) then throw new
Conflict(APPLICATION_ERROR_MESSAGES.APPLICATION_ALREADY_REVIEWED) so only
PENDING records proceed to the migrate/update path that calls
transformPayloadToApplication and ApplicationModel.updateApplication.
In @test/integration/application.test.ts:
- Around line 356-372: The test is flaky because leftover applications persist
between tests; add an afterEach hook in the same describe block in
application.test.ts that cleans up test users' applications (e.g., await
applicationModel.deleteApplicationsByUserId(secondUserId) and the other test
user id) or alternatively generate and use a unique user id per test, and ensure
the cleanup awaits completion before proceeding to the next test so
getApplicationByUserId() returns deterministic results.
In @types/application.d.ts:
- Around line 78-81: The answers property currently uses a loose Record<string,
any> which reduces type safety; replace it with a more specific type (e.g.,
define an ApplicationAnswers interface or type alias that models expected
question keys and answer shapes, or use Record<string, string | number | boolean
| string[]> if answers are simple) and update the answers declaration to that
type (replace Record<string, any> with ApplicationAnswers or the chosen alias)
and then update any usages/tests to conform to the new shape to catch mismatches
at compile time.
- Around line 9-18: The SocialLink type has a typo: rename the field dribble to
dribbble within the SocialLink type definition and update all references/usages
of SocialLink across the codebase (imports, destructuring, mapping, tests,
serializers/deserializers, and any JSON keys) to use the new name; ensure
backward compatibility where necessary by migrating input/output mappings or
adding a temporary alias conversion from dribble to dribbble in places that
consume external data.
- Around line 20-25: Rename the exported type declaration named "feedback" to
use PascalCase ("Feedback") and update all references to it throughout the
codebase (including the usage currently referencing `feedback` on the other
declaration). Ensure the export name is updated to "Feedback" and fix any
imports/usages, type annotations, generics, or unions that refer to `feedback`
so they now reference `Feedback`, and run TypeScript to catch remaining spots.
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (8)
constants/application.tscontrollers/applications.tsmiddlewares/validators/application.tsmodels/applications.tsservices/applicationService.tstest/fixtures/applications/applications.tstest/integration/application.test.tstypes/application.d.ts
🧰 Additional context used
🧬 Code graph analysis (2)
services/applicationService.ts (2)
test/integration/discordactions.test.js (1)
ApplicationModel(11-11)types/application.d.ts (2)
applicationPayload(64-82)application(27-62)
controllers/applications.ts (1)
services/applicationService.ts (1)
createApplicationService(67-129)
⏰ 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: build (22.10.0)
- GitHub Check: Analyze (javascript)
🔇 Additional comments (10)
middlewares/validators/application.ts (2)
50-55: LGTM!Role validation correctly uses
Object.values(APPLICATION_ROLES)to ensure only valid roles are accepted. The imageUrl and socialLink validations are appropriately optional with proper URI validation.
76-81: LGTM!The status validation correctly uses
Object.values(APPLICATION_STATUS_TYPES).includes(value)to align with the refactored object-based constants.controllers/applications.ts (1)
67-109: LGTM!Good refactoring to use the service layer. The response handling correctly differentiates between new applications (201) and migrated ones (200). Error handling properly catches
Conflicterrors and returns appropriate 409 responses.test/integration/application.test.ts (1)
349-352: LGTM!Test expectations correctly verify the new response format with
applicationIdand appropriate messages for the creation flow.services/applicationService.ts (2)
18-54: LGTM!Clean transformation logic that properly maps the flat payload structure to the nested application model. Optional fields are handled correctly.
107-114: This type assertion is appropriate and all required fields are properly initialized.The
transformPayloadToApplicationfunction explicitly returnsPartial<application>and includes all required fields (userId,biodata,location,professional,intro,foundFrom). The object literal then provides additional fields (score,status,createdAt,isNew,nudgeCount). Theas applicationcast is justified because the resulting object satisfies the completeapplicationtype contract.Likely an incorrect or invalid review comment.
constants/application.ts (2)
1-6: LGTM!Good refactoring from array to object for
APPLICATION_STATUS_TYPES. This provides better type safety and allows for cleaner code when referencing specific statuses.
8-15: LGTM!Well-defined role constants with consistent naming. Consider adding TypeScript type exports for better type inference across the codebase.
types/application.d.ts (2)
52-61: LGTM with minor note.The new optional fields appropriately extend the application type to support role-based applications, social links, and migration tracking. The use of the newly defined
ApplicationRoleandSocialLinktypes ensures type safety.Note: The
feedbacktype reference on line 61 should be updated toFeedbackonce the naming convention issue is resolved (already flagged separately).
1-7: No action needed. The ApplicationRole type values already align perfectly with the APPLICATION_ROLES constant inconstants/application.ts. All six role strings ("developer", "designer", "product_manager", "project_manager", "qa", "social_media") match exactly between the type definition and the constant values.
5c88e7c to
2df534a
Compare
…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.
cf9de1e to
1c501e6
Compare
* 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
* 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.
…quad#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
Date: 10 Jan 2026
Developer Name: @AnujChhikara
Issue Ticket Number
Description
This PR implements the create application flow for the onboarding revamp, introducing role-based applications, migration support for existing pending applications, and enhanced validation.
Documentation Updated?
Under Feature Flag
Database Changes
Breaking Changes
Development Tested?
Screenshots
Screenshot 1
For new user successfully creating
screen-recording-2026-01-13-at-110213-am_LHykvFuR.mp4
For old user who have application before 1 Jan 2026
already-exist.mp4
Test Coverage
Screenshot 1
Additional Notes