Support #11577
openTo Test orders flow in e-commerce and admin panels and optimize api calls
Added by Ajit A 12 days ago. Updated 11 days ago.
100%
Files
| Screenshot 2026-10-21 173639.png (45.6 KB) Screenshot 2026-10-21 173639.png | Ajit A, 10/21/2026 12:06 PM | Delete |
Subtasks
Related issues
Updated by Ajit A 12 days ago
- File Screenshot 2026-10-21 173639.png Screenshot 2026-10-21 173639.png added
- Due date set to 10/22/2026
- % Done changed from 0 to 50
- Estimated time changed from 8:00 h to 16:00 h
Repository: evergreenpos_E-commerce_new (Frontend)
1. Bug Fixes
Auth Modal Reset on Close: Fixed an issue where closing the "Join EvergreenFarms" (Create Account) modal left the modal stuck in signup mode. Implemented handleCloseLoginModal and updated handleCloseAllModals / resetForm to purge auth query params and reset activeModal and form fields back to "login".
Pre-order Catalog Route Listener: Resolved an issue in PreorderAvailabilityContext.tsx where route transitions caused pre-order availability state to drop by subscribing to useLocation().
Order Details Payment Status: Corrected OrderDetails.tsx and OrderDetailsModal.tsx so unpaid, pending, or partially paid orders display dynamic Total Due, Pending, or Partial status badges instead of falsely reporting Paid.
IP Geolocation Reliability: Hardened CustomerLocationContext.tsx and customerLocationStorage.ts with multi-tier fallbacks (ipwho.is → freeipapi.com), a 4-second timeout controller, and poisoned cache sanitization to prevent blank location states.
2. Features & UX Enhancements
Header Rewards Club Touchpoint: Relocated the reward points entry point from an intrusive floating button (GardeningClubPopup.tsx) to an interactive [🪙 Points] pill in TopHeader.tsx, a menu item in ProfileMenu.tsx, and a navigation entry in MobileCategorySidebar.tsx.
Unified Loyalty Hook: Created useCustomerLoyalty.ts to manage loyalty balance fetching, 5-minute session storage caching, and multi-component synchronization via customerLoyaltyUpdated events.
Merchandising & Browsing Polish: Optimized HomeMerchTabs.tsx and RecentlyViewedSection.tsx with unified product card components (ProductUnifiedCard.tsx), skeleton loaders, and empty state illustrations.
3. Technical Changes
Standardized useSearchParams usage in Header.tsx to ensure search parameters are updated via React Router instead of raw window.history.replaceState.
Removed redundant inline CSS overrides and tightened mobile responsive layouts in navigation drawers and headers.
Repository: evergreen_pos_be (Backend)
1. Bug Fixes
In-Store Pickup Shipping Zeroing: In payment.service.js, enforced shippingCharges = 0 when deliveryType === 'pickup', preventing delivery fees from applying to store pickup orders.
Composite Product ID Normalization: Fixed order creation in payment.service.js to strip variant suffixes from composite cart item IDs (<productId>_<sku>), ensuring orders reference valid base product IDs in MongoDB.
2. Technical & Performance Optimizations
Public Company Settings In-Memory Cache: Added a 60-second in-memory cache in shop-controller.js for getPublicCompanySettings to eliminate redundant database reads on high-frequency storefront requests.
Best Selling & Featured Aggregation Caching: Introduced 5-minute scoped in-memory caches in product.service.js for getBestSellingPublic and getFeaturedProductsPublic.
Query Projection Optimization:
In merchIntel.service.js and weatherProduct.controller.js, added field projections (select(...)) and .lean() queries to strip heavy internal audit fields and send only relevant product card fields.
In product.service.js (getAllCategoryEcom), projected out large joined products arrays.
Weather API Latency Guard: Reduced external API timeouts from 3500ms to 1800ms in weatherSnapshot.service.js to prevent third-party weather provider latency from slowing storefront page loads.
Detailed Endpoint-by-Endpoint Analysis
1. GET /api/v1/growth/weather-products
Before:
Response Time: 12.39 seconds
Payload Size: 2,010 kB (2.0 MB)
Root Cause: Backend was executing Product.find().lean() without field projection, returning 50 complete MongoDB documents including large audit histories, wholesale pricing arrays, raw descriptions, and embedded logs.
After:
Response Time: < 300 ms (~97.5% latency reduction)
Payload Size: ~15 kB (~99.2% size reduction)
Optimization: Added strict field projection (.select(WEATHER_PRODUCT_FIELDS)) across control, candidate, and backfill queries in weatherProduct.controller.js to return only storefront card essentials.
2. GET /api/v1/preorder/catalogEcom/:catalogId?type=... (Pre-order N+1 Cascade)
Before:
Request Count: 3 to 6 separate serial network calls (CA1001-1031_068?type=pick, CA1001-1031_068?type=del, CA1001-1031_067?type=del, etc.)
Response Time: 1.5s – 3.0s cumulative (blocked the thread serially in a for ... of await loop on every F5 reload)
After:
Request Count on Reload: 0 requests
Response Time on Reload: 0 ms
Optimization:
Implemented a 10-minute persistent sessionStorage cache (ecom_preorder_avail_cache_v1) in PreorderAvailabilityContext.tsx. On reload, availability hints hydrate synchronously in 0ms.
Parallelized first-time/expired fetching using Promise.allSettled, executing all catalog and fulfillment combinations concurrently within a single round-trip.
3. GET /api/v1/growth/local-merch-context
Before:
Request Count: 2 identical back-to-back requests on mount (Call #1 returned 200, followed immediately by Call #2 returning 304).
Root Cause: When location resolved, it fired fetchMerchContext. Immediately after, currency state updated currency.country, re-triggering the useEffect with the exact same coordinates.
After:
Request Count: 1 deduplicated request
Optimization: Added a composite location key ref check (lastMerchFetchKeyRef) in CustomerLocationContext.tsx to debounce and intercept the redundant second call.
4. GET /v1/nus-category/products/category/:id?limit=6 (Footer Dead Code & Header Preload)
Before:
Request Count: 2 separate requests on initial reload
Root Cause:
Footer.tsx was querying products and catalogs into a hasNoData variable that was never rendered anywhere in the DOM (100% dead code).
Header.tsx was eagerly fetching category recommendations on page reload just in case the user clicked the search input.
After:
Request Count on Reload: 0 requests
Optimization:
Removed the dead query and unused hook dependencies from Footer.tsx.
Configured Header search recommendations to be lazy-loaded (enabled: (isSearchFocused || isMobileSearchFocused || showSuggestions)), firing only when the user actually engages with search.
5. GET /api/v1/nursery/shop/public-company-settings
Before:
Response Time: 120 ms – 250 ms on every route transition / page reload.
Root Cause: Queried the database and resolved company details on every single storefront visit.
After:
Response Time: < 5 ms (memory cache hit)
Optimization: Added a 60-second in-memory cache partitioned by slug/dbName (publicCompanySettingsCache) in shop-controller.js.
6. GET /v1/products/public/best-selling & featured
Before:
Response Time: 300 ms – 600 ms per call.
Root Cause: Executed heavy multi-stage MongoDB aggregation pipelines across historical order lines and product collections on every request.
After:
Response Time: < 10 ms (memory cache hit)
Optimization: Introduced 5-minute scoped in-memory caches (bestSellingCache and featuredProductsCache) in product.service.js.
7. Third-Party Weather Provider Latency (weatherSnapshot.service.js)
Before:
Worst-Case Latency: Up to 11 – 12 seconds
Root Cause: 3,500ms timeout per provider cascading sequentially across WeatherAPI and OpenWeatherMap when third-party services had high latency or rate limits.
After:
Worst-Case Latency: < 2.0 seconds
Optimization: Tightened external provider timeouts from 3,500ms to 1,800ms, triggering rapid failover to Open-Meteo or cached snapshots.
8. Unsolicited Reload POSTs & Status Checks
Before:
POST /api/v1/growth/weather/subscribe and GET /api/v1/growth/weather/alerts/status were firing on every page mount even for anonymous guest visitors.
After:
0 requests on reload for regular visitors. Calls are now strictly guarded and only trigger when a user explicitly opts in to weather alerts or is logged in.
User Experience & Device Impact
Zero Layout Shifts & Stutter: The removal of 2MB payload downloads and serial request chains eliminates browser thread blocking and UI freezes.
Mobile Data Friendly: Total page weight dropped by over 4.2 MB per reload, making the storefront fast and responsive even on slow 3G/4G connections.
Instant Preorder Navigation: Preorder catalogs and product availability badges render instantly in 0ms from session storage without waiting for network round-trips.
Updated by Ajit A 11 days ago
- Status changed from In Progress to Resolved
- Target version set to sprint (10/12/2026 - 10/31/2026)
- % Done changed from 50 to 100
1. Repository: evergreen_pos_be (Backend)
Key Modifications & Optimizations:
Company & Tenant Resolution Caching: Implemented in-memory caching (companySlugCache, 5 min TTL) in
EcomService.findCompany
to eliminate redundant database lookups on every request.
Optimized Offer & Product Detail Queries: Refactored
offer.service.js
(/api/v1/ofc/prcOff/:id) with 30s caching, parallel category queries, and clustered UUID lookups.
Typeahead Preview Search: Introduced preview mode in
ecom.controller.js
and
product.service.js
that bypasses expensive MongoDB $facet aggregation pipelines and facet calculations for instant autocomplete responses.
Database Indexing: Added compound indexes in
nursery.product.js
for { active: 1, showInEcomm: 1, isDeleted: 1, name: 1 } and { UId: 1 }.
Bug Fixes:
Loyalty Authorization Fix: Added /api/v1/loyalty to STOREFRONT_PREFIXES in
tenantPermissions.js
and updated route middleware to optionalVerifyToken in
routes/nursery/index.js
, preventing 403 Forbidden errors when fetching customer loyalty summaries.
2. Repository: evergreenpos_E-commerce_new (E-Commerce Frontend)
Bug Fixes:
React Hook Order Violation: Fixed Rendered fewer hooks than expected in
WeatherPicks.tsx
by ensuring all hooks evaluate before any conditional returns.
Deduplication of API Storms:
Added in-flight request deduplication and session tracking in
searchApi.ts
(recordProductView).
Added in-flight deduplication and short-term failure caching in
useCustomerLoyalty.ts
to eliminate duplicate /v1/loyalty/customers/:id/summary calls.
Removed redundant category product multi-fetch in
Header.tsx
and increased search debounce to 400ms.
Features & Enhancements:
Error Boundary Green Theme: Re-styled
RouteErrorBoundary.tsx
to match the Evergreen brand aesthetic (emerald gradients, AlertCircle badge, RotateCcw reload button, and tenant-aware toTenantPath('/home') redirection).
Product Details Lazy Loading & Error Recovery:
Converted Product Reviews and Related Products carousel in
productdetailsui.tsx
to lazy load on scroll via IntersectionObserver.
Added an error recovery card with "Retry" and "Reload Page" buttons when network or database connection issues occur.
Currency-Aware Dispatch Table: Updated
ProductDispatchTable.tsx
to dynamically format shipping tier amounts using useCurrency and display item returnability windows.
Global Company Settings Context: Added
CompanySettingsContext.tsx
to provide tenant features application-wide without repeated fetches.
3. Repository: evergreen_pos_fe (POS / Admin Frontend)
Features & Bug Fixes:
Permission Failure Auto-Redirect & Countdown: Updated
ScreenAccessGuard.tsx
with a 5-second countdown timer that automatically redirects to the first accessible role screen or the tenant login page when RBAC permissions fail (e.g. 403 Forbidden).
Action Controls: Added real-time countdown badge, "Go to Login / Go to Screen Now" button, and reset capabilities on the "Retry" button.