# Dynamic Route and Sidebar Access System - Setup Summary

## Overview
This system dynamically controls route access and sidebar visibility based on user access permissions fetched from an API after token verification in the middleware.

## Access Types & Their Permissions

### 1. **Store keeper**
**Routes & Sidebar Items:**
- Category (`/inventory/category/category-list`)
- Products (`/inventory/product`)
- Vendors (`/inventory/vendor`)
- QR Generator (`/inventory/issue-panel/qr-code`)
- Add Inventory (`/inventory/barcode`)
- Operation Logs (`/inventory/logs`)

### 2. **PO View**
**Routes & Sidebar Items:**
- Purchase Orders (`/inventory/purchase-orders`) - PO Panel

### 3. **Accounts**
**Routes & Sidebar Items:**
- Purchase Orders (`/inventory/purchase-orders`) - PO Panel (shared with PO View)
- All Payments (`/inventory/payments`) - Payment History
- PO Payment Entry (`/inventory/purchase-orders/payment/[id]`) - PO Pay

### 4. **User**
**Routes & Sidebar Items:**
- Request Item (`/inventory/purchase`)
- Approvals (`/inventory/approval`)
- Store Keeper (`/inventory/storekeeper`)
- Purchase Officer Request (`/inventory/purchase-officer`)
- Quotation Approval (`/inventory/quotation-approver`)

### 5. **ALL** (Special Access)
- Dashboard (`/inventory/dashboard`) - Accessible to all authenticated users

## How It Works

### Flow Diagram
```
1. User Request → Middleware
2. Middleware verifies JWT token
3. Extracts user_id from token
4. Calls API: POST /api/roll-access with { user_id }
5. API returns: ["Store keeper", "User", ...]
6. Middleware checks route access
7. Sidebar filters items based on access
```

### API Endpoint Required

**Endpoint:** `POST /api/roll-access`

**Request Body:**
```json
{
  "user_id": "123"
}
```

**Expected Response Formats (all supported):**
```json
// Format 1 (Recommended)
{
  "success": true,
  "data": {
    "access": ["Store keeper", "User"]
  }
}

// Format 2
{
  "success": true,
  "data": ["Store keeper", "User"]
}

// Format 3
{
  "access": ["Store keeper", "User"]
}

// Format 4
["Store keeper", "User"]
```

**Important:** The access names must match exactly:
- `"Store keeper"` (with space)
- `"PO View"` (with space)
- `"Accounts"` (capitalized)
- `"User"` (capitalized)

## Files Modified/Configured

### Core Files
1. **`accessMapping.js`** - Maps routes to access names
   - `ROUTE_ACCESS_MAPPING` - Route permissions
   - `SIDEBAR_ACCESS_MAPPING` - Sidebar item permissions
   - `ACCESS_NAMES` - Access name constants

2. **`checkRouteAccess.js`** - Checks if user can access a route
   - Used by middleware to protect routes

3. **`hasSidebarAccess.js`** - Checks if user can see sidebar item
   - Used by Sidebar component to filter items

4. **`sidebarPermissions.js`** - Sidebar structure with access mapping
   - Defines all sidebar sections and items

5. **`fetchUserAccess.js`** - Fetches user access from API
   - Handles multiple response formats
   - Includes caching (5 minutes)

6. **`useUserAccess.js`** - React hook for components
   - Fetches and provides user access in client components

### Middleware
- **`middleware.js`** - Already configured to:
  - Verify JWT token
  - Extract user_id
  - Fetch user access from API
  - Check route permissions

### Components
- **`Sidebar.js`** - Already configured to:
  - Use `useUserAccess()` hook
  - Filter sidebar items based on access
  - Show loading state while fetching

## Testing Your Setup

### 1. Test API Response
```bash
curl -X POST http://your-api-url/api/roll-access \
  -H "Content-Type: application/json" \
  -d '{"user_id": "123"}'
```

Expected: Array of access names like `["Store keeper", "User"]`

### 2. Test Route Access
- Login with a user that has "Store keeper" access
- Try accessing `/inventory/product` → Should work
- Try accessing `/inventory/purchase` → Should redirect (no access)

### 3. Test Sidebar
- Login and check sidebar
- Only items matching user's access should be visible
- Sections with no accessible items should be hidden

## Adding New Routes

To add a new route with access control:

1. **Add to `accessMapping.js`:**
```javascript
// In ROUTE_ACCESS_MAPPING
"/inventory/new-route": [ACCESS_NAMES.STORE_KEEPER],

// In SIDEBAR_ACCESS_MAPPING (if it should appear in sidebar)
"/inventory/new-route": [ACCESS_NAMES.STORE_KEEPER],
```

2. **Add to `sidebarPermissions.js` (if sidebar item needed):**
```javascript
{
  title: "New Route",
  path: "/inventory/new-route",
  icon: "IconName",
  access: SIDEBAR_ACCESS_MAPPING["/inventory/new-route"] || [],
}
```

3. **Create the route page:**
```javascript
// src/app/inventory/new-route/page.js
export default function NewRoutePage() {
  // Your page content
}
```

## Troubleshooting

### Issue: Sidebar shows all items
- **Check:** Is `useUserAccess` hook working?
- **Check:** Console for API errors
- **Check:** User access array format matches access names exactly

### Issue: Routes not protected
- **Check:** Middleware is running (check console logs)
- **Check:** Route is in `ROUTE_ACCESS_MAPPING`
- **Check:** User access is being fetched correctly

### Issue: API returns different format
- **Check:** `fetchUserAccess.js` handles your format
- **Update:** Add new format handler if needed

## Current Status

✅ Middleware configured to fetch user access
✅ Route access checking implemented
✅ Sidebar filtering implemented
✅ All routes mapped to correct access types
✅ Payment routes added for Accounts access
✅ API response format handling enhanced

## Next Steps

1. **Backend:** Ensure your API endpoint `/api/roll-access` returns access in one of the supported formats
2. **Test:** Login with different users and verify access
3. **Monitor:** Check browser console and server logs for any issues



