Nature Think

Comprehensive Technical Specification & Architecture Plan

1. Executive Summary

Nature Think is a full-stack e-commerce platform dedicated to natural products. Built with a modern React frontend and a robust Node.js/Express backend, it features a custom file-based database (EveloDB) for data persistence. The platform supports user authentication, product management, order processing, and a comprehensive admin dashboard.

2. Technical Architecture

Frontend Stack

  • Framework: React 18 + TypeScript
  • Build Tool: Vite
  • Styling: Tailwind CSS, PostCSS
  • Routing: React Router DOM
  • State/Effects: Framer Motion (Animations)
  • HTTP Client: Native Fetch / Axios

Backend Stack

  • Runtime: Node.js
  • Framework: Express.js
  • Database: EveloDB (JSON-based)
  • Auth: JWT + Bcrypt
  • Email: Nodemailer

3. Database Schema (EveloDB)

The system uses a collection-based JSON storage engine. Key collections include:

Collection Description & Key Fields
users Stores user profiles. Key fields: id, name, email, password (hashed), phone, address, avatarUrl, role (user/seller/admin), isActive, favourites (array of item ids), suggestion, lastLogin, loginsIpHistory (last N IPs), and cartItemsCount.
stock Product inventory. Key fields: id, name, seller, sellerId, desc, currency, quantity, images, videos, category, subcategory, keywords, rating, sellCount, freeze, and product variants products[] with label, price, mass (grams), and optional discountedPrice.
orders Customer orders. Key fields: id, user (user id), items (array of CartType entries with product snapshot), deliveryFee, totalPrice, totalMass, address, phone, name, email, type ('pickup'|'cod'), timestamp, state (pending|accepted|ontheway|rejected|delivered|cancelled), optional notes (timeline entries), trackingCode, deliveryDate, and podData (QR data / proof of delivery). Delivery events set deliveredAt when applicable.
cart Per-user cart items. Each record contains id, user, item (stock id), quantity, product snapshot (label, mass, price), total, and itemData (name, image, currency) for rendering and consistency.
revenue Financial tracking. Records: timestamp, revenue, and packageWeight (used for analytics and reporting).
comments Product comments and reviews. Fields: id, item (stock id), user, optional userName, userAvatar, rating (0–5), text, optional media[], and timestamp.
delivery Delivery services and configuration. Fields: name, icon, description, website, phone, authorization, and prices (e.g., basic, up). Used for calculating fees and courier integrations.
notifications In-app and push notifications. Fields: id, title, body, optional html, url (link target), timestamp, icon ('info'|'warning'|'error'|'success'), and numeric code for categorization.

4. API Specification

Authentication & User

POST/api/get-verify-email - Send OTP for signup or password reset (returns success/error)
POST/api/signup - Register (Validates OTP, hashes password)
POST/api/login - Authenticate & return JWT
POST/api/get-user - Retrieve profile by token
POST/api/edit-user - Update profile details
POST/api/reset-password - Reset password using OTP. Request body: { email, newPassword, otp }. Server validates the OTP (stored per-email with an expireAt timestamp), enforces attempt limits, hashes the new password with bcrypt (salt rounds: 10), and updates the user's password via the database db.edit. Returns detailed error messages for missing fields, expired/invalid OTP, too many attempts, or DB failures.
POST/api/change-password - Change password for authenticated users (protected by authenticateUser). Request body: { oldPassword, newPassword }. The route delegates to userFunctions.changePassword which validates the current password, hashes the new password, and persists the update.

Commerce & Operations

POST/api/cart - Manage cart (Add/Remove/Get)
POST/api/favourites - Toggle user favourites
POST/api/order - Place new order
POST/api/stock - Retrieve product list
POST/api/comment-item - Rate & review products

Admin Routes (Protected)

POST/api/admin/users - Manage user accounts
POST/api/admin/orders - Order fulfillment & tracking
POST/api/proof-of-delivery - Mark order delivered via QR scan (protected by authCourier). Request body: { qrData }. Server decodes qrData to an order ID, validates the order, ensures it isn't already delivered, sets state: 'delivered' and records deliveredAt timestamp via db.edit('orders', ...). Returns errors for missing QR, order not found, already delivered, or DB failures.
POST/api/admin/stock - Inventory management
POST/api/admin/delivery - Configure delivery fees
POST/api/admin/data - System analytics
POST/api/backup-restore - Create backup (download zip) or restore from zip. Protected by authenticateAdmin.

5. SEO Systems

Purpose: Improve organic discoverability and rich result coverage for product pages while keeping crawlability and performance high.

Objectives

  • Ensure every item and key pages have unique titles, descriptions, canonical URLs, Open Graph/Twitter metadata and valid structured data (Product JSON-LD).
  • Generate and maintain an up-to-date XML sitemap and robots.txt, and submit to Search Consoles.
  • Improve indexability and speed via pre-rendered item pages and optimized image delivery.
  • Automate monitoring (Lighthouse CI, Search Console, index coverage, 4xx/5xx alerts).

Core Features

  • Dynamic pre-rendering: Server-side pre-render endpoint for item slugs (already implemented as /store/item/:slugId with preRenderItemSlug).
  • Automated sitemap: updateSiteMap(items) to produce XML; run on product create/update/delete and as a scheduled job.
  • Canonical & hreflang: canonical links for product variants and optional hreflang support for multi-lingual pages.
  • Product structured data: JSON-LD Product markup for each item (price, currency, availability, image) for rich results.
  • Open Graph / Twitter cards: Ensure social sharing tags (og:title, og:description, og:image, twitter:card).
  • Image CDN & optimization: Leverage existing /cdn/images route + server-side resizing & quality query params for fast thumbnails and social images.
  • Robots & headers: Serve robust /robots.txt and enforce canonical & noindex/noarchive where applicable.

Implementation Plan

  1. Audit current markup (pages, item metadata, schema) and create a checklist of missing tags.
  2. Fix updateSiteMap to persist sitemap file and return the XML correctly; add unit/integration tests.
  3. Ensure preRenderItemSlug outputs valid Product JSON-LD and canonical tag using process.env.SITE_URL.
  4. Add server-side cron (or webhooks) to regenerate sitemap on product changes and once daily.
  5. Create admin UI to view/trigger sitemap generation and view SEO warnings for items (missing image, missing price, missing keywords).
  6. Integrate monitoring: Lighthouse CI (PR checks), scheduled Lighthouse runs, Search Console/Bing verification, and automated alerts on index coverage changes.

Success Metrics

  • Indexed product pages (Search Console coverage) increases by X% within 30 days of rollout.
  • Rich results (Product snippets) observed for representative products within 14 days.
  • Average Lighthouse score (Performance/SEO) >= 90 for product pages.
  • Reduction in 4xx/5xx crawl errors and correctly generated sitemap.xml with lastmod dates.

Notes & Known Improvements

  • Backend: confirm that process.env.SITE_URL is set in production and used consistently for canonical and sitemap generation.
  • Frontend: ensure SSR/Pre-rendered variants are tested on canonical pages and fallback client rendering is healthy for JS-disabled crawlers.

6. Core Business Logic

7. Project Structure

nature-think/
├── backend/
│   ├── index.js              # Start Application
│   ├── apiServer.js          # Express Application Entry Point
│   ├── package.json          # Backend Dependencies
│   ├── database/             # Database Schema & Models
│   └── middleware/
│       ├── auth.js           # Authentication Middleware
│       ├── utills.js         # Core Database & Business Logic
│       ├── backup.js         # Backup & Restore logic
│       ├── sendEmail.js      # Email Service (Nodemailer)
│       ├── tools.js          # Utility Functions (Token, Formatting)
│       ├── evelodb-config.js # Database Configuration
│       ├── dataManager.js    # Data Management Utilities
│       ├── updateSiteMap.js  # Generate Sitemap
│       └── resendMail.js     # Email Resending Logic
└── frontend/
    ├── vite.config.ts        # Vite Configuration
    ├── tailwind.config.js    # Tailwind Configuration
    ├── project_plan.html     # This Document
    └── src/
        ├── main.tsx          # React Entry Point
        ├── App.tsx           # Main App Component
        ├── admin/            # Admin Dashboard
        │   ├── AdminHome.tsx
        │   ├── AdminActions.tsx
        │   └── components/
        │       ├── ManageUsers.tsx
        │       ├── ManageOrders.tsx
        │       ├── PackageLabel.tsx
        │       ├── Stock.tsx
        │       ├── CreateItem.tsx
        │       ├── EditItem.tsx
        │       ├── DeliveryService.tsx
        │       └── ManageUpdates.tsx
        └── routes/           # User Facing Routes
            ├── Home.tsx
            ├── Store.tsx
            ├── Item.tsx
            ├── Cart.tsx
            ├── Orders.tsx
            ├── Favourites.tsx
            ├── ChangePassword.tsx
            ├── ResetPassword.tsx
            ├── Login.tsx
            ├── Signup.tsx
            ├── Settings.tsx
            ├── About.tsx
            ├── Help.tsx
            ├── Updates.tsx
            ├── PrivacyPolicy.tsx
            ├── TermsConditions.tsx
            ├── WarrantyInfo.tsx
            ├── ShippingPolicy.tsx
            ├── Footer.tsx
            └── components/   # Shared Components
                ├── NavBar.tsx
                ├── ItemComponent.tsx
                ├── Loading.tsx
                ├── Rain.tsx
                ├── types.ts      # TypeScript Interfaces
                ├── utils.ts      # Frontend Utilities
                ├── sendReq.ts    # API Request Helper
                ├── categories.ts # Category Definitions
                ├── cart/         # Cart Specific Components
                │   ├── CartItem.tsx
                │   └── PlaceOrderSection.tsx
                ├── home/         # Home Page Components
                │   ├── Hero.tsx
                │   ├── Overview.tsx
                │   └── TopItems.tsx
                └── settings/     # Settings Page Components
                    ├── Account.tsx
                    └── Suggestions.tsx