Skip to content
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

feat: Add past weeks/months for Autofill/Clear/Export windows #3428

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

ild0tt0re
Copy link
Contributor

Description

[FEAT] Add past weeks/months for Autofill/Clear/Export windows
task: https://app.clickup.com/t/86c1kj9fg

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • Any dependent changes have been merged and published in downstream modules

Copy link

vercel bot commented Jan 20, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
organized-app ✅ Ready (Inspect) Visit Preview Jan 20, 2025 10:35am

Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

Walkthrough

The pull request introduces a new environment variable VITE_APP_MODE to enable a "DEMO MODE" for the application. This change spans multiple files, including .env.example, LOCAL_ENVIRONMENT_SETUP.md, and several components related to meetings and reports. A new MenuSubHeader component is created to improve the UI organization, and utility functions for date manipulation are added to support more flexible date range handling.

Changes

File Change Summary
.env.example Added empty VITE_APP_MODE= environment variable
LOCAL_ENVIRONMENT_SETUP.md Added documentation for "DEMO MODE" configuration
src/components/menu_sub_header/index.tsx New MenuSubHeader functional component created
src/features/meetings/schedule_range_selector/index.tsx Refactored month options display with MenuSubHeader
src/features/meetings/schedule_range_selector/useScheduleRangeSelector.tsx Enhanced date filtering and sorting logic
src/features/meetings/week_range_selector/index.tsx Reorganized week options display with MenuSubHeader
src/features/meetings/week_range_selector/useWeekRangeSelector.tsx Modified week options generation logic
src/features/reports/field_service/selector_stats/person_filter/index.tsx Replaced local MenuSubHeader with imported component
src/utils/date.ts Added new date utility functions and MAX_DATE constant

Possibly related PRs

  • fix(reports): update logic to count inactive publishers #2471: This PR involves changes to the logic for counting inactive publishers, which may relate to the handling of environment variables like VITE_APP_MODE if it affects the application's state management or feature toggles.
  • feat(contact): connect to backend #3021: The addition of the VITE_APP_MODE variable in the .env.example file is directly related to the new feature for the frontend setup instructions in LOCAL_ENVIRONMENT_SETUP.md, which mentions activating "DEMO MODE" using this variable.

Suggested reviewers

  • rhahao

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?

❤️ 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.

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. (Beta)
  • @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.

Copy link
Contributor

@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: 1

🔭 Outside diff range comments (1)
src/features/meetings/week_range_selector/index.tsx (1)

Line range hint 41-58: Enhance accessibility for date selection.

The date selection UI could benefit from improved accessibility features.

Add ARIA labels and group roles:

+<div role="group" aria-label={t('tr_pastDates')}>
   <MenuSubHeader>{t('tr_pastDates')}</MenuSubHeader>
   {startPastWeeks.map((option) => (
     <MenuItem 
       key={option.value} 
       value={option.value}
+      aria-label={`${t('tr_startWeek')} ${option.label}`}
     >
       <Typography className="body-regular" color="var(--black)">
         {option.label}
       </Typography>
     </MenuItem>
   ))}
+</div>
🧹 Nitpick comments (4)
src/components/menu_sub_header/index.tsx (1)

1-19: Consider enhancing component flexibility with additional props.

The component is well-structured, but could benefit from additional customization options:

  • Allow overriding styles through props
  • Add optional padding/margin props
  • Consider adding a prop for sticky positioning

Example enhancement:

-export const MenuSubHeader = ({ children }: PropsWithChildren) => {
+type MenuSubHeaderProps = PropsWithChildren<{
+  className?: string;
+  sticky?: boolean;
+  sx?: Record<string, unknown>;
+}>;
+
+export const MenuSubHeader = ({ 
+  children, 
+  className = 'body-small-semibold',
+  sticky = false,
+  sx = {},
+}: MenuSubHeaderProps) => {
   return (
     <ListSubheader
-      className="body-small-semibold"
+      className={className}
       sx={{
         color: 'var(--accent-dark)',
         font: 'inherit',
         padding: '16px 16px 8px 16px',
         userSelect: 'none',
         backgroundColor: 'var(--white)',
+        position: sticky ? 'sticky' : 'static',
+        ...sx,
       }}
     >
src/features/meetings/week_range_selector/useWeekRangeSelector.tsx (1)

33-46: Consider memoizing mapSourcesToOptions function.

The mapping function could benefit from memoization to prevent unnecessary recalculations.

+const memoizedMapSourcesToOptions = useMemo(() => 
   (sourceList: typeof sources) =>
     sourceList.map((source) => {
       const [year, month, date] = source.weekOf.split('/');
       const monthName = monthNames[+month - 1];
 
       return {
         label: t('tr_longDateWithYearLocale', {
           year,
           month: monthName,
           date,
         }),
         value: source.weekOf,
       };
     });
+, [monthNames, t]);
src/features/meetings/schedule_range_selector/useScheduleRangeSelector.tsx (1)

25-40: Optimize date object creation in filtering function.

The current implementation creates new Date objects for each comparison. Consider caching the date object creation:

 const filterAndSortSources = (
   sources: SourceWeekType[],
   startDate: Date,
   endDate: Date
 ) => {
+  const sourceCache = sources.map(source => ({
+    ...source,
+    date: new Date(source.weekOf)
+  }));
   return sources
     .filter(
       (source) =>
-        new Date(source.weekOf) >= startDate &&
-        new Date(source.weekOf) < endDate &&
+        source.date >= startDate &&
+        source.date < endDate &&
         source.midweek_meeting.week_date_locale[lang]
     )
     .sort(
-      (a, b) => new Date(a.weekOf).getTime() - new Date(b.weekOf).getTime()
+      (a, b) => a.date.getTime() - b.date.getTime()
     );
 };
src/utils/date.ts (1)

6-6: Consider a more descriptive name for MAX_DATE constant.

The constant could benefit from a more descriptive name and documentation explaining its purpose.

-export const MAX_DATE = new Date(9999, 11, 31);
+/** Maximum allowed date for date range operations (December 31, 9999) */
+export const MAXIMUM_SUPPORTED_DATE = new Date(9999, 11, 31);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 585068f and 122219f.

⛔ Files ignored due to path filters (1)
  • src/locales/en/meetings.json is excluded by !**/*.json
📒 Files selected for processing (9)
  • .env.example (1 hunks)
  • LOCAL_ENVIRONMENT_SETUP.md (1 hunks)
  • src/components/menu_sub_header/index.tsx (1 hunks)
  • src/features/meetings/schedule_range_selector/index.tsx (4 hunks)
  • src/features/meetings/schedule_range_selector/useScheduleRangeSelector.tsx (2 hunks)
  • src/features/meetings/week_range_selector/index.tsx (4 hunks)
  • src/features/meetings/week_range_selector/useWeekRangeSelector.tsx (2 hunks)
  • src/features/reports/field_service/selector_stats/person_filter/index.tsx (1 hunks)
  • src/utils/date.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .env.example
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (5)
src/features/reports/field_service/selector_stats/person_filter/index.tsx (1)

6-6: LGTM! Good component reuse.

The replacement of the local MenuSubHeader with the shared component improves code reusability and maintains consistency across the application.

src/features/meetings/schedule_range_selector/index.tsx (1)

4-4: LGTM! UI improvements enhance user experience.

The changes effectively organize month options into "Past Dates" and "Upcoming Dates" categories using the MenuSubHeader component, making the selection interface more intuitive and user-friendly.

Also applies to: 20-20, 22-22, 40-41, 49-50

src/features/meetings/schedule_range_selector/useScheduleRangeSelector.tsx (1)

25-40: LGTM! Well-organized code with clear separation of concerns.

The extraction of filtering and sorting logic into a separate function improves code maintainability and reusability.

src/utils/date.ts (1)

15-29: LGTM! Well-structured date utility functions.

The new utility functions are well-organized, follow consistent naming patterns, and maintain single responsibility principle.

LOCAL_ENVIRONMENT_SETUP.md (1)

180-180: LGTM! Clear documentation for DEMO MODE feature.

The documentation clearly explains the purpose and configuration of the DEMO MODE feature, helping developers understand its usage during testing and demonstration.

Comment on lines +23 to +31
const filterSources = (startDate: Date, endDate: Date) =>
sources.filter(
(source) =>
new Date(source.weekOf) >= startDate &&
new Date(source.weekOf) < endDate &&
((meeting === 'midweek' &&
source.midweek_meeting.week_date_locale[lang]) ||
meeting === 'weekend')
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance date comparison robustness.

The date comparison logic could be improved to handle edge cases and timezone issues.

Consider this enhancement:

 const filterSources = (startDate: Date, endDate: Date) =>
   sources.filter(
     (source) =>
-      new Date(source.weekOf) >= startDate &&
-      new Date(source.weekOf) < endDate &&
+      new Date(source.weekOf).setHours(0, 0, 0, 0) >= startDate.setHours(0, 0, 0, 0) &&
+      new Date(source.weekOf).setHours(0, 0, 0, 0) < endDate.setHours(0, 0, 0, 0) &&
       ((meeting === 'midweek' &&
         source.midweek_meeting.week_date_locale[lang]) ||
         meeting === 'weekend')

Committable suggestion skipped: line range outside the PR's diff.

@ild0tt0re ild0tt0re force-pushed the feat/add-past-weeks-months branch from 122219f to 4b02050 Compare January 20, 2025 10:31
Copy link
Contributor

@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: 0

♻️ Duplicate comments (1)
src/features/meetings/week_range_selector/useWeekRangeSelector.tsx (1)

23-31: 🛠️ Refactor suggestion

Improve date comparison robustness.

The date comparison logic needs enhancement to handle timezone-related edge cases.

Apply this diff to normalize the dates for comparison:

 const filterSources = (startDate: Date, endDate: Date) =>
   sources.filter(
     (source) =>
-      new Date(source.weekOf) >= startDate &&
-      new Date(source.weekOf) < endDate &&
+      new Date(source.weekOf).setHours(0, 0, 0, 0) >= startDate.setHours(0, 0, 0, 0) &&
+      new Date(source.weekOf).setHours(0, 0, 0, 0) < endDate.setHours(0, 0, 0, 0) &&
       ((meeting === 'midweek' &&
         source.midweek_meeting.week_date_locale[lang]) ||
         meeting === 'weekend')
   );
🧹 Nitpick comments (3)
src/features/meetings/week_range_selector/useWeekRangeSelector.tsx (1)

33-46: Add error handling for date parsing.

The date splitting operation assumes a valid date format. Consider adding error handling for malformed dates.

 const mapSourcesToOptions = (sourceList: typeof sources) =>
   sourceList.map((source) => {
+    try {
       const [year, month, date] = source.weekOf.split('/');
+      if (!year || !month || !date) {
+        throw new Error('Invalid date format');
+      }
       const monthName = monthNames[+month - 1];
+      if (!monthName) {
+        throw new Error('Invalid month');
+      }

       return {
         label: t('tr_longDateWithYearLocale', {
           year,
           month: monthName,
           date,
         }),
         value: source.weekOf,
       };
+    } catch (error) {
+      console.error(`Invalid date format for source: ${source.weekOf}`);
+      return null;
+    }
   }).filter(Boolean);
src/features/meetings/schedule_range_selector/useScheduleRangeSelector.tsx (2)

42-58: Consider memoizing month names lookup.

The generateScheduleOptions function accesses monthNames array in a loop. Consider memoizing the month name lookup to avoid potential performance issues with large datasets.

 const generateScheduleOptions = (sources: SourceWeekType[]) => {
   const result: ScheduleOptionsType[] = [];
+  const monthNameMap = new Map(monthNames.map((name, i) => [i + 1, name]));
   for (const source of sources) {
     const [year, month] = source.weekOf.split('/');
     const isExist = result.find(
       (schedule) => schedule.value === `${year}/${month}`
     );
     if (!isExist) {
-      const monthName = monthNames[+month - 1];
+      const monthName = monthNameMap.get(+month);
       result.push({
         label: `${monthName} ${year}`,
         value: `${year}/${month}`,
       });
     }
   }
   return result;
 };

78-83: Consider adding type safety for array destructuring.

The endMonthOptions logic assumes startMonthOptions always returns a tuple of two arrays. Consider adding type safety to handle potential edge cases.

-    if (startMonth.length <= 0) return [[], []];
+    if (startMonth.length <= 0) return [[], []] as const;

-    const endSchedules = startMonthOptions.map((options) => {
+    const [pastOptions, upcomingOptions] = startMonthOptions;
+    const endSchedules = [
+      pastOptions.filter((schedule) => schedule.value >= startMonth),
+      upcomingOptions.filter((schedule) => schedule.value >= startMonth),
+    ] as const;
-      return options.filter((schedule) => schedule.value >= startMonth);
-    });

     return endSchedules;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 122219f and 4b02050.

⛔ Files ignored due to path filters (1)
  • src/locales/en/meetings.json is excluded by !**/*.json
📒 Files selected for processing (9)
  • .env.example (1 hunks)
  • LOCAL_ENVIRONMENT_SETUP.md (1 hunks)
  • src/components/menu_sub_header/index.tsx (1 hunks)
  • src/features/meetings/schedule_range_selector/index.tsx (4 hunks)
  • src/features/meetings/schedule_range_selector/useScheduleRangeSelector.tsx (2 hunks)
  • src/features/meetings/week_range_selector/index.tsx (4 hunks)
  • src/features/meetings/week_range_selector/useWeekRangeSelector.tsx (2 hunks)
  • src/features/reports/field_service/selector_stats/person_filter/index.tsx (1 hunks)
  • src/utils/date.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • .env.example
  • LOCAL_ENVIRONMENT_SETUP.md
  • src/features/reports/field_service/selector_stats/person_filter/index.tsx
  • src/components/menu_sub_header/index.tsx
  • src/utils/date.ts
  • src/features/meetings/week_range_selector/index.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (9)
src/features/meetings/week_range_selector/useWeekRangeSelector.tsx (3)

3-3: LGTM! Import statements are well-organized.

The new imports are properly structured and align with the added functionality.

Also applies to: 5-5


48-53: LGTM! Clear separation of past and upcoming sources.

The implementation effectively separates past and upcoming sources using appropriate date utility functions.


55-58: LGTM! Well-structured return values.

The separation of past and upcoming options in both startWeekOptions and endWeekOptions is well-implemented and maintains consistency.

Also applies to: 62-69

src/features/meetings/schedule_range_selector/index.tsx (3)

4-4: LGTM! Clean import organization.

The imports are well-organized, with related components grouped together.

Also applies to: 8-9


20-20: LGTM! Clear state destructuring.

The destructuring pattern effectively splits the options into past and upcoming months, improving code readability.

Also applies to: 22-22


40-50: LGTM! Well-structured UI with clear date categorization.

The implementation effectively separates past and upcoming dates using MenuSubHeader, providing clear visual hierarchy and improved user experience. The structure is consistently applied to both start and end month selectors.

Also applies to: 70-80

src/features/meetings/schedule_range_selector/useScheduleRangeSelector.tsx (3)

4-9: LGTM! Well-organized date utility imports.

The date utility functions are appropriately imported and provide clear functionality for date range handling.


60-74: LGTM! Clear separation of past and recent sources.

The implementation effectively separates and processes past and recent sources using appropriate date utility functions.


25-40: Consider adding error handling for invalid dates.

The filterAndSortSources function should handle potential invalid dates in the source data.

Consider adding date validation:

 const filterAndSortSources = (
   sources: SourceWeekType[],
   startDate: Date,
   endDate: Date
 ) => {
   return sources
     .filter(
-      (source) =>
-        new Date(source.weekOf) >= startDate &&
-        new Date(source.weekOf) < endDate &&
-        source.midweek_meeting.week_date_locale[lang]
+      (source) => {
+        try {
+          const sourceDate = new Date(source.weekOf);
+          return sourceDate >= startDate &&
+                 sourceDate < endDate &&
+                 source.midweek_meeting.week_date_locale[lang];
+        } catch {
+          console.warn(`Invalid date found: ${source.weekOf}`);
+          return false;
+        }
+      }
     )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant