Skip to content

Coding Challenge Solutions#18

Open
fikremariamF wants to merge 2 commits into
vula-africa:mainfrom
fikremariamF:main
Open

Coding Challenge Solutions#18
fikremariamF wants to merge 2 commits into
vula-africa:mainfrom
fikremariamF:main

Conversation

@fikremariamF
Copy link
Copy Markdown

@fikremariamF fikremariamF commented Dec 23, 2025

Summary by CodeRabbit

  • Documentation

    • Added UI component architecture documentation and diagrams
    • Added post-mortem and remediation plan for performance regression
    • Added unsubmitted forms cleanup job documentation
    • Added reference video links for system solutions
  • Bug Fixes

    • Implemented improved cleanup process for expired unsubmitted forms with enhanced error handling and logging

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Dec 23, 2025

Walkthrough

This PR introduces documentation and implementation for three solutions: a UI component architecture breakdown with visual schematic, a performance regression post-mortem with remediation plan, and a cleanup job for expired unsubmitted forms featuring proper date calculations, transactional integrity, batching, and enhanced error handling and logging.

Changes

Cohort / File(s) Summary
Video Links & Root Documentation
Solutions/README.md
Adds Loom video links section referencing Breakdown UI, End of Week Issues, and Unsubmitted Forms Cleanup (note: "Videa LInk" appears to contain typo)
UI Component Architecture
Solutions/breakdown_ui/Breakdown_UI_Challenge.drawio, Solutions/breakdown_ui/README.md
Introduces draw.io diagram schematic and comprehensive documentation detailing Rural Agri Overview dashboard UI component breakdown, categorized components (layout, shared, portfolio-specific), architectural decisions, and reusability classification
Performance Incident Resolution
Solutions/end_of_week_issues/README.md
Adds post-mortem documentation identifying modelVersion v1.3 regression affecting /risk-score and /funding-approve endpoints; outlines immediate rollback actions, prevention strategy (canary deployments, automated regression tests, real-time monitoring), and retrospective recommendations
Unsubmitted Forms Cleanup Implementation
Solutions/unsubmitted_forms/cleanup_unsubmitted_forms.ts, Solutions/unsubmitted_forms/README.md
Implements cleanup_unsubmitted_forms() scheduled job function with corrected 7-day date logic, batch relationship fetching, transactional multi-entity deletion respecting foreign key constraints, per-token error handling, and enhanced logging; accompanying documentation details fixes and validation improvements

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Hop along through UI blocks so neat,
Clean the forms that missed their beat,
Rollback quick when speeds take flight,
Videos guide the path to right!
Solutions built with care and jest,
Documentation puts it all to rest. 🎥✨

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Coding Challenge Solutions' is overly vague and generic. It does not specifically describe the main changes (UI breakdown documentation, performance issue remediation, form cleanup job implementation, and Loom video links). Consider a more descriptive title such as 'Add UI breakdown docs, performance remediation plan, and form cleanup job implementation' to clearly communicate the primary changes in the changeset.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@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

🧹 Nitpick comments (3)
Solutions/README.md (1)

2-4: Use proper Markdown link syntax for URLs.

Bare URLs violate markdown best practices (MD034). Convert them to named links for better accessibility and readability.

🔎 Proposed fix
-### Breakdown UI: https://www.loom.com/share/49e34955625b4f568756ac9b55f396e4
-### End of week issues: https://www.loom.com/share/7855388fd7bd4e628b874ff578d9b100
-### Unsubmitted Forms cleanup: https://www.loom.com/share/5172be850c3446b38efd0a66273f2535
+### [Breakdown UI](https://www.loom.com/share/49e34955625b4f568756ac9b55f396e4)
+### [End of week issues](https://www.loom.com/share/7855388fd7bd4e628b874ff578d9b100)
+### [Unsubmitted Forms cleanup](https://www.loom.com/share/5172be850c3446b38efd0a66273f2535)
Solutions/unsubmitted_forms/cleanup_unsubmitted_forms.ts (2)

36-70: Orphaned tokens are not cleaned up.

When a token has no matching relationship (line 43 condition fails) or when entityId is null, the expired token itself is not deleted. This could lead to orphaned publicFormsTokens records accumulating over time.

Consider adding cleanup for the token record even when the relationship doesn't exist:

🔎 Proposed fix
         if (relationship && token.entityId) {
           // ... existing transaction logic ...
           deletedCount++;
         } else if (!token.entityId) {
           console.warn(`Skipping token ${token.token}: missing entityId`);
+          // Still delete the orphaned token
+          await prisma.publicFormsTokens.delete({
+            where: { token: token.token },
+          });
+        } else if (!relationship) {
+          // Token exists but relationship doesn't - clean up orphaned token
+          await prisma.publicFormsTokens.delete({
+            where: { token: token.token },
+          });
         }

13-19: Consider adding batch size limits for large datasets.

The query fetches all expired tokens at once without a limit. In production with many expired forms, this could cause memory pressure. Consider processing in batches with pagination.

🔎 Proposed approach
+    const BATCH_SIZE = 1000;
+    let skip = 0;
+    let hasMore = true;
+
+    while (hasMore) {
       const expiredTokens = await prisma.publicFormsTokens.findMany({
         where: {
           createdAt: {
             lt: sevenDaysAgo,
           },
         },
+        take: BATCH_SIZE,
+        skip: skip,
       });
+
+      hasMore = expiredTokens.length === BATCH_SIZE;
+      skip += BATCH_SIZE;
+      // ... process batch ...
+    }
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 1dd21f7 and 27f0ba0.

📒 Files selected for processing (6)
  • Solutions/README.md
  • Solutions/breakdown_ui/Breakdown_UI_Challenge.drawio
  • Solutions/breakdown_ui/README.md
  • Solutions/end_of_week_issues/README.md
  • Solutions/unsubmitted_forms/README.md
  • Solutions/unsubmitted_forms/cleanup_unsubmitted_forms.ts
🧰 Additional context used
🪛 markdownlint-cli2 (0.18.1)
Solutions/README.md

2-2: Bare URL used

(MD034, no-bare-urls)


3-3: Bare URL used

(MD034, no-bare-urls)


4-4: Bare URL used

(MD034, no-bare-urls)

🔇 Additional comments (8)
Solutions/breakdown_ui/README.md (1)

1-82: LGTM!

Well-structured documentation with clear component breakdown, architectural decisions, and reusability classifications. The deliverables section clearly references the diagram file.

Solutions/breakdown_ui/Breakdown_UI_Challenge.drawio (1)

1-244: LGTM!

Valid Draw.io diagram asset that complements the UI breakdown documentation.

Solutions/unsubmitted_forms/README.md (1)

1-29: LGTM!

Clear documentation of the bugs fixed and improvements made. The key changes section provides a good summary of the technical corrections.

Solutions/end_of_week_issues/README.md (1)

1-41: LGTM!

Excellent post-mortem structure with clear root cause analysis, evidence-based conclusions, and actionable prevention strategies. The immediate action plan and retrospective notes provide good operational guidance.

Solutions/unsubmitted_forms/cleanup_unsubmitted_forms.ts (4)

10-19: LGTM on date calculation and query logic.

The 7-day calculation is correct (7 * 24 * 60 * 60 * 1000 = 604,800,000 ms) and the lt: sevenDaysAgo filter properly captures all tokens older than 7 days.


80-88: LGTM on completion handling and status updates.

Good observability with count logging and proper job status management for both success and failure paths.


47-65: Deletion order is correct.

The sequence (relationship → new_corpus → publicFormsTokens → entity) respects logical dependencies: relationship is independent, new_corpus and publicFormsTokens both reference entity via entity_id and entityId respectively, so they must be deleted before entity. Deleting the entity last prevents foreign key constraint violations.


32-34: Map will lose relationships if multiple exist for the same product_id.

If the data model allows multiple relationships with the same product_id and status: "new", only the last one will be retained in the Map. Verify in the Prisma schema whether product_id has a unique constraint on the relationship model, or use .findFirst() to safely handle multiple matches per product_id.

Comment thread Solutions/README.md
@@ -0,0 +1,4 @@
## Loom Videa LInk
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fix typo in heading.

"Videa LInk" should be "Video Link".

🔎 Proposed fix
-## Loom Videa LInk
+## Loom Video Link
📝 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
## Loom Videa LInk
## Loom Video Link
🤖 Prompt for AI Agents
In Solutions/README.md around lines 1 to 1, the heading contains a typo "Loom
Videa LInk"; update it to read "Loom Video Link" (fixing both "Videa" -> "Video"
and "LInk" -> "Link") so the heading is correct and consistently capitalized.

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