-
Notifications
You must be signed in to change notification settings - Fork 19
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
Individual validation #753
Conversation
WalkthroughWalkthroughThe recent updates to the project-factory's server utilities primarily focus on performance optimization, enhanced error handling, and improved validation logic. Key changes include the removal of unnecessary delays, refactoring of user validation functions, addition of batching logic, and improved logging. Additionally, a new configuration parameter and a new enum value for campaign actions were introduced, alongside significant updates to validation logic and project date management. Changes
Sequence Diagram(s) (Beta)sequenceDiagram
participant Client
participant Server
participant Database
Client->>Server: Request to get all facilities
Server->>Database: Fetch facilities without delay
Database-->>Server: Facilities data
Server-->>Client: Response with facilities data
Client->>Server: Request to match user validation
Server->>Server: getUserWithMobileNumbers
Server->>Database: Batch fetch mobile numbers
Database-->>Server: Mobile numbers data
Server->>Server: matchUserValidation
Server-->>Client: Validation result
Client->>Server: Request to update project dates
Server->>Server: Validate action and dates
Server->>Database: Update project dates
Database-->>Server: Update confirmation
Server-->>Client: Response with update status
Poem
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (invoked as PR comments)
Additionally, you can add CodeRabbit Configration File (
|
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: 4
Outside diff range and nitpick comments (7)
utilities/project-factory/src/server/api/genericApis.ts (5)
Line range hint
37-37
: Replace directhasOwnProperty
usage with a safer alternative.- if (!workbook.Sheets.hasOwnProperty(sheetName)) { + if (!Object.prototype.hasOwnProperty.call(workbook.Sheets, sheetName)) {
Line range hint
72-72
: Replace directhasOwnProperty
usage with a safer alternative.- if (!workbook.Sheets.hasOwnProperty(mainSheet)) { + if (!Object.prototype.hasOwnProperty.call(workbook.Sheets, mainSheet)) {
Line range hint
103-105
: Simplify the optional chaining for better readability.- const firstRowValue = workbook.Sheets[localizedSheetName][`${sheetColumn}1`]?.v; + const firstRowValue = workbook.Sheets[localizedSheetName]?.[`${sheetColumn}1`]?.v;
Line range hint
178-185
: ReplaceforEach
withfor...of
for better performance and readability.- Object.keys(row).forEach((key) => { + for (const key of Object.keys(row)) {
Line range hint
200-200
: Specify more precise types instead ofany
to enhance type safety.Consider defining interfaces or types for the parameters and return values of this function to improve code robustness and maintainability.
utilities/project-factory/src/server/validators/campaignValidators.ts (2)
Line range hint
817-837
: Refactor to improve error handling and reduce duplication.The function
validateById
contains logic that could be simplified or broken down into smaller functions for better readability and maintainability. Additionally, consider handling the case whereaction
is not "changeDates" outside of this function to adhere to the Single Responsibility Principle.- if (action != "changeDates") { - if (request.body.ExistingCampaignDetails?.status != campaignStatuses?.drafted) { - throwError("COMMON", 400, "VALIDATION_ERROR", `Campaign can only be updated in drafted state. Change action to changeDates if you want to just update date.`); - } - } + validateCampaignDraftStatus(request.body.ExistingCampaignDetails?.status);
Line range hint
28-28
: Address type safety issues and improve iteration methods.Several lines in the file use the type
any
, which can lead to runtime errors and makes the code less maintainable. Additionally, the use offorEach
could be replaced withfor...of
for better performance and readability.- function processBoundary(responseBoundaries: any[], request: any, boundaryItems: any[], parentId?: string) { + function processBoundary(responseBoundaries: BoundaryType[], request: RequestType, boundaryItems: BoundaryItemType[], parentId?: string) { - boundaryItems.forEach((boundaryItem: any) => { + for (const boundaryItem of boundaryItems) {Also applies to: 30-30, 38-38, 40-40, 43-43, 46-46, 53-53, 54-54, 63-63, 65-65, 68-68, 71-71
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (7)
- utilities/project-factory/src/server/api/campaignApis.ts (7 hunks)
- utilities/project-factory/src/server/api/genericApis.ts (1 hunks)
- utilities/project-factory/src/server/config/index.ts (1 hunks)
- utilities/project-factory/src/server/config/models/campaignDetails.ts (1 hunks)
- utilities/project-factory/src/server/kafka/Listener.ts (1 hunks)
- utilities/project-factory/src/server/utils/campaignUtils.ts (4 hunks)
- utilities/project-factory/src/server/validators/campaignValidators.ts (5 hunks)
Additional context used
Biome
utilities/project-factory/src/server/config/models/campaignDetails.ts
[error] 2-2: The computed expression can be simplified without the use of a string literal.
[error] 3-3: The computed expression can be simplified without the use of a string literal.
[error] 4-4: The computed expression can be simplified without the use of a string literal.
[error] 5-5: The computed expression can be simplified without the use of a string literal.
[error] 6-6: The computed expression can be simplified without the use of a string literal.
[error] 7-7: The computed expression can be simplified without the use of a string literal.
[error] 8-8: The computed expression can be simplified without the use of a string literal.
[error] 10-10: The computed expression can be simplified without the use of a string literal.
[error] 11-11: The computed expression can be simplified without the use of a string literal.
[error] 12-12: The computed expression can be simplified without the use of a string literal.
[error] 13-13: The computed expression can be simplified without the use of a string literal.
[error] 15-15: The computed expression can be simplified without the use of a string literal.
[error] 16-16: The computed expression can be simplified without the use of a string literal.
[error] 17-17: The computed expression can be simplified without the use of a string literal.
[error] 18-18: The computed expression can be simplified without the use of a string literal.
[error] 20-20: The computed expression can be simplified without the use of a string literal.
[error] 21-21: The computed expression can be simplified without the use of a string literal.
[error] 22-22: The computed expression can be simplified without the use of a string literal.
[error] 23-23: The computed expression can be simplified without the use of a string literal.
[error] 24-24: The computed expression can be simplified without the use of a string literal.
utilities/project-factory/src/server/kafka/Listener.ts
[error] 34-34: Unexpected any. Specify a different type.
[error] 38-38: Template literals are preferred over string concatenation.
[error] 40-40: Unexpected any. Specify a different type.
[error] 45-45: Do not use template literals if interpolation and special-character handling are not needed.
[error] 71-71: Unexpected any. Specify a different type.
[error] 71-71: Unexpected any. Specify a different type.
[error] 1-1: Some named imports are only used as types.
utilities/project-factory/src/server/config/index.ts
[error] 54-54: Use Number.parseInt instead of the equivalent global.
utilities/project-factory/src/server/api/campaignApis.ts
[error] 23-23: Unexpected any. Specify a different type.
[error] 28-28: Unsafe usage of optional chaining.
[error] 34-34: Unexpected any. Specify a different type.
[error] 34-34: Unexpected any. Specify a different type.
[error] 34-34: Unexpected any. Specify a different type.
[error] 38-38: Unsafe usage of optional chaining.
[error] 40-43: This else clause can be omitted because previous branches break early.
[error] 52-52: Unexpected any. Specify a different type.
[error] 65-65: Unexpected any. Specify a different type.
[error] 83-83: Unexpected any. Specify a different type.
[error] 83-83: Unexpected any. Specify a different type.
[error] 85-85: Unexpected any. Specify a different type.
[error] 96-96: Unexpected any. Specify a different type.
[error] 102-102: Template literals are preferred over string concatenation.
[error] 115-115: Unexpected any. Specify a different type.
[error] 115-115: Unexpected any. Specify a different type.
[error] 117-117: Unexpected any. Specify a different type.
[error] 139-139: Unexpected any. Specify a different type.
[error] 139-139: Unexpected any. Specify a different type.
[error] 159-159: Unexpected any. Specify a different type.
utilities/project-factory/src/server/api/genericApis.ts
[error] 37-37: Do not access Object.prototype method 'hasOwnProperty' from target object.
[error] 51-51: Unexpected any. Specify a different type.
[error] 72-72: Do not access Object.prototype method 'hasOwnProperty' from target object.
[error] 85-85: Unexpected any. Specify a different type.
[error] 94-94: Unexpected any. Specify a different type.
[error] 99-99: Unexpected any. Specify a different type.
[error] 103-105: Change to an optional chain.
[error] 112-112: This var should be declared at the root of the enclosing function.
[error] 112-112: This variable implicitly has the any type.
[error] 139-139: Unexpected any. Specify a different type.
[error] 140-140: Unexpected any. Specify a different type.
[error] 142-149: Prefer for...of instead of forEach.
[error] 163-163: Unexpected any. Specify a different type.
[error] 165-165: Unexpected any. Specify a different type.
[error] 169-169: Unexpected any. Specify a different type.
[error] 175-190: This var should be declared at the root of the enclosing function.
[error] 175-175: Unexpected any. Specify a different type.
[error] 176-176: Unexpected any. Specify a different type.
[error] 178-185: Prefer for...of instead of forEach.
[error] 200-200: Unexpected any. Specify a different type.
utilities/project-factory/src/server/validators/campaignValidators.ts
[error] 28-28: Unexpected any. Specify a different type.
[error] 28-28: Unexpected any. Specify a different type.
[error] 28-28: Unexpected any. Specify a different type.
[error] 30-36: Prefer for...of instead of forEach.
[error] 30-30: Unexpected any. Specify a different type.
[error] 38-38: Unexpected any. Specify a different type.
[error] 40-40: Unexpected any. Specify a different type.
[error] 43-43: Unexpected any. Specify a different type.
[error] 46-49: Prefer for...of instead of forEach.
[error] 46-46: Unexpected any. Specify a different type.
[error] 53-53: Unexpected any. Specify a different type.
[error] 53-53: Unexpected any. Specify a different type.
[error] 53-53: Unexpected any. Specify a different type.
[error] 54-60: Prefer for...of instead of forEach.
[error] 54-54: Unexpected any. Specify a different type.
[error] 63-63: Unexpected any. Specify a different type.
[error] 65-65: Unexpected any. Specify a different type.
[error] 68-68: Unexpected any. Specify a different type.
[error] 71-74: Prefer for...of instead of forEach.
[error] 71-71: Unexpected any. Specify a different type.
utilities/project-factory/src/server/utils/campaignUtils.ts
[error] 23-23: Unexpected any. Specify a different type.
[error] 23-23: Unexpected any. Specify a different type.
[error] 40-40: Unexpected any. Specify a different type.
[error] 44-44: Unexpected any. Specify a different type.
[error] 57-57: Unexpected any. Specify a different type.
[error] 70-70: Template literals are preferred over string concatenation.
[error] 74-74: Template literals are preferred over string concatenation.
[error] 78-78: Template literals are preferred over string concatenation.
[error] 82-82: Unexpected any. Specify a different type.
[error] 82-82: Unexpected any. Specify a different type.
[error] 82-82: Unexpected any. Specify a different type.
[error] 82-82: Unexpected any. Specify a different type.
[error] 83-83: Unexpected any. Specify a different type.
[error] 89-89: Unexpected any. Specify a different type.
[error] 91-100: Prefer for...of instead of forEach.
[error] 91-91: Unexpected any. Specify a different type.
[error] 97-97: Use === instead of ==.
== is only allowed when comparing againstnull
[error] 97-97: Use === instead of ==.
== is only allowed when comparing againstnull
[error] 106-112: Prefer for...of instead of forEach.
[error] 106-106: Unexpected any. Specify a different type.
Additional comments not posted (3)
utilities/project-factory/src/server/config/models/campaignDetails.ts (1)
22-22
: The addition of "changeDates" to the enum for the "action" field is correctly implemented.Verification successful
The validation functions
validateCampaignBody
andvalidateProjectCampaignRequest
handle the "changeDates" action appropriately. However, the functionvalidateCampaignName
does not explicitly handle the "changeDates" action, but it is called withinvalidateCampaignBody
, which does handle it.
validateCampaignBody
includes a specific check foraction == "changeDates"
and callsvalidateChangeDatesRequest
.validateProjectCampaignRequest
does not directly handle "changeDates" but relies onvalidateCampaignBody
for detailed validation.Thus, the addition of "changeDates" to the enum for the "action" field is correctly integrated into the validation logic.
Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify that all validation functions handle the "changeDates" action. # Test: Search for validation functions that use the "action" field. Expect: Handling of "changeDates". rg --type typescript $'validate.*action'Length of output: 76
Script:
#!/bin/bash # Description: Verify that all validation functions handle the "changeDates" action. # Test: Search for validation functions that use the "action" field. Expect: Handling of "changeDates". rg --type ts 'validate.*action'Length of output: 882
Script:
#!/bin/bash # Description: Extract implementations of validation functions to verify handling of "changeDates" action. # Extract implementations of relevant validation functions. rg --type ts --context 10 'async function validateCampaignName' utilities/project-factory/src/server/validators/campaignValidators.ts rg --type ts --context 10 'async function validateCampaignBody' utilities/project-factory/src/server/validators/campaignValidators.ts rg --type ts --context 10 'async function validateProjectCampaignRequest' utilities/project-factory/src/server/validators/campaignValidators.tsLength of output: 3205
utilities/project-factory/src/server/kafka/Listener.ts (1)
72-72
: The added logging statements in theproduceModifiedMessages
function enhance traceability and debugging.Verification successful
The
produceModifiedMessages
function inListener.ts
contains several logging statements that enhance traceability and debugging. These statements are appropriately placed to log key events such as message production, errors, and successful operations.
- The logging statements are placed at the beginning of the function to log the topic and messages being sent.
- Additional logging is present to capture errors and successful message production.
The logging statements appear to be well-placed and should not lead to excessive logging under normal operation. However, it is advisable to monitor the log output to ensure it does not impact performance.
Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Monitor the log output to ensure it does not lead to excessive logging. # Test: Check log files for excessive logging. Expect: Reasonable amount of log entries. cat /var/log/kafka/listener.log | grep 'KAFKA :: PRODUCER'Length of output: 120
Script:
#!/bin/bash # Description: Search for logging statements in the `produceModifiedMessages` function within `Listener.ts`. # Find the `produceModifiedMessages` function and extract its content. ast-grep --lang typescript --pattern $'function produceModifiedMessages($_) { $$$ }' --json | jq -r '.[].text' | grep 'Logger'Length of output: 127
Script:
#!/bin/bash # Description: Display the content of the `Listener.ts` file, focusing on the `produceModifiedMessages` function. # Extract the `produceModifiedMessages` function from `Listener.ts`. ast-grep --lang typescript --pattern $'function produceModifiedMessages($_) { $$$ }' --json | jq -r '.[].text'Length of output: 113
Script:
#!/bin/bash # Description: Display the entire content of the `Listener.ts` file to manually verify the `produceModifiedMessages` function and logging statements. # Display the content of the `Listener.ts` file. cat $(fd Listener.ts)Length of output: 4196
utilities/project-factory/src/server/config/index.ts (1)
82-82
: The addition of thehealthIndividualHost
configuration parameter is correctly implemented and follows the existing pattern.Verification successful
The
healthIndividualHost
parameter is correctly implemented and used in the application.
index.ts
: The parameter is defined with a fallback URL.campaignApis.ts
: The parameter is used in an HTTP request.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify that the `healthIndividualHost` parameter is being used correctly in the application. # Test: Search for usages of `healthIndividualHost`. Expect: Correct usage in HTTP requests. rg --type typescript 'healthIndividualHost'Length of output: 78
Script:
#!/bin/bash # Description: Verify that the `healthIndividualHost` parameter is being used correctly in the application. # Test: Search for usages of `healthIndividualHost`. Expect: Correct usage in HTTP requests. rg --type ts 'healthIndividualHost'Length of output: 375
@@ -1148,7 +1150,7 @@ async function getCodesTarget(request: any, localizationMap?: any) { | |||
|
|||
async function createProject(request: any, actionUrl: any, localizationMap?: any) { | |||
logger.info("Create Projects started for the given Campaign") | |||
var { tenantId, boundaries, projectType, projectId, startDate, endDate } = request?.body?.CampaignDetails; | |||
var { tenantId, boundaries, projectType, projectId } = request?.body?.CampaignDetails; |
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.
Ensure proper type definitions to avoid using any
.
// Before
var { tenantId, boundaries, projectType, projectId } = request?.body?.CampaignDetails;
// After
interface CampaignDetails {
tenantId: string;
boundaries: Boundary[];
projectType: string;
projectId: string | null;
}
const { tenantId, boundaries, projectType, projectId }: CampaignDetails = request?.body?.CampaignDetails;
This change introduces a TypeScript interface to ensure type safety and avoid the use of any
.
async function updateProjectDates(request: any, actionInUrl: any) { | ||
const { startDate, endDate, projectId } = request?.body?.CampaignDetails | ||
if ((startDate || endDate) && projectId && actionInUrl == "update") { | ||
const projects = await getRelatedProjects(request); | ||
for (const project of projects) { | ||
project.startDate = startDate || project.startDate; | ||
project.endDate = endDate || project.endDate; | ||
delete project?.address; | ||
} | ||
logger.info("Projects related to current Campaign : " + JSON.stringify(projects)); | ||
const projectUpdateBody = { | ||
RequestInfo: request?.body?.RequestInfo, | ||
Projects: projects | ||
} | ||
const projectUpdateResponse = await httpRequest(config?.host?.projectHost + config?.paths?.projectUpdate, projectUpdateBody); | ||
if (projectUpdateResponse?.Project && Array.isArray(projectUpdateResponse?.Project) && projectUpdateResponse?.Project?.length == projects?.length) { | ||
logger.info("Project dates updated successfully") | ||
} | ||
else { | ||
throwError("PROJECT", 500, "PROJECT_UPDATE_ERROR") | ||
} |
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.
Refactor updateProjectDates
to handle errors more gracefully.
- throwError("PROJECT", 500, "PROJECT_UPDATE_ERROR")
+ if (!projectUpdateResponse?.Project || !Array.isArray(projectUpdateResponse?.Project) || projectUpdateResponse?.Project?.length !== projects?.length) {
+ logger.error("Failed to update project dates");
+ throw new Error("PROJECT_UPDATE_ERROR");
+ } else {
+ logger.info("Project dates updated successfully");
+ }
This change ensures that errors are logged before throwing, providing better traceability and error handling.
Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.
async function updateProjectDates(request: any, actionInUrl: any) { | |
const { startDate, endDate, projectId } = request?.body?.CampaignDetails | |
if ((startDate || endDate) && projectId && actionInUrl == "update") { | |
const projects = await getRelatedProjects(request); | |
for (const project of projects) { | |
project.startDate = startDate || project.startDate; | |
project.endDate = endDate || project.endDate; | |
delete project?.address; | |
} | |
logger.info("Projects related to current Campaign : " + JSON.stringify(projects)); | |
const projectUpdateBody = { | |
RequestInfo: request?.body?.RequestInfo, | |
Projects: projects | |
} | |
const projectUpdateResponse = await httpRequest(config?.host?.projectHost + config?.paths?.projectUpdate, projectUpdateBody); | |
if (projectUpdateResponse?.Project && Array.isArray(projectUpdateResponse?.Project) && projectUpdateResponse?.Project?.length == projects?.length) { | |
logger.info("Project dates updated successfully") | |
} | |
else { | |
throwError("PROJECT", 500, "PROJECT_UPDATE_ERROR") | |
} | |
async function updateProjectDates(request: any, actionInUrl: any) { | |
const { startDate, endDate, projectId } = request?.body?.CampaignDetails | |
if ((startDate || endDate) && projectId && actionInUrl == "update") { | |
const projects = await getRelatedProjects(request); | |
for (const project of projects) { | |
project.startDate = startDate || project.startDate; | |
project.endDate = endDate || project.endDate; | |
delete project?.address; | |
} | |
logger.info("Projects related to current Campaign : " + JSON.stringify(projects)); | |
const projectUpdateBody = { | |
RequestInfo: request?.body?.RequestInfo, | |
Projects: projects | |
} | |
const projectUpdateResponse = await httpRequest(config?.host?.projectHost + config?.paths?.projectUpdate, projectUpdateBody); | |
if (!projectUpdateResponse?.Project || !Array.isArray(projectUpdateResponse?.Project) || projectUpdateResponse?.Project?.length !== projects?.length) { | |
logger.error("Failed to update project dates"); | |
throw new Error("PROJECT_UPDATE_ERROR"); | |
} else { | |
logger.info("Project dates updated successfully"); | |
} | |
} | |
} |
function isObjectOrArray(value: any) { | ||
return typeof value === 'object' && value !== null && !Array.isArray(value); | ||
} | ||
|
||
|
||
|
||
async function validateProjectCampaignRequest(request: any, actionInUrl: any) { | ||
const CampaignDetails = request.body.CampaignDetails; | ||
const { id, hierarchyType, action, tenantId, boundaries, resources, projectType } = CampaignDetails; | ||
if (actionInUrl == "update") { | ||
if (!id) { | ||
throwError("COMMON", 400, "VALIDATION_ERROR", "id is required for update"); | ||
async function validateChangeDatesRequest(request: any) { | ||
var ExistingCampaignDetails = request?.body?.ExistingCampaignDetails; | ||
const { startDate: exsistingStartDate, endDate: exsistingEndDate } = ExistingCampaignDetails; | ||
var newCampaignDetails = request?.body?.CampaignDetails; | ||
const { startDate: newStartDate, endDate: newEndDate } = newCampaignDetails; | ||
|
||
for (const key in newCampaignDetails) { | ||
if (!isObjectOrArray(newCampaignDetails[key])) { | ||
// If the value is not an object or array, compare it with the corresponding value in ExistingCampaignDetails | ||
if (!(key == "startDate" || key == "endDate") && newCampaignDetails[key] !== ExistingCampaignDetails[key]) { | ||
// Handle the validation failure (for example, throw an error or log a message) | ||
throwError("COMMON", 400, "VALIDATION_ERROR", `${key} value in request campaign is not matching with existing campaign`); | ||
} | ||
} | ||
} | ||
if (!CampaignDetails) { | ||
throwError("COMMON", 400, "VALIDATION_ERROR", "CampaignDetails is required"); | ||
const today: any = Date.now(); | ||
if (exsistingStartDate >= today) { | ||
logger.info("Existing start date is greater than or equal to current date"); | ||
logger.info("Now only endDate can be updated") | ||
if (exsistingStartDate != newStartDate) { | ||
throwError("COMMON", 400, "VALIDATION_ERROR", "StartDate cannot be updated as campaign is started or completed."); | ||
} | ||
} | ||
if (!action) { | ||
throwError("COMMON", 400, "VALIDATION_ERROR", "CampaignDetails.action is required and must be either 'create' or 'draft'") | ||
if (exsistingEndDate > today) { | ||
logger.info("Existing end date is greater than or equal to current date"); | ||
if (exsistingEndDate != newEndDate) { | ||
throwError("COMMON", 400, "VALIDATION_ERROR", "EndDate cannot be updated as campaign is completed."); | ||
} | ||
} | ||
if (!(action == "create" || action == "draft")) { | ||
throwError("COMMON", 400, "VALIDATION_ERROR", "action can only be create or draft"); | ||
request.body.CampaignDetails = ExistingCampaignDetails; | ||
request.body.CampaignDetails.startDate = newStartDate; | ||
request.body.CampaignDetails.endDate = newEndDate; | ||
} |
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.
Simplify logic and improve readability in validateChangeDatesRequest
.
This function contains complex conditional logic that could be simplified. Consider breaking down the function into smaller, more focused functions and using early returns to reduce nesting and improve readability.
- for (const key in newCampaignDetails) {
- if (!isObjectOrArray(newCampaignDetails[key])) {
- if (!(key == "startDate" || key == "endDate") && newCampaignDetails[key] !== ExistingCampaignDetails[key]) {
- throwError("COMMON", 400, "VALIDATION_ERROR", `${key} value in request campaign is not matching with existing campaign`);
- }
- }
- }
+ validateCampaignDetails(newCampaignDetails, ExistingCampaignDetails);
Committable suggestion was skipped due low confidence.
const { startDate, endDate, action } = CampaignDetails; | ||
if (action != "changeDates") { | ||
if (startDate && endDate && (new Date(endDate).getTime() - new Date(startDate).getTime()) < (24 * 60 * 60 * 1000)) { | ||
throwError("COMMON", 400, "VALIDATION_ERROR", "endDate must be at least one day after startDate"); | ||
} | ||
const today: any = Date.now(); | ||
if (startDate <= today) { | ||
throwError("COMMON", 400, "VALIDATION_ERROR", "startDate cannot be today or past date"); | ||
} |
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.
Ensure consistent date validation logic across different actions.
The validation logic for startDate
and endDate
is duplicated in both validateDraftProjectCampaignMissingFields
and validateProjectCampaignMissingFields
. Consider refactoring this into a separate utility function to avoid code duplication and ensure consistency across different validation scenarios.
- if (startDate && endDate && (new Date(endDate).getTime() - new Date(startDate).getTime()) < (24 * 60 * 60 * 1000)) {
- throwError("COMMON", 400, "VALIDATION_ERROR", "endDate must be at least one day after startDate");
- }
- const today: any = Date.now();
- if (startDate <= today) {
- throwError("COMMON", 400, "VALIDATION_ERROR", "startDate cannot be today or past date");
- }
+ validateCampaignDates(startDate, endDate);
Committable suggestion was skipped due low confidence.
* Updates the delivery rules logic for gender * * info message for status creating (#644) * success message if user cred sheet * send id with key resourceid * Send variant in sku also Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Feat : added boundary validation (#643) Co-authored-by: Jagankumar <53823168+jagankumar-egov@users.noreply.github.com> * Update campaignValidators.ts (#645) * added delay in download (#646) * Update campaignValidators.ts (#647) * fixes (#649) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * fixed header validation (#648) * change in filter recursive (#650) * Update genericUtils.ts (#652) * fix (#651) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * updated lowest level hierarchy validation for target HLM -5948 (#654) * Update campaignValidators.ts (#655) * fixes-> cyclenumber issue, hover issue, dropdown height issue, * css * fixes-> cyclenumber issue, hover issue, dropdown height issue, (#656) * fixes-> cyclenumber issue, hover issue, dropdown height issue, * css --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Update campaignUtils.ts * fixed HLM-5970 * Feat : added boundary validation at data level * fixes * local add * Added boundary validation * Refactor * fixed HLM-5935 and HLM-5749 * Refactor * Feat : updated table * change campaignid in payload * Feat : added campaignId * Update campaignApis.ts * Update campaignValidators.ts * refactored * Refactor * assigned campaignId * Refactor * updated createRequest Schema * Feat : invalid Status Persist * status fix * version-fix * Update CODEOWNERS * core version updated and css fix for language dropdown * refactor (#676) * Uat signoff (#678) * change in filter recursive * lowest level * added validation related to target sheet headers * HLM-5916 * download button fixes in summary (#682) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Hlm 5927 (#687) * change in filter recursive * lowest level * added validation for boundary codes to be invalid other than that selected from UI in target upload * Added Delivery and cycle config for LLIN and SMC both (#688) * no of cycle and deivery drafted changes * fixes * add localisation code for boundaries * fixes * fixes * Value localise in summary screen, api error change * fixes * genarate api call fix * font size change for summary * login css change * HLM-5718: SMC delivery config enhancement * config update * added config for in between * fix config for llin * added mdms integration --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Fixed HLM-5988_warning message (#689) Co-authored-by: nabeelmd-eGov <94039229+nabeelmd-eGov@users.noreply.github.com> * download filename fixes (#693) * download button fixes in summary * download filename with custom name changes added --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * download filename fixes (#694) * download button fixes in summary * download filename with custom name changes added * config fix for llin --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * successful toast message is fixed (#695) * successful toast message is fixed * Update UploadData.js * HLM-5991: Alert Pop UP CR (#696) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * HLM-5718 changes (#703) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Localization cache (#706) * change in filter recursive * lowest level * refactored localization cache logic * Update README.md (#707) * Update README.md * Update README.md * Update utilities/project-factory/README.md Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update README.md --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * HLM-5985_made lowest level changes (#708) * HLM-5985_made lowest level changes * resolved codeRabbit comments * Create LOCALSETUP.md (#709) * Create LOCALSETUP.md * Refactored config * Update LOCALSETUP.md * Update utilities/project-factory/LOCALSETUP.md Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update utilities/project-factory/LOCALSETUP.md Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update utilities/project-factory/LOCALSETUP.md Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update utilities/project-factory/LOCALSETUP.md Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update LOCALSETUP.md --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * updated the localisation module config * Refactor config (#713) * Refactor config * Update utilities/project-factory/src/server/validators/campaignValidators.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update utilities/project-factory/src/server/validators/campaignValidators.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update utilities/project-factory/src/server/validators/campaignValidators.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update postman_collection.json (#714) * Update postman_collection.json * Update postman_collection.json * Delete utilities/project-factory/project_factory_swagger.yml (#715) * Feat : removed campaignId validation for boundary upload (#718) * updated the delay for boundary relationship * added logger for request TODO TEST will be reverted * Revert "added logger for request TODO TEST" This reverts commit d5c2bf5. * Schema validation (#719) * Feat : removed campaignId validation for boundary upload * Feat : added schema validation * Fixed mdms host * updated the logger messages * updated the loggers * delivery new changes, toast fix, error fix (#716) * delivery new changes, toast fix, error fix * new fixes * fixes * change text component to field component * added hierarchy * fix * fix * fix * fix * passing hierarchy from props --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Schema validation2 (#721) * Feat : removed campaignId validation for boundary upload * Feat : added schema validation * Fixed mdms host * Feat : added boundary validation * Feat : optimized product search * Fix : project mapping fixed (#722) * Fixed project search (#723) * smc fixes (#724) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Feat : added boundary confirmation (#727) * Fix: fixed processing boundary * Refactor * fixed HLM-6109 (#729) * gate fixes validation, ui ux (#731) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * integrated panelcard component (#732) * integrated panelcard component * Update micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/Response.js Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --------- Co-authored-by: Jagankumar <53823168+jagankumar-egov@users.noreply.github.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update genericUtils.ts (#733) * Create CHANGELOG.md (#717) * Update request.ts (#735) * fixed generate api issue (#734) Co-authored-by: Jagankumar <53823168+jagankumar-egov@users.noreply.github.com> * Create CHANGELOG.md * gate fixes (#736) * gate fixes validation, ui ux * gate fix --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * added loader in the selecting boundaries (#737) * Update createAndSearch.ts (#738) * fix (#739) * fix * fix --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Patch 3 (#740) * change in filter recursive * lowest level * trimmed underscore and empty spaces * boundary fix (#742) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Update genericUtils.ts (#746) * fixed the delivery products issue * Fixed delivery conditions issue * Update campaignApis.ts (#747) * fixed warning toast (#748) * fixed warning toast * Update UploadData.js * fix (#749) * fix * fx * fix --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * core -update (#751) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * fixed stepper issue (#752) * fixed stepper issue * Update index.html * Feat : added user validation via individual (#753) * fixes (#754) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * code fix nabeel (#756) * fixes * fix --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Updated few loggers (#759) * updated few loggers flow * Update utilities/project-factory/src/server/api/campaignApis.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update utilities/project-factory/src/server/utils/campaignMappingUtils.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update utilities/project-factory/src/server/utils/campaignUtils.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update utilities/project-factory/src/server/validators/campaignValidators.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update utilities/project-factory/src/server/api/campaignApis.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update utilities/project-factory/src/server/utils/campaignMappingUtils.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update utilities/project-factory/src/server/utils/genericUtils.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Updated the user Password generation logic #761 * Update Listener.ts (#730) * Update Listener.ts * added try catch logic in producer * Feat : added parallel batch execution (#767) * Feat : added parallel batch execution * Refactor * Update utilities/project-factory/src/server/validators/campaignValidators.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * fixed the stepper (#765) * changes config (#769) * Project type config and added loggers for process of campaign (#772) * Feat : added themes in generate template (#773) * fixed the ajv package version for build issue * Feat : removed xlsx (#776) * HLM-6177: PARALLEL SEARCH IMPLEMENT, DELIVERY TYPE IMPLEMENT (#778) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * css update (#780) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * HLM-6179 and HLM-6180 (#777) * HLM-6179 and HLM-6180 * campaign name changes --------- Co-authored-by: Jagankumar <53823168+jagankumar-egov@users.noreply.github.com> * Feat : fixed target generation (#781) * fixed tenantId issue (#784) * fix: resolved AJV-related Jenkins build issue reference #783 #786 (#787) * module ui fix * updated all the package version for build fixes * fixed kafka-error at target generation (#789) * updated core version (#791) * updated core version * updated css also * Update campaignValidators.ts (#794) * Updated the excel generation logic and files * added changes for configurable column in target sheet (#779) * change in filter recursive * lowest level * made target headers genearte through mdms schema * changed config index.ts * changed config index.ts * changes for now * added configurable column logic from schema HLM-6169 * updated validate of target columns through schema * added masterForColumnSchema in index.ts * formatted dataManageService * refactored lock TargetFields func * removed console.log * User creation performance improved (#800) * Feat : Improved user creation performance * Change status color * Update utilities/project-factory/src/server/utils/campaignUtils.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --------- Co-authored-by: Jagankumar <53823168+jagankumar-egov@users.noreply.github.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update genericUtils.ts (#801) * Hlm 6170 (#802) * change in filter recursive * lowest level * HLM -6170 added logic for only village level data in target sheet and some refactoring * updated css (#804) * fixed button issue (#805) * HLM 6177: Error card implementation in summary screen (#806) * HLM-6177: PARALLEL SEARCH IMPLEMENT, DELIVERY TYPE IMPLEMENT * Added Error Cards in summary screen and redirection --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * added error button styles (#807) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * updated popUp css (#808) * HLM 6178: Implementing New Pop up screen in boundaries (#809) * added error button styles * Implementing New Pop up screen in boundaries --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Facility changes (#812) * Feat : changed facility Template * Feat : locked target templates * fixed colour issue (#813) * Updated the project type conversion logic for the "deliveryType" dont1 and n config * Unique field added (#814) * Feat : changed facility Template * Feat : locked target templates * Feat : added unique check logic * Target schema update (#815) * change in filter recursive * lowest level * updated shcema of target columns to be configurable * removed empty spaces from config index.ts * Active mapping (#817) * Feat : changed facility Template * Feat : locked target templates * Feat : added unique check logic * Feat : added mapping via active field * changes in the schema validation (#816) * Updated the workbench and css module version * Feat : added active inactive boundary check (#818) * Update campaignValidators.ts (#819) * added active inactive validation (#820) * changed api call time (#826) * Feat : added target sum mapping (#825) * added campaign type as filter (#827) * Update genericApis.ts (#828) * Update excelUtils.ts (#829) * UI issue fixes, icon fix in summary error (#831) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Target columns (#830) * change in filter recursive * lowest level * commit * Feat : target flow fixed for LLIN-mz * uat to dev --------- Co-authored-by: admin1 <nitish@egovernments.org> * Feat : freezed target columns (#833) * Target mr dn (#834) * change in filter recursive * lowest level * Feat : skipped validation temporarily * changes in the target validation (#835) * fixed error info (#837) * Added roboto font (#840) * Feat : added roboto font * Fixed config * target validation based on diff campaign types (#843) * change in filter recursive * lowest level * updated validation of target based on campaign type * fixed validation issue (#844) * Updated the workbench package version * fixed validation logic (#846) * fixed validation logic * Update micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/UploadData.js Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --------- Co-authored-by: Jagankumar <53823168+jagankumar-egov@users.noreply.github.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Error messages improved (#848) * Feat : imporved error messages and initilised utils for tracking process * Fix ; unused variables fixed * Feat : improved error messages * Fix : download error fix (#850) * Update campaignUtils.ts (#851) * Update campaignUtils.ts * Update utilities/project-factory/src/server/utils/campaignUtils.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update campaignValidators.ts (#853) * HLM 6210: Toast, error focus fix and project type reset delivery data fix (#854) * HLM-6210: campaign type change reset delivery data fix, summary error focus fix * summary error focus fix --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * HLM-6225_added time out according to data (#855) * Update campaignValidators.ts (#859) * HLM 6210 (#858) * HLM-6210: campaign type change reset delivery data fix, summary error focus fix * summary error focus fix * parallel search fixes --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Remove validation (#852) * change in filter recursive * lowest level * removed unnecessary validation for target * spacing refactor * Update campaignValidators.ts (#863) * Header validation (#861) * change in filter recursive * lowest level * removed unnecessary validation for target * changed the logic of header validation * space refactor * Update campaignUtils.ts (#864) * fixed ui error (#865) * Read me (#867) * change in filter recursive * lowest level * removed unnecessary validation for target * changed the logic of header validation * fixed portugese language error * space refactoring * Update Dockerfile * Update Dockerfile * Update migrate.sh * Update Dockerfile * Update campaignValidators.ts (#868) * HLM 6210:campaign type change reset fix (#869) * HLM-6210: campaign type change reset delivery data fix, summary error focus fix * summary error focus fix * parallel search fixes * campaign type change reset fix --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Update excelUtils.ts for sheetHeaders wraping (#870) * Update package.json * updated error messages (#871) * feat : added jaeger-client tracing (#872) * updated the table config * Update campaignApis.ts (#875) * removed the schema and updated the db name * fixing generate API call, file auto delete, date error (#877) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Trim resource (#878) * Feat : trimmed resource persist message * Refactor * Removed reject error in produce message * fixed min time, draft logic (#879) * Update index.ts (#880) * added min ui error and facility usage (#883) * added min ui error and facility usage * changes * Update campaignUtils.ts (#884) * HLM 6007 (#885) * fixing generate API call, file auto delete, date error * generate api fix --------- Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * Update Dockerfile * Feat : docker config update (#886) * Update Dockerfile (#887) * Create buildWorkbenchUI.yml * Update README.md (#917) * Update buildWorkbenchUI.yml * Update README.md * Updated the DB Schema issue of Project-factory * fixed hierarchy order (#919) * User flag hcm (#920) * Feat : docker config update * Feat : added user create flag * Refactored * Update campaignUtils.ts * Update campaignMappingUtils.ts (#922) * Ashish egov patch 2 (#921) * Update index.ts * Update campaignApis.ts * Fixed the project type conversion and product duplicate issue * Update campaignApis.ts (#924) * Update campaignMappingUtils.ts (#925) * Update campaignMappingUtils.ts * Refactored * Update publishProjectFactory.yml * Update buildWorkbenchUI.yml * Update campaignMappingUtils.ts (#926) * Update request.ts (#928) * Update request.ts * Feat : updated httprequest * Feat : warning response added * Refactor * added start and enddate in cycles * Update campaignApis.ts (#930) * Update request.ts (#932) * fixed generate issue (#933) * Fixed project-type resources duplication * updated target error messages (#936) * fixed stepper from draft (#937) * Update Listener.ts * delivery type disable fix, product sku name change (#939) Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> * fixed error message issue (#941) * Redis integration (#940) * Feat : added redis * Feat : added redis retry * removed templates folder * updated the folder structure for health ui and removed utilties * Update publishAllPackages.yml * Update buildWorkbenchUI.yml --------- Co-authored-by: nabeelmd-eGov <94039229+nabeelmd-eGov@users.noreply.github.com> Co-authored-by: nabeelmd-eGov <nabeel.md@egovernments.com> Co-authored-by: ashish-egov <137176738+ashish-egov@users.noreply.github.com> Co-authored-by: Bhavya-egov <137176879+Bhavya-egov@users.noreply.github.com> Co-authored-by: nitish-egov <137176807+nitish-egov@users.noreply.github.com> Co-authored-by: Bhavya-egov <bhavya.mangal@egovernments.org> Co-authored-by: ashish-egov <ashish.tiwari@egovernments.org> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> Co-authored-by: Swathi-eGov <137176788+Swathi-eGov@users.noreply.github.com> Co-authored-by: admin1 <nitish@egovernments.org>
No description provided.