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

Website: Fetch recipient details on partners page and transparency/finance page from firestore #1020

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

DarkMenacer
Copy link
Contributor

@DarkMenacer DarkMenacer commented Jan 24, 2025

Summary by CodeRabbit

  • Localization Updates

    • Updated text strings for finances in German, English, French, and Italian locales
    • Refined messaging about recipient support and program engagement
    • Introduced "Active Recipients" metric across multiple languages
  • Partner Management

    • Simplified NGO identifiers
    • Removed detailed recipient statistics from NGO entries
    • Standardized partner data representation across languages
  • Data Calculation

    • Added new utility for calculating recipient statistics
    • Enhanced transparency reporting with more precise recipient tracking
  • User Interface

    • Updated financial dashboard to display active recipient information
    • Improved data rounding and presentation logic

Copy link

coderabbitai bot commented Jan 24, 2025

📝 Walkthrough

Walkthrough

This pull request introduces comprehensive changes across multiple localization files and components, focusing on recipient statistics and NGO representation. The modifications streamline NGO identifiers, remove recipient-specific metrics from partner data, and introduce a new RecipientStatsCalculator to dynamically compute recipient statistics. Changes span locales (German, English, French, Italian) and affect website components related to partners and financial transparency.

Changes

File Change Summary
shared/locales/*/website-finances.json Updated "totalRecipients" text from enrollment to support, added "activeRecipients" metric across German, English, French, and Italian locales
shared/locales/*/website-partners.json Simplified NGO identifiers, removed recipient-related fields, standardized across locales
shared/src/utils/stats/RecipientStatsCalculator.ts New utility for calculating recipient statistics with methods for total and organization-specific counts
website/src/app/[lang]/[region]/(website)/partners/(sections)/ngolist.tsx Integrated RecipientStatsCalculator for dynamic recipient data retrieval
website/src/app/[lang]/[region]/(website)/transparency/finances/[currency]/page.tsx Added recipientStats to page and section props
website/src/app/[lang]/[region]/(website)/transparency/finances/[currency]/section-1.tsx Updated rounding logic, integrated recipient statistics display

Sequence Diagram

sequenceDiagram
    participant FirestoreAdmin
    participant RecipientStatsCalculator
    participant NgoList
    participant TransparencyPage

    FirestoreAdmin->>RecipientStatsCalculator: Retrieve recipient data
    RecipientStatsCalculator-->>NgoList: Provide organization stats
    RecipientStatsCalculator-->>TransparencyPage: Provide total recipient stats
    TransparencyPage->>Section1: Render recipient statistics
Loading

Possibly related PRs

Suggested Labels

surveys, website

Suggested Reviewers

  • andrashee
  • socialincome-dev
  • mkue
  • ssandino

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a59b32f and 9463af0.

📒 Files selected for processing (5)
  • shared/locales/de/website-partners.json (6 hunks)
  • shared/locales/en/website-partners.json (6 hunks)
  • shared/locales/fr/website-partners.json (6 hunks)
  • shared/locales/it/website-partners.json (6 hunks)
  • website/src/app/[lang]/[region]/(website)/partners/(sections)/ngolist.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • shared/locales/it/website-partners.json
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Test website
  • GitHub Check: Test shared code
  • GitHub Check: Test functions
  • GitHub Check: Test admin
  • GitHub Check: Prettify
  • GitHub Check: Security checks (typescript)
🔇 Additional comments (5)
website/src/app/[lang]/[region]/(website)/partners/(sections)/ngolist.tsx (2)

13-13: LGTM!

The imports are correctly added for the new functionality.

Also applies to: 15-15


46-53: Verify the NGO identifier usage.

The code assumes the NGO identifiers in the translation files match those in Firestore.

✅ Verification successful

NGO identifier usage is properly implemented

The code safely separates translation slugs from Firestore data, using proper database references for querying organization data.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify NGO identifiers match between translation files and Firestore

# Test: Compare NGO IDs in translation files
echo "Checking NGO IDs across translation files..."
rg -A 1 '"ngos":\s*\[' shared/locales/*/website-partners.json

# Test: Search for Firestore ID usage
echo "Checking Firestore ID usage..."
rg -A 5 'allStats\(' 

Length of output: 6082


Script:

#!/bin/bash
# Find initialization of arrays and RecipientStatsCalculator implementation
echo "Checking ngolist.tsx for array initialization..."
rg -B 10 "const recipientStats = recipientCalculator.allStats" website/src/app/[lang]/[region]/\(website\)/partners/\(sections\)/ngolist.tsx

echo "\nChecking RecipientStatsCalculator implementation..."
ast-grep --pattern 'class RecipientStatsCalculator {
  $$$
  allStats($_) {
    $$$
  }
  $$$
}'

echo "\nChecking Firestore query patterns..."
rg -A 5 "getDoc|getDocs|collection|doc" shared/src/utils/stats/RecipientStatsCalculator.ts

Length of output: 1511

shared/locales/en/website-partners.json (1)

35-35: LGTM!

The NGO identifiers are simplified and consistent with the new dynamic stats approach.

shared/locales/fr/website-partners.json (1)

35-35: LGTM!

The NGO identifiers are consistent across localization files.

shared/locales/de/website-partners.json (1)

35-35: Consider moving shared keys to a common file.

NGO identifiers are identical across all locale files. Consider moving them to a shared configuration file.


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

vercel bot commented Jan 24, 2025

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

Name Status Preview Comments Updated (UTC)
public ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 24, 2025 3:45pm

Copy link

github-actions bot commented Jan 24, 2025

Visit the preview URL for this PR (updated for commit 9463af0):

https://si-admin-staging--pr1020-pranav-dynamic-fetch-jxgk22fg.web.app

(expires Fri, 31 Jan 2025 15:13:27 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: b7b0969384059dce6ea8fad1ee1d1737e54e6676

@DarkMenacer DarkMenacer marked this pull request as ready for review January 24, 2025 13:06
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: 2

🧹 Nitpick comments (11)
shared/src/utils/stats/RecipientStatsCalculator.ts (2)

1-3: Check lodash usage overhead
Using an entire lodash chain for a straightforward array-based approach may elevate complexity. Consider switching to native arrays for minimal overhead.


48-60: Combine multiple filter calls
Performing repeated .filter(...).size() calls can be consolidated into a single iteration, improving performance.

+ const counts = { active: 0, former: 0, suspended: 0 };
+ const validRecipients = this.recipients.filter((recipient) => !recipient.test_recipient);
+ validRecipients.forEach((r) => {
+   if (r.progr_status === RecipientProgramStatus.Active) counts.active++;
+   else if (r.progr_status === RecipientProgramStatus.Former) counts.former++;
+   else if (r.progr_status === RecipientProgramStatus.Suspended) counts.suspended++;
+ });
+ 
+ return {
+   total: validRecipients.size(),
+   active: counts.active,
+   former: counts.former,
+   suspended: counts.suspended,
+ };
website/src/app/[lang]/[region]/(website)/transparency/finances/[currency]/section-1.tsx (2)

35-57: Check sum logic
Summing active, former, and suspended for totalRecipients may omit potential future statuses. Consider a fallback or a dynamic approach if new statuses appear.


58-71: Maintain numeric consistency
Ensuring consistent formatting (e.g., rounding or commas) on displayed currency amounts can improve readability.

website/src/app/[lang]/[region]/(website)/transparency/finances/[currency]/page.tsx (2)

40-46: Ensure clarity in naming
Section1Props might benefit from a name reflecting its purpose (e.g., RecipientsAndContributionsProps).


61-61: Leverage previously fetched data
Destructure your stats only once to clarify the boundaries between data retrieval and component consumption.

website/src/app/[lang]/[region]/(website)/partners/(sections)/ngolist.tsx (1)

50-53: Localize badge labels.
Strings like translatorBadgeActive, etc., are empty. For consistency, consider populating them with translated text.

shared/locales/en/website-finances.json (1)

13-13: Check capitalization consistency.
Consider matching the casing style of other recipient labels.

- "activeRecipients": "{{ value }} Active Recipients"
+ "activeRecipients": "{{ value }} active recipients"
shared/locales/de/website-partners.json (3)

99-99: Consider a more specific firestore ID.

The current ID "jamil" might be too generic. Consider using "jnjf" to match the organization's short name.

-    "firestore-id": "jamil",
+    "firestore-id": "jnjf",

190-190: Maintain consistent ID format.

Other IDs don't use delimiters. Consider using "equalrights" to match the pattern.

-    "firestore-id": "equal_rights",
+    "firestore-id": "equalrights",

231-231: Maintain consistent ID format.

Remove the underscore to match other IDs' pattern.

-    "firestore-id": "united_polio",
+    "firestore-id": "unitedpolio",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fc7c259 and a59b32f.

📒 Files selected for processing (13)
  • shared/locales/de/website-finances.json (1 hunks)
  • shared/locales/de/website-partners.json (6 hunks)
  • shared/locales/en/website-finances.json (1 hunks)
  • shared/locales/en/website-partners.json (6 hunks)
  • shared/locales/fr/website-finances.json (1 hunks)
  • shared/locales/fr/website-partners.json (6 hunks)
  • shared/locales/it/website-finances.json (1 hunks)
  • shared/locales/it/website-partners.json (6 hunks)
  • shared/src/utils/stats/RecipientStatsCalculator.ts (1 hunks)
  • website/src/app/[lang]/[region]/(website)/partners/(sections)/ngolist.tsx (2 hunks)
  • website/src/app/[lang]/[region]/(website)/partners/(types)/PartnerCards.ts (1 hunks)
  • website/src/app/[lang]/[region]/(website)/transparency/finances/[currency]/page.tsx (3 hunks)
  • website/src/app/[lang]/[region]/(website)/transparency/finances/[currency]/section-1.tsx (2 hunks)
🔇 Additional comments (40)
shared/src/utils/stats/RecipientStatsCalculator.ts (3)

33-46: Handle potential missing organization document
When fetching organisationSnapshot, ensure that recipientData.data().organisation is defined and that the referenced document exists. Otherwise, you risk runtime errors or inconsistent data.


61-88: Clarify zero organization case
Returning zeroes for all status counts if no orgId is provided is logical, but confirm that this placeholder aligns with your business requirements.


90-94: Straightforward aggregation
The allStats method directly composes statistics by organization or overall recipients. Looks good.

website/src/app/[lang]/[region]/(website)/transparency/finances/[currency]/section-1.tsx (2)

5-9: Protect against negative amounts
Your roundAmount function handles zero but not negative values. If negatives are possible, handle them similarly.


26-34: Review transitions
The hover scale effect is functional. However, confirm that the added UI interactions (e.g., "hover:scale-[101%]") do not conflict with your design language or accessibility.

website/src/app/[lang]/[region]/(website)/transparency/finances/[currency]/page.tsx (3)

12-15: Module imports
The new imports look correct and facilitate fetching recipient data.


58-58: Good practice
Returning multiple stats as a single object keeps your code organization flexible.


71-71: Prop alignment
Providing recipientStats ensures the child component can leverage dynamic stats. Seems consistent with Section1Props.

website/src/app/[lang]/[region]/(website)/partners/(sections)/ngolist.tsx (3)

13-13: No issues found on this import.


15-15: Verify server-side usage.
Ensure RecipientStatsCalculator usage doesn’t cause issues when rendering on the client.


46-46: Confirm synchronous vs asynchronous behavior.
Ensure allStats is meant to be called synchronously, or add await if it’s async.

shared/locales/en/website-finances.json (1)

12-12: Revised emphasis on empowerment is clear.

shared/locales/de/website-finances.json (2)

12-12: Clarity improved by focusing on support.


13-13: Inclusive language looks good.

shared/locales/fr/website-finances.json (2)

12-12: Clear transition from “engagés” to “soutenus.”


13-13: New active recipients key is consistent.

shared/locales/it/website-finances.json (1)

12-13: Verify translations across all language files.

The Italian translations look accurate. Let's ensure consistency across other language files.

✅ Verification successful

Translations are consistent across all language files

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check translations for totalRecipients and activeRecipients across all language files
# Expected: Similar semantic meaning across languages

echo "Checking translations across language files..."
for lang in de en fr it; do
  echo -e "\n=== $lang ==="
  rg '"totalRecipients"|"activeRecipients"' "shared/locales/$lang/website-finances.json"
done

Length of output: 1252

website/src/app/[lang]/[region]/(website)/partners/(types)/PartnerCards.ts (1)

46-46: Add optional Firestore ID property
This optional property aligns well with Firestore integration. Confirm it's consistently referenced in the codebase, and consider removing recipient fields if they’re no longer used.

shared/locales/en/website-partners.json (6)

44-44: Add "firestore-id" for Aurora
Great addition for Firestore reference. Ensure consistency with other locales.


100-100: Add "firestore-id" for Jamil
The unique ID is correct. Confirm matching doc names in Firestore.


144-144: Add "firestore-id" for Reachout
No concerns. Make sure the name is spelled correctly in Firestore.


186-186: Add "firestore-id" for Equal Rights
Looks good. Keep naming consistent across locales.


227-227: Add "firestore-id" for United Polio
Perfectly fine. Mind underscores in Firestore doc IDs if needed.


267-267: Add "firestore-id" for SLAES
Clear addition. Validate correctness in your Firestore setup.

shared/locales/it/website-partners.json (6)

44-44: Add "firestore-id": "aurora"
Consistent with the type definition. Looks fine.


99-99: Add "firestore-id": "jamil"
No issues. Confirm Firestore alignment.


143-143: Add "firestore-id": "reachout"
ID naming is consistent. Good job.


185-185: Add "firestore-id": "equal_rights"
Underscore is okay if it matches Firestore doc IDs.


226-226: Add "firestore-id": "united_polio"
Everything seems in order.


266-266: Add "firestore-id": "slaes"
Check that it aligns with Firestore’s actual doc name.

shared/locales/fr/website-partners.json (6)

44-44: Add "firestore-id": "aurora"
Clean insertion. Make sure all references are spelled identically.


99-99: Add "firestore-id": "jamil"
Looks consistent. Ensure identical naming across languages.


143-143: Add "firestore-id": "reachout"
All good. Validate Firestore references.


185-185: Add "firestore-id": "equal_rights"
No issues. Confirm underscore usage if needed in Firestore.


226-226: Add "firestore-id": "united_polio"
Looks correct. The underscore is acceptable as long as it’s consistent.


266-266: Add "firestore-id": "slaes"
Works well. Double-check for matching doc name.

shared/locales/de/website-partners.json (4)

44-44: LGTM! Well-structured firestore ID.

The ID is simple, lowercase, and clearly identifies the organization.


143-143: LGTM! Clear and consistent ID.


271-271: LGTM! Well-chosen ID using the organization's acronym.


Line range hint 44-271: Verify firestore ID uniqueness across all collections.

While the IDs are well-chosen, ensure they don't conflict with IDs in other Firestore collections.

✅ Verification successful

Firestore IDs are properly integrated and used in the system

The firestore-ids in website-partners.json are verified to be valid and match actual database usage, as evidenced by their integration in the backend code.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for firestore IDs across the codebase to check for uniqueness
echo "Searching for firestore IDs..."
rg -i "firestore-id.*(?:aurora|jamil|reachout|equal_rights|united_polio|slaes)" --type json

Length of output: 1844


Script:

#!/bin/bash
# Search for Firestore-related files and collection definitions
echo "Searching for Firestore collection references..."
rg -i "firestore|collection.*partners" --type ts --type js -A 2

# Also check for any configuration files
echo -e "\nSearching for Firestore config files..."
fd -e ts -e js -e json firestore

Length of output: 66342


Script:

#!/bin/bash
# Search for partner organization collection references and ID usage
echo "Searching for partner org collections and ID usage..."
rg -i "partner.*organization.*collection|partner.*organisation.*collection" --type ts --type js -A 2

echo -e "\nSearching for specific firestore IDs in TypeScript/JavaScript files..."
rg -i "aurora|jamil|reachout|equal_rights|united_polio|slaes" --type ts --type js -A 2

Length of output: 2764

Comment on lines +54 to +55
const recipientCalculator = await RecipientStatsCalculator.build(firestoreAdmin);
const recipientStats = recipientCalculator.allStats();
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling
Consider wrapping the build steps in a try/catch block to handle Firestore or network issues more gracefully.

+ let recipientStats;
+ try {
+   const recipientCalculator = await RecipientStatsCalculator.build(firestoreAdmin);
+   recipientStats = recipientCalculator.allStats();
+ } catch (err) {
+   // handle or log error
+   recipientStats = { totalRecipients: {}, totalRecipientsByOrganization: {} }; 
+ }
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const recipientCalculator = await RecipientStatsCalculator.build(firestoreAdmin);
const recipientStats = recipientCalculator.allStats();
let recipientStats;
try {
const recipientCalculator = await RecipientStatsCalculator.build(firestoreAdmin);
recipientStats = recipientCalculator.allStats();
} catch (err) {
// handle or log error
recipientStats = { totalRecipients: {}, totalRecipientsByOrganization: {} };
}

Comment on lines +43 to +44
const recipientCalculator = await RecipientStatsCalculator.build(firestoreAdmin);

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for Firestore.
Consider wrapping this call in a try/catch block to gracefully handle potential Firestore errors.

- const recipientCalculator = await RecipientStatsCalculator.build(firestoreAdmin);
+ let recipientCalculator;
+ try {
+   recipientCalculator = await RecipientStatsCalculator.build(firestoreAdmin);
+ } catch (error) {
+   console.error("Error building recipient calculator:", error);
+   // Handle or rethrow the error as needed
+ }
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const recipientCalculator = await RecipientStatsCalculator.build(firestoreAdmin);
let recipientCalculator;
try {
recipientCalculator = await RecipientStatsCalculator.build(firestoreAdmin);
} catch (error) {
console.error("Error building recipient calculator:", error);
// Handle or rethrow the error as needed
}

@@ -283,6 +268,7 @@
"org-photo": ""
},
"sierra-leone-association-of-ebola-survivors": {
"firestore-id": "slaes",
Copy link
Contributor

Choose a reason for hiding this comment

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

A key that is the same in every translation file, seems wrong. This file should be for strings that differ across languages.

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.

2 participants