Skip to content

Conversation

surajmaity1
Copy link
Contributor

@surajmaity1 surajmaity1 commented May 4, 2025

Date: 04 May, 2025

Developer Name: @surajmaity1


Issue Ticket Number

Description

  • A feature-flag-driven utility to normalize and transform Out-of-Office (OOO) request data based on feature flag
  • It ensures consistent data structure for OOO requests regardless of their source format.
  • The transformGetOooRequest function is a temporary solution implemented to handle mixed data. It will be removed once all the data is properly standardized and fixed.

When dev = true, format will be:

  id: string;
  type: REQUEST_TYPE.OOO;
  from: number;
  until: number;
  message: string;
  state: REQUEST_STATE;
  lastModifiedBy: string | null;
  requestedBy: string;
  reason: string | null;
  createdAt: Timestamp;
  updatedAt: Timestamp;

When dev = false, format will be:

  id: string;
  type: REQUEST_TYPE.OOO;
  from: number;
  until: number;
  reason: string;
  status: REQUEST_STATE;
  lastModifiedBy: string | null;
  requestedBy: string;
  userId: string;
  createdAt: Timestamp;
  updatedAt: Timestamp;
  comment: string | null;

Documentation Updated?

  • Yes
  • No

Under Feature Flag

  • Yes
  • No

Database Changes

  • Yes
  • No

Breaking Changes

  • Yes
  • No

Development Tested?

  • Yes
  • No

Screenshots

Screenshot 1 image image
GET.REQEST.DEV.FLAG.mp4
dashboard.OOO.GET.request.mp4

Test Coverage

Screenshot 1

image

Additional Notes

Copy link

coderabbitai bot commented May 4, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Summary by CodeRabbit

  • New Features
    • Improved handling of out-of-office (OOO) requests, with enhanced processing and transformation of request data based on user environment.
  • Chores
    • Added a new type for legacy out-of-office requests to support broader compatibility.

Walkthrough

The changes introduce a new asynchronous function, transformGetOooRequest, to handle transformation of out-of-office (OOO) requests based on a development flag. The getRequests function in the requests model now conditionally applies this transformation for OOO requests. Additionally, a new type alias, OldOooRequest, is added to represent a legacy or alternate structure for OOO requests. These updates facilitate differentiated processing and type safety for OOO request data, particularly in migration or compatibility scenarios.

Changes

File(s) Change Summary
models/requests.ts Updated imports and added conditional transformation of OOO requests via transformGetOooRequest in getRequests.
types/oooRequest.d.ts Added new type alias OldOooRequest representing an alternative OOO request structure.
utils/requests.ts Added transformGetOooRequest async function to transform OOO requests based on a dev flag and user data.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant RequestsModel
    participant UtilsRequests
    participant UserFetcher

    Caller->>RequestsModel: getRequests(type, ...)
    RequestsModel->>RequestsModel: fetch allRequests
    alt type == REQUEST_TYPE.OOO
        RequestsModel->>UtilsRequests: transformGetOooRequest(dev, allRequests)
        alt dev == true
            UtilsRequests->>UtilsRequests: Map requests to OldOooRequest if status exists
        else dev == false
            loop for each request with state
                UtilsRequests->>UserFetcher: fetchUser(requestedBy)
                UserFetcher-->>UtilsRequests: username
                UtilsRequests->>UtilsRequests: Map to OooStatusRequest with username
            end
        end
        UtilsRequests-->>RequestsModel: transformedRequests
    end
    RequestsModel-->>Caller: paginated (possibly transformed) requests
Loading

Suggested labels

backend, bug-fix, tests

Suggested reviewers

  • tejaskh3
  • pankajjs
  • vikasosmium
  • Achintya-Chatterjee
  • MayankBansal12

Poem

A bunny in code with ears so tall,
Hopped through requests, transforming them all.
With types anew and logic neat,
OOO requests now skip and leap!
Legacy or fresh, they’re handled with care—
In burrows of TypeScript, changes everywhere!
🐇✨


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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@surajmaity1 surajmaity1 marked this pull request as ready for review May 4, 2025 07:50
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🔭 Outside diff range comments (1)
models/requests.ts (1)

75-76: 🧹 Nitpick (assertive)

dev flag parsing silently ignores unexpected values

dev is derived from a string comparison (query.dev === "true").
• A typo such as True, 1, or "false " will silently fall back to false, producing the legacy payload when the caller might expect the new one.
• Consider coercing to boolean with a helper that validates the incoming value and throws (or logs) when it is neither "true" nor "false".

-const dev = query.dev === "true";
+const dev = (() => {
+  if (query.dev === undefined) return false;
+  if (query.dev === "true") return true;
+  if (query.dev === "false") return false;
+  logger.warn(`Unexpected dev flag value "${query.dev}", defaulting to false`);
+  return false;
+})();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cd928e2 and a8a81f6.

📒 Files selected for processing (3)
  • models/requests.ts (2 hunks)
  • types/oooRequest.d.ts (1 hunks)
  • utils/requests.ts (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
types/oooRequest.d.ts (1)
Learnt from: surajmaity1
PR: Real-Dev-Squad/website-backend#2386
File: test/fixtures/oooRequest/oooRequest.ts:59-60
Timestamp: 2025-03-16T05:23:33.460Z
Learning: The `createOooRequests2` object in test/fixtures/oooRequest/oooRequest.ts still uses the old property names `message` and `state` (instead of `reason` and `status`) because it's specifically used in acknowledging OOO request tests. This naming inconsistency will be fixed by surajmaity1 in a dedicated PR for acknowledging OOO requests.
🧬 Code Graph Analysis (3)
models/requests.ts (2)
constants/requests.ts (1)
  • REQUEST_TYPE (13-19)
utils/requests.ts (1)
  • transformGetOooRequest (41-99)
types/oooRequest.d.ts (1)
constants/requests.ts (2)
  • REQUEST_TYPE (13-19)
  • REQUEST_STATE (1-5)
utils/requests.ts (2)
types/oooRequest.d.ts (2)
  • OldOooRequest (22-34)
  • OooStatusRequest (7-20)
constants/requests.ts (1)
  • ERROR_WHILE_FETCHING_REQUEST (39-39)
🔇 Additional comments (3)
models/requests.ts (1)

93-99: requestedBy filter now branches on dev but the semantics diverge

When dev is true we expect requestedBy to already be a user-id, while in legacy mode it is a username.
That assumption is not documented anywhere and can easily break if the front-end forgets to toggle the flag. Please:

  1. Add JSDoc or runtime checks clarifying what the field represents in each mode.
  2. Fail fast if the format does not match the expectation (e.g. a UUID when a username is expected).
  3. Unit-test both branches.
types/oooRequest.d.ts (1)

22-34: lastModifiedBy initialisation in implementation contradicts the declared type

OldOooRequest.lastModifiedBy is typed as string | null, yet the transformation code initialises it with an empty string ("").
Using null is semantically clearer (“unknown”) and avoids the need for truthy checks.

- lastModifiedBy: string | null;
+ lastModifiedBy: string | null; // prefer null over empty string for “not set”

Please align the implementation (utils/requests.ts line 54) with the type or adjust the union to include "".

utils/requests.ts (1)

41-96: Parallelise user look-ups to avoid N × serial network calls

The for ... of + await pattern results in sequential calls to fetchUser, which can severely slow down pagination.
Prepare the promises first and await Promise.all:

-        for (const request of allRequests) {
-            if (request.state) {
-                try {
-                    const userResponse: any = await fetchUser({ userId: request.requestedBy });
-                    ...
-                } catch (error) { ... }
-            }
-        }
+        const transformed = await Promise.all(
+          allRequests.map(async (request) => {
+            if (!request.state) return request;
+            const { user } = await fetchUser({ userId: request.requestedBy });
+            return {
+              ... /* build OooStatusRequest */
+            };
+          })
+        );
+        oooRequests.push(...transformed);

[ suggest_optional_refactor ]

@AnujChhikara
Copy link
Member

Also, consider creating a dedicated issue or sub-issue for things like this, just to make sure they don’t get missed

@shubhdevelop
Copy link
Contributor

shubhdevelop commented May 5, 2025

Add test coverage screenshot and test PR

Copy link
Contributor

@shubhdevelop shubhdevelop left a comment

Choose a reason for hiding this comment

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

Is an integration test not necessary in this case?

@surajmaity1 surajmaity1 force-pushed the fix/ooo-get-request branch from c6736a6 to 5f7f267 Compare May 6, 2025 15:34
Copy link
Contributor

@shubhdevelop shubhdevelop left a comment

Choose a reason for hiding this comment

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

Update the test screenshot with the integration test coverage as well, and make the changes in the unit test. The rest looks good to me.

@surajmaity1 surajmaity1 force-pushed the fix/ooo-get-request branch from 5f7f267 to 05d07f2 Compare May 6, 2025 16:24
RishiChaubey31
RishiChaubey31 previously approved these changes May 6, 2025
@RishiChaubey31 RishiChaubey31 self-requested a review May 6, 2025 21:03
import * as requestsQuery from "../../models/requests";
import { userState } from "../../constants/userStatus";
import * as logUtils from "../../services/logService";
import { OldOooRequest, OooStatusRequest } from "../../types/oooRequest";
Copy link
Contributor

Choose a reason for hiding this comment

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

Are we using these types anywhere? If not why are we importing this?

Comment on lines 1 to 7
import { convertDateStringToMilliseconds, getNewDeadline, transformGetOooRequest } from "../../../utils/requests"
import { convertDaysToMilliseconds } from "../../../utils/time";
import {expect} from "chai";
import { createdOOORequest, oooStatusRequests } from "../../fixtures/oooRequest/oooRequest";
import sinon from "sinon";
import * as usersModel from "../../../models/users";
import { ERROR_WHILE_FETCHING_REQUEST } from "../../../constants/requests";
Copy link
Contributor

Choose a reason for hiding this comment

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

Same here, why are we importing these if not getting used anywhere?

};
};

export const transformGetOooRequest = async (dev, allRequests) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

If this is temporary then what is the need of putting this function inside utils?
Can't we put the entire thing on that if block in model and put a comment that this will eventually get removed once everything is fixed?

cc: @AnujChhikara

@surajmaity1 surajmaity1 force-pushed the fix/ooo-get-request branch 2 times, most recently from aa77448 to 6226837 Compare May 7, 2025 19:14
@surajmaity1 surajmaity1 force-pushed the fix/ooo-get-request branch from 6226837 to 2ba3e48 Compare May 7, 2025 19:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants